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")
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 = []
def status_info(): try: CO2 = sensors.get(sensors.CO2)[0].read_val() temperature, humidity, num_cycles_wrong = sensors.get( sensors.TempHum)[0].read_val() particles = sensors.get(sensors.Particles_pms7003)[0].read_val() info_data = re.split( '\n|:', controls.get_status_str() + sensors.get_status_str()) info_data = list(filter(None, info_data)) res_info = "<trt><td>Update time</td><td>" + \ get_time(datetime.now())+"</td></tr>" for counter in range(0, len(info_data) - 1, 2): res_info += "<tr>" res_info += "<td>" + info_data[counter] + "</td>" res_info += "<td>" + info_data[counter + 1].replace(';', ':') + "</td>" res_info += "</tr>" out_particles = [] out_particles.append(particles['data']['8']) out_particles.append(particles['data']['10']) out_particles.append(particles['data']['12']) return render_template('status_info.html', temp=str("%.1f" % temperature), hum=str("%.1f" % humidity), co2=str(CO2), particles=out_particles, status_info=res_info) except Exception as e: my_logging.logger.exception("status_info chart error") return "Unable to process status_info chart: " + traceback.format_exc( ), 400 finally: pass
def __init__(self): super().__init__(self.__class__.__name__) self.control_sensors = sensors.get(sensors.Particles_pms7003) if len(self.control_sensors) > 1: raise ValueError("now we are supporting only 1 particles sensor") self.control_devices = []
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)
def __init__(self): super().__init__(self.__class__.__name__) self.control_sensors = sensors.get(sensors.CO2) if len(self.control_sensors) > 1: raise ValueError("now we are supporting only 1 CO2 sensor")
def exec_command(command): my_logging.logger.info("command:" + command) # devices control if command in [ "вентилятор", "включи вентилятор", "включить вентилятор", "выключи вентилятор", "выключить вентилятор" ]: say_ok(command) controls.get(controls.control_TempHum).switch(external_command=True) elif command in ["вентилятор авто"]: say_ok(command) controls.get(controls.control_TempHum).set_auto() elif command in [ "розетка", "включи розетку", "включить розетку", "выключи розетку", "выключить розетку" ]: say_ok(command) controls.get(controls.control_Outlet).switch(external_command=True) elif command in ["розетка авто"]: say_ok(command) controls.get(controls.control_Outlet).set_auto() elif command in [ "кондиционер", "включи кондиционер", "выключи кондиционер", "жарко" ]: say_ok(command) controls.get(controls.control_ConditionerControl_IR).switch( external_command=True) elif command in ["кондиционер авто"]: say_ok(command) controls.get(controls.control_ConditionerControl_IR).set_auto() elif command in ["включи все"]: say_ok(command) controls.enable() elif command in ["выключи все"]: say_ok(command) controls.disable() elif command in ["все авто"]: say_ok(command) controls.set_auto() # noise control elif command in ["тихо"]: say_ok(command) controls.get(controls.control_NoisyActions).force_silent = True elif command in ["говори"]: say_ok(command) controls.get(controls.control_NoisyActions).force_silent = False #temperature and humidity and co2 elif command in [ "температура", "какая температура", "температура в комнате" ]: temperature, humidity, num_cycles_wrong = sensors.get( sensors.TempHum)[0].read_val() temp_str = "{:.1f}".format(temperature).replace('.', ',') TTS.say("Температура в комнате: " + temp_str + " градусов") if temperature < 22: TTS.say("прохладно, оденься потеплее") elif command in ["влажность", "какая влажность", "влажность в комнате"]: temperature, humidity, num_cycles_wrong = sensors.get( sensors.TempHum)[0].read_val() hum_str = "{:.1f}".format(humidity).replace('.', ',') TTS.say("Влажность в комнате: " + str(hum_str) + " %") if humidity < 35: TTS.say("суховато, можно увлажнить") elif command in [ "углекислый газ", "газ", "какой уровень углекислого газа" ]: co2 = sensors.get(sensors.CO2)[0].read_val() TTS.say("Уровень углекислого газа в комнате: " + str(co2) + " ppm") if co2 > 800: TTS.say("можно открыть окно") elif command in ["частицы", "загрязнение"]: particles = sensors.get(sensors.Particles_pms7003)[0].read_val() pm25 = particles['data']['10'] TTS.say("Частиц 2.5 в комнате: " + str(pm25[1]) + "микрограмм на кубометр") if pm25[1] > 100: TTS.say("надевай маску, загрязнение высокое !") #time, weather,news elif command in ["время", "сколько время", "сколько времени"]: TTS.say('{0:%H:%M}'.format(datetime.now())) elif command in ["дата", "какой день", "какой сегодня день"]: dt = format_datetime(datetime.now(), "dd MMMM HH:mm", locale='ru') TTS.say("Сейчас : " + dt) elif command in [ "погода", "прогноз погоды", "что на улице", "что с погодой" ]: TTS.say(utils.common.get_weather_desc()) elif command in ["новости", "что нового"]: count = 1 TTS.say("Новости от РосБизнесКонсалтинг:") for news in utils.common.get_news(): TTS.say(f"Новость {count}: {news}") count += 1 # misc, just for fun elif command in ["отзовись", "привет"]: sound.play_command("hello") elif command in ["спокойной ночи", "спокойной"]: TTS.say("Спокойной ночи дорог'ой") elif command in ["доброе утро", "доброе", "с добрым утром"]: TTS.say("С добрым утром дорог'ой") elif command in ["как дела", "как жизнь"]: TTS.say("Отлично, температура " + str(utils.common.get_cpu_temperature()) + ", у тебя как ?") elif command in ["как тебя зовут", "твое имя", "кто ты"]: TTS.say( "я автоматизировнный помощник по дому, пока не до конца доделанный" ) # wake up elif command in [ "разбуди завтра в 7", "разбуди завтра в 7:00", "разбуди в 7:00" ]: next = datetime.now() + timedelta(days=1) next = next.replace(hour=7) wakeup_list.append(next) TTS.say("Хорошо, разбужу в 7") elif command in [ "разбуди завтра в 8", "разбуди завтра в 8:00", "разбуди в 8:00" ]: next = datetime.now() + timedelta(days=1) next = next.replace(hour=8) wakeup_list.append(next) TTS.say("Хорошо, разбужу в 8") elif command in ["отмена", "отмена комманды"]: TTS.say("всего хорошего") #unknown, error else: if not TTS.say("непонятная комманда : " + command): sound.play_command("repeat") my_logging.logger.info("unknown command: " + command)