Example #1
0
    def __init__(self, HUB_SERIAL_NUM, PORT_NUM):

        # voltage to direction mapping when connect to a 10k 5v pull up
        self.v_d_tuples_raw = [
            (3.84, 0.0),
            (1.98, 22.5),
            (2.25, 45.0),
            (0.41, 67.5),
            (0.45, 90.0),
            (0.32, 112.5),
            (0.90, 135.0),
            (0.62, 157.5),
            (1.40, 180.0),
            (1.19, 202.5),
            (3.08, 225.0),
            (2.93, 247.5),
            (4.62, 270.0),
            (4.04, 292.5),
            (4.33, 315.0),
            (3.43, 337.5),
        ]
        self.v_d_tuples = []
        self.init_voltage_range_map()

        self.ch = VoltageInput()
        self.ch.setDeviceSerialNumber(HUB_SERIAL_NUM)
        self.ch.setHubPort(PORT_NUM)

        super(WindDirectionDevice, self).__init__(self.ch)
Example #2
0
 def attachSensor(self):
     '''
     Connects the sensor to the application
     '''
     self.channel = VoltageInput()
     self.channel.setDeviceSerialNumber(self.deviceSN)
     self.channel.setChannel(self.channelNo)
     self.channel.openWaitForAttachment(100)
     print("\n***** {} Sensor Attached *****".format(self.sensorName))
     self.attached = True
     self.channel.setSensorType(self.sensorType)
     self.channel.setDataInterval(self.dataInterval)
     self.sensorUnits=self.channel.getSensorUnit().symbol
Example #3
0
def main():
    snd1 = SoundSensor()
    snd2 = SoundSensor()
    temp = VoltageRatioInput()
    hum = VoltageRatioInput()
    light = VoltageInput()

    openChannels(snd1, snd2, temp, hum, light)

    for i in range(10):
        print(getJSONSensorValues(snd1, snd2, temp, hum, light))
        print('')
        time.sleep(1)

    snd1.close()
    snd2.close()
    temp.close()
    hum.close()
    light.close()
 def __init__(self,channel,sensor_name,topic_name,modo):
     self.channel = channel
     self.sensor_name = sensor_name
     self.topic_name = topic_name
     self.modo = modo
     self.pub = rospy.Publisher(self.topic_name, DeviceInfo, queue_size=10)
     self.msg = DeviceInfo()
     self.modo = modo
     if modo == 'ANALOG':
         self.ch = VoltageInput()
     elif modo == 'DIGITAL':
         self.ch = DigitalInput()
Example #5
0
    def __init__(self):
        # Name of the controller
        self.name = "PAUL controller for Raspberry Pi"

        # Current Speed of the robot
        self.speed = 0
        # Speed that the robot will travel up (note negative speed goes up)
        self.up_speed = -70
        #Speed that the robot will travel down (note negative speed goes down)
        self.down_speed = 70

        # Threshold reading on top distance sensors before triggering
        self.top_threshold = 1.9
        # Threshold reading on bottom distance sensors before triggering
        self.bottom_threshold = 2.6

        # Note: The following should only be set if distance sensors are not attached,
        # they should be set to 0 if sensors are attached.
        self.top_ds_reading = 0
        self.bottom_ds_reading = 0

        # Create an instance of the Motors class used in SDP
        self.mc = Motors()

        #Sensors
        #define array of digital inputs to store readings from the bump sensors
        self.bump_sensors = [DigitalInput() for i in range (0,6)]
        #addressing the channels for the bump sensors
        #0-2 are top sensors
        #3-5 are bottom channels
        for i in range(0,6):
            self.bump_sensors[i].setChannel(i)
            self.bump_sensors[i].openWaitForAttachment(5000)

        #define array of analogue inputs to store readings from the ir sensors
        self.ir_sensors = [VoltageInput() for i in range (0,6)]
        #addressing the channels for the ir sensors
        #0-2 are top sensors
        #3-5 are bottom channels
        for i in range(0,6):
            self.ir_sensors[i].setChannel(i)
            #this line will basically call the event handler when the readings change
            self.ir_sensors[i].openWaitForAttachment(5000)


        #Light
        # connect to pin 12(slot PWM)
        PIN = 18
        # For Grove - WS2813 RGB LED Strip Waterproof - 30 LED/m
        # there is 30 RGB LEDs.
        COUNT = 60
        self.strip = GroveWS2813RgbStrip(PIN, COUNT)
