Skip to content

Commit

Permalink
Merge branch 'master' into masater_merge
Browse files Browse the repository at this point in the history
  • Loading branch information
beniroquai committed Jul 5, 2023
2 parents 4a9dcbf + fff3128 commit cee479a
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 46 deletions.
3 changes: 3 additions & 0 deletions uc2rest/UC2Client.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,9 @@ def __init__(self, host=None, port=31950, serialport=None, identity="UC2_Feather
# initialize module controller
self.modules = Modules(parent=self)

def is_sending(self):
return self.serial.is_sending

def post_json(self, path, payload, getReturn=True, timeout=1):
if self.is_wifi:
# FIXME: this is not working
Expand Down
15 changes: 10 additions & 5 deletions uc2rest/motor.py
Original file line number Diff line number Diff line change
Expand Up @@ -452,13 +452,18 @@ def get_position(self, axis=None, timeout=1):
"task":path,
"position":True,
}
r = self._parent.post_json(path, payload, timeout=timeout)
_position = np.array((0,0,0,0)) # T,X,Y,Z
_physicalStepSizes = np.array((self.stepSizeT, self.stepSizeX, self.stepSizeY, self.stepSizeZ))
try:
for index, istepper in enumerate(r["motor"]["steppers"]):
_position[istepper["stepperid"]]=istepper["position"]*_physicalStepSizes[self.motorAxisOrder[index]]
except Exception as e: self._parent.logger.error(e)

# this may be an asynchronous call.. #FIXME!
for i in range(3):
if not self._parent.is_sending():
r = self._parent.post_json(path, payload, timeout=timeout)
if "motor" in r:
for index, istepper in enumerate(r["motor"]["steppers"]):
_position[istepper["stepperid"]]=istepper["position"]*_physicalStepSizes[self.motorAxisOrder[index]]
break

return _position

def set_position(self, axis=1, position=0, timeout=1):
Expand Down
88 changes: 47 additions & 41 deletions uc2rest/mserial.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
T_SERIAL_WARMUP = 3 # the time to wait for the serial to warm up

class Serial(object):

