Дописал немного

This commit is contained in:
Your Name
2019-06-05 21:14:13 +03:00
parent 9f3e1cb781
commit 88c48eab6f
18 changed files with 99 additions and 180 deletions
-129
View File
@@ -1,129 +0,0 @@
import appdaemon.plugins.hass.hassapi as hass
import json
#
# Yandex.Alice integration
#
# Args:
#
#
#
#
# None
#
# Release Notes
#
# Version 1.0:
# Initial Version
class YandexAlice(hass.Hass):
def initialize(self):
self.register_endpoint(self.api_call)
self.sessionStorage = {}
self.log('started')
def api_call(self, request):
# js = json.dumps(request, indent=4, sort_keys=True)
# self.log('Request: %s' % js)
response = {
"version": request['version'],
"session": request['session'],
"response": {
"end_session": False
}
}
self.handle_dialog(request, response)
# self.log('response: {}'.format(response['response']['text']))
# js = json.dumps(response, indent=4, sort_keys=True)
# self.log('Response: %s' % js)
return response, 200
# Функция для непосредственной обработки диалога.
def handle_dialog(self, req, res):
user_id = req['session']['user_id']
command = req['request']['original_utterance'].lower()
command_password = req['request']['command'].lower().replace(" ", "")
password = "123456"
self.log('command: {}'.format(command))
if command == "ping":
res['response']['text'] = 'pong =)'
return
if user_id not in self.sessionStorage:
self.sessionStorage[user_id] = { 'auth': False }
res['response']['text'] = 'Привет. Я могу управлять твоим домом. Для начала работы назови пароль.'
return
if command_password != password and self.sessionStorage[user_id]['auth'] == False:
res['response']['text'] = 'Неправильный пароль: %s.' % command_password
return
# Обрабатываем ответ пользователя.
if command_password == password and self.sessionStorage[user_id]['auth'] == False:
self.sessionStorage[user_id]['auth'] = True
res['response']['text'] = 'Вы авторизованы.'
return
self.handle_command(req, res)
return
# Функция возвращает две подсказки для ответа.
def handle_command(self, req, res):
user_id = req['session']['user_id']
command = req['request']['original_utterance'].lower()
command = command.replace('попроси управление домом', '').strip()
command = command.replace('алиса', '').strip()
isAuth = self.sessionStorage[user_id]['auth'] == True
if not isAuth:
res['response']['text'] = 'Вы не авторизованы.'
return
if command in ["включи свет", "включить свет"]:
res['response']['text'] = 'Включаю свет.'
self.turn_on("group.all_lights")
self.turn_on("switch.kitchen_mini_light")
return
if command in ["включи свет в зале", "включить свет в зале","включи свет в гостинной", "включить свет в гостинной"]:
res['response']['text'] = 'Свет включен.'
self.turn_on("group.mainroom_light")
return
if command in ["выключи свет в зале", "выключить свет в зале","выключи свет в гостинной", "выключить свет в гостинной"]:
res['response']['text'] = 'Свет выключен.'
self.turn_off("group.mainroom_light")
return
if command in ["выключи свет", "выключить свет", "выключи весь свет"]:
res['response']['text'] = 'Свет выключен.'
self.turn_off("group.all_lights")
self.turn_off("switch.kitchen_mini_light")
return
if command in ["хватит", "алиса, хватит", "алиса хватит", "отмена"]:
res['response']['text'] = 'Хорошо'
res['response']['end_session'] = True
return
if command in ["я ушел", "алиса я ушел"]:
self.call_service("alarm_control_panel/alarm_arm_away", entity_id="alarm_control_panel.ha_alarm")
res['response']['text'] = 'Приятной дороги.'
return
if command in ["я вернулся", "я пришёл", "я пришел"]:
self.call_service("alarm_control_panel/alarm_disarm", entity_id="alarm_control_panel.ha_alarm")
res['response']['text'] = 'Добро пожаловать домой.'
return
if command in ["запусти навык управление домом"]:
res['response']['text'] = 'Уже запущен.'
return
res['response']['text'] = 'Извините, я не знаю команды %s.' % command
return
-9
View File
@@ -1,9 +0,0 @@
#################################
# YANDEX.ALICE #
#################################
alice:
module: alice
class: YandexAlice
global_dependencies:
- globals
+27 -27
View File
@@ -53,21 +53,13 @@ class Climate(hass.Hass):
self.timer = self.run_in(self.run_in_split_mode, 10, mode=mode, temp=temp, state="ON")
def run_in_split_mode(self, args):
code = ""
self.log('mode: {}'.format(args['mode']))
remote = Remote()
code = remote.set_mode(args['mode'], "2", args['temp'], args['state'])
self.call_service("mqtt/publish", topic = self.ir_topic, payload = code.decode("utf-8"))
code = code.decode("utf-8")
self.call_service("mqtt/publish", topic = self.ir_topic, payload = code)
def set_color_entity(self, to):
if 'color_entity' not in self.args:
return
entity = self.args['color_entity']
if to == "hot":
self.turn_on(entity, rgb_color=[255,0,0], brightness = 100)
if to == "cold":
self.turn_on(entity, rgb_color=[0,0,255], brightness = 100)
if to == "off":
self.turn_off(entity)
def do_action(self):
if 'constraint' in self.args and not self.constrain_input_boolean(self.args['constraint']):
self.log("Temperature control is disabled.")
@@ -81,13 +73,6 @@ class Climate(hass.Hass):
self.split_off()
return
# Проверить датчики дверей и окон
door_window_state = self.get_state(self.args['door_window'])
if (door_window_state != 'off'):
self.log("Balcony door is opened. Turning off split.")
self.split_off()
return
nest_target_cool = self.get_state('climate.living_room', attribute="temperature")
nest_target_hot = nest_target_cool
if nest_target_cool == None and nest_target_hot == None:
@@ -101,27 +86,41 @@ class Climate(hass.Hass):
nest_y1 = self.get_state('binary_sensor.nest_y1')
if nest_y1 == "on":
if self.check_door('FAN'):
return
self.split_state = "on"
self.log("Turn on split for COOLING to {}.".format(nest_target_cool))
self.split_on("COOLING", 20)
self.set_color_entity('cold')
self.split_on("COOLING", 16)
elif nest_w1 == "on":
if self.check_door('OFF'):
return
self.split_state = "on"
self.log("Turn on split for HEATING to {}".format(nest_target_hot))
self.split_on("HEATING", 28)
self.set_color_entity('hot')
else:
self.log("Nest is reporting that temp is ok.")
self.split_off()
self.set_color_entity('off')
def terminate(self):
if self.listen_event_handle_list != None:
for listen_event_handle in self.listen_event_handle_list:
self.cancel_listen_event(listen_event_handle)
def check_door(self, mode):
# Проверить датчики дверей и окон
door_window_state = self.get_state(self.args['door_window'])
if (door_window_state != 'off'):
self.log("Balcony door is opened. Set split to fan mode.")
if mode == "FAN":
self.split_on("FAN", 16)
return True
else:
self.split_off()
return True
return False
#
# App to control climate device (split system)
#
@@ -151,6 +150,7 @@ STATE = {
MODE = {
"HEATING": 4, # b100
"AUTO": 3, # b011
"FAN": 2, # b010
"DEHUIDIFICATION": 1, # b001
"COOLING": 0,
"NONE": 0,
@@ -159,8 +159,8 @@ MODE = {
TEMPERATURE_OFFSET = 15
FAN = {
"1": 1,
"2": 0,
"1": 0,
"2": 1,
"3": 2,
"4": 4, # b100
"NONE": 5, # b101
@@ -197,7 +197,7 @@ class Remote(object):
self.codes = [0] * BUFFER_SIZE
self.crc = 0
def set_mode(self, mode, fan, temperature, state):
def set_mode(self, mode, fan, temperature, state, jet=0):
"""
Generate code and put it in the buffer
"""
@@ -218,7 +218,7 @@ class Remote(object):
else:
self.fill_buffer(16, 4, temperature - TEMPERATURE_OFFSET)
self.fill_buffer(20, 1, 0) # jet
self.fill_buffer(20, 1, jet) # jet
if state == 'OFF':
self.fill_buffer(21, 3, FAN['NONE'])
@@ -6,7 +6,6 @@ entities_action:
class: EntitiesByPresence
away_entities:
- group.all_lights
- switch.kitchen_mini_light
- switch.plug_158d0001104a0c # телевизор
- switch.plug_158d0001a68b18 # термопот
return_entities:
@@ -0,0 +1,32 @@
import appdaemon.plugins.hass.hassapi as hass
import globals
#
# Управление замком Xiaomi
#
# Args:
#
# None
#
# Release Notes
#
# Version 1.0:
# Initial Version
class CurtainSecurity(hass.Hass):
def initialize(self):
if not globals.check_args(self, ['curtain', 'door']):
return
self.listen_event(self.curtain_changed, event='call_service', entity_id = self.args['curtain'])
# self.listen_event_handle_list = []
# locks = globals.get_group_entities(self, "group.all_locks")
# for lock in locks:
# self.listen_event_handle_list.append(self.listen_state(self.lock_state_changed, lock))
def curtain_changed(self, event_name, data, kwargs):
if 'constraint' in self.args and not self.constrain_input_boolean(self.args['constraint']):
return
service = data['service']
if service in ['close_cover', 'open_cover']:
door_state = self.get_state(self.args['door'])
if door_state == "on":
self.call_service("cover/stop_cover", entity_id = self.args['curtain'])
@@ -0,0 +1,8 @@
curtainsecurity:
module: curtainsecurity
class: CurtainSecurity
curtain: cover.curtain_158d0002b0c46a
door: binary_sensor.door_window_sensor_158d00010f7e19
# constraint: input_boolean.lock_report
global_dependencies:
- globals
@@ -26,6 +26,7 @@ class ToiletPresence(hass.Hass):
if 'sensor' not in self.args:
self.error("Please provide sensor in config!")
return
self.set_value("off")
self.listen_state(self.distance_changed, self.args['sensor'])
def distance_changed(self, entity, attribute, old, new, kwargs):
+5
View File
@@ -9,6 +9,11 @@ homeassistant:
customize_domain: !include customize_domain.yaml
packages: !include_dir_named packages/
logger:
default: info
# logs:
# custom_components.yandex_smart_home: debug
api:
http:
+4
View File
@@ -1,6 +1,7 @@
filter:
include_domains:
- alarm_control_panel
- climate
- switch
- light
- vacuum
@@ -9,6 +10,9 @@ filter:
- switch.plug_158d00020f3a29
- switch.plug_158d00026ea017
- switch.xiaomi_miio_switch
- switch.domofon_mode
- switch.domofon_open
- light.gateway_light_f0b429aa1463
# include_entities:
# - media_player.tv
# entity_config:
@@ -69,6 +69,6 @@ smart_home:
name: "Curtain lights"
switch.plug_158d0001a68b18:
name: Kettle
switch.kitchen_mini_light:
light.kitchen_mini_light:
name: "Kitchen Mini Light"
display_categories: LIGHT
@@ -24,6 +24,9 @@ light.bath:
light.balcony:
friendly_name: Свет
light.kitchen_mini_light:
friendly_name: Подсветка
light.yeelight_mono1_286c07f12bed:
friendly_name: Балкон1
@@ -1,7 +1,5 @@
switch.water_valve:
friendly_name: Подача воды
switch.kitchen_mini_light:
friendly_name: Подсветка
switch.domofon_mode:
friendly_name: Открытие домофона
switch.domofon_open:
@@ -3,4 +3,4 @@ kitchen_light:
control: hidden
entities:
- light.kitchen
- switch.kitchen_mini_light
- light.kitchen_mini_light
@@ -8,7 +8,7 @@ report_entities:
- light.yeelight_mono1_f0b4290e5444
- light.yeelight_mono1_f0b429a8f6df
- light.kitchen
- switch.kitchen_mini_light
- light.kitchen_mini_light
- light.hall
- light.bath
- switch.plug_158d0001104a0c # телевизор
@@ -5,3 +5,10 @@
payload_on: "ON"
payload_off: "OFF"
optimistic: false
- platform: mqtt
name: kitchen_mini_light
state_topic: "home/plug/kitchen-mini-light/status"
command_topic: "home/plug/kitchen-mini-light/status/set"
payload_on: "on"
payload_off: "off"
@@ -1,9 +1,9 @@
- platform: mqtt
name: kitchen_mini_light
state_topic: "home/plug/kitchen-mini-light/status"
command_topic: "home/plug/kitchen-mini-light/status/set"
payload_on: "on"
payload_off: "off"
# - platform: mqtt
# name: kitchen_mini_light
# state_topic: "home/plug/kitchen-mini-light/status"
# command_topic: "home/plug/kitchen-mini-light/status/set"
# payload_on: "on"
# payload_off: "off"
# - platform: broadlink
# host: 192.168.1.63
Submodule hass/settings/custom_components/yandex_smart_home updated: a323a790d1...7373db4978
+2 -2
View File
@@ -36,7 +36,7 @@ views:
show_header_toggle: false
entities:
- light.kitchen
- switch.kitchen_mini_light
- light.kitchen_mini_light
- switch.plug_158d0001a68b18
- switch.plug_158d0001a68c64
- switch.plug_158d0001a4cfb4
@@ -355,4 +355,4 @@ views:
entities:
- sensor.speedtest_ping
- sensor.speedtest_download
- sensor.speedtest_upload
- sensor.speedtest_upload