Example #6
0
def main():
    try:
        """
        * Allocate a new Phidget Channel object
        """
        try:
            ch = VoltageInput()
        except PhidgetException as e:
            sys.stderr.write("Runtime Error -> Creating VoltageInput: \n\t")
            DisplayError(e)
            raise
        except RuntimeError as e:
            sys.stderr.write("Runtime Error -> Creating VoltageInput: \n\t" +
                             e)
            raise
        """
        * Set matching parameters to specify which channel to open
        """
        ch.setDeviceSerialNumber(261542)
        ch.setChannel(0)
        """
        * Add event handlers before calling open so that no events are missed.
        """
        SetAttachDetachError_Handlers(ch)

        SetVoltageHandler(ch, onVoltageChangeHandler)

        SetSensorHandler(ch, onSensorChangeHandler)
        """
        * Open the channel with a timeout
        """
        OpenPhidgetChannel_waitForAttach(ch, 5000)

        print("Sampling data for 10 seconds...")
        pub = rospy.Publisher('GripperForceSensor', String, queue_size=1)
        rospy.init_node('talker', anonymous=True)
        rate = rospy.Rate(10)
        while not rospy.is_shutdown():
            talker(volts, publisher=pub)
            rate.sleep()
        """
         * Perform clean up and exit
         """

        SetVoltageHandler(ch, None)

        print("\nDone Sampling...")

        print("Cleaning up...")
        ClosePhidgetChannel(ch)
        print("\nExiting...")
        print("Press ENTER to end program.")
        readin = sys.stdin.readline(1)
        return 0

    except PhidgetException as e:
        sys.stderr.write("\nExiting with error(s)...")
        DisplayError(e)
        print("Press ENTER to end program.")
        readin = sys.stdin.readline(1)
        return 1
Example #7
0
def main():
        voltageInput0 = VoltageInput()
        voltageInput1 = VoltageInput()
        voltageInput2 = VoltageInput()
        voltageInput3 = VoltageInput()
        voltageInput4 = VoltageInput()
        voltageInput5 = VoltageInput()
        voltageInput6 = VoltageInput()
        voltageInput7 = VoltageInput()

        voltageInput0.setChannel(0)
        voltageInput1.setChannel(1)
        voltageInput2.setChannel(2)
        voltageInput3.setChannel(3)
        voltageInput4.setChannel(4)
        voltageInput5.setChannel(5)
        voltageInput6.setChannel(6)
        voltageInput7.setChannel(7)

        voltageInput0.setOnVoltageChangeHandler(onVoltageChange)
        voltageInput1.setOnVoltageChangeHandler(onVoltageChange)
        voltageInput2.setOnVoltageChangeHandler(onVoltageChange)
Example #8
0
            #invert motors
        
        else:
            #continue

#defining array of digital inputs
digitalIN = [DigitalInput() for i in range (0,8)]
#addressing the channels
for i in range(0,8):
    digitalIN[i].setChannel(i)
    digitalIN[i].setOnStateChangeHandler(BSonStateChange)
    digitalIN[i].openWaitForAttachment(5000)

#defining array of analogue inputs

analogueIN = [VoltageInput() for i in range (0,8)]
#addressing the channels
for i in range(0,8):
    analogueIN[i].setChannel(i)
    
    #this line will basically call the event handler when the readings change
    analogueIN[i].setOnVoltageChangeHandler(IRonVoltageChange)
    analogueIN[i].openWaitForAttachment(5000)

#creating an average of the IR sensors
top_ds_reading = (analogueIN[0] + analogueIN[1] + analogueIN[2])/3

bottom_ds_reading = (analogueIN[3] + analogueIN[4] + analogueIN[5])/3
#closing channels
for i in range (0, 8):
    analogueIN[i].close()
Example #9
0
 def __init__(self, provider, channel):
     self.ai = VoltageInput()
     self.ai.setDeviceSerialNumber(provider)
     self.ai.setChannel(channel)
     self.ai.setOnAttachHandler(self._attached)
     self.ai.openWaitForAttachment(1000)
Example #10
0
#!/usr/bin/env python
# license removed for brevity
import rospy
import sys
import time 
from std_msgs.msg import Float32
from Phidget22.Devices.VoltageInput import *
from Phidget22.PhidgetException import *
from Phidget22.Phidget import *
from Phidget22.Net import *

try:
    pub = rospy.Publisher('obstacle_distance', Float32, queue_size=10)
    rospy.init_node('phidgets_sharp', anonymous=True)
    ch1 = VoltageInput()
   
   
except RuntimeError as e:
    print("Runtime Exception %s" % e.details)
    print("Press Enter to Exit...\n")
    readin = sys.stdin.read(1)
    exit(1)

