Ejemplo n.º 1
0
 def test_add_device(self):
     self.list.add_device(
         'dev1',
         Device.W1Sensor(4,
                         Device.W1Sensor.list_available_sensors()[0]))
     self.list.add_device('dev2', Device.DiscreteSensor(6))
     self.assertEqual(len(self.list.get_list()), 2)
Ejemplo n.º 2
0
    def __init__(self, adc, lock, kill_flag, not_running_flag, queue, evom,
                 measurer, relays, phases):
        assert isinstance(evom, dict), evom
        assert isinstance(measurer, dict), measurer
        assert isinstance(relays, list) and all(
            isinstance(x, dict) for x in relays), relays
        assert isinstance(phases, list) and all(
            isinstance(x, dict) for x in phases), phases

        self.measurer = Measurer.Measurer(measurer["frequency"],
                                          measurer["duration"], adc)
        self.evom = Device.Device(evom["gpio"], logic=True, wait=evom["wait"])
        self.relays = [
            Device.Device(r["gpio"],
                          active=r["active"],
                          wait=r["wait"],
                          logic=True) for r in relays
        ]
        self.series = Series.Series(self.measurer, self.relays)
        self.kill_flag = kill_flag
        self.not_running_flag = not_running_flag

        self.phases = [
            Phase.Phase(p["duration"], p["delay_between_series"], self.evom,
                        self.series, self.kill_flag, self.not_running_flag,
                        lock, queue) for p in phases
        ]
        self.start = -1
Ejemplo n.º 3
0
 def on_after_startup(self):
     self._refresh_rate = float(self._settings.get(['sensor_refresh_rate']))
     self._sensors = Device.DeviceList()
     self._devices = Device.DeviceList()
     self._sensors.update_list(self._settings.get(['sensors']))
     self._devices.update_list(self._settings.get(['devices']))
     self._triggers = self._settings.get(['triggers'])
     self.start_timer()
Ejemplo n.º 4
0
def initialize_raspberry_pi():
    # Check to see if device is connected to network
    is_connected = DeviceGetInformation.is_connected()
    connection_try_count = 0

    while not is_connected:
        print("Connection Attempt: " + str(connection_try_count + 1) + ".")
        time.sleep(5)
        connection_try_count += 1
        is_connected = DeviceGetInformation.is_connected()

        if connection_try_count == 10:
            print("Failed to Connect to Internet.")
            return False

    # Check to see if device is already in the database by getting all devices and verifying the DeviceID
    device_list = ApiConnect.get_all_devices()
    device_from_db = DeviceGetInformation.get_device_from_list(device_list)

    # if device does not exist in database, then run method to create new entry
    if device_from_db is None:
        print("Creating Database Entry...")
        new_device = Device.Device(None, DeviceGetInformation.get_host_name(),
                                   DeviceGetInformation.get_local_ip(),
                                   DeviceGetInformation.get_external_ip(),
                                   DeviceGetInformation.get_mac_address(),
                                   datetime.datetime.now(), None, True)
        new_device_id = ApiConnect.create_device(new_device)
        new_device.DeviceID = new_device_id

        # Check to see if newly inserted DeviceId is valid
        if new_device.DeviceID is not None:
            print("Database Entry Inserted.")
            return new_device

        else:
            print("Could Not Insert Entry.")
            return None

    # if device exists in database, update the database
    else:
        print("Updating Existing Database Entry...")
        updated_device = Device.Device(device_from_db.DeviceID,
                                       DeviceGetInformation.get_host_name(),
                                       DeviceGetInformation.get_local_ip(),
                                       DeviceGetInformation.get_external_ip(),
                                       DeviceGetInformation.get_mac_address(),
                                       datetime.datetime.now(),
                                       device_from_db.CompanyID,
                                       device_from_db.TakeNewImage)

        is_updated = ApiConnect.update_device(updated_device)
        if is_updated:
            print("Database Entry Updated.")
            return updated_device
        else:
            print("Could Not Update Entry.")
            return None
Ejemplo n.º 5
0
def get_data():
    while 1:
        data = api.get_qos_detail()
        devices = data['data']['list']
        for device in devices:
            device_object = Device()
            device_object.from_response(device)

        time.sleep(POLLING_TIME)
Ejemplo n.º 6
0
 def connect(self):
     self.device = Device(self.port)
     if self.device.isConnected():
         self.actionConnect.setEnabled(False)
         self.actionDisconnect.setEnabled(True)
         self.actionCommand.setEnabled(True)
         self.connectTimer.start(2000)
     else:
         self.device = None
