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-Group3/ChenYiyan_README
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
91 lines (78 sloc)
2.76 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 sqlite3 | |
import time | |
import logging | |
# Configure logging | |
logging.basicConfig(level=logging.INFO) | |
# MQTT Broker address and port | |
broker_address = 'broker.emqx.io' | |
port = 1883 | |
# Topic name | |
topic = '/sensor_data/' | |
# Initialize SQLite database connection | |
db_file = 'stage_lighting.db' | |
def init_db(): | |
conn = sqlite3.connect(db_file) | |
cursor = conn.cursor() | |
cursor.execute(''' | |
CREATE TABLE IF NOT EXISTS LightingData ( | |
id INTEGER PRIMARY KEY AUTOINCREMENT, | |
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP, | |
illuminance INTEGER, | |
motion_detected BOOLEAN, | |
light_intensity INTEGER | |
) | |
''') | |
conn.commit() | |
conn.close() | |
init_db() | |
# Connect to the MQTT Broker | |
def connect() -> mqtt.Client: | |
def on_connect(client, userdata, flags, rc): | |
if rc == 0: | |
logging.info('MQTT connected') | |
client.subscribe(topic) | |
else: | |
logging.error(f'Connection failed with code {rc}') | |
client = mqtt.Client(f'python-mqtt-{random.randint(0, 1000)}') | |
client.on_connect = on_connect | |
client.connect(broker_address, port) | |
return client | |
# Subscribe and process messages | |
def subscribe(client: mqtt.Client): | |
def on_message(client, userdata, msg): | |
try: | |
data = msg.payload.decode().split(',') | |
if len(data) == 3: | |
illuminance = int(data[0]) | |
motion_detected = data[1].strip().lower() == 'true' | |
light_intensity = calculate_light_intensity(illuminance, motion_detected) | |
conn = sqlite3.connect(db_file) | |
cursor = conn.cursor() | |
cursor.execute(''' | |
INSERT INTO LightingData (illuminance, motion_detected, light_intensity) | |
VALUES (?, ?, ?) | |
''', (illuminance, motion_detected, light_intensity)) | |
conn.commit() | |
conn.close() | |
logging.info(f'Received data: illuminance={illuminance}, motion_detected={motion_detected}, light_intensity={light_intensity}') | |
else: | |
logging.error('Invalid message format') | |
except ValueError as e: | |
logging.error(f'Error in message conversion: {str(e)}') | |
except sqlite3.Error as e: | |
logging.error(f'SQLite error: {str(e)}') | |
client.on_message = on_message | |
def calculate_light_intensity(illuminance, motion_detected): | |
if motion_detected: | |
if illuminance < 30: | |
return 100 # High intensity | |
elif illuminance < 70: | |
return 50 # Medium intensity | |
else: | |
return 25 # Low intensity | |
else: | |
return 0 # Turn off lights | |
client = connect() | |
subscribe(client) | |
client.loop_forever() |