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) 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()