Decode sensor data.

        Returns:
            dict: Sensor values
790
def decode_data(self, encoded):
        '''
        
        '''
        try:
            identifier = None
            data_format = 2
            if len(encoded) > 8:
                data_format = 4
                identifier = encoded[8:]
                encoded = encoded[:8]
            decoded = bytearray(base64.b64decode(encoded, '-_'))
            return {
                'data_format': data_format,
                'temperature': self._get_temperature(decoded),
                'humidity': self._get_humidity(decoded),
                'pressure': self._get_pressure(decoded),
                'identifier': identifier
            }
        except:
            log.exception('Encoded value: %s not valid', encoded)
            return None
707021
def read(self, sensors):
        """"""
        payload = {'destDev': [], 'keys': list(set([s.key for s in sensors]))}
        if self.sma_sid is None:
            yield from self.new_session()
            if self.sma_sid is None:
                return False
        body = yield from self._fetch_json(URL_VALUES, payload=payload)

        # On the first 401 error we close the session which will re-login
        if body.get('err') == 401:
            _LOGGER.warning("401 error detected, closing session to force "
                            "another login attempt")
            self.close_session()
            return False

        _LOGGER.debug(json.dumps(body))
        for sen in sensors:
            if sen.extract_value(body):
                _LOGGER.debug("%s\t= %s %s",
                              sen.name, sen.value, sen.unit)
        return True
964228
def decode(self, data):
        
        return Zchunk(lib.zarmour_decode(self._as_parameter_, data), True)
803709
def tdSensor(self):
        
        protocol = create_string_buffer(20)
        model = create_string_buffer(20)
        sid = c_int()
        datatypes = c_int()

        self._lib.tdSensor(protocol, sizeof(protocol), model, sizeof(model),
                           byref(sid), byref(datatypes))
        return {'protocol': self._to_str(protocol),
                'model': self._to_str(model),
                'id': sid.value, 'datatypes': datatypes.value}
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
17373
async def get_data(self):
        """"""
        try:
            with async_timeout.timeout(5, loop=self._loop):
                response = await self._session.get(
                    '{}/{}/'.format(self.url, self.sensor_id))

            _LOGGER.debug(
                "Response from luftdaten.info: %s", response.status)
            self.data = await response.json()
            _LOGGER.debug(self.data)
        except (asyncio.TimeoutError, aiohttp.ClientError):
            _LOGGER.error("Can not load data from luftdaten.info")
            raise exceptions.LuftdatenConnectionError()

        if not self.data:
            self.values = self.meta = None
            return

        try:
            sensor_data = sorted(
                self.data, key=lambda timestamp: timestamp['timestamp'],
                reverse=True)[0]
            print(sensor_data)

            for entry in sensor_data['sensordatavalues']:
                for measurement in self.values.keys():
                    if measurement == entry['value_type']:
                        self.values[measurement] = float(entry['value'])

            self.meta['sensor_id'] = self.sensor_id
            self.meta['longitude'] = float(
                sensor_data['location']['longitude'])
            self.meta['latitude'] = float(sensor_data['location']['latitude'])
        except (TypeError, IndexError):
            raise exceptions.LuftdatenError()
1209162
def info(self):
        
        result = list()
        result.append("Agents:\n")
        for agent in self._all_agents:
            result.append("\tName: ")
            result.append(agent.name)
            result.append("\n\tType: ")
            result.append(type(agent).__name__)
            result.append("\n\t")
            result.append("Sensors:\n")
            for sensor in self._sensor_map[agent.name].keys():
                result.append("\t\t")
                result.append(Sensors.name(sensor))
                result.append("\n")
        return "".join(result)
1070064
def _lw_decode(self, msg):
        """"""
        keypad_temps = []
        zone_temps = []
        for i in range(16):
            keypad_temps.append(int(msg[4+3*i:7+3*i]) - 40)
            zone_temps.append(int(msg[52+3*i:55+3*i]) - 60)
        return {'keypad_temps': keypad_temps, 'zone_temps': zone_temps}
4208
def decode(obj):
    

    typ = obj.get('typ')
    if typ is None:
        return obj
    elif typ == 'timestamp':
        freq = obj['freq'] if 'freq' in obj else obj['offset']
        return Timestamp(obj['value'], tz=obj['tz'], freq=freq)
    elif typ == 'nat':
        return NaT
    elif typ == 'period':
        return Period(ordinal=obj['ordinal'], freq=obj['freq'])
    elif typ == 'index':
        dtype = dtype_for(obj['dtype'])
        data = unconvert(obj['data'], dtype,
                         obj.get('compress'))
        return Index(data, dtype=dtype, name=obj['name'])
    elif typ == 'range_index':
        return RangeIndex(obj['start'],
                          obj['stop'],
                          obj['step'],
                          name=obj['name'])
    elif typ == 'multi_index':
        dtype = dtype_for(obj['dtype'])
        data = unconvert(obj['data'], dtype,
                         obj.get('compress'))
        data = [tuple(x) for x in data]
        return MultiIndex.from_tuples(data, names=obj['names'])
    elif typ == 'period_index':
        data = unconvert(obj['data'], np.int64, obj.get('compress'))
        d = dict(name=obj['name'], freq=obj['freq'])
        freq = d.pop('freq', None)
        return PeriodIndex(PeriodArray(data, freq), **d)

    elif typ == 'datetime_index':
        data = unconvert(obj['data'], np.int64, obj.get('compress'))
        d = dict(name=obj['name'], freq=obj['freq'])
        result = DatetimeIndex(data, **d)
        tz = obj['tz']

        # reverse tz conversion
        if tz is not None:
            result = result.tz_localize('UTC').tz_convert(tz)
        return result

    elif typ in ('interval_index', 'interval_array'):
        return globals()[obj['klass']].from_arrays(obj['left'],
                                                   obj['right'],
                                                   obj['closed'],
                                                   name=obj['name'])
    elif typ == 'category':
        from_codes = globals()[obj['klass']].from_codes
        return from_codes(codes=obj['codes'],
                          categories=obj['categories'],
                          ordered=obj['ordered'])

    elif typ == 'interval':
        return Interval(obj['left'], obj['right'], obj['closed'])
    elif typ == 'series':
        dtype = dtype_for(obj['dtype'])
        pd_dtype = pandas_dtype(dtype)

        index = obj['index']
        result = Series(unconvert(obj['data'], dtype, obj['compress']),
                        index=index,
                        dtype=pd_dtype,
                        name=obj['name'])
        return result

    elif typ == 'block_manager':
        axes = obj['axes']

        def create_block(b):
            values = _safe_reshape(unconvert(
                b['values'], dtype_for(b['dtype']),
                b['compress']), b['shape'])

            # locs handles duplicate column names, and should be used instead
            # of items; see GH 9618
            if 'locs' in b:
                placement = b['locs']
            else:
                placement = axes[0].get_indexer(b['items'])

            if is_datetime64tz_dtype(b['dtype']):
                assert isinstance(values, np.ndarray), type(values)
                assert values.dtype == 'M8[ns]', values.dtype
                values = DatetimeArray(values, dtype=b['dtype'])

            return make_block(values=values,
                              klass=getattr(internals, b['klass']),
                              placement=placement,
                              dtype=b['dtype'])

        blocks = [create_block(b) for b in obj['blocks']]
        return globals()[obj['klass']](BlockManager(blocks, axes))
    elif typ == 'datetime':
        return parse(obj['data'])
    elif typ == 'datetime64':
        return np.datetime64(parse(obj['data']))
    elif typ == 'date':
        return parse(obj['data']).date()
    elif typ == 'timedelta':
        return timedelta(*obj['data'])
    elif typ == 'timedelta64':
        return np.timedelta64(int(obj['data']))
    # elif typ == 'sparse_series':
    #    dtype = dtype_for(obj['dtype'])
    #    return SparseSeries(
    #        unconvert(obj['sp_values'], dtype, obj['compress']),
    #        sparse_index=obj['sp_index'], index=obj['index'],
    #        fill_value=obj['fill_value'], kind=obj['kind'], name=obj['name'])
    # elif typ == 'sparse_dataframe':
    #    return SparseDataFrame(
    #        obj['data'], columns=obj['columns'],
    #        default_fill_value=obj['default_fill_value'],
    #        default_kind=obj['default_kind']
    #    )
    # elif typ == 'sparse_panel':
    #    return SparsePanel(
    #        obj['data'], items=obj['items'],
    #        default_fill_value=obj['default_fill_value'],
    #        default_kind=obj['default_kind'])
    elif typ == 'block_index':
        return globals()[obj['klass']](obj['length'], obj['blocs'],
                                       obj['blengths'])
    elif typ == 'int_index':
        return globals()[obj['klass']](obj['length'], obj['indices'])
    elif typ == 'ndarray':
        return unconvert(obj['data'], np.typeDict[obj['dtype']],
                         obj.get('compress')).reshape(obj['shape'])
    elif typ == 'np_scalar':
        if obj.get('sub_typ') == 'np_complex':
            return c2f(obj['real'], obj['imag'], obj['dtype'])
        else:
            dtype = dtype_for(obj['dtype'])
            try:
                return dtype(obj['data'])
            except (ValueError, TypeError):
                return dtype.type(obj['data'])
    elif typ == 'np_complex':
        return complex(obj['real'] + '+' + obj['imag'] + 'j')
    elif isinstance(obj, (dict, list, set)):
        return obj
    else:
        return obj
1106296
def get_precision(self):
        
        config_str = self.raw_sensor_strings[1].split()[4]  # Byte 5 is the config register
        bit_base = int(config_str, 16) >> 5  # Bit 5-6 contains the resolution, cut off the rest
        return bit_base + 9
981886
def api_sensors(self) -> Set[str]:
        """"""
        today = round_time(datetime.now(timezone.utc), by=timedelta(days=1))
        c = requests.get(
            f"https://opensky-network.org/api/sensor/myStats"
            f"?days={int(today.timestamp())}",
            auth=self.auth,
        )
        if c.status_code != 200:
            raise ValueError(c.content.decode())
        return set(c.json()[0]["stats"].keys())
103139
def _parse_sensor_data(self, obs_el, sensor_info):
        
        data_array = obs_el.content

        # get column defs
        data_record = data_array.elementType.content
        columns = []
        for f in data_record.field:
            columns.append(f)

        # get more information on sensor cols
        sensor_cols = defaultdict(list)
        # sensor_vals = defaultdict(list)

        sensor_rec = data_record.get_by_name("sensor")
        for sendata in sensor_rec.content.item:
            if sendata.content is None:
                continue

            for f in sendata.content.field:
                sensor_cols[sendata.name].append(f)

        # @TODO deduplicate
        # decimalSeparator = data_array.encoding.decimalSeparator
        tokenSeparator = data_array.encoding.tokenSeparator
        blockSeparator = data_array.encoding.blockSeparator
        # collapseWhiteSpaces = data_array.encoding.collapseWhiteSpaces

        data_values = data_array.values
        lines = [x for x in data_values.split(blockSeparator) if x != ""]

        # profile cacher!
        profile_cache = ProfileCache()

        for row in lines:
            values = row.split(tokenSeparator)

            # skey = None
            i = 0
            cur_time = None
            # cur_qual = None

            for c in columns:

                if (
                    isinstance(c.content, Time)
                    and c.content.definition
                    == "http://www.opengis.net/def/property/OGC/0/SamplingTime"
                ):
                    cur_time = parser.parse(values[i])
                    i += 1

                    if len(c.quality):
                        # @TODO: do some quality constraint checks
                        i += len(c.quality)
                        # for qua in c.quality:

                elif isinstance(c.content, DataChoice) and c.name == "sensor":
                    sensor_key = values[i]
                    i += 1

                    sensor_dr = c.content.get_by_name(sensor_key).content
                    sensor_info_ = sensor_info[sensor_key]
                    parsed, nc = self._parse_sensor_record(
                        sensor_dr, sensor_info_, values[i:]
                    )

                    # turn these into Points/Members
                    for rec in parsed:
                        # calc a Z value from rec/sensor and build point
                        point, members = self._build_obs_point(
                            sensor_info_, rec
                        )

                        # add to profile
                        profile_cache.add_obs(
                            sensor_info_, cur_time, point, members
                        )

                    i += nc

        return profile_cache.get_collections()
766403
def _read_weights(self):
        
        weights = []

        grams_per_pound = 453.592

        # Read from each of the sensors
        for ser in self._serials:
            ser.write('W\r')
            ser.flush()
        time.sleep(0.02)
        for ser in self._serials:
            try:
                output_str = ser.readline()
                weight = float(output_str) * grams_per_pound
                weights.append(weight)
            except:
                weights.append(0.0)

        # Log the output
        log_output = ''
        for w in weights:
            log_output +='{:.2f} '.format(w)
        rospy.loginfo(log_output)

        return weights
885308
def _parse(self, registers):
        """"""
        result = {'ip': self.ip, 'connected': True}
        decoder = BinaryPayloadDecoder.fromRegisters(registers,
                                                     byteorder=Endian.Big,
                                                     wordorder=Endian.Little)
        # Register 40001 is a collection of alarm status signals
        b = [decoder.decode_bits(), decoder.decode_bits()]
        reg_40001 = b[1] + b[0]
        # Bits 0-3 map to the monitor state
        monitor_integer = sum(1 << i for i, b in enumerate(reg_40001[:4]) if b)
        result['state'] = options['monitor state'][monitor_integer]
        # Bits 4-5 map to fault status
        fault_integer = sum(1 << i for i, b in enumerate(reg_40001[4:6]) if b)
        result['fault'] = {'status': options['fault status'][fault_integer]}
        # Bits 6 and 7 tell if low and high alarms are active
        low, high = reg_40001[6:8]
        result['alarm'] = options['alarm level'][low + high]
        # Bits 8-10 tell if internal sensor relays 1-3 are energized. Skipping.
        # Bit 11 is a heartbeat bit that toggles every two seconds. Skipping.
        # Bit 12 tells if relays are under modbus control. Skipping.
        # Remaining bits are empty. Skipping.
        # Register 40002 has a gas ID and a sensor cartridge ID. Skipping.
        decoder._pointer += 2
        # Registers 40003-40004 are the gas concentration as a float
        result['concentration'] = decoder.decode_32bit_float()
        # Register 40005 is the concentration as an int. Skipping.
        decoder._pointer += 2
        # Register 40006 is the number of the most important fault.
        fault_number = decoder.decode_16bit_uint()
        if fault_number != 0:
            code = ('m' if fault_number < 30 else 'F') + str(fault_number)
            result['fault']['code'] = code
            result['fault'].update(faults[code])
        # Register 40007 holds the concentration unit in the second byte
        # Instead of being an int, it's the position of the up bit
        unit_bit = decoder.decode_bits().index(True)
        result['units'] = options['concentration unit'][unit_bit]
        decoder._pointer += 1
        # Register 40008 holds the sensor temperature in Celsius
        result['temperature'] = decoder.decode_16bit_int()
        # Register 40009 holds number of hours remaining in cell life
        result['life'] = decoder.decode_16bit_uint() / 24.0
        # Register 40010 holds the number of heartbeats (16 LSB). Skipping.
        decoder._pointer += 2
        # Register 40011 is the sample flow rate in cc / min
        result['flow'] = decoder.decode_16bit_uint()
        # Register 40012 is blank. Skipping.
        decoder._pointer += 2
        # Registers 40013-40016 are the alarm concentration thresholds
        result['low-alarm threshold'] = round(decoder.decode_32bit_float(), 6)
        result['high-alarm threshold'] = round(decoder.decode_32bit_float(), 6)
        # Despite what the manual says, thresholds are always reported in ppm.
        # Let's fix that to match the concentration units.
        if result['units'] == 'ppb':
            result['concentration'] *= 1000
            result['low-alarm threshold'] *= 1000
            result['high-alarm threshold'] *= 1000
        return result
