Example #1
0
    def test_df3decode_is_valid_min_values(self):
        decoder = Df3Decoder()
        humidity = '00'
        temp = 'FF63'
        pressure = '0000'
        accX = 'FC18'
        accY = 'FC18'
        accZ = 'FC18'
        batt = '0000'
        data = decoder.decode_data(
            '03{humidity}{temp}{pressure}{accX}{accY}{accZ}{batt}00000000BB'.
            format(humidity=humidity,
                   temp=temp,
                   pressure=pressure,
                   accX=accX,
                   accY=accY,
                   accZ=accZ,
                   batt=batt))

        self.assertEqual(data['temperature'], -127.99)
        self.assertEqual(data['pressure'], 500.0)
        self.assertEqual(data['humidity'], 0.0)
        self.assertEqual(data['battery'], 0)
        self.assertEqual(data['acceleration_x'], -1000)
        self.assertEqual(data['acceleration_y'], -1000)
        self.assertEqual(data['acceleration_z'], -1000)
        self.assertNotEqual(data['acceleration'], 0)
def handle_ruuvigateway(client, userdata, msg, payload):
    """
    Topic: ruuvi/24:0a:cc:ee:34:e4/d1:c7:08:22:12:5e
    Payload: {"gw_mac":"24:0a:cc:ee:34:e4","rssi":-71,"aoa":[],"gwts":1606226785,"ts":1606226777,"data":"0201061BFF990405138A35E7C5900014003003F0A3F63B50CED1C70822125E","coords":""}
    :param client:
    :param userdata:
    :param msg:
    :param payload:
    :return:
    """
    topic = msg.topic
    topic_levels = topic.split('/')
    topic_levels.pop(0)
    if len(topic_levels) != 2:
        logging.info("Topic levels don't match 3: {}".format(topic))
        return
    gw_mac, ruuvi_mac = topic_levels
    # Get rid of non-ruuvitag broadcasts
    if re.search("^[cdef]1", ruuvi_mac, re.IGNORECASE) is None:
        logging.debug(f'{ruuvi_mac} is not a RuuviTag (does not start with [cdef])')
        return
    logging.info(f'{topic}: {payload}')
    msgdata = json.loads(payload)
    raw = msgdata['data'][14:]
    if raw.startswith('05'):
        data = Df5Decoder().decode_data(raw)
    elif raw.startswith('03'):
        data = Df3Decoder().decode_data(raw)
    else:
        logging.warning(f"Not supported: {raw}")
        # TODO: add support
        return
    data['rssi'] = msgdata['rssi']
    # Calculate total acceleration
    if data.keys() >= {'acceleration_x', 'acceleration_y', 'acceleration_z'}:
        data['acceleration'] = math.sqrt(
            sum([float(data[x]) ** 2 for x in ['acceleration_x', 'acceleration_y', 'acceleration_z']]))
    epoch = msgdata['ts']
    try:
        if (time.time() - 365 * 24 * 60 * 60) < int(epoch) < (time.time() + 1 * 24 * 60 * 60):
            timestamp = datetime.datetime.utcfromtimestamp(int(epoch))
        else:
            timestamp = time.time()
            logging.warning(f'Got invalid epoch Ruuvitag collector: {epoch}. Using {timestamp} instead.')
        timestamp = pytz.UTC.localize(timestamp)
    except Exception as err:
        logging.info(err)
        return
    # Delete obsolete keys from data
    for key in ['tx_power', 'mac']:
        data.pop(key, None)
    devid = ruuvi_mac.upper()
    extratags = {'gw-id': gw_mac.upper()}
    idata = create_influxdb_obj(devid, client.args.measurement, data, timestamp=timestamp, extratags=extratags)
    logging.debug(json.dumps(idata))
    database = client.args.database
    iclient = get_influxdb_client(database=database)
    iclient.write_points([idata])
Example #3
0
    def test_df3decode_is_valid(self):
        decoder = Df3Decoder()
        data = decoder.decode_data('03291A1ECE1EFC18F94202CA0B5300000000BB')

        self.assertEqual(data['temperature'], 26.3)
        self.assertEqual(data['pressure'], 1027.66)
        self.assertEqual(data['humidity'], 20.5)
        self.assertEqual(data['battery'], 2899)
        self.assertNotEqual(data['acceleration'], 0)
        self.assertEqual(data['acceleration_x'], -1000)
        self.assertNotEqual(data['acceleration_y'], 0)
        self.assertNotEqual(data['acceleration_z'], 0)
