在Home Assistant中配置天气信息

在Home Assistant中配置Yr.no天气信息

https://www.home-assistant.io/components/sensor.yr/

Windows系统下配置文件默认位置:

C:\Users\你的Windows系统账号名\AppData\Roaming\.homeassistant\configuration.yaml

Linux系统下配置文件默认位置:

/home/你的Linux系统账号名/.homeassistant/configuration.yaml

打开并编辑configuration.yaml配置文件。

在配置文件顶部找到地理坐标配置行,检查坐标数据是否正确(该数据是Home Assistant软件安装过程中自动根据用户的ip地址等信息自动设置的)。可参考相关网站(例如:http://jingwei.supfree.net/)进行查询,确定城市坐标数据。

  # Location required to calculate the time the sun rises and sets
  latitude: 43.83
  longitude: 125.28

此步骤必须实现,否则无法定位,导致天气不正确。

还有时区也需要修改,否则sun时间计算不正确,也就是日出日落时间不对。

# Pick yours from here: http://en.wikipedia.org/wiki/List_of_tz_database_time_zones
  time_zone: Asia/Shanghai

如果你想设置其他地区的时区就去访问 http://en.wikipedia.org/wiki/List_of_tz_database_time_zones

在List中选择你想要的TZ*时区进行替换。

在配置文件中找到Weather prediction(天气预测)节点,参照下面配置进行修改,天气信息内容可按需进行取舍:

详细参数参考前面的官方网站。

# Weather prediction
sensor:
  - platform: yr
    name: Weather
    forecast: 24           #未来24小时天气,可有手工按需修改
    monitored_conditions:
      - symbol
      - temperature        #气温
      - precipitation      #雨量
      - windSpeed          #风速
      - pressure           #气压
      - windDirection      #风向
      - humidity           #湿度

*以上天气信息内容可按需取舍,亦可以访问Yr组件介绍页面选择加载更多天气信息内容。

保存配置文件,重新启动Home Assistant。

看到Home Assistant系统Web操作页面顶端出现各种天气信息显示图标,说明配置成功。

在Home Assistant中配置yahoo天气信息

https://www.home-assistant.io/components/sensor.yweather/

细节就不多讲了,直接上图

# Weather prediction
sensor:
  - platform: yweather
    woeid: 2151330
    monitored_conditions:
      - weather
      - weather_current
      - temp_min
      - temp_max
      - wind_speed
      - pressure
      - visibility
      - humidity
      - temperature

woeid: 2151330此行可不写,不写就是按照经纬度定位。这个中的数字是你在雅虎网站上搜索时等到的网站的最后面的数字。

https://www.yahoo.com/news/weather/china/beijing/beijing-2151330

yahoo天气信息汉化

上图是yahoo天气的显示,英文和Yweather让人看着很不爽,决定进行汉化。

首先找到yweather的python文件。

我的是在如下目录:

/usr/local/lib/python3.5/dist-packages/homeassistant/components/sensor

的yweather.py文件。

基本就是在对应python库路径下找到homeassistant/components/sensor中的。

然后将其中显示相关改为汉语

找到下面几行并进行修改

DEFAULT_NAME = ''
MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=10)

