amv-wol 1.0.2__tar.gz

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.
Files changed (38) hide show
  1. amv_wol-1.0.2/LICENSE +21 -0
  2. amv_wol-1.0.2/PKG-INFO +157 -0
  3. amv_wol-1.0.2/README.md +134 -0
  4. amv_wol-1.0.2/pyproject.toml +57 -0
  5. amv_wol-1.0.2/setup.cfg +4 -0
  6. amv_wol-1.0.2/src/ameva_wol/__init__.py +4 -0
  7. amv_wol-1.0.2/src/ameva_wol/__main__.py +7 -0
  8. amv_wol-1.0.2/src/ameva_wol/app.py +143 -0
  9. amv_wol-1.0.2/src/ameva_wol/cli.py +203 -0
  10. amv_wol-1.0.2/src/ameva_wol/commands.py +767 -0
  11. amv_wol-1.0.2/src/ameva_wol/config.py +196 -0
  12. amv_wol-1.0.2/src/ameva_wol/locking.py +93 -0
  13. amv_wol-1.0.2/src/ameva_wol/logging_config.py +71 -0
  14. amv_wol-1.0.2/src/ameva_wol/models.py +51 -0
  15. amv_wol-1.0.2/src/ameva_wol/ping.py +64 -0
  16. amv_wol-1.0.2/src/ameva_wol/registry.py +178 -0
  17. amv_wol-1.0.2/src/ameva_wol/scheduler.py +158 -0
  18. amv_wol-1.0.2/src/ameva_wol/security.py +180 -0
  19. amv_wol-1.0.2/src/ameva_wol/sysinfo.py +199 -0
  20. amv_wol-1.0.2/src/ameva_wol/tapo_plug.py +157 -0
  21. amv_wol-1.0.2/src/ameva_wol/tapo_registry.py +118 -0
  22. amv_wol-1.0.2/src/ameva_wol/telegram_bot.py +88 -0
  23. amv_wol-1.0.2/src/ameva_wol/utils.py +80 -0
  24. amv_wol-1.0.2/src/ameva_wol/wol.py +110 -0
  25. amv_wol-1.0.2/src/amv_wol.egg-info/PKG-INFO +157 -0
  26. amv_wol-1.0.2/src/amv_wol.egg-info/SOURCES.txt +36 -0
  27. amv_wol-1.0.2/src/amv_wol.egg-info/dependency_links.txt +1 -0
  28. amv_wol-1.0.2/src/amv_wol.egg-info/entry_points.txt +2 -0
  29. amv_wol-1.0.2/src/amv_wol.egg-info/requires.txt +13 -0
  30. amv_wol-1.0.2/src/amv_wol.egg-info/top_level.txt +1 -0
  31. amv_wol-1.0.2/tests/test_commands.py +139 -0
  32. amv_wol-1.0.2/tests/test_config.py +72 -0
  33. amv_wol-1.0.2/tests/test_ping.py +43 -0
  34. amv_wol-1.0.2/tests/test_registry.py +104 -0
  35. amv_wol-1.0.2/tests/test_scheduler.py +71 -0
  36. amv_wol-1.0.2/tests/test_security.py +100 -0
  37. amv_wol-1.0.2/tests/test_tapo.py +30 -0
  38. amv_wol-1.0.2/tests/test_wol.py +69 -0
