Beispiel #1
0
 def on_add(self, _event):
     device = Device()
     device.isDevice = False
     self.devices.append(device)
     self.gridDev.AppendRows(1)
     self.set_dev_grid()
     self.SetSizerAndFit(self.devbox)
Beispiel #2
0
    def test_Register(self):
        led = Device("name", self.message_handler)
        self.assertEqual(led.connect(), True)
        time.sleep(0.1)
        connected_nodes = self.gw.get_connected_nodes()
        self.assertEqual(len(connected_nodes), 1)
        node = connected_nodes[led.node_id]
        self.assertEqual(node.name, led.name)
        self.assertEqual(node.registered, True)

        last_seen = node.last_seen

        led._send_status()
        time.sleep(0.1)

        connected_nodes = self.gw.get_connected_nodes()
        self.assertEqual(len(connected_nodes), 1)
        node = connected_nodes[led.node_id]
        self.assertEqual(node.name, led.name)
        self.assertEqual(node.registered, True)
        self.assertNotEqual(node.last_seen, last_seen)

        # calling connect again should change nothing
        self.assertEqual(led.connect(), True)
        connected_nodes = self.gw.get_connected_nodes()
        self.assertEqual(len(connected_nodes), 1)
Beispiel #3
0
def test_device_info():
    """Tests 5.1.2 Retrieving device information
    """
    dev = Device()
    dev_info = dev.getInfo()

    assert dev_info == ["Roam NXT", 12345, 2.11, 1.2, 423434343,
                        100], "Incorrect device information"
Beispiel #4
0
 def test_sendACKForUnknownMessage(self):
     dev = Device("name", self.message_handler)
     self.assertEqual(dev.connect(), True)
     header = MessageHeader(node_id = dev.node_id, group_id = dev.group_id, wants_ack = False)
     m = ACKMessage(header)
     self.message_handler.write_message_from_device(m)
     time.sleep(0.1)
     self.assertEqual(len(self.gw.get_connected_nodes()), 1)
Beispiel #5
0
    def __init__(self,*args,**kwargs):
        """
        EyeTracker class. This class is to be extended by each eye tracker specific implemetation
        of the pyEyeTrackerInterface.

        Please review the documentation page for the specific eye tracker model that you are using the
        pyEyeTrackerInterface with to get the appropriate module path for that eye tracker; for example,
        if you are using an interface that supports eye trackers developed by EyeTrackingCompanyET, you
        may initialize the eye tracker object for that manufacturer something similar too :

           eyeTracker = hub.eyetrackers.EyeTrackingCompanyET.EyeTracker(**kwargs)

        where hub is the instance of the ioHubClient class that has been created for your experiment.

        **kwargs are an optional set of named parameters.

        **If an instance of EyeTracker has already been created, trying to create a second will raise an exception. Either destroy the first instance and then create the new instance, or use the class method EyeTracker.getInstance() to access the existing instance of the eye tracker object.**
        """
        if EyeTracker._INSTANCE is not None:
            raise ioHub.devices.ioDeviceError(self.__class__.__name__,"EyeTracker object has already been created; only one instance can exist. Delete existing instance before recreating EyeTracker object.")
        
        # >>>> eye tracker config
        EyeTracker.eyeTrackerConfig=kwargs['dconfig']
        #print " #### EyeTracker Configuration #### "
        #print self.eyeTrackerConfig
        #print ''
        # <<<<
		
		## Load quicklink dll
        EyeTracker._DLL = windll.LoadLibrary("C:\\Program Files\\EyeTechDS\\QuickLink2_2.5.1.0\\bin\\QuickLink2.dll")
        ioHub.print2err("DLL: ",EyeTracker._DLL)
        
        # create Device level class setting dictionary and pass it Device constructor
        deviceSettings= dict(instance_code=self.eyeTrackerConfig['instance_code'],
            category_id=ioHub.devices.EventConstants.DEVICE_CATERGORIES['EYE_TRACKER'],
            type_id=ioHub.devices.EventConstants.DEVICE_TYPES['EYE_TRACKER_DEVICE'], device_class=self.eyeTrackerConfig['device_class'],
            user_label=self.eyeTrackerConfig['name'], os_device_code='OS_DEV_CODE_NOT_SET',
            max_event_buffer_length=self.eyeTrackerConfig['event_buffer_length'])
        Device.__init__(self,**deviceSettings)
        
        # set this instance as 'THE' instance of the eye tracker.
        EyeTracker._INSTANCE=self
        EyeTracker.DEVICE_START_TIME=0.0
        
        # >>>> eye tracker setting to config (if possible)
        runtimeSettings=self.eyeTrackerConfig['runtime_settings']
        
        # >>>> Display / Calibration related information to use for config if possible
        EyeTracker.displaySettings = self.eyeTrackerConfig['display_settings']


        ioHub.print2err("Start createFrameTest")
        testFrame=createFrameTest()
        ioHub.print2err(testFrame.PixelData[0:testFrame.Width*testFrame.Height])
        ioHub.print2err("End createFrameTest")

        ioHub.print2err("Done EyeTech Init")
Beispiel #6
0
def test_set_time():
    """Tests 5.1.4 Date synchronization
    """
    dev = Device()

    set_time = 342342343
    dev.setTime(set_time)
    get_time = dev.getTime()

    assert get_time == set_time, "Time was not set correctly"