Ejemplo n.º 7
0
    def get_batch_loss_and_error_signal(self,
                                        log_posteriors,
                                        seq_lengths,
                                        tags=None):
        """
    :param numpy.ndarray log_posteriors: 3d (time,batch,label)
    :param numpy.ndarray seq_lengths: 1d (batch)
    :param list[str] tags: seq names, length = batch
    :rtype (numpy.ndarray, numpy.ndarray)
    :returns (loss, error_signal). error_signal has the same shape as posteriors.
    loss is a 1d-array (batch).

    Note that this accesses some global references, like global current seg info,
    via the current Device instance.
    Thus this is expected to be run from the Device host proc,
      inside from SprintErrorSigOp.perform.
    This also expects that we don't have chunked seqs.
    """
        assert seq_lengths.ndim == 1
        assert log_posteriors.ndim == 3
        n_batch = seq_lengths.shape[0]
        assert n_batch == log_posteriors.shape[1]

        if tags is None:
            import Device
            assert Device.is_device_host_proc()
            tags = Device.get_current_seq_tags()
        assert len(tags) == n_batch

        batch_loss = numpy.zeros((n_batch, ), dtype="float32")
        batch_error_signal = numpy.zeros_like(log_posteriors, dtype="float32")
        # Very simple parallelism. We must avoid any form of multi-threading
        # because this can be problematic with Theano.
        # See: https://groups.google.com/forum/#!msg/theano-users/Pu4YKlZKwm4/eNcAegzaNeYJ
        # We also try to keep it simple here.
        for bb in range(0, n_batch, self.max_num_instances):
            for i in range(self.max_num_instances):
                b = bb + i
                if b >= n_batch: break
                instance = self._get_instance(i)
                instance.get_loss_and_error_signal__send(
                    seg_name=tags[b],
                    seg_len=seq_lengths[b],
                    log_posteriors=log_posteriors[:seq_lengths[b], b])
            for i in range(self.max_num_instances):
                b = bb + i
                if b >= n_batch: break
                instance = self._get_instance(i)
                seg_name, loss, error_signal = instance.get_loss_and_error_signal__read(
                )
                assert seg_name == tags[b]
                batch_loss[b] = loss
                batch_error_signal[:seq_lengths[b], b] = error_signal
                numpy_set_unused(error_signal)
        return batch_loss, batch_error_signal
Ejemplo n.º 8
0
 def test_update_settings(self):
     self.list.add_device(
         'dev1',
         Device.W1Sensor(4,
                         Device.W1Sensor.list_available_sensors()[0]))
     self.list.add_device('dev2', Device.DiscreteSensor(17))
     self.list.add_device('dev3', Device.DiscreteSensor(6))
     settings = self.list.get_settings_list()
     settings[1]['gpio'] = 8
     self.list.update_list(settings)
     new_settings = self.list.get_settings_list()
     self.assertEqual(new_settings[1]['gpio'], 8)
Ejemplo n.º 9
0
    def CreateDevice(self, address, reply_handler=None, error_handler=None):
        '''
        Creates a new dbus object path for a remote device,
        then returns Device instance. This method will connect to
        the remote device and retrieve all SDP records.
        If the dbus object path for the remote device already exists
        this method will fail.
        '''
        def reply_handler_wrapper(obj_path):
            if not callable(reply_handler):
                return
            reply_handler(Device.Device(obj_path))

        def error_handler_wrapper(exception):
            exception = errors.parse_dbus_error(exception)
            if not callable(error_handler):
                raise exception
            error_handler(exception)

        if reply_handler is None and error_handler is None:
            obj_path = self.GetInterface().CreateDevice(address)
            return Device.Device(obj_path)
        else:
            self.GetInterface().CreateDevice(
                address,
                reply_handler=reply_handler_wrapper,
                error_handler=error_handler_wrapper)
            return None
Ejemplo n.º 10
0
 def ListDevices(self):
     '''Returns list of Device instances.'''
     obj_paths = self.GetInterface().ListDevices()
     devices = []
     for obj_path in obj_paths:
         devices.append(Device.Device(obj_path))
     return devices
Ejemplo n.º 11
0
def sprint_loss_and_error_signal(output_layer, target, sprint_opts, log_posteriors, seq_lengths):
  """
  :param NetworkOutputLayer.SequenceOutputLayer output_layer: output layer
  :param str target: e.g. "classes"
  :param dict[str] sprint_opts: for SprintInstancePool
  :param log_posteriors: 3d ndarray (time,batch,dim)
  :param seq_lengths: 1d ndarray (batch,) -> seq len
  :return: loss, error_signal.
    loss is a 2d ndarray (batch,) -> loss.
    error_signal has the same shape as log_posteriors.
    error_signal is the grad w.r.t. z, i.e. before softmax is applied.
  """
  if output_layer and output_layer.train_flag:
    import Device
    if Device.is_device_host_proc():
      if Device.deviceInstance.config.is_typed("seq_train_parallel"):
        print >>log.v3, "sprint_loss_and_error_signal: seq_train_parallel for output_layer %r" % output_layer.name
        assert not Device.deviceInstance.seq_train_parallel_control, "Only one supported so far."
        control = \
          SeqTrainParallelControlDevHost(
            output_layer=output_layer, output_target=target, sprint_opts=sprint_opts,
            **Device.deviceInstance.config.typed_value("seq_train_parallel"))
        Device.deviceInstance.seq_train_parallel_control = control
        loss = control.output_var_loss
        hat_y = control.output_var_hat_y  # hat_y = posteriors - error_signal
        error_signal = T.exp(log_posteriors) - hat_y
        index_mask = T.cast(output_layer.network.j["data"], "float32").dimshuffle(0, 1, 'x')
        error_signal *= index_mask
        return loss, error_signal
  op = SprintErrorSigOp(sprint_opts)
  return op(log_posteriors, seq_lengths)
Ejemplo n.º 12
0
 def __init__(self, genesisDevice=None):
     if not genesisDevice:
         genesisDevice = Device.getGenesisDevice()
     self.dev = genesisDevice
     Device.Emulator.__init__(self)
     self.power = Controller.Button("BTN_POWER", 0)
     self.reset = Controller.Button("BTN_RESET", 0)
