-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSensorShare_Receiver2.py
More file actions
297 lines (250 loc) Β· 11.8 KB
/
Copy pathSensorShare_Receiver2.py
File metadata and controls
297 lines (250 loc) Β· 11.8 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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
#!/usr/bin/env python3
"""
SensorShare - MQTT Sensor Receiver
Runs on another Raspberry Pi to receive and display sensor data
Updated to include force sensor data and day/night mode
"""
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)
self.force_sensor_state = {"timecycle": False, "mode": "night"}
# 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}/timecycle/#") # Force sensor timecycle
client.subscribe(f"{BASE_TOPIC}/mode/#") # Force sensor day/night mode
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}/timecycle/# (force sensor timecycle)")
print(f" - {BASE_TOPIC}/mode/# (force sensor day/night mode)")
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
topic_parts = topic.split('/')
sensor_type = topic_parts[-2] # light, uvb, timecycle, or mode
sensor_id = topic_parts[-1] # outside_dome, inside_dome, or force_a
if sensor_type in ['timecycle', 'mode']:
# Force sensor data
self.force_sensor_state[sensor_type] = data.get('value', 'N/A')
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}")
else:
# Light or UVB sensor data
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 get_motor_status(self):
"""Determine motor status based on current sensor data"""
day_mode = self.force_sensor_state.get('mode', 'night') == 'day'
light_outside = None
# Get outside light level
for sensor_id, data in self.sensor_data.items():
if sensor_id == 'light_outside_dome':
light_outside = data.get('value')
break
if not day_mode:
return "π Night Mode: Motor Inactive"
if light_outside is None:
return "β οΈ Day Mode: No Light Data"
if light_outside > 19000:
return f"βοΈ Day Mode: Motor Clockwise (Light: {light_outside} lux > 19000)"
elif light_outside < 2000:
return f"βοΈ Day Mode: Motor Counter-Clockwise (Light: {light_outside} lux < 2000)"
else:
return f"βοΈ Day Mode: Motor Stopped (Light: {light_outside} lux, 2000-19000 range)"
def display_status(self):
"""Display current sensor status"""
print("\n" + "="*70)
print("π CURRENT SENSOR STATUS")
print("="*70)
# Display force sensor status
timecycle = self.force_sensor_state.get('timecycle', False)
mode = self.force_sensor_state.get('mode', 'night')
mode_icon = "βοΈ" if mode == 'day' else "π"
timecycle_icon = "β
" if timecycle else "β"
print("π FORCE SENSOR STATUS:")
print("-" * 40)
print(f" {mode_icon} Mode: {mode.upper()}")
print(f" {timecycle_icon} TimeCycle: {timecycle}")
print()
# Display motor status
motor_status = self.get_motor_status()
print("π MOTOR STATUS:")
print("-" * 40)
print(f" {motor_status}")
print()
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_')}
force_sensors = {k: v for k, v in self.sensor_data.items() if k.startswith(('timecycle_', 'mode_'))}
# Display light sensors
if light_sensors:
print("π‘ LIGHT SENSORS:")
print("-" * 40)
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"
# Add status indicators for outside light
if "outside" in sensor_id and value != 'N/A':
if value > 19000:
status = "π΄ HIGH (Motor Clockwise)"
elif value < 2000:
status = "π΅ LOW (Motor Counter-Clockwise)"
else:
status = "π‘ MEDIUM (Motor Stopped)"
else:
status = ""
print(f"π {location}")
print(f" π‘ Light Level: {value} {unit} {status}")
print(f" π Last Update: {last_update}")
print(f" π
Timestamp: {timestamp}")
print()
# Display UVB sensors
if uvb_sensors:
print("βοΈ UVB SENSORS:")
print("-" * 40)
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 force sensor data
if force_sensors:
print("π FORCE SENSOR DATA:")
print("-" * 40)
for sensor_id, data in force_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')
sensor_type = "TimeCycle" if "timecycle" in sensor_id else "Day/Night Mode"
print(f"π {sensor_type}")
print(f" π Value: {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("-" * 40)
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(f" Force sensors: {len(force_sensors)}")
print("="*70)
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(" - Force sensor (TimeCycle & Day/Night mode)")
print(" - Motor status based on light levels and mode")
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()