linknlink 0.2.0__tar.gz → 0.2.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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: linknlink
3
- Version: 0.2.0
3
+ Version: 0.2.2
4
4
  Summary: Python API for controlling linknlink devices
5
5
  Home-page: https://github.com/xuanxuan000/python-linknlink
6
6
  Author: Zhao Zehua
@@ -6,7 +6,7 @@ import typing as t
6
6
  from . import exceptions as e
7
7
  from .const import DEFAULT_BCAST_ADDR, DEFAULT_PORT, DEFAULT_TIMEOUT
8
8
  from .device import Device, scan, ping
9
- from .remote import ehub
9
+ from .remote import ehub, eremote
10
10
  from .sensor import motion, eths
11
11
 
12
12
  SUPPORTED_TYPES = {
@@ -19,6 +19,9 @@ SUPPORTED_TYPES = {
19
19
  ehub: {
20
20
  0x520B: ("eHub", "LinknLink"),
21
21
  },
22
+ eremote: {
23
+ 0xAC99: ("eRemote", "LinknLink"),
24
+ },
22
25
  }
23
26
 
24
27
 
@@ -45,7 +48,7 @@ def gendevice(
45
48
  manufacturer=manufacturer,
46
49
  is_locked=is_locked,
47
50
  )
48
- return Device(host, mac, dev_type, name=name, is_locked=is_locked)
51
+ return Device(host, mac, dev_type, name=name, model=model, manufacturer=manufacturer, is_locked=is_locked)
49
52
 
50
53
 
51
54
  def hello(
@@ -0,0 +1,9 @@
1
+ """Constants."""
2
+ DEFAULT_BCAST_ADDR = "255.255.255.255"
3
+ DEFAULT_PORT = 80
4
+ DEFAULT_RETRY_INTVL = 1
5
+ DEFAULT_TIMEOUT = 10
6
+
7
+ PID_DOORSENSOR = "00000000000000000000000073150100"
8
+ PID_HUMITURE = "0000000000000000000000006e150100"
9
+ PID_REMOTE = "00000000000000000000000074150100"
@@ -109,6 +109,7 @@ class Device:
109
109
  model: str = "",
110
110
  manufacturer: str = "",
111
111
  is_locked: bool = False,
112
+ cb: callable = None,
112
113
  ) -> None:
113
114
  """Initialize the controller."""
114
115
  self.host = host
@@ -124,6 +125,7 @@ class Device:
124
125
  self.id = 0
125
126
  self.type = self.TYPE # For backwards compatibility.
126
127
  self.lock = threading.Lock()
128
+ self.cb = cb
127
129
 
128
130
  self.aes = None
129
131
  self.update_aes(bytes.fromhex(self.__INIT_KEY))
@@ -344,6 +346,20 @@ class Device:
344
346
  packet[0x04:0x06] = p_checksum.to_bytes(2, "little")
345
347
 
346
348
  return packet
349
+
350
+ def build_cmdstuV2(self, cmd: int, payload: bytes = b"") -> bytes:
351
+ """Build a command to send."""
352
+ packet = bytearray(0x0C)
353
+ packet[0x00:0x04] = bytes.fromhex("a5a55a5a")
354
+ packet[0x06:0x08] = cmd.to_bytes(2, "little")
355
+ packet[0x08:0x10] = len(payload).to_bytes(2, "little")
356
+ packet[0x10:0x12] = [0, 0]
357
+ if len(payload):
358
+ packet.extend(payload)
359
+ p_checksum = sum(packet, 0xBEAF) & 0xFFFF
360
+ # p_checksum = sum(payload, p_checksum) & 0xFFFF
361
+ packet[0x04:0x06] = p_checksum.to_bytes(2, "little")
362
+ return packet
347
363
 
348
364
  def analysis_data(self, payload: bytes):
349
365
  """Build a command to send."""
@@ -0,0 +1,263 @@
1
+ """Support for universal remotes."""
2
+ import struct
3
+ import socket
4
+ import time
5
+ import threading
6
+ from typing import Tuple
7
+
8
+ from linknlink.const import DEFAULT_TIMEOUT
9
+
10
+ from . import exceptions as e
11
+ from .device import Device
12
+ from .device import Device
13
+ from.const import PID_DOORSENSOR, PID_HUMITURE, PID_REMOTE
14
+ import json
15
+ import typing as t
16
+
17
+ class ehub(Device):
18
+ """Controls a LinknLink ehub."""
19
+
20
+ TYPE = "EHUB"
21
+
22
+ # sensor function
23
+ def _send(self, command: int, data: bytes = b"") -> bytes:
24
+ """Send a packet to the device."""
25
+ packet = struct.pack("<HI", len(data) + 4, command) + data
26
+ resp = self.send_packet(0x6A, packet)
27
+ e.check_error(resp[0x22:0x24])
28
+ payload = self.decrypt(resp[0x38:])
29
+ p_len = struct.unpack("<H", payload[:0x2])[0]
30
+ return payload[0x6 : p_len + 2]
31
+
32
+ def check_sensors(self) -> dict:
33
+ """Return the state of the sensors."""
34
+ resp = self._send(0x24)
35
+ return {
36
+ "envtemp": resp[0x0] + resp[0x1] / 100.0,
37
+ "envhumid": resp[0x2] + resp[0x3] / 100.0,
38
+ "pir_detected": resp[0x6],
39
+ }
40
+
41
+ def check_temperature(self) -> float:
42
+ """Return the temperature."""
43
+ return self.check_sensors()["temperature"]
44
+
45
+ def check_humidity(self) -> float:
46
+ """Return the humidity."""
47
+ return self.check_sensors()["humidity"]
48
+
49
+ def check_pir(self) -> str:
50
+ """Return the pirDetected."""
51
+ return self.check_sensors()["pir_detected"]
52
+
53
+ # remote function
54
+ def sweep_frequency(self) -> None:
55
+ """Sweep frequency."""
56
+ self._send(0x19)
57
+
58
+ def check_frequency(self) -> bool:
59
+ """Return True if the frequency was identified successfully."""
60
+ resp = self._send(0x1A)
61
+ return resp[0] == 1
62
+
63
+ def find_rf_packet(self) -> None:
64
+ """Enter radiofrequency learning mode."""
65
+ self._send(0x1B)
66
+
67
+ def cancel_sweep_frequency(self) -> None:
68
+ """Cancel sweep frequency."""
69
+ self._send(0x1E)
70
+
71
+ def update(self) -> None:
72
+ """Update device name and lock status."""
73
+ resp = self._send(0x1)
74
+ self.name = resp[0x48:].split(b"\x00")[0].decode()
75
+ self.is_locked = bool(resp[0x87])
76
+
77
+ def send_data(self, data: bytes) -> None:
78
+ """Send a code to the device."""
79
+ self._send(0x2, data)
80
+
81
+ def enter_learning(self) -> None:
82
+ """Enter infrared learning mode."""
83
+ self._send(0x3)
84
+
85
+ def check_data(self) -> bytes:
86
+ """Return the last captured code."""
87
+ return self._send(0x4)
88
+
89
+ class eremote(Device):
90
+ """Controls a LinknLink eremote."""
91
+
92
+ TYPE = "EREMOTE"
93
+ UdpFlag = False
94
+ Port = 61212
95
+
96
+ def _send(self, command: int, data: bytes = b"") -> bytes:
97
+ """Send a packet to the device."""
98
+ packet = struct.pack("<HI", len(data) + 4, command) + data
99
+ resp = self.send_packet(0x6A, packet)
100
+ e.check_error(resp[0x22:0x24])
101
+ payload = self.decrypt(resp[0x38:])
102
+ p_len = struct.unpack("<H", payload[:0x2])[0]
103
+ return payload[0x6 : p_len + 2]
104
+
105
+ def _sendV2(self, command: int, data: bytes = b"") -> bytes:
106
+ """Send a packet to the device."""
107
+ cmdstu = self.build_cmdstuV2(command, data)
108
+ resp = self.send_packet(0x6A, cmdstu)
109
+ e.check_error(resp[0x22:0x24])
110
+ payload = self.decrypt(resp[0x38:])
111
+ res = self.analysis_data(payload)
112
+ return res[2]
113
+
114
+ def startUdpServer(self):
115
+ # 创建一个 UDP socket
116
+ udp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
117
+
118
+ # 绑定服务器地址和端口
119
+ server_address = ('', self.Port) # 绑定到所有网络接口
120
+ try:
121
+ udp_server_socket.bind(server_address)
122
+ except OSError as e:
123
+ if e.errno == socket.errno.EADDRINUSE:
124
+ # print(f"端口{self.Port}已被占用")
125
+ self.Port += 1
126
+ return self.startUdpServer()
127
+ else:
128
+ raise e
129
+
130
+ # print(f"UDP 服务器已在{self.Port}启动,等待客户端连接...")
131
+
132
+ # 接收数据并发送响应
133
+ while True:
134
+ # 接收数据
135
+ data, client_address = udp_server_socket.recvfrom(1024)
136
+ print(f"收到来自 {client_address} 的消息:{data.decode('utf-8')}")
137
+
138
+ if self.cb:
139
+ try:
140
+ data_dict = json.loads(data.decode('utf-8'))
141
+ for key, value in data_dict.items():
142
+ if key.startswith("rmkey") and value != 0:
143
+ # print(f"键: {key}, 值: {value}")
144
+ self.cb(key)
145
+ except Exception as e:
146
+ print(e)
147
+
148
+ # 发送响应
149
+ response = "ok"
150
+ udp_server_socket.sendto(response.encode('utf-8'), client_address)
151
+
152
+ def sendTimeout(self) -> bytes:
153
+ """Send a packet to the device."""
154
+ while True:
155
+ data = (("""{"port":%s, "timeout":60}""") % (self.Port)).encode('utf-8')
156
+ print(data)
157
+ print(len(data) + 4)
158
+ packet = struct.pack("<I", 20000) + data
159
+ # packet = struct.pack("<HI", len(data) + 4, 20000) + data
160
+ print(packet.hex())
161
+ try:
162
+ resp = self.send_packet(0x6A, packet)
163
+ except Exception as e:
164
+ print(e)
165
+ print(resp.hex())
166
+ time.sleep(60)
167
+
168
+ def getalldev(self) -> dict:
169
+ """Return the all devices."""
170
+ resp = self._sendV2(0x0b0e, """{"count":16,"index":0,}""".encode('utf-8')) # max 16dev
171
+ try:
172
+ json_string = resp.decode('utf-8')
173
+ json_object = json.loads(json_string)
174
+ except Exception:
175
+ return {}
176
+ # 使用字典推导式创建pid到did的映射
177
+ pid_to_did_map = {}
178
+ for item in json_object['list']:
179
+ pid = item['pid']
180
+ did = item['did']
181
+ if pid in pid_to_did_map:
182
+ pid_to_did_map[pid].append(did)
183
+ else:
184
+ pid_to_did_map[pid] = [did]
185
+ return pid_to_did_map
186
+
187
+ def check_sensors(self) -> dict:
188
+ """Return the state of the sensors."""
189
+ if not self.UdpFlag:
190
+ self.UdpFlag = True
191
+ # 启动一个线程来运行 UDP 服务器
192
+ thread = threading.Thread(target=self.startUdpServer)
193
+ thread.start()
194
+ # 周期向客户端发送超时时间
195
+ thread2 = threading.Thread(target=self.sendTimeout)
196
+ thread2.start()
197
+ big_dict = {}
198
+ pid_to_did_map = self.getalldev()
199
+ # print(pid_to_did_map)
200
+ for pid in PID_HUMITURE, PID_DOORSENSOR, PID_REMOTE:
201
+ if pid in pid_to_did_map:
202
+ for did in pid_to_did_map[pid]:
203
+ resp = self._sendV2(0x0b01, ("""{"did":"%s"}"""%(did)).encode('utf-8'))
204
+ try:
205
+ json_string = resp.decode('utf-8')
206
+ json_object = json.loads(json_string)
207
+ except Exception:
208
+ return {}
209
+ # print(json_object)
210
+ big_dict.update(json_object)
211
+ if "envtemp" in big_dict:
212
+ big_dict["envtemp"] = round(float(big_dict["envtemp"])/100, 2)
213
+ if "envhumid" in big_dict:
214
+ big_dict["envhumid"] = round(float(big_dict["envhumid"])/100, 2)
215
+ return big_dict
216
+
217
+ def check_temperature(self) -> float:
218
+ """Return the temperature."""
219
+ return round(float(self.check_sensors()["envtemp"])/100, 2)
220
+
221
+ def check_humidity(self) -> float:
222
+ """Return the humidity."""
223
+ return round(float(self.check_sensors()["envhumid"])/100, 2)
224
+
225
+ def check_doorsensor(self) -> str:
226
+ """Return the pirDetected."""
227
+ return self.check_sensors()["doorsensor_status"]
228
+
229
+ # remote function
230
+ def sweep_frequency(self) -> None:
231
+ """Sweep frequency."""
232
+ self._send(0x19)
233
+
234
+ def check_frequency(self) -> bool:
235
+ """Return True if the frequency was identified successfully."""
236
+ resp = self._send(0x1A)
237
+ return resp[0] == 1
238
+
239
+ def find_rf_packet(self) -> None:
240
+ """Enter radiofrequency learning mode."""
241
+ self._send(0x1B)
242
+
243
+ def cancel_sweep_frequency(self) -> None:
244
+ """Cancel sweep frequency."""
245
+ self._send(0x1E)
246
+
247
+ def update(self) -> None:
248
+ """Update device name and lock status."""
249
+ resp = self._send(0x1)
250
+ self.name = resp[0x48:].split(b"\x00")[0].decode()
251
+ self.is_locked = bool(resp[0x87])
252
+
253
+ def send_data(self, data: bytes) -> None:
254
+ """Send a code to the device."""
255
+ self._send(0x2, data)
256
+
257
+ def enter_learning(self) -> None:
258
+ """Enter infrared learning mode."""
259
+ self._send(0x3)
260
+
261
+ def check_data(self) -> bytes:
262
+ """Return the last captured code."""
263
+ return self._send(0x4)
@@ -43,7 +43,7 @@ class eths(Device):
43
43
  class motion(eths):
44
44
  """Controls a LinknLink motion."""
45
45
 
46
- TYPE = "MOTION"
46
+ TYPE = "EMOTION"
47
47
 
48
48
  def check_sensors(self) -> dict:
49
49
  """Return the state of the sensors."""
@@ -51,12 +51,10 @@ class motion(eths):
51
51
  try:
52
52
  json_string = resp.decode('utf-8')
53
53
  json_object = json.loads(json_string)
54
- except Exception or "pir_detected" not in json_object:
54
+ except Exception:
55
55
  return {}
56
- return {
57
- "pir_detected": "on" if json_object["pir_detected"] else "off",
58
- }
56
+ return json_object
59
57
 
60
- def check_pir(self) -> str:
58
+ def check_pir(self) -> int:
61
59
  """Return the pirDetected."""
62
60
  return self.check_sensors()["pir_detected"]
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: linknlink
3
- Version: 0.2.0
3
+ Version: 0.2.2
4
4
  Summary: Python API for controlling linknlink devices
5
5
  Home-page: https://github.com/xuanxuan000/python-linknlink
6
6
  Author: Zhao Zehua
@@ -5,7 +5,7 @@
5
5
  from setuptools import setup, find_packages
6
6
 
7
7
 
8
- version = '0.2.0'
8
+ version = '0.2.2'
9
9
 
10
10
  setup(
11
11
  name="linknlink",
@@ -1,5 +0,0 @@
1
- """Constants."""
2
- DEFAULT_BCAST_ADDR = "255.255.255.255"
3
- DEFAULT_PORT = 80
4
- DEFAULT_RETRY_INTVL = 1
5
- DEFAULT_TIMEOUT = 10
@@ -1,77 +0,0 @@
1
- """Support for universal remotes."""
2
- import struct
3
-
4
- from . import exceptions as e
5
- from .device import Device
6
-
7
- class ehub(Device):
8
- """Controls a LinknLink ehub."""
9
-
10
- TYPE = "EHUB"
11
-
12
- # sensor function
13
- def _send(self, command: int, data: bytes = b"") -> bytes:
14
- """Send a packet to the device."""
15
- packet = struct.pack("<HI", len(data) + 4, command) + data
16
- resp = self.send_packet(0x6A, packet)
17
- e.check_error(resp[0x22:0x24])
18
- payload = self.decrypt(resp[0x38:])
19
- p_len = struct.unpack("<H", payload[:0x2])[0]
20
- return payload[0x6 : p_len + 2]
21
-
22
- def check_sensors(self) -> dict:
23
- """Return the state of the sensors."""
24
- resp = self._send(0x24)
25
- return {
26
- "envtemp": resp[0x0] + resp[0x1] / 100.0,
27
- "envhumid": resp[0x2] + resp[0x3] / 100.0,
28
- "pir_detected": "on" if resp[0x6] else "off",
29
- }
30
-
31
- def check_temperature(self) -> float:
32
- """Return the temperature."""
33
- return self.check_sensors()["temperature"]
34
-
35
- def check_humidity(self) -> float:
36
- """Return the humidity."""
37
- return self.check_sensors()["humidity"]
38
-
39
- def check_pir(self) -> str:
40
- """Return the pirDetected."""
41
- return self.check_sensors()["pir_detected"]
42
-
43
- # remote function
44
- def sweep_frequency(self) -> None:
45
- """Sweep frequency."""
46
- self._send(0x19)
47
-
48
- def check_frequency(self) -> bool:
49
- """Return True if the frequency was identified successfully."""
50
- resp = self._send(0x1A)
51
- return resp[0] == 1
52
-
53
- def find_rf_packet(self) -> None:
54
- """Enter radiofrequency learning mode."""
55
- self._send(0x1B)
56
-
57
- def cancel_sweep_frequency(self) -> None:
58
- """Cancel sweep frequency."""
59
- self._send(0x1E)
60
-
61
- def update(self) -> None:
62
- """Update device name and lock status."""
63
- resp = self._send(0x1)
64
- self.name = resp[0x48:].split(b"\x00")[0].decode()
65
- self.is_locked = bool(resp[0x87])
66
-
67
- def send_data(self, data: bytes) -> None:
68
- """Send a code to the device."""
69
- self._send(0x2, data)
70
-
71
- def enter_learning(self) -> None:
72
- """Enter infrared learning mode."""
73
- self._send(0x3)
74
-
75
- def check_data(self) -> bytes:
76
- """Return the last captured code."""
77
- return self._send(0x4)
File without changes
File without changes
File without changes