Skip to content

Commit

Permalink
minor updates
Browse files Browse the repository at this point in the history
  • Loading branch information
myTonino committed Jan 28, 2023
1 parent f2a20e7 commit 9f95236
Show file tree
Hide file tree
Showing 23 changed files with 791 additions and 774 deletions.
2 changes: 0 additions & 2 deletions src/build-mac3.sh
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,6 @@ done

# PyQt5
#$PYTHON/bin/pylupdate5 conf/tonino.pro
# PyQt4
#pylupdate4 conf/tonino.pro

$QT_PATH/bin/lrelease -verbose conf/tonino.pro

Expand Down
69 changes: 42 additions & 27 deletions src/lib/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@
import lib.serialport
import lib.scales
from uic import MainWindowUI, AboutDialogUI, PreferencesDialogUI, CalibDialogUI, TinyCalibDialogUI, TinyCalibDialogUI2, DebugDialogUI, PreCalibDialogUI
import uic.resources as resources
from uic import resources

# platform dependent imports:
if sys.platform.startswith('darwin'):
Expand Down Expand Up @@ -409,18 +409,16 @@ def response2values(self, response:str, elemType:type, numOfArgs:Optional[int])
def toString(self, o:Any) -> str:
if sys.version < '3':
return str(o)
if isinstance(o, bytes):
return str(o, 'latin1')
else:
if type(o) == bytes:
return str(o,'latin1')
else:
return str(o)
return str(o)

def float2str(self, max_len:int, n:float) -> str:
if n == int(n):
return '%d'%n
else:
li:int = len(str(int(n))) + 1 # of characters for decimal point + preceding numbers
return ('{number:.{digits}f}'.format(number=n, digits=max(0,max_len-li))).rstrip('0').rstrip('.')
li:int = len(str(int(n))) + 1 # of characters for decimal point + preceding numbers
return ('{number:.{digits}f}'.format(number=n, digits=max(0,max_len-li))).rstrip('0').rstrip('.')

# format given float numbers into a string of maximal total_size (plus additional space in-between)
# trying to give as many digits as possible per number
Expand Down Expand Up @@ -988,11 +986,11 @@ def scan(self,_:bool=False) -> None:
raw_readings2 = self.app.getRawReadings(self.app.toninoPort)
else:
raw_readings2 = None
if raw_readings1 == None:
if raw_readings1 is None:
raw_readings1 = raw_readings2
if raw_readings2 == None:
if raw_readings2 is None:
raw_readings2 = raw_readings1
if dark_readings == None:
if dark_readings is None:
dark_readings = [0., 0., 0., 0.]
if raw_readings1 and raw_readings2 and dark_readings and len(raw_readings1)>3 and len(raw_readings2)>3 and len(dark_readings)>3:
r:float = (raw_readings1[1] + raw_readings2[1]) / 2. - dark_readings[1]
Expand Down Expand Up @@ -1181,12 +1179,14 @@ def master(self,_:bool=False) -> None:
try:
self.ui.logOutput.appendPlainText('<Master>')
time.sleep(0.5)
res1:Optional[str] = self.insertRequestResponse('RSCAN') # RSCAN
res1:Optional[str] = self.insertRequestResponse('RSCAN')
if res1 is not None:
res = self.app.response2values(res1,float,5)
if res is not None and len(res) == 5:
self.app.pre_cal_targets.append(res[1]/res[3]) # append classic r/b ratio
self.ui.logOutput.appendPlainText('targets r/b: ' + str([f'{t:.3f}' for t in self.app.pre_cal_targets]))
out = 'targets r/b: ' + str([f'{t:.3f}' for t in self.app.pre_cal_targets])
self.ui.logOutput.appendPlainText(out)
_log.info(out)
if len(self.app.pre_cal_targets) >= self.app.pre_cal_cardinality:
self.ui.pushButtonScan.setEnabled(True)
self.ui.pushButtonScan.repaint()
Expand All @@ -1205,12 +1205,14 @@ def scan(self,_:bool=False) -> None:
self.ui.pushButtonPreCal.repaint()
self.ui.logOutput.appendPlainText('<Scan>')
time.sleep(0.5)
res1 = self.insertRequestResponse('RSCAN') # RSCAN
res1 = self.insertRequestResponse('RSCAN')
if res1:
res = self.app.response2values(res1,float,5)
if res is not None and len(res) == 5:
self.sources.append(res[1]/res[3])
self.ui.logOutput.appendPlainText('sources: ' + str([f'{t:.3f}' for t in self.sources]))
out = 'sources: ' + str([f'{t:.3f}' for t in self.sources])
self.ui.logOutput.appendPlainText(out)
_log.info(out)
if len(self.sources) == len(self.app.pre_cal_targets):
self.ui.pushButtonPreCal.setEnabled(True)
self.ui.pushButtonPreCal.repaint()
Expand All @@ -1225,8 +1227,19 @@ def preCal(self,_:bool=False) -> None:
try:
if self.app.toninoPort:
self.ui.logOutput.appendPlainText('<PreCal>')
c:list[float]
c,_ = poly.polyfit(self.sources,self.app.pre_cal_targets,self.app.pre_cal_degree,full=True)
_log.info('polyfit(%s.%s,%s)',self.sources,self.app.pre_cal_targets,self.app.pre_cal_degree)
c:np.ndarray
stats:list[float]
c,stats = poly.polyfit(self.sources,self.app.pre_cal_targets,self.app.pre_cal_degree,full=True)
try:
yv:np.ndarray = np.array(self.app.pre_cal_targets)
r2:np.ndarray = 1 - stats[0] / (yv.size * yv.var())
if r2.size>0:
self.ui.logOutput.appendPlainText('RR: ')
self.ui.logOutput.appendPlainText(r2[0])
_log.info('RR: %s',r2[0])
except Exception as e: # pylint: disable=broad-except
_log.exception(e)
coefficients:list[float] = list(c)
coefficients.reverse()
coefs:str = ''
Expand All @@ -1235,6 +1248,7 @@ def preCal(self,_:bool=False) -> None:
coefs = coefs + str(co).replace('.',',') + ' '
self.ui.logOutput.appendPlainText('coefficients:')
self.ui.logOutput.appendPlainText(coefs[:-1])
_log.info('coefficients: %s',coefs[:-1])
self.ui.logOutput.repaint()
self.app.ser.sendCommand(self.app.toninoPort,self.app.formatCommand('SETPRE',coefficients,fitStringMaxLength=True))
except Exception as e: # pylint: disable=broad-except
Expand Down Expand Up @@ -1302,7 +1316,7 @@ class ApplicationWindow(QMainWindow):
endprogress = pyqtSignal()

