Skip to content
Permalink
3f773c09fb
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
60 lines (51 sloc) 1.96 KB
import paho.mqtt.client as mqtt
import json
import sqlite3 as sql
from datetime import date, datetime
import pandas as pd
# Define callback functions
def on_connect(client, userdata, flags, rc):
if rc == 0:
print("Connected to MQTT broker")
client.subscribe("client/med/#") # Subscribe to the desired topic
else:
print(f"Connection failed with code {rc}")
def on_message(client, userdata, msg):
print(f"{msg.payload.decode()}")
# Check if the received message matches the one you want to respond to
if msg.topic == "client/med/alert2":
con = sql.connect("med_data1.1.db") # name of the database
cur = con .cursor() # connect to database file
#cur.execute ("CREATE TABLE MED (DATE VARCHAR(20), TIME VARCHAR(20),MED char(25));")
# Prompt the user for a response
response = input("Enter your response: ")
day = date.today()
time = datetime.now()
cur.execute("INSERT INTO MED VALUES(?,?,?);",(day,time,response))
con.commit() #commit the current transcation
cur.close() # close database
data = pd.read_sql("SELECT * FROM MED", con)
data.to_csv("data.csv")
con.close()
# Save the message and response to a file for persistence
#with open('messages_and_responses.json', 'a') as file:
#data = { "response": response}
#json.dump(data, file)
#file.write('\n') # Add a newline for readability or separation
# Create an MQTT client
client = mqtt.Client()
# Set callback functions
client.on_connect = on_connect
client.on_message = on_message
# Connect to the broker
client.connect("broker.hivemq.com", 1883)
# Start the MQTT loop to listen for messages
client.loop_start()
# Keep the script running
try:
while True:
pass
except KeyboardInterrupt:
print("Disconnecting from MQTT broker")
client.disconnect()
client.loop_stop()