class OBAs(object): def __init__(self): self._obas = [] self._logger = Logger('obas', 'Class : OBAs') def addOBA(self, oba): self._obas.append(oba) def editOBA(self, oba, index): self._obas[index] = oba def rmOBA(self, index): self._obas.pop(index) def save(self): configOBAs = {} i = 0 for x in self.obas: configOBAs[i] = { 'name': x.name, 'outputPin': x.outputPin, 'momentary': x.momentary, 'enabled': x.enabled, 'icon': x.icon } i += 1 obacfg = open(Config.obaConfig, 'wb') pickle.dump(configOBAs, obacfg) obacfg.close() msg = 'Pickled %s OBA elements to local config file.' % i self._logger.log(msg) def load(self): i = 0 obacfg = open(Config.obaConfig, 'rb') cfg = pickle.load(obacfg) for key in cfg.keys(): self.addOBA( OBA(name=cfg[key]['name'], outputPin=cfg[key]['outputPin'], enabled=cfg[key]['enabled'], icon=cfg[key]['icon'], momentary=cfg[key]['momentary'])) i += 1 obacfg.close() msg = 'Loaded %s OBA elements from local config file.' % i self._logger.log(msg) @property def obas(self): return self._obas
class Tracs(object): def __init__(self): self._tracs = [] self._logger = Logger('tracs', 'Class : Tracs') def addTrac(self, trac): self._tracs.append(trac) def editTrac(self, trac, index): self._tracs[index] = trac def rmTrac(self, index): self._tracs.pop(index) def save(self): configTracs = {} i = 0 for x in self.tracs: configTracs[i] = { 'name': x.name, 'outputPin': x.outputPin, 'enabled': x.enabled, 'icon': x.icon } i += 1 tcfg = open(Config.tracConfig, 'wb') pickle.dump(configTracs, tcfg) tcfg.close() msg = 'Pickled %s tracs to local config file.' % i self._logger.log(msg) def load(self): i = 0 tcfg = open(Config.tracConfig, 'rb') cfg = pickle.load(tcfg) for key in cfg.keys(): self.addTrac( Trac(name=cfg[key]['name'], outputPin=cfg[key]['outputPin'], enabled=cfg[key]['enabled'], icon=cfg[key]['icon'])) i += 1 tcfg.close() msg = 'Loaded %s tracs from local config file.' % i self._logger.log(msg) @property def tracs(self): return self._tracs
def __init__(self, tracs, parent): super(TracControlUI, self).__init__() self.title = 'Light Configuration' self.setLayout(QVBoxLayout(self)) self.tracs = tracs self.parent = parent # Init logger self.logger = Logger('tracControl', "UI : TracControl") # Dynamically generate controls _keyStrings = [] for _i, _trac in enumerate(self.tracs): _ctrl = TracControl(_trac.name, parent=self) exec("self._%s = _ctrl" % _i) _ctrl.setParent(self) _ctrl.setIcon(QIcon( Config.icon('tracControl', _trac.icon)['path'])) if _trac.active: _ctrl.setChecked(True) _keyStrings.append('_%s' % _i) oList = Tools.group(Config.tracColumns, _keyStrings) del _keyStrings # Dynamically generate panel layout using grouped tuples for oTuple in oList: _panel = QWidget(self) _panel.setLayout(QHBoxLayout(_panel)) for oWidget in oTuple: _panel.layout().addWidget(eval('self.%s' % oWidget)) self.layout().addWidget(_panel) del _panel
def __init__(self, obas, parent): super(OBAControlUI, self).__init__() self.title = 'OnBoard Air Control UI' self.setLayout(QVBoxLayout(self)) self.obas = obas self.parent = parent # Init logger self.logger = Logger('obaControl', "UI : OBAControl") # Dynamically generate controls _keyStrings = [] for _i, _oba in enumerate(self.obas): _ctrl = OBAControl(_oba.name, momentary=_oba.momentary, parent=self) exec("self._%s = _ctrl" % _i) _ctrl.setIcon(QIcon(Config.icon('oba', _oba.icon)['path'])) if _oba.active: _ctrl.setChecked(True) _keyStrings.append('_%s' % _i) _oList = Tools.group(Config.obaColumns, _keyStrings) del _keyStrings # Dynamically generate panel layout using grouped tuples for oTuple in _oList: _panel = QWidget(self) _panel.setLayout(QHBoxLayout(_panel)) for oWidget in oTuple: _panel.layout().addWidget(eval('self.%s' % oWidget)) self.layout().addWidget(_panel) del _panel
def __init__(self, bus=1, address='0x20', debug=False): # Init logger self._logger = Logger('i2cBus', 'I2CBus : Controller') # Set debug state self._debug = debug # Init I2C comms if not self._debug: self._bus = SMBus(bus) else: self._bus = None self._address = address self._state = 0x0000 # Clear all relays at startup self.deEnergizeAll()
class Lights(object): def __init__(self): self._lights = [] self._logger = Logger('lights', 'Class : Lights') def addLight(self, light): self._lights.append(light) def editLight(self, light, index): self._lights[index] = light def rmLight(self, index): self._lights.pop(index) def save(self): configLights = {} i = 0 for x in self.lights: configLights[i] = {'name': x.name, 'outputPin': x.outputPin, 'enabled': x.enabled, 'icon': x.icon, 'strobe': x.strobe} i += 1 lcfg = open(Config.lightConfig, 'wb') pickle.dump(configLights, lcfg) lcfg.close() msg = 'Pickled %s lights to local config file.' % i self._logger.log(msg) def load(self): i = 0 lcfg = open(Config.lightConfig, 'rb') cfg = pickle.load(lcfg) for key in cfg.keys(): self.addLight(Light(name=cfg[key]['name'], outputPin=cfg[key]['outputPin'], enabled=cfg[key]['enabled'], icon=cfg[key]['icon'], strobe=cfg[key]['strobe'])) i += 1 lcfg.close() msg = 'Loaded %s lights from local config file.' % i self._logger.log(msg) @property def lights(self): return self._lights
def __init__(self, lights, parent): super(LightConfigUI, self).__init__() self.title = 'Lighting Configuration' self.setLayout(QVBoxLayout(self)) self.layout().setAlignment(Qt.AlignCenter) self.parent = parent self.lights = lights # Init logger self.logger = Logger('lightConfig', "UI : LightConfig", level='debug') # Create layout self._plus = QPushButton('+', self) self._plus.clicked.connect(self.__createLight) self._minus = QPushButton('-', self) self._minus.clicked.connect(self.__destroyLight) _panel = QWidget(self) _panel.setLayout(QHBoxLayout(_panel)) _panel.layout().setAlignment(Qt.AlignRight) _panel.layout().addWidget(self._plus) _panel.layout().addWidget(self._minus) self.layout().addWidget(_panel) self._lightsList = QTableWidget(0, 5, self) self._lightsList.setSelectionBehavior(QAbstractItemView.SelectRows) self._lightsList.setHorizontalHeaderLabels( ['Name', 'Output Pin', 'Enabled', 'Icon', 'Strobe']) self._lightsList.horizontalHeader().setSectionResizeMode( QHeaderView.Stretch) self.keyPressed.connect(self.__onKey) self.layout().addWidget(self._lightsList) self._editBtn = QPushButton('Edit', self) self._editBtn.clicked.connect(self.__editLight) self.layout().addWidget(self._editBtn) self._closeBtn = QPushButton('Close', self) self._closeBtn.clicked.connect(self.__closeBtnAction) self.layout().addWidget(self._closeBtn) # Populate table for _light in self.lights: _i = self._lightsList.rowCount() self._lightsList.setRowCount(_i + 1) for _c, _item in enumerate([ _light.name, str(_light.outputPin), str(_light.enabled), _light.icon, str(_light.strobe) ]): _tblItem = QTableWidgetItem(_item) _tblItem.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) self._lightsList.setItem(_i, _c, _tblItem)
def __init__(self, obas, parent): super(OBAConfigUI, self).__init__() self.title = 'OnBoard Air Configuration' self.setLayout(QVBoxLayout(self)) self.layout().setAlignment(Qt.AlignCenter) self.parent = parent self.obas = obas # Init logger self.logger = Logger('obaConfig', "UI : OBAConfig") # Create layout self._plus = QPushButton('+', self) self._plus.clicked.connect(self.__createOBA) self._minus = QPushButton('-', self) self._minus.clicked.connect(self.__destroyOBA) _panel = QWidget(self) _panel.layout = QHBoxLayout(_panel) _panel.layout.setAlignment(Qt.AlignRight) _panel.layout.addWidget(self._plus) _panel.layout.addWidget(self._minus) self.layout().addWidget(_panel) self._obaList = QTableWidget(0, 5, self) self._obaList.setSelectionBehavior(QAbstractItemView.SelectRows) self._obaList.setHorizontalHeaderLabels( ['Name', 'Output Pin', 'Momentary', 'Enabled', 'Icon']) self._obaList.horizontalHeader().setSectionResizeMode( QHeaderView.Stretch) self.keyPressed.connect(self.__onKey) self.layout().addWidget(self._obaList) self._editBtn = QPushButton('Edit', self) self._editBtn.clicked.connect(self.__editOBA) self.layout().addWidget(self._editBtn) self._closeBtn = QPushButton('Close', self) self._closeBtn.clicked.connect(self.__closeBtnAction) self.layout().addWidget(self._closeBtn) # Populate table for _oba in self.obas: _i = self._obaList.rowCount() self._obaList.setRowCount(_i + 1) for _c, _item in enumerate([ _oba.name, str(_oba.outputPin), str(_oba.momentary), str(_oba.enabled), _oba.icon ]): _tblItem = QTableWidgetItem(_item) _tblItem.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) self._obaList.setItem(_i, _c, _tblItem)
def __init__(self): self._lights = [] self._logger = Logger('lights', 'Class : Lights')
def __init__(self, prefs, parent): super(UserPrefUI, self).__init__() self.title = 'User Preferences' self.setLayout(QVBoxLayout(self)) self.parent = parent self.prefs = prefs # Init logger self.logger = Logger('userPrefsUI', 'UI : User Preferences') # Set up container container = QWidget() container.setLayout(QVBoxLayout()) # Set up scroll area scrollArea = QScrollArea() scrollArea.setWidget(container) scrollArea.setWidgetResizable(True) self.layout().addWidget(scrollArea) # Permanent controls self._saveButton = QPushButton('Save', self) self._saveButton.clicked.connect(self.__save) self._startMaximized = QCheckBox('Start Maximized', self) self._allowDuplicatePins = QCheckBox('Allow Duplicate Output Pins', self) self._enableOBA = QCheckBox('OnBoard Air', self) self._enableLighting = QCheckBox('Lighting', self) self._enableTracControl = QCheckBox('Traction Control', self) self._enableCamViewer = QCheckBox('Camera Viewer', self) self._enableGyro = QCheckBox('Inclinometer', self) self._panelLabel = QLabel( '<html><center>Enable Modules:<br>\ <em>Restart TacOS for changes to take effect.</em></center></html>', self) self._i2cBus = QComboBox(self) self._i2cBus.addItems(Config.busList) self._i2cBusLabel = QLabel('I2C Bus', self) self._i2cAddress = QLineEdit('I2C Address', self) self._i2cLabel = QLabel( '<html><center>I2C Parameters:<br>\ <em>Restart TacOS for changes to take effect.</em></center></html>', self) self._i2cDebug = QCheckBox('I2C Debug Mode', self) self._i2cDebugLabel = QLabel( '<html><center>I2C Debug Mode:<br>\ <em>Disables all I2C comms.<br>\ Restart TacOS for changes to take effect.</em></center></html>', self) self._debugLogging = QCheckBox('Enable Debug Logs', self) self._restartButton = QPushButton('Restart TacOS', self) self._restartButton.clicked.connect(self.__restart) # Set initial values for control in [ 'startMaximized', 'allowDuplicatePins', 'enableOBA', 'enableLighting', 'enableTracControl', 'enableCamViewer', 'enableGyro', 'i2cDebug', 'debugLogging' ]: if control in prefs.keys(): exec('self._%s.setChecked(prefs["%s"])' % (control, control)) else: if control in [ 'enableOBA', 'enableLighting', 'enableTracControl', 'enableCamViewer', 'enableGyro' ]: exec('self._%s.setChecked(True)' % control) else: exec('self._%s.setChecked(False)' % control) if 'i2cAddress' in prefs.keys(): self._i2cAddress.setText(prefs['i2cAddress']) else: self._i2cAddress.setText('0x20') if 'i2cBus' in prefs.keys(): self._i2cBus.setCurrentText(str(prefs['i2cBus'])) else: self._i2cBus.setCurrentIndex(0) layoutList = [[ '_startMaximized', '_allowDuplicatePins', '_debugLogging' ], ['_panelLabel'], ['_enableOBA', '_enableLighting', '_enableTracControl'], ['_enableCamViewer', '_enableGyro'], ['_i2cLabel'], ['_i2cBusLabel', '_i2cBus', '_i2cAddress'], ['_i2cDebugLabel'], ['_i2cDebug'], ['_saveButton', '_restartButton']] for i in layoutList: panel = QWidget() panel.setLayout(QHBoxLayout(panel)) panel.layout().setSpacing(20) panel.layout().setAlignment(Qt.AlignCenter) for c in i: panel.layout().addWidget(eval('self.%s' % c)) container.layout().addWidget(panel)
def __init__(self): self._obas = [] self._logger = Logger('obas', 'Class : OBAs')
def __init__(self): super().__init__() self.left = Config.geometry[0] self.top = Config.geometry[1] self.width = Config.geometry[2] self.height = Config.geometry[3] self.setLayout(QHBoxLayout(self)) # Init logger self.logger = Logger('mainUI', 'UI : Main') # Read in user prefs self.prefs = {} self.loadPrefs() # Load configured objects self.lights = Lights() self.lights.load() self.obas = OBAs() self.obas.load() self.tracs = Tracs() self.tracs.load() # Init I2C control if 'i2cAddress' in self.prefs.keys(): _address = self.prefs['i2cAddress'] else: _address = Config.defaultI2CAddress if 'i2cBus' in self.prefs.keys(): _bus = self.prefs['i2cBus'] else: _bus = Config.defaultI2CBus if 'i2cDebug' in self.prefs.keys(): _debug = self.prefs['i2cDebug'] else: _debug = False self._i2cBus = I2CBus(int(_bus), str(_address), bool(_debug)) del _bus, _address, _debug # Create menu frame self._sidebarMenu = QFrame(self) self._sidebarMenu.layout = QVBoxLayout(self._sidebarMenu) self._sidebarMenu.setMaximumWidth(Config.menuWidth + 50) self._sidebarMenu.setMaximumHeight(Config.geometry[3]) self._sidebarMenu.setStyleSheet( "QFrame{border-right: 1px solid black}") # Create menu _container = QWidget() _container.layout = QVBoxLayout() _container.setLayout(_container.layout) _scroll = QScrollArea() _scroll.setWidget(_container) _scroll.setWidgetResizable(True) self._sidebarMenu.layout.addWidget(_scroll) for _key in [ 'enableOBA', 'enableLighting', 'enableTracControl', 'enableCamViewer', 'enableGyro' ]: if _key in self.prefs.keys(): if self.prefs[_key]: _title = { 'enableOBA': 'control_oba', 'enableLighting': 'control_light', 'enableTracControl': 'control_trac', 'enableCamViewer': 'control_cam', 'enableGyro': 'control_gyro' }[_key] _icon = { 'enableOBA': Config.faIcon("wind"), 'enableLighting': Config.faIcon("lightbulb"), 'enableTracControl': Config.icon("tracControl", "rearDiff")['path'], 'enableCamViewer': Config.faIcon("camera"), 'enableGyro': Config.faIcon("truck-pickup") }[_key] _button = MenuButton(panel=_title, parent=self) _button.setIcon(QIcon(_icon)) _container.layout.addWidget(_button) _settingsButton = MenuButton(panel="config_prefs", parent=self) _settingsButton.setIcon(QIcon(Config.faIcon("user-cog"))) _container.layout.addWidget(_settingsButton) del _container, _scroll, _key, _settingsButton, _title, _icon, _button # Create version info label self._version = QLabel('v%s' % Config.version, self) self._version.setAlignment(Qt.AlignCenter) self._version.setFixedWidth(Config.menuWidth) self._version.setStyleSheet("QLabel{border: none}") self._sidebarMenu.layout.addWidget(self._version) # Create OSK button self._oskButton = QPushButton('', self) self._oskButton.setIcon(QIcon(Config.faIcon('keyboard'))) self._oskButton.setFixedWidth(Config.menuWidth) self._oskButton.clicked.connect(self.showOSK) self._sidebarMenu.layout.addWidget(self._oskButton) # Add menu frame to main UI self.layout().addWidget(self._sidebarMenu) # Create main UI panel self._mainPanel = QWidget(self) self._mainPanel.setLayout(QVBoxLayout(self._mainPanel)) self.layout().addWidget(self._mainPanel) # Init default UI for _key in [ 'enableOBA', 'enableLighting', 'enableTracControl', 'enableCamViewer', 'enableGyro' ]: _cUI = None _uiName = None if _key in self.prefs.keys(): if self.prefs[_key]: if _key == 'enableOBA': _cUI = OBAControlUI(self.obas.obas, self) _uiName = 'control_oba' elif _key == 'enableLighting': _cUI = LightControlUI(self.lights.lights, self) _uiName = 'control_light' elif _key == 'enableTracControl': _cUI = TracControlUI(self.tracs.tracs, self) _uiName = 'control_trac' elif _key == 'enableCamViewer': _cUI = CamViewer(0) _uiName = 'control_cam' elif _key == 'enableGryo': _cUI = Gyrometer() _uiName = 'control_gyro' if _cUI is not None: break if _cUI is None: _cUI = UserPrefUI(self.prefs, parent=self) _uiName = 'config_prefs' self._currentUI = {'name': _uiName, 'obj': _cUI} _cUI.setParent(self) self._mainPanel.layout().addWidget(_cUI) _cUI.show() # Create button panel self._btnPanel = QWidget(self) self._btnPanel.setLayout(QHBoxLayout(self._btnPanel)) self._mainPanel.layout().addWidget(self._btnPanel) # Create Config button self._configButton = QPushButton('Configure', self) self._configButton.setFixedHeight(50) self._configButton.setIcon(QIcon(Config.faIcon('cog'))) self._configButton.clicked.connect(self.__configButtonAction) self._btnPanel.layout().addWidget(self._configButton) # Create Night Mode button self._nightModeButton = QPushButton('', self) self._nightModeButton.setFixedHeight(50) self._nightModeButton.setIcon( QIcon({ True: Config.faIcon('sun'), False: Config.faIcon('moon') }[self.prefs['nightMode']])) self._nightModeButton.setText({ True: 'Day Mode', False: 'Night Mode' }[self.prefs['nightMode']]) self._nightModeButton.clicked.connect(self.toggleNightMode) self._btnPanel.layout().addWidget(self._nightModeButton) self.setNightMode(self.prefs['nightMode'])
class MainUI(QWidget): def __init__(self): super().__init__() self.left = Config.geometry[0] self.top = Config.geometry[1] self.width = Config.geometry[2] self.height = Config.geometry[3] self.setLayout(QHBoxLayout(self)) # Init logger self.logger = Logger('mainUI', 'UI : Main') # Read in user prefs self.prefs = {} self.loadPrefs() # Load configured objects self.lights = Lights() self.lights.load() self.obas = OBAs() self.obas.load() self.tracs = Tracs() self.tracs.load() # Init I2C control if 'i2cAddress' in self.prefs.keys(): _address = self.prefs['i2cAddress'] else: _address = Config.defaultI2CAddress if 'i2cBus' in self.prefs.keys(): _bus = self.prefs['i2cBus'] else: _bus = Config.defaultI2CBus if 'i2cDebug' in self.prefs.keys(): _debug = self.prefs['i2cDebug'] else: _debug = False self._i2cBus = I2CBus(int(_bus), str(_address), bool(_debug)) del _bus, _address, _debug # Create menu frame self._sidebarMenu = QFrame(self) self._sidebarMenu.layout = QVBoxLayout(self._sidebarMenu) self._sidebarMenu.setMaximumWidth(Config.menuWidth + 50) self._sidebarMenu.setMaximumHeight(Config.geometry[3]) self._sidebarMenu.setStyleSheet( "QFrame{border-right: 1px solid black}") # Create menu _container = QWidget() _container.layout = QVBoxLayout() _container.setLayout(_container.layout) _scroll = QScrollArea() _scroll.setWidget(_container) _scroll.setWidgetResizable(True) self._sidebarMenu.layout.addWidget(_scroll) for _key in [ 'enableOBA', 'enableLighting', 'enableTracControl', 'enableCamViewer', 'enableGyro' ]: if _key in self.prefs.keys(): if self.prefs[_key]: _title = { 'enableOBA': 'control_oba', 'enableLighting': 'control_light', 'enableTracControl': 'control_trac', 'enableCamViewer': 'control_cam', 'enableGyro': 'control_gyro' }[_key] _icon = { 'enableOBA': Config.faIcon("wind"), 'enableLighting': Config.faIcon("lightbulb"), 'enableTracControl': Config.icon("tracControl", "rearDiff")['path'], 'enableCamViewer': Config.faIcon("camera"), 'enableGyro': Config.faIcon("truck-pickup") }[_key] _button = MenuButton(panel=_title, parent=self) _button.setIcon(QIcon(_icon)) _container.layout.addWidget(_button) _settingsButton = MenuButton(panel="config_prefs", parent=self) _settingsButton.setIcon(QIcon(Config.faIcon("user-cog"))) _container.layout.addWidget(_settingsButton) del _container, _scroll, _key, _settingsButton, _title, _icon, _button # Create version info label self._version = QLabel('v%s' % Config.version, self) self._version.setAlignment(Qt.AlignCenter) self._version.setFixedWidth(Config.menuWidth) self._version.setStyleSheet("QLabel{border: none}") self._sidebarMenu.layout.addWidget(self._version) # Create OSK button self._oskButton = QPushButton('', self) self._oskButton.setIcon(QIcon(Config.faIcon('keyboard'))) self._oskButton.setFixedWidth(Config.menuWidth) self._oskButton.clicked.connect(self.showOSK) self._sidebarMenu.layout.addWidget(self._oskButton) # Add menu frame to main UI self.layout().addWidget(self._sidebarMenu) # Create main UI panel self._mainPanel = QWidget(self) self._mainPanel.setLayout(QVBoxLayout(self._mainPanel)) self.layout().addWidget(self._mainPanel) # Init default UI for _key in [ 'enableOBA', 'enableLighting', 'enableTracControl', 'enableCamViewer', 'enableGyro' ]: _cUI = None _uiName = None if _key in self.prefs.keys(): if self.prefs[_key]: if _key == 'enableOBA': _cUI = OBAControlUI(self.obas.obas, self) _uiName = 'control_oba' elif _key == 'enableLighting': _cUI = LightControlUI(self.lights.lights, self) _uiName = 'control_light' elif _key == 'enableTracControl': _cUI = TracControlUI(self.tracs.tracs, self) _uiName = 'control_trac' elif _key == 'enableCamViewer': _cUI = CamViewer(0) _uiName = 'control_cam' elif _key == 'enableGryo': _cUI = Gyrometer() _uiName = 'control_gyro' if _cUI is not None: break if _cUI is None: _cUI = UserPrefUI(self.prefs, parent=self) _uiName = 'config_prefs' self._currentUI = {'name': _uiName, 'obj': _cUI} _cUI.setParent(self) self._mainPanel.layout().addWidget(_cUI) _cUI.show() # Create button panel self._btnPanel = QWidget(self) self._btnPanel.setLayout(QHBoxLayout(self._btnPanel)) self._mainPanel.layout().addWidget(self._btnPanel) # Create Config button self._configButton = QPushButton('Configure', self) self._configButton.setFixedHeight(50) self._configButton.setIcon(QIcon(Config.faIcon('cog'))) self._configButton.clicked.connect(self.__configButtonAction) self._btnPanel.layout().addWidget(self._configButton) # Create Night Mode button self._nightModeButton = QPushButton('', self) self._nightModeButton.setFixedHeight(50) self._nightModeButton.setIcon( QIcon({ True: Config.faIcon('sun'), False: Config.faIcon('moon') }[self.prefs['nightMode']])) self._nightModeButton.setText({ True: 'Day Mode', False: 'Night Mode' }[self.prefs['nightMode']]) self._nightModeButton.clicked.connect(self.toggleNightMode) self._btnPanel.layout().addWidget(self._nightModeButton) self.setNightMode(self.prefs['nightMode']) def closeEvent(self, event): self.savePrefs() self._i2cBus.deEnergizeAll() super(MainUI, self).closeEvent(event) def availablePins(self, value=None): if not self.prefs['allowDuplicatePins']: _pins = Config.outputPinList for _light in self.lights.lights: if _light.outputPin in _pins: _pins.remove(_light.outputPin) for _oba in self.obas.obas: if _oba.outputPin in _pins: _pins.remove(_oba.outputPin) for _trac in self.tracs.tracs: if _trac.outputPin in _pins: _pins.remove(_trac.outputPin) else: _pins = Config.outputPinList _pins.sort() return _pins def setOutputPin(self, pin, state): fx = { True: self.i2cBus.energizeRelay, False: self.i2cBus.deEnergizeRelay }[state] fx(pin) def disableConfigButtons(self): for _ctrl in [self.configButton]: _ctrl.setEnabled(False) del _ctrl def enableConfigButtons(self): for _ctrl in [self.configButton]: _ctrl.setEnabled(True) del _ctrl def loadUI(self, ui, idx=None): if 'cam' in self.currentUI['name']: self.currentUI['obj'].stop() if 'gyro' in self.currentUI['name']: self.currentUI['obj'].stopSerial() self.currentUI['obj'].stopRotation() self.currentUI['obj'].hide() self.mainPanel.layout().removeWidget(self.currentUI['obj']) self.mainPanel.layout().removeWidget(self.btnPanel) _mode = ui.split('_')[0] _type = ui.split('_')[1] _ui = None if _mode == 'control': if _type == 'gyro': self.configButton.setText("Calibrate") else: self.configButton.setText("Configure") if _type == 'light': _ui = LightControlUI(self.lights.lights, self) elif _type == 'oba': _ui = OBAControlUI(self.obas.obas, self) elif _type == 'trac': _ui = TracControlUI(self.tracs.tracs, self) elif _type == 'cam': _ui = CamViewer(0) _ui.start() elif _type == 'gyro': _ui = Gyrometer(parent=self) _ui.startSerial() _ui.startRotation() elif _mode == 'config': if _type == 'light': _ui = LightConfigUI(self.lights.lights, self) elif _type == 'oba': _ui = OBAConfigUI(self.obas.obas, self) elif _type == 'trac': _ui = TracConfigUI(self.tracs.tracs, self) elif _type == 'prefs': _ui = UserPrefUI(self.prefs, self) elif _mode == 'edit': if _type == 'light': _ui = EditLightUI(self.lights.lights[idx], self) elif _type == 'oba': _ui = EditOBAUI(self.obas.obas[idx], self) elif _type == 'trac': _ui = EditTracUI(self.tracs.tracs[idx], self) elif _mode == 'create': if _type == 'light': _ui = AddLightUI(self) elif _type == 'oba': _ui = AddOBAUI(self) elif _type == 'trac': _ui = AddTracUI(self) if _ui is not None: _ui.setParent(self) self.mainPanel.layout().addWidget(_ui) _ui.show() self.currentUI = {'name': ui, 'obj': _ui} self.mainPanel.layout().addWidget(self.btnPanel) def toggleNightMode(self): _mode = self.prefs['nightMode'] _value = {False: Config.dayBright, True: Config.nightBright}[not _mode] self.nightModeButton.setIcon({ False: QIcon(Config.faIcon('sun')), True: QIcon(Config.faIcon('moon')) }[not _mode]) self.nightModeButton.setText({ False: 'Day Mode', True: 'Night Mode' }[not _mode]) os.system("echo %s > /sys/class/backlight/rpi_backlight/brightness" % _value) self.prefs['nightMode'] = not _mode self.savePrefs() self.logger.log('Night mode %s: backlight set to %s' % (not _mode, _value)) del _mode, _value def setNightMode(self, mode): _value = {False: Config.dayBright, True: Config.nightBright}[mode] self.nightModeButton.setIcon({ False: QIcon(Config.faIcon('sun')), True: QIcon(Config.faIcon('moon')) }[mode]) self.nightModeButton.setText({ False: 'Day Mode', True: 'Night Mode' }[mode]) os.system("echo %s > /sys/class/backlight/rpi_backlight/brightness" % _value) del _value def loadPrefs(self): _pPrefs = open(Config.prefs, 'rb') _prefs = pickle.load(_pPrefs) for key in _prefs: self.prefs[key] = _prefs[key] _pPrefs.close() del _pPrefs, _prefs def savePrefs(self): _pPrefs = open(Config.prefs, 'wb') pickle.dump(self.prefs, _pPrefs) _pPrefs.close() def showOSK(self): if self.window().dock.isHidden(): self.window().dock.show() else: self.window().dock.hide() def __configButtonAction(self): if self.currentUI['name'] not in ['control_camera', 'control_gyro']: self.disableConfigButtons() self.mainPanel.layout().removeWidget(self.currentUI['obj']) self.loadUI(self.currentUI['name'].replace('control', 'config')) elif self.currentUI['name'] == 'control_gyro': self.currentUI['obj'].calibrate() @property def mainPanel(self): return self._mainPanel @property def btnPanel(self): return self._btnPanel @property def nightModeButton(self): return self._nightModeButton @property def configButton(self): return self._configButton @property def currentUI(self): return self._currentUI @currentUI.setter def currentUI(self, value): self._currentUI = value @property def i2cBus(self): return self._i2cBus
class I2CBus(object): def __init__(self, bus=1, address='0x20', debug=False): # Init logger self._logger = Logger('i2cBus', 'I2CBus : Controller') # Set debug state self._debug = debug # Init I2C comms if not self._debug: self._bus = SMBus(bus) else: self._bus = None self._address = address self._state = 0x0000 # Clear all relays at startup self.deEnergizeAll() def deEnergizeAll(self): self._state = 0x0000 if not self._debug: self._logger.log('De-energizing all relays.') success = False while not success: success = self.__sendI2CData() time.sleep(0.1) else: print('De-energizing all relays.') print('I2C Bus state : %s' % str(bin(self._state))) def energizeRelay(self, relay): """ Energize relay at position. :param relay: The index of the relay to energize (1 - 16) :type relay: int :return: None """ if checkRelayInputValue(relay): self._state |= 1 << (relay - 1) if not self._debug: self._logger.log('Energizing relay @ position %s' % relay) success = False while not success: success = self.__sendI2CData() time.sleep(0.1) else: print('Energizing relay @ position %s' % relay) print('I2C Bus state : %s' % str(bin(self._state))) def deEnergizeRelay(self, relay): """ De-energize relay at position. :param relay: The index of the relay to de-energize (1 - 16) :type relay: int :return: None """ if checkRelayInputValue(relay): self._state &= ~(1 << (relay - 1)) if not self._debug: self._logger.log('De-energizing relay @ position %s' % relay) success = False while not success: success = self.__sendI2CData() time.sleep(0.1) else: print('De-energizing relay @ position %s' % relay) print('I2C Bus state : %s' % str(bin(self._state))) def __sendI2CData(self): try: self.bus.write_byte_data(int(self.address, 16), 0xFF & ~self.state, 0xFF & (~(0x00FF & (self.state >> 8)))) return True except Exception as e: self.logger.log('Error setting relay state : %s' % e) return False @property def logger(self): return self._logger @property def debug(self): return self._debug @debug.setter def debug(self, value): if not isinstance(value, bool): raise TypeError('Debug value must be of type bool, %s provided.' % type(value)) else: self._debug = value @property def bus(self): return self._bus @property def address(self): return self._address @property def state(self): return self._state @bus.setter def bus(self, value): """ Set the I2C bus to use. :param value: Bus parameter to set. :type value: int :return: None """ self._bus = value @address.setter def address(self, value): """ Set the I2C address to use. :param value: I2C address. :type value: int :return: None """ self._address = value
def __init__(self): self._tracs = [] self._logger = Logger('tracs', 'Class : Tracs')