def __init__(self, application:Tonino) -> None:
super(QMainWindow, self).__init__()
super().__init__()
self.app:Tonino = application
self.ui:MainWindowUI.Ui_MainWindow = MainWindowUI.Ui_MainWindow()
self.ui.setupUi(self)
Expand Down Expand Up @@ -1578,7 +1592,7 @@ def fileDialog(self, msg:str, path:Optional[str]=None, ffilter:str='', openFile:
else:
res = QFileDialog.getSaveFileName(self,msg,path,ffilter)
if res is not None and res != '':
if isinstance(res,list) or isinstance(res,tuple):
if isinstance(res, (list, tuple)):
res = res[0]
self.app.setWorkingDirectory(res)
return res
Expand Down Expand Up @@ -1801,7 +1815,8 @@ def sliderChanged(self,_:int=0) -> None:
self.app.scales.setPolyfitDegree(self.ui.degreeSlider.value())
self.ui.widget.canvas.redraw(force=True)
self.updateLCDS()
_log.debug('sliderChanged(%s)',self.ui.degreeSlider.value())
if _log.isEnabledFor(logging.DEBUG):
_log.debug('sliderChanged(%s)',self.ui.degreeSlider.value())


#
Expand Down Expand Up @@ -1877,8 +1892,7 @@ def selectionChanged(self, _newSelection:QItemSelection, _oldSelection:QItemSele
def getSelectedRows(self) -> list[int]:
if self.ui.tableView and self.ui.tableView.selectionModel():
return [s.row() for s in self.ui.tableView.selectionModel().selectedRows()]
else:
return []
return []

# invoked by clicks on coordinates in the graph
def toggleSelection(self, row:int) -> None:
Expand Down Expand Up @@ -1931,7 +1945,7 @@ def showAbout(self,_:bool=False) -> None:

def toggleDebug(self, ui:AboutDialogUI.Ui_Dialog) -> None:
modifiers:Qt.KeyboardModifier = QApplication.keyboardModifiers()
if modifiers == Qt.KeyboardModifier.MetaModifier|Qt.KeyboardModifier.AltModifier:
if modifiers == (Qt.KeyboardModifier.MetaModifier|Qt.KeyboardModifier.AltModifier):
self.toggleDebugLogging()
else:
self.debug = (self.debug + 1) % 3
Expand All @@ -1954,7 +1968,7 @@ def toggleDebugLogging(self) -> None:
else:
level = logging.INFO
self.showMessage(QApplication.translate('Message','debug logging OFF',None),msecs=3000)
loggers = [logging.getLogger(name) for name in logging.root.manager.loggerDict if ('.' not in name)] # @UndefinedVariable pylint: disable=no-member
loggers = [logging.getLogger(name) for name in logging.root.manager.loggerDict if '.' not in name] # @UndefinedVariable pylint: disable=no-member
for logger in loggers:
logger.setLevel(level)
for handler in logger.handlers:
Expand Down Expand Up @@ -2031,9 +2045,10 @@ def checkPorts(self, ports:list[serial.tools.list_ports_common.ListPortInfo], on
self.app.processEvents()
version:Optional[list[int]] = self.app.getToninoFirmwareVersion(p.device,onStartup)
if version:
_log.debug('port: %s',p.device)
_log.debug('serial: %s',p.serial_number)
_log.debug('firmware version: %s',version)
if _log.isEnabledFor(logging.DEBUG):
_log.debug('port: %s',p.device)
_log.debug('serial: %s',p.serial_number)
_log.debug('firmware version: %s',version)
res = p.device,version,p.serial_number
break
return res
Expand Down
26 changes: 16 additions & 10 deletions src/lib/scales.py
Original file line number Diff line number Diff line change
Expand Up @@ -225,20 +225,26 @@ def float2float(f, n=1):
def computePolyfit(self) -> None:
if self.polyfit_degree and len(self.coordinates) > self.polyfit_degree:
_log.debug('computePolyfit: %s',self.polyfit_degree)
xv = np.array([e[0] for e in self.coordinates])
yv = np.array([e[1] for e in self.coordinates])
xv:np.ndarray = np.array([e[0] for e in self.coordinates])
yv:np.ndarray = np.array([e[1] for e in self.coordinates])
c:np.ndarray
stats:list[float]
c, stats = poly.polyfit(xv,yv,self.polyfit_degree,full=True)
r2 = 1 - stats[0] / (yv.size * yv.var())
if r2 and len(r2)>0:
self.setRR(r2[0])
else:
try:
r2:np.ndarray = 1 - stats[0] / (yv.size * yv.var())
if r2.size>0:
self.setRR(r2[0])
else:
self.setRR(None)
except Exception:
self.setRR(None)
self.coefficients = list(c)
self.coefficients.reverse()
_log.debug('polyfit(%s)=%s',self.polyfit_degree,self.coefficients)
# compute the inverse mapping
ci, _ = poly.polyfit(yv,xv,self.polyfit_degree,full=True)
_log.debug('inverse_polyfit(%s)=%s',self.polyfit_degree,list(reversed(list(ci))))
if _log.isEnabledFor(logging.DEBUG):
_log.debug('polyfit(%s)=%s',self.polyfit_degree,self.coefficients)
# compute the inverse mapping
ci, _ = poly.polyfit(yv,xv,self.polyfit_degree,full=True)
_log.debug('inverse_polyfit(%s)=%s',self.polyfit_degree,list(reversed(list(ci))))
else:
self.coefficients = None
self.setRR(None)
Expand Down
50 changes: 23 additions & 27 deletions src/lib/serialport.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,14 +31,14 @@
_log: Final = logging.getLogger(__name__)

def str2cmd(s:Union[str,bytes]) -> bytes:
if type(s) == bytes:
if isinstance(s,bytes):
return s
return bytes(cast(str,s),'ascii')
bytes(cast(str,s),'ascii')

def cmd2str(c:Union[str,bytes]) -> str:
if type(c) == bytes:
if isinstance(c,bytes):
return str(c,'latin1')
return cast(str,c)
cast(str,c)

class SerialPort:

Expand Down Expand Up @@ -90,7 +90,7 @@ def configurePort(self,port:str) -> None:
def openPort(self,port:str) -> None:
_log.debug('openPort(%s)',port)
try:
if self.port != None and port != self.port:
if self.port is not None and port != self.port:
self.closePort()
if not self.SP.is_open:
# open port if not yet open
Expand Down Expand Up @@ -120,8 +120,7 @@ def writeString(self,port:str, s:str) -> Optional[str]:
self.SP.write(str2cmd(s + '\n'))
self.SP.flush()
return cmd2str(self.SP.readline())
else:
return None
return None
except Exception as e: # pylint: disable=broad-except
_log.exception(e)
self.closePort()
Expand All @@ -141,12 +140,14 @@ def sendCommand(self,port:str, command:str, retry:bool=True) -> Optional[str]:
time.sleep(0.3)
r:bytes = self.SP.readline()
response:str = cmd2str(r)
_log.debug('response(%s): %s',len(response),response.strip())
if _log.isEnabledFor(logging.DEBUG):
_log.debug('response(%s): %s',len(response),response.strip())
if not (response and len(response) > 0):
# we got an empty line, maybe the next line contains the response
r = self.SP.readline()
response = cmd2str(r)
_log.debug('second response(%s):%s',len(response),response.strip())
if _log.isEnabledFor(logging.DEBUG):
_log.debug('second response(%s):%s',len(response),response.strip())
if response and len(response) > 0:
# each <command> is answered by the Tonino by returning "<command>:<result>\n"
parts:list[str] = response.split(command + self.cmdSeparatorChar)
Expand All @@ -156,16 +157,14 @@ def sendCommand(self,port:str, command:str, retry:bool=True) -> Optional[str]:
res = ''
if retry and res == None:
return self.sendCommand(port,command,False)
else:
_log.debug('result: %s',res)
return res
_log.debug('result: %s',res)
return res
except Exception as e: # pylint: disable=broad-except
_log.exception(e)
self.closePort()
if retry:
return self.sendCommand(port,command,False)
else:
return None
return None

def getSerialPorts(self) -> list[serial.tools.list_ports_common.ListPortInfo]:
# we are looking for
Expand All @@ -187,19 +186,16 @@ def getSerialPorts(self) -> list[serial.tools.list_ports_common.ListPortInfo]:
if tinyToninos and len(tinyToninos) > 0:
self.setModel(1)
return tinyToninos
else:
self.setModel(0)
return list(self.filter_ports_by_vid_pid(ports,vid,classicToninoPID))
else:
# pyserial >2.7
ports = list(serial.tools.list_ports.comports())
tinyToninos = list(self.filter_ports_by_vid_pid(ports,vid,tinyToninoPID))
if tinyToninos and len(tinyToninos) > 0:
self.setModel(1)
return tinyToninos
else:
self.setModel(0)
return list(self.filter_ports_by_vid_pid(ports,vid,classicToninoPID))
self.setModel(0)
return list(self.filter_ports_by_vid_pid(ports,vid,classicToninoPID))
# pyserial >2.7
ports = list(serial.tools.list_ports.comports())
tinyToninos = list(self.filter_ports_by_vid_pid(ports,vid,tinyToninoPID))
if tinyToninos and len(tinyToninos) > 0:
self.setModel(1)
return tinyToninos
self.setModel(0)
return list(self.filter_ports_by_vid_pid(ports,vid,classicToninoPID))

def filter_ports_by_vid_pid(self,ports:list[serial.tools.list_ports_common.ListPortInfo],vid:Optional[int]=None,pid:Optional[int]=None) -> Iterator[serial.tools.list_ports_common.ListPortInfo]:
""" Given a VID and PID value, scans for available port, and
Expand Down
4 changes: 2 additions & 2 deletions src/lib/suppress_errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,14 +38,14 @@ def __init__(self):

def __enter__(self):
# Assign the null pointers to stdout and stderr.
if self.save_fds != []:
if self.save_fds:
os.dup2(self.null_fds[0],1)
os.dup2(self.null_fds[1],2)

def __exit__(self, *_):
# Re-assign the real stdout/stderr back to (1) and (2)
try:
if self.save_fds != []:
if self.save_fds:
os.dup2(self.save_fds[0],1)
os.dup2(self.save_fds[1],2)
except Exception: # pylint: disable=broad-except
Expand Down
2 changes: 1 addition & 1 deletion src/requirements-mac.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@ pyserial==3.5
pyyaml==6.0
numpy==1.24.1
scipy==1.10.0
PyQt6==6.4.0
PyQt6==6.4.1
matplotlib==3.6.3
darkdetect==0.7.1
2 changes: 1 addition & 1 deletion src/requirements-win.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,5 @@ pyserial==3.5
pyyaml==6.0
numpy==1.24.1
scipy==1.10.0
PyQt6==6.4.0
PyQt6==6.4.1
matplotlib==3.6.3
Loading

0 comments on commit 9f95236

Please sign in to comment.