def VoltageInputAttached(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())
def main():
    global current, voltage, app, serverUpdateThread, hadPhidgetException, sessionFile

    hadPhidgetException = False

    voltage_sensor = None
    current_sensor = None
    serverUpdateThread = StoppableThread()

    sessionNum = 0

    with open("numSessions.txt", "r+") as numSessionsFile:
        sessionNum = int(numSessionsFile.read()) + 1
        print(sessionNum)
        numSessionsFile.seek(0)
        numSessionsFile.write(str(sessionNum))
        numSessionsFile.truncate()
        numSessionsFile.close()

    timestamp = datetime.now()
    sessionFile = open(
        "Sessions/session" + str(sessionNum) + "_" + str(timestamp.month) +
        "-" + str(timestamp.day) + "_" + str(timestamp.hour) + "-" +
        str(timestamp.minute) + "-" + str(timestamp.second) + ".txt", "w+")

    print("Session File created")

    try:
        voltage_sensor = VoltageInput()
        current_sensor = VoltageRatioInput()

        voltage_sensor.setHubPort(0)
        voltage_sensor.setIsHubPortDevice(False)
        voltage_sensor.setOnVoltageChangeHandler(on_new_voltage_reading)

        current_sensor.setHubPort(1)
        current_sensor.setIsHubPortDevice(True)
        current_sensor.setOnVoltageRatioChangeHandler(on_new_current_reading)

        voltage_sensor.openWaitForAttachment(1000)
        current_sensor.openWaitForAttachment(1000)

        serverUpdateThread.start()

        atexit.register(exit_handler)
        app.run(host='0.0.0.0')
        voltage_sensor.close()
        current_sensor.close()

    except PhidgetException as e:
        print(e)
        hadPhidgetException = True
        exit_handler(voltage_sensor, current_sensor)

    except KeyboardInterrupt as key:
        print(key)
        exit_handler(voltage_sensor, current_sensor)

    except IOError as e:
        print(e)
        exit_handler(voltage_sensor, current_sensor)
Example #12
0
    def __init__(self):
        self.motor_current_publisher = rospy.Publisher(
            'phidgetsensor/motor_current_draw', Float64, queue_size=10)
        self.voltage_publisher = rospy.Publisher(
            'phidgetsensor/battery_voltage', Float64, queue_size=10)
        self.battery_current_publisher = rospy.Publisher(
            'phidgetsensor/battery_current_draw', Float64, queue_size=10)

        self._hz = 10

        #Channel 1 will be the motor_current_draw
        ch1 = CurrentInput()

        channelInfo = ChannelInfo()
        channelInfo.deviceSerialNumber = 539331
        channelInfo.hubPort = 2
        channelInfo.isHubPortDevice = 0
        channelInfo.channel = 0

        ch1.setDeviceSerialNumber(channelInfo.deviceSerialNumber)
        ch1.setHubPort(channelInfo.hubPort)
        ch1.setIsHubPortDevice(channelInfo.isHubPortDevice)
        ch1.setChannel(channelInfo.channel)

        ch1.setOnAttachHandler(self.onAttachHandler)
        ch1.setOnDetachHandler(self.onDetachHandler)
        ch1.setOnErrorHandler(self.onErrorHandler)
        ch1.setOnCurrentChangeHandler(self.onCurrentChangeHandler_m)

        try:
            ch1.openWaitForAttachment(5000)
        except PhidgetException as e:
            PrintOpenErrorMessage(e, ch1)
            raise EndProgramSignal("Program Terminated: Open ch1 failed")
        #channel 2 will be the battery voltage
        ch2 = VoltageInput()

        channelInfo = ChannelInfo()
        channelInfo.deviceSerialNumber = 539331
        channelInfo.hubPort = 1
        channelInfo.isHubPortDevice = 0
        channelInfo.channel = 0

        ch2.setDeviceSerialNumber(channelInfo.deviceSerialNumber)
        ch2.setHubPort(channelInfo.hubPort)
        ch2.setIsHubPortDevice(channelInfo.isHubPortDevice)
        ch2.setChannel(channelInfo.channel)

        ch2.setOnAttachHandler(self.onAttachHandler)
        ch2.setOnDetachHandler(self.onDetachHandler)
        ch2.setOnErrorHandler(self.onErrorHandler)
        ch2.setOnVoltageChangeHandler(self.onVoltageChangeHandler)

        try:
            ch2.openWaitForAttachment(5000)
        except PhidgetException as e:
            PrintOpenErrorMessage(e, ch2)
            raise EndProgramSignal("Program Terminated: Open ch2 failed")

        #channel 3 will be the battery current
        ch3 = CurrentInput()

        channelInfo = ChannelInfo()
        channelInfo.deviceSerialNumber = 539331
        channelInfo.hubPort = 0
        channelInfo.isHubPortDevice = 0
        channelInfo.channel = 0

        ch3.setDeviceSerialNumber(channelInfo.deviceSerialNumber)
        ch3.setHubPort(channelInfo.hubPort)
        ch3.setIsHubPortDevice(channelInfo.isHubPortDevice)
        ch3.setChannel(channelInfo.channel)

        ch3.setOnAttachHandler(self.onAttachHandler)
        ch3.setOnDetachHandler(self.onDetachHandler)
        ch3.setOnErrorHandler(self.onErrorHandler)
        ch3.setOnCurrentChangeHandler(self.onCurrentChangeHandler_b)

        try:
            ch3.openWaitForAttachment(5000)
        except PhidgetException as e:
            PrintOpenErrorMessage(e, ch3)
            raise EndProgramSignal("Program Terminated: Open ch3 failed")
