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):
210 RESPOND = Respond.NON # Do not send anything back by default
211 IN_KWARGS: Tuple[Tuple[str, Callable[[Any], Any], Any], ...] = ()
212 OUT_KWARGS: Tuple[Tuple[str, Callable[[Any], Any], Any], ...] = ()
213 KWARGS: Tuple[Tuple[str, Callable[[Any], Any], Any], ...] = ()
214 In: Type["BeeSurePkt"]
215 Out: Type["BeeSurePkt"]
219 def __getattr__(self, name: str) -> Any:
222 def __setattr__(self, name: str, value: Any) -> None:
225 def __init__(self, *args: Any, **kwargs: Any):
227 Construct the object _either_ from (length, payload),
228 _or_ from the values of individual fields
230 self.payload: Union[List[str], bytes]
231 assert not args or (len(args) == 4 and not kwargs)
232 if args: # guaranteed to be two arguments at this point
233 self.vendor, self.imei, self.datalength, self.payload = args
235 if isinstance(self.payload, list):
236 self.decode(*self.payload)
238 self.decode(self.payload)
240 raise DecodeError(e, obj=self)
242 for kw, typ, dfl in self.KWARGS:
243 setattr(self, kw, typ(kwargs.pop(kw, dfl)))
246 self.__class__.__name__ + " stray kwargs " + str(kwargs)
249 def __repr__(self) -> str:
250 return "{}({})".format(
251 self.__class__.__name__,
255 'bytes.fromhex("{}")'.format(v.hex())
256 if isinstance(v, bytes)
259 for k, v in self.__dict__.items()
260 if not k.startswith("_")
264 def decode(self, *args: Any) -> None:
267 def in_decode(self, *args: str) -> None:
268 # Overridden in subclasses, otherwise do not decode payload
271 def out_decode(self, *args: str) -> None:
272 # Overridden in subclasses, otherwise do not decode payload
275 def encode(self) -> str:
278 def in_encode(self) -> str:
279 # Necessary to emulate terminal, which is not implemented
280 raise NotImplementedError(
281 self.__class__.__name__ + ".encode() not implemented"
284 def out_encode(self) -> str:
285 # Overridden in subclasses, otherwise command verb only
289 def PROTO(cls: "BeeSurePkt") -> str:
290 """Name of the class without possible .In / .Out suffix"""
293 proto, _ = cls.__name__.split(".")
299 def proto_name(cls) -> str:
300 """Name of the command as used externally"""
301 return PROTO_PREFIX + cls.PROTO[:16]
304 def packed(self) -> bytes:
306 payload = self.PROTO + "," + data if data else self.PROTO
307 return f"[LT*0000000000*{len(payload):04X}*{payload}]".encode()
310 class UNKNOWN(BeeSurePkt):
314 class _LOC_DATA(BeeSurePkt):
315 def in_decode(self, *args: str) -> None:
316 p = SimpleNamespace()
318 for (obj, attr, func), val in zip(
322 (self, "gps_valid", lambda x: x == "A"),
324 (p, "nors", lambda x: 1 if x == "N" else -1),
326 (p, "eorw", lambda x: 1 if x == "E" else -1),
327 (self, "speed", float),
328 (self, "direction", float),
329 (self, "altitude", float),
330 (self, "num_of_sats", int),
331 (self, "gsm_strength_percentage", int),
332 (self, "battery_percentage", int),
333 (self, "pedometer", int),
334 (self, "tubmling_times", int),
335 (self, "device_status", lambda x: int(x, 16)),
336 (self, "gsm_cells_number", int),
337 (self, "connect_base_station_number", int),
343 setattr(obj, attr, func(val)) # type: ignore
344 rest_args = args[20:]
345 # (area_id, cell_id, strength)*
346 self.gsm_cells: List[Tuple[int, int, int]] = [
347 tuple(int(el) for el in rest_args[i * 3 : 3 + i * 3]) # type: ignore
348 for i in range(self.gsm_cells_number)
350 rest_args = rest_args[3 * self.gsm_cells_number :]
351 self.wifi_aps_number = int(rest_args[0])
352 # (SSID, MAC, strength)*
355 rest_args[1 + i * 3],
356 rest_args[2 + i * 3],
357 int(rest_args[3 + i * 3]),
359 for i in range(self.wifi_aps_number)
361 rest_args = rest_args[1 + 3 * self.wifi_aps_number :]
362 self.positioning_accuracy = float(rest_args[0])
368 # .replace(tzinfo=timezone.utc)
369 # .astimezone(tz=timezone.utc)
371 self.latitude = p.lat * p.nors
372 self.longitude = p.lon * p.eorw
374 def rectified(self) -> Report:
377 devtime=str(self.devtime),
378 battery_percentage=self.battery_percentage,
379 accuracy=self.positioning_accuracy,
380 altitude=self.altitude,
382 direction=self.direction,
383 latitude=self.latitude,
384 longitude=self.longitude,
388 devtime=str(self.devtime),
389 battery_percentage=self.battery_percentage,
392 gsm_cells=self.gsm_cells,
393 wifi_aps=self.wifi_aps,
398 RESPOND = Respond.INL
401 class CONFIG(BeeSurePkt):
405 class CR(BeeSurePkt):
409 class FLOWER(BeeSurePkt):
410 OUT_KWARGS = (("number", int, 1),)
412 def out_encode(self) -> str:
414 return str(self.number)
417 class ICCID(BeeSurePkt):
421 class LK(BeeSurePkt):
422 RESPOND = Respond.INL
424 def in_decode(self, *args: str) -> None:
429 self.tumbling_number = args[1]
431 self.battery_percentage = args[2]
433 def in_encode(self) -> str:
437 class MESSAGE(BeeSurePkt):
438 OUT_KWARGS = (("message", str, ""),)
440 def out_encode(self) -> str:
441 return str(self.message.encode("utf_16_be").hex())
444 class _PHB(BeeSurePkt):
445 OUT_KWARGS: Tuple[Tuple[str, Callable[[Any], Any], Any], ...] = (
446 ("entries", pblist, []),
449 def out_encode(self) -> str:
450 self.entries: List[Tuple[str, str]]
453 ",".join((num, name.encode("utf_16_be").hex()))
454 for name, num in self.entries
467 class POWEROFF(BeeSurePkt):
471 class RESET(BeeSurePkt):
475 class SOS(BeeSurePkt):
476 OUT_KWARGS = (("phonenumbers", l3str, ["", "", ""]),)
478 def out_encode(self) -> str:
479 self.phonenumbers: List[str]
480 return ",".join(self.phonenumbers)
483 class _SET_PHONE(BeeSurePkt):
484 OUT_KWARGS = (("phonenumber", str, ""),)
486 def out_encode(self) -> str:
487 self.phonenumber: str
488 return self.phonenumber
491 class SOS1(_SET_PHONE):
495 class SOS2(_SET_PHONE):
499 class SOS3(_SET_PHONE):
503 class TK(BeeSurePkt):
504 RESPOND = Respond.INL
506 def in_decode(self, *args: Any) -> None:
507 assert len(args) == 1 and isinstance(args[0], bytes)
510 .replace(b"}*", b"*")
511 .replace(b"},", b",")
512 .replace(b"}[", b"[")
513 .replace(b"}]", b"]")
514 .replace(b"}}", b"}")
517 def out_encode(self) -> str:
518 return "1" # 0 - receive failure, 1 - receive success
521 class TKQ(BeeSurePkt):
522 RESPOND = Respond.INL
525 class TKQ2(BeeSurePkt):
526 RESPOND = Respond.INL
533 class UD2(_LOC_DATA):
537 # Build dicts protocol number -> class and class name -> protocol number
539 if True: # just to indent the code, sorry!
542 for name, cls in globals().items()
544 and issubclass(cls, BeeSurePkt)
545 and not name.startswith("_")
547 CLASSES[cls.__name__] = cls
552 ) -> Union[Type[BeeSurePkt], List[str]]:
553 if prefix.startswith(PROTO_PREFIX):
554 pname = prefix[len(PROTO_PREFIX) :].upper()
556 raise KeyError(pname)
557 lst = [name for name in CLASSES.keys() if name.upper().startswith(pname)]
559 if len(lst) == 1: # unique prefix match
560 return CLASSES[proto]
561 if proto == pname: # exact match
562 return CLASSES[proto]
566 def proto_handled(proto: str) -> bool:
567 return proto.startswith(PROTO_PREFIX)
570 def proto_of_message(packet: bytes) -> str:
571 return PROTO_PREFIX + packet[20:-1].split(b",")[0].decode()
574 def imei_from_packet(packet: bytes) -> Optional[str]:
575 toskip, _, imei, _ = _framestart(packet)
576 if toskip == 0 and imei != "":
581 def is_goodbye_packet(packet: bytes) -> bool:
585 def inline_response(packet: bytes) -> Optional[bytes]:
586 proto = packet[20:-1].split(b",")[0].decode()
589 if cls.RESPOND is Respond.INL:
590 return cls.Out().packed
594 def probe_buffer(buffer: bytes) -> bool:
595 return bool(RE.search(buffer))
598 def parse_message(packet: bytes, is_incoming: bool = True) -> BeeSurePkt:
599 """From a packet (without framing bytes) derive the XXX.In object"""
600 toskip, vendor, imei, datalength = _framestart(packet)
602 splits = packet[20:-1].decode().split(",")
603 proto = splits[0] if len(splits) > 0 else ""
604 payload: Union[List[str], bytes] = splits[1:]
605 except UnicodeDecodeError:
606 bsplits = packet[20:-1].split(b",", 1)
607 if len(bsplits) == 2:
608 proto = bsplits[0].decode("ascii")
610 if proto not in CLASSES:
611 cause: Union[DecodeError, ValueError, IndexError] = ValueError(
612 f"Proto {proto} is unknown"
617 return CLASSES[proto].In(vendor, imei, datalength, payload)
619 return CLASSES[proto].Out(vendor, imei, datalength, payload)
620 except (DecodeError, ValueError, IndexError) as e:
623 retobj = UNKNOWN.In(vendor, imei, datalength, payload)
625 retobj = UNKNOWN.Out(vendor, imei, datalength, payload)
626 retobj.proto = proto # Override class attr with object attr
631 def exposed_protos() -> List[Tuple[str, bool]]:
633 (cls.proto_name(), False)
634 for cls in CLASSES.values()
635 if hasattr(cls, "rectified")