Example #1
0
    def __init__(self, id, port):
        self.id = id
        self.port = port
        self.serial_numbers = (
            262305,  # 4-port, shelf 6
            262295,  # 4-port, shelf 6
            318471,  # 8-port, shelf 2
            312226,  # 8-port, shelf 4
            259764,  # 4-port, shelf 8
            319749,  # 8-port, shelf 10
            259763,  # 4-port, shelf 6
        )
        self.serial_num = self.serial_numbers[id]
        self.lockfile = "/var/run/lock/phidget-%s.lock" % self.id
        self.lock_fp = open(self.lockfile, "w")
        self.lock_fd = self.lock_fp.fileno()
        fcntl.lockf(self.lock_fd, fcntl.LOCK_EX)
        if debug:
            print "[%.2f] Aquired lock for Phidget %s" % (time.time(), self.id)

        try:
            self.device = InterfaceKit()
        except RuntimeError as e:
            print("Runtime Error: %s" % e.message)

        try:
            self.device.openPhidget(serial=self.serial_num)
        except PhidgetException as e:
            print("Phidget Exception %i: %s" % (e.code, e.detail))
            fcntl.lockf(self.lock_fd, fcntl.LOCK_UN)
            exit(1)

        self.device.waitForAttach(10000)
Example #2
0
class tosRelayControl:
    """
    This class handles polling and controlling the Phidgets InterfaceKit 0/0/4. It requires the PhidgetLinux libraries and the PhidgetPython libraries.
    """

    ifkit = None
    logger = None

    def __init__(self):
        """
        Instantiate the InterfaceKit object and open it.
        """
        self.logger = tosLogger
        
        self.ifkit = InterfaceKit()

        # open ifkit
        try:
            self.ifkit.openPhidget()
        except PhidgetException, e:
            self.logger.log(self, 3, "Phidget Exception %i: %s" % (e.code, e.message))
            exit(1)

        # wait for attach
        try:
            self.ifkit.waitForAttach(10000)
        except PhidgetException, e:
            self.logger.log(self, 3, "Phidget Exception %i: %s" % (e.code, e.message))
Example #3
0
class tosRelayControl:
    """
    This class handles polling and controlling the Phidgets InterfaceKit 0/0/4. It requires the PhidgetLinux libraries and the PhidgetPython libraries.
    """

    ifkit = None
    logger = None

    def __init__(self):
        """
        Instantiate the InterfaceKit object and open it.
        """
        self.logger = tosLogger

        self.ifkit = InterfaceKit()

        # open ifkit
        try:
            self.ifkit.openPhidget()
        except PhidgetException, e:
            self.logger.log(self, 3,
                            "Phidget Exception %i: %s" % (e.code, e.message))
            exit(1)

        # wait for attach
        try:
            self.ifkit.waitForAttach(10000)
        except PhidgetException, e:
            self.logger.log(self, 3,
                            "Phidget Exception %i: %s" % (e.code, e.message))
Example #4
0
 def __init__(self):
     rospy.init_node('interface_kit', anonymous=True)
     self.name = rospy.get_param('~name', '')
     self.serial = rospy.get_param('~serial_number', -1)
     
     if self.serial == -1:
         rospy.logwarn('No serial number specified. This node will connect to the first interface kit attached.')
     self.interface_kit = InterfaceKit()
Example #5
0
class phidget:
    def __init__(self, id, port):
        self.id = id
        self.port = port
        self.serial_numbers = (
            262305,  # 4-port, shelf 6
            262295,  # 4-port, shelf 6
            318471,  # 8-port, shelf 2
            312226,  # 8-port, shelf 4
            259764,  # 4-port, shelf 8
            319749,  # 8-port, shelf 10
            259763,  # 4-port, shelf 6
        )
        self.serial_num = self.serial_numbers[id]
        self.lockfile = "/var/run/lock/phidget-%s.lock" % self.id
        self.lock_fp = open(self.lockfile, "w")
        self.lock_fd = self.lock_fp.fileno()
        fcntl.lockf(self.lock_fd, fcntl.LOCK_EX)
        if debug:
            print "[%.2f] Aquired lock for Phidget %s" % (time.time(), self.id)

        try:
            self.device = InterfaceKit()
        except RuntimeError as e:
            print("Runtime Error: %s" % e.message)

        try:
            self.device.openPhidget(serial=self.serial_num)
        except PhidgetException as e:
            print("Phidget Exception %i: %s" % (e.code, e.detail))
            fcntl.lockf(self.lock_fd, fcntl.LOCK_UN)
            exit(1)

        self.device.waitForAttach(10000)

        #print ("Phidget %d attached!" % (self.device.getSerialNum()))
        #print ("Phidget has %d inputs, %d outputs, %d sensors"
        #       %(self.device.getInputCount(), self.device.getOutputCount(), self.device.getSensorCount()))

    def close(self):
        self.device.closePhidget()
        fcntl.lockf(self.lock_fd, fcntl.LOCK_UN)
        if debug:
            print "[%.2f] Released lock for Phidget %s" % (time.time(),
                                                           self.id)

    def on(self):
        self.device.setOutputState(self.port, 1)

    def off(self):
        self.device.setOutputState(self.port, 0)

    def cmd(self, cmd):
        if cmd == 'on':
            self.on()
        if cmd == 'off':
            self.off()