Beispiel #7
0
    def __init__(self, *args, **kwargs):
        deviceConfig = kwargs['dconfig']
        deviceSettings = {
            'instance_code':
            deviceConfig['instance_code'],
            'category_id':
            ioHub.devices.EventConstants.DEVICE_CATERGORIES[
                Joystick.categoryTypeString],
            'type_id':
            ioHub.devices.EventConstants.DEVICE_TYPES[
                Joystick.deviceTypeString],
            'device_class':
            deviceConfig['device_class'],
            'user_label':
            deviceConfig['name'],
            'os_device_code':
            'OS_DEV_CODE_NOT_SET',
            'max_event_buffer_length':
            deviceConfig['event_buffer_length']
        }
        Device.__init__(self, **deviceSettings)
        #ioHub.print2stderr("kwargs: "+str(kwargs))

        self._lastPollTime = None

        if Joystick._joystickGLFWInitialized is False:
            Joystick._joystickGLFWInitialized = True
            glfw.Init()

            for i in xrange(glfw.JOYSTICK_LAST):
                if glfw.GetJoystickParam(i, glfw.PRESENT):
                    Joystick._detectedJoysticks.append(i)

        if 'joystick_index' in kwargs['dconfig']:
            self._jid = kwargs['dconfig']['joystick_index']
            if not glfw.GetJoystickParam(self._jid, glfw.PRESENT):
                raise ioHub.devices.ioDeviceError(
                    self,
                    "Requested joystick ID is not present on the computer: %d"
                    % (deviceSettings['joystick_index']))
            jbuttons = glfw.GetJoystickButtons(self._jid)
            jpositions = glfw.GetJoystickPos(self._jid)
            self._joystickButtonStates = N.copy((jbuttons, jbuttons))
            self._joystickPositionStates = N.copy((jpositions, jpositions))

            #ioHub.print2stderr('Buttons:')
            #ioHub.print2stderr(str(self._jid)+' : '+str(self._joystickButtonStates.shape)+' : '+str(self._joystickButtonStates[0])+' : '+str(len(jbuttons)))

            #ioHub.print2stderr('Positions:')
            #ioHub.print2stderr(str(self._jid)+' : '+str(self._joystickPositionStates.shape)+' : '+str(self._joystickPositionStates[1])+' : '+str(len(jpositions)))
        else:
            raise ioHub.devices.ioDeviceError(
                self,
                "joystick_index must be supplied as an entry in the configuration for this device."
            )
Beispiel #8
0
def test_connection_type_wired():
    """Tests 4.2.1 Device connection methods
       Tests 5.1.1 Connection type 
    """
    dev = Device()

    set_conn_type = "Wired"
    dev.setConnection(set_conn_type)
    get_conn_type = dev.getConnection()

    assert get_conn_type == set_conn_type, "Wired device connection was not set"
Beispiel #9
0
    def test_moreThan30Nodes(self):
        for i in range(0, 30):
            dev = Device('%s' % i, self.message_handler)
            if i == 29:
                # too many nodes registered
                self.assertEqual(dev.connect(), False)
            else:
                self.assertEqual(dev.connect(), True)

        time.sleep(0.1)
        connected_nodes = self.gw.get_connected_nodes()
        self.assertEqual(len(connected_nodes), 29)
Beispiel #10
0
  def registerDevice(self, message, data, addr):
    for x in self.devices: 
      if (x.id == message[1] and x.mac == message[3]):
        if (x.ip != addr[0] and x.passphrase == message[2]):
          x.ip = addr[0]
          x.addMessage(data)
          return "02"
        else:
          x.addMessage(data)
          return "01"
      elif (x.ip == addr[0] and (not (x.id == message[1] and x.mac == message[3]))):
        return "12"
      elif (x.mac == message[3] and x.id != message[1]):
        return "13"

    temp = Device(message[1], message[2], message[3], addr[0])
    temp.addMessage(data)
    self.devices.append(temp)
    return "00"
Beispiel #11
0
def assembleServer(host, port, broadcast_port):
    #init player
    player = LocalPlayer()
    player.setHeadless()

    #init the request server
    server = RequestServer((host,port), player=player)

    #init device
    thisDevice = Device(type="local", visibleName="rpi-yamserver", url="{0}:{1}".format(host,port))
    thisDevice.setCapabilities([devices.Capability.PlayMusic])

    #init presence broadcaster
    presenceBroadcaster = DevicePresenceBroadcaster(thisDevice, broadcast_port)

    #init state broadcaster
    stateBroadcaster = DeviceStateMulticaster(player)

    #assemble and return the server
    return ServerApp(server, player, presenceBroadcaster, stateBroadcaster)
