-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathintegrated_server.py
More file actions
1548 lines (1296 loc) · 55.6 KB
/
integrated_server.py
File metadata and controls
1548 lines (1296 loc) · 55.6 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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
MASH IoT Device - Integrated Server
Combines sensor reading, actuator control, and HTTP API
"""
from flask import Flask, jsonify, request
from flask_cors import CORS
import os
import time
import threading
from datetime import datetime
from collections import deque
import logging
import os
import serial
import socket
import subprocess
from dotenv import load_dotenv
from rule_based_controller import RuleBasedController
from data_logger import DataLogger
from src.utils.bluetooth_manager import BluetoothManager
from src.utils.bluetooth_tethering import BluetoothTethering
from src.utils.bluetooth_setup import setup_bluetooth
from src.utils.bluetooth_agent import start_bluetooth_agent, stop_bluetooth_agent, get_agent_manager
from src.utils.ble_advertiser import start_ble_advertising
from src.utils.bluetooth_serial_wifi import start_bluetooth_serial_wifi_provisioning
from src.utils.config import Config
from src.backend_client import BackendClient
from src.firebase_client import FirebaseClient
from src.discovery.mdns_service import MDNSService
try:
import RPi.GPIO as GPIO
GPIO_AVAILABLE = True
except ImportError:
GPIO_AVAILABLE = False
print("WARNING: RPi.GPIO not available, running in simulation mode")
def check_internet_connectivity():
"""Check if device has internet connectivity"""
try:
# Try to connect to Google DNS
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(2)
s.connect(("8.8.8.8", 53))
s.close()
return True
except:
return False
def get_ip_address():
"""Get the device's IP address"""
try:
# Create a socket connection to an external server
# This doesn't actually establish a connection, but gets the local IP
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
ip_address = s.getsockname()[0]
s.close()
return ip_address
except Exception as e:
logging.error(f"Error getting IP address: {e}")
return "127.0.0.1" # Return localhost as fallback
def get_mac_address():
"""Get the device's MAC address"""
try:
# Try to get the MAC address of the primary interface
import uuid
# Get the hex representation of the MAC address
mac = ':'.join(['{:02x}'.format((uuid.getnode() >> elements) & 0xff)
for elements in range(0, 8*6, 8)][::-1])
return mac
except Exception as e:
logging.error(f"Error getting MAC address: {e}")
return "" # Return empty string as fallback
# ========== Load Environment Variables ==========
load_dotenv()
# ========== Load Configuration ==========
config = Config(config_file='config/device_config.yaml')
# Validate configuration
if not config.validate():
print("ERROR: Invalid configuration. Please check config/device_config.yaml")
exit(1)
# ========== Configuration Values ==========
# Device Identity
DEVICE_ID = config.get_nested('device', 'id', default='MASH-A1-CAL25-D5A91F')
DEVICE_NAME = config.get_nested('device', 'name', default='MASH Chamber #1')
# Serial Configuration (Arduino)
SERIAL_PORT = config.get_nested('sensors', 'serial', 'port', default='/dev/ttyUSB0')
SERIAL_BAUD = config.get_nested('sensors', 'serial', 'baud_rate', default=9600)
# GPIO Pin Configuration (BCM numbering)
gpio_config = config.get_gpio_config()
RELAY_BLOWER_FAN = gpio_config['relays']['blower_fan']
RELAY_EXHAUST_FAN = gpio_config['relays']['exhaust_fan']
RELAY_HUMIDIFIER = gpio_config['relays']['humidifier']
RELAY_LED_LIGHTS = gpio_config['relays']['led_lights']
# Data collection
WINDOW_SIZE = 30
READING_HISTORY = deque(maxlen=WINDOW_SIZE)
# ========== Logging Setup ==========
log_level = config.get('log_level', 'INFO')
logging.basicConfig(
level=getattr(logging, log_level.upper()),
format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
# ========== Flask App ==========
app = Flask(__name__)
CORS(app)
# ========== Global State ==========
ser = None
current_mode = 's' # 's' = Spawning, 'f' = Fruiting
# Current sensor data
sensor_data = {
'co2': 0,
'temperature': 0.0,
'humidity': 0.0,
'mode': 's',
'alert': False,
'timestamp': datetime.now().isoformat()
}
# Actuator states
actuator_states = {
'blower_fan': False,
'exhaust_fan': False,
'humidifier': False,
'led_lights': False
}
# Lock for thread-safe access
data_lock = threading.Lock()
# ========== GPIO/Actuator Control ==========
class ActuatorController:
"""Controls relay-connected actuators"""
def __init__(self):
self.simulation_mode = not GPIO_AVAILABLE
if not self.simulation_mode:
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(RELAY_BLOWER_FAN, GPIO.OUT)
GPIO.setup(RELAY_EXHAUST_FAN, GPIO.OUT)
GPIO.setup(RELAY_HUMIDIFIER, GPIO.OUT)
GPIO.setup(RELAY_LED_LIGHTS, GPIO.OUT)
# Turn all off initially (relays are active LOW: HIGH = OFF)
self._set_all_off()
logger.info("GPIO initialized - actuators ready")
else:
logger.info("WARNING: Running in SIMULATION mode - no GPIO control")
def _set_all_off(self):
"""Turn off all actuators (active LOW relays: HIGH = OFF)"""
GPIO.output(RELAY_BLOWER_FAN, GPIO.HIGH)
GPIO.output(RELAY_EXHAUST_FAN, GPIO.HIGH)
GPIO.output(RELAY_HUMIDIFIER, GPIO.HIGH)
GPIO.output(RELAY_LED_LIGHTS, GPIO.HIGH)
def set_actuator(self, actuator_name, state):
"""Control a specific actuator"""
pin_map = {
'blower_fan': RELAY_BLOWER_FAN,
'exhaust_fan': RELAY_EXHAUST_FAN,
'humidifier': RELAY_HUMIDIFIER,
'led_lights': RELAY_LED_LIGHTS
}
if actuator_name not in pin_map:
logger.error(f"Unknown actuator: {actuator_name}")
return False
pin = pin_map[actuator_name]
with data_lock:
actuator_states[actuator_name] = state
if not self.simulation_mode:
# Active LOW relays: LOW = ON, HIGH = OFF
GPIO.output(pin, GPIO.LOW if state else GPIO.HIGH)
logger.info(f"Actuator {actuator_name}: {'ON' if state else 'OFF'}")
return True
def cleanup(self):
"""Cleanup GPIO resources"""
if not self.simulation_mode:
self._set_all_off()
GPIO.cleanup()
logger.info("GPIO cleanup complete")
# Initialize actuator controller
actuator_controller = ActuatorController()
# Initialize rule-based automation controller
automation_controller = RuleBasedController()
# Initialize data logger
data_logger = DataLogger()
# Initialize Bluetooth manager and tethering
bt_config = config.get_bluetooth_config()
bluetooth_device_name = bt_config['device_name']
logger.info(f"Initializing Bluetooth with device name: {bluetooth_device_name}")
bluetooth_manager = BluetoothManager(device_name=bluetooth_device_name)
bluetooth_tethering = BluetoothTethering(bluetooth_manager)
# Initialize Backend Client
backend_client = None
try:
# Get device ID from config file
device_id = config.get_nested('device', 'id')
if not device_id:
device_id = os.getenv('DEVICE_ID', 'MASH-A1-CAL25-D5A91F')
# Debug logging
logger.info(f"Device ID from config: '{device_id}'")
logger.info(f"DEVICE_ID variable: '{DEVICE_ID}'")
backend_api_url = os.getenv('BACKEND_API_URL', config.get('backend_api_url', 'https://mash-backend-production.up.railway.app/api/v1'))
backend_api_key = os.getenv('BACKEND_API_KEY', config.get('backend_api_key', ''))
backend_timeout = int(os.getenv('BACKEND_TIMEOUT', config.get('backend_timeout', 30)))
backend_client = BackendClient(
api_url=backend_api_url,
device_id=device_id, # Use the device ID from config
api_key=backend_api_key if backend_api_key else None,
timeout=backend_timeout,
mock_mode=not backend_api_url.startswith('http')
)
logger.info(f"Backend client initialized: {backend_api_url}")
logger.info(f"Using device ID: {device_id}")
except Exception as e:
logger.error(f"Failed to initialize backend client: {e}")
# Initialize Firebase Client
firebase_client = None
try:
firebase_project_id = os.getenv('FIREBASE_PROJECT_ID', config.get('firebase_project_id', ''))
firebase_database_url = os.getenv('FIREBASE_DATABASE_URL', config.get('firebase_database_url', ''))
firebase_client_email = os.getenv('FIREBASE_CLIENT_EMAIL', config.get('firebase_client_email', ''))
firebase_private_key = os.getenv('FIREBASE_PRIVATE_KEY', config.get('firebase_private_key', ''))
if firebase_project_id and firebase_database_url:
firebase_client = FirebaseClient(
project_id=firebase_project_id,
database_url=firebase_database_url,
service_account_email=firebase_client_email,
private_key=firebase_private_key,
device_id=DEVICE_ID,
mock_mode=not firebase_database_url.startswith('http')
)
logger.info(f"✅ Firebase client initialized: {firebase_database_url}")
else:
logger.warning("⚠️ Firebase credentials not found, running without Firebase")
except Exception as e:
logger.error(f"❌ Failed to initialize Firebase client: {e}")
# ========== Serial Communication ==========
def find_arduino_port():
"""Auto-detect Arduino serial port"""
import serial.tools.list_ports
ports = serial.tools.list_ports.comports()
# Try common Arduino ports first
common_ports = ['/dev/ttyACM0', '/dev/ttyUSB0', '/dev/ttyACM1', '/dev/ttyUSB1']
for port_name in common_ports:
for port in ports:
if port.device == port_name:
logger.info(f"Found potential Arduino port: {port.device} - {port.description}")
return port.device
# If not found in common ports, try any USB serial device
for port in ports:
if 'USB' in port.description or 'Arduino' in port.description:
logger.info(f"Found USB serial device: {port.device} - {port.description}")
return port.device
return None
def init_serial():
"""Initialize serial connection to Arduino"""
global ser
# Try configured port first
port_to_try = SERIAL_PORT
try:
logger.info(f"Attempting to connect to Arduino on {port_to_try}...")
ser = serial.Serial(port_to_try, SERIAL_BAUD, timeout=1)
time.sleep(2) # Wait for Arduino to reset
logger.info(f"Serial connection established on {port_to_try}")
return True
except Exception as e:
logger.warning(f"WARNING: Failed to connect on {port_to_try}: {e}")
# Try auto-detection
logger.info("Attempting to auto-detect Arduino port...")
detected_port = find_arduino_port()
if detected_port and detected_port != port_to_try:
try:
logger.info(f"Trying detected port: {detected_port}...")
ser = serial.Serial(detected_port, SERIAL_BAUD, timeout=1)
time.sleep(2)
logger.info(f"Serial connection established on {detected_port}")
logger.info(f"TIP: Update SERIAL_PORT in config to: {detected_port}")
return True
except Exception as e2:
logger.error(f"ERROR: Failed to connect on detected port: {e2}")
logger.error("ERROR: Could not establish serial connection to Arduino")
logger.info("TIP: Run 'python3 check_serial.py' to diagnose serial port issues")
return False
def parse_sensor_line(line):
"""Parse sensor data from Arduino
Format 1: SENSOR,timestamp,co2,temperature,humidity,mode,alert
Format 2: T:23.5,H:65.2,C:450.0,M:f (simpler format)
"""
try:
# Try format 1: SENSOR,timestamp,co2,temperature,humidity,mode,alert
parts = line.split(',')
if len(parts) >= 7 and parts[0] == 'SENSOR':
return {
'co2': int(parts[2]),
'temperature': float(parts[3]),
'humidity': float(parts[4]),
'mode': 's' if parts[5] == 'SPAWNING' else 'f',
'alert': parts[6] == '1',
'timestamp': datetime.now().isoformat()
}
# Try format 2: T:23.5,H:65.2,C:450.0,M:f
if 'T:' in line and 'H:' in line and 'C:' in line:
data = {}
for part in parts:
if ':' in part:
key, value = part.split(':')
if key == 'T':
data['temperature'] = float(value)
elif key == 'H':
data['humidity'] = float(value)
elif key == 'C':
data['co2'] = int(float(value))
elif key == 'M':
data['mode'] = value.strip()
if 'temperature' in data and 'humidity' in data and 'co2' in data:
data['alert'] = False
data['timestamp'] = datetime.now().isoformat()
if 'mode' not in data:
data['mode'] = 's'
logger.info(f"Parsed sensor data: T={data['temperature']}°C, H={data['humidity']}%, CO2={data['co2']}ppm, Mode={data['mode']}")
return data
except Exception as e:
logger.error(f"Error parsing sensor data: {e}")
return None
def read_sensor_data():
"""Continuously read sensor data from Arduino"""
global sensor_data, current_mode
logger.info("Starting sensor data reader...")
while True:
try:
if ser and ser.in_waiting > 0:
line = ser.readline().decode('utf-8').strip()
# Parse sensor data - Format 1: SENSOR,timestamp,co2,temperature,humidity,mode,alert
if line.startswith('SENSOR,'):
data = parse_sensor_line(line)
if data:
with data_lock:
sensor_data.update(data)
current_mode = data['mode']
# Add to history
READING_HISTORY.append(data)
# Log to database
data_logger.log_sensor_reading(data)
# Sync to Backend and Firebase
sync_sensor_data(data)
logger.debug(f"Sensor data: CO2={data['co2']}ppm, T={data['temperature']}°C, H={data['humidity']}%")
# Parse sensor data - Format 2: T:25.5,H:85.2,C:1200
elif 'T:' in line and 'H:' in line and 'C:' in line:
data = parse_sensor_line(line)
if data:
with data_lock:
sensor_data.update(data)
# Use stored mode if not in data
if 'mode' in data:
current_mode = data['mode']
else:
data['mode'] = current_mode
# Add to history
READING_HISTORY.append(data)
# Log to database
data_logger.log_sensor_reading(data)
# Sync to Backend and Firebase
sync_sensor_data(data)
logger.debug(f"Sensor data: CO2={data['co2']}ppm, T={data['temperature']}°C, H={data['humidity']}%")
# Handle mode changes
elif line.startswith('MODE,'):
mode_name = line.split(',')[1]
with data_lock:
current_mode = 's' if mode_name == 'SPAWNING' else 'f'
sensor_data['mode'] = current_mode
logger.info(f"Mode changed to {mode_name}")
# Handle alerts
elif line.startswith('ALERT,'):
logger.warning(f"ALERT: {line}")
except Exception as e:
logger.error(f"ERROR: Error reading sensor data: {e}")
time.sleep(0.1)
# ========== Data Syncing Functions ==========
def sync_sensor_data(data):
"""Sync sensor data to Backend and Firebase"""
try:
# Check internet connectivity first
if not check_internet_connectivity():
logger.debug("No internet connection - skipping sensor data sync")
return
# Check if device is active before sending data
if backend_client and not backend_client.is_device_active():
logger.debug("Device is turned OFF - skipping sensor data sync")
return
# Sync to Backend
if backend_client:
threading.Thread(
target=lambda: backend_client.send_sensor_data(data),
daemon=True
).start()
# Sync to Firebase
if firebase_client:
threading.Thread(
target=lambda: firebase_client.send_sensor_data(data),
daemon=True
).start()
except Exception as e:
logger.error(f"Error syncing sensor data: {e}")
def sync_device_status(status='ONLINE'):
"""Sync device status to Backend and Firebase
Args:
status: Device status to set (default: 'ONLINE')
"""
try:
# Check internet connectivity first
if not check_internet_connectivity():
logger.debug("No internet connection - skipping device status sync")
return
# Only include fields that are supported by the Prisma schema
# Format the timestamp in a way that's compatible with the backend
# Use UTC time to avoid timezone issues
current_time = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%fZ')
status_data = {
'status': status,
'lastSeen': current_time,
'firmware': '1.0.0',
'ipAddress': get_ip_address(),
'macAddress': get_mac_address()
}
logger.info(f"Using timestamp: {current_time}")
# Sync to Backend
if backend_client:
threading.Thread(
target=lambda: backend_client.update_device_status(status, status_data),
daemon=True
).start()
# Sync to Firebase
if firebase_client:
threading.Thread(
target=lambda: firebase_client.send_device_status(status_data),
daemon=True
).start()
except Exception as e:
logger.error(f"Error syncing device status: {e}")
def mark_device_offline():
"""Mark device as offline in backend"""
try:
logger.info("Marking device as OFFLINE in backend")
# Use a direct call instead of a thread to ensure it completes before shutdown
if backend_client:
current_time = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%fZ')
status_data = {
'status': 'OFFLINE',
'lastSeen': current_time,
'ipAddress': get_ip_address(),
'macAddress': get_mac_address()
}
backend_client.update_device_status('OFFLINE', status_data)
logger.info("Device marked as OFFLINE successfully")
except Exception as e:
logger.error(f"Error marking device as offline: {e}")
def sync_actuator_states():
"""Sync actuator states to Backend and Firebase"""
try:
# Sync to Firebase
if firebase_client:
threading.Thread(
target=lambda: firebase_client.send_actuator_states(actuator_states.copy()),
daemon=True
).start()
except Exception as e:
logger.error(f"Error syncing actuator states: {e}")
def send_command_to_arduino(command):
"""Send command to Arduino via serial"""
try:
if ser:
ser.write(f"{command}\n".encode('utf-8'))
logger.info(f"Sent command to Arduino: {command}")
return True
return False
except Exception as e:
logger.error(f"ERROR: Failed to send command: {e}")
return False
def automation_loop():
"""Rule-based automation loop - runs every 10 seconds"""
logger.info("Starting rule-based automation loop...")
while True:
try:
if automation_controller.is_enabled():
with data_lock:
current_sensor_data = sensor_data.copy()
current_actuator_states = actuator_states.copy()
# Get automation decision
decision = automation_controller.analyze_and_decide(
current_sensor_data,
current_actuator_states
)
# Execute recommended actions
if decision.get('actions'):
for actuator, state in decision['actions'].items():
if actuator in actuator_states:
actuator_controller.set_actuator(actuator, state)
logger.info(f"Automation Action: {actuator} -> {'ON' if state else 'OFF'}")
# Log actuator changes
data_logger.log_actuator_change(actuator_states, current_sensor_data.get('mode', 's'), 'automation')
# Sync actuator states
sync_actuator_states()
# Log reasoning
if decision.get('reasoning'):
for reason in decision['reasoning']:
logger.info(f" Reasoning: {reason}")
# Log automation decision
data_logger.log_automation_decision(decision)
except Exception as e:
logger.error(f"ERROR: Error in automation loop: {e}")
time.sleep(10) # Run every 10 seconds
# ========== API Endpoints ==========
@app.route('/api/status', methods=['GET'])
def get_status():
"""Get device status"""
return jsonify({
'success': True,
'data': {
'deviceId': DEVICE_ID,
'deviceName': DEVICE_NAME,
'status': 'online',
'serialConnected': ser is not None and ser.is_open if ser else False,
'timestamp': datetime.now().isoformat()
}
})
@app.route('/api/sensor/current', methods=['GET'])
def get_current_sensor_data():
"""Get current sensor readings"""
with data_lock:
return jsonify({
'success': True,
'data': {
**sensor_data,
'actuators': actuator_states
}
})
@app.route('/api/sensor/history', methods=['GET'])
def get_sensor_history():
"""Get sensor reading history"""
limit = request.args.get('limit', 30, type=int)
history_list = list(READING_HISTORY)[-limit:]
return jsonify({
'success': True,
'data': {
'readings': history_list,
'count': len(history_list)
}
})
@app.route('/api/mode', methods=['POST'])
def set_mode():
"""Set device mode (Spawning or Fruiting)"""
try:
data = request.get_json()
mode = data.get('mode', '').lower()
if mode not in ['s', 'f', 'spawning', 'fruiting']:
return jsonify({
'success': False,
'error': 'Invalid mode. Use "s"/"spawning" or "f"/"fruiting"'
}), 400
# Normalize mode
mode_char = 's' if mode in ['s', 'spawning'] else 'f'
mode_name = 'Spawning' if mode_char == 's' else 'Fruiting'
# Send mode command to Arduino
if send_command_to_arduino(mode_char):
with data_lock:
sensor_data['mode'] = mode_char
logger.info(f"Mode set to {mode_name}")
return jsonify({
'success': True,
'data': {
'mode': mode_char,
'modeName': mode_name
}
})
return jsonify({
'success': False,
'error': 'Failed to send command to Arduino'
}), 500
except Exception as e:
logger.error(f"ERROR: Error setting mode: {e}")
return jsonify({
'success': False,
'error': str(e)
}), 500
@app.route('/api/actuator', methods=['POST'])
def control_actuator():
"""Control actuator (relay)"""
try:
data = request.get_json()
actuator = data.get('actuator', '')
state = data.get('state', False)
valid_actuators = ['blower_fan', 'exhaust_fan', 'humidifier', 'led_lights']
if actuator not in valid_actuators:
return jsonify({
'success': False,
'error': f'Invalid actuator. Valid options: {", ".join(valid_actuators)}'
}), 400
# Control the actuator
if actuator_controller.set_actuator(actuator, state):
return jsonify({
'success': True,
'data': {
'actuator': actuator,
'state': state
}
})
return jsonify({
'success': False,
'error': 'Failed to control actuator'
}), 500
except Exception as e:
logger.error(f"ERROR: Error controlling actuator: {e}")
return jsonify({
'success': False,
'error': str(e)
}), 500
@app.route('/api/actuators', methods=['GET'])
def get_actuator_states():
"""Get all actuator states"""
with data_lock:
return jsonify({
'success': True,
'data': actuator_states
})
@app.route('/api/automation/status', methods=['GET'])
def get_automation_status():
"""Get rule-based automation status"""
try:
status = automation_controller.get_status()
return jsonify({
'success': True,
'data': status
})
except Exception as e:
logger.error(f"ERROR: Error getting automation status: {e}")
return jsonify({
'success': False,
'error': str(e)
}), 500
@app.route('/api/automation/enable', methods=['POST'])
def enable_automation():
"""Enable rule-based automation"""
try:
automation_controller.enable()
return jsonify({
'success': True,
'data': {
'enabled': True,
'message': 'Rule-based automation enabled'
}
})
except Exception as e:
logger.error(f"ERROR: Error enabling automation: {e}")
return jsonify({
'success': False,
'error': str(e)
}), 500
@app.route('/api/automation/disable', methods=['POST'])
def disable_automation():
"""Disable rule-based automation"""
try:
automation_controller.disable()
return jsonify({
'success': True,
'data': {
'enabled': False,
'message': 'Rule-based automation disabled'
}
})
except Exception as e:
logger.error(f"ERROR: Error disabling automation: {e}")
return jsonify({
'success': False,
'error': str(e)
}), 500
@app.route('/api/automation/history', methods=['GET'])
def get_automation_history():
"""Get automation decision history"""
try:
limit = request.args.get('limit', 10, type=int)
history = automation_controller.get_decision_history(limit)
return jsonify({
'success': True,
'data': {
'history': history,
'count': len(history)
}
})
except Exception as e:
logger.error(f"ERROR: Error getting automation history: {e}")
return jsonify({
'success': False,
'error': str(e)
}), 500
@app.route('/api/logs/sensors', methods=['GET'])
def get_sensor_logs():
"""Get sensor reading logs"""
try:
hours = request.args.get('hours', 24, type=int)
limit = request.args.get('limit', 1000, type=int)
readings = data_logger.get_sensor_readings(hours=hours, limit=limit)
return jsonify({
'success': True,
'data': {
'readings': readings,
'count': len(readings)
}
})
except Exception as e:
logger.error(f"ERROR: Error getting sensor logs: {e}")
return jsonify({
'success': False,
'error': str(e)
}), 500
@app.route('/api/logs/actuators', methods=['GET'])
def get_actuator_logs():
"""Get actuator state history"""
try:
hours = request.args.get('hours', 24, type=int)
limit = request.args.get('limit', 500, type=int)
history = data_logger.get_actuator_history(hours=hours, limit=limit)
return jsonify({
'success': True,
'data': {
'history': history,
'count': len(history)
}
})
except Exception as e:
logger.error(f"ERROR: Error getting actuator logs: {e}")
return jsonify({
'success': False,
'error': str(e)
}), 500
@app.route('/api/logs/ai-decisions', methods=['GET'])
def get_ai_decision_logs():
"""Get AI decision logs"""
try:
hours = request.args.get('hours', 24, type=int)
limit = request.args.get('limit', 100, type=int)
decisions = data_logger.get_ai_decisions(hours=hours, limit=limit)
return jsonify({
'success': True,
'data': {
'decisions': decisions,
'count': len(decisions)
}
})
except Exception as e:
logger.error(f"ERROR: Error getting AI decision logs: {e}")
return jsonify({
'success': False,
'error': str(e)
}), 500
@app.route('/api/logs/alerts', methods=['GET'])
def get_alert_logs():
"""Get alert logs"""
try:
hours = request.args.get('hours', 24, type=int)
limit = request.args.get('limit', 100, type=int)
alerts = data_logger.get_alerts(hours=hours, limit=limit)
return jsonify({
'success': True,
'data': {
'alerts': alerts,
'count': len(alerts)
}
})
except Exception as e:
logger.error(f"ERROR: Error getting alert logs: {e}")
return jsonify({
'success': False,
'error': str(e)
}), 500
@app.route('/api/logs/statistics', methods=['GET'])
def get_statistics():
"""Get statistics"""
try:
hours = request.args.get('hours', 24, type=int)
stats = data_logger.get_statistics(hours=hours)
return jsonify({
'success': True,
'data': stats
})
except Exception as e:
logger.error(f"ERROR: Error getting statistics: {e}")
return jsonify({
'success': False,
'error': str(e)
}), 500
@app.route('/api/bluetooth/status', methods=['GET'])
def get_bluetooth_status():
"""Get Bluetooth status"""
try:
status = bluetooth_manager.get_status()
tethering_status = bluetooth_tethering.get_tethering_status()
return jsonify({
'success': True,
'data': {
'bluetooth': status,
'tethering': tethering_status
}
})
except Exception as e:
logger.error(f"Error getting Bluetooth status: {e}")
return jsonify({
'success': False,
'error': str(e)
}), 500
# ========== WiFi Provisioning API ==========
@app.route('/api/wifi/scan', methods=['GET'])
def wifi_scan():
"""Scan for available WiFi networks"""
try:
from src.utils.wifi_provisioning import get_wifi_provisioning
wifi = get_wifi_provisioning()
networks = wifi.scan_wifi_networks()
logger.info(f"WiFi scan completed: {len(networks)} networks found")
return jsonify({
'success': True,
'data': {
'networks': networks,
'count': len(networks)
}
})
except Exception as e:
logger.error(f"ERROR: WiFi scan failed: {e}")
return jsonify({
'success': False,
'error': str(e)