Example #6
0
class phidget:
    def __init__(self, id, port):
        self.id = id
        self.port = port
        self.serial_numbers = (262305, # 4-port, shelf 6
                               262295, # 4-port, shelf 6
                               318471, # 8-port, shelf 2
                               312226, # 8-port, shelf 4
                               259764, # 4-port, shelf 8
                               319749, # 8-port, shelf 10
                               259763, # 4-port, shelf 6
                               )
        self.serial_num = self.serial_numbers[id]
        self.lockfile = "/var/run/lock/phidget-%s.lock" %self.id
        self.lock_fp = open(self.lockfile, "w")
        self.lock_fd = self.lock_fp.fileno()
        fcntl.lockf(self.lock_fd, fcntl.LOCK_EX)
        if debug:
            print "[%.2f] Aquired lock for Phidget %s" %(time.time(), self.id)

        try:
            self.device = InterfaceKit()	
        except RuntimeError as e:
            print("Runtime Error: %s" % e.message)
    
        try:
            self.device.openPhidget(serial=self.serial_num)
        except PhidgetException as e:
            print ("Phidget Exception %i: %s" % (e.code, e.detail))
            fcntl.lockf(self.lock_fd, fcntl.LOCK_UN)
            exit(1)

        self.device.waitForAttach(10000)

        #print ("Phidget %d attached!" % (self.device.getSerialNum()))
        #print ("Phidget has %d inputs, %d outputs, %d sensors"
        #       %(self.device.getInputCount(), self.device.getOutputCount(), self.device.getSensorCount()))

    def close(self):
        self.device.closePhidget()
        fcntl.lockf(self.lock_fd, fcntl.LOCK_UN)
        if debug:
            print "[%.2f] Released lock for Phidget %s" %(time.time(), self.id)

    def on(self):
        self.device.setOutputState(self.port, 1)

    def off(self):
        self.device.setOutputState(self.port, 0)

    def cmd(self, cmd):
        if cmd == 'on':
            self.on()
        if cmd == 'off':
            self.off()
Example #7
0
class SensorThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        # Create
        try:
            print "Setting up sensor interface"
            self.device = InterfaceKit()	
        except RuntimeError as e:
            print("Runtime Error: %s" % e.message)
         
        # Open
        try:
            # Hook our function above into the device object
            self.device.setOnSensorChangeHandler(sensorChanged)
            self.device.openPhidget()
        except PhidgetException as e:
            print ("Phidget Exception %i: %s" % (e.code, e.detail))		
            exit(1)

    def run(self):
        self.running = True
        print "Sensors> Waiting for attach"
        try:
            self.device.setOnAttachHandler(AttachHandler)
        except PhidgetException as e:
            print "Phidget Exception %i" % (e.code)		
        pass
    
    def stop(self):
        self.running = False
        self.device.closePhidget()
Example #8
0
    def __init__(self):
        """
        Instantiate the InterfaceKit object and open it.
        """
        self.logger = tosLogger

        self.ifkit = InterfaceKit()

        # open ifkit
        try:
            self.ifkit.openPhidget()
        except PhidgetException, e:
            self.logger.log(self, 3,
                            "Phidget Exception %i: %s" % (e.code, e.message))
            exit(1)
Example #9
0
def connect_phidget():
	try:
  		log_info('creating the interface kit')
  		device = InterfaceKit()
	except RuntimeError as e:
  		log_error("Error when trying to create the device: %s" % e.message)

	#This connects to the device.
	try:
 		#print 'connecting to the device!'
  		device.openPhidget()
	except PhidgetException as e:
 		log_warning("Exception when trying to connect %i: %s" % (e.code, e.detail))		
  		exit(1)

	return device
Example #10
0
    def __init__(self, id, port):
        self.id = id
        self.port = port
        self.serial_numbers = (262305, # 4-port, shelf 6
                               262295, # 4-port, shelf 6
                               318471, # 8-port, shelf 2
                               312226, # 8-port, shelf 4
                               259764, # 4-port, shelf 8
                               319749, # 8-port, shelf 10
                               259763, # 4-port, shelf 6
                               )
        self.serial_num = self.serial_numbers[id]
        self.lockfile = "/var/run/lock/phidget-%s.lock" %self.id
        self.lock_fp = open(self.lockfile, "w")
        self.lock_fd = self.lock_fp.fileno()
        fcntl.lockf(self.lock_fd, fcntl.LOCK_EX)
        if debug:
            print "[%.2f] Aquired lock for Phidget %s" %(time.time(), self.id)

        try:
            self.device = InterfaceKit()	
        except RuntimeError as e:
            print("Runtime Error: %s" % e.message)
    
        try:
            self.device.openPhidget(serial=self.serial_num)
        except PhidgetException as e:
            print ("Phidget Exception %i: %s" % (e.code, e.detail))
            fcntl.lockf(self.lock_fd, fcntl.LOCK_UN)
            exit(1)

        self.device.waitForAttach(10000)
Example #11
0
def connect_phidget():
    try:
        log_info('creating the interface kit')
        device = InterfaceKit()
    except RuntimeError as e:
        log_error("Error when trying to create the device: %s" % e.message)

    #This connects to the device.
    try:
        #print 'connecting to the device!'
        device.openPhidget()
    except PhidgetException as e:
        log_warning("Exception when trying to connect %i: %s" %
                    (e.code, e.detail))
        exit(1)

    return device