Beispiel #12
0
    def __init__(self,*args,**kwargs):
        deviceConfig=kwargs['dconfig']
        deviceSettings={'instance_code':deviceConfig['instance_code'],
                        'category_id':ioHub.devices.EventConstants.DEVICE_CATERGORIES[Joystick.categoryTypeString],
                        'type_id':ioHub.devices.EventConstants.DEVICE_TYPES[Joystick.deviceTypeString],
                        'device_class':deviceConfig['device_class'],
                        'user_label':deviceConfig['name'],
                        'os_device_code':'OS_DEV_CODE_NOT_SET',
                        'max_event_buffer_length':deviceConfig['event_buffer_length']
                        }
        Device.__init__(self,**deviceSettings)
        #ioHub.print2stderr("kwargs: "+str(kwargs))

        self._lastPollTime=None

        if Joystick._joystickGLFWInitialized is False:
            Joystick._joystickGLFWInitialized=True
            glfw.Init()

            for i in xrange(glfw.JOYSTICK_LAST):
                if glfw.GetJoystickParam(i,glfw.PRESENT):
                    Joystick._detectedJoysticks.append(i)

        if 'joystick_index' in kwargs['dconfig']:
            self._jid=kwargs['dconfig']['joystick_index']
            if not glfw.GetJoystickParam(self._jid,glfw.PRESENT):
                raise ioHub.devices.ioDeviceError(self,"Requested joystick ID is not present on the computer: %d"%(deviceSettings['joystick_index']))
            jbuttons=glfw.GetJoystickButtons(self._jid)
            jpositions= glfw.GetJoystickPos(self._jid)
            self._joystickButtonStates=N.copy((jbuttons,jbuttons))
            self._joystickPositionStates=N.copy((jpositions,jpositions))

            #ioHub.print2stderr('Buttons:')
            #ioHub.print2stderr(str(self._jid)+' : '+str(self._joystickButtonStates.shape)+' : '+str(self._joystickButtonStates[0])+' : '+str(len(jbuttons)))

            #ioHub.print2stderr('Positions:')
            #ioHub.print2stderr(str(self._jid)+' : '+str(self._joystickPositionStates.shape)+' : '+str(self._joystickPositionStates[1])+' : '+str(len(jpositions)))
        else:
            raise ioHub.devices.ioDeviceError(self,"joystick_index must be supplied as an entry in the configuration for this device.")
Beispiel #13
0
  def registerDevice(self, message, data):
    for x in self.devices:
      if (x.id == message[1] and x.mac == message[3]):
        if (x.ip != message[4] and x.passphrase == message[2]):
          x.ip = message[4]
          x.addMessage(data)
          return "02"
        else:
          x.addMessage(data)
          return "01"
      elif (x.ip == message[5] and (not (x.id == message[1] and x.mac == message[3]))):
        return "12"
      elif (x.mac == message[3] and x.id != message[1]):
        return "13"
      else:
        return "-1"

    temp = Device(message[1], message[2], message[3], message[4], message[5])
    temp.addMessage(data)
    self.devices.append(temp)
    # self.devices[0].debug()
    return "00"
async def handler(websocket, path):

    async for message in websocket:
        data = json.loads(message)
        id = data['id']
        # Dynamic service registration
        if not state.is_registered(id):
            if 'registration' in data:
                ty = data['registration']
                device = Device(id, ty)
                state.register(id, device)
            else:
                print("Message sent before registering, skipping")
                continue

        print(
            f"\nReceived message from sensor {state.device(id).ty} with id number {id[:6]} ...."
        )

        state.update_connection(id, websocket)
        if 'data' in data:
            new_data = data['data']
            state.update_data(id, new_data)

        print("\nEvaluating rules")

        rules_firing = state.rules_to_apply()
        for rule in rules_firing:

            print(
                "\n Logical rule activated under the hood for the device with the following id ",
                rule.statement.to_str())

            for activator in rule.activators:
                id_to_ping = activator
                if state.is_connected(id_to_ping):
                    conn = state.get_connection(id_to_ping)
                    await conn.send(
                        json.dumps({
                            'id': id_to_ping,
                            'msg': 'instruction'
                        }))
Beispiel #15
0
    def run(self):
        '''Wait'''
        self.base.framebox.add(self.load_wait(self.base, "Loading, please wait ..."))

	if not os.path.isfile(HW_XML) or not os.path.getsize(HW_XML) or self.flag == "DET":
            '''set timeout is 600s, the default is 25s'''
            iface = init_dbus()
            data = iface.scan_device(timeout=600)
            with open(HW_XML, "w") as fp:
                fp.write(data)
            iface.quit_loop()
            
	device = Device(HW_XML)
	self.dev_dict = device.dev_type
        self.base.pcid = device.pcid
        
	self.base.device_page = DevicePage(self.dev_dict, self.base)
        self.emit('load-wait')
	self.base.select_page(DEV_ID)
        self.base.lock = False
Beispiel #16
0
 def genDevices(self):
     res = {}
     for device in self.devices:
         res[device['id']] = Device(device['id'], device['type'])
     return res
Beispiel #17
0
from mqtt_handler import MQTTHandler
from watchdog import TimerWatchdog
from devices import Device
from relay import Relay

devicelist = {
    b'\xd5\x9f\xa1\x00': b'zistvorne',  # Shelly1
    b'\xfd\x76\xf8\x00': b'schlazilicht',  # ESP01-relay
}

####
# Main
####

mydevice = Device(devicelist)

wdt = TimerWatchdog(interval=180)
wdt.feed()

# time to connect WLAN, since marginal reception
time.sleep(5)

sc = MQTTHandler(b'pentling/' + mydevice.name, '192.168.0.13')

if mydevice.name == b'zistvorne':
    relay = Relay(4)
    sc.register_action('pump_enable', relay.set_state)
    sc.register_publisher('pump', relay.get_state)

