コード例 #1
0
    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()
コード例 #2
0
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()
コード例 #3
0
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()
コード例 #4
0
    exit(1)


if(not enc.getEnabled()):
    enc.setEnabled(1)

print("INITIAL POSITION: %d\n" % enc.getPosition());

print("Setting Target Velocity to 1 for 5 seconds...\n")
motorControl.setTargetVelocity(0.1)
time.sleep(10)

print("FINAL POSITION: %d\n" % enc.getPosition());

print("Setting Target Velocity to 0 for 5 seconds...\n")
motorControl.setTargetVelocity(0)
time.sleep(1)

try:
    motorControl.close()
    enc.close()
except PhidgetException as e:
    motorControl.setTargetVelocity(0)
    print("Phidget Exception %i: %s" % (e.code, e.details))
    print("Press Enter to Exit...\n")
    readin = sys.stdin.read(1)
    exit(1) 
print("Closed DCMotor device")
exit(0)
                     
コード例 #5
0
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()