Example #1
0
def get(id, device):
    id = str(id)
    if devices.get(id) is None:
        return NoContent, 404
    devices[id] = device

    return devices[id]
Example #2
0
def _last_read(book, exclude_device = None):
	lr_list = []
	for lr in annotations.list_last_read(book.asin):
		if lr.device == exclude_device:
			continue
		device = devices.get(lr.device)
		lr_list.append(_LAST_READ % (lr.timestamp * 1000, 'US', device_lto(device), lr.pos, lr.device))
	xml = '<?xml version="1.0" encoding="UTF-8"?><book>' + ''.join(lr_list) + '</book>'
	return DummyResponse(headers = { 'Content-Type': 'text/xml;charset=UTF-8' }, data = bytes(xml, 'UTF-8'))
Example #3
0
 def __init__(self):
     super().__init__(self.__class__.__name__)
     self.control_devices.extend(devices.get(devices.WaterPump))
     self.control_sensors.extend(sensors.get(sensors.Moisture))
     if len(self.control_sensors) > 1:
         raise ValueError("now we are supporting only 1 Moisture sensor")
     self.control_sensors.extend(sensors.get(sensors.WaterLevelDrop))
     if len(self.control_sensors) > 2:
         raise ValueError(
             "now we are supporting only 1 WaterLevelDrop sensor")
Example #4
0
 def update_conf(self, conf):
     new_name = None
     new_clock = None
     new_output = None
     new_time_table = None
     try:
         new_name = conf['name']
         new_clock = devices.get(conf['clock'])
         new_output = devices.get(conf['output'])
         new_time_table = []
         for t, v in conf['schedule'].items():
             h, m, s = t.split(':')
             sec = int(h) * 3600 + int(m) * 60 + int(s)
             new_time_table.append([sec, v])
         new_time_table.sort()
     except:
         raise Exception()
     self.name = new_name
     self.clock = new_clock
     self.output = new_output
     self.time_table = new_time_table
Example #5
0
def devices():
	if request.method == 'GET':
		return render_template('devices.html', devices=dev.get())
	else:
		if 'username' in session:
			if 'on' in request.form or 'off' in request.form:
				device = request.form.get('on', request.form.get('off'))
				target_state = True if 'on' in request.form else False
				if dev.get(device).get('writeable') or session['admin']:
					dev.power(device, target_state)
					target_str = 'up' if target_state else 'down'
					flash('Device "%s" powered %s.' % (device, target_str), 'success')
			elif 'delete' in request.form:
				#FIXME: log
				if session.get('admin'):
					device = request.form.get('delete')
					dev.remove(device)
					flash('Device "%s" deleted.' % device, 'success')
			elif 'add' in request.form:
				return redirect(url_for('device_new'))
			elif 'edit' in request.form:
				return redirect(url_for('device_edit', device=request.form.get('edit')))
			elif 'set' in request.form:
				name = request.form.get('set')
				title = request.form.get('title')
				action = request.form.get('action')
				site_code = request.form.get('site_code')
				device_code = request.form.get('device_code')
				writeable = True if request.form.get('writeable') == 'on' else False
				try:
					power = dev.get(name).get('power')
				except:
					power = False
				#FIXME: log
				dev.set(name=name, title=title, site_code=site_code, device_code=device_code, writeable=writeable, power=power)
				if action == 'add':
					flash('Device "%s" created.' % (name), 'success')
				else:
					flash('Device "%s" updated.' % (name), 'success')
		return redirect(url_for('devices'))
Example #6
0
    def __init__(self):
        super().__init__(self.__class__.__name__)
        self.control_devices = devices.get(devices.ThermalFan)
        self.control_sensors = sensors.get(sensors.TempHum)

        self.auto_mode = True
        self.check_temp = config.DEF_CHECK_TEMP

        if len(self.control_sensors) > 1:
            raise ValueError("now we are supporting only 1 temperature sensor")

        # if no devices - no reason to work
        if len(self.control_devices) == 0 or len(self.control_sensors) == 0:
            self.control_sensors = []
            self.control_devices = []
