Poll data from the sensor.
19812
def poll(args):
    """"""
    backend = _get_backend(args)
    poller = MiFloraPoller(args.mac, backend)
    print("Getting data from Mi Flora")
    print("FW: {}".format(poller.firmware_version()))
    print("Name: {}".format(poller.name()))
    print("Temperature: {}".format(poller.parameter_value(MI_TEMPERATURE)))
    print("Moisture: {}".format(poller.parameter_value(MI_MOISTURE)))
    print("Light: {}".format(poller.parameter_value(MI_LIGHT)))
    print("Conductivity: {}".format(poller.parameter_value(MI_CONDUCTIVITY)))
    print("Battery: {}".format(poller.parameter_value(MI_BATTERY)))
1335878
def start (self):
        """"""
        values = self._defn.name, self.server_host, self.server_port
        log.info('Listening for %s telemetry on %s:%d (UDP)' % values)
        super(UdpTelemetryServer, self).start()
159456
def poll(self, offset=None, poll_timeout=600, cooldown=60, debug=False):
        '''

        '''
        if self.config['api_key'] is None:
            raise ValueError('config api_key is undefined')

        if offset or self.config.get('offset', None):
            self.offset = offset or self.config.get('offset', None)

        self._start()

        while True:
            try:
                response = self.get_updates(poll_timeout, self.offset)
                if response.get('ok', False) is False:
                    raise ValueError(response['error'])
                else:
                    self.process_updates(response)
            except Exception as e:
                print('Error: Unknown Exception')
                print(e)
                if debug:
                    raise e
                else:
                    time.sleep(cooldown)
145022
def refresh(self):
        """"""
        # new_device = {}
        if self.type in CONST.BINARY_SENSOR_TYPES:
            response = self._lupusec.get_sensors()
            for device in response:
                if device['device_id'] == self._device_id:
                    self.update(device)

            return device

        elif self.type == CONST.ALARM_TYPE:
            response = self._lupusec.get_panel()
            self.update(response)
            return response
        
        elif self.type == CONST.TYPE_POWER_SWITCH:
            response = self._lupusec.get_power_switches()
            for pss in response:
                if pss['device_id'] == self._device_id:
                    self.update(pss)
            return pss
898185
def run(self):
        
        if self.probes is None:
            self._stop = True
        while True:

            if self._stop:
                break

            self.probes_values = {
                instrument_name:
                    {probe_name: probe_instance.value for probe_name, probe_instance in probe.items()}
                for instrument_name, probe in self.probes.items()
                }

            self.updateProgress.emit(1)

            self.msleep(int(1e3*self.refresh_interval))
1127604
def request_set_sensor_unreachable(self, req, sensor_name):
        """"""
        sensor = self.get_sensor(sensor_name)
        ts, status, value = sensor.read()
        sensor.set_value(value, sensor.UNREACHABLE, ts)
        return('ok',)
56550
function SensorCheck(sensorRootObj) {

	var promise = new Promise(function(resolve, reject) {

		var runCheck = function (tries) {

			setTimeout(function() {

				if (sensorRootObj && sensorRootObj.data) {

					resolve();

				} else if (tries >= 20) {

					reject();

				} else {

					runCheck(++tries);

				}

			}, 50);

		};

		runCheck(0);

	});

	return promise;

}
361258
private function _other()
    {
        foreach ($this->_buf as $sensor) {
            if (isset($sensor['Sensor Type (Discrete)'])) {
                $dev = new SensorDevice();
                if ($sensor['Sensor Type (Discrete)']!=='') {
                    $dev->setName($sensor['Sensor'].' ('.$sensor['Sensor Type (Discrete)'].')');
                } else {
                    $dev->setName($sensor['Sensor']);
                }
                if (isset($sensor['State'])) {
                    $dev->setValue($sensor['State']);
                } else {
                    $dev->setValue('0x0');
                }
                $this->mbinfo->setMbOther($dev);
            }
        }
    }
1183628
def _parse_sensor_record(self, sensor_data_rec, sensor_info, rem_values):
        
        val_idx = 0

        # @TODO seems there is only a single field in each of these
        assert len(sensor_data_rec.field) == 1
        sensor_data_array = sensor_data_rec.field[0].content

        # there is probably not going to be a count in the def, it'll be in the data
        count = None
        count_text = sensor_data_array.elementCount.text
        if count_text:
            count = int(count_text.strip())

        if not count:
            count = int(rem_values[val_idx])
            val_idx += 1

        parsed = []

        for recnum in range(count):
            cur = []

            for f in sensor_data_array.elementType.field:
                cur_val = rem_values[val_idx]
                val_idx += 1

                m = Member(name=f.name, standard=f.content.definition)

                if hasattr(f.content, "uom"):
                    m["units"] = f.content.uom

                try:
                    m["value"] = float(cur_val)
                except ValueError:
                    m["value"] = cur_val

                if len(f.quality):
                    m["quality"] = []
                    for qual in f.quality:
                        cur_qual = rem_values[val_idx]
                        val_idx += 1

                        # @TODO check this against constraints
                        m["quality"].append(cur_qual)

                cur.append(m)

            parsed.append(cur)

        return parsed, val_idx