Ejemplo n.º 13
0
 def __init__(self,
              output_layer,
              output_target,
              sprint_opts,
              forward_seq_delay=5):
     import NetworkOutputLayer
     assert isinstance(output_layer, NetworkOutputLayer.SequenceOutputLayer)
     self.output_layer = output_layer
     self.output_target = output_target
     self.output_var_loss = theano.shared(numpy.zeros((1, ), "float32"),
                                          name="loss")  # (batch,)
     self.output_var_hat_y = theano.shared(numpy.zeros((1, 1, 1),
                                                       "float32"),
                                           name='hat_y')  # (time,batch,dim)
     sprint_instance_pool = SprintInstancePool.get_global_instance(
         sprint_opts)
     assert isinstance(sprint_instance_pool, SprintInstancePool)
     self.sprint_instance_pool = sprint_instance_pool
     import Device
     assert Device.is_device_host_proc(
     ), "SeqTrainParallelControlDevHost is expected to live in the Dev proc"
     self.device = Device.deviceInstance
     self.train_started = False
     self.train_start_seq = 0
     self.train_end_seq = 0
     self.train_batches = None
     self.forward_seq_delay = forward_seq_delay
     self.forward_data_queue = []
     ":type: list[SeqTrainParallelControl.ForwardData]"
     self.calc_loss_states = []
     ":type: list[SeqTrainParallelControlDevHost.CalcLossState]"
     self.loss_data_queue = []
     ":type: list[SeqTrainParallelControl.LossData]"
Ejemplo n.º 14
0
    def draw_bluetooth(self):
        #while CF.source == 1:
        self.Time()
        with canvas(self.device) as draw:
            #basic outline Box and text rendered in portrait mode
            #draw.rectangle(device.bounding_box, outline="white", fill="black")
            D.draw_rectangle(draw, self.device)

            #date and time
            draw.line((0, 13, 128, 13), fill="white")
            draw.text((2, 1), self.today_date, fill="white")
            draw.text((78, 1), self.today_time, fill="white")
            draw.text((15, 14),
                      "Bluetooth",
                      font=self.font_basic_8,
                      fill="white")
Ejemplo n.º 15
0
def sprint_loss_and_error_signal(output_layer, target, sprint_opts,
                                 log_posteriors, seq_lengths):
    """
  :param NetworkOutputLayer.SequenceOutputLayer output_layer: output layer
  :param str target: e.g. "classes"
  :param dict[str] sprint_opts: for SprintInstancePool
  :param log_posteriors: 3d ndarray (time,batch,dim)
  :param seq_lengths: 1d ndarray (batch,) -> seq len
  :return: loss, error_signal.
    loss is a 2d ndarray (batch,) -> loss.
    error_signal has the same shape as log_posteriors.
    error_signal is the grad w.r.t. z, i.e. before softmax is applied.
  """
    if output_layer and output_layer.train_flag:
        import Device
        if Device.is_device_host_proc():
            if Device.deviceInstance.config.is_typed("seq_train_parallel"):
                print >> log.v3, "sprint_loss_and_error_signal: seq_train_parallel for output_layer %r" % output_layer.name
                assert not Device.deviceInstance.seq_train_parallel_control, "Only one supported so far."
                control = \
                  SeqTrainParallelControlDevHost(
                    output_layer=output_layer, output_target=target, sprint_opts=sprint_opts,
                    **Device.deviceInstance.config.typed_value("seq_train_parallel"))
                Device.deviceInstance.seq_train_parallel_control = control
                loss = control.output_var_loss
                hat_y = control.output_var_hat_y  # hat_y = posteriors - error_signal
                error_signal = T.exp(log_posteriors) - hat_y
                index_mask = T.cast(output_layer.network.j["data"],
                                    "float32").dimshuffle(0, 1, 'x')
                error_signal *= index_mask
                return loss, error_signal
    op = SprintErrorSigOp(sprint_opts)
    return op(log_posteriors, seq_lengths)
Ejemplo n.º 16
0
 def getTemperature(self, maxAge=1.0):
     """
     getTemperature(maxAge = 1.0) --> float
     This routine returns the current temperature mesurment.
     maxAge is the maximum allowable age (in seconds) of the
     temperature data.
     """
     trace("OmegaDp251Thermometer.getTemperature()")
     if not self.isOpen():
         self.openDevice()
     if (maxAge > 0.1 and self.timestamp and self.currentTemperature):
         now = time.time()
         if self.timestamp + maxAge > now:
             return self.currentTemperature
     s = self.sendCmdAndRecvResponse('T')
     if s == None or len(s) == 0:
         return None
     s = s[1:].strip()[:-1]
     try:
         self.currentTemperature = float(s)
     except (ValueError, TypeError):
         raise Device.DeviceError(("Cannot parse Omega "
                                   "temperature value: %s") % s)
     self.timestamp = time.time()
     return self.currentTemperature