elif mydevice.name == b'schlazilicht':
Beispiel #18
0
class DeviceTest(unittest.TestCase):
    if not QtGui.qApp:
        _app = QtGui.QApplication([])
    NAME = "TestDevice"
    ADDRESS = "127.0.0.1"
    PORT = 2 ** 14
    _port = PORT
    _sock = None
    _dev = None

    def setUp(self):
        QtGui.qApp.processEvents()
        self.__class__._port += 1
        self._daemon = DeviceDaemon((self.ADDRESS, self._port))
        self._dev = Device(self.NAME, self.ADDRESS, self._port)
        QtGui.qApp.processEvents()

    def tearDown(self):
        QtGui.qApp.processEvents()
        self._dev.disconnectDevice()
        self._daemon.close()
        QtGui.qApp.processEvents()

    def testDeviceList(self):
        """
        Tests creation of a list of 3 devices. There is an issue about it.
        """

        def createDevice(name):
            return Device(name, self.ADDRESS, self.PORT)

        N_DEVS = 3
        devs = [createDevice(self.NAME + str(i)) for i in xrange(N_DEVS)]
        self.failUnlessEqual(len(devs), N_DEVS)

    def testConnecting(self):
        """
        Tries to create three devices.
        """
        dw = DeviceWatcher(self._dev)
        self._dev.connectDevice()
        self.failUnless(dw.connected)

    def testDisconnecting(self):
        dw = DeviceWatcher(self._dev)
        self._dev.connectDevice()
        self.failUnless(dw.connected)
        self._dev.disconnectDevice()
        self.failIf(dw.connected)

    def testSendingReqest(self):
        dw = DeviceWatcher(self._dev)
        self._dev.connectDevice()
        self.failUnless(dw.connected)
        self._dev.requestDevice("requestSystemExec", "ls -l")
        self.failUnless(dw.sent)

    def testReceivingResponse(self):
        dw = DeviceWatcher(self._dev)
        self._dev.connectDevice()
        self.failUnless(dw.connected)
        self._dev.client.messages.put(QueueItem(1))
        QtGui.qApp.processEvents()
        self.failUnless(dw.received)
Beispiel #19
0
 def setUp(self):
     QtGui.qApp.processEvents()
     self.__class__._port += 1
     self._daemon = DeviceDaemon((self.ADDRESS, self._port))
     self._dev = Device(self.NAME, self.ADDRESS, self._port)
     QtGui.qApp.processEvents()
Beispiel #20
0
class Main():
    SHUTOFF_TIME = 30  # seconds
    PIR_LOCK_TIME = 120
    LONG_PRESS_TIME = 2
    pirPin = 17  # Pin 11 on the
    buttonPin = 3
    lastUserRequestedDisplayOff = 0
    lastMovementDetected = 0
    display = Display()
    device = Device()
    pirLocked = False
    turnOffTimer = None
    pirUnlockTimer = None

    def shortPress(self):
        print("Button was pressed")
        self.display.toggle()
        if self.display.isOn:
            self.pirLocked = False
            self.restartTurnOffTimer()
        else:
            #display shut down by user
            self.pirLocked = True
            self.restartPirLockTimer()

    def restartPirLockTimer(self):
        if self.pirUnlockTimer:
            self.pirUnlockTimer.cancel()
        self.pirUnlockTimer = Timer(self.PIR_LOCK_TIME,
                                    lambda: self.setPirLocked(False))
        self.pirUnlockTimer.start()

    def restartTurnOffTimer(self):
        if self.turnOffTimer:
            self.turnOffTimer.cancel()
        self.turnOffTimer = Timer(self.SHUTOFF_TIME, self.display.turn_off)
        self.turnOffTimer.start()

    def setPirLocked(self, value):
        self.pirLocked = value

    def onMovementDetected(self):
        if not self.pirLocked:
            self.display.turn_on()
            self.restartTurnOffTimer()

    def main(self):
        GPIO.setmode(GPIO.BCM)

        buttonListener = GpioPinListener(self.buttonPin,
                                         onLongPress=self.device.shutdown,
                                         onShortPress=self.shortPress,
                                         onFallingEdge=None,
                                         onRisingEdge=None,
                                         shutdown=self.LONG_PRESS_TIME,
                                         debounce=0.01,
                                         pull_up_down=GPIO.PUD_UP,
                                         use_internal_pull=True)

        pirListener = GpioPinListener(self.pirPin,
                                      onLongPress=None,
                                      onShortPress=None,
                                      onFallingEdge=None,
                                      onButtonDown=self.onMovementDetected,
                                      shutdown=self.SHUTOFF_TIME,
                                      debounce=0.01,
                                      pull_up_down=GPIO.PUD_DOWN,
                                      use_internal_pull=False)
        self.display.turn_off()
        while True:
            buttonListener.update()
            pirListener.update()
            time.sleep(.1)
