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
43 MAXBUFFER: int = 65557 # Theoretical max buffer 65536 + 21
44 RE = re.compile(b"\[(\w\w)\*(\d{10})\*([0-9a-fA-F]{4})\*")
47 def _framestart(buffer: bytes) -> Tuple[int, str, str, int]:
49 Find the start of the frame in the buffer.
50 If found, return (offset, vendorId, imei, datalen) tuple.
51 If not found, set -1 as the value of `offset`
53 mo = RE.search(buffer)
67 def __init__(self) -> None:
69 self.imei: Optional[str] = None
72 def recv(self, segment: bytes) -> List[Union[bytes, str]]:
74 Process next segment of the stream. Return successfully deframed
75 packets as `bytes` and error messages as `str`.
78 self.buffer += segment
79 if len(self.buffer) > MAXBUFFER:
80 # We are receiving junk. Let's drop it or we run out of memory.
82 return [f"More than {MAXBUFFER} unparseable data, dropping"]
83 msgs: List[Union[bytes, str]] = []
85 if not self.datalen: # we have not seen packet start yet
86 toskip, _, imei, datalen = _framestart(self.buffer)
87 if toskip < 0: # No frames, continue reading
89 if toskip > 0: # Should not happen, report
91 f"Skipping {toskip} bytes of undecodable data"
92 f' "{self.buffer[:toskip][:64]=!r}"'
94 self.buffer = self.buffer[toskip:]
95 # From this point, buffer starts with a packet header
100 f"Packet's imei {imei} mismatches"
101 f" previous value {self.imei}, old value kept"
103 self.datalen = datalen
104 if len(self.buffer) < self.datalen + 21: # Incomplete packet
106 # At least one complete packet is present in the buffer
107 if chr(self.buffer[self.datalen + 20]) == "]":
108 msgs.append(self.buffer[: self.datalen + 21])
111 f"Packet does not end with ']'"
112 f" at {self.datalen+20}: {self.buffer=!r}"
114 self.buffer = self.buffer[self.datalen + 21 :]
118 def close(self) -> bytes:
126 def enframe(buffer: bytes, imei: Optional[str] = None) -> bytes:
127 assert imei is not None and len(imei) == 10
128 off, vid, _, dlen = _framestart(buffer)
130 return f"[{vid:2s}*{imei:10s}*{dlen:04X}*".encode() + buffer[20:]
133 ### Parser/Constructor ###
136 class DecodeError(Exception):
137 def __init__(self, e: Exception, **kwargs: Any) -> None:
139 for k, v in kwargs.items():
143 def maybe(typ: type) -> Callable[[Any], Any]:
144 return lambda x: None if x is None else typ(x)
147 def intx(x: Union[str, int]) -> int:
148 if isinstance(x, str):
153 def boolx(x: Union[str, bool]) -> bool:
154 if isinstance(x, str):
155 if x.upper() in ("ON", "TRUE", "1"):
157 if x.upper() in ("OFF", "FALSE", "0"):
159 raise ValueError(str(x) + " could not be parsed as a Boolean")
165 For each class corresponding to a message, automatically create
166 two nested classes `In` and `Out` that also inherit from their
167 "nest". Class attribute `IN_KWARGS` defined in the "nest" is
168 copied to the `In` nested class under the name `KWARGS`, and
169 likewise, `OUT_KWARGS` of the nest class is copied as `KWARGS`
170 to the nested class `Out`. In addition, method `encode` is
171 defined in both classes equal to `in_encode()` and `out_encode()`
177 def __getattr__(self, name: str) -> Any:
180 def __setattr__(self, name: str, value: Any) -> None:
184 cls: Type["MetaPkt"],
186 bases: Tuple[type, ...],
187 attrs: Dict[str, Any],
189 newcls = super().__new__(cls, name, bases, attrs)
190 newcls.In = super().__new__(
195 "KWARGS": newcls.IN_KWARGS,
196 "decode": newcls.in_decode,
197 "encode": newcls.in_encode,
200 newcls.Out = super().__new__(
205 "KWARGS": newcls.OUT_KWARGS,
206 "decode": newcls.out_decode,
207 "encode": newcls.out_encode,
214 NON = 0 # Incoming, no response needed
215 INL = 1 # Birirectional, use `inline_response()`
216 EXT = 2 # Birirectional, use external responder
219 class BeeSurePkt(metaclass=MetaPkt):
220 RESPOND = Respond.NON # Do not send anything back by default
222 IN_KWARGS: Tuple[Tuple[str, Callable[[Any], Any], Any], ...] = ()
223 OUT_KWARGS: Tuple[Tuple[str, Callable[[Any], Any], Any], ...] = ()
224 KWARGS: Tuple[Tuple[str, Callable[[Any], Any], Any], ...] = ()
225 In: Type["BeeSurePkt"]
226 Out: Type["BeeSurePkt"]
230 def __getattr__(self, name: str) -> Any:
233 def __setattr__(self, name: str, value: Any) -> None:
236 def __init__(self, *args: Any, **kwargs: Any):
238 Construct the object _either_ from (length, payload),
239 _or_ from the values of individual fields
241 assert not args or (len(args) == 4 and not kwargs)
242 if args: # guaranteed to be two arguments at this point
243 self.vendor, self.imei, self.datalength, self.payload = args
245 self.decode(*self.payload)
247 raise DecodeError(e, obj=self)
249 for kw, typ, dfl in self.KWARGS:
250 setattr(self, kw, typ(kwargs.pop(kw, dfl)))
253 self.__class__.__name__ + " stray kwargs " + str(kwargs)
256 def __repr__(self) -> str:
257 return "{}({})".format(
258 self.__class__.__name__,
262 'bytes.fromhex("{}")'.format(v.hex())
263 if isinstance(v, bytes)
266 for k, v in self.__dict__.items()
267 if not k.startswith("_")
271 def decode(self, *args: str) -> None:
274 def in_decode(self, *args: str) -> None:
275 # Overridden in subclasses, otherwise do not decode payload
278 def out_decode(self, *args: str) -> None:
279 # Overridden in subclasses, otherwise do not decode payload
282 def encode(self) -> str:
285 def in_encode(self) -> str:
286 # Necessary to emulate terminal, which is not implemented
287 raise NotImplementedError(
288 self.__class__.__name__ + ".encode() not implemented"
291 def out_encode(self) -> str:
292 # Overridden in subclasses, otherwise command verb only
296 def packed(self) -> bytes:
297 buffer = self.encode().encode()
298 return f"[LT*0000000000*{len(buffer):04X}*".encode() + buffer + b"]"
301 class UNKNOWN(BeeSurePkt):
305 class LK(BeeSurePkt):
307 RESPOND = Respond.INL
309 def in_decode(self, *args: str) -> None:
314 self.tumbling_number = args[2]
316 self.battery_percentage = args[3]
318 def in_encode(self) -> str:
322 class CONFIG(BeeSurePkt):
326 class ICCID(BeeSurePkt):
330 class UD(BeeSurePkt):
333 def in_decode(self, *args: str) -> None:
347 self.gsm_strength_percentage,
348 self.battery_percentage,
353 rest_args = args[17:]
354 self.base_stations_number = int(rest_args[0])
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 self.wifi_ap = rest_args[1 : self.wifi_ap_number]
359 # rest_args = rest_args[self_wifi_ap_number+1:]
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_by_name(name: str) -> str:
423 return PROTO_PREFIX + PROTOS.get(name, "UNKNOWN")
426 def proto_of_message(packet: bytes) -> str:
427 return PROTO_PREFIX + packet[20:-1].split(b",")[0].decode()
430 def imei_from_packet(packet: bytes) -> Optional[str]:
431 toskip, _, imei, _ = _framestart(packet)
432 if toskip == 0 and imei != "":
437 def is_goodbye_packet(packet: bytes) -> bool:
441 def inline_response(packet: bytes) -> Optional[bytes]:
442 proto = packet[20:-1].split(b",")[0].decode()
445 if cls.RESPOND is Respond.INL:
446 return cls.Out().packed
450 def probe_buffer(buffer: bytes) -> bool:
451 return bool(RE.search(buffer))
454 def parse_message(packet: bytes, is_incoming: bool = True) -> BeeSurePkt:
455 """From a packet (without framing bytes) derive the XXX.In object"""
456 toskip, vendor, imei, datalength = _framestart(packet)
457 payload = packet[20:-1].decode().split(",")
458 proto = payload[0] if len(payload) > 0 else ""
459 if proto not in CLASSES:
460 cause: Union[DecodeError, ValueError, IndexError] = ValueError(
461 f"Proto {proto} is unknown"
466 return CLASSES[proto].In(vendor, imei, datalength, payload)
468 return CLASSES[proto].Out(vendor, imei, datalength, payload)
469 except (DecodeError, ValueError, IndexError) as e:
472 retobj = UNKNOWN.In(vendor, imei, datalength, payload)
474 retobj = UNKNOWN.Out(vendor, imei, datalength, payload)
475 retobj.PROTO = proto # Override class attr with object attr