def __init__(self, port, baudrate, timeout=1, identity="UC2_Feather", parent=None, DEBUG=False):
self.serialport = port
self.baudrate = baudrate
Expand All @@ -19,22 +19,22 @@ def __init__(self, port, baudrate, timeout=1, identity="UC2_Feather", parent=Non
self.DEBUG = DEBUG

self.isSafetyBreak = False

# default version (v1 or v2) for the API
self.versionFirmware = "V2.0"

self.NumberRetryReconnect = 0
self.MaxNumberRetryReconnect = 0

self.open() # creates self.serialdevice
# switch between different api versions

# switch between different api versions
if self.versionFirmware == "V1.2":
self._parent.APIVersion = 1
elif self.versionFirmware == "V2.0":
self._parent.APIVersion = 2


def open(self):
'''Open the serial port'''
self.is_connected = False
Expand All @@ -47,7 +47,7 @@ def open(self):
correctFirmware = self.checkFirmware()
if not correctFirmware:
raise Exception("Wrong firmware")

self._parent.logger.debug("We are connected: "+str(self.is_connected) + " on port: "+self.serialdevice.port)
return self.serialdevice
except Exception as e:
Expand Down Expand Up @@ -80,7 +80,7 @@ def open(self):
self.serialport = "NotConnected"
self.serialdevice = SerialDeviceDummy()
self._parent.logger.debug("No USB device connected! Using DUMMY!")
return self.serialdevice
return self.serialdevice

def checkFirmware(self, timeout=1):
"""Check if the firmware is correct"""
Expand All @@ -91,16 +91,16 @@ def checkFirmware(self, timeout=1):
except Exception as e:
self._parent.logger.error(e)
self.versionFirmware = "V2.0"
if _state["identifier_name"] == self.identity:

if _state["identifier_name"] == self.identity:
return True

else: return False


def closeSerial(self):
self.serialdevice.close()

def reconnect(self):
"""Reconnect to serial device"""
if self.is_serial:
Expand All @@ -115,20 +115,21 @@ def get_json(self, path):
self._parent.logger.debug(message)
returnmessage = self.serialdevice.write(message.encode(encoding='UTF-8'))
return returnmessage

def post_json(self, path, payload={}, getReturn=True, timeout=1):
"""Make an HTTP POST request and return the JSON response"""
self.is_sending = True
if "task" not in payload:
payload["task"] = path

if "isblock" in payload:
is_blocking = payload["isblock"]
else:
is_blocking = True

# write message to the serial
self.writeSerial(payload)

if getReturn:
# we read the return message
#self._parent.logger.debug(payload)
Expand All @@ -141,17 +142,18 @@ def post_json(self, path, payload={}, getReturn=True, timeout=1):
self.open()
else:
returnmessage = False
self.is_sending = False
return returnmessage

def writeSerial(self, payload):
"""Write JSON document to serial device"""
try:
if self.serialport == "NotConnected" and self.NumberRetryReconnect<self.MaxNumberRetryReconnect:
# try to reconnect
self._parent.logger.debug("Trying to reconnect to serial device: "+str(self.NumberRetryReconnect))
# try to reconnect
self._parent.logger.debug("Trying to reconnect to serial device: "+str(self.NumberRetryReconnect))
self.NumberRetryReconnect += 1
self.open()

self.serialdevice.flushInput()
self.serialdevice.flushOutput()
except Exception as e:
Expand Down Expand Up @@ -210,20 +212,20 @@ def readSerial(self, is_blocking=True, timeout = 1): # TODO: hardcoded timeout -
if self.DEBUG: self._parent.logger.debug("Casting json string from serial to Python dict failed")
self.isSafetyBreak = False
return _returnmessage

class SerialManagerWrapper(object):

def __init__(self, SerialManager, DEBUG = True, parent=None) -> None:
self._parent=parent
self._parent.logger.debug("SerialManagerWrapper init")
self.SerialManager = SerialManager
self.isSafetyBreak = False
self.DEBUG = DEBUG

async def post_json(self, path, payload={}, getReturn=True, timeout=1):
if "task" not in payload:
payload["task"] = path

if "isblock" in payload:
is_blocking = payload["isblock"]
else:
Expand All @@ -240,7 +242,7 @@ async def post_json(self, path, payload={}, getReturn=True, timeout=1):
else:
returnmessage = False
return returnmessage

async def writeSerial(self, payload):
"""Write JSON document to serial device"""
if type(payload)==dict:
Expand Down Expand Up @@ -281,42 +283,44 @@ async def readSerial(self, is_blocking=True, timeout = 1): # TODO: hardcoded tim
self.isSafetyBreak = False
return _returnmessage
class SerialDummy(object):

def __init__(self, port, baudrate, timeout=1, parent=None):
self.port = port
self.baudrate = baudrate
self.timeout = timeout
self._parent = parent
self.versionFirmware = "Dummy"

self.is_sending = False
self.serialdevice = self.open()

def open(self):
'''Open the serial port'''
return SerialDeviceDummy()
return SerialDeviceDummy()

def checkFirmware(self):
"""Check if the firmware is correct"""
return True

def close(self):
self.closeSerial()

def closeSerial(self):
self.serialdevice.close()

def reconnect(self):
"""Reconnect to serial device"""
if self.is_serial:
self.initSerial(self.serialport, self.baudrate)

def get_json(self, path):
"""Perform an HTTP GET request and return the JSON response"""
self.is_sending = True
message = {"task":path}
message = json.dumps(message)
self.serialdevice.flushInput()
self.serialdevice.flushOutput()
returnmessage = self.serialdevice.write(message.encode(encoding='UTF-8'))
self.is_sending = False
return returnmessage

def post_json(self, path, payload={}, getReturn=True, timeout=1):
Expand All @@ -337,10 +341,12 @@ def post_json(self, path, payload={}, getReturn=True, timeout=1):
else:
returnmessage = None
return returnmessage

def writeSerial(self, payload):
"""Write JSON document to serial device"""
try:
# clear any data that's in the buffer
self.serialdevice.readline()
self.serialdevice.flushInput()
self.serialdevice.flushOutput()
except Exception as e:
Expand Down Expand Up @@ -389,22 +395,22 @@ def readSerial(self, is_blocking=True, timeout = 15): # TODO: hardcoded timeout
returnmessage = ""
return returnmessage


class SerialDeviceDummy(object):
def __init__(self) -> None:
pass

def close(self):
pass

def flushInput(self):
pass

def flushOutput(self):
pass

def write(self, payload):
pass

def readline(self):
return b'{"task":"dummy"}--'
return b'{"task":"dummy"}--'

0 comments on commit cee479a

Please sign in to comment.