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
import sqlite3
from datetime import datetime
# Function to determine health status based on parameters
def send_alert(battery_percentage):
if battery_percentage < 20:
return "Alert: Battery level is below 20%!"
# Function to create SQLite3 table
def create_table():
try:
conn = sqlite3.connect('battery_data.db')
cursor = conn.cursor()
# Create table if not exists
cursor.execute('''CREATE TABLE IF NOT EXISTS battery_data
(battery_percentage REAL, alert_message TEXT, time_received TEXT)''')
conn.commit()
cursor.close()
conn.close()
except sqlite3.Error as e:
print("Error creating table:", e)
# Function to insert data into SQLite3 table
def insert_data_into_table(battery_percentage, alert_message, time_received):
try:
conn = sqlite3.connect('battery_data.db')
cursor = conn.cursor()
# Insert data into the table
cursor.execute("INSERT INTO battery_data (battery_percentage, alert_message, time_received) VALUES (?, ?, ?)",
(battery_percentage, alert_message, time_received))
conn.commit()
cursor.close()
conn.close()
except sqlite3.Error as e:
print("Error inserting data into table:", e)
# MQTT callback function for on_connect
def on_connect(client, userdata, flags, rc):
if rc == 0:
client.connected_flag = True
print("Connected successfully! Returned code:", rc)
client.subscribe("project/battery/percentage") # Subscribe to battery percentage topic
else:
print("Bad connection. Returned code:", rc)
# MQTT callback function for on_message
def on_message(client, userdata, msg):
try:
data = json.loads(msg.payload.decode("utf8"))
battery_percentage = data[0]
timestamp = data[1]
alert_message = send_alert(battery_percentage)
print(f"Battery: {battery_percentage}%, {alert_message if alert_message else ''}, Time: {timestamp}")
# Insert data into SQLite3 table
insert_data_into_table(battery_percentage, alert_message, timestamp)
except Exception as e:
print("Error processing message:", e)
# Create SQLite3 table
create_table()
# MQTT client setup
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("broker.hivemq.com", 1883)
client.loop_forever()