Skip to content

Commit c51b6a0

Browse files
Merge pull request #20 from anedyaio/development
RC v0.1.4
2 parents 8ab8c45 + f5a8161 commit c51b6a0

9 files changed

Lines changed: 117 additions & 58 deletions

File tree

setup.cfg

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[metadata]
22
name = anedya-dev-sdk
3-
version = 0.1.3
3+
version = 0.1.4
44
url = https://github.com/anedyaio/anedya-dev-sdk-pyhton
55
author = Anedya Systems
66
author_email = support@anedya.io

src/anedya/anedya.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -46,8 +46,8 @@ def __init__(self, config: AnedyaConfig):
4646
self.on_connect = config.on_connect
4747
self.on_disconnect = config.on_disconnect
4848
self.on_message = config.on_message
49-
self._mqttclient.on_connect = self.onconnect_handler
50-
self._mqttclient.on_disconnect = self.ondisconnect_handler
49+
self._mqttclient.on_connect = self._onconnect_handler
50+
self._mqttclient.on_disconnect = self._ondisconnect_handler
5151
# self._mqttclient.on_message = self.onmessage_handler
5252
self._mqttclient._connect_timeout = 1.0
5353
self._transactions = Transactions()
@@ -103,6 +103,7 @@ def disconnect(self):
103103

104104
from .client.bindDevice import bind_device
105105
from .client.submitData import submit_data
106+
from .client.submitLogs import submit_logs
106107
from .client.timeSync import get_time
107-
from .client.mqttHandlers import onconnect_handler, ondisconnect_handler
108+
from .client.mqttHandlers import _onconnect_handler, _ondisconnect_handler
108109
from .client.callbacks import _error_callback, _response_callback

src/anedya/client/bindDevice.py

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,21 @@
33
from ..errors import AnedyaInvalidConfig, AnedyaTxFailure
44

55

6-
def bind_device(self, binding_secret: str, timeout: float | None = None):
6+
def bind_device(self, binding_secret: str, timeout: float | None = None) -> bool:
77
"""
8-
:param binding_secret: Binding secret to be used for binding the device
9-
:raises AnedyaInvalidConfig: If the configuration is not provided
10-
:raises AnedyaTxFailure: If the transaction fails
8+
Call this function to bind a device with the Anedya platform
119
12-
This function provides a way to bind a device to the Anedya platform.
10+
Args:
11+
binding_secret (str): A one time Binding secret obtained from the platform. This secret is usually passed to device during provisioning process through
12+
mobile app or any other process.
13+
timeout (float | None, optional): Time out in seconds for the request. In production setup it is advisable to use a timeout or else your program can get stuck indefinitely. Defaults to None.
14+
15+
Raises:
16+
AnedyaInvalidConfig: Method can raise this method if either configuration is not provided or if the connection mode is invalid.
17+
AnedyaTxFailure: Method can raise this method if the transaction fails.
18+
19+
Returns:
20+
bool: Returns true if the device is successfully bound with the platform.
1321
"""
1422
if self._config is None:
1523
raise AnedyaInvalidConfig('Configuration not provided')
@@ -21,7 +29,7 @@ def bind_device(self, binding_secret: str, timeout: float | None = None):
2129
raise AnedyaInvalidConfig('Invalid connection mode')
2230

2331

24-
def _bind_device_http(self, binding_secret: str, timeout: float | None = None):
32+
def _bind_device_http(self, binding_secret: str, timeout: float | None = None) -> bool:
2533
if self._config._testmode:
2634
url = "https://device.stageapi.anedya.io/v1/submitData"
2735
else:
@@ -36,7 +44,7 @@ def _bind_device_http(self, binding_secret: str, timeout: float | None = None):
3644
raise AnedyaTxFailure(payload['error'], payload['errCode'])
3745
except ValueError:
3846
raise AnedyaTxFailure(message="Invalid JSON response")
39-
return
47+
return True
4048

4149

4250
def _bind_device_mqtt(self, binding_secret: str, timeout: float | None = None):

src/anedya/client/mqttHandlers.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
from ..errors import AnedyaException
33

44

5-
def onconnect_handler(self, client, userdata, flags, reason_code, properties):
5+
def _onconnect_handler(self, client, userdata, flags, reason_code, properties):
66
rc = reason_code.value
77
if rc == 135:
88
raise AnedyaInvalidCredentials("Invalid credentials")
@@ -36,12 +36,12 @@ def onconnect_handler(self, client, userdata, flags, reason_code, properties):
3636
return
3737

3838

