Permalink
Cannot retrieve contributors at this time
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?
MQTT-SAPTS-4005/Medical_sub.py
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
60 lines (51 sloc)
1.96 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |