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
50 MAXBUFFER: int = 65557 # Theoretical max buffer 65536 + 21
51 RE = re.compile(b"\[(\w\w)\*(\d{10})\*([0-9a-fA-F]{4})\*")
54 def _framestart(buffer: bytes) -> Tuple[int, str, str, int]:
56 Find the start of the frame in the buffer.
57 If found, return (offset, vendorId, imei, datalen) tuple.
58 If not found, set -1 as the value of `offset`
60 mo = RE.search(buffer)
74 def __init__(self) -> None:
76 self.imei: Optional[str] = None
79 def recv(self, segment: bytes) -> List[Union[bytes, str]]:
81 Process next segment of the stream. Return successfully deframed
82 packets as `bytes` and error messages as `str`.
85 self.buffer += segment
86 if len(self.buffer) > MAXBUFFER:
87 # We are receiving junk. Let's drop it or we run out of memory.
89 return [f"More than {MAXBUFFER} unparseable data, dropping"]
90 msgs: List[Union[bytes, str]] = []
92 if not self.datalen: # we have not seen packet start yet
93 toskip, _, imei, datalen = _framestart(self.buffer)
94 if toskip < 0: # No frames, continue reading
96 if toskip > 0: # Should not happen, report
98 f"Skipping {toskip} bytes of undecodable data"
99 f' "{self.buffer[:toskip][:64]=!r}"'
101 self.buffer = self.buffer[toskip:]
102 # From this point, buffer starts with a packet header
103 if self.imei is None:
105 if self.imei != imei:
107 f"Packet's imei {imei} mismatches"
108 f" previous value {self.imei}, old value kept"
110 self.datalen = datalen
111 if len(self.buffer) < self.datalen + 21: # Incomplete packet
113 # At least one complete packet is present in the buffer
114 if chr(self.buffer[self.datalen + 20]) == "]":
115 msgs.append(self.buffer[: self.datalen + 21])
118 f"Packet does not end with ']'"
119 f" at {self.datalen+20}: {self.buffer=!r}"
121 self.buffer = self.buffer[self.datalen + 21 :]
125 def close(self) -> bytes:
133 def enframe(buffer: bytes, imei: Optional[str] = None) -> bytes:
134 assert imei is not None and len(imei) == 10
135 off, vid, _, dlen = _framestart(buffer)
137 return f"[{vid:2s}*{imei:10s}*{dlen:04X}*".encode() + buffer[20:]
140 ### Parser/Constructor ###
144 def __init__(self, f: Callable[[Any], str]) -> None:
147 def __get__(self, obj: Any, owner: Any) -> str:
151 class DecodeError(Exception):
152 def __init__(self, e: Exception, **kwargs: Any) -> None:
154 for k, v in kwargs.items():
158 def maybe(typ: type) -> Callable[[Any], Any]:
159 return lambda x: None if x is None else typ(x)
162 def intx(x: Union[str, int]) -> int:
163 if isinstance(x, str):
168 def boolx(x: Union[str, bool]) -> bool:
169 if isinstance(x, str):
170 if x.upper() in ("ON", "TRUE", "1"):
172 if x.upper() in ("OFF", "FALSE", "0"):
174 raise ValueError(str(x) + " could not be parsed as a Boolean")
178 def l3str(x: Union[str, List[str]]) -> List[str]:
179 if isinstance(x, str):
183 if len(lx) != 3 or not all(isinstance(el, str) for el in x):
184 raise ValueError(str(lx) + " is not a list of three strings")
188 def pblist(x: Union[str, List[Tuple[str, str]]]) -> List[Tuple[str, str]]:
189 if isinstance(x, str):
191 def splitpair(s: str) -> Tuple[str, str]:
195 lx = [splitpair(el) for el in x.split(",")]
199 raise ValueError(str(lx) + " has too many elements (max 5)")
204 NON = 0 # Incoming, no response needed
205 INL = 1 # Birirectional, use `inline_response()`
206 EXT = 2 # Birirectional, use external responder
209 class BeeSurePkt(ProtoClass):
211 RESPOND = Respond.NON # Do not send anything back by default
212 IN_KWARGS: Tuple[Tuple[str, Callable[[Any], Any], Any], ...] = ()
213 OUT_KWARGS: Tuple[Tuple[str, Callable[[Any], Any], Any], ...] = ()
214 KWARGS: Tuple[Tuple[str, Callable[[Any], Any], Any], ...] = ()
215 In: Type["BeeSurePkt"]
216 Out: Type["BeeSurePkt"]
220 def __getattr__(self, name: str) -> Any:
223 def __setattr__(self, name: str, value: Any) -> None:
226 def __init__(self, *args: Any, **kwargs: Any):
228 Construct the object _either_ from (length, payload),
229 _or_ from the values of individual fields
231 self.payload: Union[List[str], bytes]
232 assert not args or (len(args) == 4 and not kwargs)
233 if args: # guaranteed to be two arguments at this point
234 self.vendor, self.imei, self.datalength, self.payload = args
236 if isinstance(self.payload, list):
237 self.decode(*self.payload)
239 self.decode(self.payload)
241 raise DecodeError(e, obj=self)
243 for kw, typ, dfl in self.KWARGS:
244 setattr(self, kw, typ(kwargs.pop(kw, dfl)))
247 self.__class__.__name__ + " stray kwargs " + str(kwargs)
250 def __repr__(self) -> str:
251 return "{}({})".format(
252 self.__class__.__name__,
256 'bytes.fromhex("{}")'.format(v.hex())
257 if isinstance(v, bytes)
260 for k, v in self.__dict__.items()
261 if not k.startswith("_")
265 def decode(self, *args: Any) -> None:
268 def in_decode(self, *args: str) -> None:
269 # Overridden in subclasses, otherwise do not decode payload
272 def out_decode(self, *args: str) -> None:
273 # Overridden in subclasses, otherwise do not decode payload
276 def encode(self) -> str:
279 def in_encode(self) -> str:
280 # Necessary to emulate terminal, which is not implemented
281 raise NotImplementedError(
282 self.__class__.__name__ + ".encode() not implemented"
285 def out_encode(self) -> str:
286 # Overridden in subclasses, otherwise command verb only
290 def PROTO(cls: "BeeSurePkt") -> str:
291 """Name of the class without possible .In / .Out suffix"""
294 proto, _ = cls.__name__.split(".")
300 def proto_name(cls) -> str:
301 """Name of the command as used externally"""
302 return PROTO_PREFIX + cls.PROTO[:16]
305 def packed(self) -> bytes:
307 payload = self.PROTO + "," + data if data else self.PROTO
308 return f"[LT*0000000000*{len(payload):04X}*{payload}]".encode()
311 class UNKNOWN(BeeSurePkt):
315 class _SET_PHONE(BeeSurePkt):
316 OUT_KWARGS = (("phonenumber", str, ""),)
318 def out_encode(self) -> str:
319 self.phonenumber: str
320 return self.phonenumber
323 class _LOC_DATA(BeeSurePkt):
324 def in_decode(self, *args: str) -> None:
325 p = SimpleNamespace()
327 for (obj, attr, func), val in zip(
331 (self, "gps_valid", lambda x: x == "A"),
333 (p, "nors", lambda x: 1 if x == "N" else -1),
335 (p, "eorw", lambda x: 1 if x == "E" else -1),
336 (self, "speed", float),
337 (self, "direction", float),
338 (self, "altitude", float),
339 (self, "num_of_sats", int),
340 (self, "gsm_strength_percentage", int),
341 (self, "battery_percentage", int),
342 (self, "pedometer", int),
343 (self, "tubmling_times", int),
344 (self, "device_status", lambda x: int(x, 16)),
345 (self, "gsm_cells_number", int),
346 (self, "connect_base_station_number", int),
352 setattr(obj, attr, func(val)) # type: ignore
353 rest_args = args[20:]
354 # (area_id, cell_id, strength)*
355 self.gsm_cells: List[Tuple[int, int, int]] = [
356 tuple(int(el) for el in rest_args[i * 3 : 3 + i * 3]) # type: ignore
357 for i in range(self.gsm_cells_number)
359 rest_args = rest_args[3 * self.gsm_cells_number :]
360 self.wifi_aps_number = int(rest_args[0])
361 # (SSID, MAC, strength)*
364 rest_args[1 + i * 3],
365 rest_args[2 + i * 3],
366 int(rest_args[3 + i * 3]),
368 for i in range(self.wifi_aps_number)
370 rest_args = rest_args[1 + 3 * self.wifi_aps_number :]
371 self.positioning_accuracy = float(rest_args[0])
377 # .replace(tzinfo=timezone.utc)
378 # .astimezone(tz=timezone.utc)
380 self.latitude = p.lat * p.nors
381 self.longitude = p.lon * p.eorw
383 def rectified(self) -> Report:
384 # self.gps_valid is supposed to mean it, but it does not. Perfectly
385 # good looking coordinates, with ten satellites, still get 'V'.
386 # I suspect that in reality, 'A' means "hint data is absent".
387 if self.gps_valid or self.num_of_sats > 3:
389 devtime=str(self.devtime),
390 battery_percentage=self.battery_percentage,
391 accuracy=self.positioning_accuracy,
392 altitude=self.altitude,
394 direction=self.direction,
395 latitude=self.latitude,
396 longitude=self.longitude,
400 devtime=str(self.devtime),
401 battery_percentage=self.battery_percentage,
404 gsm_cells=self.gsm_cells,
405 wifi_aps=self.wifi_aps,
410 RESPOND = Respond.INL
413 class CALL(_SET_PHONE):
417 class CENTER(_SET_PHONE):
421 class CONFIG(BeeSurePkt):
425 class CR(BeeSurePkt):
429 class FIND(BeeSurePkt):
433 class FLOWER(BeeSurePkt):
434 OUT_KWARGS = (("number", int, 1),)
436 def out_encode(self) -> str:
438 return str(self.number)
441 class ICCID(BeeSurePkt):
445 class LK(BeeSurePkt):
446 RESPOND = Respond.INL
448 def in_decode(self, *args: str) -> None:
453 self.tumbling_number = args[1]
455 self.battery_percentage = args[2]
457 def in_encode(self) -> str:
461 class LZ(BeeSurePkt):
462 OUT_KWARGS = (("language", int, 1), ("timezone", int, 0))
464 def out_encode(self) -> str:
465 return f"{self.language},{self.timezone}"
468 class MESSAGE(BeeSurePkt):
469 OUT_KWARGS = (("message", str, ""),)
471 def out_encode(self) -> str:
472 return str(self.message.encode("utf_16_be").hex())
475 class MONITOR(BeeSurePkt):
479 class _PHB(BeeSurePkt):
480 OUT_KWARGS: Tuple[Tuple[str, Callable[[Any], Any], Any], ...] = (
481 ("entries", pblist, []),
484 def out_encode(self) -> str:
485 self.entries: List[Tuple[str, str]]
488 ",".join((num, name.encode("utf_16_be").hex()))
489 for name, num in self.entries
502 class POWEROFF(BeeSurePkt):
506 class RESET(BeeSurePkt):
510 class SOS(BeeSurePkt):
511 OUT_KWARGS = (("phonenumbers", l3str, ["", "", ""]),)
513 def out_encode(self) -> str:
514 self.phonenumbers: List[str]
515 return ",".join(self.phonenumbers)
518 class SOS1(_SET_PHONE):
522 class SOS2(_SET_PHONE):
526 class SOS3(_SET_PHONE):
530 class TK(BeeSurePkt):
532 RESPOND = Respond.INL
534 def in_decode(self, *args: Any) -> None:
535 assert len(args) == 1 and isinstance(args[0], bytes)
538 .replace(b"}*", b"*")
539 .replace(b"},", b",")
540 .replace(b"}[", b"[")
541 .replace(b"}]", b"]")
542 .replace(b"}}", b"}")
545 def out_encode(self) -> str:
546 return "1" # 0 - receive failure, 1 - receive success
549 class TKQ(BeeSurePkt):
550 RESPOND = Respond.INL
553 class TKQ2(BeeSurePkt):
554 RESPOND = Respond.INL
561 class UD2(_LOC_DATA):
565 class UPLOAD(BeeSurePkt):
566 OUT_KWARGS = (("interval", int, 600),)
568 def out_encode(self) -> str:
569 return str(self.interval)
572 # Build dicts protocol number -> class and class name -> protocol number
574 if True: # just to indent the code, sorry!
577 for name, cls in globals().items()
579 and issubclass(cls, BeeSurePkt)
580 and not name.startswith("_")
582 CLASSES[cls.__name__] = cls
587 ) -> Union[Type[BeeSurePkt], List[str]]:
588 if prefix.startswith(PROTO_PREFIX):
589 pname = prefix[len(PROTO_PREFIX) :].upper()
591 raise KeyError(pname)
592 lst = [name for name in CLASSES.keys() if name.upper().startswith(pname)]
594 if len(lst) == 1: # unique prefix match
595 return CLASSES[proto]
596 if proto == pname: # exact match
597 return CLASSES[proto]
601 def proto_handled(proto: str) -> bool:
602 return proto.startswith(PROTO_PREFIX)
605 def proto_of_message(packet: bytes) -> str:
606 return PROTO_PREFIX + packet[20:-1].split(b",")[0].decode()
609 def imei_from_packet(packet: bytes) -> Optional[str]:
610 toskip, _, imei, _ = _framestart(packet)
611 if toskip == 0 and imei != "":
616 def is_goodbye_packet(packet: bytes) -> bool:
620 def inline_response(packet: bytes) -> Optional[bytes]:
621 proto = packet[20:-1].split(b",")[0].decode()
624 if cls.RESPOND is Respond.INL:
625 return cls.Out().packed
629 def probe_buffer(buffer: bytes) -> bool:
630 return bool(RE.search(buffer))
633 def parse_message(packet: bytes, is_incoming: bool = True) -> BeeSurePkt:
634 """From a packet (without framing bytes) derive the XXX.In object"""
635 toskip, vendor, imei, datalength = _framestart(packet)
636 bsplits = packet[20:-1].split(b",", 1)
638 proto = bsplits[0].decode("ascii")
639 except UnicodeDecodeError:
640 proto = str(bsplits[0])
641 if len(bsplits) == 2:
646 cls = CLASSES[proto].In if is_incoming else CLASSES[proto].Out
648 # Some people encode their SSIDs in non-utf8
651 else rest.decode("Windows-1252").split(",")
654 return cls(vendor, imei, datalength, payload)
655 except (DecodeError, ValueError, IndexError) as e:
656 cause: Union[DecodeError, ValueError, IndexError] = e
659 cause = ValueError(f"Proto {proto} is unknown")
661 retobj = UNKNOWN.In(vendor, imei, datalength, payload)
663 retobj = UNKNOWN.Out(vendor, imei, datalength, payload)
664 retobj.proto = proto # Override class attr with object attr
669 def exposed_protos() -> List[Tuple[str, bool]]:
671 (cls.proto_name(), False)
672 for cls in CLASSES.values()
673 if hasattr(cls, "rectified")