Files
mesh-network-project/relay/connection.py

44 lines
1.4 KiB
Python
Raw Normal View History

from crypt_random import secure_random
2026-05-15 12:09:41 +10:00
from lora_handler import LoRaHandler, LoRaMessage
2026-05-15 12:09:41 +10:00
import time
import uasyncio as asyncio
class Connection:
2026-05-15 17:14:33 +10:00
def __init__(self, bluetooth_handler=None):
self.bluetooth_handler = bluetooth_handler
self.load_public_constants()
2026-05-15 12:09:41 +10:00
# generate diffie-hellman keys
print("Generating keys...")
print(" - Generating private key...")
self.private_key = int.from_bytes(secure_random(32), "big") # 32 bytes = 256 bits
print(" - Generating public key...")
self.public_key = pow(self.G, self.private_key, self.P)
# start lora handler
self.lora = LoRaHandler()
2026-05-15 17:14:33 +10:00
async def bluetooth_listener(self):
while True:
msg_type, payload = await self.bluetooth_handler.packets.get()
if msg_type == 3: # advertise self
self.lora.advertise()
2026-05-15 12:09:41 +10:00
async def start(self):
print("Starting connection...")
2026-05-15 17:14:33 +10:00
if self.bluetooth_handler:
asyncio.create_task(self.bluetooth_listener())
2026-05-15 12:09:41 +10:00
while True:
msg: LoRaMessage = await self.lora.message_queue.get()
print(f"Received message from {msg.sender_id}: {msg.payload}")
def load_public_constants(self):
with open("public_constants.txt", "r") as f:
self.P = int(f.readline(), 16)
self.G = int(f.readline(), 16)