#!/usr/bin/env python3 # BFi53ER0 Battery-Free Bluetooth Gateway -- example: read the TCP feed. # # python3 tcp_feed.py bfi53er0-xxxx.local # the name on the label # python3 tcp_feed.py 192.168.1.20 # python3 tcp_feed.py GATEWAY --key HEX # encrypted output (needs 'cryptography') # # The same JSON objects as over UDP, one per line, on TCP port 9000. With a # microSD card in the gateway, a client that connects first receives the # telegrams it missed while it was away, then the live stream. Read every # line promptly: a client that does not take a line within 2 s is # disconnected (and catches up when it connects again). This example # reconnects by itself. # # Python 3, standard library only. The feed answers the local network only. # # (c) 2026 BANFi Semiconductor Co., Ltd. and FL Semiconductor LLC. You may # use, copy and modify this example to integrate with BFi53ER0 products. import base64 import json import socket import sys import time if len(sys.argv) < 2: sys.exit("usage: tcp_feed.py GATEWAY") HOST, PORT = sys.argv[1], 9000 def opener(keyhex): """Encrypted output (firmware 0.57.105 and later): open an AES-256-GCM envelope. Needs the 'cryptography' package (pip install cryptography); only this option does. Returns a function that gives the telegram, or None for an envelope already seen (the other family's copy, or a replay).""" from cryptography.hazmat.primitives.ciphers.aead import AESGCM gcm, last = AESGCM(bytes.fromhex(keyhex)), {} def open_(e): aad = ("A256GCM|%s|%d|%d|%d" % (e["gw"], e["kid"], e["b"], e["n"])).encode() try: t = json.loads(gcm.decrypt(base64.b64decode(e["iv"]), base64.b64decode(e["ct"]), aad)) except Exception: print("an envelope did not authenticate (wrong key, or altered): dropped", file=sys.stderr) return None if last.get(e["gw"], (-1, -1)) >= (e["b"], e["n"]): return None last[e["gw"]] = (e["b"], e["n"]) return t return open_ KEY = sys.argv[sys.argv.index("--key") + 1] if "--key" in sys.argv else None while True: try: with socket.create_connection((HOST, PORT), timeout=10) as s: s.settimeout(None) print("connected to %s:%d" % (HOST, PORT), file=sys.stderr) open_ = opener(KEY) if KEY else None # a new connection: a fresh sequence check for line in s.makefile("r", encoding="utf-8"): t = json.loads(line) if "enc" in t: if not open_: sys.exit("encrypted output: run with --key HEX") t = open_(t) if t is None: continue if "io" in t: # analog data, when chosen on the gateway (0.57.117) print("%s %s" % (t["io"], json.dumps({k: v for k, v in t.items() if k != "io"})), flush=True) continue print("%s seq %-9d rssi %4d dBm payload %s" % (t["src"], t["seq"], t["rssi"], t["d"]), flush=True) print("the gateway closed the connection", file=sys.stderr) except OSError as e: print("not connected (%s); trying again in 5 s" % e, file=sys.stderr) time.sleep(5)