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
23 from types import SimpleNamespace
25 from .protomodule import ProtoClass
51 MAXBUFFER: int = 65557 # Theoretical max buffer 65536 + 21
52 RE = re.compile(b"\[(\w\w)\*(\d{10})\*([0-9a-fA-F]{4})\*")
55 def _framestart(buffer: bytes) -> Tuple[int, str, str, int]:
57 Find the start of the frame in the buffer.
58 If found, return (offset, vendorId, imei, datalen) tuple.
59 If not found, set -1 as the value of `offset`
61 mo = RE.search(buffer)
75 def __init__(self) -> None:
77 self.imei: Optional[str] = None
80 def recv(self, segment: bytes) -> List[Union[bytes, str]]:
82 Process next segment of the stream. Return successfully deframed
83 packets as `bytes` and error messages as `str`.
86 self.buffer += segment
87 if len(self.buffer) > MAXBUFFER:
88 # We are receiving junk. Let's drop it or we run out of memory.
90 return [f"More than {MAXBUFFER} unparseable data, dropping"]
91 msgs: List[Union[bytes, str]] = []
93 if not self.datalen: # we have not seen packet start yet
94 toskip, _, imei, datalen = _framestart(self.buffer)
95 if toskip < 0: # No frames, continue reading
97 if toskip > 0: # Should not happen, report
99 f"Skipping {toskip} bytes of undecodable data"
100 f' "{self.buffer[:toskip][:64]=!r}"'
102 self.buffer = self.buffer[toskip:]
103 # From this point, buffer starts with a packet header
104 if self.imei is None:
106 if self.imei != imei:
108 f"Packet's imei {imei} mismatches"
109 f" previous value {self.imei}, old value kept"
111 self.datalen = datalen
112 if len(self.buffer) < self.datalen + 21: # Incomplete packet
114 # At least one complete packet is present in the buffer
115 if chr(self.buffer[self.datalen + 20]) == "]":
116 msgs.append(self.buffer[: self.datalen + 21])
119 f"Packet does not end with ']'"
120 f" at {self.datalen+20}: {self.buffer=!r}"
122 self.buffer = self.buffer[self.datalen + 21 :]
126 def close(self) -> bytes:
134 def enframe(buffer: bytes, imei: Optional[str] = None) -> bytes:
135 assert imei is not None and len(imei) == 10
136 off, vid, _, dlen = _framestart(buffer)
138 return f"[{vid:2s}*{imei:10s}*{dlen:04X}*".encode() + buffer[20:]
141 ### Parser/Constructor ###
144 class DecodeError(Exception):
145 def __init__(self, e: Exception, **kwargs: Any) -> None:
147 for k, v in kwargs.items():
151 def maybe(typ: type) -> Callable[[Any], Any]:
152 return lambda x: None if x is None else typ(x)
155 def intx(x: Union[str, int]) -> int:
156 if isinstance(x, str):
161 def boolx(x: Union[str, bool]) -> bool:
162 if isinstance(x, str):
163 if x.upper() in ("ON", "TRUE", "1"):
165 if x.upper() in ("OFF", "FALSE", "0"):
167 raise ValueError(str(x) + " could not be parsed as a Boolean")
171 def l3str(x: Union[str, List[str]]) -> List[str]:
172 if isinstance(x, str):
176 if len(lx) != 3 or not all(isinstance(el, str) for el in x):
177 raise ValueError(str(lx) + " is not a list of three strings")
181 def pblist(x: Union[str, List[Tuple[str, str]]]) -> List[Tuple[str, str]]:
182 if isinstance(x, str):
184 def splitpair(s: str) -> Tuple[str, str]:
188 lx = [splitpair(el) for el in x.split(",")]
192 raise ValueError(str(lx) + " has too many elements (max 5)")
197 NON = 0 # Incoming, no response needed
198 INL = 1 # Birirectional, use `inline_response()`
199 EXT = 2 # Birirectional, use external responder
202 class BeeSurePkt(ProtoClass):
203 RESPOND = Respond.NON # Do not send anything back by default
204 IN_KWARGS: Tuple[Tuple[str, Callable[[Any], Any], Any], ...] = ()
205 OUT_KWARGS: Tuple[Tuple[str, Callable[[Any], Any], Any], ...] = ()
206 KWARGS: Tuple[Tuple[str, Callable[[Any], Any], Any], ...] = ()
207 In: Type["BeeSurePkt"]
208 Out: Type["BeeSurePkt"]
212 def __getattr__(self, name: str) -> Any:
215 def __setattr__(self, name: str, value: Any) -> None:
218 def __init__(self, *args: Any, **kwargs: Any):
220 Construct the object _either_ from (length, payload),
221 _or_ from the values of individual fields
223 self.payload: Union[List[str], bytes]
224 assert not args or (len(args) == 4 and not kwargs)
225 if args: # guaranteed to be two arguments at this point
226 self.vendor, self.imei, self.datalength, self.payload = args
228 if isinstance(self.payload, list):
229 self.decode(*self.payload)
231 self.decode(self.payload)
233 raise DecodeError(e, obj=self)
235 for kw, typ, dfl in self.KWARGS:
236 setattr(self, kw, typ(kwargs.pop(kw, dfl)))
239 self.__class__.__name__ + " stray kwargs " + str(kwargs)
242 def __repr__(self) -> str:
243 return "{}({})".format(
244 self.__class__.__name__,
248 'bytes.fromhex("{}")'.format(v.hex())
249 if isinstance(v, bytes)
252 for k, v in self.__dict__.items()
253 if not k.startswith("_")
257 def decode(self, *args: Any) -> None:
260 def in_decode(self, *args: str) -> None:
261 # Overridden in subclasses, otherwise do not decode payload
264 def out_decode(self, *args: str) -> None:
265 # Overridden in subclasses, otherwise do not decode payload
268 def encode(self) -> str:
271 def in_encode(self) -> str:
272 # Necessary to emulate terminal, which is not implemented
273 raise NotImplementedError(
274 self.__class__.__name__ + ".encode() not implemented"
277 def out_encode(self) -> str:
278 # Overridden in subclasses, otherwise command verb only
282 def PROTO(self) -> str:
284 proto, _ = self.__class__.__name__.split(".")
286 proto = self.__class__.__name__
290 def packed(self) -> bytes:
292 payload = self.PROTO + "," + data if data else self.PROTO
293 return f"[LT*0000000000*{len(payload):04X}*{payload}]".encode()
296 class UNKNOWN(BeeSurePkt):
300 class _LOC_DATA(BeeSurePkt):
301 def in_decode(self, *args: str) -> None:
302 p = SimpleNamespace()
304 for (obj, attr, func), val in zip(
308 (self, "gps_valid", lambda x: x == "A"),
310 (p, "nors", lambda x: 1 if x == "N" else -1),
312 (p, "eorw", lambda x: 1 if x == "E" else -1),
313 (self, "speed", float),
314 (self, "direction", float),
315 (self, "altitude", float),
316 (self, "num_of_sats", int),
317 (self, "gsm_strength_percentage", int),
318 (self, "battery_percentage", int),
319 (self, "pedometer", int),
320 (self, "tubmling_times", int),
321 (self, "device_status", lambda x: int(x, 16)),
322 (self, "gsm_cells_number", int),
323 (self, "connect_base_station_number", int),
329 setattr(obj, attr, func(val)) # type: ignore
330 rest_args = args[20:]
331 # (area_id, cell_id, strength)*
332 self.gsm_cells: List[Tuple[int, int, int]] = [
333 tuple(int(el) for el in rest_args[i * 3 : 3 + i * 3]) # type: ignore
334 for i in range(self.gsm_cells_number)
336 rest_args = rest_args[3 * self.gsm_cells_number :]
337 self.wifi_aps_number = int(rest_args[0])
338 # (SSID, MAC, strength)*
341 rest_args[1 + i * 3],
342 rest_args[2 + i * 3],
343 int(rest_args[3 + i * 3]),
345 for i in range(self.wifi_aps_number)
347 rest_args = rest_args[1 + 3 * self.wifi_aps_number :]
348 self.positioning_accuracy = float(rest_args[0])
354 # .replace(tzinfo=timezone.utc)
355 # .astimezone(tz=timezone.utc)
357 self.latitude = p.lat * p.nors
358 self.longitude = p.lon * p.eorw
360 def rectified(self) -> Report:
363 devtime=str(self.devtime),
364 battery_percentage=self.battery_percentage,
365 accuracy=self.positioning_accuracy,
366 altitude=self.altitude,
368 direction=self.direction,
369 latitude=self.latitude,
370 longitude=self.longitude,
374 devtime=str(self.devtime),
375 battery_percentage=self.battery_percentage,
378 gsm_cells=self.gsm_cells,
379 wifi_aps=self.wifi_aps,
384 RESPOND = Respond.INL
387 class CONFIG(BeeSurePkt):
391 class CR(BeeSurePkt):
395 class FLOWER(BeeSurePkt):
396 OUT_KWARGS = (("number", int, 1),)
398 def out_encode(self) -> str:
400 return str(self.number)
403 class ICCID(BeeSurePkt):
407 class LK(BeeSurePkt):
408 RESPOND = Respond.INL
410 def in_decode(self, *args: str) -> None:
415 self.tumbling_number = args[1]
417 self.battery_percentage = args[2]
419 def in_encode(self) -> str:
423 class MESSAGE(BeeSurePkt):
424 OUT_KWARGS = (("message", str, ""),)
426 def out_encode(self) -> str:
427 return str(self.message.encode("utf_16_be").hex())
430 class _PHB(BeeSurePkt):
431 OUT_KWARGS: Tuple[Tuple[str, Callable[[Any], Any], Any], ...] = (
432 ("entries", pblist, []),
435 def out_encode(self) -> str:
436 self.entries: List[Tuple[str, str]]
439 ",".join((num, name.encode("utf_16_be").hex()))
440 for name, num in self.entries
453 class POWEROFF(BeeSurePkt):
457 class RESET(BeeSurePkt):
461 class SOS(BeeSurePkt):
462 OUT_KWARGS = (("phonenumbers", l3str, ["", "", ""]),)
464 def out_encode(self) -> str:
465 self.phonenumbers: List[str]
466 return ",".join(self.phonenumbers)
469 class _SET_PHONE(BeeSurePkt):
470 OUT_KWARGS = (("phonenumber", str, ""),)
472 def out_encode(self) -> str:
473 self.phonenumber: str
474 return self.phonenumber
477 class SOS1(_SET_PHONE):
481 class SOS2(_SET_PHONE):
485 class SOS3(_SET_PHONE):
489 class TK(BeeSurePkt):
490 RESPOND = Respond.INL
492 def in_decode(self, *args: Any) -> None:
493 assert len(args) == 1 and isinstance(args[0], bytes)
496 .replace(b"}*", b"*")
497 .replace(b"},", b",")
498 .replace(b"}[", b"[")
499 .replace(b"}]", b"]")
500 .replace(b"}}", b"}")
503 def out_encode(self) -> str:
504 return "1" # 0 - receive failure, 1 - receive success
507 class TKQ(BeeSurePkt):
508 RESPOND = Respond.INL
511 class TKQ2(BeeSurePkt):
512 RESPOND = Respond.INL
519 class UD2(_LOC_DATA):
523 # Build dicts protocol number -> class and class name -> protocol number
525 if True: # just to indent the code, sorry!
528 for name, cls in globals().items()
530 and issubclass(cls, BeeSurePkt)
531 and not name.startswith("_")
533 CLASSES[cls.__name__] = cls
538 ) -> Union[Type[BeeSurePkt], List[str]]:
539 if prefix.startswith(PROTO_PREFIX):
540 pname = prefix[len(PROTO_PREFIX) :].upper()
542 raise KeyError(pname)
543 lst = [name for name in CLASSES.keys() if name.upper().startswith(pname)]
545 if len(lst) == 1: # unique prefix match
546 return CLASSES[proto]
547 if proto == pname: # exact match
548 return CLASSES[proto]
552 def proto_handled(proto: str) -> bool:
553 return proto.startswith(PROTO_PREFIX)
556 def proto_name(obj: Union[Type[BeeSurePkt], BeeSurePkt]) -> str:
557 return PROTO_PREFIX + (
558 obj.__class__.__name__ if isinstance(obj, BeeSurePkt) else obj.__name__
562 def proto_of_message(packet: bytes) -> str:
563 return PROTO_PREFIX + packet[20:-1].split(b",")[0].decode()
566 def imei_from_packet(packet: bytes) -> Optional[str]:
567 toskip, _, imei, _ = _framestart(packet)
568 if toskip == 0 and imei != "":
573 def is_goodbye_packet(packet: bytes) -> bool:
577 def inline_response(packet: bytes) -> Optional[bytes]:
578 proto = packet[20:-1].split(b",")[0].decode()
581 if cls.RESPOND is Respond.INL:
582 return cls.Out().packed
586 def probe_buffer(buffer: bytes) -> bool:
587 return bool(RE.search(buffer))
590 def parse_message(packet: bytes, is_incoming: bool = True) -> BeeSurePkt:
591 """From a packet (without framing bytes) derive the XXX.In object"""
592 toskip, vendor, imei, datalength = _framestart(packet)
594 splits = packet[20:-1].decode().split(",")
595 proto = splits[0] if len(splits) > 0 else ""
596 payload: Union[List[str], bytes] = splits[1:]
597 except UnicodeDecodeError:
598 bsplits = packet[20:-1].split(b",", 1)
599 if len(bsplits) == 2:
600 proto = bsplits[0].decode("ascii")
602 if proto not in CLASSES:
603 cause: Union[DecodeError, ValueError, IndexError] = ValueError(
604 f"Proto {proto} is unknown"
609 return CLASSES[proto].In(vendor, imei, datalength, payload)
611 return CLASSES[proto].Out(vendor, imei, datalength, payload)
612 except (DecodeError, ValueError, IndexError) as e:
615 retobj = UNKNOWN.In(vendor, imei, datalength, payload)
617 retobj = UNKNOWN.Out(vendor, imei, datalength, payload)
618 retobj.proto = proto # Override class attr with object attr
623 def exposed_protos() -> List[Tuple[str, bool]]:
625 (proto_name(cls)[:16], False)
626 for cls in CLASSES.values()
627 if hasattr(cls, "rectified")