Beispiel #21
0
 def load(self):
     self.cfg = wx.Config('rtlsdr-scanner')
     self.display = self.cfg.ReadInt('display', self.display)
     self.saveWarn = self.cfg.ReadBool('saveWarn', self.saveWarn)
     self.fileHistory.Load(self.cfg)
     self.dirScans = self.cfg.Read('dirScans', self.dirScans)
     self.dirExport = self.cfg.Read('dirExport', self.dirExport)
     self.annotate = self.cfg.ReadBool('annotate', self.annotate)
     self.retainScans = self.cfg.ReadBool('retainScans', self.retainScans)
     self.fadeScans = self.cfg.ReadBool('fadeScans', self.fadeScans)
     self.lineWidth = self.cfg.ReadFloat('lineWidth', self.lineWidth)
     self.retainMax = self.cfg.ReadInt('retainMax', self.retainMax)
     self.colourMap = self.cfg.Read('colourMap', self.colourMap)
     self.background = self.cfg.Read('background', self.background)
     self.wireframe = self.cfg.ReadBool('wireframe', self.wireframe)
     self.average = self.cfg.ReadBool('average', self.average)
     self.pointsLimit = self.cfg.ReadBool('pointsLimit', self.pointsLimit)
     self.pointsMax = self.cfg.ReadInt('pointsMax', self.pointsMax)
     self.grid = self.cfg.ReadBool('grid', self.grid)
     self.start = self.cfg.ReadInt('start', self.start)
     self.stop = self.cfg.ReadInt('stop', self.stop)
     self.mode = self.cfg.ReadInt('mode', self.mode)
     self.dwell = self.cfg.ReadFloat('dwell', self.dwell)
     self.nfft = self.cfg.ReadInt('nfft', self.nfft)
     self.overlap = self.cfg.ReadFloat('overlap', self.overlap)
     self.winFunc = self.cfg.Read('winFunc', self.winFunc)
     self.liveUpdate = self.cfg.ReadBool('liveUpdate', self.liveUpdate)
     self.calFreq = self.cfg.ReadFloat('calFreq', self.calFreq)
     self.autoF = self.cfg.ReadBool('autoF', self.autoF)
     self.autoL = self.cfg.ReadBool('autoL', self.autoL)
     self.autoT = self.cfg.ReadBool('autoT', self.autoT)
     self.showMeasure = self.cfg.ReadBool('showMeasure', self.showMeasure)
     self.alert = self.cfg.ReadBool('alert', self.alert)
     self.alertLevel = self.cfg.ReadFloat('alertLevel', self.alertLevel)
     self.index = self.cfg.ReadInt('index', self.index)
     self.cfg.SetPath("/Devices")
     group = self.cfg.GetFirstGroup()
     while group[0]:
         self.cfg.SetPath("/Devices/" + group[1])
         device = Device()
         device.name = group[1]
         device.serial = self.cfg.Read('serial', '')
         device.isDevice = self.cfg.ReadBool('isDevice', True)
         device.server = self.cfg.Read('server', 'localhost')
         device.port = self.cfg.ReadInt('port', 1234)
         device.gain = self.cfg.ReadFloat('gain', 0)
         device.calibration = self.cfg.ReadFloat('calibration', 0)
         device.lo = self.cfg.ReadFloat('lo', 0)
         device.offset = self.cfg.ReadFloat('offset', 250e3)
         device.tuner = self.cfg.ReadInt('tuner', 0)
         self.devices.append(device)
         self.cfg.SetPath("/Devices")
         group = self.cfg.GetNextGroup(group[2])
Beispiel #22
0
 def __init__(self, env, parent, radius=10):
     self.radius = radius
     kp=np.array([[-radius, 0], [radius, 0]])
     Device.__init__(self, env, parent, kp=kp, color=(0, 1, 0, 0.5), filled=True)
Beispiel #23
0
class DeviceTest(unittest.TestCase):
    if not QtGui.qApp:
        _app = QtGui.QApplication([])
    NAME = "TestDevice"
    ADDRESS = "127.0.0.1"
    PORT = 2**14
    _port = PORT
    _sock = None
    _dev = None

    def setUp(self):
        QtGui.qApp.processEvents()
        self.__class__._port += 1
        self._daemon = DeviceDaemon((self.ADDRESS, self._port))
        self._dev = Device(self.NAME, self.ADDRESS, self._port)
        QtGui.qApp.processEvents()

    def tearDown(self):
        QtGui.qApp.processEvents()
        self._dev.disconnectDevice()
        self._daemon.close()
        QtGui.qApp.processEvents()

    def testDeviceList(self):
        '''
        Tests creation of a list of 3 devices. There is an issue about it.
        '''
        def createDevice(name):
            return Device(name, self.ADDRESS, self.PORT)

        N_DEVS = 3
        devs = [createDevice(self.NAME + str(i)) for i in xrange(N_DEVS)]
        self.failUnlessEqual(len(devs), N_DEVS)

    def testConnecting(self):
        '''
        Tries to create three devices.
        '''
        dw = DeviceWatcher(self._dev)
        self._dev.connectDevice()
        self.failUnless(dw.connected)

    def testDisconnecting(self):
        dw = DeviceWatcher(self._dev)
        self._dev.connectDevice()
        self.failUnless(dw.connected)
        self._dev.disconnectDevice()
        self.failIf(dw.connected)

    def testSendingReqest(self):
        dw = DeviceWatcher(self._dev)
        self._dev.connectDevice()
        self.failUnless(dw.connected)
        self._dev.requestDevice("requestSystemExec", "ls -l")
        self.failUnless(dw.sent)

    def testReceivingResponse(self):
        dw = DeviceWatcher(self._dev)
        self._dev.connectDevice()
        self.failUnless(dw.connected)
        self._dev.client.messages.put(QueueItem(1))
        QtGui.qApp.processEvents()
        self.failUnless(dw.received)