Example #7
0
def _update_annotations(device, x_items):
	was_updated = False

	for lr in annotations.get_last_read_updates(device):
		source_device = devices.get(lr.device)
		source_device_alias = (source_device.alias or source_device.serial) if source_device else lr.device
		_add_item(x_items, 'UPD_LPRD', 'EBOK', key = lr.asin, priority = 1100, sequence = lr.pos,
				source_device = source_device_alias, lto = device_lto(source_device), annotation_time_utc = lr.timestamp)
		was_updated = True

	for asin in annotations.get_annotation_updates(device):
		_add_item(x_items, 'UPD_ANOT', 'EBOK', key = asin, priority = 1100)
		was_updated = True

	return was_updated
Example #8
0
def _last_read(book, exclude_device = None):
	lr_list = []
	for lr in annotations.list_last_read(book.asin):
		if lr.device == exclude_device:
			continue
		device = devices.get(lr.device)
		alias = device.alias if device else lr.device
		alias = lr.device if alias is None \
					else alias.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;').replace('"', '&quot;').replace('\'', '&apos;')
		lr_list.append(_LAST_READ % (lr.timestamp * 1000, device_lto(device), lr.pos, alias))
	if lr_list:
		xml = '<?xml version="1.0" encoding="UTF-8"?><book>' + ''.join(lr_list) + '</book>'
	else:
		xml = '<?xml version="1.0" encoding="UTF-8"?><book/>'
	return DummyResponse(headers = { 'Content-Type': 'text/xml;charset=UTF-8' }, data = bytes(xml, 'UTF-8'))
Example #9
0
def _last_read(book, exclude_device=None):
    lr_list = []
    for lr in annotations.list_last_read(book.asin):
        if lr.device == exclude_device:
            continue
        device = devices.get(lr.device)
        alias = device.alias if device else lr.device
        alias = lr.device if alias is None \
           else alias.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;').replace('"', '&quot;').replace('\'', '&apos;')
        lr_list.append(
            _LAST_READ %
            (lr.timestamp * 1000, device_lto(device), lr.pos, alias))
    if lr_list:
        xml = '<?xml version="1.0" encoding="UTF-8"?><book>' + ''.join(
            lr_list) + '</book>'
    else:
        xml = '<?xml version="1.0" encoding="UTF-8"?><book/>'
    return DummyResponse(headers={'Content-Type': 'text/xml;charset=UTF-8'},
                         data=bytes(xml, 'UTF-8'))
Example #10
0
def _update_annotations(device, x_items):
    was_updated = False

    for lr in annotations.get_last_read_updates(device):
        source_device = devices.get(lr.device)
        source_device_alias = (source_device.alias or source_device.serial
                               ) if source_device else lr.device
        _add_item(x_items,
                  'UPD_LPRD',
                  'EBOK',
                  key=lr.asin,
                  priority=1100,
                  sequence=lr.pos,
                  source_device=source_device_alias,
                  lto=device_lto(source_device),
                  annotation_time_utc=lr.timestamp)
        was_updated = True

    for asin in annotations.get_annotation_updates(device):
        _add_item(x_items, 'UPD_ANOT', 'EBOK', key=asin, priority=1100)
        was_updated = True

    return was_updated
 def __init__(self):
     super().__init__(self.__class__.__name__)
     self.control_devices = devices.get(devices.Outlet)