Example #13
0
 def __init__(self):
     self.voltage_publisher = rospy.Publisher('CurrentSensor/battery_voltage_draw', Float64, queue_size=10)
 	self._hz = 10
     ch1 = VoltageInput()
        
     channelInfo = ChannelInfo()
     channelInfo.deviceSerialNumber = 539331
     channelInfo.hubPort = 1
     channelInfo.isHubPortDevice = 0
     channelInfo.channel = 0
        
     ch1.setDeviceSerialNumber(channelInfo.deviceSerialNumber)
     ch1.setHubPort(channelInfo.hubPort)
     ch1.setIsHubPortDevice(channelInfo.isHubPortDevice)
     ch1.setChannel(channelInfo.channel)   
         
     ch1.setOnAttachHandler(self.onAttachHandler)
     ch1.setOnDetachHandler(self.onDetachHandler)
     ch1.setOnErrorHandler(self.onErrorHandler)
     ch1.setOnVoltageChangeHandler(self.onVoltageChangeHandler)
     ch1.setOnSensorChangeHandler(self.onSensorChangeHandler)
         
     print("\nOpening and Waiting for Attachment...")
     
     try:
         ch1.openWaitForAttachment(5000)
     except PhidgetException as e:
         PrintOpenErrorMessage(e, ch1)
         raise EndProgramSignal("Program Terminated: Open Failed")
Example #14
0
class WindDirectionDevice(Device):
    def __init__(self, HUB_SERIAL_NUM, PORT_NUM):

        # voltage to direction mapping when connect to a 10k 5v pull up
        self.v_d_tuples_raw = [
            (3.84, 0.0),
            (1.98, 22.5),
            (2.25, 45.0),
            (0.41, 67.5),
            (0.45, 90.0),
            (0.32, 112.5),
            (0.90, 135.0),
            (0.62, 157.5),
            (1.40, 180.0),
            (1.19, 202.5),
            (3.08, 225.0),
            (2.93, 247.5),
            (4.62, 270.0),
            (4.04, 292.5),
            (4.33, 315.0),
            (3.43, 337.5),
        ]
        self.v_d_tuples = []
        self.init_voltage_range_map()

        self.ch = VoltageInput()
        self.ch.setDeviceSerialNumber(HUB_SERIAL_NUM)
        self.ch.setHubPort(PORT_NUM)

        super(WindDirectionDevice, self).__init__(self.ch)

    def on_attach(self):
        self.ch.setDataInterval(500)
        self.ch.setVoltageChangeTrigger(0.01)
        self.listen("VoltageChange", self.onVoltageChangeHandler)

    def onVoltageChangeHandler(self, ch, voltage):
        logging.debug("voltage changed to %f", voltage)
        self.set_event_val("wind_direction", self.find_direction(voltage))

    def init_voltage_range_map(self):
        self.v_d_tuples_raw = sorted(
            self.v_d_tuples_raw, key=lambda v_d_map: v_d_map[0])

        previous_range_end = 0.0
        for idx, v_d_tuple in enumerate(self.v_d_tuples_raw):
            mid_point = v_d_tuple[0]
            direction = v_d_tuple[1]
            if (idx + 1) == len(self.v_d_tuples_raw):
                next_midpoint = self.v_d_tuples_raw[idx - 1][0]
            else:
                next_midpoint = self.v_d_tuples_raw[idx + 1][0]
            margin = abs((next_midpoint - mid_point)/2)
            range_start = previous_range_end
            range_end = mid_point + margin
            previous_range_end = range_end
            v_range = (range_start, range_end)
            self.v_d_tuples.append((v_range, direction))

    def find_direction(self, voltage):
        for v_range, direction in self.v_d_tuples:
            if v_range[0] < voltage <= v_range[1]:
                return direction
        return None
