commit e95297fe93337f9a863f72f5fab1bebe56f6b87f Author: sessionm21 Date: Sun Apr 19 07:36:00 2020 +0100 init diff --git a/README.md b/README.md new file mode 100644 index 0000000..66f86dc --- /dev/null +++ b/README.md @@ -0,0 +1,8 @@ +# Dependencies + +- protobuf-compiler +- python-sqlite + +# Generate files from .proto file + +```protoc -I=./ --python_out=./ message.proto``` diff --git a/main.py b/main.py new file mode 100644 index 0000000..c99250e --- /dev/null +++ b/main.py @@ -0,0 +1,63 @@ +import paho.mqtt.client as mqtt +import json +import base64 +import message_pb2 +import sqlite3 + +app_id = "fenceles_grazing" +access_key = "ttn-account-v2.XVvtBVcWzkeby-fe9eLtiJBLRbjQR-b358S4z70Xa-0" + + +# For now use collar id of 1, should look up collar id based on collarname from db +def store_coord(collarname, x, y): + print("Coord {x: " + str(x) + ", y: " + str(y) + "}") + db = sqlite3.connect('data.sqlite') + entries = [(1, x, y)] + db.executemany("INSERT INTO data_point (collar_id, longitude, latitude, datetime) VALUES (?,?,?,datetime('now'))", entries) + db.commit() + db.close() + +# The callback for when the client receives a CONNACK response from the server. +def on_connect(client, userdata, flags, rc): + print("Connected with result code "+str(rc)) + + # Subscribing in on_connect() means that if we lose the connection and + # reconnect then subscriptions will be renewed. + # client.subscribe("+/devices/+/events/activations") + client.subscribe("+/devices/+/up") + client.publish(appid+"/devices/+/down", "hello world") + +# The callback for when a PUBLISH message is received from the server. +def on_message(client, userdata, msg): + # Print entire payload + print(msg.payload) + # Parse payload (JSON) + payload = json.loads(msg.payload) + + # Decode payload_raw, which is the protobuf + code = payload['payload_raw'] + bcode = base64.b64decode(code) + res = message_pb2.CollarResponse() + res.ParseFromString(bcode) + store_coord(payload['dev_id'], res.loc.x, res.loc.y) + +# Test protobuf here +# code = bytearray('CgoNAAAAABUAAAAA', "utf-8") +# print(code) +# bcode = base64.b64decode(code) +# res = message_pb2.CollarResponse() +# res.ParseFromString(bcode) +# print("Coord {x: " + str(res.loc.x) + ", y: " + str(res.loc.y) + "}") + +client = mqtt.Client() +client.on_connect = on_connect +client.on_message = on_message + +client.username_pw_set(app_id, access_key) +client.connect("us-west.thethings.network", 1883, 60) + +# Blocking call that processes network traffic, dispatches callbacks and +# handles reconnecting. +# Other loop*() functions are available that give a threaded interface and a +# manual interface. +client.loop_forever()