import paho.mqtt.client as mqtt import json import base64 import message_pb2 import sqlite3 import configparser config = configparser.ConfigParser() config.read("config.ini") app_id = config['Default']['AppId'] access_key = config['Default']['AccessKey'] # For now use collar id of 1, should look up collar id based on collarname from db def store_collar_data(collarname, res): print("Coord {x: " + str(res.loc.x) + ", y: " + str(res.loc.y) + "}") db = sqlite3.connect('data.sqlite') entries = [(1, res.loc.x, res.loc.y)] db.executemany( "INSERT INTO data_point (collar_id, longitude, latitude, datetime) VALUES (?,?,?,datetime('now'))", entries) db.commit() if(res.oob == 1): entries = [(1, res.loc.x, res.loc.y)] db.executemany( "INSERT INTO stimulus_activation (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_collar_data(payload['dev_id'], res.loc.x, res.loc.y) store_collar_data(payload['dev_id'], res) 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()