Skip to content

Commit c7c979b

Browse files
added a ping function and a new optional input called login_on_init
1 parent 889fe73 commit c7c979b

File tree

1 file changed

+26
-2
lines changed

1 file changed

+26
-2
lines changed

chirpstack_api_wrapper/client.py

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import sys
55
import os
66
import time
7+
import requests
78
from grpc import _channel as channel
89
from chirpstack_api import api
910
from chirpstack_api_wrapper.objects import *
@@ -20,14 +21,19 @@ class ChirpstackClient:
2021
- email: The email of the Account that will be used to call the Api(s).
2122
- password: The password of the Account that will be used to call the Api(s).
2223
- api_endpoint: The Chirpstack grpc api endpoint (usually port 8080).
24+
- login_on_init (optional): The instance will try to login when initialized.
2325
"""
24-
def __init__(self, email:str, password:str, api_endpoint:str):
26+
def __init__(self, email:str, password:str, api_endpoint:str, login_on_init: bool = True):
2527
"""Constructor method to initialize a ChirpstackClient object."""
2628
self.server = api_endpoint
2729
self.channel = grpc.insecure_channel(self.server)
2830
self.email = email
2931
self.password = password
30-
self.auth_token = self.login()
32+
self.login_on_init = login_on_init
33+
if self.login_on_init:
34+
self.auth_token = self.login()
35+
else:
36+
self.auth_token = None
3137

3238
def login(self) -> str:
3339
"""
@@ -69,6 +75,20 @@ def login(self) -> str:
6975

7076
return resp.jwt
7177

78+
def ping(self) -> bool:
79+
"""
80+
Checks if the server is reachable by sending a request. Returns True if reachable, False otherwise.
81+
"""
82+
try:
83+
response = requests.get(f"http://{self.server}")
84+
if response.status_code >= 200 and response.status_code < 300:
85+
return True
86+
else:
87+
return False
88+
except Exception as e:
89+
logging.error(f"ChirpstackClient.ping(): {e}")
90+
return False
91+
7292
def list_all_devices(self,app_resp: dict) -> dict:
7393
"""
7494
List all devices.
@@ -558,6 +578,10 @@ def refresh_token(self, e: grpc.RpcError, method, *args, **kwargs):
558578
self.auth_token = self.login() # Update auth_token with the new token
559579
time.sleep(2) # Introduce a short delay before retrying
560580
return method(*args, **kwargs) # Re-run the specified method with the same parameters
581+
elif not self.login_on_init:
582+
self.auth_token = self.login() #login, since client didn't on init
583+
time.sleep(2) # Introduce a short delay before retrying
584+
return method(*args, **kwargs) # Re-run the specified method with the same parameters
561585

562586
logging.error(f"ChirpstackClient.{method.__name__}(): Unknown error occurred with status code {status_code}")
563587
logging.error(f" Details: {details}")

0 commit comments

Comments
 (0)