Ejemplo n.º 17
0
  def get_batch_loss_and_error_signal(self, log_posteriors, seq_lengths):
    """
    :param numpy.ndarray log_posteriors: 3d (time,batch,label)
    :param numpy.ndarray seq_lengths: 1d (batch)
    :rtype (numpy.ndarray, numpy.ndarray)
    :returns (loss, error_signal). error_signal has the same shape as posteriors.
    loss is a 1d-array (batch).

    Note that this accesses some global references, like global current seg info,
    via the current Device instance.
    Thus this is expected to be run from the Device host proc,
      inside from SprintErrorSigOp.perform.
    This also expects that we don't have chunked seqs.
    """
    import Device
    assert Device.is_device_host_proc()
    assert seq_lengths.ndim == 1
    assert log_posteriors.ndim == 3
    n_batch = seq_lengths.shape[0]
    assert n_batch == log_posteriors.shape[1]

    tags = Device.get_current_seq_tags()
    assert len(tags) == n_batch

    batch_loss = numpy.zeros((n_batch,), dtype="float32")
    batch_error_signal = numpy.zeros_like(log_posteriors, dtype="float32")
    # Very simple parallelism. We must avoid any form of multi-threading
    # because this can be problematic with Theano.
    # See: https://groups.google.com/forum/#!msg/theano-users/Pu4YKlZKwm4/eNcAegzaNeYJ
    # We also try to keep it simple here.
    for bb in range(0, n_batch, self.max_num_instances):
      for i in range(self.max_num_instances):
        b = bb + i
        if b >= n_batch: break
        instance = self._get_instance(i)
        instance.get_loss_and_error_signal__send(
          seg_name=tags[b], seg_len=seq_lengths[b], log_posteriors=log_posteriors[:seq_lengths[b], b])
      for i in range(self.max_num_instances):
        b = bb + i
        if b >= n_batch: break
        instance = self._get_instance(i)
        seg_name, loss, error_signal = instance.get_loss_and_error_signal__read()
        assert seg_name == tags[b]
        batch_loss[b] = loss
        batch_error_signal[:seq_lengths[b], b] = error_signal
        numpy_set_unused(error_signal)
    return batch_loss, batch_error_signal
Ejemplo n.º 18
0
 def test_update_remove_settings(self):
     self.list.add_device(
         'dev1',
         Device.W1Sensor(4,
                         Device.W1Sensor.list_available_sensors()[0]))
     self.list.add_device('dev2', Device.DiscreteSensor(17))
     self.list.add_device('dev3', Device.DiscreteSensor(6))
     settings = []
     settings.append({
         'name': 'dev2',
         'gpio': 4,
         'direction': Device.Device.IN,
         'path': None,
         'type': Device.Device.DISCRETE
     })
     self.list.update_list(settings)
     self.assertEqual(len(self.list.get_list()), 1)
Ejemplo n.º 19
0
 def FindDevice(self, address):
     '''
     Returns the Device instance for given address.
     The device object needs to be first created via
     CreateDevice or CreatePairedDevice.
     '''
     obj_path = self.GetInterface().FindDevice(address)
     return Device.Device(obj_path)
Ejemplo n.º 20
0
  def get_batch_loss_and_error_signal(self, target, log_posteriors, seq_lengths):
    """
    :param str target: e.g. "classes". not yet passed over to Sprint.
    :param numpy.ndarray log_posteriors: 3d (time,batch,label)
    :param numpy.ndarray seq_lengths: 1d (batch)
    :rtype (numpy.ndarray, numpy.ndarray)
    :returns (loss, error_signal). error_signal has the same shape as posteriors.
    loss is a 1d-array (batch).

    Note that this accesses some global references, like global current seg info.
    """
    assert seq_lengths.ndim == 1
    assert log_posteriors.ndim == 3
    n_batch = seq_lengths.shape[0]
    assert n_batch == log_posteriors.shape[1]

    import Device
    index = Device.get_current_seq_index(target)  # (time,batch)
    assert index.ndim == 2
    assert index.shape[1] == n_batch
    assert (numpy.sum(index, axis=0) == seq_lengths).all()
    tags = Device.get_current_seq_tags()
    assert len(tags) == n_batch

    batch_loss = numpy.zeros((n_batch,), dtype="float32")
    batch_error_signal = numpy.zeros_like(log_posteriors, dtype="float32")
    # Very simple parallelism. We must avoid any form of multi-threading
    # because this can be problematic with Theano.
    # See: https://groups.google.com/forum/#!msg/theano-users/Pu4YKlZKwm4/eNcAegzaNeYJ
    # We also try to keep it simple here.
    for bb in range(0, n_batch, self.max_num_instances):
      for i in range(self.max_num_instances):
        b = bb + i
        if b >= n_batch: break
        instance = self._get_instance(i)
        instance.get_loss_and_error_signal__send(
          seg_name=tags[b], seg_len=seq_lengths[b], posteriors=log_posteriors[:seq_lengths[b], b])
      for i in range(self.max_num_instances):
        b = bb + i
        if b >= n_batch: break
        instance = self._get_instance(i)
        seg_name, loss, error_signal = instance.get_loss_and_error_signal__read()
        assert seg_name == tags[b]
        batch_loss[b] = loss
        batch_error_signal[:seq_lengths[b], b] = error_signal
    return batch_loss, batch_error_signal
Ejemplo n.º 21
0
 def __init__(self,
              i2c,
              mode=_BME280_OSAMPLE_1,
              address=_BME280_I2CADDR,
              debug=False,
              raw=False,
              calibrate=None):
     # Check that mode is valid.
     if mode not in [
             _BME280_OSAMPLE_1, _BME280_OSAMPLE_2, _BME280_OSAMPLE_4,
             _BME280_OSAMPLE_8, _BME280_OSAMPLE_16
     ]:
         raise ValueError(
             'Unexpected mode value {0}. Set mode to one of '
             'BME280_ULTRALOWPOWER, BME280_STANDARD, BME280_HIGHRES, or '
             'BME280_ULTRAHIGHRES'.format(mode))
     self._mode = mode
     # Create I2C device.
     if not type(i2c) is I2C:
         raise ValueError('An I2C object is required.')
     self._device = Device(address, i2c)
     # check chip ID
     chip_id = self._device.readU8(_BME280_ID_ADDR)
     print("Got ID: 0x%X" % chip_id)
     if chip_id != _BME280_ID:
         raise RuntimeError(
             "BME280 Not Found. Invalid chip ID: 0x{0:02x}".format(chip_id))
     # Load calibration values.
     self._load_calibration()
     self._device.write8(_BME280_REGISTER_CONTROL, 0x3F)
     self.t_fine = 0
     self.sea_level_pressure = 1010.25
     """Pressure in hectoPascals at sea level. Used to calibrate ``altitude``."""
     self.raw = raw
     self.calibrate = {
         'temperature': None,
         'pressure': None,
         'humidity': None,
         'altitude': None
     }
     if (not raw) and (type(calibrate) is dict):
         for k in calibrate.keys():
             if (not k in self.calibrate.keys()) or (
                     not type(calibrate[k]) is list):
                 continue
             self.calibrate[k] = calibrate[k]
Ejemplo n.º 22
0
 def __init__(self, mode=BME280_OSAMPLE_1, address=BME280_I2CADDR, i2c=None,
              **kwargs):
     # Check that mode is valid.
     if mode not in [BME280_OSAMPLE_1, BME280_OSAMPLE_2, BME280_OSAMPLE_4,
                     BME280_OSAMPLE_8, BME280_OSAMPLE_16]:
         raise ValueError(
             'Unexpected mode value {0}. Set mode to one of '
             'BME280_ULTRALOWPOWER, BME280_STANDARD, BME280_HIGHRES, or '
             'BME280_ULTRAHIGHRES'.format(mode))
     self._mode = mode
     # Create I2C device.
     if i2c is None:
         raise ValueError('An I2C object is required.')
     self._device = Device(address, i2c)
     # Load calibration values.
     self._load_calibration()
     self._device.write8(BME280_REGISTER_CONTROL, 0x3F)
     self.t_fine = 0
Ejemplo n.º 23
0
def connectDevice():
    print(f"Attempting connection with {sys.argv[1]}...", end="")
    global station
    station = Device(sys.argv[1], 115200)  # Creates the device
    station.device.flush()
    if station:
        print("OK")
        return True
    else:
        print("ERROR")
        return False
Ejemplo n.º 24
0
def ToSetRailWidth():
    try:
        width = scale.get()
        writeDebug("SetRailWidth(%s %d)" %
                   (RunningMode.device_to_set_rail_width, width))
        if (RunningMode.device_to_set_rail_width):
            Device.SetRailWidth(RunningMode.device_to_set_rail_width, width)
        else:
            tkMessageBox.showwarning("告警", "请先点选要设置的设备")
    except BxtException.ExceptionCommunication, e:
        writeError("%s SetRailWidth failed for [%s]" %
                   (RunningMode.device_to_set_rail_width, e))
Ejemplo n.º 25
0
 def __init__(self,x_servo=0,y_servo=1,z_servo=2):
   self.x_servo = x_servo
   self.y_servo = y_servo
   self.z_servo = z_servo
   self.device = Device()
   self.device.set_acceleration(self.x_servo,10)
   self.device.set_speed(self.x_servo,10)
   self.device.set_acceleration(self.y_servo,10)
   self.device.set_speed(self.y_servo,10)
   self.device.set_acceleration(self.z_servo,10)
   self.device.set_speed(self.z_servo,10)
   self.device.go_home()
Ejemplo n.º 26
0
    def nearby_devices(self):
        print("build near by devices ", threading.get_ident())
        devices = []
        for host, name, class_id in self.__near_by:
            d = Device.Device(self)
            d.name = name
            d.host = host
            d.class_id = class_id
            d.available = True
            devices.append(d)

        return QQmlListProperty(Device.Device, self, devices)
Ejemplo n.º 27
0
def details():
    global api
    if (api.login_token is None):
        raise LoginError
    data = api.get_qos_detail()
    devices = data['data']['list']
    devs = []

    for device in devices:
        util.log(device, file=True, mode='w+')
        device_object = Device()
        device_object.from_response(device)
        """storage.save_device_detail(device_object)
        stored_device = storage.get_by("mac", device_object.mac)
                
        device_object.details = stored_device['data']['details']"""

        devs.append(device_object.to_dict())
    devs = sorted(devs,
                  reverse=True,
                  key=lambda i: (i['statistics']['downspeed']))
    return jsonify(devs)
Ejemplo n.º 28
0
 def __init__(self, trigger=False):  # originally 0-4
     self.device = D.Device()
     self.servo_map = {}
     self.id_map = {}
     self.servo_list = []
     self.frame_list = []
     self.frame_list_length = 0
     self.frame_number = 0
     self.verbose = False
     self.trigger = trigger
     self.loop = False
     self.debug(self.device)
     self.device.go_home()