28320
def _get_sensor_names(self):
        """"""
        # if the user didn't tell us what sensors to work with, let's figure it
        # out
        if not self.attrs.get('sensor'):
            # reader finder could return multiple readers
            return set([sensor for reader_instance in self.readers.values()
                        for sensor in reader_instance.sensor_names])
        elif not isinstance(self.attrs['sensor'], (set, tuple, list)):
            return set([self.attrs['sensor']])
        else:
            return set(self.attrs['sensor'])
297670
def sensordata(self, event):
        

        if len(self.datatypes) == 0:
            return

        data = event.data
        timestamp = event.timestamp
        # bus = event.bus

        # TODO: What about multiple busses? That is prepared, but how exactly
        # should they be handled?

        self.log("New incoming navdata:", data, lvl=verbose)

        for name, value in data.items():
            if name in self.datatypes:
                ref = self.datatypes[name]
                self.sensed[name] = ref

                if ref.lastvalue != str(value):
                    # self.log("Reference outdated:", ref._fields)

                    item = {
                        'value': value,
                        'timestamp': timestamp,
                        'type': name
                    }

                    self.referenceframe[name] = value
                    self.referenceages[name] = timestamp

                    # self.log("Subscriptions:", self.subscriptions, ref.name)
                    if ref.name in self.subscriptions:

                        packet = {
                            'component': 'hfos.navdata.sensors',
                            'action': 'update',
                            'data': item
                        }

                        self.log("Serving update: ", packet, lvl=verbose)
                        for uuid in self.subscriptions[ref.name]:
                            self.log("Serving to ", uuid, lvl=events)
                            self.fireEvent(send(uuid, packet),
                                           'hfosweb')

                    # self.log("New item: ", item)
                    sensordata = objectmodels['sensordata'](item)
                    # self.log("Value entry:", sensordata._fields)

                    if ref.record:
                        self.log("Recording updated reference:",
                                 sensordata._fields)
                        sensordata.save()

                    ref.lastvalue = str(value)
                    ref.timestamp = timestamp
            else:
                self.log("Unknown sensor data received!", data, lvl=warn)
630273
def to_dict(self):
        
        return {
            'station_id': self.station_id,
            'timestamp': self.timestamp,
            'temperature': self.temperature,
            'wind_speed': self.wind_speed,
            'wind_gust': self.wind_gust,
            'wind_deg': self.wind_deg,
            'pressure': self.pressure,
            'humidity': self.humidity,
            'rain_1h': self.rain_1h,
            'rain_6h': self.rain_6h,
            'rain_24h': self.rain_24h,
            'snow_1h': self.snow_1h,
            'snow_6h': self.snow_6h,
            'snow_24h': self.snow_24h,
            'dew_point': self.dew_point,
            'humidex': self.humidex,
            'heat_index': self.heat_index,
            'visibility_distance': self.visibility_distance,
            'visibility_prefix': self.visibility_prefix,
            'clouds_distance': self.clouds_distance,
            'clouds_condition': self.clouds_condition,
            'clouds_cumulus': self.clouds_cumulus,
            'weather_precipitation': self.weather_precipitation,
            'weather_descriptor': self.weather_descriptor,
            'weather_intensity': self.weather_intensity,
            'weather_proximity': self.weather_proximity,
            'weather_obscuration': self.weather_obscuration,
            'weather_other': self.weather_other}