예제 #1
0
파일: logger.py 프로젝트: terop/env-logger
    def read_tag(tag_mac, device):
        """Read data from the RuuviTag with the provided MAC address.
        Returns a dictionary containing the data."""
        sensor = RuuviTag(tag_mac, bt_device=device)
        sensor.update()

        # get latest state (does not get it from the device)
        return sensor.state
def read_data():
    global cachedData
    allData = []
    try:
        for mac in configuredTags.keys():
            sensor = RuuviTag(mac)
            sensor.update()
            tagData = sensor.state
            tagData['name'] = configuredTags[mac]
            allData.append(tagData)
    except:
        sys.exit(1)
    cachedData.clear()
    return allData
예제 #3
0
    def poll(sensor, results):

        """
        Polls a RuuviTag using BT

        Returns:
            True
        """

        tag_instance = RuuviTag(sensor.mac)

        # update state from the device
        state = tag_instance.update()

        if state:

            # populate the sensor results
            if state.get('temperature'):
                results.set_result(sensor, 'temperature', state['temperature'])

            if state.get('humidity'):
                results.set_result(sensor, 'humidity', state['humidity'])

            if state.get('pressure'):
                results.set_result(sensor, 'pressure', state['pressure'])

            if state.get('identifier'):
                # This is NOT the configured NAME
                results.set_result(sensor, 'identifier', state['identifier'])

        else:
            results.inactive_sensors.append(sensor)

        return True
예제 #4
0
def ruuviScan():
    sensor = RuuviTag(sensor_mac)
    state = sensor.update()
    json_str = '{"uid": "' + str(sensor_mac) + '", "payload": ' + json.dumps(
        state) + '}'
    print(json_str)
    sender.send_message(json_str)
    time.sleep(2)
    def test_tag_update_is_valid(self):
        tag = RuuviTag('48:2C:6A:1E:59:3D')

        state = tag.state
        self.assertEqual(state, {})

        state = tag.update()
        self.assertEqual(state['temperature'], 24)
        self.assertEqual(state['pressure'], 995)
        self.assertEqual(state['humidity'], 30)
예제 #6
0
def log_reading(mac, logfile=None):
    """Reads the state of a Ruubitag and writes it into a logfile if provided.
    The logfile is created if it doesn't already exist.

    # Arguments
        mac: str. MAC-address of the ruuvitag
        logfile: str or None (default None). Path to the logfile. If `None`,
            the reading is just returned and nothing gets logged.
    """
    sensor = RuuviTag(mac)
    sensor.update()
    reading = sensor.state
    reading['time'] = str(datetime.datetime.now())
    if logfile:
        maybe_create_log(logfile)
        with open(logfile, 'a', newline='\n') as f:
            dw = csv.DictWriter(f, fieldnames=_fields, extrasaction='ignore')
            dw.writerow(reading)
    return reading
예제 #7
0
from ruuvitag_sensor.ruuvitag import RuuviTag
import os
import datetime
import time

sensor = RuuviTag('D7:05:12:28:73:D9')
i = 0
while 1:
    print(i)
    i = i + 1
    # update state from the device
    state = sensor.update()

    # get latest state (does not get it from the device)
    state = sensor.state

    for var in state:
        print(var + " : " + str(state[var]))

    date = datetime.datetime.now()
    print("Ano : " + str(date.year))
    print("Mês : " + str(date.month))
    print("dia : " + str(date.day))
    print("hora : " + str(date.hour))
    print("minuto : " + str(date.minute))
    print("segundo : " + str(date.second))
    print("\n\n--------------------------\n\n")
예제 #8
0
    con.close()
    print('insert ruuvitagdata database')


# Change here your own device's mac-address
tagList = [
    'F6:DB:7F:5E:C8:62', 'F1:15:2E:FC:0C:3A', 'EF:28:0A:7D:E1:1D',
    'E9:7A:A6:0B:51:1E', 'F0:DE:F8:93:AF:A2'
]
print('Starting')
tz = pytz.timezone('Europe/Helsinki')

while True:

    for tag in tagList:
        sensor = RuuviTag(tag)
        data = sensor.update()

        insertRuuvitagData(data['temperature'], data['pressure'],
                           data['humidity'], tag,
                           datetime.now(tz=tz).strftime('%Y-%m-%d %H:%M'))
        print(tag)

