Commit 00b9412d authored by Federico Sismondi's avatar Federico Sismondi

Add() hanlder for node info updates coming from LoRa server'

parent c47c3f7c
......@@ -119,3 +119,10 @@ UPDATE|
+----------------------+
```
## Useful mysql queries for DB querying
```mysql-sql
SELECT time_index, entity_id, soilMoisture FROM mtcarouge.etflowerbed ORDER BY time_index DESC limit 100;
```
from flask import Flask
from flask import Flask, jsonify
from flask import request
import requests
import os
......@@ -30,12 +30,39 @@ http_header_post = {
}
# API errors & handlers
class InvalidUsage(Exception):
status_code = 400
def __init__(self, message, status_code=None, payload=None):
Exception.__init__(self)
self.message = message
if status_code is not None:
self.status_code = status_code
self.payload = payload
def to_dict(self):
rv = dict(self.payload or ())
rv['message'] = self.message
return rv
@app.errorhandler(InvalidUsage)
def handle_invalid_usage(error):
response = jsonify(error.to_dict())
response.status_code = error.status_code
return response
@app.route('/')
@app.route('/healthcheck')
def healthcheck():
return 'This service is up and running!'
# Utility functions
def _log_level_of_moisture(cb, sensor):
"""
0-10 Centibars = Saturated soil
......@@ -50,25 +77,27 @@ def _log_level_of_moisture(cb, sensor):
"""
if cb < 10:
app.logger.warning("{} indicates soil is saturated wet ({} cb)!".format(sensor,cb))
app.logger.warning("{} indicates soil is saturated wet ({} cb)!".format(sensor, cb))
elif cb < 30:
app.logger.info("{} indicates soil is adequately wet :] ({} cb)".format(sensor,cb))
app.logger.info("{} indicates soil is adequately wet :] ({} cb)".format(sensor, cb))
elif cb < 60:
app.logger.info("{} indicates soil in usual range of irrigation for moist soils :) ({} cb)".format(sensor,cb))
app.logger.info("{} indicates soil in usual range of irrigation for moist soils :) ({} cb)".format(sensor, cb))
elif cb < 100:
app.logger.warning("{} indicates soil needs irrigation ({} cb)!".format(sensor,cb))
app.logger.warning("{} indicates soil needs irrigation ({} cb)!".format(sensor, cb))
elif cb < 200:
app.logger.warning("{} indicates soil is dangerously dry !!! ({} cb)!".format(sensor,cb))
app.logger.warning("{} indicates soil is dangerously dry !!! ({} cb)!".format(sensor, cb))
else:
app.logger.error("Measurement not it expected range {}".format(cb))
def _conv_micro_volts_to_moiture_cb(micro_volts):
"""
Lora Bridge device has to channels (A and B). Only the channel A is connected. To read correctly the value from the channel A, you should take the byte 3 to 5.
Lora Bridge device has to channels (A and B).
Only the channel A is connected. To read correctly the value from the channel A, you should take the byte 3 to 5.
Then, you should decoded from Hex to Decimal. IMPORTANT: The value is expressed in µV. (1V = 1.000.000µV)
Sensor Voltage range is from 0V to 3V. This voltage range is linearly dependent to the real value of the sensor, which is expressed in cb (kPa):
Sensor Voltage range is from 0V to 3V.
This voltage range is linearly dependent to the real value of the sensor, which is expressed in cb (kPa):
- 0V = Plants are wet - do not need watering (0cb)
- 3V = Plant are dry - need watering (239cb)
......@@ -96,11 +125,12 @@ def _get_reading(message_data):
reading_hex = base64.standard_b64decode(message_data).hex()
if reading_hex[0:2] == '42': # it's a dataFrame
return _conv_micro_volts_to_moiture_cb(int(reading_hex[6:12], 16)) # ToDo may need some calculations here
return _conv_micro_volts_to_moiture_cb(int(reading_hex[6:12], 16))
else:
app.logger.warning("Not a sensor reading (expected 0x42) {}".format(reading_hex))
return None
msg = 'Not a sensor reading (expected 0x42) {}'.format(reading_hex)
app.logger.warning(msg)
raise InvalidUsage(message=msg)
def _forward_to_message_broker():
......@@ -112,8 +142,8 @@ def _forward_to_message_broker():
dev_eui = request.json['deveui']
entity_id, street_address = mapping_deveui_to_fiware_instance_meta[dev_eui]
_log_level_of_moisture(sensor_reading,entity_id)
app.logger.info("Pushing IoT reading ({}) to {}".format(sensor_reading, entity_id))
_log_level_of_moisture(sensor_reading, entity_id)
app.logger.info("Forwarding IoT reading ({}) to IoT platform entity: {}".format(sensor_reading, entity_id))
url = "{}/v2/entities/{}/attrs?options=keyValues".format(URL_BASE, entity_id)
payload = {
'boxId': entity_id.split('-')[-1],
......@@ -170,6 +200,7 @@ def _dummy_post_handler():
return 'Got POST with json %s' % request.json
# Flask route handlers
@app.route('/dca-carouge-watering-sensed-data', methods=['POST'])
def post_dca_carouge_watering_sensed_data():
return _dummy_post_handler()
......@@ -185,18 +216,24 @@ def post_dca_carouge_watering_sensed_data_payload():
resp = {}
resp.update({"fs_dump": _dump_raw_data_to_filesystem()})
resp.update({"message_broker_fw": _forward_to_message_broker()})
#resp.update({'description': _dummy_post_handler()})
# resp.update({'description': _dummy_post_handler()})
return resp
@app.route('/dca-carouge-watering-sensed-data/rest/callback/nodeinfo', methods=['POST'])
def post_dca_carouge_watering_sensed_node_info():
print(request.json)
raise InvalidUsage(message='This is still not implemented', payload=request.json)
@app.route('/dca-carouge-watering-sensed-data', methods=['GET'])
def get_dca_carouge_watering_sensed_data():
return 'This is still not implemented '
raise InvalidUsage(message='This is still not implemented')
@app.route('/dca-carouge-watering-sensed-data/rest/callback/payloads/ul', methods=['GET'])
def get_dca_carouge_watering_sensed_data_callback():
return 'This is still not implemented '
raise InvalidUsage(message='This is still not implemented')
if __name__ == "__main__":
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment