Reticulum/FPE/Interfaces/SerialInterface.py

84 lines
1.9 KiB
Python
Raw Normal View History

2016-06-03 17:02:02 +00:00
from __future__ import print_function
from Interface import Interface
2018-03-19 15:39:08 +00:00
from time import sleep
2016-06-03 17:02:02 +00:00
import sys
import serial
import threading
2018-03-19 15:39:08 +00:00
import FPE
2016-06-03 17:02:02 +00:00
class SerialInterface(Interface):
MAX_CHUNK = 32768
TIMEOUT_SECONDS = 0.15
owner = None
port = None
speed = None
databits = None
parity = None
stopbits = None
serial = None
def __init__(self, owner, port, speed, databits, parity, stopbits):
2018-03-19 15:39:08 +00:00
self.serial = None
2016-06-03 17:02:02 +00:00
self.owner = owner
self.port = port
self.speed = speed
self.databits = databits
self.parity = serial.PARITY_NONE
self.stopbits = stopbits
if parity.lower() == "e" or parity.lower() == "even":
self.parity = serial.PARITY_EVEN
if parity.lower() == "o" or parity.lower() == "odd":
self.parity = serial.PARITY_ODD
try:
2018-03-19 15:39:08 +00:00
FPE.log("Opening serial port "+self.port+"...")
2016-06-03 17:02:02 +00:00
self.serial = serial.Serial(
port = self.port,
baudrate = self.speed,
bytesize = self.databits,
parity = self.parity,
stopbits = self.stopbits,
timeout = SerialInterface.TIMEOUT_SECONDS,
xonxoff = False,
rtscts = False,
write_timeout = None,
dsrdtr = False,
)
except Exception as e:
2018-03-19 15:39:08 +00:00
FPE.log("Could not create serial port", FPE.LOG_ERROR)
2016-06-03 17:02:02 +00:00
raise e
if self.serial.is_open:
thread = threading.Thread(target=self.readLoop)
thread.setDaemon(True)
thread.start()
2018-03-19 15:39:08 +00:00
sleep(0.5)
FPE.log("Serial port "+self.port+" is now open")
2016-06-03 17:02:02 +00:00
else:
raise IOError("Could not open serial port")
def processIncoming(self, data):
2018-03-19 19:51:26 +00:00
self.owner.inbound(data)
2016-06-03 17:02:02 +00:00
def processOutgoing(self,data):
2018-03-19 15:39:08 +00:00
written = self.serial.write(data)
if written != len(data):
raise IOError("Serial interface only wrote "+str(written)+" bytes of "+str(len(data)))
2016-06-03 17:02:02 +00:00
def readLoop(self):
2018-03-19 15:39:08 +00:00
#pass
2016-06-03 17:02:02 +00:00
while self.serial.is_open:
data = self.serial.read(size=self.owner.__class__.MTU)
if not data == "":
self.processIncoming(data)