# Wait for 60 seconds and start over again
    try:
        time.sleep(300)
    except KeyboardInterrupt:
        # When Ctrl+C is pressed execution of the while loop is stopped
        print('Exit')
        break
예제 #9
0
datas = RuuviTagSensor.get_data_for_sensors(list(datas.keys())[0],
                                            search_duratio_sec=15)
print(datas)

if not datas:
    raise Exception('FAILED')
else:
    print('OK')

#
# RuuviTag.update
#
print_header('RuuviTag.update')

tag = RuuviTag(list(datas.keys())[0])
tag.update()
print(tag.state)

if not tag.state:
    raise Exception('FAILED')
else:
    print('OK')

#
# RuuviTagSensor.get_datas
#
print_header('RuuviTagSensor.get_datas')

flag = RunFlag()

예제 #10
0
def main_page():
	if request.method == "POST":
		selected_report = request.form['selected_report']
		days_data       = request.form['days_data']
	else:
		selected_report = 'temp_over_time'
		days_data       = '1'

	record_count = DBQuery("SELECT COUNT(*) FROM TEMP_HISTORY WHERE DATE_READ > datetime('now','-{} day')".format(days_data),True)

	if record_count==0:
		days_data='30'

	if days_data=='1':
		time_name = '24 Hours'
	elif days_data=='3':
		time_name = '72 Hours'
	elif days_data=='7':
		time_name = '7 Days'
	else:
		time_name = days_data+' Days'


	weather_url  = 'https://api.openweathermap.org/data/2.5/weather?zip={},us&appid={}'.format(cfg.zip_code,cfg.weather_api_key)
	r            = requests.get(weather_url)
	outside_temp = convCel(r.json()['main']['temp'])
	outside_hum  = r.json()['main']['humidity']

	results = {}

	for name, mac in cfg.sensors.items():
		sensor   = RuuviTag(mac)
		state    = sensor.update()
		temp     = convCel(sensor.state['temperature'])
		humidity = sensor.state['humidity']
		results.update({name:{'temp':temp,'humidity':humidity}})

	current_temp_diff = round(results['ac_return']['temp'] - results['ac_vent']['temp'],2)

	ac_is_running = True if current_temp_diff>=10 else False

	print(ac_is_running)

	#SETTING COLOR BASED ON VALUE
	if current_temp_diff>=13 and current_temp_diff<16:
		current_temp_html = '<span style="color:orange;">{}</span>'.format(current_temp_diff)
	elif current_temp_diff>=16:
		current_temp_html = '<span style="color:green;">{}</span>'.format(current_temp_diff)
	else:
		current_temp_html = '<span style="color:red;">{}</span>'.format(current_temp_diff)

	db_sensors = [x[0] for x in DBQuery("SELECT DISTINCT SENSOR_NAME FROM TEMP_HISTORY WHERE DATE_READ > datetime('now','-{} day')".format(days_data))]

	min_max_temps = {}
	for s in db_sensors:
		max_hum  = DBQuery("SELECT MAX(HUMIDITY) FROM TEMP_HISTORY WHERE SENSOR_NAME='{}' AND DATE_READ > datetime('now','-{} day')".format(s,days_data),True)
		min_hum  = DBQuery("SELECT MIN(HUMIDITY) FROM TEMP_HISTORY WHERE SENSOR_NAME='{}' AND DATE_READ > datetime('now','-{} day')".format(s,days_data),True)
		avg_hum  = round(DBQuery("SELECT AVG(HUMIDITY) FROM TEMP_HISTORY WHERE SENSOR_NAME='{}' AND DATE_READ > datetime('now','-{} day')".format(s,days_data),True),2)
		max_temp = DBQuery("SELECT MAX(TEMP) FROM TEMP_HISTORY WHERE SENSOR_NAME='{}' AND DATE_READ > datetime('now','-{} day')".format(s,days_data),True)
		min_temp = DBQuery("SELECT MIN(TEMP) FROM TEMP_HISTORY WHERE SENSOR_NAME='{}' AND DATE_READ > datetime('now','-{} day')".format(s,days_data),True)
		avg_temp = round(DBQuery("SELECT AVG(TEMP) FROM TEMP_HISTORY WHERE SENSOR_NAME='{}' AND DATE_READ > datetime('now','-{} day')".format(s,days_data),True),2)
		min_max_temps.update({s:{
									'max_temp':max_temp,
									'min_temp':min_temp,
									'avg_temp':avg_temp,
									'max_humidity':max_hum,
									'min_humidity':min_hum,
									'avg_humidity':avg_hum
										}
									})

	m_m = ['MAX','MIN','AVG']
	min_max_diff = {}
	for m in m_m:
		q_min_max_diff = """
					SELECT COALESCE({}(t1.TEMP - (
										SELECT 	t2.TEMP 
										FROM 	TEMP_HISTORY AS t2 
										WHERE 	t1.DATE_READ=t2.DATE_READ 
												AND t2.SENSOR_NAME='ac_vent'
												)),0)
					FROM 	TEMP_HISTORY AS t1 
					WHERE 	t1.SENSOR_NAME='ac_return'
							AND DATE_READ > datetime('now','-{} day')
					""".format(m,days_data)
		temp = round(DBQuery(q_min_max_diff,True),2)
		min_max_diff.update({m:temp})

	#DETERMINING LAST TOTAL RUNTIME
	ac_return_ids= [x[0] for x in DBQuery("SELECT ID FROM TEMP_HISTORY WHERE SENSOR_NAME='ac_return' AND DATE_READ > datetime('now','-{} day') ORDER BY DATE_READ DESC".format(days_data))]
	count     = 1
	last_date = ''
	continuous_ids = []
	temp_list = []
	for i in ac_return_ids:
		if count==1:
			last_date = DBQuery('SELECT DATE_READ FROM TEMP_HISTORY WHERE ID = {}'.format(i),True)
			continuous_ids.append(i)
			count+=1
		else:
			cur_date = DBQuery('SELECT DATE_READ FROM TEMP_HISTORY WHERE ID = {}'.format(i),True)
			delta = __datetime(last_date) - __datetime(cur_date)
			delta = delta.total_seconds()
			print(last_date,cur_date)
			temp_list.append(delta-300)
			last_date = cur_date
			continuous_ids.append(i)
			if delta>=310:
				break
	print(temp_list)
	run_start_date = DBQuery("SELECT COALESCE(MAX(DATE_READ),'1970-01-01 13:00:00') FROM TEMP_HISTORY WHERE ID IN ({})".format(','.join([str(x) for x in continuous_ids])),True)
	run_end_date   = DBQuery("SELECT COALESCE(MIN(DATE_READ),'1970-01-01 12:00:00') FROM TEMP_HISTORY WHERE ID IN ({})".format(','.join([str(x) for x in continuous_ids])),True)
	max_ac_return  = DBQuery("SELECT COALESCE(MAX(TEMP),0) FROM TEMP_HISTORY WHERE SENSOR_NAME='ac_return' AND DATE_READ='{}'".format(run_end_date),True)
	min_ac_return  = DBQuery("SELECT COALESCE(MIN(TEMP),0) FROM TEMP_HISTORY WHERE SENSOR_NAME='ac_return' AND DATE_READ='{}'".format(run_start_date),True)

	run_delta  = __datetime(run_start_date) - __datetime(run_end_date)
	run_delta  = run_delta.total_seconds()
	ac_runtime = sec2humanTime(run_delta)

	total_degrees_cooled = max_ac_return - min_ac_return

	degrees_over_time = coolAgainstTime(total_degrees_cooled,run_delta)

	#RENDER SElECTED GRAPH REPORT
	if selected_report=='temp_over_time':
		chart = pygal.Line(style=custom_style,x_label_rotation=20)
		chart.title = 'Tempature Over {}'.format(time_name)

		labels = [x[0] for x in DBQuery("SELECT DISTINCT strftime('%m/%d %Hhrs %Mmins',DATE_READ) FROM TEMP_HISTORY WHERE SENSOR_NAME='attic' AND DATE_READ > datetime('now','-{} day')".format(days_data))]
		chart.x_labels = labels

		for s in db_sensors:
			sensor_name  = s 
			sensor_temps = [x[0] for x in DBQuery("SELECT TEMP FROM TEMP_HISTORY WHERE SENSOR_NAME='{}' AND DATE_READ > datetime('now','-{} day')".format(sensor_name,days_data))]
			chart.add(sensor_name,sensor_temps)
	elif selected_report=='diff_over_time':
		chart = pygal.Line(fill=True, interpolate='cubic', style=custom_style)
		chart.title = 'Tempature Differential Over {}'.format(time_name)
		labels = [x[0] for x in DBQuery("SELECT DISTINCT strftime('%m/%d %Hhrs',DATE_READ) FROM TEMP_HISTORY WHERE SENSOR_NAME='attic' AND DATE_READ > datetime('now','-{} day')".format(days_data))]
		chart.x_labels = labels
		data_query = """
					SELECT t1.TEMP - (
										SELECT 	t2.TEMP 
										FROM 	TEMP_HISTORY AS t2 
										WHERE 	t1.DATE_READ=t2.DATE_READ 
												AND t2.SENSOR_NAME='ac_vent'
												) 
					FROM 	TEMP_HISTORY AS t1 
					WHERE 	t1.SENSOR_NAME='ac_return'
							AND DATE_READ > datetime('now','-{} day')
					""".format(days_data)
		sensor_temps = [x[0] for x in DBQuery(data_query)]
		chart.add('Temp Diff',sensor_temps)


	graph_data = chart.render_data_uri()
	post_url   = url_for('main_page')

	last_update = DBQuery("SELECT DATE_READ FROM TEMP_HISTORY ORDER BY DATE_READ DESC LIMIT 1",True)

	last_update_delta = __datetime(now_date_time()) - __datetime(last_update)
	last_update       = sec2humanTime(last_update_delta.total_seconds()) 

	return render_template('pygal_reports.html',graph_data=graph_data,outside_temp=outside_temp,
							outside_hum=outside_hum,results=results,min_max_temps=min_max_temps,
							current_temp_html=current_temp_html,post_url=post_url,
							selected_report=selected_report,min_max_diff=min_max_diff,
							days_data=days_data,ac_runtime=ac_runtime,degrees_over_time=degrees_over_time,
							ac_is_running=ac_is_running,last_update=last_update)
