2 Implementation of the protocol "beesure" used by some watch-trackers
3 https://www.4p-touch.com/beesure-gps-setracker-server-protocol.html
6 from datetime import datetime, timezone
8 from inspect import isclass
10 from struct import error, pack, unpack
42 MAXBUFFER: int = 65557 # Theoretical max buffer 65536 + 21
43 RE = re.compile(b"\[(\w\w)\*(\d{10})\*([0-9a-fA-F]{4})\*")
46 def _framestart(buffer: bytes) -> Tuple[int, str, str, int]:
48 Find the start of the frame in the buffer.
49 If found, return (offset, vendorId, imei, datalen) tuple.
50 If not found, set -1 as the value of `offset`
52 mo = RE.search(buffer)
66 def __init__(self) -> None:
68 self.imei: Optional[str] = None
71 def recv(self, segment: bytes) -> List[Union[bytes, str]]:
73 Process next segment of the stream. Return successfully deframed
74 packets as `bytes` and error messages as `str`.
77 self.buffer += segment
78 if len(self.buffer) > MAXBUFFER:
79 # We are receiving junk. Let's drop it or we run out of memory.
81 return [f"More than {MAXBUFFER} unparseable data, dropping"]
82 msgs: List[Union[bytes, str]] = []
84 if not self.datalen: # we have not seen packet start yet
85 toskip, _, imei, datalen = _framestart(self.buffer)
86 if toskip < 0: # No frames, continue reading
88 if toskip > 0: # Should not happen, report
90 f"Skipping {toskip} bytes of undecodable data"
91 f' "{self.buffer[:toskip][:64]=!r}"'
93 self.buffer = self.buffer[toskip:]
94 # From this point, buffer starts with a packet header
99 f"Packet's imei {imei} mismatches"
100 f" previous value {self.imei}, old value kept"
102 self.datalen = datalen
103 if len(self.buffer) < self.datalen + 21: # Incomplete packet
105 # At least one complete packet is present in the buffer
106 if chr(self.buffer[self.datalen + 20]) == "]":
107 msgs.append(self.buffer[: self.datalen + 21])
110 f"Packet does not end with ']'"
111 f" at {self.datalen+20}: {self.buffer=!r}"
113 self.buffer = self.buffer[self.datalen + 21 :]
117 def close(self) -> bytes:
125 def enframe(buffer: bytes, imei: Optional[str] = None) -> bytes:
126 assert imei is not None and len(imei) == 10
127 off, vid, _, dlen = _framestart(buffer)
129 return f"[{vid:2s}*{imei:10s}*{dlen:04X}*".encode() + buffer[20:]
132 ### Parser/Constructor ###
135 class DecodeError(Exception):
136 def __init__(self, e: Exception, **kwargs: Any) -> None:
138 for k, v in kwargs.items():
142 def maybe(typ: type) -> Callable[[Any], Any]:
143 return lambda x: None if x is None else typ(x)
146 def intx(x: Union[str, int]) -> int:
147 if isinstance(x, str):
152 def boolx(x: Union[str, bool]) -> bool:
153 if isinstance(x, str):
154 if x.upper() in ("ON", "TRUE", "1"):
156 if x.upper() in ("OFF", "FALSE", "0"):
158 raise ValueError(str(x) + " could not be parsed as a Boolean")
164 For each class corresponding to a message, automatically create
165 two nested classes `In` and `Out` that also inherit from their
166 "nest". Class attribute `IN_KWARGS` defined in the "nest" is
167 copied to the `In` nested class under the name `KWARGS`, and
168 likewise, `OUT_KWARGS` of the nest class is copied as `KWARGS`
169 to the nested class `Out`. In addition, method `encode` is
170 defined in both classes equal to `in_encode()` and `out_encode()`
176 def __getattr__(self, name: str) -> Any:
179 def __setattr__(self, name: str, value: Any) -> None:
183 cls: Type["MetaPkt"],
185 bases: Tuple[type, ...],
186 attrs: Dict[str, Any],
188 newcls = super().__new__(cls, name, bases, attrs)
189 newcls.In = super().__new__(
194 "KWARGS": newcls.IN_KWARGS,
195 "decode": newcls.in_decode,
196 "encode": newcls.in_encode,
199 newcls.Out = super().__new__(
204 "KWARGS": newcls.OUT_KWARGS,
205 "decode": newcls.out_decode,
206 "encode": newcls.out_encode,
213 NON = 0 # Incoming, no response needed
214 INL = 1 # Birirectional, use `inline_response()`
215 EXT = 2 # Birirectional, use external responder
218 class BeeSurePkt(metaclass=MetaPkt):
219 RESPOND = Respond.NON # Do not send anything back by default
221 IN_KWARGS: Tuple[Tuple[str, Callable[[Any], Any], Any], ...] = ()
222 OUT_KWARGS: Tuple[Tuple[str, Callable[[Any], Any], Any], ...] = ()
223 KWARGS: Tuple[Tuple[str, Callable[[Any], Any], Any], ...] = ()
224 In: Type["BeeSurePkt"]
225 Out: Type["BeeSurePkt"]
229 def __getattr__(self, name: str) -> Any:
232 def __setattr__(self, name: str, value: Any) -> None:
235 def __init__(self, *args: Any, **kwargs: Any):
237 Construct the object _either_ from (length, payload),
238 _or_ from the values of individual fields
240 assert not args or (len(args) == 4 and not kwargs)
241 if args: # guaranteed to be two arguments at this point
242 self.vendor, self.imei, self.datalength, self.payload = args
244 self.decode(*self.payload)
246 raise DecodeError(e, obj=self)
248 for kw, typ, dfl in self.KWARGS:
249 setattr(self, kw, typ(kwargs.pop(kw, dfl)))
252 self.__class__.__name__ + " stray kwargs " + str(kwargs)
255 def __repr__(self) -> str:
256 return "{}({})".format(
257 self.__class__.__name__,
261 'bytes.fromhex("{}")'.format(v.hex())
262 if isinstance(v, bytes)
265 for k, v in self.__dict__.items()
266 if not k.startswith("_")
270 def decode(self, *args: str) -> None:
273 def in_decode(self, *args: str) -> None:
274 # Overridden in subclasses, otherwise do not decode payload
277 def out_decode(self, *args: str) -> None:
278 # Overridden in subclasses, otherwise do not decode payload
281 def encode(self) -> str:
284 def in_encode(self) -> str:
285 # Necessary to emulate terminal, which is not implemented
286 raise NotImplementedError(
287 self.__class__.__name__ + ".encode() not implemented"
290 def out_encode(self) -> str:
291 # Overridden in subclasses, otherwise command verb only
295 def packed(self) -> bytes:
296 buffer = self.encode().encode()
297 return f"[LT*0000000000*{len(buffer):04X}*".encode() + buffer + b"]"
300 class UNKNOWN(BeeSurePkt):
304 class LK(BeeSurePkt):
306 RESPOND = Respond.INL
308 def in_decode(self, *args: str) -> None:
313 self.tumbling_number = args[2]
315 self.battery_percentage = args[3]
317 def in_encode(self) -> str:
321 class CONFIG(BeeSurePkt):
325 class ICCID(BeeSurePkt):
329 class UD(BeeSurePkt):
332 def in_decode(self, *args: str) -> None:
346 self.gsm_strength_percentage,
347 self.battery_percentage,
352 rest_args = args[17:]
353 self.base_stations_number = int(rest_args[0])
354 # ???, mcc, net, (area, cell, strength)*
355 self.base_stations = rest_args[1 : 4 + 3 * self.base_stations_number]
356 rest_args = rest_args[3 + 3 * self.base_stations_number + 1 :]
357 self.wifi_ap_number = int(rest_args[0])
358 # (SSID, MAC, strength)*
359 self.wifi_ap = rest_args[1 : 1 + 3 * self.wifi_ap_number]
360 self.positioning_accuracy = rest_args[-1]
363 class UD2(BeeSurePkt):
367 class TKQ(BeeSurePkt):
369 RESPOND = Respond.INL
372 class TKQ2(BeeSurePkt):
374 RESPOND = Respond.INL
377 class AL(BeeSurePkt):
379 RESPOND = Respond.INL
382 # Build dicts protocol number -> class and class name -> protocol number
385 if True: # just to indent the code, sorry!
388 for name, cls in globals().items()
390 and issubclass(cls, BeeSurePkt)
391 and not name.startswith("_")
393 if hasattr(cls, "PROTO"):
394 CLASSES[cls.PROTO] = cls
395 PROTOS[cls.__name__] = cls.PROTO
400 ) -> Union[Type[BeeSurePkt], List[Tuple[str, str]]]:
403 for name, proto in PROTOS.items()
404 if name.upper().startswith(prefix.upper())
409 return CLASSES[proto]
412 def proto_handled(proto: str) -> bool:
413 return proto.startswith(PROTO_PREFIX)
416 def proto_name(obj: Union[MetaPkt, BeeSurePkt]) -> str:
417 return PROTO_PREFIX + (
418 obj.__class__.__name__ if isinstance(obj, BeeSurePkt) else obj.__name__
422 def proto_of_message(packet: bytes) -> str:
423 return PROTO_PREFIX + packet[20:-1].split(b",")[0].decode()
426 def imei_from_packet(packet: bytes) -> Optional[str]:
427 toskip, _, imei, _ = _framestart(packet)
428 if toskip == 0 and imei != "":
433 def is_goodbye_packet(packet: bytes) -> bool:
437 def inline_response(packet: bytes) -> Optional[bytes]:
438 proto = packet[20:-1].split(b",")[0].decode()
441 if cls.RESPOND is Respond.INL:
442 return cls.Out().packed
446 def probe_buffer(buffer: bytes) -> bool:
447 return bool(RE.search(buffer))
450 def parse_message(packet: bytes, is_incoming: bool = True) -> BeeSurePkt:
451 """From a packet (without framing bytes) derive the XXX.In object"""
452 toskip, vendor, imei, datalength = _framestart(packet)
453 payload = packet[20:-1].decode().split(",")
454 proto = payload[0] if len(payload) > 0 else ""
455 if proto not in CLASSES:
456 cause: Union[DecodeError, ValueError, IndexError] = ValueError(
457 f"Proto {proto} is unknown"
462 return CLASSES[proto].In(vendor, imei, datalength, payload)
464 return CLASSES[proto].Out(vendor, imei, datalength, payload)
465 except (DecodeError, ValueError, IndexError) as e:
468 retobj = UNKNOWN.In(vendor, imei, datalength, payload)
470 retobj = UNKNOWN.Out(vendor, imei, datalength, payload)
471 retobj.PROTO = proto # Override class attr with object attr