Example #12
0
class PhidgetTextLCD(object):
  """
  A class modelled after a Phidget InterfaceKit with an integrated LCD.
  It contains a list of objects, which are subclasses of Sensor object.

  Attributes:
      analog_sensors: a list containing objects of one of subclasses of Sensor
      data_dir: a string of directory path to save sensor reading data in
  """

  def __init__(self, analog_sensors, data_dir):
    """Initializes the members."""
    self.__interfaceKit = InterfaceKit()
    self.__textLCD = TextLCD()

    self.__data_dir = data_dir

    # instantiate classes according to actual sensor port configuration
    self.sensors = []
    for sensor in analog_sensors:
      a_sensor = self.__Factory(sensor)
      self.sensors.append(a_sensor)

    try:
      # Interface Kit
      self.__interfaceKit.openPhidget()
      self.__interfaceKit.waitForAttach(10000)
      print "%s (serial: %d) attached!" % (
        self.__interfaceKit.getDeviceName(), self.__interfaceKit.getSerialNum())

      # get initial value from each sensor
      i = 0
      for sensor in self.sensors:
        #print sensor.product_name
        #print sensor.value
        sensor.value = self.__interfaceKit.getSensorValue(i)
        i += 1

      self.__interfaceKit.setOnSensorChangeHandler(self.__SensorChanged)

      # Text LCD
      self.__textLCD.openPhidget()
      self.__textLCD.waitForAttach(10000)
      print "%s attached!" % (self.__textLCD.getDeviceName())

      self.__textLCD.setCursorBlink(False)

    except PhidgetException, e:
      print "Phidget Exception %i: %s" % (e.code, e.message)
      sys.exit(1)
Example #13
0
class IfkAgent(object):
    def __init__(self, queue, serial):
        self.serial=serial
        self._q=queue
        self._ic=0 ## digital input count
        self._oc=0 ## digital output count
        self._sc=0 ## sensor input count
        
        try:
            self.ifk=InterfaceKit()
            self._setHooks()
            self.ifk.openPhidget(int(serial))
            

        except Exception,e:
            print "*** Exception: ",e
            w="Can't instantiate a Phidgets.Devices.InterfaceKit"
            Bus.publish(self, "%log", "warning", w)
Example #14
0
def start_sensors_for_changes():
	#Create and connect to the device using the InterfaceKit() method.
	#This method depends on the device that we are using. For us, it
	#happens to be the interfacekit.
	try:
  		print 'creating the interface kit'
  		device = InterfaceKit()
	except RuntimeError as e:
  		print("Error when trying to create the device: %s" % e.message)

	#This connects to the device.
	try:
  		print 'connecting to the device!'
  		device.openPhidget()
	except PhidgetException as e:
  		print ("Exception when trying to connect %i: %s" % (e.code, e.detail))
  		exit(1)

	device.setOnSensorChangeHandler(sensorChanged)
Example #15
0
class PhidgetsInterfaceKit:
    def __init__(self):
        rospy.init_node('interface_kit', anonymous=True)
        self.name = rospy.get_param('~name', '')
        self.serial = rospy.get_param('~serial_number', -1)
        
        if self.serial == -1:
            rospy.logwarn('No serial number specified. This node will connect to the first interface kit attached.')
        self.interface_kit = InterfaceKit()

    def initialize(self):
        try:
            self.interface_kit.setOnAttachHandler(self.interfaceKitAttached)
            self.interface_kit.setOnDetachHandler(self.interfaceKitDetached)
            self.interface_kit.setOnErrorhandler(self.interfaceKitError)
            self.interface_kit.setOnSensorChangeHandler(self.interfaceKitSensorChanged)
            self.interface_kit.openPhidget(self.serial)
        except PhidgetException, e:
            rospy.logfatal('Phidget Exception %i: %s' % (e.code, e.message))
            sys.exit(1)
Example #16
0
 def init(self):
     """ Init 
     """
     try:
         self.ikit = InterfaceKit()
         
         self.ikit.setOnAttachHandler(self.inferfaceKitAttached)
         self.ikit.setOnDetachHandler(self.interfaceKitDetached)
         self.ikit.setOnErrorhandler(self.interfaceKitError)
         self.ikit.setOnInputChangeHandler(self.interfaceKitInputChanged)
         self.ikit.setOnOutputChangeHandler(self.interfaceKitOutputChanged)
         self.ikit.setOnSensorChangeHandler(self.interfaceKitSensorChanged)
     except Exception,e:
         pass
Example #17
0
    def __init__(self):
        """
        Instantiate the InterfaceKit object and open it.
        """
        self.logger = tosLogger
        
        self.ifkit = InterfaceKit()

        # open ifkit
        try:
            self.ifkit.openPhidget()
        except PhidgetException, e:
            self.logger.log(self, 3, "Phidget Exception %i: %s" % (e.code, e.message))
            exit(1)
Example #18
0
 def __init__(self):
     threading.Thread.__init__(self)
     # Create
     try:
         print "Setting up sensor interface"
         self.device = InterfaceKit()	
     except RuntimeError as e:
         print("Runtime Error: %s" % e.message)
      
     # Open
     try:
         # Hook our function above into the device object
         self.device.setOnSensorChangeHandler(sensorChanged)
         self.device.openPhidget()
     except PhidgetException as e:
         print ("Phidget Exception %i: %s" % (e.code, e.detail))		
         exit(1)
Example #19
0
def init():
        notifo = Notifo(user="******", secret="xc53e5cdc470b9adb5165adcd4aeb597549136d7c")
        db=MySQLdb.connect(host="localhost",user="******",passwd="",db="security")
        c=db.cursor()
        interfaceKit = InterfaceKit()
        interfaceKit.openPhidget()
        interfaceKit.waitForAttach(10000)
        security_state = interfaceKit.getInputState(0)
        sec_state(security_state)
        FD,BSDR,BSLR = getSensor()
        updateMysql(FD,"FD")
        updateMysql(BSDR,"BSDR")
        updateMysql(BSLR,"BSLR")