Example #15
0
    def __init__(self):
	self.motor_current_publisher = rospy.Publisher('phidgetsensor/motor_current_draw', Float64, queue_size=10)
	self.voltage_publisher = rospy.Publisher('phidgetsensor/battery_voltage' , Float64, queue_size=10)
	self.battery_current_publisher = rospy.Publisher('phidgetsensor/battery_current_draw', Float64, queue_size=10)

	self._hz = 10
	
	#Channel 1 will be the motor_current_draw
	ch1 = CurrentInput()

	channelInfo = ChannelInfo()
	channelInfo.deviceSerialNumber = 539331
	channelInfo.hubPort = 2
	channelInfo.isHubPortDevice = 0
	channelInfo.channel = 0

	ch1.setDeviceSerialNumber(channelInfo.deviceSerialNumber)
        ch1.setHubPort(channelInfo.hubPort)
        ch1.setIsHubPortDevice(channelInfo.isHubPortDevice)
        ch1.setChannel(channelInfo.channel) 

        ch1.setOnAttachHandler(self.onAttachHandler)
        ch1.setOnDetachHandler(self.onDetachHandler)
        ch1.setOnErrorHandler(self.onErrorHandler)
        ch1.setOnCurrentChangeHandler(self.onCurrentChangeHandler_m)
	
	try: 
	    ch1.openWaitForAttachment(5000)
	except PhidgetException as e:
	    PrintOpenErrorMessage(e, ch1)
	    raise EndProgramSignal("Program Terminated: Open ch1 failed")
	#channel 2 will be the battery voltage
	ch2 = VoltageInput()

        channelInfo = ChannelInfo()
        channelInfo.deviceSerialNumber = 539331
        channelInfo.hubPort = 1
        channelInfo.isHubPortDevice = 0
        channelInfo.channel = 0

        ch2.setDeviceSerialNumber(channelInfo.deviceSerialNumber)
        ch2.setHubPort(channelInfo.hubPort)
        ch2.setIsHubPortDevice(channelInfo.isHubPortDevice)
        ch2.setChannel(channelInfo.channel) 

        ch2.setOnAttachHandler(self.onAttachHandler)
        ch2.setOnDetachHandler(self.onDetachHandler)
        ch2.setOnErrorHandler(self.onErrorHandler)
        ch2.setOnVoltageChangeHandler(self.onVoltageChangeHandler)

        try: 
            ch2.openWaitForAttachment(5000)
        except PhidgetException as e:
            PrintOpenErrorMessage(e, ch2)
            raise EndProgramSignal("Program Terminated: Open ch2 failed")

	#channel 3 will be the battery current
	ch3 = CurrentInput()

        channelInfo = ChannelInfo()
        channelInfo.deviceSerialNumber = 539331
        channelInfo.hubPort = 0
        channelInfo.isHubPortDevice = 0
        channelInfo.channel = 0

        ch3.setDeviceSerialNumber(channelInfo.deviceSerialNumber)
        ch3.setHubPort(channelInfo.hubPort)
        ch3.setIsHubPortDevice(channelInfo.isHubPortDevice)
        ch3.setChannel(channelInfo.channel) 

        ch3.setOnAttachHandler(self.onAttachHandler)
        ch3.setOnDetachHandler(self.onDetachHandler)
        ch3.setOnErrorHandler(self.onErrorHandler)
        ch3.setOnCurrentChangeHandler(self.onCurrentChangeHandler_b)
	
        try: 
            ch3.openWaitForAttachment(5000)
        except PhidgetException as e:
            PrintOpenErrorMessage(e, ch3)
            raise EndProgramSignal("Program Terminated: Open ch3 failed")