예제 #11
0
class MyRuuvi():

    def __init__(self, mac_addr='E8:C7:D7:F2:4B:47', bt_device=''):
        self._sensor = RuuviTag(mac_addr, bt_device)
        self._data_count = 0

    ### Properties ###
    @property
    def mac(self):
        return self._sensor.mac

    @property
    def state(self):
        return self._sensor.state

    @property
    def temp(self):
        return self.state['temperature']

    @property
    def humid(self):
        return self.state['humidity']

    @property
    def press(self):
        return self.state['pressure']

    @property
    def acc(self):
        return self.state['acceleration'] / 1000

    @property
    def acc_x(self):
        return self.state['acceleration_x'] / 1000

    @property
    def acc_y(self):
        return self.state['acceleration_y'] / 1000

    @property
    def acc_z(self):
        return self.state['acceleration_z'] / 1000

    @property
    def bat(self):
        return self.state['battery']

    @property
    def dataformat(self):
        return self.state['data_format']

    @property
    def elev_x(self):
        return math.acos(self.acc_x / self.acc) * 180 / math.pi

    @property
    def elev_y(self):
        return math.acos(self.acc_y / self.acc) * 180 / math.pi

    @property
    def elev_z(self):
        return math.acos(self.acc_z / self.acc) * 180 / math.pi

    @property
    def rssi(self):
        return self.state['rssi']

    @property
    def data_count(self):
        return self._data_count

    ### Methods ###
    def update(self):
        self._sensor.update()
        self._data_count += 1

    def print_to_shell(self):
        ''' Printing collected data from saved state to shell '''

        os.system('clear')
        print('\n\r')
        print(str(datetime.now()))
        print('Sensor:\t{}'.format(self.mac))
        print('-'*30)
        print('Temperature:\t{:.2f}\t°C'.format(self.temp))
        print('Humidity:\t{:.2f}\t%'.format(self.humid))
        print('Pressure:\t{:.2f}\thPa'.format(self.press))
        print('-'*30)
        print('Acceleration:\t{:.3f}\tG'.format(self.acc))
        print('X:\t\t{:.3f}\tG'.format(self.acc_x))
        print('Y:\t\t{:.3f}\tG'.format(self.acc_y))
        print('Z:\t\t{:.3f}\tG'.format(self.acc_z))
        print('-'*30)
        print('Elevation X:\t{:.0f}\t°'.format(self.elev_x))
        print('Elevation Y:\t{:.0f}\t°'.format(self.elev_y))
        print('Elevation Z:\t{:.0f}\t°'.format(self.elev_z))
        print('-' * 30)
        print('RSSI:\t\t{}\tdBm'.format(self.rssi))
        print('Battery:\t{:.0f}\tmV'.format(self.bat))
        print('Data Count:\t{}'.format(self.data_count))