本帖最后由 zhanghy 于 2019-10-21 23:02 编辑
1. 安装postgre Sql等...
sudo apt-get update
sudo hassbian-config install postgresql
sudo nano /etc/systemd/system/[email protected]
复制代码
2. 创建表,插入默认数据
CREATE TABLE HOLIDAY(ID INT PRIMARY KEY NOT NULL,DATE TEXT NOT NULL,TYPE INT NOT NULL);
复制代码
3. 配置config
shell_command:
update_day_type: python3 /home/homeassistant/.homeassistant/myshells/holiday.py
复制代码
4.安装python库
sudo pip3 install psycopg2
复制代码
5. 创建一个holiday.py,放到shell_command指定的位置,如:/home/homeassistant/.homeassistant/myshells/holiday.py 修改以下语句:对应库名,用户,密码,服务器信息
conn = psycopg2.connect(database="homeassistant", user="homeassistant",
password="homeassistant", host="127.0.0.1", port="5432")
# encoding: utf-8
import requests
import json
from time import gmtime, strftime
import psycopg2
date = strftime("%Y%m%d", gmtime())
github_url = "http://api.goseek.cn/Tools/holiday?date=" + date
print(github_url)
r = requests.get(github_url)
holiday_date = r.json()
get_day = holiday_date['data']
print(get_day)
# CREATE TABLE HOLIDAY(ID INT PRIMARY KEY NOT NULL,DATE TEXT NOT NULL,TYPE INT NOT NULL);
conn = psycopg2.connect(database="homeassistant", user="homeassistant",
password="homeassistant", host="127.0.0.1", port="5432")
print("Opened database successfully")
cur = conn.cursor()
sql = "UPDATE HOLIDAY set DATE =%s,TYPE=%d WHERE ID=1" % (date, get_day)
cur.execute(sql)
conn.commit()
print("Records update successfully")
conn.close()
复制代码
6. 将该脚本放到ha所在电脑的系统当中, 路径与shell_command中一致
7. 配置一条自动化: 每天0点一分调用shell_command 中的 py脚本
- alias: update_day_type
initial_state: true
trigger:
- platform: time
at: '00:01:00'
action:
- service: shell_command.update_day_type
复制代码
8 .创建一个sql传感器
sensor:
- platform: sql
db_url: postgresql://homeassistant:homeassistant@localhost/homeassistant
queries:
- name: DB size
query: "SELECT (pg_database_size('homeassistant')/1024/1024) as db_size;"
column: "db_size"
unit_of_measurement: MB
- name: day type
query: "SELECT type FROM HOLIDAY where id=1;"
column: "type"
复制代码
9. 重启ha
应该没有遗漏了....