Beispiel #24
0
    def load(self):
        servers = 0
        self.cfg = wx.Config('rtlsdr-scanner')
        self.saveWarn = self.cfg.ReadBool('saveWarn', self.saveWarn)
        self.fileHistory.Load(self.cfg)
        self.annotate = self.cfg.ReadBool('annotate', self.annotate)
        self.retainScans = self.cfg.ReadBool('retainScans', self.retainScans)
        self.fadeScans = self.cfg.ReadBool('fadeScans', self.fadeScans)
        self.maxScans = self.cfg.ReadInt('maxScans', self.maxScans)
        self.start = self.cfg.ReadInt('start', self.start)
        self.stop = self.cfg.ReadInt('stop', self.stop)
        self.mode = self.cfg.ReadInt('mode', self.mode)
        self.dwell = self.cfg.ReadFloat('dwell', self.dwell)
        self.nfft = self.cfg.ReadInt('nfft', self.nfft)
        self.liveUpdate = self.cfg.ReadBool('liveUpdate', self.liveUpdate)
        self.calFreq = self.cfg.ReadFloat('calFreq', self.calFreq)
        self.autoScale = self.cfg.ReadBool('autoScale', self.autoScale)
        self.yMax = self.cfg.ReadInt('yMax', self.yMax)
        self.yMin = self.cfg.ReadInt('yMin', self.yMin)
        self.index = self.cfg.ReadInt('index', self.index)
        self.cfg.SetPath("/Devices")
        group = self.cfg.GetFirstGroup()
        while group[0]:
            self.cfg.SetPath("/Devices/" + group[1])
            device = Device()
            device.name = group[1]
            device.serial = self.cfg.Read('serial', '')
            device.isDevice = self.cfg.ReadBool('isDevice', True)
            if not device.isDevice:
                servers += 1
            device.server = self.cfg.Read('server', 'localhost')
            device.port = self.cfg.ReadInt('port', 1234)
            device.gain = self.cfg.ReadFloat('gain', 0)
            device.calibration = self.cfg.ReadFloat('calibration', 0)
            device.lo = self.cfg.ReadFloat('lo', 0)
            device.offset = self.cfg.ReadFloat('offset', 250e3)
            self.devices.append(device)
            self.cfg.SetPath("/Devices")
            group = self.cfg.GetNextGroup(group[2])

        if servers == 0:
            device = Device()
            device.name = 'Server'
            device.isDevice = False
            device.server = 'localhost'
            device.port = 1234
            self.devices.append(device)
Beispiel #25
0
 def __init__(self,*args,**kwargs):   
     Device.__init__(self,*args,**kwargs['dconfig'])
     self._position=0,0
     self._lastPosition=0,0
     self._display_index=None
