• Изменено

Переделал вариант получения погоды с weatherapi.com на прогноз, а не текущую погоду.
Т.к. мне хотелось с утра получать в телегу текущую погоду, рассвет/закат и прогноз на день.

Image description

Custom-устройство:

{
  "exposes": [
    "lastUpdated",
    "locationName",
    "locationRegion",
    "condition",
    "temperature",
    "humidity",
    "feelsLike",
    "dewPoint",
    "pressure",
    "windSpeed",
    "windDirection",
    "precipitation",
    "uvIndex",
    "forecastDate",
    "conditionForecast",
    "sunrise",
    "sunset",
    "moonrise",
    "moonset",
    "moonPhase",
    "minTempc",
    "maxTempc",
    "maxWindKph"
  ],
  "real": true,
  "options": {
    "maxWindKph": {
      "round": 1
    },
    "pressure": {
      "unit": "mmHg"
    },
    "windSpeed": {
      "round": 1
    }
  },
  "bindings": {
    "condition": {
      "inPattern": "{{ json.current.condition.text }}",
      "inTopic": "weatherapiforecast"
    },
    "conditionForecast": {
      "inPattern": "{{ json.forecast.forecastday[0].day.condition.text }}",
      "inTopic": "weatherapiforecast"
    },
    "dewPoint": {
      "inPattern": "{{ json.current.dewpoint_c }}",
      "inTopic": "weatherapiforecast"
    },
    "feelsLike": {
      "inPattern": "{{ json.current.feelslike_c }}",
      "inTopic": "weatherapiforecast"
    },
    "forecastDate": {
      "inPattern": "{{ json.forecast.forecastday[0].date }}",
      "inTopic": "weatherapiforecast"
    },
    "humidity": {
      "inPattern": "{{ json.current.humidity }}",
      "inTopic": "weatherapiforecast"
    },
    "lastUpdated": {
      "inPattern": "{{ json.current.last_updated }}",
      "inTopic": "weatherapiforecast"
    },
    "locationName": {
      "inPattern": "{{ json.location.name}}",
      "inTopic": "weatherapiforecast"
    },
    "locationRegion": {
      "inPattern": "{{ json.location.region}}",
      "inTopic": "weatherapiforecast"
    },
    "maxTempc": {
      "inPattern": "{{ json.forecast.forecastday[0].day.maxtemp_c }}",
      "inTopic": "weatherapiforecast"
    },
    "maxWindKph": {
      "inPattern": "{{ json.forecast.forecastday[0].day.maxwind_kph / 3.6 }}",
      "inTopic": "weatherapiforecast"
    },
    "minTempc": {
      "inPattern": "{{ json.forecast.forecastday[0].day.mintemp_c }}",
      "inTopic": "weatherapiforecast"
    },
    "moonPhase": {
      "inPattern": "{{ 'Новолуние' if json.forecast.forecastday[0].astro.moon_phase == 'New Moon' else 'Молодая Луна' if json.forecast.forecastday[0].astro.moon_phase == 'Waxing crescent' else 'Растущая Луна' if json.forecast.forecastday[0].astro.moon_phase == 'Waxing gibbous' else 'Полнолуние' if json.forecast.forecastday[0].astro.moon_phase == 'Full Moon' else 'Убывающая Луна' if json.forecast.forecastday[0].astro.moon_phase == 'Waning gibbous' else 'Последняя четверть' if json.forecast.forecastday[0].astro.moon_phase == 'Last quarter' else 'Старая Луна' if json.forecast.forecastday[0].astro.moon_phase == 'Waning Crescent' else 'Луну черти украли' }}",
      "inTopic": "weatherapiforecast"
    },
    "moonrise": {
      "inPattern": "{{ json.forecast.forecastday[0].astro.moonrise }}",
      "inTopic": "weatherapiforecast"
    },
    "moonset": {
      "inPattern": "{{ json.forecast.forecastday[0].astro.moonset }}",
      "inTopic": "weatherapiforecast"
    },
    "precipitation": {
      "inPattern": "{{ json.current.precip_mm }}",
      "inTopic": "weatherapiforecast"
    },
    "pressure": {
      "inPattern": "{{ json.current.pressure_mb / 1.33322 }}",
      "inTopic": "weatherapiforecast"
    },
    "sunrise": {
      "inPattern": "{{ json.forecast.forecastday[0].astro.sunrise }}",
      "inTopic": "weatherapiforecast"
    },
    "sunset": {
      "inPattern": "{{ json.forecast.forecastday[0].astro.sunset }}",
      "inTopic": "weatherapiforecast"
    },
    "temperature": {
      "inPattern": "{{ json.current.temp_c }}",
      "inTopic": "weatherapiforecast"
    },
    "uvIndex": {
      "inPattern": "{{ json.current.uv }}",
      "inTopic": "weatherapiforecast"
    },
    "windDirection": {
      "inPattern": "{{ 'Северный' if json.current.wind_dir == 'N' else 'Северо-Северо-Восток' if json.current.wind_dir == 'NNE' else 'Северо-Восток' if json.current.wind_dir == 'NE' else 'Востоко-Северо-Восток' if json.current.wind_dir == 'ENE' else 'Восточный' if json.current.wind_dir == 'E' else 'Востоко-Юго-Восток' if json.current.wind_dir == 'ESE' else 'Юго-Восток' if json.current.wind_dir == 'SE' else 'Юго-Юго-Восток' if json.current.wind_dir == 'SSE' else 'Южный' if json.current.wind_dir == 'S' else 'Юго-Юго-Запад' if json.current.wind_dir == 'SSW' else 'Юго-Запад' if json.current.wind_dir == 'SW' else 'Западо-Юго-Запад' if json.current.wind_dir == 'WSW' else 'Западный' if json.current.wind_dir == 'W' else 'Западо-Северо-Запад' if json.current.wind_dir == 'WNW' else 'Северо-Запад' if json.current.wind_dir == 'NW' else 'Северо-Северо-Запад' if json.current.wind_dir == 'NNW' else 'Неизвестно' }}",
      "inTopic": "weatherapiforecast"
    },
    "windSpeed": {
      "inPattern": "{{ json.current.wind_kph / 3.6 }}",
      "inTopic": "weatherapiforecast"
    }
  }
}

Автоматизация:

{
  "actions": [
    {
      "command": "DATA=$(curl -s \"https://api.weatherapi.com/v1/forecast.json?key=your_api_token&q=your_location&lang=ru&alerts=yes\") && echo $DATA | jq > /dev/null 2>&1 && mosquitto_pub -t \"weatherapiforecast\" -m \"$DATA\" -r -u \"homed_mqtt_user\" -P \"homed_mqtt_password\" &",
      "type": "shell"
    },
    {
      "delay": "2",
      "type": "delay"
    },
    {
      "message": "Weather from HOMEd {{ timestamp | dd.MM.yy hh:mm }}\n---- Now -----\nПоследнее обновление: {{ property | custom/weatherapiforecast | lastUpdated }}\nМестоположение: {{ property | custom/weatherapiforecast | locationName }} | {{ property | custom/weatherapiforecast | locationRegion }}\nСостояние: {{ property | custom/weatherapiforecast | condition }} \nТемпература: {{ property | custom/weatherapiforecast | temperature }} °C\nОщущается как: {{ property | custom/weatherapiforecast | feelsLike }} °C\nТочка росы: {{ property | custom/weatherapiforecast | dewPoint }} °C\nВлажность: {{ property | custom/weatherapiforecast | humidity }} %\nДавление: [[ round({{ property | custom/weatherapiforecast | pressure }} * 10) / 10 ]] мм рт. ст.\nСкорость ветра: [[ round({{ property | custom/weatherapiforecast | windSpeed }} * 10) / 10 ]] м/с\nНаправление ветра: {{ property | custom/weatherapiforecast | windDirection }} \nОсадки: {{ property | custom/weatherapiforecast | precipitation }} мм\nУФ-индекс: {{ property | custom/weatherapiforecast | uvIndex }} \n--- Astro ----\n🌞 ↑{{ property | custom/weatherapiforecast | sunrise }} ↓{{ property | custom/weatherapiforecast | sunset }}\n🌜 ↑{{ property | custom/weatherapiforecast | moonrise }} ↓{{ property | custom/weatherapiforecast | moonset }} Фаза: {{ property | custom/weatherapiforecast | moonPhase }} \n-- Forecast --\nСостояние на {{ property | custom/weatherapiforecast | forecastDate }}: {{ property | custom/weatherapiforecast | conditionForecast }}\nТемпература: min {{ property | custom/weatherapiforecast | minTempc }} °C, max {{ property | custom/weatherapiforecast | maxTempc }} °C\nМакс. ветер: [[ round({{ property | custom/weatherapiforecast | maxWindKph }} * 10) / 10 ]] м/с",
      "triggerName": "reqest",
      "type": "telegram"
    },
    {
      "message": "Weather from HOMEd {{ timestamp | dd.MM.yy hh:mm }}\n---- Now -----\nПоследнее обновление: {{ property | custom/weatherapiforecast | lastUpdated }}\nМестоположение: {{ property | custom/weatherapiforecast | locationName }} | {{ property | custom/weatherapiforecast | locationRegion }}\nСостояние: {{ property | custom/weatherapiforecast | condition }} \nТемпература: {{ property | custom/weatherapiforecast | temperature }} °C\nОщущается как: {{ property | custom/weatherapiforecast | feelsLike }} °C\nТочка росы: {{ property | custom/weatherapiforecast | dewPoint }} °C\nВлажность: {{ property | custom/weatherapiforecast | humidity }} %\nДавление: [[ round({{ property | custom/weatherapiforecast | pressure }} * 10) / 10 ]] мм рт. ст.\nСкорость ветра: [[ round({{ property | custom/weatherapiforecast | windSpeed }} * 10) / 10 ]] м/с\nНаправление ветра: {{ property | custom/weatherapiforecast | windDirection }} \nОсадки: {{ property | custom/weatherapiforecast | precipitation }} мм\nУФ-индекс: {{ property | custom/weatherapiforecast | uvIndex }} \n--- Astro ----\n🌞 ↑{{ property | custom/weatherapiforecast | sunrise }} ↓{{ property | custom/weatherapiforecast | sunset }}\n🌜 ↑{{ property | custom/weatherapiforecast | moonrise }} ↓{{ property | custom/weatherapiforecast | moonset }} Фаза: {{ property | custom/weatherapiforecast | moonPhase }} \n-- Forecast --\nСостояние на {{ property | custom/weatherapiforecast | forecastDate }}: {{ property | custom/weatherapiforecast | conditionForecast }}\nТемпература: min {{ property | custom/weatherapiforecast | minTempc }} °C, max {{ property | custom/weatherapiforecast | maxTempc }} °C\nМакс. ветер: [[ round({{ property | custom/weatherapiforecast | maxWindKph }} * 10) / 10 ]] м/с",
      "triggerName": "time632",
      "type": "telegram"
    }
  ],
  "restart": false,
  "triggers": [
    {
      "name": "time632",
      "time": "6:32",
      "type": "time"
    },
    {
      "interval": 30,
      "name": "30min",
      "type": "interval"
    },
    {
      "message": "weather",
      "name": "reqest",
      "type": "telegram"
    }
  ],
  "conditions": []
}