Ejemplo n.º 29
0
    def AddDevice(self, Serial):
        self.ListDevice[Serial] = Device(Serial,
                                         self.CallUi.ui.PathScript.text())

        Itemid, data, process = (self.ListDevice[Serial]).GetItem()
        self.CallUi.ui.tableWidget.setRowCount(
            self.CallUi.ui.tableWidget.rowCount() + 1)
        self.CallUi.ui.tableWidget.setItem(
            self.CallUi.ui.tableWidget.rowCount() - 1, 0, Itemid)
        self.CallUi.ui.tableWidget.setItem(
            self.CallUi.ui.tableWidget.rowCount() - 1, 1, data)
        self.CallUi.ui.tableWidget.setItem(
            self.CallUi.ui.tableWidget.rowCount() - 1, 2, process)
Ejemplo n.º 30
0
    def __init__(self):
        self.codes = CF.codes
        self.today_date = None
        self.today_time = None
        self.device = D.get_device()
        self.font_basic = None
        self.font_basic_8 = None
        self.font_awesome = None
        self.font_awesome_small = None
        self.font_menu = None
        self.interval = CF.interval
        self.source = CF.source

        self.makeFonts(self.device)
Ejemplo n.º 31
0
    def draw_boat(self):
        #while CF.source == 1:
        self.Time()
        with canvas(self.device) as draw:
            #basic outline Box and text rendered in portrait mode
            #draw.rectangle(device.bounding_box, outline="white", fill="black")
            D.draw_rectangle(draw, self.device)

            #date and time
            draw.line((0, 13, 128, 13), fill="white")
            draw.text((2, 1), self.today_date, fill="white")
            draw.text((78, 1), self.today_time, fill="white")
            draw.text((15, 14),
                      "Folder Navigation",
                      font=self.font_basic_8,
                      fill="white")
            try:
                draw.rectangle((9, 32, 122, 24), outline="white", fill="white")
                draw.text((10, 24),
                          CF.listDirectoriesSelect[CF.interval],
                          font=self.font_basic_8,
                          fill="black")
                draw.text((10, 34),
                          CF.listDirectoriesSelect[CF.interval + 1],
                          font=self.font_basic_8,
                          fill="white")
                draw.text((10, 44),
                          CF.listDirectoriesSelect[CF.interval + 2],
                          font=self.font_basic_8,
                          fill="white")
                draw.text((10, 54),
                          CF.listDirectoriesSelect[CF.interval + 3],
                          font=self.font_basic_8,
                          fill="white")
            except:
                pass
Ejemplo n.º 32
0
    def to_json(self):
        vs = VarsSetting()
        vs.config = self.config
        for k, d in self.devices.items():
            vs.devices[k] = (Device.PureController(d))

            if d.groups:
                for g in d.groups.values():
                    pg = Group.PureGroup(g)
                    vs.groups.append(pg)
        try:
            s = json.dumps(vs, default=Utilities.Utility.serialize_instance)
        except Exception as e:
            s = json.dumps(vs)
        return s
Ejemplo n.º 33
0
    def CreatePairedDevice(self,
                           address,
                           agent,
                           capability='',
                           reply_handler=None,
                           error_handler=None):
        '''
        Creates a new object path for a remote device and then
        returns Device instance. This method will connect to
        the remote device and retrieve all SDP records and then
        initiate the pairing.
        If previously CreateDevice was used successfully,
        this method will only initiate the pairing.
        Compared to CreateDevice this method will fail if
        the pairing already exists, but not if the object
        path already has been created. This allows applications
        to use CreateDevice first and the if needed use
        CreatePairedDevice to initiate pairing.
        The capability parameter is the same as for the
        RegisterAgent method.
        Use reply_handler and error_handler to make asynchronous call,
        and this method will return None.
        reply_handler will receive an instance of Device as the parameter,
        error_handler will receive an exception as the parameter.
        '''
        def reply_handler_wrapper(obj_path):
            if not callable(reply_handler):
                return
            reply_handler(Device.Device(obj_path))

        def error_handler_wrapper(exception):
            exception = errors.parse_dbus_error(exception)
            if not callable(error_handler):
                raise exception
            error_handler(exception)

        if reply_handler is None and error_handler is None:
            obj_path = self.GetInterface().CreatePairedDevice(
                address, agent, capability)
            return Device.Device(obj_path)
        else:
            self.GetInterface().CreatePairedDevice(
                address,
                agent,
                capability,
                reply_handler=reply_handler_wrapper,
                error_handler=error_handler_wrapper)
            return None
Ejemplo n.º 34
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.__transfer_manager = QBluetoothTransferManager()
        self.__device = Device.Device()
        self.__settings = QSettings("PCSuite", "maxvanceffer")

        self.__settings.beginGroup("device")
        all_groups = self.__settings.allKeys()
        if len(all_groups):
            self.__device.host = self.__settings.value('host')
            self.__device.name = self.__settings.value('name')
            self.__device.class_id = self.__settings.value('class_id')

        self.__settings.endGroup()
        if self.__device.is_empty() is False:
            self.find_device_state(self.__device)
