diff --git a/host/fipy/lib/espnow.py b/host/fipy/lib/espnow.py new file mode 100644 index 0000000000000000000000000000000000000000..1e04f9bd393cff2917770eda5c66997d92442da9 --- /dev/null +++ b/host/fipy/lib/espnow.py @@ -0,0 +1,53 @@ +import network +from network import ESPNOW +import time +# from lib.rtc_time import RTCTime + +import struct + +w = network.WLAN() +self_mac, sta = w.mac() + +class Forte_ESPNOW: + def __init__(self): + ESPNOW.init() + p = ESPNOW.add_peer("58CF7904412C") # TODO: make management of peers dynamic (line 37) + ESPNOW.on_recv(espnow_recv) + +def espnow_respond(mac): + msg = struct.pack("<6sl", self_mac, time.time() * 1000) + print(time.time() * 1000) + ESPNOW.send(mac, msg) + print("response sent") + +def espnow_recv(result): + print("message recv") + mac, peer, msg = result + + data = bytes_to_data(msg) + try: + print(data["amountData"]) + print(data["timestamp"]) + print(data["data"]) + + except Exception as error: + print(error) + + # if(result not in ESPNOW.get_peers()): + # ESPNOW.add_peer(mac) + espnow_respond(mac) + +def bytes_to_data(msg): + # turn bytes from message into 22-tuple of integers(identifiers), floats(values), integer(amount) and long(timestamp) + data = struct.unpack("<10i10fil", bytes(msg)) + amountData = data[20] + timestamp = data[21] + identifiers = data[0:amountData] + values = data[10 : (10 + amountData)] + return { + "amountData": amountData, + "timestamp": timestamp, + "data": dict(zip(identifiers, values)), + } + +