# RAK4630 HDGL node
from network import LoRa
import socket
import struct
import time
import math
import machine
import uos
import urandom as random

# -----------------------------
# LoRa Setup
# -----------------------------
lora = LoRa(mode=LoRa.LORA, region=LoRa.EU868)
s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
s.setblocking(False)

# -----------------------------
# HDGL Lattice Parameters
# -----------------------------
STRANDS = 8
SLOTS = 4
lattice = [[0.0 for _ in range(SLOTS)] for _ in range(STRANDS)]

# Recursive evolution
def evolve_lattice(lattice, tick):
    for s in range(STRANDS):
        for slot in range(SLOTS):
            delta = 0.02 * (1 + math.sin(2*math.pi*(slot+1)/SLOTS))
            lattice[s][slot] += delta + (random.getrandbits(4)/64.0)
    return lattice

# Encode lattice to bytes
def encode_lattice(lattice, tick):
    # Flatten and convert to 1 byte per slot (0-255)
    flat = [int(min(max(x*50,0),255)) for strand in lattice for x in strand]
    return struct.pack("B"*len(flat) + "B", *flat, tick%256)

# -----------------------------
# Main Loop
# -----------------------------
tick = 0
while True:
    lattice = evolve_lattice(lattice, tick)
    packet = encode_lattice(lattice, tick)
    try:
        s.send(packet)
    except Exception as e:
        print("Send error:", e)
    tick += 1
    time.sleep_ms(100)  # adjust tick rate
