Compare commits

..
10 Commits
Author SHA1 Message Date
Your Name 194723e228 updating configuration
Python application / build (push) Failing after 55s
2020-01-30 22:22:18 +03:00
Your Name eb13a3ab19 updating configuration 2020-01-20 10:14:08 +03:00
Your Name 4904b639e3 secrets update 2020-01-10 15:34:18 +03:00
Your Name c022111030 secrets update 2020-01-10 15:29:04 +03:00
Your Name a09d27fa3a secrets update 2020-01-10 14:48:14 +03:00
Your Name 86aaa6b179 ok 2020-01-10 14:43:36 +03:00
Your Name 654d7c4881 secrets update 2020-01-10 14:41:33 +03:00
Your Name 0ed06741b9 updating configuration 2020-01-10 14:29:02 +03:00
Your Name 9ed8186f28 updating configuration 2019-12-06 14:25:36 +03:00
Your Name 0a380e0597 updating configuration 2019-12-06 10:36:10 +03:00
158 changed files with 505 additions and 6868 deletions

No files matched your search

+3
View File
@@ -0,0 +1,3 @@
[submodule "secrets"]
path = secrets
url = git@github.com:monster1025/secrets.git
+2 -7
View File
@@ -2,14 +2,10 @@
ARGS = `arg="$(filter-out $@,$(MAKECMDGOALS))" && echo $${arg:-${1}}`
lint:
@echo "Checking python syntax with pyflakes"
@pyflakes appdaemon
update_secrets_sample:
@echo "Masking passwords..."
#hass
@cat hass/settings/secrets.yaml | sed "s/\:.*/\: xxxxxxxxx/g" > hass/settings/secrets.yaml.sample #mask passwords
@cat secrets/hass/settings/secrets.yaml | sed "s/\:.*/\: xxxxxxxxx/g" > hass/settings/secrets.yaml.sample #mask passwords
@sed -i "s/latitude:.*/latitude: 1.0/g" hass/settings/secrets.yaml.sample #must be a number
@sed -i "s/longitude:.*/longitude: 1.0/g" hass/settings/secrets.yaml.sample #must be a number
@sed -i "s/aqara1_mac:.*/aqara1_mac: xxxxxxxxxxxx/g" hass/settings/secrets.yaml.sample #len 12
@@ -27,7 +23,6 @@ update_secrets_sample:
@sed -i "s/modbus_port:.*/modbus_port: 9977/g" hass/settings/secrets.yaml.sample #must be valid
@sed -i "s/xiaomi_remote_token:.*/xiaomi_remote_token: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/g" hass/settings/secrets.yaml.sample #must be valid
@echo "Masking env files..."
@find . -name *.env | xargs -I{} cp {} {}.sample
@find . -name *.env.sample | xargs -I{} sed -i "s/\=.*/\=xxxxxxxxx/g" {}
@@ -36,7 +31,7 @@ update_secrets_sample:
commit: update_secrets_sample
git add .
git commit -m "$(call ARGS,\"updating configuration\")"
git diff-index --quiet HEAD || git commit -m "$(call ARGS,\"updating configuration\")"
git push
%:
@@ -8,11 +8,3 @@ kitchen_led_controller:
topic: home/kitchen-led/kitchen-led/state/set
global_dependencies:
- globals
bath_led_controller:
module: kitchen_led_controller
class: KitchenLedController
watch_entity: light.bath
control_entity: light.philips_led
global_dependencies:
- globals
@@ -1,46 +0,0 @@
import appdaemon.plugins.hass.hassapi as hass
class Noolite(hass.Hass):
brightness = 40
force = False
def initialize(self):
self.run_at_sunrise(self.sunrise_cb)
# self.run_at_sunset(self.sunset_cb)
self.listen_state(self.light_change, "group.mainroom_light")
self.listen_event(self.away_mode, "away_mode")
def away_mode(self, event_id, event_args, kwargs):
self.noolite_off()
def light_change(self, entity, attribute, old, new, kwargs):
sun_down = self.sun_down()
if new == "off" and (sun_down or self.force) and self.somebody_home():
self.noolite_on(self.brightness)
else:
self.noolite_off()
def noolite_off(self):
self.log("Turning off salt lamp.")
self.turn_off(self.args['entity_id'])
def noolite_on(self, brightness=120):
self.log("Turning on salt lamp for brightness {}.".format(brightness))
self.turn_on(self.args['entity_id'], brightness=self.brightness)
def sunset_cb(self, kwargs):
if not self.somebody_home():
return
self.noolite_on(self.brightness)
def somebody_home(self):
if 'ha_panel' not in self.args:
return True
ha_panel_state = self.get_state(self.args['ha_panel'])
if ha_panel_state == 'armed_away':
return False
return True
def sunrise_cb(self, kwargs):
self.noolite_off()
@@ -1,5 +0,0 @@
salt_lamp:
module: salt_lamp
class: Noolite
entity_id: light.salt_lamp
ha_panel: alarm_control_panel.ha_alarm
@@ -35,7 +35,7 @@ watchdog_sonoff_uptime:
module: watchdog
constraint: input_boolean.watchdog_report
entities:
- sensor.uptime_bathlight
#- sensor.uptime_bathlight
- sensor.uptime_kitchen
check_interval: 60
timeout: 7200
@@ -38,10 +38,6 @@ class AliceScenes(hass.Hass):
self.night_mode()
if (entity_name == "away_mode"):
self.away_mode()
# if (entity_name == "turn_on_coffeemachine"):
# self.turn_on_coffeemachine()
# if (entity_name == "make_coffee"):
# self.make_coffee()
def terminate(self):
if self.listen_event_handle_list != None:
@@ -54,15 +50,12 @@ class AliceScenes(hass.Hass):
def night_mode(self):
self.turn_off('switch.plug_158d0001104a0c') #tv
self.turn_off('group.all_lights')
self.turn_on('light.wled', brightness=5)
self.call_service("cover/close_cover", entity_id = 'cover.curtain_158d0002b0c46a')
def away_mode(self):
self.call_service("alarm_control_panel/alarm_arm_away", entity_id = self.args['ha_panel'])
def turn_on_coffeemachine(self):
self.log('Turn on coffeemachine')
self.call_service("mqtt/publish", topic = 'home/coffee/coffee/power/set', payload = 'on')
def make_coffee(self):
self.log('Make coffee')
self.call_service("mqtt/publish", topic = 'home/coffee/coffee/power/set', payload = 'on')
+11 -11
View File
@@ -50,17 +50,17 @@ water_sensor:
global_dependencies:
- globals
water_sender:
class: WaterCounterSender
module: mosru
entity_ids:
hot: sensor.counter_hot
cold: sensor.counter_cold
app: mosru_client
dependencies:
- mosru_client
global_dependencies:
- globals
# water_sender:
# class: WaterCounterSender
# module: mosru
# entity_ids:
# hot: sensor.counter_hot
# cold: sensor.counter_cold
# app: mosru_client
# dependencies:
# - mosru_client
# global_dependencies:
# - globals
power_sender:
class: PowerCounterSender
+51 -56
View File
@@ -1,73 +1,68 @@
import appdaemon.plugins.hass.hassapi as hass
import requests
import json
class TelegramTest(hass.Hass):
def initialize(self):
"""Listen to Telegram Bot events of interest."""
self.listen_event(self.receive_telegram_text, 'telegram_text')
self.listen_event(self.receive_telegram_callback, 'telegram_callback')
def receive_telegram_text(self, event_id, payload_event, *args):
"""Text repeater."""
assert event_id == 'telegram_text'
user_id = payload_event['user_id']
msg = 'You said: ``` %s ```' % payload_event['text']
keyboard = [[("Edit message", "/edit_msg"),
("Don't", "/do_nothing")],
[("Remove this button", "/remove button")]]
self.call_service('telegram_bot/send_message',
title='*Dumb automation*',
target=user_id,
message=msg,
disable_notification=True,
inline_keyboard=keyboard)
msg = payload_event['text']
self.log('got msg: {}'.format(msg))
if msg.startswith('https://www.youtube.com/watch') or msg.startswith('https://youtube.com/watch'):
self.sendToScreen(payload_event['text'])
def receive_telegram_callback(self, event_id, payload_event, *args):
"""Event listener for Telegram callback queries."""
assert event_id == 'telegram_callback'
data_callback = payload_event['data']
callback_id = payload_event['id']
chat_id = payload_event['chat_id']
self.log(payload_event)
# keyboard = ["Edit message:/edit_msg, Don't:/do_nothing",
# "Remove this button:/remove button"]
keyboard = [[("Edit message", "/edit_msg"),
("Don't", "/do_nothing")],
[("Remove this button", "/remove button")]]
def sendToScreen(self, video_url):
auth_data = {
'login': self.args.get('alice_login', ''),
'passwd': self.args.get('alice_pwd', '')
}
# self.log('auth_data: {}'.format(auth_data))
if data_callback == '/edit_msg': # Message editor:
# Answer callback query
self.call_service('telegram_bot/answer_callback_query',
message='Editing the message!',
callback_query_id=callback_id,
show_alert=True)
s = requests.Session()
s.get("https://passport.yandex.ru/")
s.post("https://passport.yandex.ru/passport?mode=auth&retpath=https://yandex.ru", data=auth_data)
# Edit the message origin of the callback query
msg_id = payload_event['message']['message_id']
user = payload_event['from_first']
title = '*Message edit*'
msg = 'Callback received from %s. Message id: %s. Data: ``` %s ```'
self.call_service('telegram_bot/edit_message',
chat_id=chat_id,
message_id=msg_id,
title=title,
message=msg % (user, msg_id, data_callback),
inline_keyboard=keyboard)
Session_id = s.cookies["Session_id"]
self.log('session: {}'.format(Session_id))
elif data_callback == '/remove button': # Keyboard editor:
# Answer callback query
self.call_service('telegram_bot/answer_callback_query',
message='Callback received for editing the '
'inline keyboard!',
callback_query_id=callback_id)
# Getting x-csrf-token
token = s.get('https://frontend.vh.yandex.ru/csrf_token').text
self.log('token: {}'.format(token))
# Edit the keyboard
new_keyboard = keyboard[:1]
self.call_service('telegram_bot/edit_replymarkup',
chat_id=chat_id,
message_id='last',
inline_keyboard=new_keyboard)
# Detting devices info TODO: device selection here
devices_online_stats = s.get("https://quasar.yandex.ru/devices_online_stats").text
devices = json.loads(devices_online_stats)["items"]
self.log('devices: {}'.format(devices))
if not devices[0].get('screen_present', False):
self.log('Device has no screen present.')
return
elif data_callback == '/do_nothing': # Only Answer to callback query
self.call_service('telegram_bot/answer_callback_query',
message='OK, you said no!',
callback_query_id=callback_id)
if "&feature=share" in video_url:
video_url = video_url.replace("&feature=share", '')
# Preparing request
headers = {
"x-csrf-token": token,
}
data = {
"msg": {
"provider_item_id": video_url
},
"device": devices[0]["id"]
}
if "https://www.youtube" in video_url:
data["msg"]["player_id"] = "youtube"
self.log('sending data: {}'.format(data))
# Sending command with video to device
res = s.post("https://yandex.ru/video/station", data=json.dumps(data), headers=headers)
return res.text
@@ -1,3 +1,5 @@
telegram_test:
module: telegram_test
class: TelegramTest
alice_login: !secret alice_login
alice_pwd: !secret alice_pwd
@@ -25,11 +25,15 @@ class Curtain(hass.Hass):
def on_timer_tick(self, kwargs):
self.log('on_timer')
if 'constraint' in self.args and not self.constrain_input_boolean(self.args['constraint']):
return
if 'entity' in self.args:
self.call_service("cover/open_cover", entity_id = self.args['entity'])
def off_timer_tick(self, kwargs):
self.log('off_timer')
if 'constraint' in self.args and not self.constrain_input_boolean(self.args['constraint']):
return
if 'entity' in self.args:
self.call_service("cover/close_cover", entity_id = self.args['entity'])
@@ -1,43 +1,17 @@
led_timer:
module: entity_timer
class: EntityTimer
on_time: "09:00:00"
off_time: "22:00:00"
entity: switch.ledstrip
global_dependencies:
- globals
# led_window_timer:
# led_timer:
# module: entity_timer
# class: EntityTimer
# on_time: "09:00:00"
# off_time: "23:00:00"
# entity: switch.wifi_socket
# off_time: "22:00:00"
# entity: switch.ledstrip
# global_dependencies:
# - globals
xmas_tree_timer:
module: entity_timer
class: EntityTimer
on_time: "09:00:00"
off_time: "23:00:00"
entity: switch.broadlink_switch
global_dependencies:
- globals
fitolamp_timer:
module: entity_timer
class: EntityTimer
on_time: "00:00:00"
off_time: "03:00:00"
entity: switch.plug_158d0002924779
global_dependencies:
- globals
# tv_timer:
# fitolamp_timer:
# module: entity_timer
# class: EntityTimer
# on_time: "09:00:00"
# off_time: "22:30:00"
# entity: switch.plug_158d0001104a0c
# on_time: "00:00:00"
# off_time: "03:00:00"
# entity: switch.plug_158d0002924779
# global_dependencies:
# - globals
+113
View File
@@ -0,0 +1,113 @@
import appdaemon.plugins.hass.hassapi as hass
import datetime
import random
#
# Entity timer
# Turn on and off this entities
#
# Args:
#
# None
#
# Release Notes
#
# Version 1.0:
# Initial Version
class XmasTreeTimer(hass.Hass):
effects = []
def initialize(self):
self.effects = ['[FX=00] Solid',
'[FX=01] Blink',
'[FX=02] Breathe',
'[FX=03] Wipe',
'[FX=04] Wipe Random',
'[FX=05] Random Colors',
'[FX=06] Sweep',
'[FX=07] Dynamic',
'[FX=08] Colorloop',
'[FX=09] Rainbow',
'[FX=10] Scan',
'[FX=11] Dual Scan',
'[FX=12] Fade',
'[FX=13] Chase',
'[FX=14] Chase Rainbow',
'[FX=15] Running',
'[FX=16] Saw',
'[FX=17] Twinkle',
'[FX=18] Dissolve',
'[FX=19] Dissolve Rnd',
'[FX=20] Sparkle',
'[FX=21] Dark Sparkle',
'[FX=22] Sparkle+',
'[FX=23] Strobe',
'[FX=24] Strobe Rainbow',
'[FX=25] Mega Strobe',
'[FX=26] Blink Rainbow',
'[FX=27] Android',
'[FX=28] Chase',
'[FX=29] Chase Random',
'[FX=30] Chase Rainbow',
'[FX=31] Chase Flash',
'[FX=32] Chase Flash Rnd',
'[FX=33] Rainbow Runner',
'[FX=34] Colorful',
'[FX=35] Traffic Light',
'[FX=36] Sweep Random',
'[FX=37] Running 2',
'[FX=38] Red & Blue',
'[FX=39] Stream',
'[FX=40] Scanner',
'[FX=41] Lighthouse',
'[FX=42] Fireworks',
'[FX=43] Rain',
'[FX=44] Merry Christmas',
'[FX=45] Fire Flicker',
'[FX=46] Gradient',
'[FX=47] Loading',
'[FX=48] In Out',
'[FX=49] In In',
'[FX=50] Out Out',
'[FX=51] Out In',
'[FX=52] Circus',
'[FX=53] Halloween',
'[FX=54] Tri Chase',
'[FX=55] Tri Wipe',
'[FX=56] Tri Fade',
'[FX=57] Lightning',
'[FX=58] ICU',
'[FX=59] Multi Comet',
'[FX=60] Dual Scanner',
'[FX=61] Stream 2',
'[FX=62] Oscillate',
'[FX=63] Pride 2015',
'[FX=64] Juggle',
'[FX=65] Palette',
'[FX=66] Fire 2012',
'[FX=67] Colorwaves',
'[FX=68] BPM',
'[FX=69] Fill Noise',
'[FX=70] Noise 1',
'[FX=71] Noise 2',
'[FX=72] Noise 3',
'[FX=73] Noise 4',
'[FX=74] Colortwinkle',
'[FX=75] Lake',
'[FX=76] Meteor',
'[FX=77] Smooth Meteor',
'[FX=78] Railway',
'[FX=79] Ripple',
'[FX=80] Twinklefox',
'[FX=81] Twinklecat',
'[FX=82] Halloween Eyes']
# self.effects = ['FX=00','FX=01','FX=02']
# self.on_timer = self.run_every(self.on_timer_tick, on_time)
# self.off_timer = self.run_daily(self.off_timer_tick, off_time)
self.run_every(self.run_every_c, datetime.datetime.now(), 15)
def run_every_c(self, kwargs):
effect = random.choice(self.effects)
# rand = random.randint(0, 82)
# effect = "FX={}".format(rand)
self.log('random: {}'.format(effect))
self.call_service("mqtt/publish", topic = 'wled/d85df2/api', payload = effect)
@@ -0,0 +1,6 @@
xmas-tree:
module: xmas-tree
class: XmasTreeTimer
global_dependencies:
- globals
+12 -2
View File
@@ -48,6 +48,7 @@ services:
container_name: hass
volumes:
- ./hass/settings:/config
- ./secrets/hass/settings/secrets.yaml:/config/secrets.yaml:ro
- ./hass/settings/hosts.txt:/etc/hosts:ro
- /etc/localtime:/etc/localtime:ro
ports:
@@ -59,6 +60,7 @@ services:
- mysql
- mosquitto
- broadlink
- tor
network_mode: "host"
restart: always
healthcheck:
@@ -71,6 +73,14 @@ services:
options:
max-size: 50m
tor:
build:
context: ./tor/docker
container_name: tor
ports:
- "9150:9150"
restart: always
appdaemon:
image: monster1025/appdaemon
build:
@@ -82,7 +92,7 @@ services:
- hass
volumes:
- ./appdaemon/settings:/conf
- ./hass/settings/secrets.yaml:/conf/secrets.yaml:ro
- ./secrets/hass/settings/secrets.yaml:/conf/secrets.yaml:ro
- ./hass/settings/hosts.txt:/etc/hosts:ro
- /etc/localtime:/etc/localtime:ro
restart: always
@@ -194,7 +204,7 @@ services:
# - "6052:6052"
volumes:
- ./esphome/settings:/config
- ./hass/settings/secrets.yaml:/config/secrets.yaml:ro
- ./secrets/hass/settings/secrets.yaml:/config/secrets.yaml:ro
network_mode: "host"
logging:
driver: json-file
+17 -8
View File
@@ -1,8 +1,16 @@
# ----------- User configutaion ------------------
substitutions:
devicename: airfresher
upper_devicename: Airfresher
fresh_motor_pin: D1
remain_init: '2000'
# ----------- /User configutaion ------------------
# Need to turn off logging because senseair uses uart and have conflicts with logging
logger:
esphome:
name: airfresher
name: $devicename
platform: ESP8266
board: d1_mini
@@ -12,11 +20,12 @@ wifi:
# Enable fallback hotspot (captive portal) in case wifi connection fails
ap:
ssid: "Airfresher Fallback Hotspot"
ssid: "$upper_devicename Fallback Hotspot"
password: !secret esphome_captive_pass
captive_portal:
# Enable Home Assistant API
api:
password: !secret esphome_pass
@@ -29,14 +38,14 @@ globals:
- id: remain
type: int
restore_value: yes
initial_value: '2000'
initial_value: $remain_init
sensor:
- platform: uptime
name: Airfresher Uptime
name: "$upper_devicename Uptime"
- platform: template
name: "Airfresher Remain"
name: "$upper_devicename Remain"
icon: "mdi:battery-80"
lambda: |-
return id(remain);
@@ -44,11 +53,11 @@ sensor:
switch:
- platform: gpio
pin: D1
pin: $fresh_motor_pin
id: fresh_motor
- platform: template
name: "Airfresher fresh"
name: "$upper_devicename fresh"
icon: "mdi:air-humidifier"
turn_on_action:
- lambda: 'id(remain) -= 1;'
@@ -57,7 +66,7 @@ switch:
- switch.turn_off: fresh_motor
- platform: template
name: "Airfresher reset"
name: "$upper_devicename reset"
icon: "mdi:backup-restore"
turn_on_action:
- lambda: 'id(remain) = 2000;'
-51
View File
@@ -1,51 +0,0 @@
esphome:
name: bath_light
platform: ESP8266
board: esp01_1m
wifi:
ssid: !secret wifi_24_name
password: !secret wifi_24_pass
# Enable fallback hotspot (captive portal) in case wifi connection fails
ap:
ssid: "BathLight Fallback Hotspot"
password: !secret esphome_captive_pass
logger:
api:
password: !secret esphome_pass
ota:
password: !secret esphome_pass
binary_sensor:
- platform: gpio
pin:
number: GPIO14
mode: INPUT_PULLUP
inverted: True
id: button_1
on_press:
then:
- light.toggle: light_1
- platform: status
name: "Bath status"
output:
- platform: gpio
pin: GPIO12
id: relay_1
light:
- platform: binary
name: "bath"
id: light_1
output: relay_1
status_led:
pin:
number: GPIO13
inverted: yes
+11 -11
View File
@@ -1,14 +1,14 @@
############# User configuration #############
# ----------- User configutaion ------------------
substitutions:
devicename: domofon
upper_devicename: Domofon
call_sensor_pin: "14"
trubka_pin: "13"
door_pin: "12"
board_name: domofon
########### End user configuration ###########
# ----------- /User configutaion ------------------
esphome:
name: $board_name
name: $devicename
platform: ESP8266
board: d1_mini
@@ -18,7 +18,7 @@ wifi:
# Enable fallback hotspot (captive portal) in case wifi connection fails
ap:
ssid: "Domofon Fallback Hotspot"
ssid: "$upper_devicename Fallback Hotspot"
password: !secret esphome_captive_pass
captive_portal:
@@ -38,7 +38,7 @@ binary_sensor:
number: $call_sensor_pin
mode: INPUT_PULLUP
inverted: true
name: "Domofon incoming call"
name: "$upper_devicename incoming call"
id: incoming_call
device_class: lock
filters:
@@ -49,7 +49,7 @@ binary_sensor:
sensor:
- platform: uptime
name: Domofon Uptime
name: "$upper_devicename Uptime"
switch:
- platform: gpio
@@ -66,7 +66,7 @@ switch:
# Automatically open door switch
- platform: template
name: "Domofon automatically open"
name: "$upper_devicename automatically open"
id: auto_open
icon: "mdi:door-open"
optimistic: true
@@ -76,7 +76,7 @@ switch:
# Automatically open door once switch
- platform: template
name: "Domofon automatically open once"
name: "$upper_devicename automatically open once"
id: auto_open_once
icon: "mdi:door-open"
optimistic: true
@@ -85,7 +85,7 @@ switch:
- switch.turn_off: auto_open
- platform: template
name: "Domofon force open"
name: "$upper_devicename force open"
id: open_force
icon: "mdi:door-open"
turn_on_action:
-40
View File
@@ -1,40 +0,0 @@
# Need to turn off logging because senseair uses uart and have conflicts with logging
logger:
baud_rate: 0
esphome:
name: senseair
platform: ESP8266
board: d1_mini
wifi:
ssid: !secret wifi_24_name
password: !secret wifi_24_pass
# Enable fallback hotspot (captive portal) in case wifi connection fails
ap:
ssid: "Senseair Fallback Hotspot"
password: !secret esphome_captive_pass
captive_portal:
# Enable Home Assistant API
api:
password: !secret esphome_pass
ota:
password: !secret esphome_pass
# senseair communication uart
uart:
rx_pin: D7
tx_pin: D8
baud_rate: 9600
# hass sensor =)
sensor:
- platform: senseair
co2:
name: "SenseAir CO2 Value"
update_interval: 60s
+137
View File
@@ -0,0 +1,137 @@
#include "esphome.h"
#include <Bounce2.h>
#define CounterNum 2
#define COUNTER_COLD 0
#define COUNTER_HOT 1
static const char *TAG = "watercounter.sensor";
class WaterCountersSensor : public Component, public Sensor, public CustomAPIDevice {
protected:
int CounterPin[CounterNum] = {D1,D2};
float CounterValues[CounterNum] = {};
Bounce CounterBouncer[CounterNum] = {};
public:
Sensor *cold_sensor = new Sensor();
Sensor *hot_sensor = new Sensor();
bool initReadValues = false;
globals::GlobalsComponent<float> *counter_cold_value;
globals::GlobalsComponent<float> *counter_hot_value;
void setup() override {
register_service(&WaterCountersSensor::on_set_counter_values, "set_counter_values",
{"cold_value", "hot_value"});
// init flash variables
counter_cold_value = new globals::GlobalsComponent<float>();
App.register_component(counter_cold_value);
counter_cold_value->set_restore_value(1547432152);
counter_hot_value = new globals::GlobalsComponent<float>();
App.register_component(counter_hot_value);
counter_hot_value->set_restore_value(2087162808);
ESP_LOGD(TAG, "Initializing counters.");
for (int i=0; i<CounterNum; i++) {
pinMode(CounterPin[i], INPUT_PULLUP);
CounterBouncer[i].attach(CounterPin[i]);
CounterBouncer[i].interval(100);
}
ESP_LOGD(TAG, "Initialize done.");
}
void loop() override {
if (is_connected() && !initReadValues) {
ESP_LOGD(TAG, "Reading counters from fs.");
for (int i=0; i<CounterNum; i++) {
readCounterFromFile(i);
sendCounterValue(i);
}
initReadValues = true;
}
for (int i=0; i<CounterNum; i++) {
boolean changed = CounterBouncer[i].update();
if ( changed ) {
int value = CounterBouncer[i].read();
if ( value == LOW) {
ESP_LOGD(TAG, "Got counter %d 'tick'.", i);
ESP_LOGD(TAG, "Incrementing value. Old: %.2f", CounterValues[i]);
CounterValues[i] = CounterValues[i] + 0.01;
ESP_LOGD(TAG, "New: %.2f", CounterValues[i]);
sendCounterValue(i);
writeFile(i);
printState(i);
}
}
}
}
// void update() override {
// for (int i=0; i<CounterNum; i++) {
// sendCounterValue(i);
// }
// }
// --------------- HASS service call handling ----------------------------
void on_set_counter_values(float cold_value, float hot_value)
{
ESP_LOGD(TAG, "Saving values: cold - %.2f, hot - %.2f", cold_value, hot_value);
CounterValues[COUNTER_COLD] = cold_value;
CounterValues[COUNTER_HOT] = hot_value;
for (int i=0; i<CounterNum; i++) {
writeFile(i);
sendCounterValue(i);
}
ESP_LOGD(TAG, "Save success.");
}
// --------------- functions ----------------------------
void readCounterFromFile(int counterId) {
if (counterId == COUNTER_COLD) {
CounterValues[COUNTER_COLD] = counter_cold_value->value();
}else if (counterId == COUNTER_HOT) {
CounterValues[COUNTER_HOT] = counter_hot_value->value();
}
}
void writeFile(int counterId) {
if (counterId == COUNTER_COLD) {
counter_cold_value->value() = CounterValues[COUNTER_COLD];
}else if (counterId == COUNTER_HOT) {
counter_hot_value->value() = CounterValues[COUNTER_HOT];
}
ESP_LOGD(TAG, "Saving done.");
}
void sendCounterValue(int counterId) {
if (counterId == COUNTER_COLD) {
ESP_LOGD(TAG, "Publishing cold state.");
float value = CounterValues[counterId];
cold_sensor->publish_state(value);
}else if (counterId == COUNTER_HOT) {
ESP_LOGD(TAG, "Publishing hot state.");
float value = CounterValues[counterId];
hot_sensor->publish_state(value);
}
}
String countrName(int Id) {
switch(Id) {
case COUNTER_HOT:
return "hot";
case COUNTER_COLD:
return "cold";
}
return "unknown";
}
void printState(int counterId) {
ESP_LOGD(TAG, "Counter[%d]=%.2f", counterId, CounterValues[counterId]);
}
};
+33 -49
View File
@@ -1,10 +1,24 @@
# ----------- User configutaion ------------------
substitutions:
devicename: watercontrol
upper_devicename: Watercontrol
water_open_pin: D5
water_close_pin: D3
ultrasonic_echo_pin: D6
ultrasonic_trig_pin: D7
# ----------- /User configutaion ------------------
# Need to turn off logging because senseair uses uart and have conflicts with logging
logger:
esphome:
name: watercontrol
name: $devicename
platform: ESP8266
board: d1_mini
libraries:
- "Bounce2"
includes:
- water_counters.h
wifi:
ssid: !secret wifi_24_name
@@ -12,7 +26,7 @@ wifi:
# Enable fallback hotspot (captive portal) in case wifi connection fails
ap:
ssid: "Watercontrol Fallback Hotspot"
ssid: "$upper_devicename Fallback Hotspot"
password: !secret esphome_captive_pass
captive_portal:
@@ -24,77 +38,47 @@ api:
ota:
password: !secret esphome_pass
globals:
- id: water_state
type: bool
restore_value: yes
initial_value: 'true'
- id: counter_cold_value
type: float
restore_value: yes
initial_value: '210.29'
- id: counter_hot_value
type: float
restore_value: yes
initial_value: '109.74'
binary_sensor:
- platform: gpio
name: pulse_cold
pin:
number: D1
mode: INPUT_PULLUP
filters:
- delayed_off: 100ms
on_press:
then:
- lambda: 'id(counter_cold_value) += 0.01;'
- platform: gpio
name: pulse_hot
pin:
number: D2
mode: INPUT_PULLUP
filters:
- delayed_off: 100ms
on_press:
then:
- lambda: 'id(counter_hot_value) += 0.01;'
#------------------------------------------------------------------------------
sensor:
- platform: uptime
name: "Watercontrol Uptime"
name: "$upper_devicename Uptime"
- platform: template
name: "counter_hot"
#------------------------------------------------------------------------------
- platform: custom
lambda: |-
return id(counter_hot_value);
update_interval: 60s
- platform: template
name: "counter_cold"
lambda: |-
return id(counter_cold_value);
update_interval: 60s
auto my_sensor = new WaterCountersSensor();
App.register_component(my_sensor);
return {my_sensor->cold_sensor, my_sensor->hot_sensor};
sensors:
- name: "Counter Cold"
accuracy_decimals: 2
- name: "Counter Hot"
accuracy_decimals: 2
#------------------------------------------------------------------------------
- platform: ultrasonic
trigger_pin: D7
echo_pin: D6
trigger_pin: $ultrasonic_trig_pin
echo_pin: $ultrasonic_echo_pin
name: "Toilet Distance"
update_interval: 5s
switch:
- platform: gpio
pin:
number: D5
number: $water_open_pin
inverted: yes
id: water_open
interlock: [water_close]
- platform: gpio
pin:
number: D3
number: $water_close_pin
inverted: yes
id: water_close
interlock: [water_open]
+4 -6
View File
@@ -11,8 +11,6 @@ homeassistant:
logger:
default: info
logs:
custom_components.yandex_smart_home: debug
api:
@@ -23,7 +21,7 @@ http:
trusted_proxies:
- 172.19.0.0/24
# noolite:
mobile_app:
# Enables the frontend
frontend:
@@ -58,7 +56,7 @@ input_datetime: !include_dir_merge_named configuration/input/input_datetime
#input_number: !include_dir_merge_named configuration/input/input_number
light: !include_dir_merge_list configuration/light
notify: !include_dir_merge_list configuration/notify
media_player: !include_dir_merge_list configuration/media_player
# media_player: !include_dir_merge_list configuration/media_player
script: !include_dir_merge_named configuration/script
sensor: !include_dir_merge_list configuration/sensor
switch: !include_dir_merge_list configuration/switch
@@ -68,7 +66,7 @@ remote: !include_dir_merge_list configuration/remote
#one item
mqtt: !include configuration/mqtt/mqtt.yaml
telegram_bot: !include configuration/bot/telegram_bot.yaml
vacuum: !include configuration/xiaomi_aqara/vacuum.yaml
# vacuum: !include configuration/xiaomi_aqara/vacuum.yaml
xiaomi_aqara: !include configuration/xiaomi_aqara/xiaomi_aqara.yaml
nest: !include configuration/nest/nest.yaml
homekit: !include configuration/homekit/homekit.yaml
@@ -81,4 +79,4 @@ modbus: !include configuration/modbus.yaml
utility_meter: !include_dir_merge_named configuration/utility_meter
speedtestdotnet: !include configuration/speedtest.yaml
yandex_smart_home: !include configuration/alice.yaml
# yandex_smart_home: !include configuration/alice.yaml
-105
View File
@@ -1,105 +0,0 @@
filter:
include_domains:
- alarm_control_panel
- climate
- switch
- light
- vacuum
- cover
- fan
include_entities:
- input_boolean.alice_night_mode
- input_boolean.alice_turn_off_light
- input_boolean.alice_away_mode
exclude_entities:
- switch.plug_158d00020f3a29
- switch.plug_158d00026ea017
- switch.plug_158d00010dd98d
- switch.xiaomi_miio_switch
- switch.domofon_mode
- switch.domofon_open
- light.gateway_light_f0b429aa1463
entity_config:
input_boolean.alice_away_mode:
name: "Я ушёл"
room: "Сценарии"
input_boolean.alice_night_mode:
name: "Спокойной ночи"
room: "Сценарии"
input_boolean.alice_turn_off_light:
name: "Выключи свет"
room: "Сценарии"
climate.living_room:
name: "Термостат"
room: "Гостиная"
light.yeelight_mono1_f0b429a8f6df:
name: "Люстра"
room: "Гостиная"
light.yeelight_color1_34ce008fe328:
name: "Люстра"
room: "Гостиная"
light.yeelight_color1_286c071065c7:
name: "Люстра"
room: "Гостиная"
light.yeelight_mono1_f0b4290e5444:
name: "Люстра"
room: "Гостиная"
light.yeelight_mono1_34ce0087ff33:
name: "Люстра"
room: "Гостиная"
light.salt_lamp:
name: "Соляная лампа"
room: "Гостиная"
switch.wifi_socket:
name: "Гирлянда"
room: "Гостиная"
fan.xiaomi_miio_device:
name: "Воздухоочиститель"
room: "Гостиная"
switch.plug_158d0001104a0c:
name: "Телевизор"
room: "Гостиная"
cover.curtain_158d0002b0c46a:
name: "Шторы"
room: "Гостиная"
light.bath:
name: "Люстра"
room: "Туалет"
light.philips_led:
name: "Люстра"
room: "Туалет"
light.kitchen_mini_light:
name: "Подсветка"
room: "Кухня"
light.kitchen:
name: "Люстра"
room: "Кухня"
switch.plug_158d0001a68c64:
name: "Посудомойка"
room: "Кухня"
switch.plug_158d0001a4cfb4:
name: "Стиралка"
room: "Кухня"
light.hall:
name: "Люстра"
room: "Коридор"
switch.plug_158d0001a68b18:
name: "Термопот"
room: "Кухня"
light.yeelight_mono1_f0b429a8d936:
name: "Люстра"
room: "Балкон"
light.yeelight_mono1_286c07f12bed:
name: "Люстра"
room: "Балкон"
switch.plug_158d0002924779:
name: "Фитолампа"
room: "Балкон"
vacuum.xiaomi_vacuum_cleaner:
name: "Пылесос"
room: "Дом"
switch.water_valve:
name: "Подача воды"
room: "Дом"
@@ -1,4 +0,0 @@
- name: appletv4
host: !secret atv4_ip
login_id: !secret atv4_login
credentials: !secret atv4_credentials
@@ -1,6 +0,0 @@
- platform: mqtt
state_topic: "home/magnet/balcony/status"
name: "door_window_sensor_158d00010f7e19"
payload_on: "open"
payload_off: "close"
device_class: opening
@@ -1,6 +0,0 @@
- platform: mqtt
state_topic: "home/magnet/bath/status"
name: "door_window_sensor_158d000111a469"
payload_on: "open"
payload_off: "close"
device_class: opening
@@ -1,6 +0,0 @@
- platform: mqtt
state_topic: "home/magnet/hall/status"
name: "door_window_sensor_158d0001130141"
payload_on: "open"
payload_off: "close"
device_class: opening
@@ -1,18 +0,0 @@
- platform: mqtt
state_topic: "home/motion/bath/status"
name: "motion_sensor_158d0000f9546b" #"bath_motion"
payload_on: "motion"
payload_off: "no_motion"
device_class: motion
- platform: mqtt
state_topic: "home/sensor_motion.aq2/bath2/status"
name: "motion_sensor_158d000165fed5" #"bath_motion2"
payload_on: "motion"
payload_off: "no_motion"
device_class: motion
- platform: mqtt
state_topic: "home/motion/bath3/status"
name: "motion_sensor_158d0001537e21" #"bath_motion3"
payload_on: "motion"
payload_off: "no_motion"
device_class: motion
@@ -1,6 +0,0 @@
- platform: mqtt
state_topic: "home/motion/hall/status"
name: "motion_sensor_158d0000e7c7ad"
payload_on: "motion"
payload_off: "no_motion"
device_class: motion
@@ -1,12 +0,0 @@
- platform: mqtt
state_topic: "home/motion/kitchen/status"
name: "motion_sensor_158d0000fbc664"
payload_on: "motion"
payload_off: "no_motion"
device_class: motion
- platform: mqtt
state_topic: "home/motion/kitchen2/status"
name: "motion_sensor_158d0001535c97"
payload_on: "motion"
payload_off: "no_motion"
device_class: motion
@@ -1,6 +0,0 @@
- platform: mqtt
state_topic: "home/motion/mainroom/status"
name: "motion_sensor_158d0000f6b2fa"
payload_on: "motion"
payload_off: "no_motion"
device_class: motion
@@ -1,6 +0,0 @@
- platform: mqtt
state_topic: "home/sensor_wleak.aq1/kitchen/status"
name: "water_leak_sensor_158d0001d594fa"
payload_on: "leak"
payload_off: "no_leak"
device_class: moisture
@@ -3,4 +3,5 @@
allowed_chat_ids:
- !secret telegram_group_chat
- !secret telegram_monster_chat
- !secret telegram_sveta_chat
proxy_url: !secret proxy_url
@@ -1,4 +0,0 @@
- platform: xiaomi_miio
model: zhimi.airpurifier.mc1
host: !secret purifier_ip
token: !secret purifier_key
@@ -2,6 +2,5 @@ bath_motion:
name: Движение (ванна)
control: hidden
entities:
- binary_sensor.motion_sensor_158d0000f9546b
- binary_sensor.motion_sensor_158d000165fed5
- binary_sensor.motion_sensor_158d0001537e21
@@ -2,5 +2,4 @@ hall_motion:
name: Движение (прихожая)
control: hidden
entities:
- binary_sensor.motion_sensor_158d0000e7c7ad
- binary_sensor.motion_sensor_158d0002044548
@@ -2,5 +2,4 @@ kitchen_motion:
name: Движение (кухня)
control: hidden
entities:
- binary_sensor.motion_sensor_158d0000fbc664
- binary_sensor.motion_sensor_158d0001535c97
@@ -3,5 +3,4 @@ mainroom_motion:
control: hidden
entities:
- binary_sensor.motion_sensor_158d0000f6b2fa
- binary_sensor.motion_sensor_158d0001e50ce4
- binary_sensor.motion_sensor_158d0001e80f0d
@@ -1,7 +0,0 @@
# - platform: mqtt
# name: "balcony"
# state_topic: "stat/BALCONYV2/POWER"
# command_topic: "cmnd/BALCONYV2/POWER"
# payload_on: "ON"
# payload_off: "OFF"
# optimistic: false
@@ -5,8 +5,3 @@
payload_on: "ON"
payload_off: "OFF"
optimistic: false
- platform: xiaomi_miio
name: "Свет2"
host: !secret philips_downlight_ip
token: !secret philips_downlight_token
@@ -1,13 +0,0 @@
- platform: mqtt
name: "salt_lamp"
availability_topic: "home/noolite/$online"
payload_available: "true"
payload_not_available: "false"
state_topic: "home/noolite/ch0/power"
command_topic: "home/noolite/ch0/power/set"
on_command_type: first
payload_on: "on"
payload_off: "off"
brightness_state_topic: "home/noolite/ch0/brightness"
brightness_command_topic: "home/noolite/ch0/brightness/set"
brightness_scale: 120
@@ -1,2 +0,0 @@
- platform: mpd
host: 192.168.1.125
@@ -1,4 +0,0 @@
#gateways:
# - device: !secret mysensors_gateway_ip
# tcp_port: 5003
#version: '2.0'
@@ -0,0 +1,4 @@
- platform: telegram
name: telegram_sveta
chat_id: !secret telegram_sveta_chat
parse_mode: html
@@ -1,4 +0,0 @@
- platform: xiaomi_miio
name: xiaomi_remote
host: !secret xiaomi_remote_host
token: !secret xiaomi_remote_token
@@ -1,6 +0,0 @@
airfresher_reset:
sequence:
- service: mqtt.publish
data:
topic: 'home/airfresher/airfresher/remain/set'
payload: 1500
@@ -1,6 +0,0 @@
audio_bass_minus:
sequence:
- service: mqtt.publish
data:
topic: "home/remote/rm2/code/set"
payload: "260050000001339514371412131313131312131313131313131313381337133814371337143714371412133814361437141213131213131313381412131313131238143714371436140005060001334a14000d050000000000000000"
@@ -1,6 +0,0 @@
audio_bass_plus:
sequence:
- service: mqtt.publish
data:
topic: "home/remote/rm2/code/set"
payload: "260050000001339414371412131313131213131313131313131313381436143714371437143713381412133813121338141213131313131313381312133814121338143614371437140005060001324a14000d050000000000000000"
@@ -1,6 +0,0 @@
audio_vol_minus:
sequence:
- service: mqtt.publish
data:
topic: "home/remote/rm2/code/set"
payload: "260050000001329513381313131313121313131313131313131312381338133813371338133813381313121313131313133812131313131313381338123813381313123813381338120005060001314b13000d050000000000000000"
@@ -1,6 +0,0 @@
audio_vol_plus:
sequence:
- service: mqtt.publish
data:
topic: "home/remote/rm2/code/set"
payload: "260058000001309613381213131313131213141214121313141113381437143614371437133714371437141213121313143713121313131313131238143713381313123814371436150005030001324916000c5b0001324914000d05"
@@ -1,3 +0,0 @@
# - platform: mqtt
# state_topic: 'home/presence/controller/balcony'
# name: 'presence_balcony'
@@ -1,3 +0,0 @@
# - platform: mqtt
# state_topic: 'home/presence/controller/hall'
# name: 'presence_hall'
@@ -1,3 +0,0 @@
# - platform: mqtt
# state_topic: 'home/presence/controller/kitchen'
# name: 'presence_kitchen'
@@ -1,7 +0,0 @@
- platform: template
sensors:
xiaomi_airpurifier_air_quality_pm25:
friendly_name: "Air quality"
value_template: "{{ state_attr('fan.xiaomi_miio_device', 'aqi') }}"
unit_of_measurement: "μg/m³"
icon_template: "mdi:weather-fog"
@@ -1,10 +0,0 @@
- platform: mqtt
state_topic: 'home/sensor_ht/balcony/temperature'
name: 'temperature_158d000117d37a'
unit_of_measurement: '°C'
value_template: '{{ float(value_json) / 100 }}'
- platform: mqtt
state_topic: 'home/sensor_ht/balcony/humidity'
name: 'humidity_158d000117d37a'
unit_of_measurement: '%'
value_template: '{{ float(value_json) / 100 }}'
@@ -1,10 +0,0 @@
- platform: mqtt
state_topic: 'home/sensor_ht/bath/temperature'
name: 'temperature_158d00012d9ad7'
unit_of_measurement: '°C'
value_template: '{{ float(value_json) / 100 }}'
- platform: mqtt
state_topic: 'home/sensor_ht/bath/humidity'
name: 'humidity_158d00012d9ad7'
unit_of_measurement: '%'
value_template: '{{ float(value_json) / 100 }}'
@@ -1,10 +0,0 @@
- platform: mqtt
state_topic: 'home/sensor_ht/mainroom/temperature'
name: 'temperature_158d0001149b3c'
unit_of_measurement: '°C'
value_template: '{{ float(value_json) / 100 }}'
- platform: mqtt
state_topic: 'home/sensor_ht/mainroom/humidity'
name: 'humidity_158d0001149b3c'
unit_of_measurement: '%'
value_template: '{{ float(value_json) / 100 }}'
@@ -1,10 +0,0 @@
- platform: mqtt
state_topic: 'home/sensor_ht/outside/temperature'
name: 'temperature_158d000149c128'
unit_of_measurement: '°C'
value_template: '{{ float(value_json) / 100 }}'
- platform: mqtt
state_topic: 'home/sensor_ht/outside/humidity'
name: 'humidity_158d000149c128'
unit_of_measurement: '%'
value_template: '{{ float(value_json) / 100 }}'
@@ -1,4 +0,0 @@
# - platform: mqtt
# state_topic: 'home/bath/bath/distance'
# name: 'toilet_distance'
# unit_of_measurement: 'cm'
@@ -1,13 +0,0 @@
#################################################
# WATER #
#################################################
# - platform: mqtt
# state_topic: 'home/bath/bath/cold'
# name: 'counter_cold'
# value_template: '{{ (value | float ) / 1000 }}'
# unit_of_measurement: 'm3'
# - platform: mqtt
# state_topic: 'home/bath/bath/hot'
# name: 'counter_hot'
# value_template: '{{ (value | float ) / 1000 }}'
# unit_of_measurement: 'm3'
@@ -1,12 +0,0 @@
# - 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
# mac: 'B4430DCB6C07'
# type: 'sp2'
# friendly_name: 'kitchen_mini_light'
@@ -1,8 +0,0 @@
# - platform: mqtt
# name: water_valve
# state_topic: "home/bath/bath/valve"
# command_topic: "home/bath/bath/valve/set"
# payload_on: "open"
# payload_off: "close"
# optimistic: false
# retain: false
@@ -1,3 +0,0 @@
- platform: xiaomi_miio
host: !secret mirobot_ip
token: !secret mirobot_key
@@ -1,187 +0,0 @@
"""
Custom element manager for community created elements.
For more details about this integration, please refer to the documentation at
https://hacs.xyz/
"""
import voluptuous as vol
from aiogithubapi import AIOGitHub
from homeassistant import config_entries
from homeassistant.const import EVENT_HOMEASSISTANT_START
from homeassistant.const import __version__ as HAVERSION
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers.aiohttp_client import async_create_clientsession
from homeassistant.helpers.event import async_call_later
from .configuration_schema import hacs_base_config_schema, hacs_config_option_schema
from .const import DEV_MODE, DOMAIN, ELEMENT_TYPES, STARTUP, VERSION
from .constrains import check_constans
from .hacsbase import Hacs
from .hacsbase.configuration import Configuration
from .hacsbase.data import HacsData
from .hacsbase.migration import ValidateData
from .setup import add_sensor, load_hacs_repository, setup_frontend
SCHEMA = hacs_base_config_schema()
SCHEMA[vol.Optional("options")] = hacs_config_option_schema()
CONFIG_SCHEMA = vol.Schema({DOMAIN: SCHEMA}, extra=vol.ALLOW_EXTRA)
async def async_setup(hass, config):
"""Set up this integration using yaml."""
if DOMAIN not in config:
return True
hass.data[DOMAIN] = config
Hacs.hass = hass
Hacs.configuration = Configuration.from_dict(
config[DOMAIN], config[DOMAIN].get("options")
)
Hacs.configuration.config_type = "yaml"
await startup_wrapper_for_yaml(Hacs)
hass.async_create_task(
hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_IMPORT}, data={}
)
)
return True
async def async_setup_entry(hass, config_entry):
"""Set up this integration using UI."""
conf = hass.data.get(DOMAIN)
if config_entry.source == config_entries.SOURCE_IMPORT:
if conf is None:
hass.async_create_task(
hass.config_entries.async_remove(config_entry.entry_id)
)
return False
Hacs.hass = hass
Hacs.configuration = Configuration.from_dict(
config_entry.data, config_entry.options
)
Hacs.configuration.config_type = "flow"
Hacs.configuration.config_entry = config_entry
config_entry.add_update_listener(reload_hacs)
startup_result = await hacs_startup(Hacs)
if not startup_result:
raise ConfigEntryNotReady
return startup_result
async def startup_wrapper_for_yaml(hacs):
"""Startup wrapper for yaml config."""
startup_result = await hacs_startup(hacs)
if not startup_result:
hacs.hass.components.frontend.async_remove_panel(
hacs.configuration.sidepanel_title.lower()
.replace(" ", "_")
.replace("-", "_")
)
hacs.logger.info("Could not setup HACS, trying again in 15 min")
async_call_later(hacs.hass, 900, startup_wrapper_for_yaml(hacs))
async def hacs_startup(hacs):
"""HACS startup tasks."""
hacs.logger.debug(f"Configuration type: {hacs.configuration.config_type}")
hacs.version = VERSION
hacs.logger.info(STARTUP)
hacs.system.config_path = hacs.hass.config.path()
hacs.system.ha_version = HAVERSION
hacs.system.disabled = False
hacs.github = AIOGitHub(
hacs.configuration.token, async_create_clientsession(hacs.hass)
)
hacs.data = HacsData()
# Check HACS Constrains
if not check_constans(hacs):
if hacs.configuration.config_type == "flow":
if hacs.configuration.config_entry is not None:
await async_remove_entry(hacs.hass, hacs.configuration.config_entry)
return False
# Set up frontend
await setup_frontend(hacs)
# Load HACS
if not await load_hacs_repository(hacs):
if hacs.configuration.config_type == "flow":
if hacs.configuration.config_entry is not None:
await async_remove_entry(hacs.hass, hacs.configuration.config_entry)
return False
val = ValidateData()
if not val.validate_local_data_file():
if hacs.configuration.config_type == "flow":
if hacs.configuration.config_entry is not None:
await async_remove_entry(hacs.hass, hacs.configuration.config_entry)
return False
# Restore from storefiles
if not await hacs.data.restore():
hacs_repo = hacs().get_by_name("hacs/integration")
hacs_repo.pending_restart = True
if hacs.configuration.config_type == "flow":
if hacs.configuration.config_entry is not None:
await async_remove_entry(hacs.hass, hacs.configuration.config_entry)
return False
# Add aditional categories
if hacs.configuration.appdaemon:
ELEMENT_TYPES.append("appdaemon")
if hacs.configuration.python_script:
ELEMENT_TYPES.append("python_script")
if hacs.configuration.theme:
ELEMENT_TYPES.append("theme")
hacs.common.categories = sorted(ELEMENT_TYPES)
# Setup startup tasks
if hacs.configuration.config_type == "yaml":
hacs.hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_START, hacs().startup_tasks()
)
else:
async_call_later(hacs.hass, 5, hacs().startup_tasks())
# Print DEV warning
if hacs.configuration.dev:
hacs.logger.warning(DEV_MODE)
hacs.hass.components.persistent_notification.create(
title="HACS DEV MODE", message=DEV_MODE, notification_id="hacs_dev_mode"
)
# Add sensor
add_sensor(hacs)
# Set up services
# await add_services(hacs)
# Mischief managed!
return True
async def async_remove_entry(hass, config_entry):
"""Handle removal of an entry."""
Hacs().logger.info("Disabling HACS")
Hacs().logger.info("Removing recuring tasks")
for task in Hacs().tasks:
task()
Hacs().logger.info("Removing sensor")
try:
await hass.config_entries.async_forward_entry_unload(config_entry, "sensor")
except ValueError:
pass
Hacs().logger.info("Removing sidepanel")
try:
hass.components.frontend.async_remove_panel("hacs_web")
except AttributeError:
pass
Hacs().system.disabled = True
Hacs().logger.info("HACS is now disabled")
async def reload_hacs(hass, config_entry):
"""Reload HACS."""
await async_remove_entry(hass, config_entry)
await async_setup_entry(hass, config_entry)
-421
View File
@@ -1,421 +0,0 @@
"""API Endpoins."""
from time import time
from aiohttp import web
from integrationhelper import Logger
from .http import HacsWebResponse
APIRESPONSE = {}
def apiresponse(classname):
"""Decorator used to register API Responses."""
APIRESPONSE[classname.name] = classname
return classname
class HacsAPI(HacsWebResponse):
"""HacsAPI class."""
name = "hacsapi"
def __init__(self):
"""Initialize."""
self.logger = Logger("hacs.api")
self.url = self.hacsapi + "/{endpoint}"
async def post(self, request, endpoint): # pylint: disable=unused-argument
"""Handle HACS API requests."""
if self.system.disabled:
return web.Response(status=404)
self.endpoint = endpoint
self.postdata = await request.post()
self.raw_headers = request.raw_headers
self.request = request
self.logger.debug(f"Endpoint ({endpoint}) called")
if self.configuration.dev:
self.logger.debug(f"Raw headers ({self.raw_headers})")
self.logger.debug(f"Postdata ({self.postdata})")
if self.endpoint in APIRESPONSE:
try:
response = APIRESPONSE[self.endpoint]
response = await response.response(self)
except Exception as exception:
render = self.render(f"error", message=exception)
return web.Response(
body=render, content_type="text/html", charset="utf-8"
)
else:
# Return default response.
response = await APIRESPONSE["generic"].response(self)
# set headers
response.headers["Cache-Control"] = "max-age=0, must-revalidate"
# serve the response
return response
class HacsRunningTask(HacsAPI):
"""Return if BG task is running."""
name = "hacs:task"
def __init__(self):
"""Initialize."""
self.url = "/hacs_task"
async def get(self, request): # pylint: disable=unused-argument
"""Handle GET request."""
return web.json_response({"task": self.system.status.background_task})
@apiresponse
class Generic(HacsAPI):
"""Generic API response."""
name = "generic"
async def response(self):
"""Response."""
self.logger.error(f"Unknown endpoint '{self.endpoint}'")
return web.HTTPFound(f"/hacsweb/{self.token}/settings?timestamp={time()}")
@apiresponse
class RemoveNewFlag(HacsAPI):
"""Remove new flag on all repositories."""
name = "remove_new_flag"
async def response(self):
"""Response."""
for repository in self.repositories:
repository.status.new = False
await self.data.async_write()
return web.HTTPFound(
f"/hacsweb/{self.token}/{self.postdata['return']}?timestamp={time()}"
)
@apiresponse
class DevTemplate(HacsAPI):
"""Remove new flag on all repositories."""
name = "dev_template"
async def response(self):
"""Response."""
from .handler.template import render_template
if "set" in self.postdata:
self.developer.template_id = self.postdata.get("repository_id")
repository = self.get_by_id(self.developer.template_id)
template = render_template(self.postdata.get("template", ""), repository)
info = await self.github.render_markdown(template)
info = info.replace("<h3>", "<h6>").replace("</h3>", "</h6>")
info = info.replace("<h2>", "<h5>").replace("</h2>", "</h5>")
info = info.replace("<h1>", "<h4>").replace("</h1>", "</h4>")
info = info.replace("<code>", "<code class='codeinfo'>")
info = info.replace(
'<a href="http', '<a rel="noreferrer" target="_blank" href="http'
)
info = info.replace("<ul>", "")
info = info.replace("</ul>", "")
self.developer.template_content = info
else:
self.developer.template_content = ""
self.developer.template_id = "Repository ID"
render = self.render("settings/dev/template_test")
return web.Response(body=render, content_type="text/html", charset="utf-8")
@apiresponse
class DevView(HacsAPI):
"""Set HA version view."""
name = "devview"
async def response(self):
"""Response."""
render = self.render(f"settings/dev/{self.postdata['view']}")
return web.Response(body=render, content_type="text/html", charset="utf-8")
@apiresponse
class SetHAVersionAction(HacsAPI):
"""Set HA version action."""
name = "set_ha_version_action"
async def response(self):
"""Response."""
self.common.ha_version = self.postdata["ha_version"]
render = self.render("settings/dev/set_ha_version")
return web.Response(body=render, content_type="text/html", charset="utf-8")
@apiresponse
class RepositoryInstall(HacsAPI):
"""Install repository."""
name = "repository_install"
async def response(self):
"""Response."""
repository = self.get_by_id(self.postdata["repository_id"])
await repository.install()
await self.data.async_write()
return web.HTTPFound(
f"/hacsweb/{self.token}/repository/{repository.information.uid}?timestamp={time()}"
)
@apiresponse
class RepositoryUpdate(HacsAPI):
"""Update repository."""
name = "repository_update"
async def response(self):
"""Response."""
repository = self.get_by_id(self.postdata["repository_id"])
await repository.update_repository()
await self.data.async_write()
return web.HTTPFound(
f"/hacsweb/{self.token}/repository/{repository.information.uid}?timestamp={time()}"
)
@apiresponse
class RepositoryUninstall(HacsAPI):
"""Uninstall repository."""
name = "repository_uninstall"
async def response(self):
"""Response."""
repository = self.get_by_id(self.postdata["repository_id"])
await repository.uninstall()
await self.data.async_write()
return web.HTTPFound(f"/hacsweb/{self.token}/overview?timestamp={time()}")
@apiresponse
class RepositoryRemove(HacsAPI):
"""Remove repository."""
name = "repository_remove"
async def response(self):
"""Response."""
repository = self.get_by_id(self.postdata["repository_id"])
await repository.remove()
await self.data.async_write()
return web.HTTPFound(f"/hacsweb/{self.token}/settings?timestamp={time()}")
@apiresponse
class RepositoryHide(HacsAPI):
"""Hide repository."""
name = "repository_hide"
async def response(self):
"""Response."""
repository = self.get_by_id(self.postdata["repository_id"])
repository.hide = True
await self.data.async_write()
return web.HTTPFound(f"/hacsweb/{self.token}/store?timestamp={time()}")
@apiresponse
class RepositoryUnhide(HacsAPI):
"""Unhide repository."""
name = "repository_unhide"
async def response(self):
"""Response."""
repository = self.get_by_id(self.postdata["repository_id"])
repository.hide = False
await self.data.async_write()
return web.HTTPFound(f"/hacsweb/{self.token}/settings?timestamp={time()}")
@apiresponse
class RepositoryBetaHide(HacsAPI):
"""Hide Beta repository."""
name = "repository_beta_hide"
async def response(self):
"""Response."""
repository = self.get_by_id(self.postdata["repository_id"])
repository.status.show_beta = False
await repository.update_repository()
await self.data.async_write()
return web.HTTPFound(
f"/hacsweb/{self.token}/repository/{repository.information.uid}?timestamp={time()}"
)
@apiresponse
class RepositoryBetaShow(HacsAPI):
"""Show Beta repository."""
name = "repository_beta_show"
async def response(self):
"""Response."""
repository = self.get_by_id(self.postdata["repository_id"])
repository.status.show_beta = True
await repository.update_repository()
await self.data.async_write()
return web.HTTPFound(
f"/hacsweb/{self.token}/repository/{repository.information.uid}?timestamp={time()}"
)
@apiresponse
class RepositoriesReload(HacsAPI):
"""Reload repository data."""
name = "repositories_reload"
async def response(self):
"""Response."""
self.hass.async_create_task(self.recuring_tasks_all())
return web.HTTPFound(f"/hacsweb/{self.token}/settings?timestamp={time()}")
@apiresponse
class RepositoriesUpgradeAll(HacsAPI):
"""Upgrade all repositories."""
name = "repositories_upgrade_all"
async def response(self):
"""Response."""
for repository in self.repositories:
if repository.pending_upgrade:
await repository.install()
await self.data.async_write()
return web.HTTPFound(f"/hacsweb/{self.token}/settings?timestamp={time()}")
@apiresponse
class RepositoryRegister(HacsAPI):
"""Register repository."""
name = "repository_register"
async def response(self):
"""Response."""
repository_name = self.postdata.get("custom_url")
repository_type = self.postdata.get("repository_type")
# Validate data
if not repository_name:
message = "Repository URL is missing."
return web.HTTPFound(
f"/hacsweb/{self.token}/settings?timestamp={time()}&message={message}"
)
if repository_type is None:
message = "Type is missing for '{}'.".format(repository_name)
return web.HTTPFound(
f"/hacsweb/{self.token}/settings?timestamp={time()}&message={message}"
)
# Stip first part if it's an URL.
if "github" in repository_name:
repository_name = repository_name.split("github.com/")[-1]
# Strip whitespace
repository_name = repository_name.split()[0]
# If it still have content, continue.
if repository_name != "":
if len(repository_name.split("/")) != 2:
message = f"""
{repository_name} is not a valid format.
Correct format is 'https://github.com/DEVELOPER/REPOSITORY'
or 'DEVELOPER/REPOSITORY'.
"""
return web.HTTPFound(
f"/hacsweb/{self.token}/settings?timestamp={time()}&message={message}"
)
is_known_repository = self.is_known(repository_name)
if is_known_repository:
message = f"'{repository_name}' is already registered, look for it in the store."
return web.HTTPFound(
f"/hacsweb/{self.token}/settings?timestamp={time()}&message={message}"
)
if repository_name in self.common.blacklist:
self.common.blacklist.remove(repository_name)
await self.register_repository(repository_name, repository_type)
repository = self.get_by_name(repository_name)
if repository is not None:
return web.HTTPFound(
f"/hacsweb/{self.token}/repository/{repository.information.uid}?timestamp={time()}"
)
message = f"""
Could not add '{repository_name}' with type '{repository_type}' at this time.</br>
If you used the correct type, check the log for more details."""
return web.HTTPFound(
f"/hacsweb/{self.token}/settings?timestamp={time()}&message={message}"
)
@apiresponse
class RepositorySelectTag(HacsAPI):
"""Select tag for Repository."""
name = "repository_select_tag"
async def response(self):
"""Response."""
from aiogithubapi import AIOGitHubException
from .hacsbase.exceptions import HacsRequirement
repository = self.get_by_id(self.postdata["repository_id"])
if self.postdata["selected_tag"] == repository.releases.last_release:
repository.status.selected_tag = None
else:
repository.status.selected_tag = self.postdata["selected_tag"]
try:
await repository.update_repository()
except (AIOGitHubException, HacsRequirement):
repository.status.selected_tag = repository.releases.last_release
await repository.update_repository()
message = "The version {} is not valid for use with HACS.".format(
self.postdata["selected_tag"]
)
return web.HTTPFound(
f"/hacsweb/{self.token}/repository/{repository.information.uid}?timestamp={time()}&message={message}"
)
await self.data.async_write()
return web.HTTPFound(
f"/hacsweb/{self.token}/repository/{repository.information.uid}?timestamp={time()}"
)
@apiresponse
class FrontentMode(HacsAPI):
"""Set the frontend mode."""
name = "frontend_mode"
async def response(self):
"""Response."""
self.configuration.frontend_mode = self.postdata["view_type"]
await self.data.async_write()
return web.HTTPFound(f"/hacsweb/{self.token}/settings?timestamp={time()}")
@@ -1,100 +0,0 @@
"""Adds config flow for HACS."""
# pylint: disable=dangerous-default-value
import logging
import voluptuous as vol
from aiogithubapi import AIOGitHub, AIOGitHubException, AIOGitHubAuthentication
from homeassistant import config_entries
from homeassistant.core import callback
from homeassistant.helpers import aiohttp_client
from .const import DOMAIN
from .configuration_schema import hacs_base_config_schema, hacs_config_option_schema
_LOGGER = logging.getLogger(__name__)
class HacsFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
"""Config flow for HACS."""
VERSION = 1
CONNECTION_CLASS = config_entries.CONN_CLASS_CLOUD_POLL
def __init__(self):
"""Initialize."""
self._errors = {}
async def async_step_user(self, user_input={}):
"""Handle a flow initialized by the user."""
self._errors = {}
if self._async_current_entries():
return self.async_abort(reason="single_instance_allowed")
if self.hass.data.get(DOMAIN):
return self.async_abort(reason="single_instance_allowed")
if user_input is not None:
if await self._test_token(user_input["token"]):
return self.async_create_entry(title="", data=user_input)
self._errors["base"] = "auth"
return await self._show_config_form(user_input)
return await self._show_config_form(user_input)
async def _show_config_form(self, user_input):
"""Show the configuration form to edit location data."""
return self.async_show_form(
step_id="user",
data_schema=vol.Schema(hacs_base_config_schema(user_input)),
errors=self._errors,
)
@staticmethod
@callback
def async_get_options_flow(config_entry):
return HacsOptionsFlowHandler(config_entry)
async def async_step_import(self, user_input):
"""Import a config entry.
Special type of import, we're not actually going to store any data.
Instead, we're going to rely on the values that are in config file.
"""
if self._async_current_entries():
return self.async_abort(reason="single_instance_allowed")
return self.async_create_entry(title="configuration.yaml", data={})
async def _test_token(self, token):
"""Return true if token is valid."""
try:
session = aiohttp_client.async_get_clientsession(self.hass)
client = AIOGitHub(token, session)
await client.get_repo("hacs/org")
return True
except (AIOGitHubException, AIOGitHubAuthentication):
pass
return False
class HacsOptionsFlowHandler(config_entries.OptionsFlow):
"""HACS config flow options handler."""
def __init__(self, config_entry):
"""Initialize HACS options flow."""
self.config_entry = config_entry
async def async_step_init(self, user_input=None):
"""Manage the options."""
return await self.async_step_user()
async def async_step_user(self, user_input=None):
"""Handle a flow initialized by the user."""
if user_input is not None:
return self.async_create_entry(title="", data=user_input)
return self.async_show_form(
step_id="user",
data_schema=vol.Schema(
hacs_config_option_schema(self.config_entry.options)
),
)
@@ -1,49 +0,0 @@
"""HACS Configuration Schemas."""
# pylint: disable=dangerous-default-value
import voluptuous as vol
from .const import LOCALE
# Configuration:
TOKEN = "token"
SIDEPANEL_TITLE = "sidepanel_title"
SIDEPANEL_ICON = "sidepanel_icon"
APPDAEMON = "appdaemon"
PYTHON_SCRIPT = "python_script"
THEME = "theme"
# Options:
COUNTRY = "country"
RELEASE_LIMIT = "release_limit"
EXPERIMENTAL = "experimental"
def hacs_base_config_schema(config: dict = {}) -> dict:
"""Return a shcema configuration dict for HACS."""
if not config:
config = {
TOKEN: "xxxxxxxxxxxxxxxxxxxxxxxxxxx",
SIDEPANEL_TITLE: "Community",
SIDEPANEL_ICON: "mdi:alpha-c-box",
APPDAEMON: False,
PYTHON_SCRIPT: False,
THEME: False,
}
return {
vol.Required(TOKEN, default=config.get(TOKEN)): str,
vol.Optional(SIDEPANEL_TITLE, default=config.get(SIDEPANEL_TITLE)): str,
vol.Optional(SIDEPANEL_ICON, default=config.get(SIDEPANEL_ICON)): str,
vol.Optional(APPDAEMON, default=config.get(APPDAEMON)): bool,
vol.Optional(PYTHON_SCRIPT, default=config.get(PYTHON_SCRIPT)): bool,
vol.Optional(THEME, default=config.get(THEME)): bool,
}
def hacs_config_option_schema(options: dict = {}) -> dict:
"""Return a shcema for HACS configuration options."""
if not options:
options = {COUNTRY: "ALL", RELEASE_LIMIT: 5, EXPERIMENTAL: False}
return {
vol.Optional("country", default=options.get(COUNTRY)): vol.In(LOCALE),
vol.Optional(RELEASE_LIMIT, default=options.get(RELEASE_LIMIT)): int,
vol.Optional(EXPERIMENTAL, default=options.get(EXPERIMENTAL)): bool,
}
@@ -1,295 +0,0 @@
"""Constants for HACS"""
NAME_LONG = "HACS (Home Assistant Community Store)"
NAME_SHORT = "HACS"
VERSION = "0.16.3"
DOMAIN = "hacs"
PROJECT_URL = "https://github.com/hacs/integration/"
CUSTOM_UPDATER_LOCATIONS = [
"{}/custom_components/custom_updater.py",
"{}/custom_components/custom_updater/__init__.py",
]
ISSUE_URL = f"{PROJECT_URL}issues"
DOMAIN_DATA = f"{NAME_SHORT.lower()}_data"
ELEMENT_TYPES = ["integration", "plugin"]
IFRAME = {
"title": "Community",
"icon": "mdi:alpha-c-box",
"url": "/community_overview",
"path": "community",
"require_admin": True,
}
# Messages
CUSTOM_UPDATER_WARNING = """
This cannot be used with custom_updater.
To use this you need to remove custom_updater form {}
"""
DEV_MODE = "You have 'dev' enabled for HACS, this is not intended for regular use, no support will be given if you break something."
STARTUP = f"""
-------------------------------------------------------------------
HACS (Home Assistant Community Store)
Version: {VERSION}
This is a custom integration
If you have any issues with this you need to open an issue here:
https://github.com/hacs/integration/issues
-------------------------------------------------------------------
"""
LOCALE = [
"ALL",
"AF",
"AL",
"DZ",
"AS",
"AD",
"AO",
"AI",
"AQ",
"AG",
"AR",
"AM",
"AW",
"AU",
"AT",
"AZ",
"BS",
"BH",
"BD",
"BB",
"BY",
"BE",
"BZ",
"BJ",
"BM",
"BT",
"BO",
"BQ",
"BA",
"BW",
"BV",
"BR",
"IO",
"BN",
"BG",
"BF",
"BI",
"KH",
"CM",
"CA",
"CV",
"KY",
"CF",
"TD",
"CL",
"CN",
"CX",
"CC",
"CO",
"KM",
"CG",
"CD",
"CK",
"CR",
"HR",
"CU",
"CW",
"CY",
"CZ",
"CI",
"DK",
"DJ",
"DM",
"DO",
"EC",
"EG",
"SV",
"GQ",
"ER",
"EE",
"ET",
"FK",
"FO",
"FJ",
"FI",
"FR",
"GF",
"PF",
"TF",
"GA",
"GM",
"GE",
"DE",
"GH",
"GI",
"GR",
"GL",
"GD",
"GP",
"GU",
"GT",
"GG",
"GN",
"GW",
"GY",
"HT",
"HM",
"VA",
"HN",
"HK",
"HU",
"IS",
"IN",
"ID",
"IR",
"IQ",
"IE",
"IM",
"IL",
"IT",
"JM",
"JP",
"JE",
"JO",
"KZ",
"KE",
"KI",
"KP",
"KR",
"KW",
"KG",
"LA",
"LV",
"LB",
"LS",
"LR",
"LY",
"LI",
"LT",
"LU",
"MO",
"MK",
"MG",
"MW",
"MY",
"MV",
"ML",
"MT",
"MH",
"MQ",
"MR",
"MU",
"YT",
"MX",
"FM",
"MD",
"MC",
"MN",
"ME",
"MS",
"MA",
"MZ",
"MM",
"NA",
"NR",
"NP",
"NL",
"NC",
"NZ",
"NI",
"NE",
"NG",
"NU",
"NF",
"MP",
"NO",
"OM",
"PK",
"PW",
"PS",
"PA",
"PG",
"PY",
"PE",
"PH",
"PN",
"PL",
"PT",
"PR",
"QA",
"RO",
"RU",
"RW",
"RE",
"BL",
"SH",
"KN",
"LC",
"MF",
"PM",
"VC",
"WS",
"SM",
"ST",
"SA",
"SN",
"RS",
"SC",
"SL",
"SG",
"SX",
"SK",
"SI",
"SB",
"SO",
"ZA",
"GS",
"SS",
"ES",
"LK",
"SD",
"SR",
"SJ",
"SZ",
"SE",
"CH",
"SY",
"TW",
"TJ",
"TZ",
"TH",
"TL",
"TG",
"TK",
"TO",
"TT",
"TN",
"TR",
"TM",
"TC",
"TV",
"UG",
"UA",
"AE",
"GB",
"US",
"UM",
"UY",
"UZ",
"VU",
"VE",
"VN",
"VG",
"VI",
"WF",
"EH",
"YE",
"ZM",
"ZW",
]
@@ -1,44 +0,0 @@
"""HACS Startup constrains."""
# pylint: disable=bad-continuation
import os
import json
from .const import CUSTOM_UPDATER_LOCATIONS, CUSTOM_UPDATER_WARNING
from .helpers.misc import version_is_newer_than_version
def check_constans(hacs):
"""Check HACS constrains."""
if not constrain_custom_updater(hacs):
return False
if not constrain_version(hacs):
return False
return True
def constrain_custom_updater(hacs):
"""Check if custom_updater exist."""
for location in CUSTOM_UPDATER_LOCATIONS:
if os.path.exists(location.format(hacs.system.config_path)):
msg = CUSTOM_UPDATER_WARNING.format(
location.format(hacs.system.config_path)
)
hacs.logger.critical(msg)
return False
return True
def constrain_version(hacs):
"""Check if the version is valid."""
with open(
f"{hacs.system.config_path}/custom_components/hacs/manifest.json", "r"
) as read:
manifest = json.loads(read.read())
# Check if HA is the required version.
if version_is_newer_than_version(manifest["homeassistant"], hacs.system.ha_version):
hacs.logger.critical(
f"You need HA version {manifest['homeassistant']} or newer to use this integration."
)
return False
return True
@@ -1,49 +0,0 @@
"""Deprecated functions, should be fine to remove."""
async def add_services(hacs):
"""Add services."""
# Service registration
async def service_hacs_install(call):
"""Install a repository."""
repository = str(call.data["repository"])
if repository not in hacs().store.repositories:
hacs.logger.error("%s is not a konwn repository!", repository)
return
repository = hacs().store.repositories[repository]
await repository.install()
async def service_hacs_register(call):
"""register a repository."""
repository = call.data["repository"]
repository_type = call.data["repository_type"]
if await hacs().is_known_repository(repository):
hacs.logger.error("%s is already a konwn repository!", repository)
return
await hacs().register_new_repository(repository_type, repository)
async def service_hacs_load(call):
"""register a repository."""
from homeassistant.loader import async_get_custom_components
del hacs.hass.data["custom_components"]
await async_get_custom_components(hacs.hass)
hacs.hass.services.async_register("hacs", "install", service_hacs_install)
hacs.hass.services.async_register("hacs", "register", service_hacs_register)
hacs.hass.services.async_register("hacs", "load", service_hacs_load)
# This should probably be in a dedicated test "package"
async def test_repositories(hacs):
"""Test repositories."""
await hacs().register_repository("ludeeus/theme-hacs", "theme")
await hacs().register_repository("ludeeus/ps-hacs", "python_script")
await hacs().register_repository("ludeeus/integration-hacs", "integration")
await hacs().register_repository(
"rgruebel/ha_zigbee2mqtt_networkmap", "integration"
)
await hacs().register_repository("ludeeus/ad-hacs", "appdaemon")
await hacs().register_repository("jonkristian/entur-card", "plugin") # Dist
await hacs().register_repository("kalkih/mini-media-player", "plugin") # Release
await hacs().register_repository("custom-cards/monster-card", "plugin") # root
Whitespace-only changes.
@@ -1,504 +0,0 @@
.yaml {
font-family: monospace, monospace;
font-size: 1em;
border-style: solid;
border-width: thin;
margin: 0;
overflow: auto;
display: inline-flex;
width: calc(100% - 20px);
white-space: pre-wrap;
}
.hacslist {
border: none;
}
.hacs-card-container {
display: grid;
grid-gap: 10px;
}
.hacs-overview-container {
width: 95%;
margin-left: 2.5%;
margin-right: 2.5%;
margin-bottom: 10px;
display: inline-block;
}
.hacs-form {
display: contents;
}
.hacs-table {
background-color: var(--paper-card-background-color);
}
.hacs-content {
position: absolute;
top: 49px;
left: 0px;
right: 0px;
bottom: 0px;
overflow-y: auto;
overflow-x: hidden;
padding-top: 20px;
padding-bottom: 15px;
}
.hacs-card {
height: 100%;
background-color: var(--paper-card-background-color) !important;
padding: 3px;
line-height: 1;
}
.overview {
height: 100%;
}
.progressbar {
margin-left: 2.5%;
margin-right: 2.5%;
margin-bottom: 20px;
}
.hacs-card-title {
font-size: medium;
color: var(--primary-text-color);
}
tr.hacs-table-row.repository {
border-bottom: 0px;
display: table-row-group;
}
td.repository {
width: 50%;
padding: 0px;
}
td.repository.text {
padding-left: 12px;
}
select.hacs-select.repository {
width: 100%;
}
.hacs-card-content {
color: var(--secondary-text-color);
font-style: italic;
font-size: small;
}
.card-status {
font-size: 18px;
padding-right: 4px;
}
.hacs-card-standalone {
background-color: var(--paper-card-background-color) !important;
color: var(--primary-text-color);
padding: 16px;
}
.installed {
color: var(--hacs-status-installed);
}
.pending-restart {
color: var(--hacs-status-pending-restart);
}
.pending-upgrade {
color: var(--hacs-status-pending-update);
}
.default {
color: var(--primary-text-color);
}
.hacs-nav {
background-color: var(--primary-color) !important;
position: fixed;
height: auto;
}
a {
color: var(--primary-color);
}
.disabledaction {
cursor: default;
color: var(--primary-color);
opacity: 0.5;
}
.hacs-bar {
background-color: var(--primary-color) !important;
}
.hacs-bar-background {
background-color: var(--dark-primary-color) !important;
}
.errorview {
display: block;
margin-bottom: 30px;
}
.hacscolor {
background-color: var(--paper-card-background-color) !important;
color: var(--primary-text-color);
}
.hacsbutton {
margin: 3%;
background-color: var(--primary-color) !important;
}
.hacsadminbutton {
margin: 1%;
background-color: var(--primary-color) !important;
}
body {
background-color: var(--primary-background-color) !important;
color: var(--primary-text-color);
overflow: hidden;
font-size: 14px;
}
input[type="text"]:not(.browser-default):focus:not([readonly]) {
border-bottom: 1px solid var(--primary-color);
-webkit-box-shadow: 0 1px 0 0 var(--primary-color);
box-shadow: 0 1px 0 0 var(--primary-color);
}
.dropdown-list-item {
color: var(--primary-color) !important;
background-color: var(--paper-card-background-color) !important;
}
a.dropdown-list-item:hover {
opacity: 0.95;
}
.actionlink {
color: var(--primary-color) !important
}
.uninstall {
float: right;
color: var(--google-red-500) !important;
font-weight: bold;
}
@media all and (max-width: 550px) {
select.hacs-select.custom_repository {
width: 100%;
}
input#custom_url {
width: 100% !important;
}
.actionlink {
width: 100%;
padding: 5px;
display: block;
font-size: x-large;
text-align: center;
}
.uninstall {
float: none;
}
}
.minigrid {
display: contents;
}
.card-action a:hover {
opacity: 0.6 !important;
}
.codeinfo {
opacity: 0.6 !important;
}
.hacs-select {
display: initial !important;
margin-left: 1%;
width: 20%;
background-color: transparent;
border-color: transparent;
color: var(--primary-text-color);
}
.hacs-badge {
background-color: var(--hacs-badge-color);
margin-right: 1%;
font-size: 12px;
padding: 0px 4px 2px 4px;
color: var(--hacs-badge-text-color);
-moz-border-radius: 10px 10px 10px 10px;
border-radius: 10px 10px 10px 10px;
}
tr.hacs-table-row:hover {
cursor: pointer;
}
/* color vars*/
:root {
--hacs-status-installed: #126e15;
--hacs-status-pending-restart: #a70000;
--hacs-status-pending-update: #ffab40;
--hacs-status-default: var(--primary-text-color);
--hacs-badge-color: var(--primary-color);
--hacs-badge-text-color: var(--primary-text-color);
--primary-color: #03a9f4;
--primary-text-color: #000000;
--secondary-text-color: #424141;
--primary-background-color: #fafafa;
--paper-card-background-color: #ffffff;
--dark-primary-color: #00405d;
--google-red-500: #db4437;
}
/* hug screens*/
@media all and (min-width: 2000px) {
.hacs-card-container {
grid-template-columns: repeat(6, 1fr);
}
}
/* even bigger screens*/
@media all and (min-width: 1500px) and (max-width: 1999px) {
.hacs-card-container {
grid-template-columns: repeat(5, 1fr);
}
}
/* bigger screens*/
@media all and (min-width: 1000px) and (max-width: 1499px) {
.hacs-card-container {
grid-template-columns: repeat(4, 1fr);
}
}
/* big screens */
@media all and (min-width: 550px) and (max-width: 999px) {
.hacs-card-container {
grid-template-columns: repeat(3, 1fr);
}
#main::-webkit-scrollbar-track
{
border-radius: 10px;
}
#main::-webkit-scrollbar
{
width: 12px;
}
#main::-webkit-scrollbar-thumb
{
border-radius: 10px;
background-color: var(--primary-color);
}
}
/* smal screens */
@media all and (max-width: 550px) {
body {
overflow: scroll !important;
}
.minigrid {
display: grid;
}
.smal-hide {
display: none !important;
}
.hacs-content {
overflow: scroll !important;
-webkit-overflow-scrolling: touch;
}
}
/* laoder */
*.hidden {
display: none !important;
}
div.loading{
position: fixed;
z-index: 999;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(16, 16, 16, 0.5);
}
@-webkit-keyframes uil-ring-anim {
0% {
-ms-transform: rotate(0deg);
-moz-transform: rotate(0deg);
-webkit-transform: rotate(0deg);
-o-transform: rotate(0deg);
transform: rotate(0deg);
}
100% {
-ms-transform: rotate(360deg);
-moz-transform: rotate(360deg);
-webkit-transform: rotate(360deg);
-o-transform: rotate(360deg);
transform: rotate(360deg);
}
}
@-webkit-keyframes uil-ring-anim {
0% {
-ms-transform: rotate(0deg);
-moz-transform: rotate(0deg);
-webkit-transform: rotate(0deg);
-o-transform: rotate(0deg);
transform: rotate(0deg);
}
100% {
-ms-transform: rotate(360deg);
-moz-transform: rotate(360deg);
-webkit-transform: rotate(360deg);
-o-transform: rotate(360deg);
transform: rotate(360deg);
}
}
@-moz-keyframes uil-ring-anim {
0% {
-ms-transform: rotate(0deg);
-moz-transform: rotate(0deg);
-webkit-transform: rotate(0deg);
-o-transform: rotate(0deg);
transform: rotate(0deg);
}
100% {
-ms-transform: rotate(360deg);
-moz-transform: rotate(360deg);
-webkit-transform: rotate(360deg);
-o-transform: rotate(360deg);
transform: rotate(360deg);
}
}
@-ms-keyframes uil-ring-anim {
0% {
-ms-transform: rotate(0deg);
-moz-transform: rotate(0deg);
-webkit-transform: rotate(0deg);
-o-transform: rotate(0deg);
transform: rotate(0deg);
}
100% {
-ms-transform: rotate(360deg);
-moz-transform: rotate(360deg);
-webkit-transform: rotate(360deg);
-o-transform: rotate(360deg);
transform: rotate(360deg);
}
}
@-moz-keyframes uil-ring-anim {
0% {
-ms-transform: rotate(0deg);
-moz-transform: rotate(0deg);
-webkit-transform: rotate(0deg);
-o-transform: rotate(0deg);
transform: rotate(0deg);
}
100% {
-ms-transform: rotate(360deg);
-moz-transform: rotate(360deg);
-webkit-transform: rotate(360deg);
-o-transform: rotate(360deg);
transform: rotate(360deg);
}
}
@-webkit-keyframes uil-ring-anim {
0% {
-ms-transform: rotate(0deg);
-moz-transform: rotate(0deg);
-webkit-transform: rotate(0deg);
-o-transform: rotate(0deg);
transform: rotate(0deg);
}
100% {
-ms-transform: rotate(360deg);
-moz-transform: rotate(360deg);
-webkit-transform: rotate(360deg);
-o-transform: rotate(360deg);
transform: rotate(360deg);
}
}
@-o-keyframes uil-ring-anim {
0% {
-ms-transform: rotate(0deg);
-moz-transform: rotate(0deg);
-webkit-transform: rotate(0deg);
-o-transform: rotate(0deg);
transform: rotate(0deg);
}
100% {
-ms-transform: rotate(360deg);
-moz-transform: rotate(360deg);
-webkit-transform: rotate(360deg);
-o-transform: rotate(360deg);
transform: rotate(360deg);
}
}
@keyframes uil-ring-anim {
0% {
-ms-transform: rotate(0deg);
-moz-transform: rotate(0deg);
-webkit-transform: rotate(0deg);
-o-transform: rotate(0deg);
transform: rotate(0deg);
}
100% {
-ms-transform: rotate(360deg);
-moz-transform: rotate(360deg);
-webkit-transform: rotate(360deg);
-o-transform: rotate(360deg);
transform: rotate(360deg);
}
}
.uil-ring-css {
margin: auto;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
width: 200px;
height: 200px;
}
.uil-ring-css > div {
position: absolute;
display: block;
width: 160px;
height: 160px;
top: 20px;
left: 20px;
border-radius: 80px;
box-shadow: 0 6px 0 0 var(--primary-color);
-ms-animation: uil-ring-anim 1s linear infinite;
-moz-animation: uil-ring-anim 1s linear infinite;
-webkit-animation: uil-ring-anim 1s linear infinite;
-o-animation: uil-ring-anim 1s linear infinite;
animation: uil-ring-anim 1s linear infinite;
}
@@ -1,111 +0,0 @@
// Copy active HA theme
document.getElementsByTagName("html").item(0).setAttribute("style", parent.document.getElementsByTagName("html").item(0).style.cssText)
// Copy yhe content of the Lovelace example to the clipboard.
function CopyToLovelaceExampleToClipboard() {
window.getSelection().selectAllChildren(document.getElementById("LovelaceExample"));
document.execCommand("copy");
document.getSelection().empty()
document.getElementById('lovelacecopy').style.color = 'forestgreen';
}
// Show progress bar
function ShowProgressBar() {
document.getElementById('progressbar').style.display = 'block';
}
// Hard reloading
function HardReload() {
parent.location.reload(true)
}
// Searchbar
function Search() {
var input = document.getElementById("Search");
if (input) {
var filter = input.value.toLowerCase();
var nodes = document.getElementsByClassName('hacs-card');
for (var i = 0; i < nodes.length; i++) {
if (nodes[i].innerHTML.toLowerCase().includes(filter)) {
nodes[i].style.display = "block";
} else {
nodes[i].style.display = "none";
}
}
var nodes = document.getElementsByClassName('hacs-table-row');
for (i = 0; i < nodes.length; i++) {
if (nodes[i].innerHTML.toLowerCase().includes(filter)) {
nodes[i].style.display = "table-row";
} else {
nodes[i].style.display = "none";
}
}
}
}
// Dropdown
document.addEventListener('DOMContentLoaded', function () {
var elems = document.querySelectorAll('.dropdown-trigger');
M.Dropdown.init(elems, { hover: false, constrainWidth: false });
});
// Modal
document.addEventListener('DOMContentLoaded', function () {
var elems = document.querySelectorAll('.modal');
M.Modal.init(elems, {});
});
// Loader
function toggleLoading() {
var loadingOverlay = document.querySelector('.loading');
loadingOverlay.classList.remove('hidden')
document.activeElement.blur();
}
// Check if we can reload
function sleep(time) {
return new Promise((resolve) => setTimeout(resolve, time));
}
function CheckIfWeCanReload() {
var data = true;
const hacsrequest = new XMLHttpRequest()
hacsrequest.open('GET', '/hacs_task', true)
hacsrequest.onload = function () {
data = JSON.parse(this.response)
data = data["task"]
if (!data) {
console.log("Background task is no longer running, reloading in 5s...")
sleep(5000).then(() => {
location.reload()
});
}
}
hacsrequest.send()
}
function IsTaskRunning() {
let retval = false;
let disp = document.getElementsByClassName("progress")
if (disp) {
disp = disp.item(0).style.display;
if (disp == "block") {
retval = true
} else {
retval = false
}
}
return retval
}
window.setInterval(function () {
var running = false;
running = IsTaskRunning();
if (running) {
CheckIfWeCanReload();
}
}, 10000);
@@ -1,51 +0,0 @@
{% set progressbar = 'block' if hacs.system.status.background_task else 'none' %}
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="/hacsweb/{{ hacs.token }}/static/materialize.min.css.gz">
<link rel="stylesheet" href="/hacsweb/{{ hacs.token }}/static/all.min.css.gz">
<script src="/hacsweb/{{ hacs.token }}/static/materialize.min.js.gz"></script>
<link rel="stylesheet" href="/hacsweb/{{ hacs.token }}/static/static/hacs.css">
<script src="/hacsweb/{{ hacs.token }}/static/hacs.js"></script>
</head>
<body>
<div class="navbar-fixed">
<nav class="nav-extended hacs-nav">
<div class="nav-content">
<ul class="right tabs tabs-transparent">
<li class="tab {{ 'active' if location == 'overview' }}"><a href="/hacsweb/{{ hacs.token }}/overview?timestamp={{ timestamp }}">Overview</a></li>
<li class="tab {{ 'active' if location == 'store' }}"><a href="/hacsweb/{{ hacs.token }}/store?timestamp={{ timestamp }}">Store</a></li>
<li class="tab right {{ 'active' if location == 'settings' }}"><a href="/hacsweb/{{ hacs.token }}/settings?timestamp={{ timestamp }}">Settings</a></li>
</ul>
</div>
</nav>
</div>
<div id="main" class="hacs-content">
<div class="progressbar" style="display: {{ progressbar }}">
<p>Background task running, this page will reload when it's done.</p>
<div class="progress hacs-bar-background" id="progressbar">
<div class="indeterminate hacs-bar"></div>
</div>
</div>
<div class="loading hidden">
<div class='uil-ring-css' style='transform:scale(0.79);'>
<div></div>
</div>
</div>
{% if message %}
{% include 'message.html' with context %}
{% endif %}
{% set hacs_repo = hacs.get_by_name("hacs/integration") %}
{% if hacs_repo.pending_restart %}
{% set message = "The frontend of HACS has been disabled until you restart Home Assistant." %}
{% include 'message.html' with context %}
{% else %}
{% block content %}
{% endblock %}
{% endif %}
</div>
</body>
</html>
@@ -1,4 +0,0 @@
{% extends "base.html" %}
{% block content %}
{% endblock %}
@@ -1,36 +0,0 @@
<div class='hacs-overview-container'>
<h5>{{ displaytype }}</h5>
<div class='hacs-card-container'>
{% for repository in repositories.repositories %}
<a href="/hacsweb/{{ hacs.token }}/repository/{{ repository.information.uid }}?timestamp={{ timestamp }}"
class="hacs-card" onclick="toggleLoading()">
<div class="hacs-card overview">
<div id="statusicon">
</div>
<div id="title">
<input type="hidden" name="author" value="{{repository.information.authors}}">
<input type="hidden" name="topics" value="{{repository.information.topics}}">
<input type="hidden" name="full_name" value="{{repository.information.full_name}}">
<span class="hacs-card-title">
{% if location == 'store' and repository.status.new %}
<span title="{{ repository.display_status_description }}" class='hacs-badge'>NEW</span>
{% else %}
<i title="{{ repository.display_status_description }}"
class='fas fa-cube card-status {{repository.display_status}}'></i>
{% endif %}
{{repository.display_name}}
</span>
</div>
<div id="description">
<span class="hacs-card-content">
<p>{{repository.information.description}}</p>
</span>
</div>
</div>
</a>
{% endfor %}
</div>
</div>
</br>
</br>
@@ -1,47 +0,0 @@
{% set repositories = namespace(repositories=[]) %}
{% for repository in hacs.sorted_by_name %}
{% if repository.status.new %}
{% set repositories.repositories = repositories.repositories+[repository] %}
{% endif %}
{% endfor %}
{% if repositories.repositories %}
<div class='hacs-overview-container'>
<h5>NEW REPOSITORIES (ALL)</h5>
<form action="/hacsapi/{{ hacs.token }}/remove_new_flag" name="remove_new_flag" method="post" accept-charset="utf-8"
enctype="application/x-www-form-urlencoded" class="hacs-form">
<input type="hidden" name="return" value="store">
<a class="waves-effect waves-light btn modal-trigger hacsbutton" href="#"
onclick="toggleLoading();document.getElementsByName('remove_new_flag')[0].submit()" style="width: 95%;">
Remove the NEW flag for all new items
</a>
</form>
<div class='hacs-card-container'>
{% for repository in repositories.repositories %}
<a href="/hacsweb/{{ hacs.token }}/repository/{{ repository.information.uid }}?timestamp={{ timestamp }}"
class="hacs-card" onclick="toggleLoading()">
<div class="hacs-card overview">
<div id="statusicon">
</div>
<div id="title">
<span class="hacs-card-title">
<span class="hacs-badge">
{{repository.information.category | upper}}
</span>
</br></br>
{{repository.display_name}}
</span>
</div>
<div id="description">
<span class="hacs-card-content">
<p>{{repository.information.description}}</p>
</span>
</div>
</div>
</a>
{% endfor %}
</div>
</div>
</br>
</br>
{% endif %}
@@ -1,13 +0,0 @@
<div class='container'>
<div class="row">
<div class="col s12">
<div class="card-panel orange darken-4">
<div class="card-content white-text">
<span>
{{message}}
</span>
</div>
</div>
</div>
</div>
</div>
@@ -1,33 +0,0 @@
<div id="modal_upgrade_all" class="modal hacscolor">
<div class="modal-content">
<h5>Pending Upgrades</h5>
{% for repository in hacs.repositories %}
{% if repository.pending_upgrade %}
<p>- {{repository.information.name}} (
{{repository.display_installed_version}}
->
{{repository.display_available_version}}
)</p>
{% endif %}
{% endfor %}
</br>
<p>
Be careful using this feature, elements may contain breaking changes,
make sure you read the release notes for all the elements in the list above.
</p>
</div>
<div class="modal-footer hacscolor">
{% if hacs.system.status.background_task %}
<p>Background task is running, batch upgrade is disabled.</p>
{% else %}
<form action="/hacsapi/{{ hacs.token }}/repositories_upgrade_all" name="upgrade_all" method="post"
accept-charset="utf-8" enctype="application/x-www-form-urlencoded" class="hacs-form">
<a href="#" onclick="toggleLoading();document.getElementsByName('upgrade_all')[0].submit()"
class='waves-effect waves-light btn hacsbutton'
style="background-color: var(--google-red-500) !important; font-weight: bold;">
UPGRADE ALL
</a>
</form>
{% endif %}
</div>
</div>
@@ -1,12 +0,0 @@
<div id="haversion" class="modal hacscolor">
<div class="modal-content">
<h5>Unsupported Home Assistant version</h5>
<p>
You have version '{{hacs.system.ha_version}}' of Home Assistant, but version
'{{repository.display_available_version}}' of '{{repository.display_name}}' require version
'{{repository.repository_manifest.homeassistant}}' of Home Assistant, installation and upgrades are disabled
for this
integration untill you upgrade Home Assistant.
</p>
</div>
</div>
@@ -1,77 +0,0 @@
<!-- Used for both overview and store-->
{% extends "base.html" %}
{% block content %}
{% if location == 'store' %}
<div class='hacs-overview-container'>
<input type="text" id="Search" onkeyup="Search()" placeholder="Please enter a search term.." title="Type in a name"
autofocus style="color: var(--primary-text-color)">
</div>
{% if hacs.configuration.frontend_mode == "Grid" %}
{% include 'grid_new.html' with context %}
{% else %}
{% include 'table_new.html' with context %}
{% endif %}
{% endif %}
{% for type in hacs.common.categories %}
{% if type == 'appdaemon' %}
{% set displaytype = 'APPDAEMON APPS' %}
{% elif type == 'python_script' %}
{% set displaytype = 'PYTHON SCRIPTS' %}
{% else %}
{% set displaytype = (type + 's') | upper %}
{% endif %}
{% set repositories = namespace(repositories=[]) %}
{% for repository in hacs.sorted_by_name %}
{% set repo = namespace(include=True) %}
{% if repository.status.hide and repo.include %}
{% set repo.include = False %}
{% endif %}
{% if repository.information.category != type and repo.include %}
{% set repo.include = False %}
{% endif %}
{% if location == 'overview' %}
{% if not repository.status.installed and repo.include %}
{% set repo.include = False %}
{% if repository.information.uid == "172733314" %}
{% set repo.include = True %}
{% endif %}
{% endif %}
{% else %}
{% if repository.information.uid == "172733314" %}
{% set repo.include = False %}
{% endif %}
{% if hacs.configuration.country and repo.include %}
{% if repository.repository_manifest %}
{% if repository.repository_manifest.country %}
{% if hacs.configuration.country not in repository.repository_manifest.country %}
{% set repo.include = False %}
{% endif %}
{% endif %}
{% endif %}
{% endif %}
{% endif %}
{% if repo.include %}
{% set repositories.repositories = repositories.repositories+[repository] %}
{% endif %}
{% endfor %}
{% if repositories.repositories %}
{% if hacs.configuration.frontend_mode == "Grid" %}
{% include 'grid.html' with context %}
{% else %}
{% include 'table.html' with context %}
{% endif %}
{% endif %}
{% endfor %}
{% endblock %}
Loaded 100 of 158 files, more files were not shown because too many files have changed in this diff. Show more