amv_wol-1.0.2/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 AMEVA-WoL Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
amv_wol-1.0.2/PKG-INFO ADDED
@@ -0,0 +1,157 @@
1
+ Metadata-Version: 2.4
2
+ Name: amv-wol
3
+ Version: 1.0.2
4
+ Summary: Lightweight, secure, Telegram-controlled Wake-on-LAN gateway for Termux and Linux
5
+ Author: AMEVA Team
6
+ License: MIT
7
+ Requires-Python: >=3.10
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: python-telegram-bot<22.0,>=20.0
11
+ Requires-Dist: python-dotenv<2.0.0,>=1.0.0
12
+ Requires-Dist: psutil<6.0.0,>=5.9.0
13
+ Requires-Dist: speedtest-cli<3.0.0,>=2.1.3
14
+ Requires-Dist: httpx<1.0.0,>=0.27.0
15
+ Requires-Dist: plugp100<4.0.0,>=3.5.0
16
+ Provides-Extra: dev
17
+ Requires-Dist: pytest<9.0.0,>=7.4.0; extra == "dev"
18
+ Requires-Dist: pytest-asyncio<1.0.0,>=0.21.0; extra == "dev"
19
+ Requires-Dist: pytest-cov<6.0.0,>=4.1.0; extra == "dev"
20
+ Requires-Dist: ruff<1.0.0,>=0.1.0; extra == "dev"
21
+ Requires-Dist: mypy<2.0.0,>=1.5.0; extra == "dev"
22
+ Dynamic: license-file
23
+
24
+ <div align="center">
25
+ <h1>๐Ÿš€ AMEVA-WoL Gateway</h1>
26
+
27
+ > **Renamed.** Up to 1.0.1 the PyPI project was `ameva-wol` (frozen old account). From 1.0.2 it is **`amv-wol`** (`pip install amv-wol`); the import package `ameva_wol` and the command `ameva-wol` are unchanged. Uninstall the old distribution first: `pip uninstall ameva-wol`.
28
+ <p><strong>Lightweight, Secure Telegram-Controlled Wake-on-LAN & Smart Plug Gateway</strong></p>
29
+ <p><i>Tailored for Android (Termux) & Linux</i></p>
30
+ </div>
31
+
32
+ ---
33
+
34
+ ## ๐ŸŒŸ Overview
35
+
36
+ AMEVA-WoL is an unprivileged Wake-on-LAN (WoL) and Smart Plug control gateway. It operates strictly via outbound Telegram Bot API long pollingโ€”meaning **zero inbound network ports, no HTTP listeners, and no router port forwarding required**.
37
+
38
+ With the new **Tapo P110 Smart Plug integration**, you can now physically control power and monitor energy usage right from Telegram!
39
+
40
+ ๐Ÿ“– For step-by-step bot creation and setup, consult our [Telegram Setup Guide](docs/telegram_setup_guide.md).
41
+
42
+ ---
43
+
44
+ ## โœจ Key Features
45
+
46
+ - ๐Ÿ”‹ **Smart Plug Control**: Natively integrates with TP-Link Tapo (P110) to turn devices on/off, reboot, and check live power consumption.
47
+ - ๐Ÿชถ **Low Overhead**: Idle CPU footprint < 0.1%, RAM consumption ~25โ€“40 MB. Perfect for old Android phones!
48
+ - ๐Ÿ›ก๏ธ **Zero Inbound Exposure**: Outbound long polling over HTTPS eliminates public IP requirements.
49
+ - ๐Ÿ”’ **Ironclad Security**:
50
+ - Commands restricted to whitelisted Telegram `ALLOWED_USER_IDS` and `ALLOWED_CHAT_IDS`.
51
+ - Secret tokens are dynamically redacted from logs.
52
+ - Unprivileged execution (No root/sudo needed).
53
+ - ๐Ÿ”„ **Always-On Monitoring**: Optional background scheduler pings your PCs and sends WoL packets automatically if they go offline.
54
+
55
+ ---
56
+
57
+ ## ๐Ÿ—๏ธ Architecture
58
+
59
+ ```mermaid
60
+ flowchart TD
61
+ A[Telegram Cloud API]
62
+
63
+ subgraph Gateway ["๐Ÿ“ฑ Local Gateway Node (Termux / Linux)"]
64
+ direction TB
65
+ B[AMEVA-WoL Core Engine]
66
+ C[(devices.json Registry)]
67
+ D[Always-On Scheduler]
68
+
69
+ B <--> C
70
+ B --- D
71
+ end
72
+
73
+ subgraph Targets ["๐Ÿ–ฅ๏ธ Target Systems (LAN)"]
74
+ direction TB
75
+ E[Workstation PC]
76
+ F[Tapo P110 Smart Plug]
77
+ end
78
+
79
+ A <-->|HTTPS Long Polling| B
80
+ D -.->|ICMP Ping| E
81
+ B ==>|UDP Magic Packet| E
82
+ B ==>|Wi-Fi Local Control| F
83
+ ```
84
+
85
+ ---
86
+
87
+ ## ๐Ÿš€ Quick Start
88
+
89
+ ### ๐Ÿ“ฑ 1. Termux (Android) ์™•์ดˆ๋ณด ๊ฐ€์ด๋“œ (๋ณต์‚ฌ&๋ถ™์—ฌ๋„ฃ๊ธฐ)
90
+
91
+ **1๋‹จ๊ณ„: ํŒจํ‚ค์ง€ ์„ค์น˜ ๋ฐ ์†Œ์Šค์ฝ”๋“œ ๋‹ค์šด๋กœ๋“œ**
92
+ ```bash
93
+ pkg update -y && pkg upgrade -y
94
+ pkg install python git -y
95
+
96
+ git clone https://github.com/uno-km/AMEVA-WoL.git
97
+ cd AMEVA-WoL
98
+
99
+ python -m venv .venv
100
+ source .venv/bin/activate
101
+
102
+ pip install --upgrade pip
103
+ pip install -r requirements.txt
104
+ ```
105
+
106
+ **2๋‹จ๊ณ„: ํ™˜๊ฒฝ์„ค์ •(.env) ์„ธํŒ…**
107
+ ์•„๋ž˜ ์ƒ์ž ์•ˆ์˜ ๋ด‡ ํ† ํฐ๊ณผ ๋‚ด ID๋ฅผ ๋„ฃ๊ณ  ๋ณต์‚ฌ/๋ถ™์—ฌ๋„ฃ๊ธฐ ํ•˜์„ธ์š”. Tapo ํ”Œ๋Ÿฌ๊ทธ๊ฐ€ ์—†๋‹ค๋ฉด ๊ด€๋ จ ์ค„์€ ๋น„์›Œ๋‘ฌ๋„ ๋ฉ๋‹ˆ๋‹ค.
108
+
109
+ ```bash
110
+ cat << 'EOF' > .env
111
+ TELEGRAM_BOT_TOKEN=์—ฌ๊ธฐ์—_๋ด‡_ํ† ํฐ_์ž…๋ ฅ
112
+ ALLOWED_USER_IDS=์—ฌ๊ธฐ์—_๋‚ด_ํ…”๋ ˆ๊ทธ๋žจ_ID_์ž…๋ ฅ
113
+ DEFAULT_BROADCAST=192.168.0.255
114
+ DEFAULT_WOL_PORT=9
115
+
116
+ EOF
117
+ ```
118
+
119
+ **3๋‹จ๊ณ„: ๋ด‡ ์‹คํ–‰**
120
+ ```bash
121
+ python -m ameva_wol
122
+ ```
123
+
124
+ ---
125
+
126
+ ## ๐Ÿ› ๏ธ Command Reference
127
+
128
+ | Command | Syntax | Description |
129
+ | :--- | :--- | :--- |
130
+ | **`/start`** | `/start` | ๐ŸŸข Check authorization and bot status |
131
+ | **`/wake`** | `/wake [alias\|all]` | โšก Send Wake-on-LAN Magic Packet |
132
+ | **`/power add`** | `/power add <alias> <email> <password> <ip> <mac>`| ๐Ÿ”Œ Register Tapo Plug credentials & PC MAC for WoL simultaneously |
133
+ | **`/power`** | `/power <on\|off\|re\|status> [alias]`| ๐Ÿ”Œ Control Tapo Smart Plug (ON/OFF/Reboot/Power Status). `/power on` also sends a Magic Packet automatically! |
134
+ | **`/status`** | `/status [alias\|all]` | ๐Ÿ” Ping devices to check if they are online |
135
+ | **`/add`** | `/add <alias> <mac> [ip]` | โž• Register a new PC for WoL (if not using Tapo plug) |
136
+ | **`/list`** | `/list` | ๐Ÿ“‹ List all registered devices |
137
+ | **`/remove`**| `/remove <alias>` | ๐Ÿ—‘๏ธ Delete a device from registry |
138
+ | **`/host`** | `/host` | ๐Ÿ“Š View Gateway phone/server stats (CPU, RAM, Network) |
139
+ | **`/how`** | `/how` | ๐Ÿ“– Read detailed user manual |
140
+
141
+ ---
142
+
143
+ ## โš™๏ธ Advanced Execution Modes
144
+
145
+ - **Default Mode** (Telegram commands only):
146
+ ```bash
147
+ python -m ameva_wol
148
+ ```
149
+ - **Always-On Mode** (Polling + 5-minute periodic ping & keep-alive wake):
150
+ ```bash
151
+ python -m ameva_wol --always-on 5
152
+ ```
153
+
154
+ ---
155
+
156
+ ## ๐Ÿ“„ License
157
+ MIT License. See [LICENSE](LICENSE) for details.
@@ -0,0 +1,134 @@
1
+ <div align="center">
2
+ <h1>๐Ÿš€ AMEVA-WoL Gateway</h1>
3
+
4
+ > **Renamed.** Up to 1.0.1 the PyPI project was `ameva-wol` (frozen old account). From 1.0.2 it is **`amv-wol`** (`pip install amv-wol`); the import package `ameva_wol` and the command `ameva-wol` are unchanged. Uninstall the old distribution first: `pip uninstall ameva-wol`.
5
+ <p><strong>Lightweight, Secure Telegram-Controlled Wake-on-LAN & Smart Plug Gateway</strong></p>
6
+ <p><i>Tailored for Android (Termux) & Linux</i></p>
7
+ </div>
8
+
9
+ ---
10
+
11
+ ## ๐ŸŒŸ Overview
12
+
13
+ AMEVA-WoL is an unprivileged Wake-on-LAN (WoL) and Smart Plug control gateway. It operates strictly via outbound Telegram Bot API long pollingโ€”meaning **zero inbound network ports, no HTTP listeners, and no router port forwarding required**.
14
+
15
+ With the new **Tapo P110 Smart Plug integration**, you can now physically control power and monitor energy usage right from Telegram!
16
+
17
+ ๐Ÿ“– For step-by-step bot creation and setup, consult our [Telegram Setup Guide](docs/telegram_setup_guide.md).
18
+
19
+ ---
20
+
21
+ ## โœจ Key Features
22
+
23
+ - ๐Ÿ”‹ **Smart Plug Control**: Natively integrates with TP-Link Tapo (P110) to turn devices on/off, reboot, and check live power consumption.
24
+ - ๐Ÿชถ **Low Overhead**: Idle CPU footprint < 0.1%, RAM consumption ~25โ€“40 MB. Perfect for old Android phones!
25
+ - ๐Ÿ›ก๏ธ **Zero Inbound Exposure**: Outbound long polling over HTTPS eliminates public IP requirements.
26
+ - ๐Ÿ”’ **Ironclad Security**:
27
+ - Commands restricted to whitelisted Telegram `ALLOWED_USER_IDS` and `ALLOWED_CHAT_IDS`.
28
+ - Secret tokens are dynamically redacted from logs.
29
+ - Unprivileged execution (No root/sudo needed).
30
+ - ๐Ÿ”„ **Always-On Monitoring**: Optional background scheduler pings your PCs and sends WoL packets automatically if they go offline.
31
+
32
+ ---
33
+
34
+ ## ๐Ÿ—๏ธ Architecture
35
+
36
+ ```mermaid
37
+ flowchart TD
38
+ A[Telegram Cloud API]
39
+
40
+ subgraph Gateway ["๐Ÿ“ฑ Local Gateway Node (Termux / Linux)"]
41
+ direction TB
42
+ B[AMEVA-WoL Core Engine]
43
+ C[(devices.json Registry)]
44
+ D[Always-On Scheduler]
45
+
46
+ B <--> C
47
+ B --- D
48
+ end
49
+
50
+ subgraph Targets ["๐Ÿ–ฅ๏ธ Target Systems (LAN)"]
51
+ direction TB
52
+ E[Workstation PC]
53
+ F[Tapo P110 Smart Plug]
54
+ end
55
+
56
+ A <-->|HTTPS Long Polling| B
57
+ D -.->|ICMP Ping| E
58
+ B ==>|UDP Magic Packet| E
59
+ B ==>|Wi-Fi Local Control| F
60
+ ```
61
+
62
+ ---
63
+
64
+ ## ๐Ÿš€ Quick Start
65
+
66
+ ### ๐Ÿ“ฑ 1. Termux (Android) ์™•์ดˆ๋ณด ๊ฐ€์ด๋“œ (๋ณต์‚ฌ&๋ถ™์—ฌ๋„ฃ๊ธฐ)
67
+
68
+ **1๋‹จ๊ณ„: ํŒจํ‚ค์ง€ ์„ค์น˜ ๋ฐ ์†Œ์Šค์ฝ”๋“œ ๋‹ค์šด๋กœ๋“œ**
69
+ ```bash
70
+ pkg update -y && pkg upgrade -y
71
+ pkg install python git -y
72
+
73
+ git clone https://github.com/uno-km/AMEVA-WoL.git
74
+ cd AMEVA-WoL
75
+
76
+ python -m venv .venv
77
+ source .venv/bin/activate
78
+
79
+ pip install --upgrade pip
80
+ pip install -r requirements.txt
81
+ ```
82
+
83
+ **2๋‹จ๊ณ„: ํ™˜๊ฒฝ์„ค์ •(.env) ์„ธํŒ…**
84
+ ์•„๋ž˜ ์ƒ์ž ์•ˆ์˜ ๋ด‡ ํ† ํฐ๊ณผ ๋‚ด ID๋ฅผ ๋„ฃ๊ณ  ๋ณต์‚ฌ/๋ถ™์—ฌ๋„ฃ๊ธฐ ํ•˜์„ธ์š”. Tapo ํ”Œ๋Ÿฌ๊ทธ๊ฐ€ ์—†๋‹ค๋ฉด ๊ด€๋ จ ์ค„์€ ๋น„์›Œ๋‘ฌ๋„ ๋ฉ๋‹ˆ๋‹ค.
85
+
86
+ ```bash
87
+ cat << 'EOF' > .env
88
+ TELEGRAM_BOT_TOKEN=์—ฌ๊ธฐ์—_๋ด‡_ํ† ํฐ_์ž…๋ ฅ
89
+ ALLOWED_USER_IDS=์—ฌ๊ธฐ์—_๋‚ด_ํ…”๋ ˆ๊ทธ๋žจ_ID_์ž…๋ ฅ
90
+ DEFAULT_BROADCAST=192.168.0.255
91
+ DEFAULT_WOL_PORT=9
92
+
93
+ EOF
94
+ ```
95
+
96
+ **3๋‹จ๊ณ„: ๋ด‡ ์‹คํ–‰**
97
+ ```bash
98
+ python -m ameva_wol
99
+ ```
100
+
101
+ ---
102
+
103
+ ## ๐Ÿ› ๏ธ Command Reference
104
+
105
+ | Command | Syntax | Description |
106
+ | :--- | :--- | :--- |
107
+ | **`/start`** | `/start` | ๐ŸŸข Check authorization and bot status |
108
+ | **`/wake`** | `/wake [alias\|all]` | โšก Send Wake-on-LAN Magic Packet |
109
+ | **`/power add`** | `/power add <alias> <email> <password> <ip> <mac>`| ๐Ÿ”Œ Register Tapo Plug credentials & PC MAC for WoL simultaneously |
110
+ | **`/power`** | `/power <on\|off\|re\|status> [alias]`| ๐Ÿ”Œ Control Tapo Smart Plug (ON/OFF/Reboot/Power Status). `/power on` also sends a Magic Packet automatically! |
111
+ | **`/status`** | `/status [alias\|all]` | ๐Ÿ” Ping devices to check if they are online |
112
+ | **`/add`** | `/add <alias> <mac> [ip]` | โž• Register a new PC for WoL (if not using Tapo plug) |
113
+ | **`/list`** | `/list` | ๐Ÿ“‹ List all registered devices |
114
+ | **`/remove`**| `/remove <alias>` | ๐Ÿ—‘๏ธ Delete a device from registry |
115
+ | **`/host`** | `/host` | ๐Ÿ“Š View Gateway phone/server stats (CPU, RAM, Network) |
116
+ | **`/how`** | `/how` | ๐Ÿ“– Read detailed user manual |
117
+
118
+ ---
119
+
120
+ ## โš™๏ธ Advanced Execution Modes
121
+
122
+ - **Default Mode** (Telegram commands only):
123
+ ```bash
124
+ python -m ameva_wol
125
+ ```
126
+ - **Always-On Mode** (Polling + 5-minute periodic ping & keep-alive wake):
127
+ ```bash
128
+ python -m ameva_wol --always-on 5
129
+ ```
130
+
131
+ ---
132
+
133
+ ## ๐Ÿ“„ License
134
+ MIT License. See [LICENSE](LICENSE) for details.
@@ -0,0 +1,57 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "amv-wol"
7
+ version = "1.0.2"
8
+ description = "Lightweight, secure, Telegram-controlled Wake-on-LAN gateway for Termux and Linux"
9
+ readme = "README.md"
10
+ authors = [
11
+ { name = "AMEVA Team" }
12
+ ]
13
+ license = { text = "MIT" }
14
+ requires-python = ">=3.10"
15
+ dependencies = [
16
+ "python-telegram-bot>=20.0,<22.0",
17
+ "python-dotenv>=1.0.0,<2.0.0",
18
+ "psutil>=5.9.0,<6.0.0",
19
+ "speedtest-cli>=2.1.3,<3.0.0",
20
+ "httpx>=0.27.0,<1.0.0",
21
+ "plugp100>=3.5.0,<4.0.0",
22
+ ]
23
+
24
+ [project.optional-dependencies]
25
+ dev = [
26
+ "pytest>=7.4.0,<9.0.0",
27
+ "pytest-asyncio>=0.21.0,<1.0.0",
28
+ "pytest-cov>=4.1.0,<6.0.0",
29
+ "ruff>=0.1.0,<1.0.0",
30
+ "mypy>=1.5.0,<2.0.0",
31
+ ]
32
+
33
+ [project.scripts]
34
+ ameva-wol = "ameva_wol.cli:main"
35
+
36
+ [tool.setuptools.packages.find]
37
+ where = ["src"]
38
+
39
+ [tool.pytest.ini_options]
40
+ minversion = "7.0"
41
+ addopts = "-ra -q"
42
+ testpaths = ["tests"]
43
+ asyncio_mode = "auto"
44
+ python_files = ["test_*.py"]
45
+
46
+ [tool.ruff]
47
+ line-length = 100
48
+ target-version = "py310"
49
+
50
+ [tool.ruff.lint]
51
+ select = ["E", "F", "W", "B", "I", "UP", "S"]
52
+ ignore = ["S101"]
53
+
54
+ [tool.mypy]
55
+ python_version = "3.10"
56
+ strict = true
57
+ ignore_missing_imports = true
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -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"
@@ -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())
@@ -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