amv-wol 1.0.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
ameva_wol/__init__.py ADDED
@@ -0,0 +1,4 @@
1
+ """AMEVA-WoL: Lightweight, secure Telegram-controlled Wake-on-LAN gateway."""
2
+
3
+ __version__ = "1.0.0"
4
+ __author__ = "AMEVA Team"
ameva_wol/__main__.py ADDED
@@ -0,0 +1,7 @@
1
+ """Main entrypoint module for AMEVA-WoL when executed via `python -m ameva_wol`."""
2
+
3
+ import sys
4
+ from ameva_wol.cli import main
5
+
6
+ if __name__ == "__main__":
7
+ sys.exit(main())
ameva_wol/app.py ADDED
@@ -0,0 +1,143 @@
1
+ """Application runner and lifecycle management for AMEVA-WoL."""
2
+
3
+ import asyncio
4
+ import logging
5
+ import signal
6
+ import sys
7
+ from typing import Optional
8
+
9
+ from ameva_wol.config import Config, ConfigurationError
10
+ from ameva_wol.locking import InstanceLock, InstanceLockError
11
+ from ameva_wol.logging_config import setup_logging
12
+ from ameva_wol.registry import DeviceRegistry
13
+ from ameva_wol.tapo_registry import TapoRegistry
14
+ from ameva_wol.scheduler import AlwaysOnScheduler
15
+ from ameva_wol.telegram_bot import create_telegram_app
16
+
17
+ logger = logging.getLogger("ameva_wol.app")
18
+
19
+
20
+ async def main_async(always_on: bool = False, interval_minutes: int = 5) -> int:
21
+ """Async main application runner."""
22
+ # 1. Load Configuration
23
+ try:
24
+ config = Config.load()
25
+ except ConfigurationError as err:
26
+ print(f"Configuration Error: {err}", file=sys.stderr)
27
+ return 1
28
+
29
+ # 2. Setup Logging
30
+ setup_logging(
31
+ log_level=config.log_level,
32
+ data_dir=config.data_dir,
33
+ bot_token=config.telegram_bot_token,
34
+ )
35
+ logger.info(f"Starting AMEVA-WoL Gateway (Log Level: {config.log_level})...")
36
+
37
+ # 3. Acquire Single-Instance Lock
38
+ lock = InstanceLock(config.data_dir)
39
+ try:
40
+ lock.acquire()
41
+ logger.info(f"Acquired single-instance lock on '{config.data_dir}'.")
42
+ except InstanceLockError as err:
43
+ logger.error(f"Failed to acquire instance lock: {err}")
44
+ return 1
45
+
46
+ # 4. Initialize Device Registry
47
+ registry = DeviceRegistry(config.data_dir)
48
+ try:
49
+ devices = await registry.load()
50
+ logger.info(f"Loaded device registry ({len(devices)} device(s) registered).")
51
+ except Exception as err:
52
+ logger.error(f"Failed to load device registry: {err}")
53
+ lock.release()
54
+ return 1
55
+
56
+ # 5. Build Telegram Application
57
+ tapo_registry = TapoRegistry(config.data_dir)
58
+ try:
59
+ tapo_data = await tapo_registry.get_config()
60
+ tapo_devices = tapo_data.get("devices", {})
61
+ logger.info(f"Loaded Tapo registry ({len(tapo_devices)} device(s) registered).")
62
+ except Exception as err:
63
+ logger.error(f"Failed to load tapo registry: {err}")
64
+
65
+ tg_app = create_telegram_app(config, registry, tapo_registry)
66
+
67
+ # 6. Initialize Always-On Scheduler if requested
68
+ scheduler: Optional[AlwaysOnScheduler] = None
69
+ if always_on:
70
+ scheduler = AlwaysOnScheduler(
71
+ config=config,
72
+ registry=registry,
73
+ interval_minutes=interval_minutes,
74
+ )
75
+
76
+ stop_event = asyncio.Event()
77
+
78
+ def _signal_handler() -> None:
79
+ logger.info("Received termination signal (SIGINT/SIGTERM). Initiating graceful shutdown...")
80
+ stop_event.set()
81
+
82
+ # Register OS Signal Handlers if supported on current platform/thread
83
+ loop = asyncio.get_running_loop()
84
+ if sys.platform != "win32":
85
+ for sig in (signal.SIGINT, signal.SIGTERM):
86
+ try:
87
+ loop.add_signal_handler(sig, _signal_handler)
88
+ except NotImplementedError:
89
+ pass
90
+
91
+ try:
92
+ # Start Telegram Application polling
93
+ await tg_app.initialize()
94
+ await tg_app.start()
95
+ await tg_app.updater.start_polling(
96
+ poll_interval=1.0,
97
+ timeout=config.telegram_poll_timeout_seconds,
98
+ drop_pending_updates=True,
99
+ )
100
+ logger.info("Telegram Bot long polling started successfully.")
101
+
102
+ # Start background scheduler task if enabled
103
+ if scheduler:
104
+ scheduler.start()
105
+ logger.info(f"Always-On scheduler active (Interval: {interval_minutes} minutes).")
106
+
107
+ print(f"AMEVA-WoL Gateway running in {'Always-On' if always_on else 'Default'} mode. Press Ctrl+C to exit.")
108
+
109
+ # Wait for shutdown signal
110
+ await stop_event.wait()
111
+
112
+ except asyncio.CancelledError:
113
+ logger.info("Main loop task cancelled.")
114
+ except Exception as err:
115
+ logger.error(f"Unhandled exception in main application loop: {err}", exc_info=True)
116
+ finally:
117
+ logger.info("Shutting down AMEVA-WoL components...")
118
+
119
+ if scheduler:
120
+ await scheduler.stop()
121
+
122
+ try:
123
+ if tg_app.updater and tg_app.updater.running:
124
+ await tg_app.updater.stop()
125
+ if tg_app.running:
126
+ await tg_app.stop()
127
+ await tg_app.shutdown()
128
+ except Exception as err:
129
+ logger.warning(f"Error shutting down Telegram application: {err}")
130
+
131
+ lock.release()
132
+ logger.info("AMEVA-WoL Gateway shutdown complete.")
133
+
134
+ return 0
135
+
136
+
137
+ def run_app(always_on: bool = False, interval_minutes: int = 5) -> int:
138
+ """Synchronous launcher wrapper for main_async."""
139
+ try:
140
+ return asyncio.run(main_async(always_on=always_on, interval_minutes=interval_minutes))
141
+ except KeyboardInterrupt:
142
+ print("\nProcess interrupted. Exiting.")
143
+ return 0
ameva_wol/cli.py ADDED
@@ -0,0 +1,203 @@
1
+ """Command-line interface (CLI) argument parser and management utilities for AMEVA-WoL."""
2
+
3
+ import argparse
4
+ import asyncio
5
+ import sys
6
+ from pathlib import Path
7
+ from typing import List, Optional
8
+
9
+ from ameva_wol import __version__
10
+ from ameva_wol.config import Config, ConfigurationError
11
+ from ameva_wol.locking import InstanceLock, InstanceLockError
12
+ from ameva_wol.registry import DeviceRegistry
13
+ from ameva_wol.scheduler import validate_interval_minutes
14
+ from ameva_wol.security import redact_secrets
15
+
16
+
17
+ def create_parser() -> argparse.ArgumentParser:
18
+ """Create command-line argument parser."""
19
+ parser = argparse.ArgumentParser(
20
+ prog="ameva-wol",
21
+ description="AMEVA-WoL: Lightweight, secure Telegram-controlled Wake-on-LAN gateway.",
22
+ formatter_class=argparse.RawDescriptionHelpFormatter,
23
+ epilog=(
24
+ "Examples:\n"
25
+ " python -m ameva_wol # Run in default Telegram-only mode\n"
26
+ " python -m ameva_wol --always-on # Run Always-On mode with 5-minute interval\n"
27
+ " python -m ameva_wol --always-on 15 # Run Always-On mode with 15-minute interval\n"
28
+ " python -m ameva_wol --check-config # Validate configuration and data files\n"
29
+ " python -m ameva_wol --list-devices # Print registered devices to console\n"
30
+ ),
31
+ )
32
+
33
+ parser.add_argument(
34
+ "-v", "--version", action="version", version=f"%(prog)s {__version__}"
35
+ )
36
+
37
+ parser.add_argument(
38
+ "--always-on",
39
+ nargs="?",
40
+ const=5,
41
+ type=int,
42
+ metavar="MINUTES",
43
+ help="Enable Always-On periodic ping & auto-wake mode (default interval: 5 minutes).",
44
+ )
45
+
46
+ parser.add_argument(
47
+ "--interval",
48
+ type=int,
49
+ metavar="MINUTES",
50
+ help="Explicit alternative syntax for specifying Always-On interval in minutes.",
51
+ )
52
+
53
+ parser.add_argument(
54
+ "--check-config",
55
+ action="store_true",
56
+ help="Validate configuration, environment secrets, data directory, and exit.",
57
+ )
58
+
59
+ parser.add_argument(
60
+ "--list-devices",
61
+ action="store_true",
62
+ help="Display all currently registered devices from the data directory and exit.",
63
+ )
64
+
65
+ return parser
66
+
67
+
68
+ async def run_check_config() -> int:
69
+ """Perform comprehensive diagnostic verification of environment and storage.
70
+
71
+ Returns:
72
+ 0 on clean success, 1 on validation error.
73
+ """
74
+ if hasattr(sys.stdout, "reconfigure"):
75
+ try:
76
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")
77
+ except Exception:
78
+ pass
79
+
80
+ print("AMEVA-WoL Configuration & Environment Check")
81
+ print("=" * 50)
82
+
83
+ # 1. Load Configuration
84
+ try:
85
+ cfg = Config.load()
86
+ print("[OK] Environment Configuration: VALID")
87
+ redacted_token = redact_secrets(cfg.telegram_bot_token, token=cfg.telegram_bot_token)
88
+ print(f" • Bot Token: {redacted_token[:10]}... [Redacted]")
89
+ print(f" • Allowed User IDs: {sorted(list(cfg.allowed_user_ids))}")
90
+ print(f" • Allowed Chat IDs: {sorted(list(cfg.allowed_chat_ids)) if cfg.allowed_chat_ids else 'Disabled (All chats)'}")
91
+ print(f" • Default Broadcast: {cfg.default_broadcast}")
92
+ print(f" • Default WoL Port: {cfg.default_wol_port}")
93
+ print(f" • Log Level: {cfg.log_level}")
94
+ print(f" • Data Directory: {cfg.data_dir}")
95
+ except ConfigurationError as err:
96
+ print(f"[FAIL] Environment Configuration ERROR: {err}")
97
+ return 1
98
+ except Exception as err:
99
+ print(f"[FAIL] Unexpected Error Loading Config: {err}")
100
+ return 1
101
+
102
+ # 2. Data Directory & Locking Check
103
+ try:
104
+ lock = InstanceLock(cfg.data_dir)
105
+ lock.acquire()
106
+ lock.release()
107
+ print("[OK] Data Directory & Instance Lock: OK")
108
+ except InstanceLockError as err:
109
+ print(f"[FAIL] Instance Lock Check ERROR: {err}")
110
+ return 1
111
+ except Exception as err:
112
+ print(f"[FAIL] Data Directory Permission ERROR: {err}")
113
+ return 1
114
+
115
+ # 3. Registry JSON Check
116
+ try:
117
+ registry = DeviceRegistry(cfg.data_dir)
118
+ devices = await registry.get_all()
119
+ print(f"[OK] Device Registry: OK ({len(devices)} device(s) registered)")
120
+ for alias, dev in devices.items():
121
+ print(f" • `{alias}` -> MAC: {dev.mac}, IP: {dev.ip or 'None'}, Broadcast: {dev.broadcast}:{dev.port}")
122
+ except Exception as err:
123
+ print(f"[FAIL] Device Registry Read ERROR: {err}")
124
+ return 1
125
+
126
+ print("=" * 50)
127
+ print("All diagnostic checks passed successfully.")
128
+ return 0
129
+
130
+
131
+ async def run_list_devices() -> int:
132
+ """Read and display registered devices to stdout."""
133
+ if hasattr(sys.stdout, "reconfigure"):
134
+ try:
135
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")
136
+ except Exception:
137
+ pass
138
+
139
+ try:
140
+ cfg = Config.load()
141
+ registry = DeviceRegistry(cfg.data_dir)
142
+ devices = await registry.get_all()
143
+
144
+ if not devices:
145
+ print("No devices currently registered.")
146
+ return 0
147
+
148
+ print(f"Registered Devices ({len(devices)}):")
149
+ for alias in sorted(devices.keys()):
150
+ dev = devices[alias]
151
+ print(f" - Alias: {dev.alias}")
152
+ print(f" MAC: {dev.mac}")
153
+ print(f" IP: {dev.ip or 'Not configured'}")
154
+ print(f" Broadcast: {dev.broadcast}")
155
+ print(f" Port: {dev.port}")
156
+ print(f" Updated: {dev.updated_at}")
157
+ print()
158
+ return 0
159
+ except Exception as err:
160
+ print(f"Error listing devices: {err}", file=sys.stderr)
161
+ return 1
162
+
163
+
164
+ def main(argv: Optional[List[str]] = None) -> int:
165
+ """Main CLI entrypoint function."""
166
+ parser = create_parser()
167
+ args = parser.parse_args(argv)
168
+
169
+ if args.check_config:
170
+ return asyncio.run(run_check_config())
171
+
172
+ if args.list_devices:
173
+ return asyncio.run(run_list_devices())
174
+
175
+ # Resolve Always-On interval from --always-on or --interval
176
+ always_on_enabled = False
177
+ interval_minutes = 5
178
+
179
+ if args.interval is not None:
180
+ always_on_enabled = True
181
+ interval_minutes = args.interval
182
+ elif args.always_on is not None:
183
+ always_on_enabled = True
184
+ interval_minutes = args.always_on
185
+
186
+ if always_on_enabled:
187
+ try:
188
+ interval_minutes = validate_interval_minutes(interval_minutes)
189
+ except ValueError as err:
190
+ print(f"Error: {err}", file=sys.stderr)
191
+ return 1
192
+
193
+ # Import app inside main execution path
194
+ from ameva_wol.app import run_app
195
+
196
+ try:
197
+ return run_app(always_on=always_on_enabled, interval_minutes=interval_minutes)
198
+ except KeyboardInterrupt:
199
+ print("\nShutdown requested by user. Exiting cleanly.")
200
+ return 0
201
+ except Exception as err:
202
+ print(f"Fatal Application Error: {err}", file=sys.stderr)
203
+ return 1