SENSOR_TYPES = {
    'weather_current': ['当前天气', None],
    'weather': ['天气情况', None],
    'temperature': ['当前温度', 'temperature'],
    'temp_min': ['最低气温', 'temperature'],
    'temp_max': ['最高气温', 'temperature'],
    'wind_speed': ['风力', 'speed'],
    'humidity': ['湿度', '%'],
    'pressure': ['气压', 'pressure'],
    'visibility': ['能见度', 'distance'],

之后保存并重新启动homeassistant。

如图

其实Yr.no也能够进行汉化,与yahoo类似,这里就不做重复工作了。

和风天气插件

将和风天气加入到工程中,实现免费api的查询,这里需要十分感谢博客作者 繁星,多亏了他的大力帮助才能够实现。

作者文章链接:

https://www.hachina.io/3973.html

源码地址:

https://github.com/morestart/HeWeather

首先需要注册和风天气,获得一个认证key,这里就不多介绍了,按照和风要求来就行,然后将下面的文件放入

homeassistant/components/sensor中,每个人的环境不同,所以目录路径不同,我的是

/usr/local/lib/python3.5/site-packages/homeassistant/components/sensor

文件 HeWeather.py

import logging
from datetime import timedelta
import voluptuous as vol
import requests
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.helpers.entity import Entity
import homeassistant.helpers.config_validation as cv
from homeassistant.util import Throttle
from requests.exceptions import (
    ConnectionError as ConnectError, HTTPError, Timeout)

_LOGGER = logging.getLogger(__name__)

TIME_BETWEEN_UPDATES = timedelta(minutes=30)

CONF_OPTIONS = "options"
CONF_CITY = "city"
CONF_AQI_CITY = "aqi_city"
CONF_APPKEY = "appkey"

life_index_list = {"comf_txt": None, "drsg_txt": None, "flu_txt": None,
                   "sport_txt": None, "trav_txt": None, "uv_txt": None, "cw_txt": None}

OPTIONS = dict(fl=["HeWeather_fl", "实时体感温度", "mdi:temperature-celsius", "℃"],
               tmp=["HeWeather_tmp", "实时室外温度", "mdi:thermometer", "℃"],
               hum=["HeWeather_hum", "实时室外湿度", "mdi:water-percent", "%Rh"],
               pcpn=["HeWeather_pcpn", "降水量", "mdi:weather-rainy", "mm"],
               pres=["HeWeather_pres", "大气压", "mdi:debug-step-over", "hPa"],
               vis=["HeWeather_vis", "能见度", "mdi:eye", "km"],
               wind_spd=["HeWeather_wind_spd", "风速", "mdi:speedometer", "km/h"],
               wind_sc=["HeWeather_wind_sc", "风力", "mdi:flag-variant", None],
               wind_dir=["HeWeather_wind_dir", "风向", "mdi:apple-safari", None],
               cond_txt=["HeWeather_cond_txt", "天气状态", "mdi:counter", None],
               qlty=["HeWeather_qlty", "空气质量", "mdi:beach", None],
               main=["HeWeather_main", "主要污染物", "mdi:chart-bar-stacked", None],
               aqi=["HeWeather_aqi", "空气质量指数", "mdi:poll", "AQI"],
               pm10=["HeWeather_pm10", "PM10", "mdi:blur", "μg/m³"],
               pm25=["HeWeather_pm25", "PM2.5", "mdi:blur", "μg/m³"],
               comf=["HeWeather_comf", "舒适度指数", "mdi:chart-bubble", None],
               cw=["HeWeather_cw", "洗车指数", "mdi:car-wash", None],
               drsg=["HeWeather_drsg", "穿衣指数", "mdi:tie", None],
               flu=["HeWeather_flu", "感冒指数", "mdi:seat-individual-suite", None],
               sport=["HeWeather_sport", "运动指数", "mdi:bike", None],
               uv=["HeWeather_uv", "紫外线指数", "mdi:sunglasses", None],
               trav=["HeWeather_trav", "出行指数", "mdi:bus", None],
               tmp_max=["HeWeather_tmp_max", "今日最高温度", "mdi:mdi:thermometer", "℃"],
               tmp_min=["HeWeather_tmp_min", "今日最低温度", "mdi:mdi:thermometer", "℃"],
               pop=["HeWeather_pop", "降水概率", "mdi:weather-rainy", "%"],
               cond_code=[])


ATTR_UPDATE_TIME = "更新时间"
ATTRIBUTION = "Powered by He Weather"
ATTRIBUTION_SUGGESTION = "生活建议"

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
    {
        vol.Required(CONF_CITY): cv.string,
        vol.Required(CONF_APPKEY): cv.string,
        vol.Required(CONF_OPTIONS, default=[]): vol.All(cv.ensure_list, [vol.In(OPTIONS)]),
    }
)


def setup_platform(hass, config, add_devices, discovery_info=None):
    _LOGGER.info("Setup platform sensor.HeWeather")
    city = config.get(CONF_CITY)
    appkey = config.get(CONF_APPKEY)
    aqi_city = config.get(CONF_AQI_CITY)
    data = WeatherData(city, appkey, aqi_city)

    dev = []
    for option in config[CONF_OPTIONS]:
        dev.append(HeWeatherSensor(data, option))
    add_devices(dev, True)