Example #16
0
    def __init__(self):
        self.voltage_publisher = rospy.Publisher(
            'CurrentSensor/battery_voltage_draw', Float64, queue_size=10)
        self._hz = 10
        ch1 = VoltageInput()

        channelInfo = ChannelInfo()
        channelInfo.deviceSerialNumber = 539331
        channelInfo.hubPort = 1
        channelInfo.isHubPortDevice = 0
        channelInfo.channel = 0

        ch1.setDeviceSerialNumber(channelInfo.deviceSerialNumber)
        ch1.setHubPort(channelInfo.hubPort)
        ch1.setIsHubPortDevice(channelInfo.isHubPortDevice)
        ch1.setChannel(channelInfo.channel)

        ch1.setOnAttachHandler(self.onAttachHandler)
        ch1.setOnDetachHandler(self.onDetachHandler)
        ch1.setOnErrorHandler(self.onErrorHandler)
        ch1.setOnVoltageChangeHandler(self.onVoltageChangeHandler)
        ch1.setOnSensorChangeHandler(self.onSensorChangeHandler)

        print("\nOpening and Waiting for Attachment...")

        try:
            ch1.openWaitForAttachment(5000)
        except PhidgetException as e:
            PrintOpenErrorMessage(e, ch1)
            raise EndProgramSignal("Program Terminated: Open Failed")
Example #17
0
	def _publish(self):
		"""
		* Allocate a new Phidget Channel object
		"""

		try:
			try:
				ch = VoltageInput()
			except PhidgetException as e:
				sys.stderr.write("Runtime Error -> Creating VoltageInput: \n\t")
				DisplayError(e)
				raise
			except RuntimeError as e:
				sys.stderr.write("Runtime Error -> Creating VoltageInput: \n\t" + e)
				raise
			
			def signal_handler(signal, frame):
				print("exiting...")
				raise EndProgramSignal("Program Terminated")
			signal.signal(signal.SIGINT, signal_handler)
			
			channelInfo = ChannelInfo()
			channelInfo.deviceSerialNumber = 539331
			channelInfo.hubPort = 0
			channelInfo.isHubPortDevice = 1
			channelInfo.channel = 0
	
			ch.setDeviceSerialNumber(channelInfo.deviceSerialNumber)
			ch.setHubPort(channelInfo.hubPort)
			ch.setIsHubPortDevice(channelInfo.isHubPortDevice)
			ch.setChannel(channelInfo.channel)
				
			"""
			* Add event handlers before calling open so that no events are missed.
			"""	
			print(channelInfo.deviceSerialNumber)
			print(channelInfo.hubPort)
			ch.setOnAttachHandler(onAttachHandler)
			ch.setOnDetachHandler(onDetachHandler)
			ch.setOnErrorHandler(onErrorHandler)
			ch.setOnVoltageChangeHandler(onVoltageChangeHandler)
			ch.setOnSensorChangeHandler(onSensorChangeHandler)
			
			print("\nOpening and Waiting for Attachment...")
			try:
				ch.openWaitForAttachment(5000)
			except PhidgetException as e:
				PrintOpenErrorMessage(e, ch)
				raise EndProgramSign00al("Program Terminated: Open Failed")
			

			print("running...")
			rate = rospy.Rate(self._hz)
			while True:
				self.current_publisher.publish(str(current[0]))
				if current[0] > 14 : playsound('/home/mars/Downloads/torture.wav')
				rate.sleep()

		except PhidgetException as e:
			sys.stderr.write("\nExiting with error(s)...")
			DisplayError(e)
			traceback.print_exc()
			print("Cleaning up...")
			ch.setOnVoltageChangeHandler(None)
			ch.setOnSensorChangeHandler(None)
			ch.close()
			return 1
		except EndProgramSignal as e:
			print(e)
			print("Cleaning up...")
			ch.setOnVoltageChangeHandler(None)
			ch.setOnSensorChangeHandler(None)
			ch.close()
			return 1
		except KeyboardInterrupt:
			ch.setOnVoltageChangeHandler(None)
			ch.setOnSensorChangeHandler(None)
			ch.close()
			return 1
Example #18
0
class VoltageInputSensor(Sensor):
    '''Class used to handle any sensor which uses a standard voltage input '''

    def __init__(self, deviceSN,channelNo,dataInterval,refreshPeriod,sensorType,
                sensorName=None):
        '''
        Constructor for creating Voltage Input Sensor objects. Takes standard sensor
        arguments.
        '''
        self.channelNo = channelNo
        self.sensorType = sensorType
        self.sensorUnits = None
        Sensor.__init__(self,deviceSN,dataInterval,refreshPeriod,sensorName)

    def attachSensor(self):
        '''
        Connects the sensor to the application
        '''
        self.channel = VoltageInput()
        self.channel.setDeviceSerialNumber(self.deviceSN)
        self.channel.setChannel(self.channelNo)
        self.channel.openWaitForAttachment(100)
        print("\n***** {} Sensor Attached *****".format(self.sensorName))
        self.attached = True
        self.channel.setSensorType(self.sensorType)
        self.channel.setDataInterval(self.dataInterval)
        self.sensorUnits=self.channel.getSensorUnit().symbol

    def activateDataListener(self):
        '''
        Sets up the event which triggers when the sensor updates its outputs
        '''
        self.startTime = time.time()
        def onSensorValueChange(channelObject,sensorVlue,sensorUnit):
            rawTime = time.time()
            deltaTime = rawTime- self.startTime
            self.dataQ.put([channelObject.getSensorValue(),deltaTime,rawTime])
        self.channel.setOnSensorChangeHandler(onSensorValueChange)
