44 lines
1.1 KiB
Python
44 lines
1.1 KiB
Python
import random
|
|
import time
|
|
|
|
|
|
class UARTTransport:
|
|
def __init__(self, controller):
|
|
self.controller = controller
|
|
self.connected = True
|
|
self.latency_ms = 0
|
|
self.packet_loss_percent = 0
|
|
|
|
def send(self, message):
|
|
if not self.connected:
|
|
return {
|
|
"type": "error",
|
|
"success": False,
|
|
"error": "UART disconnected"
|
|
}
|
|
|
|
if self.latency_ms > 0:
|
|
time.sleep(self.latency_ms / 1000)
|
|
|
|
if self.packet_loss_percent > 0:
|
|
if random.randint(1, 100) <= self.packet_loss_percent:
|
|
return {
|
|
"type": "error",
|
|
"success": False,
|
|
"error": "UART packet lost"
|
|
}
|
|
|
|
return self.controller.handle_message(message)
|
|
|
|
def disconnect(self):
|
|
self.connected = False
|
|
|
|
def restore(self):
|
|
self.connected = True
|
|
|
|
def set_latency(self, latency_ms):
|
|
self.latency_ms = max(0, int(latency_ms))
|
|
|
|
def set_packet_loss(self, percent):
|
|
self.packet_loss_percent = max(0, min(100, int(percent)))
|