]> www.average.org Git - loctrkd.git/blob - loctrkd/beesure.py
9b0255c2401a7d65f817afcb7363d9190122f073
[loctrkd.git] / loctrkd / beesure.py
1 """
2 Implementation of the protocol "beesure" used by some watch-trackers
3 https://www.4p-touch.com/beesure-gps-setracker-server-protocol.html
4 """
5
6 from datetime import datetime, timezone
7 from enum import Enum
8 from inspect import isclass
9 import re
10 from struct import error, pack, unpack
11 from time import time
12 from typing import (
13     Any,
14     Callable,
15     Dict,
16     List,
17     Optional,
18     Tuple,
19     Type,
20     TYPE_CHECKING,
21     Union,
22 )
23
24 __all__ = (
25     "Stream",
26     "class_by_prefix",
27     "inline_response",
28     "parse_message",
29     "probe_buffer",
30     "proto_by_name",
31     "proto_name",
32     "DecodeError",
33     "Respond",
34     "LK",
35 )
36
37 PROTO_PREFIX = "BS:"
38
39 ### Deframer ###
40
41 MAXBUFFER: int = 65557  # Theoretical max buffer 65536 + 21
42 RE = re.compile(b"\[(\w\w)\*(\d{10})\*([0-9a-fA-F]{4})\*")
43
44
45 def _framestart(buffer: bytes) -> Tuple[int, str, str, int]:
46     """
47     Find the start of the frame in the buffer.
48     If found, return (offset, vendorId, imei, datalen) tuple.
49     If not found, set -1 as the value of `offset`
50     """
51     mo = RE.search(buffer)
52     return (
53         (
54             mo.start(),
55             mo.group(1).decode(),
56             mo.group(2).decode(),
57             int(mo.group(3), 16),
58         )
59         if mo
60         else (-1, "", "", 0)
61     )
62
63
64 class Stream:
65     def __init__(self) -> None:
66         self.buffer = b""
67         self.imei: Optional[str] = None
68         self.datalen: int = 0
69
70     @staticmethod
71     def enframe(buffer: bytes, imei: Optional[str] = None) -> bytes:
72         assert imei is not None and len(imei) == 10
73         return f"[LT*{imei:10s}*{len(buffer):04X}*".encode() + buffer + b"]"
74
75     def recv(self, segment: bytes) -> List[Union[bytes, str]]:
76         """
77         Process next segment of the stream. Return successfully deframed
78         packets as `bytes` and error messages as `str`.
79         """
80         when = time()
81         self.buffer += segment
82         if len(self.buffer) > MAXBUFFER:
83             # We are receiving junk. Let's drop it or we run out of memory.
84             self.buffer = b""
85             return [f"More than {MAXBUFFER} unparseable data, dropping"]
86         msgs: List[Union[bytes, str]] = []
87         while True:
88             if not self.datalen:  # we have not seen packet start yet
89                 toskip, _, imei, datalen = _framestart(self.buffer)
90                 if toskip < 0:  # No frames, continue reading
91                     break
92                 if toskip > 0:  # Should not happen, report
93                     msgs.append(
94                         f"Skipping {toskip} bytes of undecodable data"
95                         f' "{self.buffer[:toskip][:64]=!r}"'
96                     )
97                     self.buffer = self.buffer[toskip:]
98                     # From this point, buffer starts with a packet header
99                 if self.imei is not None and self.imei != imei:
100                     msgs.append(
101                         f"Packet's imei {imei} mismatches"
102                         f" previous value {self.imei}"
103                     )
104                 self.imei = imei
105                 self.datalen = datalen
106             if len(self.buffer) < self.datalen + 21:  # Incomplete packet
107                 break
108             # At least one complete packet is present in the buffer
109             if chr(self.buffer[self.datalen + 20]) == "]":
110                 msgs.append(self.buffer[: self.datalen + 21])
111             else:
112                 msgs.append(
113                     f"Packet does not end with ']'"
114                     f" at {self.datalen+20}: {self.buffer=!r}"
115                 )
116             self.buffer = self.buffer[self.datalen + 21 :]
117             self.datalen = 0
118         return msgs
119
120     def close(self) -> bytes:
121         ret = self.buffer
122         self.buffer = b""
123         self.imei = None
124         self.datalen = 0
125         return ret
126
127
128 ### Parser/Constructor ###
129
130
131 class DecodeError(Exception):
132     def __init__(self, e: Exception, **kwargs: Any) -> None:
133         super().__init__(e)
134         for k, v in kwargs.items():
135             setattr(self, k, v)
136
137
138 def maybe(typ: type) -> Callable[[Any], Any]:
139     return lambda x: None if x is None else typ(x)
140
141
142 def intx(x: Union[str, int]) -> int:
143     if isinstance(x, str):
144         x = int(x, 0)
145     return x
146
147
148 def boolx(x: Union[str, bool]) -> bool:
149     if isinstance(x, str):
150         if x.upper() in ("ON", "TRUE", "1"):
151             return True
152         if x.upper() in ("OFF", "FALSE", "0"):
153             return False
154         raise ValueError(str(x) + " could not be parsed as a Boolean")
155     return x
156
157
158 class MetaPkt(type):
159     """
160     For each class corresponding to a message, automatically create
161     two nested classes `In` and `Out` that also inherit from their
162     "nest". Class attribute `IN_KWARGS` defined in the "nest" is
163     copied to the `In` nested class under the name `KWARGS`, and
164     likewise, `OUT_KWARGS` of the nest class is copied as `KWARGS`
165     to the nested class `Out`. In addition, method `encode` is
166     defined in both classes equal to `in_encode()` and `out_encode()`
167     respectively.
168     """
169
170     if TYPE_CHECKING:
171
172         def __getattr__(self, name: str) -> Any:
173             pass
174
175         def __setattr__(self, name: str, value: Any) -> None:
176             pass
177
178     def __new__(
179         cls: Type["MetaPkt"],
180         name: str,
181         bases: Tuple[type, ...],
182         attrs: Dict[str, Any],
183     ) -> "MetaPkt":
184         newcls = super().__new__(cls, name, bases, attrs)
185         newcls.In = super().__new__(
186             cls,
187             name + ".In",
188             (newcls,) + bases,
189             {
190                 "KWARGS": newcls.IN_KWARGS,
191                 "decode": newcls.in_decode,
192                 "encode": newcls.in_encode,
193             },
194         )
195         newcls.Out = super().__new__(
196             cls,
197             name + ".Out",
198             (newcls,) + bases,
199             {
200                 "KWARGS": newcls.OUT_KWARGS,
201                 "decode": newcls.out_decode,
202                 "encode": newcls.out_encode,
203             },
204         )
205         return newcls
206
207
208 class Respond(Enum):
209     NON = 0  # Incoming, no response needed
210     INL = 1  # Birirectional, use `inline_response()`
211     EXT = 2  # Birirectional, use external responder
212
213
214 class BeeSurePkt(metaclass=MetaPkt):
215     RESPOND = Respond.NON  # Do not send anything back by default
216     PROTO: str
217     IN_KWARGS: Tuple[Tuple[str, Callable[[Any], Any], Any], ...] = ()
218     OUT_KWARGS: Tuple[Tuple[str, Callable[[Any], Any], Any], ...] = ()
219     KWARGS: Tuple[Tuple[str, Callable[[Any], Any], Any], ...] = ()
220     In: Type["BeeSurePkt"]
221     Out: Type["BeeSurePkt"]
222
223     if TYPE_CHECKING:
224
225         def __getattr__(self, name: str) -> Any:
226             pass
227
228         def __setattr__(self, name: str, value: Any) -> None:
229             pass
230
231     def __init__(self, *args: Any, **kwargs: Any):
232         """
233         Construct the object _either_ from (length, payload),
234         _or_ from the values of individual fields
235         """
236         assert not args or (len(args) == 4 and not kwargs)
237         if args:  # guaranteed to be two arguments at this point
238             self.vendor, self.imei, self.datalength, self.payload = args
239             try:
240                 self.decode(*self.payload)
241             except error as e:
242                 raise DecodeError(e, obj=self)
243         else:
244             for kw, typ, dfl in self.KWARGS:
245                 setattr(self, kw, typ(kwargs.pop(kw, dfl)))
246             if kwargs:
247                 raise ValueError(
248                     self.__class__.__name__ + " stray kwargs " + str(kwargs)
249                 )
250
251     def __repr__(self) -> str:
252         return "{}({})".format(
253             self.__class__.__name__,
254             ", ".join(
255                 "{}={}".format(
256                     k,
257                     'bytes.fromhex("{}")'.format(v.hex())
258                     if isinstance(v, bytes)
259                     else v.__repr__(),
260                 )
261                 for k, v in self.__dict__.items()
262                 if not k.startswith("_")
263             ),
264         )
265
266     def decode(self, *args: str) -> None:
267         ...
268
269     def in_decode(self, *args: str) -> None:
270         # Overridden in subclasses, otherwise do not decode payload
271         return
272
273     def out_decode(self, *args: str) -> None:
274         # Overridden in subclasses, otherwise do not decode payload
275         return
276
277     def encode(self) -> str:
278         ...
279
280     def in_encode(self) -> str:
281         # Necessary to emulate terminal, which is not implemented
282         raise NotImplementedError(
283             self.__class__.__name__ + ".encode() not implemented"
284         )
285
286     def out_encode(self) -> str:
287         # Overridden in subclasses, otherwise command verb only
288         return self.PROTO
289
290     @property
291     def packed(self) -> bytes:
292         return self.encode().encode()  # first is object's, second str's
293
294
295 class UNKNOWN(BeeSurePkt):
296     PROTO = "UNKNOWN"
297
298
299 class LK(BeeSurePkt):
300     PROTO = "LK"
301     RESPOND = Respond.INL
302
303     def in_decode(self, *args: str) -> None:
304         numargs = len(args)
305         if numargs > 1:
306             self.step = args[1]
307         if numargs > 2:
308             self.tumbling_number = args[2]
309         if numargs > 3:
310             self.battery_percentage = args[3]
311
312     def in_encode(self) -> str:
313         return "LK"
314
315
316 class CONFIG(BeeSurePkt):
317     PROTO = "CONFIG"
318     RESPOND = Respond.INL
319
320
321 class UD(BeeSurePkt):
322     PROTO = "UD"
323
324     def in_decode(self, *args: str) -> None:
325         (
326             _,
327             self.date,
328             self.time,
329             self.gps_valid,
330             self.lat,
331             self.nors,
332             self.lon,
333             self.eorw,
334             self.speed,
335             self.direction,
336             self.altitude,
337             self.num_of_sats,
338             self.gsm_strength_percentage,
339             self.battery_percentage,
340             self.pedometer,
341             self.tubmling_times,
342             self.device_status,
343         ) = args[:17]
344         rest_args = args[17:]
345         self.base_stations_number = int(rest_args[0])
346         self.base_stations = rest_args[1 : 4 + 3 * self.base_stations_number]
347         rest_args = rest_args[3 + 3 * self.base_stations_number + 1 :]
348         self.wifi_ap_number = int(rest_args[0])
349         self.wifi_ap = rest_args[1 : self.wifi_ap_number]
350         # rest_args = rest_args[self_wifi_ap_number+1:]
351         self.positioning_accuracy = rest_args[-1]
352
353
354 class UD2(BeeSurePkt):
355     PROTO = "UD2"
356
357
358 class TKQ(BeeSurePkt):
359     PROTO = "TKQ"
360     RESPOND = Respond.INL
361
362
363 class TKQ2(BeeSurePkt):
364     PROTO = "TKQ2"
365     RESPOND = Respond.INL
366
367
368 class AL(BeeSurePkt):
369     PROTO = "AL"
370     RESPOND = Respond.INL
371
372
373 # Build dicts protocol number -> class and class name -> protocol number
374 CLASSES = {}
375 PROTOS = {}
376 if True:  # just to indent the code, sorry!
377     for cls in [
378         cls
379         for name, cls in globals().items()
380         if isclass(cls)
381         and issubclass(cls, BeeSurePkt)
382         and not name.startswith("_")
383     ]:
384         if hasattr(cls, "PROTO"):
385             CLASSES[cls.PROTO] = cls
386             PROTOS[cls.__name__] = cls.PROTO
387
388
389 def class_by_prefix(
390     prefix: str,
391 ) -> Union[Type[BeeSurePkt], List[Tuple[str, str]]]:
392     lst = [
393         (name, proto)
394         for name, proto in PROTOS.items()
395         if name.upper().startswith(prefix.upper())
396     ]
397     if len(lst) != 1:
398         return lst
399     _, proto = lst[0]
400     return CLASSES[proto]
401
402
403 def proto_name(obj: Union[MetaPkt, BeeSurePkt]) -> str:
404     return PROTO_PREFIX + (
405         obj.__class__.__name__ if isinstance(obj, BeeSurePkt) else obj.__name__
406     )
407
408
409 def proto_by_name(name: str) -> str:
410     return PROTO_PREFIX + PROTOS.get(name, "UNKNOWN")
411
412
413 def proto_of_message(packet: bytes) -> str:
414     return PROTO_PREFIX + packet.split(b",")[0].decode()
415
416
417 def imei_from_packet(packet: bytes) -> Optional[str]:
418     toskip, _, imei, _ = _framestart(packet)
419     if toskip == 0 and imei != "":
420         return imei
421     return None
422
423
424 def is_goodbye_packet(packet: bytes) -> bool:
425     return False
426
427
428 def inline_response(packet: bytes) -> Optional[bytes]:
429     proto = packet[20:-1].split(b",")[0].decode()
430     if proto in CLASSES:
431         cls = CLASSES[proto]
432         if cls.RESPOND is Respond.INL:
433             return cls.Out().packed
434     return None
435
436
437 def probe_buffer(buffer: bytes) -> bool:
438     return bool(RE.search(buffer))
439
440
441 def parse_message(packet: bytes, is_incoming: bool = True) -> BeeSurePkt:
442     """From a packet (without framing bytes) derive the XXX.In object"""
443     toskip, vendor, imei, datalength = _framestart(packet)
444     payload = packet[20:-1].decode().split(",")
445     proto = payload[0] if len(payload) > 0 else ""
446     if proto not in CLASSES:
447         cause: Union[DecodeError, ValueError, IndexError] = ValueError(
448             f"Proto {proto} is unknown"
449         )
450     else:
451         try:
452             if is_incoming:
453                 return CLASSES[proto].In(vendor, imei, datalength, payload)
454             else:
455                 return CLASSES[proto].Out(vendor, imei, datalength, payload)
456         except (DecodeError, ValueError, IndexError) as e:
457             cause = e
458     if is_incoming:
459         retobj = UNKNOWN.In(vendor, imei, datalength, payload)
460     else:
461         retobj = UNKNOWN.Out(vendor, imei, datalength, payload)
462     retobj.PROTO = proto  # Override class attr with object attr
463     retobj.cause = cause
464     return retobj