def test_no_dispatch_alarm_for_Keep_Alive_high_value(self): server = Server(None, None, self.sns_client, self.log) data = {"timeStamp": "1499366509000", "DevEUI": "260113E3", "KA": {"interval": "24", "voltage": "2.856"}} server.dispatch_alarm("AE1234567", data) self.assertEqual(0, self.sns_client.return_published_times())
def test_persist_data_to_DynamoDB(self): server = Server(self.dynamodb, None, self.log) expected_item = { 'title': "The Big New Movie", 'year': 2015, 'info': { 'plot': "Nothing happens at all.", 'rating': "0" } } server.persist_data() self.assertEqual(1, self.dynamodb.return_persisted_times()) self.assertEqual(expected_item, self.dynamodb.return_persisted_item())
def test_dispatch_alarm_Keep_Alive_low_value(self): server = Server(None, None, self.sns_client, self.log) virtual_tx = "AE1234567" data = {"timeStamp": "1499366509000", "DevEUI": "260113E3", "KA": {"interval": "24", "voltage": "2.456"}} server.dispatch_alarm(virtual_tx, data) data.update({"virtual_tx": virtual_tx}) expected_message = json.dumps(data) self.assertEqual(1, self.sns_client.return_published_times()) self.assertEqual("arn:aws:sns:eu-west-1:488643450383:NotifySNS", self.sns_client.return_topicarn()) self.assertEqual(expected_message, self.sns_client.return_message()) self.assertEqual("Triggered Alarm 260113E3", self.sns_client.return_subject())
def test_update_data_in_DynamoDB(self): server = Server(self.dynamodb_device_data, None, None, self.log) expected_item = { "timeStamp": 1499366509000, "DevEUI": "260113E3", "GEO": {"lat": "12.5", "lng": "1.4"} } server.update_data(expected_item) self.assertEqual(1, self.dynamodb_device_data.return_updated_times()) self.assertEqual( {"timeStamp": 1499366509000, "DevEUI": "260113E3"}, self.dynamodb_device_data.return_updated_item()["Key"]) self.assertEqual( 'SET geo = :val', self.dynamodb_device_data.return_updated_item()["UpdateExpression"]) self.assertEqual( {':val': {"lat": "12.5", "lng": "1.4"}}, self.dynamodb_device_data.return_updated_item()["ExpressionAttributeValues"])
def sigfox(): try: parsed_dic = Server.parse_sigfox_dic(app.current_request.to_dict()) app.log.debug("Received event virtual_tx:" + parsed_dic["virtual_tx"]) server.publish_data_store_device(parsed_dic) return Response(body='', status_code=200, headers={'Content-Type': 'text/plain'}) except KeyError: app.log.error("Error parsing SIGFOX document") raise BadRequestError("Error parsing SIGFOX document")
def lora(): try: request = app.current_request app.log.debug(request.json_body) parsed_json = Server.parse_lora_json(request.json_body["body"]) app.log.debug("Received event virtual_tx:" + parsed_json["virtual_tx"]) server.publish_data_store_device(parsed_json) return parsed_json except KeyError: app.log.error("Error parsing LORA document") raise BadRequestError("Error parsing LORA document")
def realtime_parsing_payload(event, context): app.log.debug("Parsing payload") for record in event["Records"]: message = record["Sns"]["Message"] message_dic = json.loads(message) parsed = Server.parse_payload(message_dic) virtual_tx = message_dic["virtual_tx"] server.dispatch_alarm(virtual_tx, parsed) server.update_data(parsed) app.log.debug("Parsing payload done") return "worked"
def test_publishing_data_to_SNS(self): data_to_publish = { "DevEUI": "260113E3", "extra": { "DevEUI_uplink": { "CustomerID": "100001774", "DevAddr": "260113E3" } }, "payload": "010000beef", "timeStamp": 1499366509000, "time_json": "2017-07-06T18:41:49.51+02:00", "type": "LORA", "virtual_tx": "2dd66154468fa5d433420f5bad5d3f580f3dab46fa33e127ef69c511f641ae2f" } server = Server(None, None, self.sns_client, self.log) expected_message = json.dumps(data_to_publish) server.publish_data_store_device(data_to_publish) self.assertEqual(1, self.sns_client.return_published_times()) self.assertEqual(expected_message, self.sns_client.return_message()) self.assertEqual("arn:aws:sns:eu-west-1:488643450383:StoreDeviceData", self.sns_client.return_topicarn())
def test_parse_sigfox_with_test_data(self): data_dic = { "method": "GET", "query_params": { "data": "10bb17f18198100734", "id": "260113E2", "time": "1515360218", "test": "test" }, "stage_vars": {}, "uri_params": {} } parsed_dic = Server.parse_sigfox_dic(data_dic) self.assertEqual(parsed_dic["timeStamp"], int("1515360218")) self.assertEqual(parsed_dic["payload"], "10bb17f18198100734") self.assertEqual(parsed_dic["DevEUI"], "260113E2") self.assertEqual(parsed_dic["type"], "SIGFOX") self.assertEqual(parsed_dic["test"], "test")
def test_parsing_keep_alive_payload(self): expected_item = {"virtual_tx": "A001", "time_json": "2017-01-21T12:12:12.001Z", "timeStamp": 1499366509000, "payload": "02180AE4", "DevEUI": "260113E3", "type": "LORA", "extra": "{}"} keep_alive = Server.parse_payload(expected_item) self.assertIsNotNone(keep_alive) payload = expected_item["payload"] interval = payload[2:4] interval_int = int(interval, 16) voltatge_hex = payload[4:8] voltatge_hex_dec = int(voltatge_hex, 16) / 1000 self.assertEqual(1499366509000, keep_alive["timeStamp"]) self.assertIsNotNone(keep_alive["KA"]) self.assertEqual(str(interval_int), keep_alive["KA"]["interval"]) self.assertEqual(str(voltatge_hex_dec), keep_alive["KA"]["voltage"])
def test_parse_sigfox(self): data_dic = { "context": { "httpMethod": "GET", "identity": { "sourceIp": "127.0.0.1" }, "resourcePath": "/sigfox" }, "headers": { "accept": "*/*", "accept-encoding": "gzip, deflate", "connection": "keep-alive", "host": "localhost:8000", "user-agent": "HTTPie/0.9.8" }, "method": "GET", "query_params": { "data": "10bb17f18198100734", "id": "260113E2", "time": "1515360218" }, "stage_vars": {}, "uri_params": {} } parsed_dic = Server.parse_sigfox_dic(data_dic) d = datetime.utcfromtimestamp(int("1515360218") * 1000 / 1e3) json_date = str(d.isoformat()) + "Z" virtual_tx = "260113E2" + "-" + json_date hash_object = hashlib.sha256(virtual_tx.encode()) hex_dig = hash_object.hexdigest() self.assertEqual(parsed_dic["time_json"], json_date) self.assertEqual(parsed_dic["timeStamp"], int("1515360218")) self.assertEqual(parsed_dic["payload"], "10bb17f18198100734") self.assertEqual(parsed_dic["DevEUI"], "260113E2") self.assertEqual(parsed_dic["type"], "SIGFOX") self.assertEqual(parsed_dic["virtual_tx"], hex_dig)
def test_parsing_geolocation_payload(self): expected_item = {"virtual_tx": "A001", "time_json": "2017-01-21T12:12:12.001Z", "timeStamp": 1499366509000, "payload": "10bb17f18198100734", "DevEUI": "260113E3", "type": "LORA", "extra": "{}"} geolocation = Server.parse_payload(expected_item) self.assertIsNotNone(geolocation) payload = expected_item["payload"] lat_hex = payload[2:8] lat_str = int(lat_hex, 16) lat = (lat_str * 180 / 16777215) - 90 lng_hex = payload[8:14] lng_str = int(lng_hex, 16) lng = (lng_str * 360 / 16777215) - 180 self.assertEqual(1499366509000, geolocation["timeStamp"]) self.assertIsNotNone(geolocation["GEO"]) # AppTest.printGeoLocation(lat, lat_hex, lat_str, lng_hex, lng_str, payload, lng) self.assertEqual(str(lat), geolocation["GEO"]["lat"]) self.assertEqual(str(lng), geolocation["GEO"]["lng"])
def test_parse_lora_json(self): jsonbody = json.loads(self.str_data) parsed_json = Server.parse_lora_json(self.str_data) time = jsonbody["DevEUI_uplink"]["Time"] payload = jsonbody["DevEUI_uplink"]["payload_hex"] device_id = jsonbody["DevEUI_uplink"]["DevAddr"] virtual_tx = device_id + "-" + time hash_object = hashlib.sha256(virtual_tx.encode()) hex_dig = hash_object.hexdigest() dt = dateutil.parser.parse(time) strftime = dt.strftime("%s") time_millis = int(strftime) * 1000 self.assertEqual(parsed_json["time_json"], time) self.assertEqual(parsed_json["timeStamp"], int(time_millis)) self.assertEqual(parsed_json["payload"], payload) self.assertEqual(parsed_json["DevEUI"], device_id) self.assertEqual(parsed_json["type"], "LORA") self.assertEqual(parsed_json["extra"], json.dumps(jsonbody)) self.assertEqual(parsed_json["virtual_tx"], hex_dig)
import boto3 import logging from chalicelib.server import Server app = Chalice(app_name='platform') app.log.setLevel(logging.DEBUG) app.debug = True MOVIE_TABLE = os.getenv('APP_TABLE_NAME', 'defaultTable') SNS_TOPIC = os.getenv('SNS_TOPIC', 'defaultSNS') table = boto3.resource('dynamodb').Table(MOVIE_TABLE) sns_client = boto3.client('sns') server = Server(table, sns_client, app.log) @app.lambda_function() def realtime_lambda_function(event, context): # print("Received event: " + json.dumps(event, indent=2)) app.log.debug("This call is from the Lambda") # app.log.debug("From SNS: " + event) server.persist_data(event, context) return "test" @app.route('/lambda') def insert_data_in_lambda(): app.log.debug("insert_data_in_lambda") return server.publish_data()
def test_publishing_data_to_SNS(self): server = Server(None, self.sns_client, self.log) expected_message = "Good news everyone!" server.publish_data() self.assertEqual(1, self.sns_client.return_published_times()) self.assertEqual(expected_message, self.sns_client.return_message())
app = Chalice(app_name='platform') app.log.setLevel(logging.DEBUG) app.debug = True DEVICE_DATA_TABLE = os.getenv('APP_TABLE_NAME', 'defaultTable') DEVICE_TABLE = os.getenv('DEVICES_TABLE_NAME', 'defaultTable') SNS_TOPIC = os.getenv('SNS_TOPIC', 'defaultSNS') device_data_table = boto3.resource('dynamodb').Table(DEVICE_DATA_TABLE) device_table = boto3.resource('dynamodb').Table(DEVICE_TABLE) sns_client = boto3.client('sns') server = Server(device_data_table, device_table, sns_client, app.log) @app.lambda_function() def realtime_lambda_function(event, context): app.log.debug("This is the new call from the Lambda realtime") for record in event["Records"]: message = record["Sns"]["Message"] message_dic = json.loads(message) print("This is the SNS message! " + message_dic["DevEUI"]) server.persist_data(message_dic) server.publish_data_payload_parser(message_dic) app.log.debug("realtime lambda done") return "worked"
def test_not_update_data_in_DynamoDB_if_None(self): server = Server(self.dynamodb_device_data, None, None, self.log) expected_item = None server.update_data(expected_item) self.assertEqual(0, self.dynamodb_device_data.return_updated_times())
def test_parsing_none_known_payload(self): expected_item = {"virtual_tx": "A001", "time_json": "2017-01-21T12:12:12.001Z", "timeStamp": 1499366509000, "payload": "A1bb17f18198100734", "DevEUI": "260113E3", "type": "LORA", "extra": "{}"} geolocation = Server.parse_payload(expected_item) self.assertIsNone(geolocation)