Repository navigation
Expand file tree
/
Copy pathhunter_node_bt_client.py
More file actions
306 lines (255 loc) · 12.6 KB
/
Copy pathhunter_node_bt_client.py
File metadata and controls
306 lines (255 loc) · 12.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
"""
Hunter NODE-BT reference BLE client (reverse-engineered from com.hunter.nodev2 v6.0.611246).
Transport: Nordic UART Service. Commands are JSON, UTF-8, written in 20-byte chunks
to the RX characteristic; responses are JSON terminated by a NUL (0x00) byte via
notifications on the TX characteristic. A PIN challenge-response login (XOR-obfuscated
6-byte packets on a separate service) is required before commands are accepted.
This is a minimal, dependency-light reference for building a Home Assistant / HACS
integration. Requires: pip install bleak
Verified against decompiled C# (NodeV2.Services.BleDeviceCommunication). Field layouts,
the 0xAC XOR (skip-zero) quirk, and the handshake order match the app exactly.
"""
import asyncio
from datetime import datetime
import importlib.util
import json
from pathlib import Path
try:
from bleak import BleakClient, BleakScanner
except ImportError:
BleakClient = None
BleakScanner = None
_PROTOCOL_PATH = (
Path(__file__).parent
/ "custom_components"
/ "hunter_node_bt"
/ "protocol.py"
)
_PROTOCOL_SPEC = importlib.util.spec_from_file_location(
"hunter_node_bt_protocol", _PROTOCOL_PATH
)
if _PROTOCOL_SPEC is None or _PROTOCOL_SPEC.loader is None:
raise ImportError(f"Cannot load protocol helpers from {_PROTOCOL_PATH}")
_PROTOCOL = importlib.util.module_from_spec(_PROTOCOL_SPEC)
_PROTOCOL_SPEC.loader.exec_module(_PROTOCOL)
# --- GATT UUIDs -------------------------------------------------------------
NUS_SERVICE = "6e400001-b5a3-f393-e0a9-e50e24dcca9e"
MSG_RX = "6e400002-b5a3-f393-e0a9-e50e24dcca9e" # write (app -> device)
MSG_TX = "6e400003-b5a3-f393-e0a9-e50e24dcca9e" # notify (device -> app)
PIN_SERVICE = "0ed3e3d3-8cd8-4f29-8fec-a7d3a2c5443e"
PIN_CHAR = "4c9dbe52-3566-4dfc-a299-4ea1353970e2" # write + notify
CHUNK = _PROTOCOL.CHUNK_SIZE
# PinMessageType
LOGIN_REQUEST = 1
LOGIN_CHALLENGE_REQUEST = 2
LOGIN_CHALLENGE_RESPONSE = 3
LOGIN_CHALLENGE_RESULT = 4
_xor_ac = _PROTOCOL.xor_ac
_pin_info = _PROTOCOL.pin_info
_parse_pin_info = _PROTOCOL.parse_pin_info
sanitize_hunter_json = _PROTOCOL.sanitize_hunter_json
validate_pin = _PROTOCOL.validate_pin
chunk_payload = _PROTOCOL.chunk_payload
to_controller_time = _PROTOCOL.to_controller_time
rain_delay_end = _PROTOCOL.rain_delay_end
class HunterNodeBT:
def __init__(self, address: str, pin: int = 0):
self.address = address
self.pin = validate_pin(pin)
self.client: BleakClient | None = None
self._pin_q: asyncio.Queue = asyncio.Queue()
self._msg_buf = _PROTOCOL.NulDelimitedMessageBuffer()
self._msg_future: asyncio.Future | None = None
# -- notifications -------------------------------------------------------
def _on_pin(self, _char, data: bytearray):
self._pin_q.put_nowait(_parse_pin_info(_xor_ac(bytes(data))))
def _on_msg(self, _char, data: bytearray):
future = self._msg_future
if future is None or future.done():
self._msg_buf.clear()
return
try:
text = self._msg_buf.append(bytes(data))
except _PROTOCOL.MessageTooLargeError as err:
future.set_exception(RuntimeError(str(err)))
return
if text is not None:
future.set_result(text)
async def _next_pin(self, timeout=15):
return await asyncio.wait_for(self._pin_q.get(), timeout)
# -- connection + login --------------------------------------------------
async def connect(self):
self.client = BleakClient(self.address)
await self.client.connect()
await self.client.start_notify(PIN_CHAR, self._on_pin)
await self.client.start_notify(MSG_TX, self._on_msg)
await self._login()
async def _login(self):
# 1) send LoginRequest (PIN characteristic requires write-without-response)
await self.client.write_gatt_char(PIN_CHAR, _xor_ac(_pin_info(LOGIN_REQUEST)), response=False)
# 2) receive challenge (random number)
ptype, result, rnd, _ = await self._next_pin()
if ptype != LOGIN_CHALLENGE_REQUEST or result != 0:
raise RuntimeError(f"login challenge failed: type={ptype} result={result}")
# 3) respond with pin XOR random
resp = _pin_info(LOGIN_CHALLENGE_RESPONSE, random_number=rnd, pin=self.pin ^ rnd)
await self.client.write_gatt_char(PIN_CHAR, _xor_ac(resp), response=False)
# 4) result
ptype, result, _, _ = await self._next_pin()
if ptype != LOGIN_CHALLENGE_RESULT or result != 0:
raise RuntimeError(f"PIN rejected (result={result})")
async def disconnect(self):
if self.client:
await self.client.disconnect()
self.client = None
# -- commands ------------------------------------------------------------
async def send_command(self, cmd: dict, expect_reply: bool = True) -> str | None:
payload = json.dumps(cmd, separators=(",", ":")).encode("utf-8")
if expect_reply:
loop = asyncio.get_running_loop()
self._msg_future = loop.create_future()
self._msg_buf.clear()
try:
for chunk in chunk_payload(payload, CHUNK):
await self.client.write_gatt_char(MSG_RX, chunk, response=True)
if not expect_reply:
return None
try:
raw = await asyncio.wait_for(self._msg_future, 20)
except TimeoutError:
await self.disconnect()
raise
return sanitize_hunter_json(raw)
except asyncio.CancelledError:
await self.disconnect()
raise
except Exception:
await self.disconnect()
raise
finally:
if expect_reply:
self._msg_future = None
self._msg_buf.clear()
async def read_all(self) -> dict:
reply = await self.send_command({"Read": "All"})
return json.loads(reply) if reply else {}
async def read_state(self) -> dict:
reply = await self.send_command({"Read": "Section_State"})
return json.loads(reply) if reply else {}
async def start_station(self, station: int, seconds: int) -> str | None:
return await self.send_command({"Manual": {"StationNumber": station, "RunTime": seconds}})
async def stop_all(self) -> str | None:
return await self.send_command({"Manual": {"StopAll": True}})
async def run_program(self, program: str) -> str | None:
return await self.send_command({"Manual": {"ProgramLetter": program.upper()}})
async def set_rain_delay(self, days: int) -> str | None:
until = rain_delay_end(datetime.now().astimezone(), days) if days > 0 else 0
return await self.send_command({"Controller": {"ProgrammableDaysOff": until}})
async def sync_clock(self) -> str | None:
now = to_controller_time(datetime.now().astimezone())
return await self.send_command({"Controller": {"CurrentTime": now}})
# --- Quick CLI runner -------------------------------------------------------
async def main():
import argparse
import sys
if BleakClient is None or BleakScanner is None:
print("Error: 'bleak' library is not installed.")
print("Please install bleak with: pip install bleak")
sys.exit(1)
parser = argparse.ArgumentParser(description="Hunter NODE-BT BLE CLI Client")
parser.add_argument("--address", "-a", default=None, help="Bluetooth address/UUID (auto-discovered if omitted)")
parser.add_argument("--pin", "-p", type=validate_pin, default=0, help="Security PIN (0-65535)")
subparsers = parser.add_subparsers(dest="cmd", help="Action to perform")
subparsers.add_parser("read-all", help="Read complete controller configuration and state (default)")
subparsers.add_parser("read-state", help="Read current watering state and station progress")
start_p = subparsers.add_parser("start", help="Start manual watering on a station")
start_p.add_argument("station", type=int, help="Station number (1-4)")
start_p.add_argument("seconds", type=int, help="Run duration in seconds")
subparsers.add_parser("stop", help="Stop all active watering")
prog_p = subparsers.add_parser("run-program", help="Run program cycle (A, B, C, or T)")
prog_p.add_argument("letter", choices=["A", "B", "C", "T", "a", "b", "c", "t"], help="Program letter")
delay_p = subparsers.add_parser("rain-delay", help="Suspend scheduled watering for N days (0 cancels)")
delay_p.add_argument("days", type=int, help="Days to delay (0 cancels)")
subparsers.add_parser("sync-clock", help="Set the controller clock to this computer's local time")
raw_p = subparsers.add_parser("raw", help="Send arbitrary raw JSON command to the controller")
raw_p.add_argument("json_str", help="JSON string, e.g. '{\"Manual\":{\"StopAll\":true}}'")
args, unknown = parser.parse_known_args()
address = args.address
pin = args.pin
action = args.cmd or "read-all"
# Backward compatibility: handle positional address and pin (e.g. client.py <MAC> [PIN])
if not address and unknown:
candidate = unknown[0]
if ":" in candidate or "-" in candidate:
address = candidate
if len(unknown) > 1 and unknown[1].isdigit():
pin = validate_pin(unknown[1])
if not address:
print(f"Scanning for NODE-BT controllers (filtering on NUS {NUS_SERVICE} or name)...")
discovered = await BleakScanner.discover(timeout=10.0, return_adv=True)
hunter_matches = []
other_devices = []
for d, adv in discovered.values():
name = d.name or adv.local_name or "Unknown"
uuids = [str(u).lower() for u in adv.service_uuids]
if NUS_SERVICE.lower() in uuids or "hunter" in name.lower() or "node" in name.lower():
hunter_matches.append(d)
print(f" [+] Hunter candidate found: {name} ({d.address}) | RSSI: {adv.rssi} dBm")
else:
other_devices.append((name, d.address))
if not hunter_matches:
print("\nNo Hunter NODE-BT controllers identified automatically.")
if other_devices:
print(f"Found {len(other_devices)} other Bluetooth device(s) nearby:")
for name, addr in other_devices[:10]:
print(f" - {name} ({addr})")
print("\nTip: Make sure the controller is powered on, nearby, and disconnected from the phone app.")
print("You can also run directly with the MAC/UUID: python hunter_node_bt_client.py -a <ADDRESS> [-p PIN]")
return
address = hunter_matches[0].address
print(f"\nProceeding to connect to: {address}")
client = HunterNodeBT(address, pin)
try:
print(f"Connecting to {address}...")
await client.connect()
print(f"Authenticated successfully with PIN {pin}!\n")
if action == "read-all":
print("Reading full state (ReadAll)...")
res = await client.read_all()
print(json.dumps(res, indent=2))
elif action == "read-state":
print("Reading running state (Section_State)...")
res = await client.read_state()
print(json.dumps(res, indent=2))
elif action == "start":
print(f"Starting station {args.station} for {args.seconds} seconds...")
reply = await client.start_station(args.station, args.seconds)
print(f"Controller reply: {reply}")
elif action == "stop":
print("Stopping all active watering...")
reply = await client.stop_all()
print(f"Controller reply: {reply}")
elif action == "run-program":
letter = args.letter.upper()
print(f"Starting program {letter}...")
reply = await client.run_program(letter)
print(f"Controller reply: {reply}")
elif action == "rain-delay":
print("Cancelling rain delay..." if args.days == 0 else f"Setting a {args.days}-day rain delay...")
reply = await client.set_rain_delay(args.days)
print(f"Controller reply: {reply}")
elif action == "sync-clock":
print("Syncing controller clock to local time...")
reply = await client.sync_clock()
print(f"Controller reply: {reply}")
elif action == "raw":
cmd = json.loads(args.json_str)
print(f"Sending raw command: {cmd}")
reply = await client.send_command(cmd)
print(f"Controller reply: {reply}")
except Exception as err:
print(f"\nError communicating with controller: {err}")
finally:
await client.disconnect()
if __name__ == "__main__":
asyncio.run(main())