Example #19
0
def main():
    try:
        """
        * Allocate a new Phidget Channel object
        """
        try:
            ch = VoltageInput()
        except PhidgetException as e:
            sys.stderr.write("Runtime Error -> Creating VoltageInput: \n\t")
            DisplayError(e)
            raise
        except RuntimeError as e:
            sys.stderr.write("Runtime Error -> Creating VoltageInput: \n\t" + e)
            raise

        """
        * Set matching parameters to specify which channel to open
        """
        
        #You may remove this line and hard-code the addressing parameters to fit your application
        channelInfo = AskForDeviceParameters(ch)
        
        ch.setDeviceSerialNumber(channelInfo.deviceSerialNumber)
        ch.setHubPort(channelInfo.hubPort)
        ch.setIsHubPortDevice(channelInfo.isHubPortDevice)
        ch.setChannel(channelInfo.channel)   
        
        if(channelInfo.netInfo.isRemote):
            ch.setIsRemote(channelInfo.netInfo.isRemote)
            if(channelInfo.netInfo.serverDiscovery):
                try:
                    Net.enableServerDiscovery(PhidgetServerType.PHIDGETSERVER_DEVICEREMOTE)
                except PhidgetException as e:
                    PrintEnableServerDiscoveryErrorMessage(e)
                    raise EndProgramSignal("Program Terminated: EnableServerDiscovery Failed")
            else:
                Net.addServer("Server", channelInfo.netInfo.hostname,
                    channelInfo.netInfo.port, channelInfo.netInfo.password, 0)
        
        """
        * Add event handlers before calling open so that no events are missed.
        """
        print("\n--------------------------------------")
        print("\nSetting OnAttachHandler...")
        ch.setOnAttachHandler(onAttachHandler)
        
        print("Setting OnDetachHandler...")
        ch.setOnDetachHandler(onDetachHandler)
        
        print("Setting OnErrorHandler...")
        ch.setOnErrorHandler(onErrorHandler)
        
        #This call may be harmlessly removed
        PrintEventDescriptions()
        
        print("\nSetting OnVoltageChangeHandler...")
        ch.setOnVoltageChangeHandler(onVoltageChangeHandler)
        
        print("\nSetting OnSensorChangeHandler...")
        ch.setOnSensorChangeHandler(onSensorChangeHandler)
        
        """
        * Open the channel with a timeout
        """
        
        print("\nOpening and Waiting for Attachment...")
        
        try:
            ch.openWaitForAttachment(5000)
        except PhidgetException as e:
            PrintOpenErrorMessage(e, ch)
            raise EndProgramSignal("Program Terminated: Open Failed")
        
        print("Sampling data for 10 seconds...")
        
        print("You can do stuff with your Phidgets here and/or in the event handlers.")
        
        time.sleep(10)
        
        """
        * Perform clean up and exit
        """

        #clear the VoltageChange event handler 
        ch.setOnVoltageChangeHandler(None)  
        #clear the SensorChange event handler
        ch.setOnSensorChangeHandler(None)
        
        print("\nDone Sampling...")

        print("Cleaning up...")
        ch.close()
        print("\nExiting...")
        return 0

    except PhidgetException as e:
        sys.stderr.write("\nExiting with error(s)...")
        DisplayError(e)
        traceback.print_exc()
        print("Cleaning up...")
        ch.setOnVoltageChangeHandler(None)
        ch.setOnSensorChangeHandler(None)
        ch.close()
        return 1
    except EndProgramSignal as e:
        print(e)
        print("Cleaning up...")
        ch.setOnVoltageChangeHandler(None)
        ch.setOnSensorChangeHandler(None)
        ch.close()
        return 1
    finally:
        print("Press ENTER to end program.")
        readin = sys.stdin.readline()