167218
def run(self):
        """"""

        t_last_click = -1

        while True:
            d = self.device.read(13)
            if d is not None and self._enabled:

                if d[0] == 1:  ## readings from 6-DoF sensor
                    self.y = convert(d[1], d[2])
                    self.x = convert(d[3], d[4])
                    self.z = convert(d[5], d[6]) * -1.0

                    self.roll = convert(d[7], d[8])
                    self.pitch = convert(d[9], d[10])
                    self.yaw = convert(d[11], d[12])

                    self._control = [
                        self.x,
                        self.y,
                        self.z,
                        self.roll,
                        self.pitch,
                        self.yaw,
                    ]

                elif d[0] == 3:  ## readings from the side buttons

                    # press left button
                    if d[1] == 1:
                        t_click = time.time()
                        elapsed_time = t_click - t_last_click
                        t_last_click = t_click
                        self.single_click_and_hold = True

                    # release left button
                    if d[1] == 0:
                        self.single_click_and_hold = False

                    # right button is for reset
                    if d[1] == 2:
                        self._reset_state = 1
                        self._enabled = False
                        self._reset_internal_state()
317545
def sensor_values(self):
        
        self.update_instance_sensors(opt="all")
        return {
            "light": self.lux,
            "water": self.soil_moisture,
            "humidity": self.humidity,
            "temperature": self.temp
        }
385138
def update(self):
        """"""
        if batinfo_tag:
            # Use the batinfo lib to grab the stats
            # Compatible with multiple batteries
            self.bat.update()
            self.bat_list = [{
                'label': 'Battery',
                'value': self.battery_percent,
                'unit': '%'}]
        elif psutil_tag and hasattr(self.bat.sensors_battery(), 'percent'):
            # Use psutil to grab the stats
            # Give directly the battery percent
            self.bat_list = [{
                'label': 'Battery',
                'value': int(self.bat.sensors_battery().percent),
                'unit': '%'}]
        else:
            # No stats...
            self.bat_list = []
1282392
def export_sensor(self, sensor):
        """"""
        value = None
        unit = None
        try:
            container = self.sensor_data.get(sensor)
            unit = container.get('unit')
            data_point = container.get('data', [[0, [0.0]]])
            if data_point and data_point[0]:
                value = data_point[0][-1][0]
        except (ValueError, KeyError, AttributeError):
            pass

        return (value, unit)
341092
def _poll(self):
        
        while True:
            self.poll_count += 1
            self._poll_action()
            if self.poll_complete:
                break
            time.sleep(self.poll_interval_s)
            self._poll_update_interval()
1309088
def poll(self):
        """"""
        self._returncode = self.process.poll()

        if self._returncode is not None:
            self.set_status(self.S_DONE, "status set to Done")

        return self._returncode
1014971
def queryByPortSensor(portiaConfig, edgeId, port, sensor, last=False, params={ 'from': None, 'to': None, 'order': None, 'precision': 'ms', 'limit': None }):
    """"""

    header = {'Accept': 'text/csv'}

    if last == False:
        endpoint = '/select/device/{0}/port/{1}/sensor/{2}{3}'.format( edgeId, port, sensor, utils.buildGetParams(params) )
    else:
        endpoint = '/select/device/{0}/port/{1}/sensor/{2}/last{3}'.format( edgeId, port, sensor, utils.buildGetParams(params) )

    response = utils.httpGetRequest(portiaConfig, endpoint, header)

    if response.status_code == 200:
        try:

            dimensionSeries = pandas.read_csv( StringIO(response.text), sep=';' )
            if portiaConfig['debug']:
                print( '[portia-debug]: {0} rows'.format( len(dimensionSeries.index) ) )

            return dimensionSeries

        except:
            raise Exception('couldn\'t create pandas data frame')
    else:
        raise Exception('couldn\'t retrieve data')
154911
def _handle_poll(self, relpath, params):
    """"""
    request = json.loads(params.get('q')[0])
    ret = {}
    # request is a polling request for multiple files. For each file:
    #  - id is some identifier assigned by the client, used to differentiate the results.
    #  - path is the file to poll.
    #  - pos is the last byte position in that file seen by the client.
    for poll in request:
      _id = poll.get('id', None)
      path = poll.get('path', None)
      pos = poll.get('pos', 0)
      if path:
        abspath = os.path.normpath(os.path.join(self._root, path))
        if os.path.isfile(abspath):
          with open(abspath, 'rb') as infile:
            if pos:
              infile.seek(pos)
            content = infile.read()
            ret[_id] = content.decode("utf-8")
    content = json.dumps(ret).encode("utf-8")
    self._send_content(content, 'application/json')