Update 24-02-2025:
Обновил приложенные файлы - добавлены все переводы и округления из коментариев.
Включены alert-ы, под них заведено отдельное custom-устройство - weatherapiforecast_alerts. Посмотрим - будут ли туда прилетать алерты о погоде, пока за выгодные в Петербурге ничего не прилетело, но и не было СМС от МЧС.
У автоматизации теперь три триггера - в 6 утра присылать погоду в Телеграм, и присылать по запросу weather и каждые 30 минут обновлять данные сенсоров.

Update 01-04-2025:
Алерты о погоде все же прилетают в России, правда реже чем СМС от МЧС.
Так как у нас в автоматизации в запросе к weatherapi уже есть параметр alerts, то нам просто нужен еще custom сенсор с алертами и авто которая будет слать сообщения. Сообщения выглядят вот так:

Image description

weatherapiforecast-automation.json
5kB
weatherapiforecast-device.json
5kB
weatherapiforecast-alerts-auto.json
1kB
weatherapiforecast-alerts-custom.json
1kB
  • Изменено

Вдруг кому интересно будет поразгадывать загадку почему дата вот так попадает в exposes:

Image description

Если она в json ответе сервера имеет такое значение:

{
  "forecast": {
    "forecastday": [
      {
        "date": "2025-02-21",
        ...

  },
}

А парсится вот так:

"forecastDate": {
      "inPattern": "{{ json.forecast.forecastday[0].date }}",
      "inTopic": "weatherapiforecast"
    },

При этом в ответе сервера значения 2002вообще нет.. Я не осилил. При этом всё остальное, даже другие даты, нормально попадают в custom-сенсор.

  • u236 и igor ответили на это сообщение.
    • Изменено

    Прогноз погоды можно запрашивать сразу на русском языке - добавив в запрос параметр:

    forecast.json?key=your_api_token&q=your_location&lang=ru

    Image description

    • Изменено

    tudimon я знаю ответ, но не скажу, скажу только, что завтра будет 2001 🙂

    • tudimon ответили на это сообщение.

      u236 да, вчера было 2003 🙂

      • u236 ответили на это сообщение.

        tudimon в общем 2025-2-21=2002, наверное надо парсер математики для биндингов сделать как в автоматизациях, со своими скобками

        • tudimon ответили на это сообщение.

          u236 а нет у jq какого-нибудь ключа-указателя? типа - "inPattern": "{{ json.forecast.forecastday[0].date }}" | string

          • u236 ответили на это сообщение.

            tudimon jq тут не причем

              • Изменено

              tudimon Image description

              Погода от HOMEd {{ timestamp | dd.MM.yy hh:mm }}
              ---- Сейчас -----
              Последнее обновление: {{ property | custom/weatherapiforecast | lastUpdated }}
              Местоположение: {{ property | custom/weatherapiforecast | locationName }} | {{ property | custom/weatherapiforecast | locationRegion }}
              Состояние: {{ property | custom/weatherapiforecast | condition }}
              Температура: {{ property | custom/weatherapiforecast | temperature }} °C
              Ощущается как: {{ property | custom/weatherapiforecast | feelsLike }} °C
              Точка росы: {{ property | custom/weatherapiforecast | dewPoint }} °C
              Влажность: {{ property | custom/weatherapiforecast | humidity }} %
              Давление: {{ property | custom/weatherapiforecast | pressure }} мм р.ст.
              Скорость ветра: {{ property | custom/weatherapiforecast | windSpeed }} м/с
              Направление ветра: {{ property | custom/weatherapiforecast | windDirection }}
              Осадки: {{ property | custom/weatherapiforecast | precipitation }} мм
              УФ-индекс: {{ property | custom/weatherapiforecast | uvIndex }}
              
              --- Астро ----
              🌞 ↑{{ property | custom/weatherapiforecast | sunrise }} ↓{{ property | custom/weatherapiforecast | sunset }}
              🌜 ↑{{ property | custom/weatherapiforecast | moonrise }} ↓{{ property | custom/weatherapiforecast | moonset }} Фаза: {{ property | custom/weatherapiforecast | moonPhase }}
              
              -- Прогноз --
              Состояние: {{ property | custom/weatherapiforecast | conditionForecast }}
              Температура: мин {{ property | custom/weatherapiforecast | minTempc }} °C, макс {{ property | custom/weatherapiforecast | maxTempc }} °C
              Макс. ветер: {{ property | custom/weatherapiforecast | maxWindKph }} м/с

              "forecastDate": {
              "inPattern": "{{ '\"' json.forecast.forecastday[0].date '\"' }}",
              "inTopic": "weatherapiforecast"
              }

              Forecast date " 2025-02-21 "

              • tudimon ответили на это сообщение.
              • tudimon оценил это.

                Можно ли пофиксить давление и скорость ветра от «шесть знаков после запятой» и «вот этого всего»? 😉 для прогноза погоды оно явно несущественно.
                Вроде же можно было писать round для математических выражений, но или это поломалось или чет не так делаю.

                • igor ответили на это сообщение.

                  A-I Можно вот так
                  "inPattern": "{{ (json.current.wind_kph / 3.6) | round(1) }}"

                  • u236 ответили на это сообщение.
                    • Изменено

                    igor нельзя, это не джинджа, чтобы округлить отображаемое значение нужно в опции нужного expose добавить параметр"round": n, актуально только для сенсоров, на сколько я помню

                    • tudimon и igor ответили на это сообщение.

                      u236 так у меня не получилось, после сохранения round исчезает

                        • Изменено

                        u236 А при формировании сообщения в телеграм это сделать можно? Там вроде есть матемтические выражения для встроенных шаблонов.
                        Что-то типо этого, но это не работает:
                        Макс. ветер: [[ round({{ property | custom/weatherapiforecast | maxWindKph }} * 10) / 10 ]] м/с
                        В конфиге кастом устройства округление работает, там отображается с округлением до десятых

                        Получилось. Так работает:

                        Погода от HOMEd {{ timestamp | dd.MM.yy hh:mm }}
                        ---- Сейчас -----
                        Последнее обновление: {{ property | custom/weatherapiforecast | lastUpdated }}
                        Местоположение: {{ property | custom/weatherapiforecast | locationName }} | {{ property | custom/weatherapiforecast | locationRegion }}
                        Состояние: {{ property | custom/weatherapiforecast | condition }}
                        Температура: {{ property | custom/weatherapiforecast | temperature }} °C
                        Ощущается как: {{ property | custom/weatherapiforecast | feelsLike }} °C
                        Точка росы: {{ property | custom/weatherapiforecast | dewPoint }} °C
                        Влажность: {{ property | custom/weatherapiforecast | humidity }} %
                        Давление: [[ round({{ property | custom/weatherapiforecast | pressure }} * 10) / 10 ]] мм р.ст.
                        Скорость ветра: [[ round({{ property | custom/weatherapiforecast | windSpeed }} * 10) / 10 ]] м/с
                        Направление ветра: {{ property | custom/weatherapiforecast | windDirection }}
                        Осадки: {{ property | custom/weatherapiforecast | precipitation }} мм
                        УФ-индекс: {{ property | custom/weatherapiforecast | uvIndex }}
                        
                        --- Астро ----
                        🌞 ↑{{ property | custom/weatherapiforecast | sunrise }} ↓{{ property | custom/weatherapiforecast | sunset }}
                        🌜 ↑{{ property | custom/weatherapiforecast | moonrise }} ↓{{ property | custom/weatherapiforecast | moonset }} Фаза: {{ property | custom/weatherapiforecast | moonPhase }}
                        
                        -- Прогноз --
                        Состояние: {{ property | custom/weatherapiforecast | conditionForecast }}
                        Температура: мин {{ property | custom/weatherapiforecast | minTempc }} °C, макс {{ property | custom/weatherapiforecast | maxTempc }} °C
                        Макс. ветер: [[ round({{ property | custom/weatherapiforecast | maxWindKph }} * 10) / 10 ]] м/с

                        igor как у тебя направление ветра переводится на русский?

                        • igor ответили на это сообщение.

                          tudimon

                          "inPattern": "{{ 'Северный' if json.current.wind_dir == 'N' else 'Северо-Северо-Восток' if json.current.wind_dir == 'NNE' else 'Северо-Восток' if json.current.wind_dir == 'NE' else 'Востоко-Северо-Восток' if json.current.wind_dir == 'ENE' else 'Восточный' if json.current.wind_dir == 'E' else 'Востоко-Юго-Восток' if json.current.wind_dir == 'ESE' else 'Юго-Восток' if json.current.wind_dir == 'SE' else 'Юго-Юго-Восток' if json.current.wind_dir == 'SSE' else 'Южный' if json.current.wind_dir == 'S' else 'Юго-Юго-Запад' if json.current.wind_dir == 'SSW' else 'Юго-Запад' if json.current.wind_dir == 'SW' else 'Западо-Юго-Запад' if json.current.wind_dir == 'WSW' else 'Западный' if json.current.wind_dir == 'W' else 'Западо-Северо-Запад' if json.current.wind_dir == 'WNW' else 'Северо-Запад' if json.current.wind_dir == 'NW' else 'Северо-Северо-Запад' if json.current.wind_dir == 'NNW' else 'Неизвестно' }}"

                          Там еще интересная штука есть https://api.weatherapi.com/v1/alerts.json
                          Это вроде оповещение о суровых погодных условиях. Было бы круто её прикрутить к автоматическим оповещениям.

                          • tudimon ответили на это сообщение.
                            • Изменено

                            igor да, в forecast они тоже есть:

                            },
                              "alert": {}
                            }

                            Weather Alerts. Forecast API and Alerts API returns alerts and warnings issued by government agencies (USA, UK, Europe and Rest of the World) as an array if available for the location provided through the Forecast API and Alerts API.

                            Хотя в доке прогноза ничего про них нет. Планировал вечером запилить уведомления, но видимо пока только запилю сбор данных из этой секции - чисто посмотреть прилетает ли туда что-то

                            По умолчанию оповещения не возвращаются. Чтобы получать оповещения обратно в ответ от Forecast API, передайте параметр alerts=yes.

                              • Изменено

                              igor похоже в РФ не работают алерты - всегда пустоту возвращает:

                               "alerts": {
                                  "alert": []
                                }

                              Настроил каждые 30 минут опрашивать, пока получаю пустоту

                              • igor ответили на это сообщение.

                                tudimon Да у меня тоже самое. Возможно если будет штормое предупреждение или обильные осадки в прогнозе, то поле будет заполнено? А может и правда в РФ не работает. Надо другие сервисы поискать, может openweathermap.org/api умеет.