39-
def ondisconnect_handler(self,
40-
client,
41-
userdata,
42-
disconnect_flags,
43-
reason_code,
44-
properties):
39+
def _ondisconnect_handler(self,
40+
client,
41+
userdata,
42+
disconnect_flags,
43+
reason_code,
44+
properties):
4545
# First call the disconnect handler callback
4646
if self.on_disconnect is not None:
4747
self.on_disconnect(client,

src/anedya/client/submitData.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,15 @@
66

77
def submit_data(self, data: DataPoints, timeout: float | None = None):
88
"""
9-
:param data: Data to send as a :class: DataPoints object
10-
:param timeout: Timeout in seconds, default is None
9+
Submit data to Anedya Platform.
1110
12-
:raises AnedyaTxFailure: If data could not be submitted due to an error
11+
Args:
12+
data (DataPoints): Datapoints object, you can submit multiple types of variable in single request.
13+
timeout (float | None, optional): Time out in seconds for the request. In production setup it is advisable to use a timeout or else your program can get stuck indefinitely. Defaults to None.
1314
14-
This function sends data to the Anedya Cloud platform. It determines the connection mode from the SDK configuration and calls the appropriate submit data method (_submit_data_http or _submit_data_mqtt).
15+
Raises:
16+
AnedyaInvalidConfig: Method can raise this method if either configuration is not provided or if the connection mode is invalid.
17+
AnedyaTxFailure: Method can raise this method if the transaction fails.
1518
"""
1619

1720
if self._config is None:

src/anedya/client/submitLogs.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,15 @@
66

77
def submit_logs(self, logs: LogsCache, timeout: float | None = None):
88
"""
9-
:param logs: Logs to be send. :class: LogCache format.
10-
:param timeout: Timeout in seconds, default is None.
9+
Submit logs to Anedya
10+
11+
Args:
12+
logs (LogsCache): Logs
13+
timeout (float | None, optional): Time out in seconds for the request. In production setup it is advisable to use a timeout or else your program can get stuck indefinitely. Defaults to None.
14+
15+
Raises:
16+
AnedyaInvalidConfig: Method can raise this method if either configuration is not provided or if the connection mode is invalid.
17+
AnedyaTxFailure: Method can raise this method if the transaction fails.
1118
"""
1219
if self._config is None:
1320
raise AnedyaInvalidConfig('Configuration not provided')

src/anedya/client/timeSync.py

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,19 @@
44
import time
55

66

7-
def get_time(self, timeout: float | None = None):
7+
def get_time(self, timeout: float | None = None) -> int:
88
"""
9-
Get current time from Anedya Time Service using HTTP request -
10-
Gets current time using HTTP requests.
11-
Accuracy is generally within few tens of millisecond. For greater accuracy
12-
consider using NTP time service from Anedya
9+
Fetch the time information from Anedya.
10+
11+
Args:
12+
timeout (float | None, optional): Time out in seconds for the request. In production setup it is advisable to use a timeout or else your program can get stuck indefinitely. Defaults to None.
13+
14+
Raises:
15+
AnedyaInvalidConfig: Method can raise this method if either configuration is not provided or if the connection mode is invalid.
16+
AnedyaTxFailure: Method can raise this method if the transaction fails.
17+
18+
Returns:
19+
int: The method returns the current time in Unix millisecond epoch in UTC timezone
1320
"""
1421
if self._config is None:
1522
raise AnedyaInvalidConfig('Configuration not provided')
@@ -36,9 +43,9 @@ def _time_sync_http(self, timeout: float | None = None):
3643
if payload['success'] is not True:
3744
raise AnedyaTxFailure(payload['error'], payload['errCode'])
3845
deviceRecTime = int(time.time_ns() / 1000000)
39-
ServerReceiveTime = jsonResponse["serverReceiveTime"]
40-
ServerSendTime = jsonResponse["serverSendTime"]
41-
currentTime = (ServerReceiveTime + ServerSendTime + deviceRecTime - deviceSendTime) / 2
46+
ServerReceiveTime = int(jsonResponse["serverReceiveTime"])
47+
ServerSendTime = int(jsonResponse["serverSendTime"])
48+
currentTime = int((ServerReceiveTime + ServerSendTime + deviceRecTime - deviceSendTime) / 2)
4249
except ValueError:
4350
raise AnedyaTxFailure(message="Invalid JSON response")
4451
return currentTime

src/anedya/config.py

Lines changed: 32 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
from enum import Enum
22
import uuid
33
from .errors import AnedyaInvalidConfig
4+
from typing import Callable
45

56

67
class ConnectionMode(Enum):
@@ -18,6 +19,10 @@ class Encoding(Enum):
1819
CBOR = "CBOR"
1920

2021

22+
class RegionCode(Enum):
23+
AP_IN_1 = "ap-in-1"
24+
25+
2126
class AnedyaConfig:
2227
def __init__(self):
2328
"""
@@ -52,57 +57,58 @@ def __init__(self):
5257
self._security_set = False
5358
self._testmode = False
5459

55-
def set_connection_key(self, key):
60+
def set_connection_key(self, key: str):
5661
"""
57-
Set a connection key
62+
This method sets the connection key for the client
63+
64+
Args:
65+
key (str): Connection key for the client
5866
"""
5967
self.connection_key = key
6068

6169
def set_deviceid(self, id: str):
6270
"""
63-
Set DeviceID
71+
This method sets the device ID for the client
72+
73+
Args:
74+
id (str): A Unique physical device ID which should not change for the entire lifetime of the device. Requires a valid UUID
75+
76+
Raises:
77+
AnedyaInvalidConfig: The provided device ID should be a valid UUID, otherwise this exception will be raised
6478
"""
6579
try:
6680
self._deviceID = uuid.UUID(id)
6781
except ValueError:
6882
raise AnedyaInvalidConfig("Device ID needs to be valid UUID")
6983
self._deviceid_set = True
7084

71-
def set_timeout(self, timeout):
72-
"""
73-
Set timeout for automatic flush of the data
74-
"""
75-
self.timeout = timeout
76-
77-
def set_maxbuffer_size(self, buffersize):
85+
def set_region(self, region: RegionCode):
7886
"""
79-
Set maximum buffer size
80-
"""
81-
self.max_buffer_size = buffersize
87+
This method sets the region for the client
8288
83-
def set_region(self, region):
84-
"""
85-
Set region
89+
Args:
90+
region (RegionCode): Set the regioncode where your Anedya project is created.
8691
"""
8792
self.region = region
8893

89-
def set_on_connect(self, callback):
94+
def set_on_connect(self, callback: Callable[[],]):
9095
"""
91-
Set on connect callback
96+
You can use this function to set a callback function that will be called when the connection is established.
97+
98+
Args:
99+
callback (Callable[[],]): A function which will be called when the connection is established. Please note that callback functions should not be blocking.
92100
"""
93101
self.on_connect = callback
94102

95-
def set_on_disconnect(self, callback):
103+
def set_on_disconnect(self, callback: Callable[[],]):
96104
"""
97-
Set on disconnect callback
98-
"""
99-
self.on_disconnect = callback
105+
You can use this function to set a callback function that will be called when the connection is disconnected. This callback will be called for both intentional
106+
and unintentional disconnections.
100107
101-
def set_on_message(self, callback):
102-
"""
103-
Set on message callback
108+
Args:
109+
callback (Callable[[],]): A function which will be called when the connection is disconnected. Please note that callback functions should not be blocking.
104110
"""
105-
self.on_message = callback
111+
self.on_disconnect = callback
106112

107113

108114
def default_config():

src/anedya/models.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,14 @@
77

88
class FloatData:
99
def __init__(self, variable: str, value: float, timestamp_milli: int = int(time.time_ns() / 1000000)):
10+
"""
11+
Create a Float datapoint object which can be sent to Anedya Server
12+
13+
Args:
14+
variable (str): Name of the variable
15+
value (float): Value of the variable
16+
timestamp_milli (int, optional): Timestamp in millisecond unix epoch. Defaults to current time. Pass 0 to take Anedya Server Time
17+
"""
1018
self.variable = variable
1119
self.timestamp = timestamp_milli
1220
self.value = value
@@ -22,6 +30,13 @@ def toJSON(self):
2230

2331
class Log:
2432
def __init__(self, log: str, timestamp_milli: int = int(time.time_ns() / 1000000)):
33+
"""
34+
Create a Log object which can be sent to Anedya Server
35+
36+
Args:
37+
log (str): Log string that you want to send to Anedya
38+
timestamp_milli (int, optional): Timestamp in millisecond unix epoch. Defaults to current time. Pass 0 to take Anedya Server Time
39+
"""
2540
self.log = log
2641
self.timestamp = timestamp_milli
2742

@@ -38,6 +53,12 @@ def __init__(self):
3853
self.data = []
3954

4055
def append(self, datapoint: FloatData):
56+
"""
57+
Append a datapoint to the datapoints batch which will be sent to Anedya Server in a single request
58+
59+
Args:
60+
datapoint (FloatData): Datapoint object
61+
"""
4162
self.data.append(datapoint)
4263

4364
def toJSON(self):
@@ -59,6 +80,12 @@ def __init__(self):
5980
self.logs = []
6081

6182
def append(self, log: Log):
83+
"""
84+
Append a log to the log batch which will be sent to Anedya Server in a single request
85+
86+
Args:
87+
log (Log): Log object
88+
"""
6289
self.logs.append(log)
6390

6491
def toJSON(self):

0 commit comments

Comments
 (0)