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
41 MAXBUFFER: int = 65557 # Theoretical max buffer 65536 + 21
42 RE = re.compile(b"\[(\w\w)\*(\d{10})\*([0-9a-fA-F]{4})\*")
45 def _framestart(buffer: bytes) -> Tuple[int, str, str, int]:
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`
51 mo = RE.search(buffer)
65 def __init__(self) -> None:
67 self.imei: Optional[str] = None
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"]"
75 def recv(self, segment: bytes) -> List[Union[bytes, str]]:
77 Process next segment of the stream. Return successfully deframed
78 packets as `bytes` and error messages as `str`.
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.
85 return [f"More than {MAXBUFFER} unparseable data, dropping"]
86 msgs: List[Union[bytes, str]] = []
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
92 if toskip > 0: # Should not happen, report
94 f"Skipping {toskip} bytes of undecodable data"
95 f' "{self.buffer[:toskip][:64]=!r}"'
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:
101 f"Packet's imei {imei} mismatches"
102 f" previous value {self.imei}"
105 self.datalen = datalen
106 if len(self.buffer) < self.datalen + 21: # Incomplete packet
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])
113 f"Packet does not end with ']'"
114 f" at {self.datalen+20}: {self.buffer=!r}"
116 self.buffer = self.buffer[self.datalen + 21 :]
120 def close(self) -> bytes:
128 ### Parser/Constructor ###
131 class DecodeError(Exception):
132 def __init__(self, e: Exception, **kwargs: Any) -> None:
134 for k, v in kwargs.items():
138 def maybe(typ: type) -> Callable[[Any], Any]:
139 return lambda x: None if x is None else typ(x)
142 def intx(x: Union[str, int]) -> int:
143 if isinstance(x, str):
148 def boolx(x: Union[str, bool]) -> bool:
149 if isinstance(x, str):
150 if x.upper() in ("ON", "TRUE", "1"):
152 if x.upper() in ("OFF", "FALSE", "0"):
154 raise ValueError(str(x) + " could not be parsed as a Boolean")
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()`
172 def __getattr__(self, name: str) -> Any:
175 def __setattr__(self, name: str, value: Any) -> None:
179 cls: Type["MetaPkt"],
181 bases: Tuple[type, ...],
182 attrs: Dict[str, Any],
184 newcls = super().__new__(cls, name, bases, attrs)
185 newcls.In = super().__new__(
190 "KWARGS": newcls.IN_KWARGS,
191 "decode": newcls.in_decode,
192 "encode": newcls.in_encode,
195 newcls.Out = super().__new__(
200 "KWARGS": newcls.OUT_KWARGS,
201 "decode": newcls.out_decode,
202 "encode": newcls.out_encode,
209 NON = 0 # Incoming, no response needed
210 INL = 1 # Birirectional, use `inline_response()`
211 EXT = 2 # Birirectional, use external responder
214 class BeeSurePkt(metaclass=MetaPkt):
215 RESPOND = Respond.NON # Do not send anything back by default
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"]
225 def __getattr__(self, name: str) -> Any:
228 def __setattr__(self, name: str, value: Any) -> None:
231 def __init__(self, *args: Any, **kwargs: Any):
233 Construct the object _either_ from (length, payload),
234 _or_ from the values of individual fields
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
240 self.decode(*self.payload)
242 raise DecodeError(e, obj=self)
244 for kw, typ, dfl in self.KWARGS:
245 setattr(self, kw, typ(kwargs.pop(kw, dfl)))
248 self.__class__.__name__ + " stray kwargs " + str(kwargs)
251 def __repr__(self) -> str:
252 return "{}({})".format(
253 self.__class__.__name__,
257 'bytes.fromhex("{}")'.format(v.hex())
258 if isinstance(v, bytes)
261 for k, v in self.__dict__.items()
262 if not k.startswith("_")
266 def decode(self, *args: str) -> None:
269 def in_decode(self, *args: str) -> None:
270 # Overridden in subclasses, otherwise do not decode payload
273 def out_decode(self, *args: str) -> None:
274 # Overridden in subclasses, otherwise do not decode payload
277 def encode(self) -> str:
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"
286 def out_encode(self) -> str:
287 # Overridden in subclasses, otherwise command verb only
291 def packed(self) -> bytes:
292 return self.encode().encode() # first is object's, second str's
295 class UNKNOWN(BeeSurePkt):
299 class LK(BeeSurePkt):
301 RESPOND = Respond.INL
303 def in_decode(self, *args: str) -> None:
308 self.tumbling_number = args[2]
310 self.battery_percentage = args[3]
312 def in_encode(self) -> str:
316 class CONFIG(BeeSurePkt):
318 RESPOND = Respond.INL
321 class UD(BeeSurePkt):
324 def in_decode(self, *args: str) -> None:
338 self.gsm_strength_percentage,
339 self.battery_percentage,
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]
354 class UD2(BeeSurePkt):
358 class TKQ(BeeSurePkt):
360 RESPOND = Respond.INL
363 class TKQ2(BeeSurePkt):
365 RESPOND = Respond.INL
368 class AL(BeeSurePkt):
370 RESPOND = Respond.INL
373 # Build dicts protocol number -> class and class name -> protocol number
376 if True: # just to indent the code, sorry!
379 for name, cls in globals().items()
381 and issubclass(cls, BeeSurePkt)
382 and not name.startswith("_")
384 if hasattr(cls, "PROTO"):
385 CLASSES[cls.PROTO] = cls
386 PROTOS[cls.__name__] = cls.PROTO
391 ) -> Union[Type[BeeSurePkt], List[Tuple[str, str]]]:
394 for name, proto in PROTOS.items()
395 if name.upper().startswith(prefix.upper())
400 return CLASSES[proto]
403 def proto_name(obj: Union[MetaPkt, BeeSurePkt]) -> str:
404 return PROTO_PREFIX + (
405 obj.__class__.__name__ if isinstance(obj, BeeSurePkt) else obj.__name__
409 def proto_by_name(name: str) -> str:
410 return PROTO_PREFIX + PROTOS.get(name, "UNKNOWN")
413 def proto_of_message(packet: bytes) -> str:
414 return PROTO_PREFIX + packet.split(b",")[0].decode()
417 def imei_from_packet(packet: bytes) -> Optional[str]:
418 toskip, _, imei, _ = _framestart(packet)
419 if toskip == 0 and imei != "":
424 def is_goodbye_packet(packet: bytes) -> bool:
428 def inline_response(packet: bytes) -> Optional[bytes]:
429 proto = packet[20:-1].split(b",")[0].decode()
432 if cls.RESPOND is Respond.INL:
433 return cls.Out().packed
437 def probe_buffer(buffer: bytes) -> bool:
438 return bool(RE.search(buffer))
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"
453 return CLASSES[proto].In(vendor, imei, datalength, payload)
455 return CLASSES[proto].Out(vendor, imei, datalength, payload)
456 except (DecodeError, ValueError, IndexError) as e:
459 retobj = UNKNOWN.In(vendor, imei, datalength, payload)
461 retobj = UNKNOWN.Out(vendor, imei, datalength, payload)
462 retobj.PROTO = proto # Override class attr with object attr