Example #20
0
  def __init__(self, analog_sensors, data_dir):
    """Initializes the members."""
    self.__interfaceKit = InterfaceKit()
    self.__textLCD = TextLCD()

    self.__data_dir = data_dir

    # instantiate classes according to actual sensor port configuration
    self.sensors = []
    for sensor in analog_sensors:
      a_sensor = self.__Factory(sensor)
      self.sensors.append(a_sensor)

    try:
      # Interface Kit
      self.__interfaceKit.openPhidget()
      self.__interfaceKit.waitForAttach(10000)
      print "%s (serial: %d) attached!" % (
        self.__interfaceKit.getDeviceName(), self.__interfaceKit.getSerialNum())

      # get initial value from each sensor
      i = 0
      for sensor in self.sensors:
        #print sensor.product_name
        #print sensor.value
        sensor.value = self.__interfaceKit.getSensorValue(i)
        i += 1

      self.__interfaceKit.setOnSensorChangeHandler(self.__SensorChanged)

      # Text LCD
      self.__textLCD.openPhidget()
      self.__textLCD.waitForAttach(10000)
      print "%s attached!" % (self.__textLCD.getDeviceName())

      self.__textLCD.setCursorBlink(False)

    except PhidgetException, e:
      print "Phidget Exception %i: %s" % (e.code, e.message)
      sys.exit(1)
Example #21
0
    def __init__(self):
        try:
            self.device = InterfaceKit()
        except RuntimeError as e:
            print("Runtime Error: %s" % e.message)

        self.height = 0
        self.vel = 0
        self.last_hit_time = 0
        self.lock = Lock()

        num = [0.0181,0.0543,0.0543,0.0181]
        den = [1,-1.76,1.1829,-0.2781]

        self.vzfilter = IIRfilter(num,den)

        try:
            self.device.setOnAttachHandler(self.AttachHandler)
            self.device.setOnDetachHandler(self.DetachHandler)
            self.device.openPhidget()
            self.device.setOnSensorChangeHandler(self.sensorChanged)
        except PhidgetException as e:
            self.LocalErrorCatcher(e)
Example #22
0
def start_sensors_for_changes():
    #Create and connect to the device using the InterfaceKit() method.
    #This method depends on the device that we are using. For us, it
    #happens to be the interfacekit.
    try:
        print 'creating the interface kit'
        device = InterfaceKit()
    except RuntimeError as e:
        print("Error when trying to create the device: %s" % e.message)

    #This connects to the device.
    try:
        print 'connecting to the device!'
        device.openPhidget()
    except PhidgetException as e:
        print("Exception when trying to connect %i: %s" % (e.code, e.detail))
        exit(1)

    device.setOnSensorChangeHandler(sensorChanged)
Example #23
0
    return 0
 
def LocalErrorCatcher(event):
    print("Phidget Exception: " + str(e.code) + " - " + str(e.details) + ", Exiting...")
    exit(1)


if __name__ == '__main__':

#    f = open('sonar.txt','a')
#    f.write('********************************\n')
#    f.close()

    # Create
    try:
        device = InterfaceKit()	
    except RuntimeError as e:
        print("Runtime Error: %s" % e.message)
        
    try:
        device.setOnAttachHandler(AttachHandler)
        device.setOnDetachHandler(DetachHandler)
        device.openPhidget()
        device.setOnSensorChangeHandler(sensorChanged)
    except PhidgetException as e: 
        LocalErrorCatcher(e)

    try:
        pub = rospy.Publisher('sonar', Float32)
        rospy.init_node('sonar')
    except rospy.ROSInterruptException:
Example #24
0
import cgitb
 
cgitb.enable()
errors = ""
 
# Print the HTML header
print("Content-type: text/html\n\n")
print("<html><title>FULL INTERFACE KIT</title><body>\n")
print('<center><b><font size="16" color="#0000ff">FULL INTERFACEKIT</font></b></center><br>')
print('<font size="4">THIS PROJECT WILL DEVELOP IN A FULL FUNCTIONAL WEB APPLICATION TO CONTROL THE PHIDGETS SBC</font>')
print('<br>&#169 J J Slabbert') 
print('<br><a href="mailto:[email protected]">[email protected]</a><br><br>')

# Create, Open, and Attach the Interface Kit
try:
    ifk = InterfaceKit()
except RuntimeError as e:
    errors = errors + "<h5>Runtime Exception on object creation: " + e.details + "</h5>\n"
try:
    ifk.openRemoteIP('192.168.10.106',5001)
except PhidgetException as e:
    errors = errors + "<h5>Phidget Exception on Open: " + e.details + "</h5>\n"
try:
    ifk.waitForAttach(10000)
except PhidgetException as e:
    errors = errors + "<h5>Phidget Exception on Attach: " + e.details + "</h5>\n"
    errors = errors + "<h5>If Phidget is 'Not Physically Attached' it may be in use</h5>\n"

print('<table><tr><td>')

Example #25
0
from Phidgets.Devices.Encoder import *
import time
import numpy

import liblo
try:
  target = liblo.Address(1234)
except liblo.AddressError, err:
  print str(err)
  sys.exit()

steer = 0
velocity = 0

try:
   interfaceKit = InterfaceKit()
   encoder = Encoder()