Example #20
0
class PowerSource():
    def __init__(self, channel):
        self.volts = None
        self.device = VoltageInput()
        self.channel = channel
        this = self

    def start(self):
        """
		* Add event handlers before calling open so that no events are missed.
		"""
        self.device.setOnAttachHandler(onAttachHandler)
        self.device.setOnDetachHandler(onDetachHandler)
        self.device.setOnErrorHandler(onErrorHandler)
        self.device.setOnVoltageChangeHandler(onVoltageChangeHandler)
        self.device.setOnSensorChangeHandler(onSensorChangeHandler)

        try:
            self.device.setDeviceSerialNumber(271638)
            self.device.setChannel(self.channel)
            self.device.openWaitForAttachment(5000)
        except PhidgetException as e:
            print("Program Terminated: Open PowerSource Failed")
            print(e)

    def getVolts(self):
        try:
            self.device.setDeviceSerialNumber(271638)
            self.device.setChannel(self.channel)
            self.device.openWaitForAttachment(5000)
        except PhidgetException as e:
            print("Program Terminated: Open PowerSource Failed")
            print(e)

        time.sleep(2)
        return self.device.getSensorValue()

    def closeDevice(self):
        self.device.close()
Example #21
0
 def __init__(self, channel):
     self.volts = None
     self.device = VoltageInput()
     self.channel = channel
     this = self
Example #22
0
    def _publish(self):
        """
		* Allocate a new Phidget Channel object
		"""

        try:
            try:
                ch = VoltageInput()
            except PhidgetException as e:
                sys.stderr.write(
                    "Runtime Error -> Creating VoltageInput: \n\t")
                DisplayError(e)
                raise
            except RuntimeError as e:
                sys.stderr.write(
                    "Runtime Error -> Creating VoltageInput: \n\t" + e)
                raise

            def signal_handler(signal, frame):
                print("exiting...")
                raise EndProgramSignal("Program Terminated")

            signal.signal(signal.SIGINT, signal_handler)

            channelInfo = ChannelInfo()
            channelInfo.deviceSerialNumber = 539331
            channelInfo.hubPort = 0
            channelInfo.isHubPortDevice = 1
            channelInfo.channel = 0

            ch.setDeviceSerialNumber(channelInfo.deviceSerialNumber)
            ch.setHubPort(channelInfo.hubPort)
            ch.setIsHubPortDevice(channelInfo.isHubPortDevice)
            ch.setChannel(channelInfo.channel)
            """
			* Add event handlers before calling open so that no events are missed.
			"""
            print(channelInfo.deviceSerialNumber)
            print(channelInfo.hubPort)
            ch.setOnAttachHandler(onAttachHandler)
            ch.setOnDetachHandler(onDetachHandler)
            ch.setOnErrorHandler(onErrorHandler)
            ch.setOnVoltageChangeHandler(onVoltageChangeHandler)
            ch.setOnSensorChangeHandler(onSensorChangeHandler)

            print("\nOpening and Waiting for Attachment...")
            try:
                ch.openWaitForAttachment(5000)
            except PhidgetException as e:
                PrintOpenErrorMessage(e, ch)
                raise EndProgramSign00al("Program Terminated: Open Failed")

            print("running...")
            rate = rospy.Rate(self._hz)
            while True:
                self.current_publisher.publish(str(current[0]))
                if current[0] > 14:
                    playsound('/home/mars/Downloads/torture.wav')
                rate.sleep()

        except PhidgetException as e:
            sys.stderr.write("\nExiting with error(s)...")
            DisplayError(e)
            traceback.print_exc()
            print("Cleaning up...")
            ch.setOnVoltageChangeHandler(None)
            ch.setOnSensorChangeHandler(None)
            ch.close()
            return 1
        except EndProgramSignal as e:
            print(e)
            print("Cleaning up...")
            ch.setOnVoltageChangeHandler(None)
            ch.setOnSensorChangeHandler(None)
            ch.close()
            return 1
        except KeyboardInterrupt:
            ch.setOnVoltageChangeHandler(None)
            ch.setOnSensorChangeHandler(None)
            ch.close()
            return 1
Example #23
0
class jigVoltage(object):
    '''voltage sensor'''

    def __init__(self, provider, channel):
        self.ai = VoltageInput()
        self.ai.setDeviceSerialNumber(provider)
        self.ai.setChannel(channel)
        self.ai.setOnAttachHandler(self._attached)
        self.ai.openWaitForAttachment(1000)

    def _attached(self, event):
        self.ai.setSensorType(VoltageSensorType.SENSOR_TYPE_1135)
        self.ai.setDataInterval(100)
        self.ai.setVoltageChangeTrigger(0)

    @property
    def voltage(self):
        return self.ai.getSensorValue()

    @property
    def unitInfo(self):
        return self.ai.getSensorUnit()