Ejemplo n.º 35
0
 def __init__(self, output_layer, output_target, sprint_opts, forward_seq_delay=5):
   import NetworkOutputLayer
   assert isinstance(output_layer, NetworkOutputLayer.SequenceOutputLayer)
   self.output_layer = output_layer
   self.output_target = output_target
   self.output_var_loss = theano.shared(numpy.zeros((1,), "float32"), name="loss")  # (batch,)
   self.output_var_hat_y = theano.shared(numpy.zeros((1,1,1), "float32"), name='hat_y')  # (time,batch,dim)
   sprint_instance_pool = SprintInstancePool.get_global_instance(sprint_opts)
   assert isinstance(sprint_instance_pool, SprintInstancePool)
   self.sprint_instance_pool = sprint_instance_pool
   import Device
   assert Device.is_device_host_proc(), "SeqTrainParallelControlDevHost is expected to live in the Dev proc"
   self.device = Device.deviceInstance
   self.train_started = False
   self.train_start_seq = 0
   self.train_end_seq = 0
   self.train_batches = None
   self.forward_seq_delay = forward_seq_delay
   self.forward_data_queue = []; ":type: list[SeqTrainParallelControl.ForwardData]"
   self.calc_loss_states = []; ":type: list[SeqTrainParallelControlDevHost.CalcLossState]"
   self.loss_data_queue = []; ":type: list[SeqTrainParallelControl.LossData]"
Ejemplo n.º 36
0
def read_Xml(devices):
    inTagGroup = False
    inDevicesContent = False
    inTagDevice = False
    #xmlFile=open('prueba.xml','r')
    xmlFile = open('wurfl-2.3.xml', 'r')
    line = xmlFile.readline()
    while line != '':
        line = xmlFile.readline()
        if not (inDevicesContent):
            if searchDevices(line) != -1:
                inDevicesContent = True
        else:
            if not (inTagDevice):
                if searchDevice(line) != -1:
                    #Instancia de dispositivo provisional hasta que se finalic el tag
                    device = Device.Device()
                    inTagDevice = True
                    extractDeviceAtt(line, device)
            else:
                if not (inTagGroup):
                    if searchGroup(line) != -1:
                        inTagGroup = True
                        temp = extractGroupId(line)
                        extractGroupAtt(line, device)
                else:
                    if searchCapability(line) != -1:
                        capability = Capability.Capability()
                        extractNameCapability(line, capability)
                        extractValueCapability(line, capability)
                        addCapabilities(device.get_groups().get(temp),
                                        capability)
                    if searchEndGroup(line) != -1:
                        inTagGroup = False
                if searchEndDevice(line) != -1:
                    devices[device.get_id()] = device
                    inTagDevice = False
            if searchEndDevices(line) != -1:
                inDevicesContent = False
Ejemplo n.º 37
0
  def get_batch_loss_and_error_signal(self, log_posteriors, seq_lengths, tags=None):
    """
    :param numpy.ndarray log_posteriors: 3d (time,batch,label)
    :param numpy.ndarray seq_lengths: 1d (batch)
    :param list[str] tags: seq names, length = batch
    :rtype (numpy.ndarray, numpy.ndarray)
    :returns (loss, error_signal). error_signal has the same shape as posteriors.
    loss is a 1d-array (batch).

    Note that this accesses some global references, like global current seg info,
    via the current Device instance.
    Thus this is expected to be run from the Device host proc,
      inside from SprintErrorSigOp.perform.
    This also expects that we don't have chunked seqs.
    """
    assert seq_lengths.ndim == 1
    assert log_posteriors.ndim == 3
    n_batch = seq_lengths.shape[0]
    assert n_batch == log_posteriors.shape[1]

    if tags is None:
      import Device
      assert Device.is_device_host_proc()
      tags = Device.get_current_seq_tags()
    assert len(tags) == n_batch
    
    batch_loss = numpy.zeros((n_batch,), dtype="float32")
    batch_error_signal = numpy.zeros_like(log_posteriors, dtype="float32")
    
    # greedy solution to the scheduling problem
    sorted_length = sorted(enumerate(seq_lengths),key=lambda x:x[1],reverse=True)
    jobs = [ [] for i in range(self.max_num_instances) ]
    joblen = [0]*self.max_num_instances
    for i,l in sorted_length:
      j = min(enumerate(joblen),key=lambda x:x[1])[0]
      jobs[j].append(i)
      joblen[j]+=l

    if not BackendEngine.is_theano_selected() and self.max_num_instances > 1:
      threads = [ReaderThread(self._get_instance(i), i, jobs[i], tags, seq_lengths, log_posteriors, batch_loss, batch_error_signal) for i in range(self.max_num_instances)]
      for i,thread in enumerate(threads):
        thread.join()
        if thread.exception:
          raise thread.exception
    else:
      # Very simple parallelism. We must avoid any form of multi-threading
      # because this can be problematic with Theano.
      # See: https://groups.google.com/forum/#!msg/theano-users/Pu4YKlZKwm4/eNcAegzaNeYJ
      # We also try to keep it simple here.
      for bb in range(0, n_batch, self.max_num_instances):
        for i in range(self.max_num_instances):
          b = bb + i
          if b >= n_batch: break
          instance = self._get_instance(i)
          instance.get_loss_and_error_signal__send(
            seg_name=tags[b], seg_len=seq_lengths[b], log_posteriors=log_posteriors[:seq_lengths[b], b])
        for i in range(self.max_num_instances):
          b = bb + i
          if b >= n_batch: break
          instance = self._get_instance(i)
          seg_name, loss, error_signal = instance.get_loss_and_error_signal__read()
          assert seg_name == tags[b]
          batch_loss[b] = loss
          batch_error_signal[:seq_lengths[b], b] = error_signal
          numpy_set_unused(error_signal)
    return batch_loss, batch_error_signal
Ejemplo n.º 38
0
import Device
#import EditPointScreen
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice, MonkeyImage

# Executa a aplicacao e retorna a mesma
application = Device.startActivity()