except RuntimeError as e:
  print("Runtime Error: %s" % e.message)

def interfaceKitSensorChanged(e):
  global steer
  DEAD_ZONE = 0
  if e.index == 0:
    steer = numpy.clip((e.value-263)/110.0, -1, 1)
    if abs(steer) < DEAD_ZONE:
      steer = 0
    print "steer", steer
  return 0
Example #26
0
from Phidgets.PhidgetException import *
from Phidgets.Events.Events import *
from Phidgets.Devices.InterfaceKit import *
from lws_client_backend import gen_id_val, get_local_ip
import time

#Create and connect to the device using the InterfaceKit() method.
#This method depends on the device that we are using. For us, it
#happens to be the interfacekit.
try:
    print 'creating the interface kit'
    device = InterfaceKit()
except RuntimeError as e:
    print("Error when trying to create the device: %s" % e.message)

#This connects to the device.
try:
    print 'connecting to the device!'
    device.openPhidget()
except PhidgetException as e:
    print("Exception when trying to connect %i: %s" % (e.code, e.detail))
    exit(1)


def start_sensors_for_changes():
    #Create and connect to the device using the InterfaceKit() method.
    #This method depends on the device that we are using. For us, it
    #happens to be the interfacekit.
    try:
        print 'creating the interface kit'
        device = InterfaceKit()
Example #27
0
import cgitb

cgitb.enable()
errors = ""

# Print the HTML header
print("Content-type: text/html\n\n")
print("<html><title>FULL INTERFACE KIT</title><body>\n")
print('<center><b><font size="16" color="#0000ff">FULL INTERFACEKIT</font></b></center><br>')
print('<font size="4">THIS PROJECT WILL DEVELOP IN A FULL FUNCTIONAL WEB APPLICATION TO CONTROL THE PHIDGETS SBC</font>')
print('<br>&#169 J J Slabbert')
print('<br><a href="mailto:[email protected]">[email protected]</a><br><br>')

# Create, Open, and Attach the Interface Kit
try:
    ifk = InterfaceKit()
except RuntimeError as e:
    errors = errors + "<h5>Runtime Exception on object creation: " + e.details + "</h5>\n"
try:
    ifk.openPhidget()
except PhidgetException as e:
    errors = errors + "<h5>Phidget Exception on Open: " + e.details + "</h5>\n"
try:
    ifk.waitForAttach(10000)
except PhidgetException as e:
    errors = errors + "<h5>Phidget Exception on Attach: " + e.details + "</h5>\n"
    errors = errors + "<h5>If Phidget is 'Not Physically Attached' it may be in use</h5>\n"

try:
    ifk.setOutputState(4,1)
    print('<font size="16">Digital Output 4 set True</font>')
Example #28
0
__author__ = 'Adam Stelmack'
__version__ = '2.1.4'
__date__ = 'May 02 2008'

#Basic imports
from threading import *
from ctypes import *
import sys
#Phidget specific imports
from Phidgets.PhidgetException import *
from Phidgets.Events.Events import *
from Phidgets.Devices.InterfaceKit import *
import time

#Create an interfacekit object
interfaceKit = InterfaceKit()

#Information Display Function
def displayDeviceInfo():
    print "|------------|----------------------------------|--------------|------------|"
    print "|- Attached -|-              Type              -|- Serial No. -|-  Version -|"
    print "|------------|----------------------------------|--------------|------------|"
    print "|- %8s -|- %30s -|- %10d -|- %8d -|" % (interfaceKit.isAttached(), interfaceKit.getDeviceType(), interfaceKit.getSerialNum(), interfaceKit.getDeviceVersion())
    print "|------------|----------------------------------|--------------|------------|"
    return 0

#Event Handler Callback Functions
def inferfaceKitAttached(e):
    attached = e.device
    print "InterfaceKit %i Attached!" % (attached.getSerialNum())
    return 0
Example #29
0
from Phidgets.PhidgetException import *
from Phidgets.Events.Events import *
from Phidgets.Devices.InterfaceKit import *

try:
  device = InterfaceKit()
except RuntimeError as e:
  print("Runtime Error: %s" % e.message)

def sensorChanged(e):
  if e.value > 0 and e.value < 301:
    device.setOutputState(0, 1)
    device.setOutputState(1, 0)
    device.setOutputState(2, 0)
  if e.value > 300 and e.value < 601:
    device.setOutputState(0, 0)
    device.setOutputState(1, 1)
    device.setOutputState(2, 0)
  if e.value > 601 and e.value < 999:
    device.setOutputState(0, 0)
    device.setOutputState(1, 0)
    device.setOutputState(2, 1)

try:
  device.openPhidget()
  device.waitForAttach(10000)
except PhidgetException as e:
  print('Phidget Exception')
  exit(1)

def AttachHandler(event):
Example #30
0
from ctypes import *
import sys
import random
from dbconnect import dbconnect
#Phidget specific imports
from Phidgets.PhidgetException import *
from Phidgets.Events.Events import *
from Phidgets.Devices.InterfaceKit import *

connect = dbconnect()
controllerID = 902
connect.disconnected(controllerID)

#Create an interfacekit object
try:
    interfaceKit = InterfaceKit()
except RuntimeError as e:
    print("Runtime Exception: %s" % e.details)
    print("Exiting....")
    exit(1)


#Event Handler Callback Functions
def inferfaceKitAttached(e):
    connect.connected(controllerID)
    attached = e.device
    print("InterfaceKit %i Attached!" % (attached.getSerialNum()))