Beispiel #26
0
    def __init__(self, *args, **kwargs):
        """
        EyeTracker class. This class is to be extended by each eye tracker specific implemetation
        of the pyEyeTrackerInterface.

        Please review the documentation page for the specific eye tracker model that you are using the
        pyEyeTrackerInterface with to get the appropriate module path for that eye tracker; for example,
        if you are using an interface that supports eye trackers developed by EyeTrackingCompanyET, you
        may initialize the eye tracker object for that manufacturer something similar too :

           eyeTracker = hub.eyetrackers.EyeTrackingCompanyET.EyeTracker(**kwargs)

        where hub is the instance of the ioHubClient class that has been created for your experiment.

        **kwargs are an optional set of named parameters.

        **If an instance of EyeTracker has already been created, trying to create a second will raise an exception. Either destroy the first instance and then create the new instance, or use the class method EyeTracker.getInstance() to access the existing instance of the eye tracker object.**
        """
        if EyeTracker._INSTANCE is not None:
            raise ioHub.devices.ioDeviceError(
                self.__class__.__name__,
                "EyeTracker object has already been created; only one instance can exist. Delete existing instance before recreating EyeTracker object."
            )

        # >>>> eye tracker config
        EyeTracker.eyeTrackerConfig = kwargs['dconfig']
        #print " #### EyeTracker Configuration #### "
        #print self.eyeTrackerConfig
        #print ''
        # <<<<

        ## Load quicklink dll
        EyeTracker._DLL = windll.LoadLibrary(
            "C:\\Program Files\\EyeTechDS\\QuickLink2_2.5.1.0\\bin\\QuickLink2.dll"
        )
        ioHub.print2err("DLL: ", EyeTracker._DLL)

        # create Device level class setting dictionary and pass it Device constructor
        deviceSettings = dict(
            instance_code=self.eyeTrackerConfig['instance_code'],
            category_id=ioHub.devices.EventConstants.
            DEVICE_CATERGORIES['EYE_TRACKER'],
            type_id=ioHub.devices.EventConstants.
            DEVICE_TYPES['EYE_TRACKER_DEVICE'],
            device_class=self.eyeTrackerConfig['device_class'],
            user_label=self.eyeTrackerConfig['name'],
            os_device_code='OS_DEV_CODE_NOT_SET',
            max_event_buffer_length=self.
            eyeTrackerConfig['event_buffer_length'])
        Device.__init__(self, **deviceSettings)

        # set this instance as 'THE' instance of the eye tracker.
        EyeTracker._INSTANCE = self
        EyeTracker.DEVICE_START_TIME = 0.0

        # >>>> eye tracker setting to config (if possible)
        runtimeSettings = self.eyeTrackerConfig['runtime_settings']

        # >>>> Display / Calibration related information to use for config if possible
        EyeTracker.displaySettings = self.eyeTrackerConfig['display_settings']

        ioHub.print2err("Start createFrameTest")
        testFrame = createFrameTest()
        ioHub.print2err(testFrame.PixelData[0:testFrame.Width *
                                            testFrame.Height])
        ioHub.print2err("End createFrameTest")

        ioHub.print2err("Done EyeTech Init")
    def __init__(self, *args, **kwargs):
        """
        EyeTracker class. This class is to be extended by each eye tracker specific implemetation
        of the pyEyeTrackerInterface.

        Please review the documentation page for the specific eye tracker model that you are using the
        pyEyeTrackerInterface with to get the appropriate module path for that eye tracker; for example,
        if you are using an interface that supports eye trackers developed by EyeTrackingCompanyET, you
        may initialize the eye tracker object for that manufacturer something similar too :

           eyeTracker = hub.eyetrackers.EyeTrackingCompanyET.EyeTracker(**kwargs)

        where hub is the instance of the ioHubClient class that has been created for your experiment.

        **kwargs are an optional set of named parameters.

        **If an instance of EyeTracker has already been created, trying to create a second will raise an exception. Either destroy the first instance and then create the new instance, or use the class method EyeTracker.getInstance() to access the existing instance of the eye tracker object.**
        """
        if EyeTracker._INSTANCE is not None:
            raise ioHub.devices.ioDeviceError(
                self.__class__.__name__,
                "EyeTracker object has already been created; only one instance can exist. Delete existing instance before recreating EyeTracker object.",
            )

        # >>>> eye tracker config
        EyeTracker.eyeTrackerConfig = kwargs["dconfig"]
        # print " #### EyeTracker Configuration #### "
        # print self.eyeTrackerConfig
        # print ''
        # <<<<

        # create Device level class setting dictionary and pass it Device constructor
        deviceSettings = dict(
            instance_code=self.eyeTrackerConfig["instance_code"],
            category_id=ioHub.devices.EventConstants.DEVICE_CATERGORIES["EYE_TRACKER"],
            type_id=ioHub.devices.EventConstants.DEVICE_TYPES["EYE_TRACKER_DEVICE"],
            device_class=self.eyeTrackerConfig["device_class"],
            user_label=self.eyeTrackerConfig["name"],
            os_device_code="OS_DEV_CODE_NOT_SET",
            max_event_buffer_length=self.eyeTrackerConfig["event_buffer_length"],
        )
        Device.__init__(self, **deviceSettings)

        # set this instance as 'THE' instance of the eye tracker.
        EyeTracker._INSTANCE = self

        EyeTracker.DEVICE_START_TIME = 0.0

        # >>>> eye tracker setting to config (if possible)
        #
        # Current settings, example from possible values.
        #
        # 'sampling_rate': 60.0,
        # 'vog_settings': {
        #                  'pupil_illumination': 'dark',
        #                  'pupil_center_algorithm': 'centroid',
        #                  'tracking_mode': 'pupil-cr'
        #                 }
        # 'default_calibration': '9P'
        # 'track_eyes': 'BINOC'
        # 'runtime_filtering': {
        #                       'ANY': 0
        #                      }
        runtimeSettings = self.eyeTrackerConfig["runtime_settings"]

        # print ''
        # print " #### EyeTracker Runtime Settings #### "
        # print runtimeSettings
        # print ''
        # <<<<

        # >>>> Display / Calibration related information to use for config if possible
        #
        # Current settings, example from possible values.
        #
        EyeTracker.displaySettings = self.eyeTrackerConfig["display_settings"]
Beispiel #28
0
    def __init__(self, pool, args):
        start = args.start
        end = args.end
        gain = args.gain
        dwell = args.dwell
        nfft = args.fft
        lo = args.lo
        index = args.index
        remote = args.remote
        directory, filename = os.path.split(args.file)
        _null, ext = os.path.splitext(args.file)

        self.lock = threading.Lock()

        self.stepsTotal = 0
        self.steps = 0

        self.spectrum = {}
        self.settings = Settings(load=False)

        self.queue = Queue.Queue()

        error = None

        if end <= start:
            error = "Start should be lower than end"
        elif dwell <= 0:
            error = "Dwell should be positive"
        elif nfft <= 0:
            error = "FFT bins should be positive"
        elif ext != ".rfs" and File.get_export_type(ext) == -1:
            error = "File extension should be .rfs, "
            error += File.get_export_pretty()
        else:
            device = Device()
            if remote is None:
                self.settings.devices = get_devices()
                count = len(self.settings.devices)
                if index > count - 1:
                    error = "Device not found ({0} devices in total):\n".format(count)
                    for device in self.settings.devices:
                        error += "\t{0}: {1}\n".format(device.index,
                                                       device.name)
            else:
                device.isDevice = False
                url = urlparse('//' + remote)
                if url.hostname is not None:
                        device.server = url.hostname
                else:
                    error = "Invalid hostname"
                if url.port is not None:
                    device.port = url.port
                else:
                    device.port = 1234
                self.settings.devices.append(device)
                index = len(self.settings.devices) - 1

        if error is not None:
            print "Error: {0}".format(error)
            exit(1)

        if end - 1 < start:
            end = start + 1
        if remote is None:
            gain = nearest(gain, self.settings.devices[index].gains)

        self.settings.start = start
        self.settings.stop = end
        self.settings.dwell = calc_real_dwell(dwell)
        self.settings.nfft = nfft
        self.settings.devices[index].gain = gain
        self.settings.devices[index].lo = lo

        print "{0} - {1}MHz".format(start, end)
        print "{0}dB Gain".format(gain)
        print "{0}s Dwell".format(self.settings.dwell)
        print "{0} FFT points".format(nfft)
        print "{0}MHz LO".format(lo)
        if remote is not None:
            print remote
        else:
            print self.settings.devices[index].name

        self.scan(self.settings, index, pool)

        if ext == ".rfs":
            scanInfo = ScanInfo()
            scanInfo.setFromSettings(self.settings)
            save_plot(directory, filename, scanInfo, self.spectrum)
        else:
            exportType = File.get_export_type(ext)
            export_plot(directory, filename, exportType, self.spectrum)

        print "Done"