class HeWeatherSensor(Entity):
    def __init__(self, data, option):
        self._data = data
        self._object_id = OPTIONS[option][0]
        self._friendly_name = OPTIONS[option][1]
        self._icon = OPTIONS[option][2]
        self._unit_of_measurement = OPTIONS[option][3]
        self._type = option
        self._state = None
        self._updatetime = None

    @property
    def name(self):
        return self._object_id

    @property
    def registry_name(self):
        return self._friendly_name

    @property
    def state(self):
        return self._state

    @property
    def icon(self):
        return self._icon

    @property
    def unit_of_measurement(self):
        return self._unit_of_measurement

    @property
    def device_state_attributes(self):
        global ATTRIBUTION

        if self._friendly_name == "舒适度指数":
            ATTRIBUTION = life_index_list['comf_txt']
        elif self._friendly_name == "穿衣指数":
            ATTRIBUTION = life_index_list["drsg_txt"]
        elif self._friendly_name == "感冒指数":
            ATTRIBUTION = life_index_list["flu_txt"]
        elif self._friendly_name == "运动指数":
            ATTRIBUTION = life_index_list["sport_txt"]
        elif self._friendly_name == "出行指数":
            ATTRIBUTION = life_index_list["trav_txt"]
        elif self._friendly_name == "紫外线指数":
            ATTRIBUTION = life_index_list["uv_txt"]
        elif self._friendly_name == "洗车指数":
            ATTRIBUTION = life_index_list["cw_txt"]
        else:
            ATTRIBUTION = "Powered by HeWeather"

        return {
            ATTR_UPDATE_TIME: self._updatetime,
            ATTRIBUTION_SUGGESTION: ATTRIBUTION,
        }

    def update(self):
        self._data.update()
        self._updatetime = self._data.updatetime

        if self._type == "fl":
            self._state = self._data.fl
        elif self._type == "tmp":
            self._state = self._data.tmp
        elif self._type == "cond_txt":
            self._state = self._data.cond_txt
        elif self._type == "wind_spd":
            self._state = self._data.wind_spd
        elif self._type == "hum":
            self._state = self._data.hum
        elif self._type == "pcpn":
            self._state = self._data.pcpn
        elif self._type == "pres":
            self._state = self._data.pres
        elif self._type == "vis":
            self._state = self._data.vis
        elif self._type == "wind_sc":
            self._state = self._data.wind_sc
        elif self._type == "wind_dir":
            self._state = self._data.wind_dir
        elif self._type == "qlty":
            self._state = self._data.qlty
        elif self._type == "main":
            self._state = self._data.main
        elif self._type == "aqi":
            self._state = self._data.aqi
        elif self._type == "pm10":
            self._state = self._data.pm10
        elif self._type == "pm25":
            self._state = self._data.pm25
        elif self._type == "cw":
            self._state = self._data.cw
        elif self._type == "comf":
            self._state = self._data.comf
        elif self._type == "drsg":
            self._state = self._data.drsg
        elif self._type == "flu":
            self._state = self._data.flu
        elif self._type == "sport":
            self._state = self._data.sport
        elif self._type == "trav":
            self._state = self._data.trav
        elif self._type == "uv":
            self._state = self._data.uv
        elif self._type == "tmp_max":
            self._state = self._data.tmp_max
        elif self._type == "tmp_min":
            self._state = self._data.tmp_min
        elif self._type == "pop":
            self._state = self._data.pop


