from pyLoraRFM9x import LoRa, ModemConfig
import MultiNode

#class MessageType(IntEnum):
#    DeviceStatus = 1;
#
#def decode_packet(data):
#    packet_type = data[0]
#    
#    #match packet_type:
#    #    case MessageType.DeviceStatus:
#    
#    if packet_type == MessageType.DeviceStatus:
#        return struct.unpack('f', data[1:5])[0]

# This is our callback function that runs when a message is received
def on_recv(payload):
    #print("From:", payload.header_from)
    #print("Received:", payload.message)
    #print("RSSI: {}; SNR: {}".format(payload.rssi, payload.snr))
    MultiNode.process_packet(payload)
    #print(payload.message.hex())
    #rx_id = int.from_bytes(payload.message[0:2], byteorder="little")
    #tx_id = int.from_bytes(payload.message[2:4], byteorder="little")
    #msg_id = int.from_bytes(payload.message[4:8], byteorder="little")
    #length = payload.message[8]
    #data = payload.message[9 : 9 + length]
    #data_hash = payload.message[9 + length : 9 + length + HASH_LENGTH]
    #
    #if len(payload.message) != length + 9 + HASH_LENGTH:
    #    print(f"Invalid length! Expected {length + 9 + HASH_LENGTH} actual {len(payload.message)}")
    #    return
    #
    #hash_function = blake2s(key=0x0.to_bytes(8, "little"), digest_size=8)
    #hash_function.update(payload.message[: -HASH_LENGTH])
#
    #if hash_function.digest() != data_hash:
    #    print(f"Hash doesn't match! Expected {hash_function.digest()} got {data_hash}")
    #    return
    
    #print(f"Received {struct.unpack('f', data[1:])[0]:.3f} V from {tx_id} with destination {rx_id} and {payload.rssi} dB(?) RSSI and {payload.snr} dB(?) SNR")
    #print(f"{tx_id} #{msg_id}: {decode_packet(data):.3f} V, {payload.rssi} dB(?) RSSI, {payload.snr} dB(?) SNR {(time.clock_gettime_ns(0) - start_time) / 1e9}")


# Use chip select 1. GPIO pin 5 will be used for interrupts and set reset pin to 25
# The address of this device will be set to 2
lora = LoRa(0, 25, 255, reset_pin = 22, modem_config=ModemConfig.Bw125Cr45Sf128, tx_power=14, freq=868, acks=False)#, receive_all=True)
lora.cad_timeout = 1
lora.on_recv = on_recv
lora.set_mode_rx()

import time

while True:
    time.sleep(0.5)