-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSensorShare_Receiver.py
More file actions
202 lines (168 loc) · 7.44 KB
/
Copy pathSensorShare_Receiver.py
File metadata and controls
202 lines (168 loc) · 7.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
#!/usr/bin/env python3
"""
SensorShare - MQTT Sensor Receiver
Runs on another Raspberry Pi to receive and display sensor data
"""
import paho.mqtt.client as mqtt
import json
import time
from datetime import datetime
from collections import defaultdict
# MQTT Configuration
MQTT_BROKER = "192.168.0.202" # Rotator-PI's IP address
MQTT_PORT = 1883
BASE_TOPIC = "sensors/rotator"
class SensorDataReceiver:
def __init__(self, broker, port):
self.client = mqtt.Client()
self.broker = broker
self.port = port
self.connected = False
self.sensor_data = defaultdict(dict)
self.last_update = defaultdict(str)
# Set up callbacks
self.client.on_connect = self.on_connect
self.client.on_disconnect = self.on_disconnect
self.client.on_message = self.on_message
def on_connect(self, client, userdata, flags, rc):
if rc == 0:
print(f"✅ Connected to MQTT broker at {self.broker}:{self.port}")
self.connected = True
# Subscribe to all sensor topics
client.subscribe(f"{BASE_TOPIC}/light/#") # All light sensors
client.subscribe(f"{BASE_TOPIC}/uvb/#") # All UVB sensors
client.subscribe(f"{BASE_TOPIC}/summary") # Summary data
print(f"📡 Subscribed to topics:")
print(f" - {BASE_TOPIC}/light/# (light sensors)")
print(f" - {BASE_TOPIC}/uvb/# (UVB sensors)")
print(f" - {BASE_TOPIC}/summary (summary data)")
else:
print(f"❌ Failed to connect to MQTT broker, return code: {rc}")
def on_disconnect(self, client, userdata, rc):
print("🔌 Disconnected from MQTT broker")
self.connected = False
def on_message(self, client, userdata, msg):
"""Handle incoming MQTT messages"""
try:
topic = msg.topic
payload = msg.payload.decode('utf-8')
print(f"\n📨 Received message on topic: {topic}")
# Parse JSON data
data = json.loads(payload)
if topic.endswith('/summary'):
# Summary data
print("📊 Summary data received:")
for sensor_id, value in data['sensors'].items():
print(f" {sensor_id}: {value}")
print(f" Total sensors: {data['sensor_count']}")
print(f" Timestamp: {data['timestamp']}")
else:
# Individual sensor data
sensor_type = topic.split('/')[-2] # light or uvb
sensor_id = topic.split('/')[-1] # outside_dome or inside_dome
full_sensor_id = f"{sensor_type}_{sensor_id}"
self.sensor_data[full_sensor_id] = data
self.last_update[full_sensor_id] = datetime.now().strftime("%H:%M:%S")
value = data.get('value', 'N/A')
unit = data.get('unit', 'N/A')
print(f"💡 {full_sensor_id}: {value} {unit}")
# Display current status
self.display_status()
except json.JSONDecodeError as e:
print(f"❌ Error parsing JSON: {e}")
except Exception as e:
print(f"❌ Error processing message: {e}")
def display_status(self):
"""Display current sensor status"""
print("\n" + "="*60)
print("📊 CURRENT SENSOR STATUS")
print("="*60)
if not self.sensor_data:
print("⏳ Waiting for sensor data...")
return
# Group sensors by type
light_sensors = {k: v for k, v in self.sensor_data.items() if k.startswith('light_')}
uvb_sensors = {k: v for k, v in self.sensor_data.items() if k.startswith('uvb_')}
# Display light sensors
if light_sensors:
print("💡 LIGHT SENSORS:")
print("-" * 30)
for sensor_id, data in light_sensors.items():
value = data.get('value', 'N/A')
unit = data.get('unit', 'N/A')
timestamp = data.get('timestamp', 'N/A')
last_update = self.last_update.get(sensor_id, 'N/A')
location = "Outside Dome" if "outside" in sensor_id else "Inside Dome"
print(f"📍 {location}")
print(f" 💡 Light Level: {value} {unit}")
print(f" 🕐 Last Update: {last_update}")
print(f" 📅 Timestamp: {timestamp}")
print()
# Display UVB sensors
if uvb_sensors:
print("☀️ UVB SENSORS:")
print("-" * 30)
for sensor_id, data in uvb_sensors.items():
value = data.get('value', 'N/A')
unit = data.get('unit', 'N/A')
timestamp = data.get('timestamp', 'N/A')
last_update = self.last_update.get(sensor_id, 'N/A')
location = "Outside Dome" if "outside" in sensor_id else "Inside Dome"
status = "✅ Working" if value != 'N/A' and value != 0 else "⚠️ No reading"
print(f"📍 {location} - {status}")
print(f" ☀️ UVB Level: {value} {unit}")
print(f" 🕐 Last Update: {last_update}")
print(f" 📅 Timestamp: {timestamp}")
print()
# Display summary
total_sensors = len(self.sensor_data)
working_sensors = sum(1 for data in self.sensor_data.values()
if data.get('value') not in ['N/A', None])
print("📈 SUMMARY:")
print("-" * 30)
print(f" Total sensors detected: {total_sensors}")
print(f" Working sensors: {working_sensors}")
print(f" Light sensors: {len(light_sensors)}")
print(f" UVB sensors: {len(uvb_sensors)}")
print("="*60)
def connect(self):
"""Connect to MQTT broker"""
try:
self.client.connect(self.broker, self.port, 60)
self.client.loop_start()
except Exception as e:
print(f"❌ Error connecting to MQTT broker: {e}")
def disconnect(self):
"""Disconnect from MQTT broker"""
self.client.loop_stop()
self.client.disconnect()
def main():
print("🚀 Starting SensorShare MQTT Receiver...")
print(f"📡 Connecting to Rotator-PI at {MQTT_BROKER}:{MQTT_PORT}")
print("🎯 This receiver will display data from:")
print(" - Light sensors (inside & outside dome)")
print(" - UVB sensors (inside & outside dome)")
print(" - Summary data from all sensors")
# Initialize receiver
receiver = SensorDataReceiver(MQTT_BROKER, MQTT_PORT)
receiver.connect()
# Wait for connection
time.sleep(2)
if not receiver.connected:
print("❌ Could not connect to MQTT broker. Exiting.")
return
print("\n🎯 Listening for sensor data...")
print("Press Ctrl+C to stop")
try:
while True:
# Keep the program running
time.sleep(1)
except KeyboardInterrupt:
print("\n🛑 Stopping SensorShare Receiver...")
except Exception as e:
print(f"❌ Error in main loop: {e}")
finally:
receiver.disconnect()
print("👋 SensorShare Receiver stopped")
if __name__ == "__main__":
main()