def interfaceKitDetached(e):
    connect.disconnected(controllerID)
Example #31
0
        for i in range(len(codeInfo.Repeat)):
            if i > 0:
                printStr += ", "
            printStr += str(codeInfo.Repeat[i])
        printStr += " }"
        
        message("Repeat: %s" % (printStr))
    else:
        message("Repeat: None")
    
    message("MinRepeat: %d\nToggle Mask: %s\nCarrier Frequency: %d\nDuty Cycle: %d" % (codeInfo.MinRepeat, codeInfo.ToggleMask.toString(), codeInfo.CarrierFrequency, codeInfo.DutyCycle))
    message("----------------------------------------------------")


try:
    interfaceKit = InterfaceKit()
    message( "Setting up interface", interfaceKit)
    ir = IR()
except RuntimeError as e:
    print("Runtime Error: %s" % e.message)

try:
    try:
        message( "Opening IR Device 121774")
        ir.openPhidget(121774)
        message( "Waiting for attachment...")
        ir.waitForAttach(10000)
        message("Device ready.")
        ir.setOnAttachHandler(irAttached)
        ir.setOnDetachHandler(irDetached)
        ir.setOnErrorhandler(irError)
Example #32
0
class Sonar:
    def __init__(self):
        try:
            self.device = InterfaceKit()
        except RuntimeError as e:
            print("Runtime Error: %s" % e.message)

        self.height = 0
        self.vel = 0
        self.last_hit_time = 0
        self.lock = Lock()

        num = [0.0181,0.0543,0.0543,0.0181]
        den = [1,-1.76,1.1829,-0.2781]

        self.vzfilter = IIRfilter(num,den)

        try:
            self.device.setOnAttachHandler(self.AttachHandler)
            self.device.setOnDetachHandler(self.DetachHandler)
            self.device.openPhidget()
            self.device.setOnSensorChangeHandler(self.sensorChanged)
        except PhidgetException as e:
            self.LocalErrorCatcher(e)

    def AttachHandler(self,event):
        attachedDevice = event.device
        serialNumber = attachedDevice.getSerialNum()
        deviceName = attachedDevice.getDeviceName()
        attachedDevice.setRatiometric(True)
        attachedDevice.setSensorChangeTrigger(5,1)
        print("Hello to Device " + str(deviceName) + ", Serial Number: " + str(serialNumber))

    def DetachHandler(self,event):
        detachedDevice = event.device
        serialNumber = detachedDevice.getSerialNum()
        deviceName = detachedDevice.getDeviceName()
        print("Goodbye Device " + str(deviceName) + ", Serial Number: " + str(serialNumber))

    def sensorChanged(self,e):
    #    f = open('sonar.txt','a')
        with self.lock:
            current_hit = time.time()
            time_elapse = current_hit-self.last_hit_time
            if time_elapse > 0.1:
                #print ("Sensor height {0} cm vel {1} cm/s".format(self.height, self.vel))
                self.last_hit_time= current_hit
                self.vel = (e.value*1024.0/1000-self.height)/time_elapse
                self.vzfilter.add_raw_data(self.vel)
                self.vel = self.vzfilter.get_filter_data()
                self.height = e.value*1024.0/1000
            #    print ("Sensor %i: %i" % (e.index, height))
            #    f.write('Height at %.3f\n',height)
            #    f.close()
        return 0

    def LocalErrorCatcher(event):
        print("Phidget Exception: " + str(event.code) + " - " + str(event.details) + ", Exiting...")
        exit(1)

    def get_height(self):
        #with self.lock:
        return self.height

    def get_vel(self):
        #with self.lock:
        return self.vel

    def close_phidget(self):
        print("Closing...")
    #   f = open('sonar.txt','a')
    #   f.write('********************************\n')
    #   f.close()
        try:
            self.device.closePhidget()
        except PhidgetException as e:
            self.LocalErrorCatcher(e)
Example #33
0
    #    hexStr = ''.join( hexStr.split(" ") )
    #    return ''.join( ["%c" % chr( int ( hexStr[i:i+2],16 ) ) \
    #                                   for i in range(0, len( hexStr ), 2) ] )

    bytes = []

    hexStr = ''.join(hexStr.split(" "))

    for i in range(0, len(hexStr), 2):
        bytes.append(chr(int(hexStr[i:i + 2], 16)))

    return ''.join(bytes)


try:
    interfaceKit = InterfaceKit()
except RuntimeError as e:
    print("Runtime Error: %s" % e.message)
try:
    ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
except:
    try:
        ser = serial.Serial('/dev/ttyUSB1', 9600, timeout=1)
    except:
        print "not connected"
try:
    #Your program Code here
    interfaceKit.openPhidget()
    interfaceKit.waitForAttach(10000)
    print("%d attached!" % (interfaceKit.getSerialNum()))
    xold = 0
	for n in range(0,sensor_number):
		try:
			#print 'checking sensor on %s'%n
			values_dict[n] = device.getSensorValue(n)
		except:
			#print 'no sensor attached to port %s'%n
			values_dict[n] = 'N/A'

	return values_dict 

#Create and connect to the device using the InterfaceKit() method.
#This method depends on the device that we are using. For us, it
#happens to be the interfacekit.
try:
 #log_info('creating the interface kit')
  device = InterfaceKit()
except RuntimeError as e:
  log_warning("Error when trying to create the device")
  #log_warning("Error when trying to create the device: %s" % e.message)

