forked from AmpScm/TadoLocal
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathroutes.py
More file actions
1694 lines (1433 loc) · 72.1 KB
/
Copy pathroutes.py
File metadata and controls
1694 lines (1433 loc) · 72.1 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
#
# Copyright 2025 The TadoLocal and AmpScm contributors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""FastAPI route handlers for Tado Local."""
import asyncio
import json
import logging
import os
import sqlite3
import time
from pathlib import Path
from typing import Optional
from fastapi import FastAPI, HTTPException, Depends, status
from fastapi.responses import StreamingResponse, FileResponse
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from fastapi.staticfiles import StaticFiles
from .__version__ import __version__
from .homekit_uuids import enhance_accessory_data
# Configure logging
logger = logging.getLogger(__name__)
# Security
security = HTTPBearer(auto_error=False)
# API key configuration (from environment variable)
# Multiple keys can be specified, space-separated
API_KEYS_RAW = os.environ.get('TADO_API_KEYS', '').strip()
API_KEYS = set(key.strip() for key in API_KEYS_RAW.split() if key.strip()) if API_KEYS_RAW else set()
def get_api_key(credentials: Optional[HTTPAuthorizationCredentials] = Depends(security)) -> Optional[str]:
"""
Validate API key from Authorization header.
If API keys are configured (TADO_API_KEYS environment variable), checks Bearer token.
If no API keys are configured, authentication is disabled (backward compatible).
Returns:
The validated API key, or None if authentication is disabled
Raises:
HTTPException 401 if authentication fails
"""
# If no API keys configured, authentication is disabled
if not API_KEYS:
return None
# API keys are configured, so authentication is required
if not credentials:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Missing authentication credentials",
headers={"WWW-Authenticate": "Bearer"},
)
# Check if the provided token matches any configured key
if credentials.credentials not in API_KEYS:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid authentication credentials",
headers={"WWW-Authenticate": "Bearer"},
)
return credentials.credentials
def create_app():
"""Create and configure the FastAPI application."""
app = FastAPI(
title="Tado Local",
description="Local REST API for Tado devices via HomeKit bridge",
version=__version__
)
# Log authentication status
if API_KEYS:
logger.info(f"API authentication enabled ({len(API_KEYS)} key(s) configured)")
else:
logger.info("API authentication disabled (no TADO_API_KEYS configured)")
# Mount static files
static_dir = Path(__file__).parent / "static"
if static_dir.exists():
app.mount("/static", StaticFiles(directory=str(static_dir)), name="static")
return app
def register_routes(app: FastAPI, get_tado_api):
"""Register all API routes.
Args:
app: FastAPI application instance
get_tado_api: Callable that returns the current TadoLocalAPI instance
"""
@app.get("/", include_in_schema=False)
async def root():
"""Serve the web UI."""
static_dir = Path(__file__).parent / "static"
index_file = static_dir / "index.html"
if index_file.exists():
return FileResponse(index_file, media_type="text/html")
else:
# Fallback to API info if web UI not found
return {
"service": "Tado Local",
"description": "Local REST API for Tado devices via HomeKit bridge",
"version": __version__,
"documentation": "/docs",
"api_info": "/api",
"note": "Web UI not found. Install static/index.html or visit /api for API details"
}
@app.get("/favicon.ico", include_in_schema=False)
async def favicon():
"""Serve favicon."""
static_dir = Path(__file__).parent / "static"
favicon_svg = static_dir / "favicon.svg"
if favicon_svg.exists():
return FileResponse(favicon_svg, media_type="image/svg+xml")
else:
raise HTTPException(status_code=404, detail="Favicon not found")
@app.get("/robots.txt", include_in_schema=False)
async def robots():
"""Serve robots.txt."""
static_dir = Path(__file__).parent / "static"
robots_file = static_dir / "robots.txt"
if robots_file.exists():
return FileResponse(robots_file, media_type="text/plain")
else:
# Fallback if file not found
return "User-agent: *\nDisallow: /\n", {"Content-Type": "text/plain"}
@app.get("/.well-known/{path:path}", include_in_schema=False)
async def well_known(path: str):
"""Stub for .well-known requests to prevent 404 logs."""
# Return 404 but gracefully (no need to log these)
raise HTTPException(status_code=404, detail="Not found")
@app.get("/api", tags=["Info"])
async def api_info(api_key: Optional[str] = Depends(get_api_key)):
"""API root with diagnostics and navigation."""
return {
"service": "Tado Local",
"description": "Local REST API for Tado devices via HomeKit bridge",
"version": __version__,
"documentation": "/docs",
"web_ui": "/",
"endpoints": {
"status": "/status",
"devices": "/devices",
"zones": "/zones",
"thermostats": "/thermostats",
"events": "/events",
"accessories": "/accessories",
"refresh": "/refresh",
"refresh_cloud": "/refresh/cloud"
}
}
@app.get("/status", tags=["Status"])
async def get_status(api_key: Optional[str] = Depends(get_api_key)):
"""Get overall system status."""
tado_api = get_tado_api()
if not tado_api or not tado_api.pairing:
raise HTTPException(status_code=503, detail="Bridge not connected")
try:
# Test connection
await tado_api.pairing.list_accessories_and_characteristics()
devices = tado_api.state_manager.get_all_devices()
status = {
"status": "connected",
"version": __version__,
"bridge_connected": True,
"last_update": tado_api.last_update,
"cached_accessories": len(tado_api.accessories_cache),
"tracked_devices": len(devices),
"active_listeners": len(tado_api.event_listeners),
"events_received": tado_api.change_tracker.get('events_received', 0),
"polling_changes": tado_api.change_tracker.get('polling_changes', 0),
"uptime": time.time() - (tado_api.last_update or time.time())
}
# Add cloud API status if available
if hasattr(tado_api, 'cloud_api') and tado_api.cloud_api:
cloud = tado_api.cloud_api
cloud_status = {
"enabled": True,
"authenticated": cloud.is_authenticated(),
"home_id": cloud.home_id,
}
# Add token expiry info if authenticated
if cloud.is_authenticated():
cloud_status["token_expires_at"] = cloud.token_expires_at
cloud_status["token_expires_in"] = int(cloud.token_expires_at - time.time()) if cloud.token_expires_at else None
# Add rate limit info if available
if cloud.rate_limit and cloud.rate_limit.granted_calls:
cloud_status["rate_limit"] = cloud.rate_limit.to_dict()
# Add authentication info if currently authenticating
if cloud.is_authenticating and cloud.auth_verification_uri:
cloud_status["authentication_required"] = True
cloud_status["verification_uri"] = cloud.auth_verification_uri
cloud_status["user_code"] = cloud.auth_user_code
cloud_status["auth_expires_at"] = cloud.auth_expires_at
cloud_status["auth_expires_in"] = int(cloud.auth_expires_at - time.time()) if cloud.auth_expires_at else None
cloud_status["message"] = f"Visit {cloud.auth_verification_uri} to authenticate"
elif not cloud.is_authenticated():
cloud_status["authentication_required"] = True
cloud_status["message"] = "Authentication will start automatically"
status["cloud_api"] = cloud_status
else:
status["cloud_api"] = {
"enabled": False,
"authenticated": False
}
return status
except Exception as e:
return {
"status": "error",
"bridge_connected": False,
"error": str(e)
}
@app.get("/accessories", tags=["HomeKit"])
async def get_accessories(enhanced: bool = True, api_key: Optional[str] = Depends(get_api_key)):
"""
Get all HomeKit accessories and their characteristics.
Args:
enhanced: If True, include human-readable names for UUIDs (default: True)
"""
tado_api = get_tado_api()
accessories = await tado_api.refresh_accessories()
if enhanced:
return {
"accessories": enhance_accessory_data(accessories),
"enhanced": True,
"note": "UUIDs have been enhanced with human-readable names. Use ?enhanced=false for raw data."
}
else:
return {
"accessories": accessories,
"enhanced": False
}
@app.get("/accessories/{accessory_id}", tags=["HomeKit"])
async def get_accessory(accessory_id: int, enhanced: bool = True, api_key: Optional[str] = Depends(get_api_key)):
"""
Get specific accessory by ID.
Args:
accessory_id: The HomeKit accessory ID
enhanced: If True, include human-readable names for UUIDs (default: True)
"""
tado_api = get_tado_api()
if not tado_api.accessories_cache:
await tado_api.refresh_accessories()
accessories = tado_api.accessories_cache
for accessory in accessories:
if accessory.get('id') == accessory_id:
if enhanced:
enhanced_accessories = enhance_accessory_data([accessory])
return {
"accessory": enhanced_accessories[0] if enhanced_accessories else accessory,
"enhanced": True
}
else:
return {
"accessory": accessory,
"enhanced": False
}
raise HTTPException(status_code=404, detail=f"Accessory {accessory_id} not found")
@app.get("/thermostats", tags=["Thermostats"])
async def get_thermostats(api_key: Optional[str] = Depends(get_api_key)):
"""
Get all thermostat devices with standardized state.
Returns temperature, humidity, mode, and heating status for each thermostat.
"""
tado_api = get_tado_api()
if not tado_api:
raise HTTPException(status_code=503, detail="API not initialized")
if not tado_api.accessories_cache:
await tado_api.refresh_accessories()
thermostats = []
accessories = tado_api.accessories_cache
for accessory in accessories:
services = accessory.get('services', [])
for service in services:
if service.get('type') == '0000004A-0000-1000-8000-0026BB765291': # Thermostat service
device_id = accessory.get('id')
if not device_id:
continue
# Get device info from cache
device_info = tado_api.state_manager.device_info_cache.get(device_id, {})
# Build standardized state
state = tado_api.state_manager.get_current_state(device_id)
cur_temp_c = state.get('current_temperature')
target_temp_c = state.get('target_temperature')
# Determine battery_low from Cloud API (cached)
battery_state = device_info.get('battery_state')
battery_low = battery_state is not None and battery_state != 'NORMAL'
thermostat = {
'device_id': device_id,
'aid': accessory.get('aid'),
'serial_number': accessory.get('serial_number'),
'zone_name': device_info.get('zone_name'),
'zone_id': device_info.get('zone_id'),
'device_type': device_info.get('device_type'),
'is_zone_leader': device_info.get('is_zone_leader', False),
'state': {
'cur_temp_c': cur_temp_c,
'cur_temp_f': round(cur_temp_c * 9/5 + 32, 1) if cur_temp_c is not None else None,
'hum_perc': state.get('humidity'),
'target_temp_c': target_temp_c,
'target_temp_f': round(target_temp_c * 9/5 + 32, 1) if target_temp_c is not None else None,
'mode': state.get('target_heating_cooling_state', 0),
'cur_heating': 1 if state.get('current_heating_cooling_state') == 1 else 0,
'valve_position': state.get('valve_position'),
'battery_low': battery_low,
}
}
thermostats.append(thermostat)
return {"thermostats": thermostats, "count": len(thermostats)}
@app.get("/thermostats/{thermostat_id}", tags=["Thermostats"])
async def get_thermostat(thermostat_id: int, api_key: Optional[str] = Depends(get_api_key)):
"""Get specific thermostat by device ID with standardized state."""
tado_api = get_tado_api()
if not tado_api:
raise HTTPException(status_code=503, detail="API not initialized")
if not tado_api.accessories_cache:
await tado_api.refresh_accessories()
# Find accessory by device ID
accessory = None
for acc in tado_api.accessories_cache:
if acc.get('id') == thermostat_id:
accessory = acc
break
if not accessory:
raise HTTPException(status_code=404, detail=f"Device with ID {thermostat_id} not found")
# Check if it's a thermostat
is_thermostat = False
for service in accessory.get('services', []):
if service.get('type') == '0000004A-0000-1000-8000-0026BB765291':
is_thermostat = True
break
if not is_thermostat:
raise HTTPException(status_code=400, detail=f"Device {thermostat_id} is not a thermostat")
# Get device info from cache
device_info = tado_api.state_manager.device_info_cache.get(thermostat_id, {})
# Build standardized state
state = tado_api.state_manager.get_current_state(thermostat_id)
cur_temp_c = state.get('current_temperature')
target_temp_c = state.get('target_temperature')
# Determine battery_low from Cloud API (cached)
battery_state = device_info.get('battery_state')
battery_low = battery_state is not None and battery_state != 'NORMAL'
thermostat = {
'device_id': thermostat_id,
'aid': accessory.get('aid'),
'serial_number': accessory.get('serial_number'),
'zone_name': device_info.get('zone_name'),
'device_type': device_info.get('device_type'),
'is_zone_leader': device_info.get('is_zone_leader'),
'is_circuit_driver': device_info.get('is_circuit_driver'),
'state': {
'cur_temp_c': cur_temp_c,
'cur_temp_f': round(cur_temp_c * 9/5 + 32, 1) if cur_temp_c is not None else None,
'hum_perc': state.get('humidity'),
'target_temp_c': target_temp_c,
'target_temp_f': round(target_temp_c * 9/5 + 32, 1) if target_temp_c is not None else None,
'mode': state.get('target_heating_cooling_state', 0),
'cur_heating': 1 if state.get('current_heating_cooling_state') == 1 else 0,
'valve_position': state.get('valve_position'),
'battery_low': battery_low,
}
}
return thermostat
@app.get("/zones", tags=["Zones"])
async def get_zones(api_key: Optional[str] = Depends(get_api_key)):
"""
Get all zones with aggregated state (no per-device details).
Returns zone-level information:
- Current temperature (°C and °F)
- Current humidity (%)
- Target temperature (°C and °F)
- Mode (0=Off, 1=Heat) - TargetHeatingCoolingState
- Currently heating (0=Off, 1=Heating, 2=Cooling) - CurrentHeatingCoolingState
Note: Mode values depend on device capabilities. Heating-only devices typically
support 0 (Off) and 1 (Heat). Devices with cooling may support additional values.
For individual device details, use /thermostats or /devices endpoints.
Note: For zones where the leader is a circuit driver (e.g., RU02 controlling
multiple rooms), the "cur_heating" status reflects the actual heating
state from radiator valves in the zone, not the circuit driver state.
"""
tado_api = get_tado_api()
if not tado_api:
raise HTTPException(status_code=503, detail="API not initialized")
zones = []
# Use cached zone info (no DB query)
# Sort by order_id (treating None as 999, but 0 is valid), then by name
for zone_id, zone_info in sorted(tado_api.state_manager.zone_cache.items(),
key=lambda x: (999 if x[1].get('order_id') is None else x[1].get('order_id'), x[1].get('name'))):
name = zone_info['name']
leader_device_id = zone_info['leader_device_id']
order_id = zone_info['order_id']
leader_serial = zone_info['leader_serial']
leader_type = zone_info['leader_type']
is_circuit_driver = zone_info['is_circuit_driver']
tado_zone_id = zone_info['tado_zone_id']
# Get device count for this zone (quick loop through device cache)
device_count = sum(1 for dev_info in tado_api.state_manager.device_info_cache.values()
if dev_info.get('zone_id') == zone_id)
# Get zone state from leader (with optimistic updates for UI responsiveness)
# Note: Individual devices always show real state. Only zone aggregation uses optimistic state.
zone_state = None
if leader_device_id:
zone_state = tado_api.state_manager.get_state_with_optimistic(leader_device_id)
# If no leader state, try first device in zone
if not zone_state:
for dev_id, dev_info in tado_api.state_manager.device_info_cache.items():
if dev_info.get('zone_id') == zone_id:
zone_state = tado_api.state_manager.get_state_with_optimistic(dev_id)
break
# Build zone summary state from zone leader:
# - All values (temp, humidity, target_temp, mode) come from zone leader (with optimistic updates)
# - Exception: cur_heating for circuit drivers with other devices uses radiator valve state
if zone_state:
current_temp = zone_state.get('current_temperature')
humidity = zone_state.get('humidity')
target_temp = zone_state.get('target_temperature')
target_heating_cooling_state = zone_state.get('target_heating_cooling_state', 0)
# Mode: Always from zone leader's target_heating_cooling_state (with optimistic updates)
mode = target_heating_cooling_state
# Currently heating: From zone leader, EXCEPT for circuit drivers with other devices
cur_heating = 0
if is_circuit_driver:
# Circuit driver - check if there are other devices (radiator valves) in zone
other_devices = [dev_id for dev_id, dev_info in tado_api.state_manager.device_info_cache.items()
if dev_info.get('zone_id') == zone_id and not dev_info.get('is_circuit_driver')]
if other_devices:
# Circuit driver WITH other devices - use radiator valve heating state (real state)
for dev_id in other_devices:
dev_state = tado_api.state_manager.get_current_state(dev_id)
if dev_state and dev_state.get('current_heating_cooling_state') == 1:
cur_heating = 1
break
else:
# Circuit driver ALONE in zone - use its own heating state
cur_heating = 1 if zone_state.get('current_heating_cooling_state') == 1 else 0
else:
# Regular zone leader (not circuit driver) - use its heating state
cur_heating = 1 if zone_state.get('current_heating_cooling_state') == 1 else 0
# Convert temperatures to Fahrenheit
cur_temp_f = round(current_temp * 9/5 + 32, 1) if current_temp is not None else None
target_temp_f = round(target_temp * 9/5 + 32, 1) if target_temp is not None else None
state_summary = {
'cur_temp_c': current_temp,
'cur_temp_f': cur_temp_f,
'hum_perc': humidity,
'target_temp_c': target_temp,
'target_temp_f': target_temp_f,
'mode': mode,
'cur_heating': cur_heating,
}
else:
state_summary = {
'cur_temp_c': None,
'cur_temp_f': None,
'hum_perc': None,
'target_temp_c': None,
'target_temp_f': None,
'mode': 0,
'cur_heating': 0,
}
zones.append({
'zone_id': zone_id,
'name': name,
'uuid': zone_info.get('uuid'),
'leader_device_id': leader_device_id,
'leader_serial': leader_serial,
'leader_type': leader_type,
'tado_zone_id': tado_zone_id,
'is_circuit_driver': bool(is_circuit_driver),
'order_id': order_id,
'device_count': device_count,
'state': state_summary
})
# Get home info if cloud API is available and authenticated
homes = []
if hasattr(tado_api, 'cloud_api') and tado_api.cloud_api and tado_api.cloud_api.is_authenticated():
try:
home_data = await tado_api.cloud_api.get_home_info()
if home_data:
homes.append({
'id': home_data.get('id'),
'name': home_data.get('name')
})
except Exception as e:
logger.debug(f"Could not fetch home info: {e}")
# Add home_id reference to each zone (from first/only home for now)
home_id = homes[0]['id'] if homes else None
for zone in zones:
zone['home_id'] = home_id
return {
'homes': homes,
'zones': zones,
'count': len(zones)
}
@app.get("/zones/{zone_id}", tags=["Zones"])
async def get_zone(zone_id: int, api_key: Optional[str] = Depends(get_api_key)):
"""
Get zone level information
Returns zone-level information:
- Current temperature (°C and °F)
- Current humidity (%)
- Target temperature (°C and °F)
- Mode (0=Off, 1=Heat) - TargetHeatingCoolingState
- Currently heating (0=Off, 1=Heating, 2=Cooling) - CurrentHeatingCoolingState
Note: Mode values depend on device capabilities. Heating-only devices typically
support 0 (Off) and 1 (Heat). Devices with cooling may support additional values.
For individual device details, use /thermostats or /devices endpoints.
Note: For zones where the leader is a circuit driver (e.g., RU02 controlling
multiple rooms), the "cur_heating" status reflects the actual heating
state from radiator valves in the zone, not the circuit driver state.
"""
tado_api = get_tado_api()
if not tado_api:
raise HTTPException(status_code=503, detail="API not initialized")
zones = []
if zone_id not in tado_api.state_manager.zone_cache:
raise HTTPException(status_code=404, detail=f"Zone {zone_id} not found")
# Use cached zone info (no DB query)
# Sort by order_id (treating None as 999, but 0 is valid), then by name
zone_info = tado_api.state_manager.zone_cache[zone_id]
name = zone_info['name']
leader_device_id = zone_info['leader_device_id']
order_id = zone_info['order_id']
leader_serial = zone_info['leader_serial']
leader_type = zone_info['leader_type']
is_circuit_driver = zone_info['is_circuit_driver']
tado_zone_id = zone_info['tado_zone_id']
# Get device count for this zone (quick loop through device cache)
device_count = sum(1 for dev_info in tado_api.state_manager.device_info_cache.values()
if dev_info.get('zone_id') == zone_id)
# Get zone state from leader (with optimistic updates for UI responsiveness)
# Note: Individual devices always show real state. Only zone aggregation uses optimistic state.
zone_state = None
if leader_device_id:
zone_state = tado_api.state_manager.get_state_with_optimistic(leader_device_id)
# If no leader state, try first device in zone
if not zone_state:
for dev_id, dev_info in tado_api.state_manager.device_info_cache.items():
if dev_info.get('zone_id') == zone_id:
zone_state = tado_api.state_manager.get_state_with_optimistic(dev_id)
break
# Build zone summary state from zone leader:
# - All values (temp, humidity, target_temp, mode) come from zone leader (with optimistic updates)
# - Exception: cur_heating for circuit drivers with other devices uses radiator valve state
if zone_state:
current_temp = zone_state.get('current_temperature')
humidity = zone_state.get('humidity')
target_temp = zone_state.get('target_temperature')
target_heating_cooling_state = zone_state.get('target_heating_cooling_state', 0)
# Mode: Always from zone leader's target_heating_cooling_state (with optimistic updates)
mode = target_heating_cooling_state
# Currently heating: From zone leader, EXCEPT for circuit drivers with other devices
cur_heating = 0
if is_circuit_driver:
# Circuit driver - check if there are other devices (radiator valves) in zone
other_devices = [dev_id for dev_id, dev_info in tado_api.state_manager.device_info_cache.items()
if dev_info.get('zone_id') == zone_id and not dev_info.get('is_circuit_driver')]
if other_devices:
# Circuit driver WITH other devices - use radiator valve heating state (real state)
for dev_id in other_devices:
dev_state = tado_api.state_manager.get_current_state(dev_id)
if dev_state and dev_state.get('current_heating_cooling_state') == 1:
cur_heating = 1
break
else:
# Circuit driver ALONE in zone - use its own heating state
cur_heating = 1 if zone_state.get('current_heating_cooling_state') == 1 else 0
else:
# Regular zone leader (not circuit driver) - use its heating state
cur_heating = 1 if zone_state.get('current_heating_cooling_state') == 1 else 0
# Convert temperatures to Fahrenheit
cur_temp_f = round(current_temp * 9/5 + 32, 1) if current_temp is not None else None
target_temp_f = round(target_temp * 9/5 + 32, 1) if target_temp is not None else None
state_summary = {
'cur_temp_c': current_temp,
'cur_temp_f': cur_temp_f,
'hum_perc': humidity,
'target_temp_c': target_temp,
'target_temp_f': target_temp_f,
'mode': mode,
'cur_heating': cur_heating,
}
else:
state_summary = {
'cur_temp_c': None,
'cur_temp_f': None,
'hum_perc': None,
'target_temp_c': None,
'target_temp_f': None,
'mode': 0,
'cur_heating': 0,
}
zone = {
'zone_id': zone_id,
'name': name,
'uuid': zone_info.get('uuid'),
'leader_device_id': leader_device_id,
'leader_serial': leader_serial,
'leader_type': leader_type,
'tado_zone_id': tado_zone_id,
'is_circuit_driver': bool(is_circuit_driver),
'order_id': order_id,
'device_count': device_count,
'state': state_summary
}
# Get home info if cloud API is available and authenticated
homes = []
if hasattr(tado_api, 'cloud_api') and tado_api.cloud_api and tado_api.cloud_api.is_authenticated():
try:
home_data = await tado_api.cloud_api.get_home_info()
if home_data:
homes.append({
'id': home_data.get('id'),
'name': home_data.get('name')
})
except Exception as e:
logger.debug(f"Could not fetch home info: {e}")
# Add home_id reference to each zone (from first/only home for now)
home_id = homes[0]['id'] if homes else None
for zone in zones:
zone['home_id'] = home_id
return {
'home': homes[0] if homes else None,
'zone': zone,
}
@app.post("/zones", tags=["Zones"])
async def create_zone(name: str, leader_device_id: Optional[int] = None, order_id: Optional[int] = None, api_key: Optional[str] = Depends(get_api_key)):
"""Create a new zone."""
tado_api = get_tado_api()
if not tado_api:
raise HTTPException(status_code=503, detail="API not initialized")
conn = sqlite3.connect(tado_api.state_manager.db_path)
cursor = conn.execute("""
INSERT INTO zones (name, leader_device_id, order_id)
VALUES (?, ?, ?)
""", (name, leader_device_id, order_id))
zone_id = cursor.lastrowid
conn.commit()
conn.close()
# Reload device cache to pick up zone info
tado_api.state_manager._load_device_cache()
return {'zone_id': zone_id, 'name': name}
@app.put("/zones/{zone_id}", tags=["Zones"])
async def update_zone(zone_id: int, name: Optional[str] = None, leader_device_id: Optional[int] = None, order_id: Optional[int] = None, api_key: Optional[str] = Depends(get_api_key)):
"""Update a zone."""
tado_api = get_tado_api()
if not tado_api:
raise HTTPException(status_code=503, detail="API not initialized")
conn = sqlite3.connect(tado_api.state_manager.db_path)
updates = []
params = []
if name is not None:
updates.append("name = ?")
params.append(name)
if leader_device_id is not None:
updates.append("leader_device_id = ?")
params.append(leader_device_id)
if order_id is not None:
updates.append("order_id = ?")
params.append(order_id)
if not updates:
raise HTTPException(status_code=400, detail="No updates provided")
params.append(zone_id)
conn.execute(f"UPDATE zones SET {', '.join(updates)} WHERE zone_id = ?", params)
conn.commit()
conn.close()
# Reload device cache
tado_api.state_manager._load_device_cache()
return {'zone_id': zone_id, 'updated': True}
@app.post("/zones/{zone_id}/set", tags=["Zones"])
async def set_zone(
zone_id: int,
temperature: Optional[float] = None,
heating_enabled: Optional[bool] = None,
no_implicit_mode: Optional[bool] = False,
api_key: Optional[str] = Depends(get_api_key)
):
"""
Control a zone's heating via its leader device.
Args:
zone_id: Zone ID to control
temperature: Target temperature in °C (-1, 0, or 5-30).
- -1 = resume schedule/auto mode (enable heating without changing target temp)
- 0 = disable heating (without changing target temp)
- >= 5 = set temperature and enable heating
heating_enabled: Enable/disable heating mode (true/false)
Returns:
Success status and applied values
Notes:
- Smart defaults:
- temperature = -1 implies heating_enabled=true (resume schedule)
- temperature = 0 implies heating_enabled=false (off)
- temperature >= 5°C implies heating_enabled=true
- Explicitly set heating_enabled to override smart defaults
- Commands are sent to the zone's leader device
- The leader propagates changes to other devices as needed
- heating_enabled controls the heat mode (OFF=0, HEAT=1)
- Both temperature=0 and temperature=-1 preserve the stored target temperature
- This allows temporary on/off control without affecting your schedule
- temperature=-1 is useful for automation: turn on without changing schedule
- temperature=0 is useful for "away mode": turn off but remember setpoint
"""
# Log the incoming request
logger.info(f"POST /zones/{zone_id}/set temperature={temperature} heating_enabled={heating_enabled}")
tado_api = get_tado_api()
if not tado_api:
raise HTTPException(status_code=503, detail="API not initialized")
if not tado_api.pairing:
raise HTTPException(status_code=503, detail="Bridge not connected")
# Apply smart defaults
if temperature is not None and heating_enabled is None:
if temperature == -1:
heating_enabled = True # Resume schedule/enable without changing temp
temperature = None # Don't set temperature
elif temperature == 0:
heating_enabled = False
temperature = None # Don't set temperature
elif temperature >= 5.0 and no_implicit_mode is not True:
heating_enabled = True
elif temperature == -1:
# temperature=-1 always means "don't change temperature, just enable"
temperature = None
if heating_enabled is None:
heating_enabled = True
# Get zone info
conn = sqlite3.connect(tado_api.state_manager.db_path)
cursor = conn.execute("""
SELECT z.name, z.leader_device_id, d.serial_number
FROM zones z
LEFT JOIN devices d ON z.leader_device_id = d.device_id
WHERE z.zone_id = ?
""", (zone_id,))
row = cursor.fetchone()
conn.close()
if not row:
raise HTTPException(status_code=404, detail=f"Zone {zone_id} not found")
zone_name, leader_device_id, leader_serial = row
if not leader_device_id:
# No explicit leader assigned - fall back to the first device in the zone
conn = sqlite3.connect(tado_api.state_manager.db_path)
cur = conn.execute(
"""
SELECT device_id, serial_number, name
FROM devices
WHERE zone_id = ?
ORDER BY device_id
LIMIT 1
""",
(zone_id,)
)
dev = cur.fetchone()
conn.close()
if dev:
leader_device_id = dev[0]
leader_serial = dev[1]
logger.warning(
"Zone %s ('%s') has no leader assigned; falling back to device %s (%s)",
zone_id, zone_name, leader_device_id, leader_serial
)
else:
raise HTTPException(status_code=400, detail=f"Zone '{zone_name}' has no leader device assigned")
# Build characteristic updates
char_updates = {}
if temperature is not None:
# Validate temperature range (5-30°C is typical for Tado)
if temperature < 0.0 or temperature > 30.0:
raise HTTPException(status_code=400, detail="Temperature must be -1 (resume), 0 (off), or between 5 and 30°C")
if temperature > 0 and temperature < 5.0:
raise HTTPException(status_code=400, detail="Temperature must be -1, 0, or between 5 and 30°C")
if temperature > 0: # Only set if not turning off
char_updates['target_temperature'] = temperature
if heating_enabled is not None:
# 0 = OFF, 1 = HEAT
char_updates['target_heating_cooling_state'] = 1 if heating_enabled else 0
if not char_updates:
raise HTTPException(status_code=400, detail="No control parameters provided")
# Log what we're changing (single summary line)
changes = []
if 'target_temperature' in char_updates:
changes.append(f"temperature={char_updates['target_temperature']}°C")
if 'target_heating_cooling_state' in char_updates:
mode = "ON" if char_updates['target_heating_cooling_state'] == 1 else "OFF"
changes.append(f"heating={mode}")
logger.info(f"Zone {zone_id} ({zone_name}): {', '.join(changes)}")
# Apply optimistic state prediction for immediate UI feedback
optimistic_state = {}
if 'target_temperature' in char_updates:
optimistic_state['target_temperature'] = char_updates['target_temperature']
if 'target_heating_cooling_state' in char_updates:
optimistic_state['target_heating_cooling_state'] = char_updates['target_heating_cooling_state']
if optimistic_state:
tado_api.state_manager.set_optimistic_state(leader_device_id, optimistic_state)
logger.debug(
"Zone %s: Applied optimistic state prediction: %s",
zone_id, optimistic_state
)
# Set the characteristics on the leader device
try:
await tado_api.set_device_characteristics(leader_device_id, char_updates)
return {
'success': True,
'zone_id': zone_id,
'zone_name': zone_name,
'leader_device_id': leader_device_id,
'leader_serial': leader_serial,
'applied': {
'target_temperature': temperature,
'heating_enabled': heating_enabled
}
}
except Exception as e:
logger.error(f"Failed to control zone {zone_id}: {e}")
raise HTTPException(status_code=500, detail=f"Failed to set zone control: {str(e)}")
@app.get("/devices", tags=["Devices"])
async def get_devices(api_key: Optional[str] = Depends(get_api_key)):
"""
Get all registered devices with standardized state.
Returns all devices (thermostats, valves, bridges, etc.) with:
- Device metadata (serial, type, zone)
- Standardized state format
- Battery status (for battery-powered devices)
"""
tado_api = get_tado_api()
if not tado_api:
raise HTTPException(status_code=503, detail="API not initialized")
all_devices = tado_api.state_manager.get_all_devices()
devices = []
for device_info in all_devices:
device_id = device_info['device_id']
state = tado_api.state_manager.get_current_state(device_id)
# Build standardized state
cur_temp_c = state.get('current_temperature')
target_temp_c = state.get('target_temperature')
# Determine battery_low from Cloud API (cached in device_info, no extra DB query)
battery_state = device_info.get('battery_state')
battery_low = battery_state is not None and battery_state != 'NORMAL'
device = {
'device_id': device_id,
'serial_number': device_info.get('serial_number'),
'aid': device_info.get('aid'),
'zone_id': device_info.get('zone_id'),
'zone_name': device_info.get('zone_name'),
'device_type': device_info.get('device_type'),
'model': device_info.get('model'),
'firmware_version': device_info.get('firmware_version'),
'is_zone_leader': device_info.get('is_zone_leader'),
'is_circuit_driver': device_info.get('is_circuit_driver'),
'state': {