Example #12
0
def callback_inline(call):
    try:
        if call.message:
            if call.data == "measure_water":
                WateringControl.do_watering("measure_water", 5, False)
                send_msg_bot_long_check(call.message.chat.id,
                                        WateringControl.get_status_str())
            elif call.data == "do_watering_now":
                WateringControl.do_watering("force from telegram")
                bot.send_message(call.message.chat.id, "Watering done !")
            elif call.data == "get_status":
                bot.send_message(
                    call.message.chat.id,
                    controls.get_status_str() + sensors.get_status_str())
            elif call.data == "manual_run_stop_fan":
                controls.get(
                    controls.control_TempHum).switch(external_command=True)
                bot.send_message(
                    call.message.chat.id,
                    controls.get(controls.control_TempHum).get_status_str())
            elif call.data == "auto_fan":
                controls.get(controls.control_TempHum).set_auto()
                bot.send_message(call.message.chat.id, "Fans auto !")
            elif call.data == "on_off_outlet":
                controls.get(
                    controls.control_Outlet).switch(external_command=True)
                bot.send_message(
                    call.message.chat.id,
                    devices.get(devices.Outlet)[0].get_status_str())
            elif call.data == "on_off_conditioner":
                controls.get(controls.control_ConditionerControl_IR).switch(
                    external_command=True)
                bot.send_message(
                    call.message.chat.id,
                    devices.get(devices.IrConditioner)[0].get_status_str())
            elif call.data == "auto_outlet":
                controls.get(controls.control_Outlet).set_auto()
                bot.send_message(call.message.chat.id, "Outlet auto !")
            elif call.data == "wake_my_pc":
                send_magic_packet('7C:05:07:11:40:26')
                send_magic_packet('7c:05:07:11:40:26')
                bot.send_message(call.message.chat.id, "Command sended !")
            elif call.data == "check_light":
                bot.send_message(
                    call.message.chat.id,
                    sensors.get(sensors.Light)[0].get_status_str())
            elif call.data == "make_camera_photo":
                devices.get(devices.Camera)[0].do_photo()
                photo = open('/dev/shm/camera.jpg', 'rb')
                bot.send_photo(call.message.chat.id, photo)
            elif call.data == "make_co2_graph":
                make_co2_graph()
                photo = open('/dev/shm/plot.png', 'rb')
                bot.send_photo(call.message.chat.id, photo)
            elif call.data == "make_temp_hum_graph":
                make_temp_hum_graph()
                photo = open('/dev/shm/plot.png', 'rb')
                bot.send_photo(call.message.chat.id, photo)
            elif call.data == "make_particles_graph":
                make_particles_graph()
                photo = open('/dev/shm/plot.png', 'rb')
                bot.send_photo(call.message.chat.id, photo)
            elif call.data == "get_last_10_watering_dates":
                values = database.get_last_10_watering_info()
                bot.send_message(call.message.chat.id, values)
            else:
                send_msg_bot_long_check(str(config.my_telegram_id),
                                        "unknown call data: " + call.data,
                                        get_markup())
                my_logging.logger.error("unknown call.data " + call.data)
        elif call.inline_message_id:
            if call.data == "test":
                bot.edit_message_text(inline_message_id=call.inline_message_id,
                                      text="forbidden !!!")
    except Exception as e:
        my_logging.logger.exception("callback_inline:" + str(e))
        pass
    finally:
        filenames = ["/dev/shm/plot.png", "/dev/shm/camera.jpg"]
        for filename in filenames:
            if os.path.exists(filename):
                os.remove(filename)
Example #13
0
def get_devices():
    device = devices.get()
    #device = 'OK!'
    #print(device)
    return device
Example #14
0
FINAL_DATA = list()

def save():
    if os.path.exists('phone_data.json'):
        print('Updating file...')
        os.remove('phone_data.json')
        json.dump(FINAL_DATA, open('phone_data.json', 'w'), indent=4)
        print('Updated!')
    else:
        print('Saving to file...')
        json.dump(FINAL_DATA, open('phone_data.json', 'w'), indent=4)
        print('Saved!')


brands = brands.get()
# for each brand get devices
for brand in brands:
    d = devices.get(brand)
    FINAL_DATA.append({
        'name': brand['name'],
        'device_count': brand['device_count'],
        'href': brand['href'],
        'devices': d
    })
    save()

print("Scraping Data Finished!!!")
if os.path.exists('phone_data.json'):
    os.remove('phone_data.json')
json.dump(FINAL_DATA, open('phone_data.json', 'w'), indent=4)
print("Saved File!")
 def __init__(self):
     super().__init__(self.__class__.__name__)
     self.control_devices = devices.get(devices.IrConditioner)
Example #16
0
def device_edit(device):
	if not session.get('admin'):
		flash("You don't have permission to do that.", 'error')
		return redirect(url_for('devices'))
	return render_template('device_form.html', device=dev.get(device), name=device)