Skip to content
Permalink
main
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
import paho.mqtt.client as mqtt
import json, os
from datetime import date, datetime
import time
import sys
import sqlite3 as sql
""" Callback function for connection """
def on_connect(client, userdata, flags,rc):
if rc == 0:
client.connected_flag = True
print("connected OK Returned code=", rc)
client.subscribe("GUG/Topics/#")
print("rc")
else:
print("Bad connection Returned code=",rc)
def on_disconnect(client, userdata):
print("client disconnected ok")
def on_subscribe(client, userdata, mid, qos):
print("in on subscribe callback result " + str(mid))
"""Callback function for messages recieved"""
def on_message(client, userdata, msg, properties=None): #https://cedalo.com/blog/configuring-paho-mqtt-python-client-with-examples/
con=sql.connect("fitnessInfo.db") #establish name of database
cur=con.cursor() #connects to database file
data = str(msg.payload)
print(data)
try:
cur.execute("CREATE TABLE IF NOT EXISTS TestTopics(StepsTaken NUMBER(10.6), CaloriesBurned NUMBER(10,6), HeartRate NUMBER(10,6));")
except:
print("Something went wrong with creating the sql table")
cur.execute("INSERT INTO TestTopics VALUES (?,?,?,?);",(data("StepsTaken"), data("CaloriesBurned"), data("HeartRate"))) #puts subscribed info into database
print(str(msg.payload))
con.commit() #commit the current transaction
cur.close() #closes database
con.close()
client = mqtt.Client()
client.connected_flag = False
client.on_connect = on_connect
client.connect("broker.hivemq.com", 1883)
client.on_message = on_message
client.disconnect = on_disconnect
topic = "GUG/Sensors/1"
print("connecting to broker", "broker.hivemq.com")
try:
client.connect("broker.hivemq.com")
except:
print("can't connect")
sys.exit(1)
client.loop_start()
while not client.connected_flag:
print("in wait loop")
time.sleep(1)
ret = client.subscribe(topic,0)
print("subscribed returned", ret)
time.sleep(30)
client.disconnect(client, "None")
client.loop_stop()