#This connects to the device.
try:
  log_info('connecting to the device!')
  device.openPhidget()
except PhidgetException as e:
  log_warning("Exception when trying to connect")
  #log_warning("Exception when trying to connect %i: %s" % (e.code, e.detail))		
  exit(1)

device.setOnSensorChangeHandler(sensorChanged)
Example #35
0
__author__ = 'Adam Stelmack'
__version__ = '2.1.4'
__date__ = 'May 02 2008'

#Basic imports
from threading import *
from ctypes import *
import sys
#Phidget specific imports
from Phidgets.PhidgetException import *
from Phidgets.Events.Events import *
from Phidgets.Devices.InterfaceKit import *
import time

#Create an interfacekit object
interfaceKit = InterfaceKit()


#Information Display Function
def displayDeviceInfo():
    print "|------------|----------------------------------|--------------|------------|"
    print "|- Attached -|-              Type              -|- Serial No. -|-  Version -|"
    print "|------------|----------------------------------|--------------|------------|"
    print "|- %8s -|- %30s -|- %10d -|- %8d -|" % (
        interfaceKit.isAttached(), interfaceKit.getDeviceType(),
        interfaceKit.getSerialNum(), interfaceKit.getDeviceVersion())
    print "|------------|----------------------------------|--------------|------------|"
    return 0


#Event Handler Callback Functions
Example #36
0
def main():
	parser = argparse.ArgumentParser(description='read sensor values from a Phidgets device')
	
	group = parser.add_mutually_exclusive_group(required=True)
	
	group.add_argument('-d', '--digital', metavar='<input id>', type=int, help='read from a digital input')
	group.add_argument('-a', '--analog', metavar='<sensor id>', type=int, help='read from an analog sensor')
	
	parser.add_argument('-t', '--temperature-sensor', action='store_const', const=True, default=False, help='device is a temperature sensor, output in degrees celcius. must be reading an analog sensor')
	parser.add_argument('-m', '--precision-light-sensor-multiplier', metavar='<multiplier>', type=float, help='\'m\' value from the underside of the precision light sensor. must be reading an analog sensor')
	parser.add_argument('-b', '--precision-light-sensor-boost', metavar='<boost>', type=float, help='\'b\' value from the underside of the precision light sensor. must be reading an analog sensor')
	cli_args = parser.parse_args()
	
	try:
		device = InterfaceKit()
	except RuntimeError as e:
		print("Runtime Error: %s" % e.message)
		exit(2)
	
	try:
		device.openPhidget()
		device.waitForAttach(1000)
		
		if cli_args.digital != None:
			if cli_args.digital < device.getInputCount():
				print device.getInputState(cli_args.digital)
			else:
				parser.print_usage()
				print('%s: error: input id out of range (maximum is %d)' % (sys.argv[0], device.getInputCount()-1))
		elif cli_args.analog != None:
			if cli_args.analog < device.getSensorCount():
				if cli_args.temperature_sensor == True:
					print (float(device.getSensorValue(cli_args.analog)) * 0.2222) - 61.1111 
				elif (cli_args.precision_light_sensor_multiplier == None) != (cli_args.precision_light_sensor_boost == None):
					parser.print_usage()
					print('%s: error: you must supply both precision light sensor arguments')
				elif cli_args.precision_light_sensor_multiplier != None and cli_args.precision_light_sensor_boost != None:
					print (cli_args.precision_light_sensor_multiplier * float(device.getSensorValue(cli_args.analog)) + cli_args.precision_light_sensor_boost)
				else:
					print device.getSensorValue(cli_args.analog)
			else:
				parser.print_usage()
				print('%s: error: sensor id out of range (maximum is %d)' % (sys.argv[0], device.getSensorCount()-1))
		device.closePhidget()
	except PhidgetException as e:
		print("Phidget Exception %i: %s" % (e.code, e.details))
		try:
			device.closePhidget()
		except PhidgetException as e:
			print("Phidget Exception %i: %s" % (e.code, e.details))
		print("Exiting...")
		exit(1)
	exit(0)
Example #37
0
from Phidgets.PhidgetException import *
from Phidgets.Events.Events import *
from Phidgets.Devices.InterfaceKit import *
from lws_client_backend import gen_id_val, get_local_ip
import time

#Create and connect to the device using the InterfaceKit() method.
#This method depends on the device that we are using. For us, it
#happens to be the interfacekit.
try:
  print 'creating the interface kit'
  device = InterfaceKit()
except RuntimeError as e:
  print("Error when trying to create the device: %s" % e.message)

#This connects to the device.
try:
  print 'connecting to the device!'
  device.openPhidget()
except PhidgetException as e:
  print ("Exception when trying to connect %i: %s" % (e.code, e.detail))
  exit(1)

def start_sensors_for_changes():
	#Create and connect to the device using the InterfaceKit() method.
	#This method depends on the device that we are using. For us, it
	#happens to be the interfacekit.
	try:
  		print 'creating the interface kit'
  		device = InterfaceKit()
	except RuntimeError as e:
Example #38
0
#Basic imports
from ctypes import *
import sys
import random
from dbconnect import dbconnect
#Phidget specific imports
from Phidgets.PhidgetException import *
from Phidgets.Events.Events import *
from Phidgets.Devices.InterfaceKit import *

connect = dbconnect()

#Create an interfacekit object
try:
    interfaceKit = InterfaceKit()
except RuntimeError as e:
    print("Runtime Exception: %s" % e.details)
    print("Exiting....")
    exit(1)