for x in xrange(1,11):
	try:
		print("Teste "+str(x))
		print("O aplicativo deve inserir um ponto atraves do botao bater ponto da barra de acoes")
		MonkeyRunner.sleep(2)
		application.touch(605, 100, 'DOWN_AND_UP')
		print("O aplicativo deve editar o segundo ponto tocando no mesmo")
		MonkeyRunner.sleep(2)
		application.touch(554, 350, 'DOWN_AND_UP')
		print("O aplicativo arrasta as horas da edicao")
		MonkeyRunner.sleep(2)
		application.drag((320,750),(320,470),0.15,5)
		print("O aplicativo arrasta os minutos da edicao")
		MonkeyRunner.sleep(2)
		application.drag((500,470),(500,750),0.15,5)
		print("O aplicativo clica em ok")
		MonkeyRunner.sleep(2)
		application.touch(380, 900, 'DOWN_AND_UP')
		print("O aplicativo troca para tela de lista de pontos")
		MonkeyRunner.sleep(2)
		application.drag((700,700),(25,700),0.15,5)
		print("Foto da lista de pontos")
		MonkeyRunner.sleep(2)
		photoListPoint = application.takeSnapshot()
Ejemplo n.º 39
0
def test_Device():
    print "Test Device"
    d = Device("COM6", "COM7")
    servos = [0, 1]
    for servo_id in servos:
        print "-- servo:", servo_id
        print "Go Home"
        d.go_home()
        print "Get Errors"
        print d.get_errors()

        print "Get Position"
        pos = d.get_position(servo_id)
        print pos

        newsetpos = pos - 50
        print "Set Target:", newsetpos
        d.set_target(servo_id, newsetpos)
        d.wait_until_at_target()
        newpos = d.get_position(servo_id)
        print "%s==%s" % (newsetpos, newpos),
        print newsetpos == newpos

        newsetpos = pos + 50
        print "Set Target:", newsetpos
        d.set_target(servo_id, newsetpos)
        d.wait_until_at_target()
        newpos = d.get_position(servo_id)
        print "%s==%s" % (newsetpos, newpos),
        print newsetpos == newpos

        d.go_home()
        print d.get_errors()
    del d
    print "Device tested"
Ejemplo n.º 40
0
class LegacyCameraDriver(object):
  def __init__(self,x_servo=0,y_servo=1,z_servo=2):
    self.x_servo = x_servo
    self.y_servo = y_servo
    self.z_servo = z_servo
    self.device = Device()
    self.device.set_acceleration(self.x_servo,10)
    self.device.set_speed(self.x_servo,10)
    self.device.set_acceleration(self.y_servo,10)
    self.device.set_speed(self.y_servo,10)
    self.device.set_acceleration(self.z_servo,10)
    self.device.set_speed(self.z_servo,10)
    self.device.go_home()

  def __del__(self):
    del(self.device)
    
  def status_report(self):
    return "X: %s\tY: %s\tZ: %s" % (self.device.get_position(self.x_servo),self.device.get_position(self.y_servo),self.device.get_position(self.z_servo))

  def pan(self,dx):
    x = self.device.get_position(self.x_servo)
    x += dx
    self.device.set_target(self.x_servo,x)
    self.device.wait_until_at_target()
 
  def tilt(self,dy):
    y = self.device.get_position(self.y_servo)
    y += dy
    self.device.set_target(self.y_servo,y)
    self.device.wait_until_at_target()

  def rotate(self,dz):
    z = self.device.get_position(self.z_servo)
    z += dz
    self.device.set_target(self.z_servo,z)
    self.device.wait_until_at_target()
    
  def goto(self,x,y,z=0):
    self.device.set_target(self.x_servo,x)
    self.device.set_target(self.y_servo,y)
    self.device.set_target(self.z_servo,z)
    self.device.wait_until_at_target()
    
  def reset(self):
    self.device.go_home()
    self.device.wait_until_at_target()
Ejemplo n.º 41
0
 def Join_device(self, mac_addr, ip_addr=None):
     dev = Device.device(mac_addr, ip_addr)
     self.device_list[mac_addr] = dev 
     print 'Join the device %s' %(mac_addr)
        for each in digits:
            self.dialDigit(each)

        writeInfo('Call ...')
        el = self.driver.find_element_by_xpath("//android.widget.ImageButton[@resource-id='com.rebtel.android:id/button14']")
        el.click()
        time.sleep(1)
        el = self.driver.find_element_by_xpath("//android.widget.Button[@resource-id='com.rebtel.android:id/next_button']")
        el.click()
        time.sleep(1)

        writeInfo('Hang up ...')
        el = self.driver.find_element_by_xpath("//android.widget.ImageView[@resource-id='com.rebtel.android:id/hangupButton']")
        el.click()
        time.sleep(3)

        self.nevigateTo('Recent')

        writeInfo('Verifying the call in Recent menu ...')
        try:
            el = self.driver.find_element_by_xpath("//android.widget.TextView[@resource-id='com.rebtel.android:id/phoneNumber']")
            phoneNumber = el.text
        except:
            phoneNumber = None
        self.assertEqual(phoneNumber, '+8801717379480', "Dialed phone number doesn't exist in the Recent menu!")


if __name__ == 'RebtelAndroidTest':
    ''' Recruit the intended device to run at. '''
    d = Device()
    device = d.getDevice('RebtelAndroidTest')