|
| 1 | +import json |
| 2 | +import string |
| 3 | +import random |
| 4 | +import base64 |
| 5 | +from ..models import CommandDetails, AnedyaEncoder |
| 6 | +from enum import Enum |
| 7 | +from ..errors import AnedyaInvalidConfig, AnedyaInvalidType, AnedyaTxFailure |
| 8 | +from ..config import ConnectionMode |
| 9 | + |
| 10 | + |
| 11 | +class CommandStatus(Enum): |
| 12 | + PENDING = "pending" |
| 13 | + RECEIVED = "received" |
| 14 | + PROCESSING = "processing" |
| 15 | + SUCCESS = "success" |
| 16 | + FAILURE = "failure" |
| 17 | + INVALIDATED = "invalidated" |
| 18 | + |
| 19 | + |
| 20 | +def update_command_status(self, command: CommandDetails, status: CommandStatus, ackdata: str | bytes | None = None, acktype: str = "string", timeout: float | None = None) -> None: |
| 21 | + """ |
| 22 | + Update status of a command |
| 23 | +
|
| 24 | + Args: |
| 25 | + command (CommandDetails): Command object of which status needs to be updated |
| 26 | + status (CommandStatus): New status of the command |
| 27 | + ackdata (str | bytes | None, optional): Data to be submitted along with acknowledgement. Maximum 1 kB of data is allowed. Defaults to None. |
| 28 | + acktype (str, optional): Specify the type of data submitted. Defaults to "string". |
| 29 | + 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. |
| 30 | +
|
| 31 | + Raises: |
| 32 | + AnedyaInvalidConfig: Invalid configuration |
| 33 | + AnedyaInvalidType: Invalid datatype is specified |
| 34 | + AnedyaTxFailure: Transaction failure |
| 35 | + """ |
| 36 | + if self._config is None: |
| 37 | + raise AnedyaInvalidConfig('Configuration not provided') |
| 38 | + if self._config.connection_mode == ConnectionMode.HTTP: |
| 39 | + return _update_command_status_http(self, command=command, status=status, timeout=timeout) |
| 40 | + elif self._config.connection_mode == ConnectionMode.MQTT: |
| 41 | + return _update_command_status_mqtt(self, command=command, status=status, timeout=timeout) |
| 42 | + else: |
| 43 | + raise AnedyaInvalidConfig('Invalid connection mode') |
| 44 | + |
| 45 | + |
| 46 | +def _update_command_status_http(self, command: CommandDetails, status: CommandStatus, ackdata: str | tuple | None = None, acktype: str = "string", timeout: float | None = None) -> None: |
| 47 | + if self._config._testmode: |
| 48 | + url = "https://device.stageapi.anedya.io/v1/submitData" |
| 49 | + else: |
| 50 | + url = self._baseurl + "/v1/submitData" |
| 51 | + d = _UpdateCommandStatusReq("req_" + ''.join(random.choices(string.ascii_letters + string.digits, k=16)), command=command, status=status, ackdata=ackdata, acktype=acktype) |
| 52 | + r = self._httpsession.post(url, data=d.encodeJSON(), timeout=timeout) |
| 53 | + # print(r.json()) |
| 54 | + try: |
| 55 | + jsonResponse = r.json() |
| 56 | + payload = json.loads(jsonResponse) |
| 57 | + if payload['success'] is not True: |
| 58 | + raise AnedyaTxFailure(payload['error'], payload['errCode']) |
| 59 | + except ValueError: |
| 60 | + raise AnedyaTxFailure(message="Invalid JSON response") |
| 61 | + return |
| 62 | + |
| 63 | + |
| 64 | +def _update_command_status_mqtt(self, command: CommandDetails, status: CommandStatus, ackdata: str | tuple | None = None, acktype: str = "string", timeout: float | None = None) -> None: |
| 65 | + # Create and register a transaction |
| 66 | + tr = self._transactions.create_transaction() |
| 67 | + # Encode the payload |
| 68 | + d = _UpdateCommandStatusReq(tr.get_id(), command=command, status=status, ackdata=ackdata, acktype=acktype) |
| 69 | + payload = d.encodeJSON() |
| 70 | + # Publish the message |
| 71 | + # print(payload) |
| 72 | + topic_prefix = "$anedya/device/" + str(self._config._deviceID) |
| 73 | + # print(topic_prefix + "/submitData/json") |
| 74 | + msginfo = self._mqttclient.publish(topic=topic_prefix + "/commands/updateStatus/json", |
| 75 | + payload=payload, qos=1) |
| 76 | + try: |
| 77 | + msginfo.wait_for_publish(timeout=timeout) |
| 78 | + except ValueError: |
| 79 | + raise AnedyaTxFailure(message="Publish queue full") |
| 80 | + except RuntimeError as err: |
| 81 | + raise AnedyaTxFailure(message=str(err)) |
| 82 | + # Wait for transaction to complete |
| 83 | + tr.wait_to_complete() |
| 84 | + # Transaction completed |
| 85 | + # Get the data from the transaction |
| 86 | + data = tr.get_data() |
| 87 | + # Clear transaction |
| 88 | + self._transactions.clear_transaction(tr) |
| 89 | + # Check if transaction is successful or not |
| 90 | + if data['success'] is not True: |
| 91 | + raise AnedyaTxFailure(data['error'], data['errCode']) |
| 92 | + return |
| 93 | + |
| 94 | + |
| 95 | +class _UpdateCommandStatusReq: |
| 96 | + def __init__(self, reqId: str, command: CommandDetails, status: CommandStatus, ackdata: str | bytes | None = None, acktype: str = "string"): |
| 97 | + self.command_id = command.id |
| 98 | + self.reqID = reqId |
| 99 | + self.status = status |
| 100 | + if acktype == "string": |
| 101 | + if isinstance(ackdata, str): |
| 102 | + raise AnedyaInvalidType('ackdata is not a valid str') |
| 103 | + self.ackdata = ackdata |
| 104 | + self.acktype = "string" |
| 105 | + elif acktype == "binary": |
| 106 | + if isinstance(ackdata, bytes): |
| 107 | + raise AnedyaInvalidType('ackdata is not a valid list') |
| 108 | + self.ackdata_binary = ackdata |
| 109 | + self.ackdata = base64.b64encode(self.ackdata_binary).decode('ascii') |
| 110 | + self.acktype = "binary" |
| 111 | + else: |
| 112 | + raise AnedyaInvalidType('Invalid acktype') |
| 113 | + |
| 114 | + def toJSON(self): |
| 115 | + dict = { |
| 116 | + "reqId": self.reqID, |
| 117 | + "commandId": str(self.command_id), |
| 118 | + "status": self.status, |
| 119 | + "ackdata": self.ackdata, |
| 120 | + "ackdatatype": self.acktype |
| 121 | + } |
| 122 | + return dict |
| 123 | + |
| 124 | + def encodeJSON(self): |
| 125 | + data = json.dumps(self, cls=AnedyaEncoder) |
| 126 | + return data |
0 commit comments