Beispiel #29
0
from simulator import Simulator, Map, Agent
from devices import Device
import numpy as np
import simulator_config

env = Simulator(simulator_config)
map = Map()
map.get_map_from_geom2d(env,
                        kp=np.array([[-100, 100], [-100, -100], [100, -100],
                                     [100, 100]]))

robot = Agent(env,
              kp=np.array([[-2, 0], [2, 0]]),
              color=(1, 0, 0, 0.5),
              v_max=5)
robot.reset(init_state=np.array([0, 40, 0]))
device = Device(env,
                parent=robot,
                kp=np.array([[-10, 0], [10, 0]]),
                color=[0, 1, 0, 1],
                filled=False)
while True:
    robot.update(v=np.array([5, 0]))
    env._render()
Beispiel #30
0
    def __init__(self, *args, **kwargs):
        """
        EyeTracker class. This class is to be extended by each eye tracker specific implemetation
        of the pyEyeTrackerInterface.

        Please review the documentation page for the specific eye tracker model that you are using the
        pyEyeTrackerInterface with to get the appropriate module path for that eye tracker; for example,
        if you are using an interface that supports eye trackers developed by EyeTrackingCompanyET, you
        may initialize the eye tracker object for that manufacturer something similar too :

           eyeTracker = hub.eyetrackers.EyeTrackingCompanyET.EyeTracker(**kwargs)

        where hub is the instance of the ioHubClient class that has been created for your experiment.

        **kwargs are an optional set of named parameters.

        **If an instance of EyeTracker has already been created, trying to create a second will raise an exception. Either destroy the first instance and then create the new instance, or use the class method EyeTracker.getInstance() to access the existing instance of the eye tracker object.**
        """
        if EyeTracker._INSTANCE is not None:
            raise ioHub.devices.ioDeviceError(
                self.__class__.__name__,
                "EyeTracker object has already been created; only one instance can exist. Delete existing instance before recreating EyeTracker object."
            )

        # >>>> eye tracker config
        EyeTracker.eyeTrackerConfig = kwargs['dconfig']
        #print " #### EyeTracker Configuration #### "
        #print self.eyeTrackerConfig
        #print ''
        # <<<<

        # create Device level class setting dictionary and pass it Device constructor
        deviceSettings = dict(
            instance_code=self.eyeTrackerConfig['instance_code'],
            category_id=ioHub.devices.EventConstants.
            DEVICE_CATERGORIES['EYE_TRACKER'],
            type_id=ioHub.devices.EventConstants.
            DEVICE_TYPES['EYE_TRACKER_DEVICE'],
            device_class=self.eyeTrackerConfig['device_class'],
            user_label=self.eyeTrackerConfig['name'],
            os_device_code='OS_DEV_CODE_NOT_SET',
            max_event_buffer_length=self.
            eyeTrackerConfig['event_buffer_length'])
        Device.__init__(self, **deviceSettings)

        # set this instance as 'THE' instance of the eye tracker.
        EyeTracker._INSTANCE = self

        EyeTracker.DEVICE_START_TIME = 0.0

        # >>>> eye tracker setting to config (if possible)
        #
        # Current settings, example from possible values.
        #
        # 'sampling_rate': 60.0,
        # 'vog_settings': {
        #                  'pupil_illumination': 'dark',
        #                  'pupil_center_algorithm': 'centroid',
        #                  'tracking_mode': 'pupil-cr'
        #                 }
        # 'default_calibration': '9P'
        # 'track_eyes': 'BINOC'
        # 'runtime_filtering': {
        #                       'ANY': 0
        #                      }
        runtimeSettings = self.eyeTrackerConfig['runtime_settings']

        #print ''
        #print " #### EyeTracker Runtime Settings #### "
        #print runtimeSettings
        #print ''
        # <<<<

        # >>>> Display / Calibration related information to use for config if possible
        #
        # Current settings, example from possible values.
        #
        EyeTracker.displaySettings = self.eyeTrackerConfig['display_settings']
Beispiel #31
0
 def createDevice(name):
     return Device(name, self.ADDRESS, self.PORT)
Beispiel #32
0
 def setUp(self):
     QtGui.qApp.processEvents()
     self.__class__._port += 1
     self._daemon = DeviceDaemon((self.ADDRESS, self._port))
     self._dev = Device(self.NAME, self.ADDRESS, self._port)
     QtGui.qApp.processEvents()