def initEncoder(self, serialNum, initPosition = 0): self.encoder = Encoder() try: self.encoder.setDeviceSerialNumber(serialNum) self.encoder.setChannel(0) self.encoder.setOnAttachHandler(self.onEncoderAttached) self.encoder.setOnDetachHandler(self.onEncoderDetached) self.encoder.setOnErrorHandler(self.onErrorEvent) #self.encoder.setOnPositionChangeHandler(self.onPositionChanged) self.encoder.openWaitForAttachment(5000) self.encoder.setPosition(initPosition) self.encoder.setDataInterval(10) if(not self.encoder.getEnabled()): self.encoder.setEnabled(1) except PhidgetException as e: print("Phidget Exception %i: %s" % (e.code, e.details)) endTest("Encoder init error")
def main(): #Create your Phidget channels encoder0 = Encoder() #Set addressing parameters to specify which channel to open (if any) #Assign any event handlers you need before calling open so that no events are missed. encoder0.setOnPositionChangeHandler(onPositionChange) #Open your Phidgets and wait for attachment encoder0.openWaitForAttachment(5000) #Do stuff with your Phidgets here or in your event handlers try: input("Press Enter to Stop\n") except (Exception, KeyboardInterrupt): pass #Close your Phidgets once the program is done. encoder0.close()
def initEncoder(channel): try: ch0 = Encoder() except RuntimeError as e: print "Runtime Exception %s" % e.details print "Press Enter to Exit...\n" readin = sys.stdin.read(1) exit(1) #Initialize Phidgetboard encoder try: ch0.setOnAttachHandler(EncoderAttached) ch0.setOnDetachHandler(EncoderDetached) ch0.setOnErrorHandler(ErrorEvent) ch0.setChannel(channel) print("Waiting for the Phidget Encoder Object to be attached...") ch0.openWaitForAttachment(5000) except PhidgetException as e: print "Phidget Exception %i: %s" % (e.code, e.details) print "Press Enter to Exit...\n" readin = sys.stdin.read(1) exit(1) if(not ch0.getEnabled()): ch0.setEnabled(1) ch0.setDataInterval(dataInterval_ms) return ch0
import csv import time import dial_indicator from Phidget22.Devices.Encoder import * from Phidget22.PhidgetException import * from Phidget22.Phidget import * from Phidget22.Net import * tick_per_rev = 4096 mm_per_rev = 3.175 samplerate_hz = float(20) sampletime_s = 0 dataInterval_ms = 25 try: ch = Encoder() except RuntimeError as e: print "Runtime Exception %s" % e.details print "Press Enter to Exit...\n" readin = sys.stdin.read(1) exit(1) def EncoderAttached(self): try: attached = self print "\nAttach Event Detected (Information Below)" print "===========================================" print "Library Version: %s" % attached.getLibraryVersion() print "Serial Number: %d" % attached.getDeviceSerialNumber() print "Channel: %d" % attached.getChannel() print "Channel Class: %s" % attached.getChannelClass()
def plugin_reconfigure(handle, new_config): """ Reconfigures the plugin Args: handle: handle returned by the plugin initialisation call new_config: JSON object representing the new configuration category for the category Returns: new_handle: new handle to be used in the future calls """ _LOGGER.info("Old config for wind_turbine plugin {} \n new config {}".format(handle, new_config)) # Shutdown sensors try: handle['humidity'].close() handle['temperature'].close() handle['current'].close() handle['encoder'].close() handle['accelerometer'].close() handle['gyroscope'].close() handle['magnetometer'].close() except Exception as ex: _LOGGER.exception("wind_turbine exception: {}".format(str(ex))) raise ex time.sleep(5) new_handle = copy.deepcopy(new_config) try: # check if temp/humidity sensor is enabled. If so restart it if new_handle['tempHumEnable']['value'] == 'true': new_handle['humidity'] = HumiditySensor() new_handle['humidity'].setDeviceSerialNumber(int(new_handle['hubSN']['value'])) new_handle['humidity'].setHubPort(int(new_handle['tempHumPort']['value'])) new_handle['humidity'].setIsHubPortDevice(False) new_handle['humidity'].setChannel(0) new_handle['humidity'].openWaitForAttachment(5000) try: new_handle['humidity'].getHumidity() except Exception: pass new_handle['temperature'] = TemperatureSensor() new_handle['temperature'].setDeviceSerialNumber(int(new_handle['hubSN']['value'])) new_handle['temperature'].setHubPort(int(new_handle['tempHumPort']['value'])) new_handle['temperature'].setIsHubPortDevice(False) new_handle['temperature'].setChannel(0) new_handle['temperature'].openWaitForAttachment(5000) try: new_handle['temperature'].getTemperature() except Exception: pass # check if current sensor is enabled, if so restart it if new_handle['currentEnable']['value'] == 'true': new_handle['current'] = CurrentInput() new_handle['current'].setDeviceSerialNumber(int(new_handle['hubSN']['value'])) new_handle['current'].setHubPort(int(new_handle['currentPort']['value'])) new_handle['current'].setIsHubPortDevice(False) new_handle['current'].setChannel(0) new_handle['current'].openWaitForAttachment(5000) try: new_handle['current'].getCurrent() except Exception: pass # check if encoder sensor is enabled if new_handle['encoderEnable']['value'] == 'true': new_handle['encoder'] = Encoder() new_handle['encoder'].setDeviceSerialNumber(int(new_handle['hubSN']['value'])) new_handle['encoder'].setHubPort(int(new_handle['encoderPort']['value'])) new_handle['encoder'].setIsHubPortDevice(False) new_handle['encoder'].setChannel(0) new_handle['encoder'].openWaitForAttachment(5000) new_handle['encoder'].setDataInterval(20) i = 0 while i < 120: try: new_handle['encoder'].getPosition() except Exception: time.sleep(1) i += 1 else: break # check if accelerometer is enabled if new_handle['accelerometerEnable']['value'] == 'true': new_handle['accelerometer'] = Accelerometer() new_handle['accelerometer'].setDeviceSerialNumber(int(new_handle['hubSN']['value'])) new_handle['accelerometer'].setHubPort(int(new_handle['spatialPort']['value'])) new_handle['accelerometer'].setIsHubPortDevice(False) new_handle['accelerometer'].setChannel(0) new_handle['accelerometer'].openWaitForAttachment(5000) new_handle['accelerometer'].setDataInterval(20) i = 0 while i < 120: try: new_handle['accelerometer'].getAcceleration() except Exception: time.sleep(1) i += 1 else: break # check if gyroscope is enabled if new_handle['gyroscopeEnable']['value'] == 'true': new_handle['gyroscope'] = Gyroscope() new_handle['gyroscope'].setDeviceSerialNumber(int(new_handle['hubSN']['value'])) new_handle['gyroscope'].setHubPort(int(new_handle['spatialPort']['value'])) new_handle['gyroscope'].setIsHubPortDevice(False) new_handle['gyroscope'].setChannel(0) new_handle['gyroscope'].openWaitForAttachment(5000) new_handle['gyroscope'].setDataInterval(20) i = 0 while i < 120: try: new_handle['gyroscope'].getAngularRate() except Exception: time.sleep(1) i += 1 else: break # check if magnetometer enable is enabled if new_handle['magnetometerEnable']['value'] == 'true': new_handle['magnetometer'] = Magnetometer() new_handle['magnetometer'].setDeviceSerialNumber(int(new_handle['hubSN']['value'])) new_handle['magnetometer'].setHubPort(int(new_handle['spatialPort']['value'])) new_handle['magnetometer'].setIsHubPortDevice(False) new_handle['magnetometer'].setChannel(0) new_handle['magnetometer'].openWaitForAttachment(5000) new_handle['magnetometer'].setDataInterval(20) i = 0 while i < 120: try: new_handle['magnetometer'].getMagneticField() except Exception: time.sleep(1) i += 1 else: break # check if hub has changed, if so init restart if new_handle['hubSN']['value'] != handle['hubSN']['value']: new_handle['restart'] = 'yes' else: new_handle['restart'] = 'no' except Exception as ex: _LOGGER.exception("wind_turbine exception: {}".format(str(ex))) raise ex # counter to know when to run process new_handle['tempHumCount'] = 0 new_handle['currentCount'] = 0 new_handle['encoderCount'] = 0 new_handle['accelerometerCount'] = 0 new_handle['gyroscopeCount'] = 0 new_handle['magnetometerCount'] = 0 # counter of last encoder value new_handle['encoderPreviousValue'] = handle['encoderPreviousValue'] return new_handle
def plugin_init(config): """ Initialise the plugin. Args: config: JSON configuration document for the South plugin configuration category Returns: data: JSON object to be used in future calls to the plugin Raises: """ try: data = copy.deepcopy(config) if data['tempHumEnable']['value'] == 'true': data['humidity'] = HumiditySensor() data['humidity'].setDeviceSerialNumber(int(data['hubSN']['value'])) data['humidity'].setHubPort(int(data['tempHumPort']['value'])) data['humidity'].setIsHubPortDevice(False) data['humidity'].setChannel(0) data['humidity'].openWaitForAttachment(5000) try: data['humidity'].getHumidity() except Exception: pass data['temperature'] = TemperatureSensor() data['temperature'].setDeviceSerialNumber(int(data['hubSN']['value'])) data['temperature'].setHubPort(int(data['tempHumPort']['value'])) data['temperature'].setIsHubPortDevice(False) data['temperature'].setChannel(0) data['temperature'].openWaitForAttachment(5000) try: data['temperature'].getTemperature() except Exception: pass if data['currentEnable']['value'] == 'true': data['current'] = CurrentInput() data['current'].setDeviceSerialNumber(int(data['hubSN']['value'])) data['current'].setHubPort(int(data['currentPort']['value'])) data['current'].setIsHubPortDevice(False) data['current'].setChannel(0) data['current'].openWaitForAttachment(5000) try: data['current'].getCurrent() except Exception: pass if data['encoderEnable']['value'] == 'true': data['encoder'] = Encoder() data['encoder'].setDeviceSerialNumber(int(data['hubSN']['value'])) data['encoder'].setHubPort(int(data['encoderPort']['value'])) data['encoder'].setIsHubPortDevice(False) data['encoder'].setChannel(0) data['encoder'].openWaitForAttachment(5000) data['encoder'].setDataInterval(20) i = 0 while i < 120: try: data['encoder'].getPosition() except Exception: time.sleep(1) i += 1 else: break if data['accelerometerEnable']['value'] == 'true': data['accelerometer'] = Accelerometer() data['accelerometer'].setDeviceSerialNumber(int(data['hubSN']['value'])) data['accelerometer'].setHubPort(int(data['spatialPort']['value'])) data['accelerometer'].setIsHubPortDevice(False) data['accelerometer'].setChannel(0) data['accelerometer'].openWaitForAttachment(5000) data['accelerometer'].setDataInterval(20) i = 0 while i < 120: try: data['accelerometer'].getAcceleration() except Exception: time.sleep(1) i += 1 else: break if data['gyroscopeEnable']['value'] == 'true': data['gyroscope'] = Gyroscope() data['gyroscope'].setDeviceSerialNumber(int(data['hubSN']['value'])) data['gyroscope'].setHubPort(int(data['spatialPort']['value'])) data['gyroscope'].setIsHubPortDevice(False) data['gyroscope'].setChannel(0) data['gyroscope'].openWaitForAttachment(5000) data['gyroscope'].setDataInterval(20) i = 0 while i < 120: try: data['gyroscope'].getAngularRate() except Exception: time.sleep(1) i += 1 else: break if data['magnetometerEnable']['value'] == 'true': data['magnetometer'] = Magnetometer() data['magnetometer'].setDeviceSerialNumber(int(data['hubSN']['value'])) data['magnetometer'].setHubPort(int(data['spatialPort']['value'])) data['magnetometer'].setIsHubPortDevice(False) data['magnetometer'].setChannel(0) data['magnetometer'].openWaitForAttachment(5000) data['magnetometer'].setDataInterval(20) i = 0 while i < 120: try: data['magnetometer'].getMagneticField() except Exception: time.sleep(1) i += 1 else: break except Exception as ex: _LOGGER.exception("wind_turbine exception: {}".format(str(ex))) raise ex # counter to know when to run process data['tempHumCount'] = 0 data['currentCount'] = 0 data['encoderCount'] = 0 data['accelerometerCount'] = 0 data['gyroscopeCount'] = 0 data['magnetometerCount'] = 0 # counter of last encoder value data['encoderPreviousValue'] = 0 data['encoderPreviousTime'] = 0 return data
def run(self): def PositionChangeHandler(self, positionChange, timeChange, indexTriggered): global prevTime currentTime = time.perf_counter() ## print(str((currentTime-prevTime)*1000)+" "+str(positionChange/timeChange/360/4*1000))## if ("y" in fileSave) or ("Y" in fileSave): ## f.write(str(positionChange/timeChange/360/4*1000)+"\r\n") f.write(str((currentTime - prevTime) * 1000) + "\r\n") avVel = positionChange prevTime = currentTime def EncoderAttached(e): try: attached = e print("\nEncoder Attached") print("\n") except PhidgetException as e: print("Exception %i: %s" % (e.code, e.details)) print("Press Enter to Exit...\n") readin = sys.stdin.read(1) exit(1) def EncoderDetached(e): detached = e try: print("\nEncoder Detached") except PhidgetException as e: print("Exception %i: %s" % (e.code, e.details)) print("Press Enter to Exit...\n") readin = sys.stdin.read(1) exit(1) def ErrorEvent(e, eCode, description): print("Error %i : %s" % (eCode, description)) en = Encoder() while not stopped: if not en.getAttached(): try: en.setOnAttachHandler(EncoderAttached) en.setOnDetachHandler(EncoderDetached) en.setOnErrorHandler(ErrorEvent) en.setOnPositionChangeHandler(PositionChangeHandler) print("\nWaiting for encoder to attach") en.openWaitForAttachment(5000) if (not en.getEnabled()): en.setEnabled(1) except PhidgetException as e: print("Exception %i: %s" % (e.code, e.details)) print("Press Enter to Exit\n") readin = sys.stdin.read(1) exit(1) en.setDataInterval(encoderDataRate) en.close()
class SpinData: _all = set() _logger = None _spinner = Encoder() _waitTimeForConnect = 5000 def __init__(self, config = {}, positionChange=0, elapsedtime=0.0, position=0): SpinData._all.add(self) self.config = config self.gestureProcessor = SpinGestureProcessor(self, config) self.position = position self.delta = positionChange self.timestamp = datetime.time() self.elapsedTime = elapsedtime self.spinHistory = Queue(config['encoderQueueLength']) if (SpinData._logger == None): SpinData._logger = logging.getLogger('spinsensorserver') try: SpinData._spinner.setOnAttachHandler(SpinData.encoderAttached) SpinData._spinner.setOnDetachHandler(SpinData.encoderDetached) SpinData._spinner.setOnErrorHandler(SpinData.encoderError) # _spinner.setOnInputChangeHandler(encoderInputChange) SpinData._spinner.setOnPositionChangeHandler(SpinData.encoderPositionChange) except PhidgetException as e: d = {'clientip': "spinner", 'user':"******"} SpinData._logger.critical('_spinner init failed: %s', 'details%s'% e.details, extra=d) SpinData._spinner = None try: SpinData._spinner.openWaitForAttachment(SpinData._waitTimeForConnect) SpinData._spinner.setDataInterval(SpinData._spinner.getMinDataInterval()); except PhidgetException as e: d = {'clientip': "spinner", 'user':"******"} SpinData._logger.critical('_spinner connect failed: %s', 'details%s'% e.details, extra=d) SpinData._spinner = None def ingestSpinData(self, positionChange, time): self.delta = positionChange self.elapsedTime = time self.spinHistory.enqueue( positionChange * self.config['flipZ']) #Information Display Function def displayDeviceInfo(): pass #Event Handler Callback Functions def encoderAttached(e): attached = e try: print("\nAttach Event Detected (Information Below)") print("===========================================") print("Library Version: %s" % attached.getLibraryVersion()) print("Serial Number: %d" % attached.getDeviceSerialNumber()) print("Channel: %d" % attached.getChannel()) print("Channel Class: %s" % attached.getChannelClass()) print("Channel Name: %s" % attached.getChannelName()) print("Device ID: %d" % attached.getDeviceID()) print("Device Version: %d" % attached.getDeviceVersion()) print("Device Name: %s" % attached.getDeviceName()) print("Device Class: %d" % attached.getDeviceClass()) print("\n") except PhidgetException as e: print("Phidget Exception %i: %s" % (e.code, e.details)) print("Press Enter to Exit...\n") readin = sys.stdin.read(1) d = {'clientip': "spinner", 'user':"******"} SpinData._logger.info('Encoder Attached! %s', 'good news', extra=d) d = { 'clientip': "spinner", 'user': "******" %(SpinData._spinner.getMinPositionChangeTrigger(), SpinData._spinner.getPositionChangeTrigger())} SpinData._logger.critical('Encoder setup: %s', "hmmm", extra=d) def encoderDetached(e): detached = e d = {'clientip': "spinner", 'user':"******" } SpinData._logger.warning('Encoder Detached: %s', detached.getDeviceSerialNumber(), extra=d) def encoderError(e, eCode, description): source = e d = {'clientip': "spinner", 'user':"******"} SpinData._logger.error('Encoder error %s', description, extra=d) def encoderInputChange(e): source = e.device def encoderPositionChange(e, positionChange, timeChange, indexTriggered): source = e for spinner in SpinData._all: spinner.ingestSpinData(positionChange, timeChange)
def main(): # Make sure current path is this file path abspath = os.path.abspath(__file__) dname = os.path.dirname(abspath) os.chdir(dname) ############ #import config file config = ConfigParser.ConfigParser() print("opening configuration file : config.cfg") config.read('config.cfg') ############ #connect to mqtt broker client = MQTT_client.createClient("Encoder", config) ############ #connection to Phidget encoder and wait for measures #publish the datas on config/MQTT/topic try: Log.enable(LogLevel.PHIDGET_LOG_INFO, "phidgetlog.log") #Create your Phidget channels encoder0 = Encoder() #Set addressing parameters to specify encoder0.client = client encoder0.clientTopic = config.get('MQTT', 'topic_publish') encoder0.printLog = config.getboolean('encoder', 'printLog') encoder0.chooseDataInterval = config.getint('encoder', 'dataInterval') #Assign any event handlers you need before calling open so that no events are missed. encoder0.setOnPositionChangeHandler(handler.onPositionChange) encoder0.setOnAttachHandler(handler.onAttach) encoder0.setOnDetachHandler(handler.onDetach) #Open your Phidgets and wait for attachment encoder0.openWaitForAttachment(5000) #Do stuff with your Phidgets here or in your event handlers. #Change the data interval from the encoder based on config datas # encoder0.setDataInterval(config.getint('encoder','dataInterval')) #Interupt script by pressing Enter try: input("Press Enter to Stop\n") except (Exception, KeyboardInterrupt): pass #Close your Phidgets once the program is done. encoder0.close() except PhidgetException as ex: #We will catch Phidget Exceptions here, and print the error informaiton. traceback.print_exc() print("") print("PhidgetException " + str(ex.code) + " (" + ex.description + "): " + ex.details) finally: encoder0.close()
def setupUi(self, Tester): Tester.setObjectName("Tester") Tester.resize(673, 541) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap("../../Downloads/Cirris.ico"), QtGui.QIcon.Normal, QtGui.QIcon.Off) Tester.setWindowIcon(icon) self.centralwidget = QtWidgets.QWidget(Tester) self.centralwidget.setObjectName("centralwidget") self.groupBox_2 = QtWidgets.QGroupBox(self.centralwidget) self.groupBox_2.setGeometry(QtCore.QRect(200, 0, 191, 80)) self.groupBox_2.setObjectName("groupBox_2") self.RecordingEnco = QtWidgets.QSlider(self.groupBox_2) self.RecordingEnco.setGeometry(QtCore.QRect(10, 30, 160, 16)) self.RecordingEnco.setOrientation(QtCore.Qt.Horizontal) self.RecordingEnco.setObjectName("RecordingEnco") self.RegisterEnco = QtWidgets.QCheckBox(self.groupBox_2) self.RegisterEnco.setGeometry(QtCore.QRect(10, 50, 92, 23)) self.RegisterEnco.setObjectName("RegisterEnco") self.CloseButton = QtWidgets.QPushButton(self.centralwidget) self.CloseButton.setGeometry(QtCore.QRect(580, 470, 89, 25)) self.CloseButton.setObjectName("CloseButton") self.groupBox_3 = QtWidgets.QGroupBox(self.centralwidget) self.groupBox_3.setGeometry(QtCore.QRect(10, 0, 181, 391)) self.groupBox_3.setObjectName("groupBox_3") self.DisplayPlotButton = QtWidgets.QPushButton(self.groupBox_3) self.DisplayPlotButton.setGeometry(QtCore.QRect(10, 350, 161, 25)) self.DisplayPlotButton.setObjectName("DisplayPlotButton") self.lcdNumber = QtWidgets.QLCDNumber(self.groupBox_3) self.lcdNumber.setGeometry(QtCore.QRect(10, 40, 141, 51)) self.lcdNumber.setObjectName("lcdNumber") self.label_3 = QtWidgets.QLabel(self.groupBox_3) self.label_3.setGeometry(QtCore.QRect(10, 90, 161, 17)) self.label_3.setObjectName("label_3") self.lcdNumber_2 = QtWidgets.QLCDNumber(self.groupBox_3) self.lcdNumber_2.setGeometry(QtCore.QRect(10, 110, 141, 51)) self.lcdNumber_2.setObjectName("lcdNumber_2") self.label_4 = QtWidgets.QLabel(self.groupBox_3) self.label_4.setGeometry(QtCore.QRect(10, 160, 161, 17)) self.label_4.setObjectName("label_4") self.lcdNumber_3 = QtWidgets.QLCDNumber(self.groupBox_3) self.lcdNumber_3.setGeometry(QtCore.QRect(10, 180, 141, 51)) self.lcdNumber_3.setObjectName("lcdNumber_3") self.lcdNumber_4 = QtWidgets.QLCDNumber(self.groupBox_3) self.lcdNumber_4.setGeometry(QtCore.QRect(10, 250, 141, 51)) self.lcdNumber_4.setObjectName("lcdNumber_4") self.label_5 = QtWidgets.QLabel(self.groupBox_3) self.label_5.setGeometry(QtCore.QRect(10, 230, 161, 17)) self.label_5.setObjectName("label_5") self.label_6 = QtWidgets.QLabel(self.groupBox_3) self.label_6.setGeometry(QtCore.QRect(10, 300, 161, 17)) self.label_6.setObjectName("label_6") self.groupBox_4 = QtWidgets.QGroupBox(self.centralwidget) self.groupBox_4.setGeometry(QtCore.QRect(400, 0, 271, 401)) self.groupBox_4.setObjectName("groupBox_4") self.textEdit = QtWidgets.QTextEdit(self.groupBox_4) self.textEdit.setGeometry(QtCore.QRect(10, 50, 251, 70)) self.textEdit.setObjectName("textEdit") self.label = QtWidgets.QLabel(self.groupBox_4) self.label.setGeometry(QtCore.QRect(10, 30, 67, 17)) self.label.setObjectName("label") self.FileConfirmButton = QtWidgets.QPushButton(self.groupBox_4) self.FileConfirmButton.setGeometry(QtCore.QRect(10, 130, 251, 25)) self.FileConfirmButton.setObjectName("FileConfirmButton") self.textEdit_2 = QtWidgets.QTextEdit(self.groupBox_4) self.textEdit_2.setGeometry(QtCore.QRect(10, 200, 251, 70)) self.textEdit_2.setObjectName("textEdit_2") self.DirectoryConfirmB = QtWidgets.QPushButton(self.groupBox_4) self.DirectoryConfirmB.setGeometry(QtCore.QRect(10, 280, 251, 25)) self.DirectoryConfirmB.setObjectName("DirectoryConfirmB") self.label_2 = QtWidgets.QLabel(self.groupBox_4) self.label_2.setGeometry(QtCore.QRect(10, 180, 67, 17)) self.label_2.setObjectName("label_2") self.spinBox = QtWidgets.QSpinBox(self.groupBox_4) self.spinBox.setGeometry(QtCore.QRect(10, 330, 251, 26)) self.spinBox.setObjectName("spinBox") self.label_7 = QtWidgets.QLabel(self.groupBox_4) self.label_7.setGeometry(QtCore.QRect(10, 310, 131, 17)) self.label_7.setObjectName("label_7") self.DataIntervalButton = QtWidgets.QPushButton(self.groupBox_4) self.DataIntervalButton.setGeometry(QtCore.QRect(10, 360, 251, 25)) self.DataIntervalButton.setObjectName("DataIntervalButton") self.groupBox_5 = QtWidgets.QGroupBox(self.centralwidget) self.groupBox_5.setGeometry(QtCore.QRect(200, 100, 191, 111)) self.groupBox_5.setObjectName("groupBox_5") self.ToConnectButton = QtWidgets.QPushButton(self.groupBox_5) self.ToConnectButton.setGeometry(QtCore.QRect(10, 30, 171, 31)) self.ToConnectButton.setObjectName("ToConnectButton") self.ToDisconnectButton = QtWidgets.QPushButton(self.groupBox_5) self.ToDisconnectButton.setGeometry(QtCore.QRect(10, 70, 171, 31)) self.ToDisconnectButton.setObjectName("ToDisconnectButton") Tester.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(Tester) self.menubar.setGeometry(QtCore.QRect(0, 0, 673, 22)) self.menubar.setObjectName("menubar") Tester.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(Tester) self.statusbar.setObjectName("statusbar") Tester.setStatusBar(self.statusbar) self.retranslateUi(Tester) QtCore.QMetaObject.connectSlotsByName(Tester) # Ends of the GUI init------------------------------------------------------------------------------------------ # Minimum value of the SpinBox which correspond to the minimum of interval time 8ms minValueDataInt = 8 # Maximum value of the SpinBox which correspond to the maximum of interval time 1000ms maxValueDataInt = 1000 # Init of the encodeur encoder0 = Encoder() # import config file could depending on the name of the config file file = 'config.cfg' config = ConfigParser.ConfigParser() connectionStatus = False print("opening configuration file : config.cfg") config.read(file) guiReady = True # User interaction---------------------------------------------------------------------------------------------- # This blocks links all the functions with all interaction possible between the user and the GUI. self.CloseButton.clicked.connect(self.closeEvent) self.RegisterEnco.stateChanged.connect(self.registerIsOnMessage) self.DisplayPlotButton.clicked.connect(lambda: PlotData(config)) self.FileConfirmButton.clicked.connect( lambda: NewFile(file, config, self.textEditFile.toPlainText())) self.DirectoryConfirmB.clicked.connect(lambda: NewPath( file, config, self.textEditDirectory.toPlainText())) self.ToConnectButton.clicked.connect( lambda: ConnectToEnco(config, encoder0, connectionStatus)) self.ToDisconnectButton.clicked.connect( lambda: DisconnectEnco(encoder0, connectionStatus)) self.spinBox.setRange(minValueDataInt, maxValueDataInt) self.DataIntervalButton.clicked.connect( lambda: SetDataInterval(file, config, self.spinBox.value()))
import sys import time from Phidget22.Devices.DCMotor import * from Phidget22.Devices.Encoder import * from Phidget22.PhidgetException import * from Phidget22.Phidget import * from Phidget22.Net import * rightWheels = 0 leftWheels = 1 try: motorControl = DCMotor() enc = Encoder() except RuntimeError as e: print("Runtime Exception %s" % e.details) print("Press Enter to Exit...\n") readin = sys.stdin.read(1) exit(1) def ObjectAttached(self): try: attached = self print("\nAttach Event Detected (Information Below)") print("===========================================") print("Library Version: %s" % attached.getLibraryVersion()) print("Serial Number: %d" % attached.getDeviceSerialNumber()) print("Channel: %d" % attached.getChannel()) print("Channel Class: %s" % attached.getChannelClass())
import time from Phidget22.Devices.Encoder import * from Phidget22.PhidgetException import * from Phidget22.Phidget import * # code for ch sensor ch = Encoder() ch.setDeviceSerialNumber(538854) ch.setHubPort(1) ch.setIsHubPortDevice(False) ch.setChannel(0) ch.openWaitForAttachment(5000) try: ch.getPosition() except Exception as e: pass time.sleep(.2) previous = 0 current = 0 while True: current = ch.getPosition() print(current) rpm = (current - previous) / 1200 print(rpm) previous = current time.sleep(1)
class ValveControl(): _ENCODER_COUNT_PER_DEGREES = 300.0 / 90.0 _DEGREES_PER_ENCODER_COUNT = 90.0 / 300.0 def __init__(self, MEVStepperSerialNum = 423768, ventStepperSerialNum = 507392, encoderSerialNum = 426800, pinMEVCloseLimit = 5, pinMEVOpenLimit = 6, pinNCValve = 20, pinIgnitor = 16, pinNCValveRelayIn = 12, pinIgnitorRelayIn = 26, pinLockoutIn = 13, pinVentCloseLimit = 25, pinVentOpenLimit = 21): GPIO.setmode(GPIO.BCM) self.pinMEVCloseLimit = pinMEVCloseLimit GPIO.setup(self.pinMEVCloseLimit, GPIO.IN, pull_up_down=GPIO.PUD_UP) self.pinMEVOpenLimit = pinMEVOpenLimit GPIO.setup(self.pinMEVOpenLimit, GPIO.IN, pull_up_down=GPIO.PUD_UP) self.pinVentCloseLimit = pinVentCloseLimit GPIO.setup(self.pinVentCloseLimit, GPIO.IN, pull_up_down=GPIO.PUD_UP) self.pinVentOpenLimit = pinVentOpenLimit GPIO.setup(self.pinVentOpenLimit, GPIO.IN, pull_up_down=GPIO.PUD_UP) self.pinIgnitor = pinIgnitor GPIO.setup(self.pinIgnitor, GPIO.OUT) self.pinNCValve = pinNCValve GPIO.setup(self.pinNCValve, GPIO.OUT) self.pinIgnitorRelayIn = pinIgnitorRelayIn GPIO.setup(self.pinIgnitorRelayIn, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) self.pinNCValveRelayIn = pinNCValveRelayIn GPIO.setup(self.pinNCValveRelayIn, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) self.pinLockoutIn = pinLockoutIn GPIO.setup(self.pinLockoutIn, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) self.fullOpenAngle = 90 self.fullClosedAngle = 0 self.burn_duration = 0 self.MEVStepper = StepperController(MEVStepperSerialNum, 0.1125, 180, 360) self.ventStepper = None if _VENT_VALVE_ENABLED: self.ventStepper = StepperController(ventStepperSerialNum, 0.0021875, 45, 90) self.initEncoder(encoderSerialNum) self.motorPos = 0 def initEncoder(self, serialNum, initPosition = 0): self.encoder = Encoder() try: self.encoder.setDeviceSerialNumber(serialNum) self.encoder.setChannel(0) self.encoder.setOnAttachHandler(self.onEncoderAttached) self.encoder.setOnDetachHandler(self.onEncoderDetached) self.encoder.setOnErrorHandler(self.onErrorEvent) #self.encoder.setOnPositionChangeHandler(self.onPositionChanged) self.encoder.openWaitForAttachment(5000) self.encoder.setPosition(initPosition) self.encoder.setDataInterval(10) if(not self.encoder.getEnabled()): self.encoder.setEnabled(1) except PhidgetException as e: print("Phidget Exception %i: %s" % (e.code, e.details)) endTest("Encoder init error") #except Exception as e: # self.MEVStepper.terminateValveControl("init encoder error") # self.ventStepper.terminateValveControl("init encoder error") def onEncoderAttached(self, e): try: attached = e print("\nAttach Event Detected (Information Below)") print("===========================================") print("Library Version: %s" % attached.getLibraryVersion()) print("Serial Number: %d" % attached.getDeviceSerialNumber()) print("Channel: %d" % attached.getChannel()) print("Channel Class: %s" % attached.getChannelClass()) print("Channel Name: %s" % attached.getChannelName()) print("Device ID: %d" % attached.getDeviceID()) print("Device Version: %d" % attached.getDeviceVersion()) print("Device Name: %s" % attached.getDeviceName()) print("Device Class: %d" % attached.getDeviceClass()) print("\n") except Exception as e: endTest("Encoder attached error") def onEncoderDetached(self, e): try: print("\nDetach event on Port %d Channel %d" % (detached.getHubPort(), detached.getChannel())) except PhidgetException as e: terminateValveControl("encoder detached! Phidget Exception " + str(e.code) + " " + e.details) try: tempVelocity = self.velocitySetting self.MEVStepper.setVelocity(0) tempPosition = self.encoder.getPosition() self.encoder.close() self.initEncoder(tempPosition) self.MEVStepper.setVelocity(tempVelocity) except Exception as e: endTest("Encoder detached error") def onErrorEvent(self, e, eCode, description): print("Error event #%i : %s" % (eCode, description)) endTest("Encoder error") def calibratePosition(self, position = 0): self.encoder.setPosition(position) def MEVCloseLimitHit(self): return GPIO.input(self.pinMEVCloseLimit) == 0 def MEVOpenLimitHit(self): return GPIO.input(self.pinMEVOpenLimit) == 0 def VentCloseLimitHit(self): return GPIO.input(self.pinVentCloseLimit) == 0 def VentOpenLimitHit(self): return GPIO.input(self.pinVentOpenLimit) == 0 def moveMEVByAngle(self, angleDegrees, velocity): encoderTarget = self.encoder.getPosition() + (angleDegrees * ValveControl._ENCODER_COUNT_PER_DEGREES) #towards closed position if (angleDegrees < 0): self.MEVStepper.setVelocity(-velocity) while self.encoder.getPosition() > encoderTarget and not self.MEVCloseLimitHit() and not testEnded(): time.sleep(0.001) #towards open position elif (angleDegrees > 0): self.MEVStepper.setVelocity(velocity) while self.encoder.getPosition() < encoderTarget and not self.MEVOpenLimitHit() and not testEnded(): time.sleep(0.001) self.MEVStepper.setVelocity(0) def moveMEVToAngle(self, targetAngleDegrees, velocity): travelDistance = targetAngleDegrees - (self.encoder.getPosition() * ValveControl._DEGREES_PER_ENCODER_COUNT) self.moveMEVByAngle(travelDistance, velocity) def moveMEVToOpenLimit(self): if testEnded(): return self.MEVStepper.setVelocity(self.MEVStepper.defaultVelocity) while not self.MEVOpenLimitHit() and not testEnded(): time.sleep(0.001) self.MEVStepper.setVelocity(0) def moveMEVToCloseLimit(self): self.MEVStepper.setVelocity(-self.MEVStepper.defaultVelocity) while not self.MEVCloseLimitHit(): time.sleep(0.001) self.MEVStepper.setVelocity(0) def moveVentToOpenLimit(self): if self.ventStepper is None: return if testEnded(): return self.ventStepper.setVelocity(-self.ventStepper.defaultVelocity) while not self.VentOpenLimitHit() and not testEnded(): time.sleep(0.001) self.ventStepper.setVelocity(0) def moveVentToCloseLimit(self): if self.ventStepper is None: return self.ventStepper.setVelocity(self.ventStepper.defaultVelocity) while not self.VentCloseLimitHit(): time.sleep(0.001) self.ventStepper.setVelocity(0) def setIgnitor(self, active): GPIO.output(self.pinIgnitor, active) def setNCValve(self, active): GPIO.output(self.pinNCValve, active) def ignitorActive(self): return GPIO.input(self.pinIgnitorRelayIn) != 0 def NCValveActive(self): return GPIO.input(self.pinNCValveRelayIn) != 0 def lockoutArmed(self): return GPIO.input(self.pinLockoutIn) != 0 def __del__(self): GPIO.cleanup()