forked from AmpScm/TadoLocal
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path__main__.py
More file actions
527 lines (465 loc) · 20.7 KB
/
Copy path__main__.py
File metadata and controls
527 lines (465 loc) · 20.7 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
#
# 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.
#
"""Command-line interface for Tado Local."""
import asyncio
import argparse
import logging
import logging.handlers
import os
import signal
import sys
from pathlib import Path
from typing import Optional
import uvicorn
from aiohomekit.controller.ip.pairing import IpPairing
from .bridge import TadoBridge
from .api import TadoLocalAPI
from .cloud import TadoCloudAPI
from .routes import create_app, register_routes
from .zeroconf_register import get_primary_ipv4
# Logger will be configured in main() based on daemon/console mode
logger = logging.getLogger(__name__)
# Global variables
bridge_pairing: Optional[IpPairing] = None
tado_api: Optional[TadoLocalAPI] = None
server: Optional[uvicorn.Server] = None
shutdown_event: Optional[asyncio.Event] = None
async def run_server(args):
"""Run the Tado Local server."""
global bridge_pairing, tado_api, server, shutdown_event
shutdown_event = asyncio.Event()
def handle_signal(signum, frame):
"""Handle shutdown signals gracefully."""
logger.info(f"Received signal {signum}, initiating immediate shutdown...")
shutdown_event.set()
# Immediately close SSE streams
if tado_api:
logger.info("Closing SSE event streams immediately...")
if tado_api.event_listeners:
for queue in list(tado_api.event_listeners):
try:
queue.put_nowait(None)
except Exception as e:
logger.error(f"Unexpected error sending shutdown event queue signal: {e}")
pass
if tado_api.zone_event_listeners:
for queue in list(tado_api.zone_event_listeners):
try:
queue.put_nowait(None)
except Exception as e:
logger.error(f"Unexpected error sending shutdown zone queue signal: {e}")
pass
if server:
server.should_exit = True
# Register signal handlers
signal.signal(signal.SIGINT, handle_signal)
signal.signal(signal.SIGTERM, handle_signal)
try:
# Initialize database and pairing
db_path = Path(os.path.expanduser(args.state))
# Ensure DB schema and run migrations before anything else touches the DB.
from .database import ensure_schema_and_migrate
try:
ensure_schema_and_migrate(str(db_path))
except Exception as e:
logger.error(f"Database migration check failed: {e}")
raise
# Initialize the API with database path
tado_api = TadoLocalAPI(str(db_path))
# Initialize Tado Cloud API (always enabled)
cloud_api = TadoCloudAPI(str(db_path), tado_api=tado_api)
# Check if already authenticated
if not cloud_api.is_authenticated():
logger.info("Tado Cloud API: Starting authentication flow...")
# Start authentication in background (non-blocking)
asyncio.create_task(cloud_api.authenticate())
else:
logger.info("Tado Cloud API: Already authenticated (Home ID: {})".format(cloud_api.home_id))
# Verify token is still valid at startup
if cloud_api.has_valid_access_token():
logger.info("Access token is valid")
else:
logger.info("Access token expired, will refresh on first API call")
# Start background 4-hour sync task (replaces continuous token refresh)
cloud_api.start_background_sync()
# Store cloud_api reference in tado_api for use by routes
tado_api.cloud_api = cloud_api
# Create the FastAPI app
app = create_app()
register_routes(app, lambda: tado_api)
# Set up pairing
bridge_pairing, bridge_ip = await TadoBridge.pair_or_load(
args.bridge_ip, args.pin, db_path, args.clear_pairings
)
# Initialize the API with the pairing
await tado_api.initialize(bridge_pairing)
# Register mDNS service asynchronously (Avahi via DBus preferred, fall back to zeroconf)
if not args.no_mdns:
try:
logger.debug("Attempting to import zeroconf_register for mDNS registration")
from .zeroconf_register import register_service_async
logger.info("mDNS registration helper loaded")
async def _schedule_mdns():
# Register a single HTTP service so basic clients can discover the API.
# We intentionally publish only the HTTP service to avoid duplicate
# registrations (the previous code registered two distinct service
# types which caused two external publisher processes).
try:
from .__version__ import __version__ as tado_version
# Do not advertise the bridge IP here; advertise the daemon host
# so clients connect to this service instance to manage Tado.
ok, method, msg, server_ip = await register_service_async(name='tado-local', port=args.port, props={
'path': '/',
'version': tado_version,
'app': 'tado-local',
'id': 'tado-local'
}, service_type='_http._tcp.local.')
if ok:
logger.info(f"HTTP mDNS service registered via {method} (advertising daemon host A/AAAA records on {server_ip})")
else:
logger.warning(f"HTTP mDNS registration: {msg} (advertising daemon host)")
except Exception as e:
logger.exception("HTTP mDNS async registration failed (%s) ", e)
# schedule background registration; do not await so startup remains fast
task = asyncio.create_task(_schedule_mdns())
logger.info("Scheduled HTTP mDNS registration task")
def _mdns_done(fut: 'asyncio.Future'):
try:
fut.result()
except Exception:
logger.exception("HTTP mDNS registration task failed")
try:
task.add_done_callback(_mdns_done)
except Exception:
# If add_done_callback isn't available for any reason, still continue
pass
except Exception as e:
# Make this visible in normal logs; use warning so users running at INFO see it
logger.warning("mDNS registration scheduler unavailable: %s", e)
else:
logger.info("mDNS registration disabled by --no-mdns flag")
server_ip = get_primary_ipv4() or "0.0.0.0"
logger.info("*** Tado Local ready! ***")
logger.info(f"Bridge IP: {bridge_ip}")
logger.info(f"API Server: http://{server_ip}:{args.port}")
logger.info(f"Documentation: http://{server_ip}:{args.port}/docs")
logger.info(f"Status: http://{server_ip}:{args.port}/status")
logger.info(f"Thermostats: http://{server_ip}:{args.port}/thermostats")
logger.info(f"Live Events: http://{server_ip}:{args.port}/events")
# Configure uvicorn logging to match our format and prevent duplicates
if args.syslog:
# Syslog mode: disable uvicorn's default logging, use root logger
log_config = {
"version": 1,
"disable_existing_loggers": False,
"loggers": {
"uvicorn": {"handlers": [], "level": "INFO", "propagate": True},
"uvicorn.error": {"handlers": [], "level": "INFO", "propagate": True},
"uvicorn.access": {"handlers": [], "level": "WARNING", "propagate": True},
},
}
elif args.daemon:
# Daemon mode: simple format without timestamps
log_format = "%(levelname)-8s %(message)s"
log_config = {
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"default": {
"format": log_format,
},
"access": {
"format": "%(levelname)-8s %(message)s",
},
},
"handlers": {
"default": {
"formatter": "default",
"class": "logging.StreamHandler",
"stream": "ext://sys.stdout",
},
"access": {
"formatter": "access",
"class": "logging.StreamHandler",
"stream": "ext://sys.stdout",
},
},
"loggers": {
"uvicorn": {"handlers": ["default"], "level": "INFO", "propagate": False},
"uvicorn.error": {"handlers": ["default"], "level": "INFO", "propagate": False},
"uvicorn.access": {"handlers": ["access"], "level": "INFO", "propagate": False},
},
}
else:
# Console mode: timestamp + message (clean and readable)
log_format = "%(asctime)s %(levelname)s %(message)s"
log_config = {
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"default": {
"format": log_format,
"datefmt": "%Y-%m-%d %H:%M:%S",
},
"access": {
"format": "%(asctime)s %(levelname)s %(message)s",
"datefmt": "%Y-%m-%d %H:%M:%S",
},
},
"handlers": {
"default": {
"formatter": "default",
"class": "logging.StreamHandler",
"stream": "ext://sys.stdout",
},
"access": {
"formatter": "access",
"class": "logging.StreamHandler",
"stream": "ext://sys.stdout",
},
},
"loggers": {
"uvicorn": {"handlers": ["default"], "level": "INFO", "propagate": False},
"uvicorn.error": {"handlers": ["default"], "level": "INFO", "propagate": False},
"uvicorn.access": {"handlers": ["access"], "level": "INFO", "propagate": False},
},
}
# Start the FastAPI server
config = uvicorn.Config(
app,
host="0.0.0.0",
port=args.port,
log_config=log_config,
access_log=True
)
server = uvicorn.Server(config)
await server.serve()
except KeyboardInterrupt:
logger.info("Keyboard interrupt received, shutting down gracefully...")
except Exception as e:
logger.error(f"ERROR: Failed to start Tado Local: {e}")
raise
finally:
# Clean up resources
if tado_api:
logger.info("Performing cleanup...")
# Close all SSE event streams (if not already closed by signal handler)
if tado_api.event_listeners or tado_api.zone_event_listeners:
logger.info("Closing remaining SSE event streams...")
if tado_api.event_listeners:
logger.info(f"Closing {len(tado_api.event_listeners)} event listener queues")
for queue in tado_api.event_listeners[:]:
try:
await queue.put(None)
except Exception as e:
logger.error(f"Unexpected error sending closing signal event queue: {e}")
pass
if tado_api.zone_event_listeners:
logger.info(f"Closing {len(tado_api.zone_event_listeners)} zone event listener queues")
for queue in tado_api.zone_event_listeners[:]:
try:
await queue.put(None)
except Exception as e:
logger.error(f"Unexpected error sending closing signal zone queue: {e}")
pass
# Give clients a moment to receive the close signal
await asyncio.sleep(0.3)
# Stop cloud API background sync if running
if hasattr(tado_api, 'cloud_api') and tado_api.cloud_api:
logger.info("Stopping Tado Cloud API background tasks...")
await tado_api.cloud_api.stop_background_sync()
# Full cleanup
await tado_api.cleanup()
# Unregister mDNS service if registered
try:
from .zeroconf_register import unregister_service
unregister_service()
except Exception:
pass
# Clean up PID file
if args.pid_file:
pid_path = Path(args.pid_file)
try:
if pid_path.exists():
pid_path.unlink()
logger.info(f"PID file removed: {pid_path}")
except Exception as e:
logger.warning(f"Failed to remove PID file: {e}")
# Forced exit after 3 seconds to avoid lingering connections (especially for browsers)
import threading
import sys
def force_exit():
logger.warning("Forcing process exit after 3 seconds to avoid lingering SSE connections.")
os._exit(0)
if sys.platform == "win32":
logger.warning("Forcing immediate process exit on Windows to avoid lingering connections and background jobs.")
os._exit(0)
else:
threading.Timer(3.0, force_exit).start()
logger.info("Shutdown complete. Process will exit in 3 seconds.")
def main():
"""Main entry point for the CLI."""
parser = argparse.ArgumentParser(
description="Tado Local - REST API for Tado devices via HomeKit bridge",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
# Initial pairing (first time setup)
python -m tado_local --bridge-ip 192.168.1.100 --pin 123-45-678
tado-local --bridge-ip 192.168.1.100 --pin 123-45-678
# Start API server with existing pairing (console mode)
python -m tado_local --bridge-ip 192.168.1.100
tado-local --bridge-ip 192.168.1.100
# Run as system daemon (structured logging for syslog)
tado-local --bridge-ip 192.168.1.100 --daemon --pid-file /var/run/tado-local.pid
# Send logs to local syslog
tado-local --bridge-ip 192.168.1.100 --syslog /dev/log
# Send logs to remote syslog server
tado-local --bridge-ip 192.168.1.100 --syslog logserver.local:514
# Custom port and database location
python -m tado_local --bridge-ip 192.168.1.100 --port 8080 --state ./my-tado.db
# Debug mode with verbose logging
tado-local --bridge-ip 192.168.1.100 --verbose
API Endpoints:
GET / - API information
GET /status - System status
GET /accessories - All HomeKit accessories
GET /zones - All Tado zones
POST /zones/{id}/set - Set zone temperature
GET /thermostats - All thermostats with temperatures
POST /thermostats/{id}/set - Set thermostat temperature
GET /events - Server-Sent Events for real-time updates
POST /refresh - Manually refresh data
"""
)
parser.add_argument(
"--state", default="~/.tado-local.db",
help="Path to state database (default: ~/.tado-local.db)"
)
parser.add_argument(
"--no-mdns", action="store_true",
help="Disable mDNS/Avahi/zeroconf service registration at startup"
)
parser.add_argument(
"--bridge-ip",
help="IP of the Tado bridge (e.g., 192.168.1.100). If not provided, will auto-discover from existing pairings."
)
parser.add_argument(
"--pin",
help="HomeKit PIN for initial pairing (XXX-XX-XXX format)"
)
parser.add_argument(
"--port", type=int, default=4407,
help="Port for REST API server (default: 4407)"
)
parser.add_argument(
"--clear-pairings", action="store_true",
help="Clear all existing pairings from database before starting"
)
parser.add_argument(
"--verbose", action="store_true",
help="Enable verbose logging (DEBUG level)"
)
parser.add_argument(
"--daemon", action="store_true",
help="Run in daemon mode (structured logging for syslog, auto-enables --pid-file)"
)
parser.add_argument(
"--syslog",
help="Send logs to syslog instead of stdout (e.g., /dev/log, localhost:514, or remote.server:514)"
)
parser.add_argument(
"--pid-file",
help="Write process ID to specified file (useful for daemon mode)"
)
# Parse CLI arguments
args = parser.parse_args()
# mDNS registration is handled inside run_server (so CLI only needs to expose the flag).
if args.no_mdns:
logger.info("mDNS registration disabled by --no-mdns flag")
# Configure logging destination: syslog (if requested), daemon, or console
if args.syslog:
syslog_address = args.syslog
if ':' in syslog_address and not syslog_address.startswith('/'):
# Network address (host:port)
host, port = syslog_address.rsplit(':', 1)
syslog_address = (host, int(port))
# else: Unix socket path (e.g., /dev/log)
try:
syslog_handler = logging.handlers.SysLogHandler(
address=syslog_address,
facility=logging.handlers.SysLogHandler.LOG_DAEMON
)
syslog_handler.setFormatter(logging.Formatter(
'tado-local[%(process)d]: %(levelname)s %(message)s'
))
root_logger = logging.getLogger()
root_logger.setLevel(logging.INFO)
root_logger.addHandler(syslog_handler)
# Silence console output in syslog mode
logging.getLogger().handlers = [syslog_handler]
logger.info("Logging to syslog: %s", args.syslog)
except Exception as e:
# Fall back to console if syslog fails
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s %(levelname)s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
stream=sys.stdout,
force=True
)
logger.error(f"Failed to connect to syslog ({args.syslog}): {e}")
logger.info("Falling back to console logging")
elif args.daemon:
# Daemon mode: structured format suitable for syslog (no timestamp - syslog adds it)
logging.basicConfig(
level=logging.INFO,
format='%(levelname)s %(message)s',
stream=sys.stdout,
force=True
)
else:
# Console mode: timestamp + message (clean and readable)
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s %(levelname)s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
stream=sys.stdout,
force=True
)
# Apply verbose logging if requested
if args.verbose:
logging.getLogger().setLevel(logging.DEBUG)
logger.info("Verbose logging enabled")
# Write PID file if requested
if args.pid_file:
pid_path = Path(args.pid_file)
try:
pid_path.write_text(str(os.getpid()))
logger.info(f"PID file written: {pid_path}")
except Exception as e:
logger.error(f"Failed to write PID file: {e}")
exit(1)
# Run with proper error handling
try:
asyncio.run(run_server(args))
except KeyboardInterrupt:
logger.info("*** Shutdown complete ***")
except Exception as e:
logger.error(f"ERROR: {e}")
exit(1)
if __name__ == "__main__":
main()