class WeatherData(object):
    def __init__(self, city, appkey, aqi_city):
        self._url = "https://free-api.heweather.com/s6/weather/now"
        self._air_url = "https://free-api.heweather.com/s6/air/now"
        self._life_index_url = "https://free-api.heweather.com/s6/weather/lifestyle"
        self._long_weather_forcasting_url = "https://free-api.heweather.com/s6/weather/forecast"
        self._params = {"location": city, "key": appkey}
        self._aqi_params = {"location": aqi_city, "key": appkey}
        self._fl = None
        self._tmp = None
        self._cond_txt = None
        self._wind_spd = None
        self._hum = None
        self._pcpn = None
        self._pres = None
        self._vis = None
        self._wind_sc = None
        self._wind_dir = None
        self._qlty = None
        self._main = None
        self._aqi = None
        self._pm10 = None
        self._pm25 = None
        self._updatetime = None
        self._comf = None
        self._cw = None
        self._drsg = None
        self._flu = None
        self._sport = None
        self._uv = None
        self._trav = None
        self._tmp_max = None
        self._tmp_min = None
        self._pop = None

    @property
    def fl(self):
        return self._fl

    @property
    def tmp(self):
        return self._tmp

    @property
    def cond_txt(self):
        return self._cond_txt

    @property
    def wind_spd(self):
        return self._wind_spd

    @property
    def wind_dir(self):
        return self._wind_dir

    @property
    def hum(self):
        return self._hum

    @property
    def pcpn(self):
        return self._pcpn

    @property
    def pres(self):
        return self._pres

    @property
    def vis(self):
        return self._vis

    @property
    def wind_sc(self):
        return self._wind_sc

    @property
    def qlty(self):
        return self._qlty

    @property
    def main(self):
        return self._main

    @property
    def aqi(self):
        return self._aqi

    @property
    def pm10(self):
        return self._pm10

    @property
    def pm25(self):
        return self._pm25

    @property
    def comf(self):
        return self._comf

    @property
    def cw(self):
        return self._cw

    @property
    def drsg(self):
        return self._drsg

    @property
    def flu(self):
        return self._flu

    @property
    def sport(self):
        return self._sport

    @property
    def uv(self):
        return self._uv

    @property
    def trav(self):
        return self._trav

    @property
    def tmp_max(self):
        return self._tmp_max

    @property
    def tmp_min(self):
        return self._tmp_min

    @property
    def pop(self):
        return self._pop

    @property
    def updatetime(self):
        return self._updatetime

    def get_data(self):
        try:
            now_weather = requests.post(self._url, self._params)
            con = now_weather.json()

            r_air = requests.post(self._air_url, self._aqi_params)
            con_air = r_air.json()

            life_index = requests.post(self._life_index_url, self._params)
            con_life_index = life_index.json()

            today_weather = requests.post(self._long_weather_forcasting_url, self._params)
            con_today_weather = today_weather.json()
            return con, con_air, con_life_index, con_today_weather

        except (ConnectError, HTTPError, Timeout, ValueError) as error:
            _LOGGER.error("Unable to connect to HeWeather. %s", error)
            return

    @Throttle(TIME_BETWEEN_UPDATES)
    def update(self):
        data = self.get_data()
        if data is None:
            data = self.get_data()
            con = data[0]
            con_air = data[1]
            con_life_index = data[2]
            today_weather = data[3]
        else:
            con = data[0]
            con_air = data[1]
            con_life_index = data[2]
            today_weather = data[3]

        _LOGGER.info("Update from HeWeather...")
        try:
            self._fl = con["HeWeather6"][0]["now"]["fl"]
            self._cond_txt = con["HeWeather6"][0]["now"]["cond_txt"]
            self._hum = con["HeWeather6"][0]["now"]["hum"]
            self._pcpn = con["HeWeather6"][0]["now"]["pcpn"]
            self._pres = con["HeWeather6"][0]["now"]["pres"]
            self._tmp = con["HeWeather6"][0]["now"]["tmp"]
            self._vis = con["HeWeather6"][0]["now"]["vis"]
            self._wind_spd = con["HeWeather6"][0]["now"]["wind_spd"]
            self._wind_dir = con["HeWeather6"][0]["now"]["wind_dir"]

            self._cond_code = con["HeWeather6"][0]["now"]["cond_code"]

            self._qlty = con_air["HeWeather6"][0]["air_now_city"]["qlty"]
            self._aqi = con_air["HeWeather6"][0]["air_now_city"]["aqi"]
            self._pm10 = con_air["HeWeather6"][0]["air_now_city"]["pm10"]
            self._pm25 = con_air["HeWeather6"][0]["air_now_city"]["pm25"]
            if con_air["HeWeather6"][0]["air_now_city"]["main"] == "-":
                if int(self._pm10) > int(self._pm25):
                    self._main = "PM10"
                elif int(self._pm10) < int(self._pm25):
                    self._main = "PM25"
                else:
                    self._main = "-"
            else:
                self._main = con_air["HeWeather6"][0]["air_now_city"]["main"]

            self._comf = con_life_index["HeWeather6"][0]["lifestyle"][0]["brf"]
            self._drsg = con_life_index["HeWeather6"][0]["lifestyle"][1]["brf"]
            self._flu = con_life_index["HeWeather6"][0]["lifestyle"][2]["brf"]
            self._sport = con_life_index["HeWeather6"][0]["lifestyle"][3]["brf"]
            self._trav = con_life_index["HeWeather6"][0]["lifestyle"][4]["brf"]
            self._uv = con_life_index["HeWeather6"][0]["lifestyle"][5]["brf"]
            self._cw = con_life_index["HeWeather6"][0]["lifestyle"][6]["brf"]
            life = ["comf_txt", "drsg_txt", "flu_txt", "sport_txt", "trav_txt", "uv_txt", "cw_txt"]
            for i, index in enumerate(life):
                life_index_list[index] = con_life_index["HeWeather6"][0]["lifestyle"][i]["txt"]

            self._tmp_max = today_weather["HeWeather6"][0]["daily_forecast"][0]["tmp_max"]
            self._tmp_min = today_weather["HeWeather6"][0]["daily_forecast"][0]["tmp_min"]
            self._pop = today_weather["HeWeather6"][0]["daily_forecast"][0]["pop"]
            self._wind_sc = today_weather["HeWeather6"][0]["daily_forecast"][0]["wind_sc"]
        except Exception as e:
            logging.info(e)

        import time
        self._updatetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())

然后在configuration.yaml中修改如下内容

sensor:
  - platform: HeWeather
    city: 你所在的城市
    aqi_city: 最近的有监测站的城市(比如你的上级城市或者你的城市)
    appkey: 你的密钥
    options:
      - fl
      - tmp
      - cond_txt
      - wind_spd
      - hum
      - pcpn
      - pres
      - vis
      - wind_sc
      - aqi
      - main
      - qlty
      - pm10
      - pm25
      - comf
      - cw
      - drsg
      - flu
      - sport
      - trav
      - uv
      - wind_dir
      - tmp_max
      - tmp_min
      - pop

然后重新启动,效果如下图

想要的都在这里可以根据自己需要修改配置文件。

猜你喜欢

转载自blog.csdn.net/andylauren/article/details/82049869