Example #4
0
 def test_df3decode_is_valid_notNone(self):
     test_cases = [
         '1502010611FF990403411540C84AFC72FE2FFFC50B89C6',
         '1502010611FF990403411544C850FC72FE2FFFC60B89B9',
         '1502010611FF990403411540C855FC72FE2FFFC30B83C7',
         '1502010611FF990403411539C842FC72FE2FFFC60B89C5',
         '1502010611FF990403421534C813FC72FE2FFFC50B8FD5',
         '1502010611FF990403441536C810FC72FE2FFFC70B83C7',
     ]
     decoder = Df3Decoder()
     for x in test_cases:
         data = decoder.decode_data(x)
         self.assertIsNotNone(data)
def handle_ruuvitag(client, userdata, msg, payload):
    global INFLUX_BUFFER, LAST_SAVE_TIME
    if payload.find(':') < 0:
        logging.info("Payload in wrong format: {}".format(payload))
        return
    topic = msg.topic
    topic_levels = topic.split('/')
    topic_levels.pop(0)
    if len(topic_levels) != 4:
        logging.info("Topic levels don't match 4: {}".format(topic))
        return
    gw_mac, RuuviTag, ruuvi_mac, msg_type = topic_levels
    epoch, raw = payload.split(':')
    # logging.info(topic, payload)
    try:
        timestamp = datetime.datetime.utcfromtimestamp(int(epoch))
        timestamp = pytz.UTC.localize(timestamp)
    except Exception as err:
        logging.info(err)
        return
    if msg_type == 'RAW':
        logging.debug(f'{timestamp.isoformat()} {msg_type} {raw}')
        if raw.startswith('05'):
            data = Df5Decoder().decode_data(raw)
        elif raw.startswith('03'):
            data = Df3Decoder().decode_data(raw)
        else:
            print(f"Not supported: {raw}")
            # TODO: add support
            return
        # print(json.dumps(data, indent=2))
        # Delete obsolete keys from data
        for key in ['data_format', 'tx_power', 'mac']:
            data.pop(key, None)
        devid = ruuvi_mac.replace(':', '')
        extratags = {'gw-id': gw_mac.replace(':', '')}
        idata = create_influxdb_obj(devid, client.args.measurement, data, timestamp=timestamp, extratags=extratags)
        INFLUX_BUFFER.append(idata)
        if (LAST_SAVE_TIME + 5) < time.time():
            save_buffer(client)
decoder = UrlDecoder()
data = decoder.decode_data('AjwYAMFc')
print(data)

if not data['temperature']:
    raise Exception('FAILED')
else:
    print('OK')

#
# Df3Decoder.decode_data
#
print_header('Df3Decoder.decode_data')

decoder = Df3Decoder()
data = decoder.decode_data('03291A1ECE1EFC18F94202CA0B5300000000BB')
print(data)

if not data['temperature']:
    raise Exception('FAILED')
else:
    print('OK')

#
# RuuviTagSensor.get_data_for_sensors
#
print_header('RuuviTagSensor.get_data_for_sensors')

datas = RuuviTagSensor.get_data_for_sensors(search_duratio_sec=15)
print(datas)
Example #7
0
	
now = time.strftime('%Y-%m-%d %H:%M:%S')
print(now+"\n")

dbData = {}
	
for mac, name in tags.items():
	tag = Rtag(mac, name)

	print("Looking for {} ({})".format(tag._name, tag._mac))
	# if weather station
	if dataFormat == '3': # get parsed data

		dataTuple = RuuviTagSensor.convert_data(tag.getData())
		data = Df3Decoder().decode_data(dataTuple[1])
		print ("Data received:", data)
		daten = {}
		daten["name"] = tag._name
		daten["data"] = data

		daten1 = json.dumps(daten, ensure_ascii=False)

		dbData[tag._mac] = {'name': tag._name}
		# add each sensor with value to the lists
		for sensor, value in data.items():
			dbData[tag._mac].update({sensor: value})

	elif dataFormat == '3': # under development
		print ("Data:", tag.getData())