From 2e90f044e670965f97b887ee61e00f612d3c94ab Mon Sep 17 00:00:00 2001
From: Callum Inglis <callum.inglis@4oh4.co.uk>
Date: Fri, 25 Mar 2022 21:29:46 +0000
Subject: [PATCH] Update Fetch Sensor Config from API

---
 RaspberryPi_Receiver/Pi_Receiver.py | 34 +++++++++++++++++++++++------
 1 file changed, 27 insertions(+), 7 deletions(-)

diff --git a/RaspberryPi_Receiver/Pi_Receiver.py b/RaspberryPi_Receiver/Pi_Receiver.py
index 5b3ec90..f00ece4 100644
--- a/RaspberryPi_Receiver/Pi_Receiver.py
+++ b/RaspberryPi_Receiver/Pi_Receiver.py
@@ -200,17 +200,30 @@ class Co2(object):
     def __init__(self, co2):
         self.co2 = co2
 
+class FilterBySensorApiRequest(object):
+    def __init__(self, sensorUID):
+        self.apiKey = None
+        self.sensorUID = sensorUID
+        self.gatewayUID = get_gateway_serial()
+        self.gatewayApiKey = secrets.GATEWAY_API_KEY
+
+    # Python Object to JSON Object
+    def to_json(self):
+        return json.dumps(self, default=lambda o: o.__dict__, sort_keys=True)
 
 def get_sensor_config_from_api(sensor_uid):
     headers = {'Content-Type': 'Application/json'}
-    response = requests.post(API_URL + '/' + secrets.API_KEY + '/sensor/getConfig/' + sensor_uid, headers=headers)
+    request_data = FilterBySensorApiRequest(sensor_uid).to_json()
+    logging.info("[i] Fetching Sensor Config for %s. Request %s" % (sensor_uid, request_data))
+    response = requests.post(API_URL + '/sensor/getConfig/', data=request_data, headers=headers)
 
     if response.status_code != 200:
+        logging.info("[-] Failed to fetch config for Sensor %s, Status Code: %s" % (sensor_uid, response.status_code))
         return None
 
+    logging.info("[+] Fetched Config for Sensor %s, Config: %s" % (sensor_uid, response.content))
     return json.loads(response.content)
 
-
 class Reply:
     """JSON Object transmitted back to sensor when they transmit a "TX Payload".
     Include ack status, and any config updates, along with sensor ID, gateway ID & message ID
@@ -388,14 +401,20 @@ class MqConsumer:
             self.channel.basic_reject(delivery_tag=method.delivery_tag) # Re-Queue
             return
 
+        # Already Reported
+        if response.status_code == 208:
+            logging.info("[MQ Consumer] [+] messageID %s (%s) from sensor %s already transmitted to API" % (data['sensorMetadata']['messageID'], content['timestamp'], data['sensorMetadata']['uid']))
+            self.channel.basic_ack(delivery_tag=method.delivery_tag) # Ack from queue
+            return
+
         # API Submissions Succesful
-        if response.status_code == 200:
+        if response.status_code >= 200 and response.status_code < 300:
             logging.info("[MQ Consumer] [+] Successfully transmitted messageID %s (%s) from sensor %s to API" % (data['sensorMetadata']['messageID'], content['timestamp'], data['sensorMetadata']['uid']))
             self.channel.basic_ack(delivery_tag=method.delivery_tag) # Ack from queue
             return
 
         # Unsucesful
-        logging.info("[MQ Consumer] [-] API Error (%s) when transmitting messageID %s (%s) from sensor %s to API" % (response.status_code, content['DATA']['sensorMetadata']['messageID'], content['timestamp'], content['DATA']['sensorMetadata']['uid']))
+        logging.info("[MQ Consumer] [-] API Error (%s) when transmitting messageID %s (%s) from sensor %s to API" % (response.status_code, data['sensorMetadata']['messageID'], content['timestamp'], data['sensorMetadata']['uid']))
         self.channel.basic_reject(delivery_tag=method.delivery_tag) # Re-Queue
         return
 
@@ -424,6 +443,7 @@ def ack_message(sensor_response):
 
     # Retrieve up-to-date sensor config from API & Transmit back to sensor
     updated_sensor_config = get_sensor_config_from_api(sensor_response.sensorMetadata.uid)
+
     if updated_sensor_config is not None:
         data.update_config_polling_frequency(updated_sensor_config['pollingFrequency'])
         data.update_config_tx_after_n_readings(updated_sensor_config['txAfterNReadings'])
@@ -455,8 +475,8 @@ def handle_rx_hello(rx_hello_queue, data):
 
     # Check I'm not expecting any methods within rx_hello.reservationTime seconds
     if not rx_hello_queue.can_accept():
-        rx_hello.set_ok(False)
-        logging.info("    [-] RX Hello \"No\" Reply Sent - Reserved by %s for %i seconds"
+        rx_hello.set_ok(False)  # We're not actually going to send any reply, this improves overall system performance.
+        logging.info("    [-] RX Hello \"No\". - Reserved by %s for %i seconds"
               % (rx_hello_queue.sensorID, rx_hello_queue.reservedUntil - time()))
 
     else:
@@ -464,10 +484,10 @@ def handle_rx_hello(rx_hello_queue, data):
 
         # Send "OK" + UID
         rx_hello.set_ok(True)  # We are happy for this sensor to send its data
+        transmit_object_with_lora(rx_hello)
         logging.info("    [+] RX Hello \"OK\" Reply Sent - %s is permitted to send for %d seconds"
               % (rx_hello.uid, rx_hello.reservationTime))
 
-    transmit_object_with_lora(rx_hello)
     return True
 
 
-- 
GitLab