#Event Handler Callback Functions
def inferfaceKitAttached(e):
    attached = e.device
    print("InterfaceKit %i Attached!" % (attached.getSerialNum()))

def interfaceKitDetached(e):
    detached = e.device
    print("InterfaceKit %i Detached!" % (detached.getSerialNum()))

def interfaceKitError(e):
Example #39
0
print("Content-type: text/html\n\n")
print("<html><title>FULL INTERFACE KIT</title><body>\n")
print(
    '<center><b><font size="16" color="#0000ff">FULL INTERFACEKIT</font></b></center><br>'
)
print(
    '<font size="4">THIS PROJECT WILL DEVELOP IN A FULL FUNCTIONAL WEB APPLICATION TO CONTROL THE PHIDGETS SBC</font>'
)
print('<br>&#169 J J Slabbert')
print(
    '<br><a href="mailto:[email protected]">[email protected]</a><br><br>'
)

# Create, Open, and Attach the Interface Kit
try:
    ifk = InterfaceKit()
except RuntimeError as e:
    errors = errors + "<h5>Runtime Exception on object creation: " + e.details + "</h5>\n"
try:
    ifk.openPhidget()
except PhidgetException as e:
    errors = errors + "<h5>Phidget Exception on Open: " + e.details + "</h5>\n"
try:
    ifk.waitForAttach(10000)
except PhidgetException as e:
    errors = errors + "<h5>Phidget Exception on Attach: " + e.details + "</h5>\n"
    errors = errors + "<h5>If Phidget is 'Not Physically Attached' it may be in use</h5>\n"

try:
    ifk.setOutputState(6, 1)
    print('<font size="16">Digital Output 6 set True</font>')
Example #40
0
import tornado.web
from tornado import ioloop

from Phidgets.PhidgetException import *
from Phidgets.Events.Events import *
from Phidgets.Devices.InterfaceKit import *

import os
import sys
import time
import urllib
import urlparse

interfaceKit = InterfaceKit()
interfaceKit.openPhidget()
try:
    interfaceKit.waitForAttach(10000)
except:
    print "Cannot connect to Phidgets!"
    sys.exit(1)


class PlayHandler(tornado.web.RequestHandler):
    wget_pid = None
    mplayer_pid = None
    chrome_pid = None
    xrandr_pid = None

    def kill_helpers(self):
        if PlayHandler.wget_pid:
Example #41
0
__author__ = 'Adam Stelmack'
__version__ = '2.1.5'
__date__ = 'October 23 2008'

#Basic imports
from threading import *
from ctypes import *
import sys
#Phidget specific imports
from Phidgets.PhidgetException import *
from Phidgets.Events.Events import *
from Phidgets.Devices.InterfaceKit import *

#Create an interfacekit object
interfaceKit = InterfaceKit()

#Information Display Function
def displayDeviceInfo():
    print "|------------|----------------------------------|--------------|------------|"
    print "|- Attached -|-              Type              -|- Serial No. -|-  Version -|"
    print "|------------|----------------------------------|--------------|------------|"
    print "|- %8s -|- %30s -|- %10d -|- %8d -|" % (interfaceKit.isAttached(), interfaceKit.getDeviceType(), interfaceKit.getSerialNum(), interfaceKit.getDeviceVersion())
    print "|------------|----------------------------------|--------------|------------|"
    return 0

#Event Handler Callback Functions
def inferfaceKitAttached(e):
    attached = e.device
    print "InterfaceKit %i Attached!" % (attached.getSerialNum())
    return 0
Example #42
0
# jantman
# Time-stamp: "2008-06-09 16:12:34 tuxostat"

#Basic imports
from threading import *
from ctypes import *
import sys
#Phidget specific imports
from Phidgets.PhidgetException import *
from Phidgets.Events.Events import *
from Phidgets.Devices.InterfaceKit import *
import time

#Create an interfacekit object
interfaceKit = InterfaceKit()

#Information Display Function
def displayDeviceInfo():
    print "|------------|----------------------------------|--------------|------------|"
    print "|- Attached -|-              Type              -|- Serial No. -|-  Version -|"
    print "|------------|----------------------------------|--------------|------------|"
    print "|- %8s -|- %30s -|- %10d -|- %8d -|" % (interfaceKit.isAttached(), interfaceKit.getDeviceType(), interfaceKit.getSerialNum(), interfaceKit.getDeviceVersion())
    print "|------------|----------------------------------|--------------|------------|"
    return 0


print "Opening phidget object...."

try:
    interfaceKit.openPhidget()
Example #43
0
# jantman
# Time-stamp: "2008-06-09 16:12:34 tuxostat"

#Basic imports
from threading import *
from ctypes import *
import sys
#Phidget specific imports
from Phidgets.PhidgetException import *
from Phidgets.Events.Events import *
from Phidgets.Devices.InterfaceKit import *
import time

#Create an interfacekit object
interfaceKit = InterfaceKit()


#Information Display Function
def displayDeviceInfo():
    print "|------------|----------------------------------|--------------|------------|"
    print "|- Attached -|-              Type              -|- Serial No. -|-  Version -|"
    print "|------------|----------------------------------|--------------|------------|"
    print "|- %8s -|- %30s -|- %10d -|- %8d -|" % (
        interfaceKit.isAttached(), interfaceKit.getDeviceType(),
        interfaceKit.getSerialNum(), interfaceKit.getDeviceVersion())
    print "|------------|----------------------------------|--------------|------------|"
    return 0


print "Opening phidget object...."