idodov
RedAlert
Python

Israeli Red Alert Service for Home Assistant

Last updated Apr 4, 2026
59
Stars
6
Forks
1
Issues
0
Stars/day
Attention Score
45
Language breakdown
Python 100.0%
โ–ธ Files click to expand
README

Red Alerts Israel

Not Official Pikud Ha-Oref
Simple rocket-alert monitoring for Home Assistant via AppDaemon
image

Red Alerts Israel is an AppDaemon application for Home Assistant that connects to the official Israeli Home Front Command (Pikud HaOref) API. It fetches real-time "Tzeva Adom" rocket alerts and other hazards, making this information available via easy-to-use Home Assistant sensors.

This script monitors various hazards signaled by PIKUD HA-OREF, including missile/rocket fire, unauthorized aircraft, seismic activity, tsunami, terrorist incursions, chemical emergencies, and more. Upon receiving an alert, the specific threat type is indicated, for example, ื™ืจื™ ืจืงื˜ื•ืช ื•ื˜ื™ืœื™ื for rocket and missile fire.

The application is designed for reliability and persistence, offering features like archiving alert details, state persistence via JSON backup, triggering Home Assistant native events, publishing messages via MQTT, and providing detailed sensor attributes for creating derived sensors and advanced automations.


Key Features

  • Polls the official Israeli Home Front Command API every few seconds for live alerts.
  • Creates dedicated Home Assistant entities: main binary sensors, a text helper, a test boolean, and three detailed history sensors.
  • Offers flexible alert notification publishing via MQTT and native Home Assistant events triggered by new alert payloads.
  • Saves alert history (TXT, CSV) and the last active state (JSON) for persistence across restarts (optional).
  • Generates GeoJSON files for visualizing active and historical alert locations on the Home Assistant map (optional).
Provides specific binary sensors to indicate if an alert affects your configured cities* or if it's a special "Pre-Alert" type.
  • Tracks the history of distinct alert events within a configurable time window.
  • Generates pre-formatted messages suitable for platforms like WhatsApp and Telegram based on cumulative window data.

Entities Created

The script creates several Home Assistant entities, using your configured sensorname as the base name (default: redalert):

binarysensor.YOURSENSOR_NAME: Indicates if any alert is currently active nationwide. This sensor stays on for the duration of the configured timer after the last detected alert activity* in a sequence. binarysensor.YOURSENSORNAMEcity: Indicates if binarysensor.YOURSENSORNAME is on and* the alert window includes one of the specific cities/areas you configured in citynames. binarysensor.YOURSENSORNAMEpre_alert: Indicates if a pre alert is currently active nationwide*. This sensor turns on. binarysensor.YOURSENSORNAMEcityprealert: Indicates if a pre alert alert is currently active and* affects one of your configured citynames. This sensor turns on only when an pre alert is received and processed AND the alert window includes one of your configured citynames. binarysensor.YOURSENSORNAMEactive_alert: Indicates if an alert with a category other than pre alert is currently active nationwide*. This sensor turns on. binarysensor.YOURSENSORNAMEcityactivealert: Indicates if an alert with a category other pre alert is currently active and* affects one of your configured citynames. This sensor turns on when a pre alert is received and processed AND the alert window includes one of your configured citynames. inputtext.YOURSENSOR_NAME: Displays a summary of the latest alert payload* received during an active alert window.

  • inputboolean.YOURSENSORNAMEtest: Allows manual triggering of a fictitious test alert sequence.
Three additional history sensors track distinct alert events that occurred within the configured hourstoshow timeframe (after applying timer-based deduplication):

  • sensor.YOURSENSORNAMEhistorycities: State is the count, attributes list unique cities alerted in the history window.
  • sensor.YOURSENSORNAMEhistorylist: State is the count, attributes list each distinct alert event entry in the history window.
  • sensor.YOURSENSORNAMEhistorygroup: State is the count, attributes group distinct alert events by title, area, and city in the history window.
Detailed Binary Sensor Logic and Attributes

Binary Sensor States (binarysensor.YOURSENSORNAME, city, prealert, cityprealert, activealert, cityactivealert)

All six binary sensors are controlled by the script's polling and reset logic.

  • When a new alert payload is received from the API:
* binarysensor.YOURSENSOR_NAME turns on (if not already) and its internal timer is reset. binarysensor.YOURSENSORNAMEcity turns on if any of the accumulated* cities in the current alert window match your configured city_names, otherwise it stays off. If the cat value in the latest incoming alert payload* is 13: * binarysensor.YOURSENSORNAMEpre_alert turns on. * binarysensor.YOURSENSORNAMEcityprealert turns on if the binarysensor.YOURSENSORNAMEcity sensor is on (i.e., if configured cities are affected), otherwise it turns off. * binarysensor.YOURSENSORNAMEactive_alert turns off. * binarysensor.YOURSENSORNAMEcityactivealert turns off. If the cat value in the latest incoming alert payload is not* 13 (e.g., cat=1 for rockets, which is the case for test alerts): * binarysensor.YOURSENSORNAMEpre_alert turns off. * binarysensor.YOURSENSORNAMEcityprealert turns off. * binarysensor.YOURSENSORNAMEactive_alert turns on. * binarysensor.YOURSENSORNAMEcityactivealert turns on if the binarysensor.YOURSENSORNAMEcity sensor is on, otherwise it turns off.
  • When the alert timer expires and confirms no active alerts are pending:
* All six binary sensors (main, city, prealert, cityprealert, activealert, cityactivealert) are explicitly set to off.
  • On Script Initialization/Restart:
* All six binary sensors are initialized to off.

Shared Binary Sensor Attributes

When any of the six binary sensors are updated, they receive the same set of attributes. These attributes reflect the state and accumulated information for the current alert window since binarysensor.YOURSENSORNAME last turned on. When binarysensor.YOURSENSORNAME is off, they show default/empty values or the prev_ values from the window that just ended, providing context about the last* alert incident.

| Attribute name | Description | Example | | :------------------ | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :----------------------------------------- | | activenow | true when binarysensor.YOURSENSORNAME is on, false when off. Mirrors the main sensor state. | false | | map_url | Dynamic Smart Map URL. Cumulative visual of the last 15 min. Orange = Pre-Alert, Red = Threat, Green = Clearance. | https://static-maps... | | script_status | The operational status of the AppDaemon script (initializing, running, error, terminated). Useful for monitoring the script itself. | running | | id | Unique ID of the latest alert payload received during the current window. | 1721993400123456 | | cat | Category number (0-14) of the latest alert payload. Corresponds to alert type (e.g., 1 for rockets, 13 for special update). | 1 | | title | Title/Type of the latest alert payload (e.g., "ื™ืจื™ ืจืงื˜ื•ืช ื•ื˜ื™ืœื™ื"). | ื™ืจื™ ืจืงื˜ื•ืช ื•ื˜ื™ืœื™ื | | desc | Recommended action description from the latest alert payload (e.g., "ื”ื™ื›ื ืกื• ืœืžืจื—ื‘ ื”ืžื•ื’ืŸ ื•ืฉื”ื• ื‘ื• 10 ื“ืงื•ืช"). | ื”ื™ื›ื ืกื• ืœืžืจื—ื‘ ื”ืžื•ื’ืŸ ื•ืฉื”ื• ื‘ื• 10 ื“ืงื•ืช | | specialupdate | true if the cat of the latest alert payload is 13, false otherwise. This attribute mirrors the state logic of the *pre_alert sensors. | false | | areas | Comma-separated string of all areas affected by any payload within the current active window. | ื’ื•ืฉ ื“ืŸ, ืงื• ื”ืขื™ืžื•ืช | | cities | A sorted list of all unique original city names affected by any payload within the current active window. | ['ืื•ืจ ื™ื”ื•ื“ื”', 'ืชืœ ืื‘ื™ื‘ - ืžืจื›ื– ื”ืขื™ืจ'] | | data | Comma-separated string of all unique original city names affected during the current active window. May be truncated if very long. | ืื•ืจ ื™ื”ื•ื“ื”, ืชืœ ืื‘ื™ื‘ - ืžืจื›ื– ื”ืขื™ืจ, ื—ื•ืœื•ืŸ... | | data_count | Count of unique original city names affected during the current active window. | 5 | | duration | Recommended duration (in seconds) to stay in a safe room, extracted from the desc of the latest alert payload. | 600 | | icon | MDI icon string based on the cat of the latest alert payload. | mdi:rocket-launch | | emoji | Emoji character based on the cat of the latest alert payload. | ๐Ÿš€ | | alerts_count | The number of individual alert payloads received and processed by the script during the current active alert window (since the main sensor last went on). | 3 | | last_changed | ISO timestamp string (YYYY-MM-DDTHH:MM:SS.ffffff) when this sensor's state or any of its attributes were last updated. | "2024-07-25T10:30:00.123456" | | mycities | A sorted list of the city names exactly as configured in your apps.yaml citynames list. | ['ื—ื™ืคื” - ืžืคืจืฅ', 'ืชืœ ืื‘ื™ื‘ - ืžืจื›ื– ื”ืขื™ืจ'] | | alert | One-line summary string: [Title] - [Areas]: [Cities]. Uses cumulative window data. | ื™ืจื™ ืจืงื˜ื•ืช ื•ื˜ื™ืœื™ื - ื’ื•ืฉ ื“ืŸ, ืงื• ื”ืขื™ืžื•ืช: ... | | alert_alt | Multi-line summary string: [Title]\n [Area]: [Cities]\n [Area]: [Cities].... Uses cumulative window data. | ื™ืจื™ ืจืงื˜ื•ืช ื•ื˜ื™ืœื™ื\n ื’ื•ืฉ ื“ืŸ: ืชืœ ืื‘ื™ื‘...\n ืงื• ื”ืขื™ืžื•ืช: ื›ื™ืกื•ืคื™ื | | alert_txt | One-line string listing Areas and Cities affected in the current window: [Area]: [Cities], [Area]: [Cities].... | ื’ื•ืฉ ื“ืŸ: ืชืœ ืื‘ื™ื‘ - ืžืจื›ื– ื”ืขื™ืจ, ืื•ืจ ื™ื”ื•ื“ื”... | | alert_wa | Multi-line formatted message optimized for WhatsApp, summarizing alerts by type and area based on cumulative window data. | whatsapp | | alert_tg | Multi-line formatted message optimized for Telegram, summarizing alerts by type and area based on cumulative window data. | | | prev_cat | Category number of the alert from the previous alert window (before the main sensor last went off and then on again). | 1 | | prev_title | Title of the alert from the previous alert window. | ื™ืจื™ ืจืงื˜ื•ืช ื•ื˜ื™ืœื™ื | | prev_desc | Description from the previous alert window. | ื”ื™ื›ื ืกื• ืœืžืจื—ื‘ ื”ืžื•ื’ืŸ ื•ืฉื”ื• ื‘ื• 10 ื“ืงื•ืช | | prev_areas | Areas from the previous alert window. | ืงื• ื”ืขื™ืžื•ืช | | prev_cities | List of cities from the previous alert window. | ['ืฉืœื•ืžื™'] | | prev_data | Comma-separated cities string from the previous alert window. | ืฉืœื•ืžื™ | | prevdatacount | City count from the previous alert window. | 1 | | prev_duration | Duration from the previous alert window. | 600 | | prevlastchanged | ISO timestamp when the previous alert window became active (when the main sensor state last went on for that window). | "2024-07-25T10:15:05.987654" | | prevalertscount | Sequence count from the previous alert window. | 2 | | prevspecialupdate | Special update flag status (cat==13) from the previous alert window. | false |

inputtext.YOURSENSOR_NAME

State: Holds a brief summary (up to 255 characters) derived from the latest alert payload's* title, area, and cities (inputtextstate attribute in the script).
  • Use: Primarily intended for simple dashboard displays or logbook entries.
  • Important: This sensor only updates its state when the primary binary sensor (binarysensor.YOURSENSOR_NAME) transitions from off to on, or while it remains on AND the script receives a new alert payload. It goes blank or shows "ืื™ืŸ ื”ืชืจืขื•ืช" when the primary sensor turns off. Due to its character limit and update behavior, it is not recommended for critical automation triggers or storing the full alert details. Use the binary sensor attributes for that.

Dedicated History Sensors (sensor.YOURSENSORNAMEhistory*)

These sensors provide structured access to a list of distinct alert events that occurred within the past hourstoshow timeframe. An "event" here is a single alert payload that is deemed unique based on its title, city, and area, and not within the timer duration of a previously recorded event of the same type/location.
  • sensor.YOURSENSORNAMEhistorycities:
State: The count of unique city names that appeared in any* distinct history event within the window. * Attribute: citiespastNh โ€“ A sorted list of the unique original city names. Includes scriptstatus.
  • sensor.YOURSENSORNAMEhistorylist:
* State: The total count of distinct alert events within the history window. * Attribute: lastNhalerts โ€“ A list of dictionaries, where each dictionary represents one distinct event with keys { title, city, area, time }. Includes scriptstatus. Note: time is a string formatted as 'YYYY-MM-DD HH:MM:SS'.
  • sensor.YOURSENSORNAMEhistorygroup:
* State: Same count as sensor.YOURSENSORNAMEhistorylist. * Attribute: lastNhalertsgroup โ€“ A nested dictionary structure { title: { area: [ { city, time }, ... ], ... }, ... } grouping the distinct events. Includes script_status. Note: time in this attribute is a string formatted as 'HH:MM:SS'.


Installation Instructions

To ensure the states of your inputtext and inputboolean helpers persist across Home Assistant restarts, create them manually beforehand:

  • Open your Home Assistant configuration.yaml file using the File Editor add-on or similar method.
2. Add Helpers and File Access to configuration.yaml

Add the configuration below under homeassistant:, inputtext:, and inputboolean:. Adjust the sensorname if you plan to use a different base name than redalert.

#/config/configuration.yaml

homeassistant: # ... other homeassistant settings ...

# Required for GeoJSON integration to access files from /config/www # Add the URL(s) Home Assistant uses to access itself locally allowlistexternalurls: - http://<YOURHOMEASSISTANTIPOR_HOSTNAME>:8123 # Replace with your actual HA access URL(s) - http://homeassistant.local:8123 # Example using the default mDNS name

# Optional: Allow File Editor or other addons to access www if needed # This entry might be needed if your add-on config paths are non-standard # or you have issues accessing /config/www from other add-ons. # allowlistexternaldirs: # - "/config/www"

input_text: # Matches default sensorname. Change 'redalert' if you use a different sensor_name red_alert: name: Last Alert Summary min: 0 # Minimum length max: 255 # Maximum length for input_text state

input_boolean: # Matches default sensorname. Change 'redalert' if you use a different sensor_name redalerttest: name: Trigger Test Alert icon: mdi:alert-circle

  • Install the AppDaemon addon in Home Assistant: Navigate to Settings > Add-ons > Add-on store > Search for "AppDaemon" and install it.
  • Once installed, configure AppDaemon: Enable Show in sidebar, Auto-start, and Watchdog. Apply the configuration changes.
  • Start the AppDaemon add-on.
  • Using a file editor (like the File Editor add-on), edit the AppDaemon configuration file. This is typically located at /addonconfigs/a0d7b954appdaemon/appdaemon.yaml.
[!TIP]
>
If using the File Editor add-on and unable to access /addon_configs, you might need to disable Enforce Basepath in its configuration: Go to Settings > Add-ons > File Editor > Configuration and toggle the option off. Remember to re-enable it later if you prefer the security.
[!IMPORTANT]
>
* The latitude, longitude, elevation, and time_zone settings here are for AppDaemon itself and affect how AppDaemon handles time-based functions. They are not used by the Red Alerts Israel script to determine your location for filtering cities.
* If you installed via HACS, ensure app_dir: /homeassistant/appdaemon/apps/ is correctly set in your appdaemon.yaml. This tells AppDaemon where to find the script files downloaded by HACS. If you installed manually into /config/appdaemon/apps, this path might be /config/appdaemon/apps. Check your AppDaemon add-on documentation for the correct default if unsure.

Configure appdaemon.yaml

#/addonconfigs/a0d7b954appdaemon/appdaemon.yaml

secrets: /homeassistant/secrets.yaml # Uncomment this line if you use secrets

appdaemon: # Set app_dir to where AppDaemon finds your app files. # For HACS installs, this is typically: app_dir: /homeassistant/appdaemon/apps/

# IMPORTANT - Add your geolocation from https://www.latlong.net/ latitude: 31.9837528 longitude: 34.7359077 elevation: 2 time_zone: Asia/Jerusalem

plugins: HASS: type: hass

http: timeout: 30 # Recommended timeout admin: api: hadashboard:

You can download the script file manually or via HACS. Using HACS is recommended as it simplifies future updates.

Manual Download

  • Download the redalertsisrael.py script file directly from the GitHub repository: Download Script.
  • Using the File Editor add-on or similar, create a new folder inside your AppDaemon apps directory (usually /config/appdaemon/apps/ or /homeassistant/appdaemon/apps/). Name the folder redalertsisrael.
  • Place the downloaded redalertsisrael.py file inside the /redalertsisrael/ folder you just created.
  • Proceed to the final step.

HACS Download

  • In Home Assistant: Navigate to Settings > Integrations > HACS > Configure and enable AppDaemon apps discovery & tracking. After enabling, return to the main HACS screen.
  • Click the ... menu in the top right and select Custom repositories.
  • Add https://github.com/idodov/RedAlert/ as the repository URL. Select AppDaemon as the Category. Click Add.
  • Go back to the main HACS page, search for Red Alerts Israel, and click on it.
  • Click the Download button on the integration page.
  • Proceed to the final step.

Final Step: Configure apps.yaml

In your AppDaemon applications configuration file, typically located at /config/appdaemon/apps/apps.yaml, add the following configuration block.
[!IMPORTANT]
citynames List: The names in the citynames list must exactly match the names defined by PIKUD HA-OREF, including spelling and special characters like hyphens or quotation marks. Consult the official list here: PIKUD HA-OREF City Names List. Using incorrect names means the binarysensor.YOURSENSORNAMEcity sensor will not turn on for those locations.

Configure apps.yaml

#/config/appdaemon/apps/apps.yaml

Make sure this entry matches your app directory name (e.g., redalertsisrael folder name)

redalertsisrael: # This is the AppDaemon app name (used in logs) module: redalertsisrael # Name of the Python file without the .py extension class: RedAlertsIsrael # Name of the main class within the Python file

# --- Core Settings --- interval: 5 # (Seconds) How often the script checks the Oref API. Default: 5. Shorter intervals provide faster updates. timer: 120 # (Seconds) How long binarysensor.#sensorname# and binarysensor.#sensorname#_city stay 'on' after the last alert activity is detected in an incident window. Default: 120. sensorname: "redalert" # Base name for all created Home Assistant entities (e.g., binarysensor.redalert). Match this in configuration.yaml if using default helpers. Default: "red_alert".

# --- History & Saving --- save2file: True # Set to True to enable saving history (.txt, .csv), GeoJSON files (latest & 24h), and JSON state backup to the '/config/www' folder. Default: True. Requires www folder to be writeable. hourstoshow: 12 # (Hours) The duration for the dedicated history sensors (sensor.#sensorname#history_*). Alerts older than this are excluded from history attributes. Default: 4.

# --- Optional Features --- mqtt: False # (Boolean or String) Set True to publish JSON alert payload via MQTT to 'home/[sensor_name]/event' topic when a new alert payload is received. Set to a custom topic string (e.g., "notifications/alerts") for a different topic. Default: False. event: True # (Boolean) Set True to fire a native Home Assistant event '[sensorname]event' with the full alert payload when a new alert payload is received. Default: True.

# --- Location Specific --- citynames: # List of exact city/area names you want to monitor for binarysensor.#sensorname#city. Case-sensitive. - "ืื–ื•ืจ ืชืขืฉื™ื™ื” ืฆืคื•ื ื™ ืืฉืงืœื•ืŸ" # Example: Ashkelon Industrial Zone North - "ื—ื™ืคื” - ืžืคืจืฅ" # Example: Haifa Bay - "ืชืœ ืื‘ื™ื‘ - ืžืจื›ื– ื”ืขื™ืจ" # Example: Tel Aviv - City Center # Add more city names here exactly as they appear in cities_name.md - "ืืฉื“ื•ื“ - ื,ื‘,ื“,ื”" - "ื›ื™ืกื•ืคื™ื"

| Parameter | Description | Example | Default Value | | :-------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------ | :------------ | | interval | The interval in seconds at which the script polls the API. Shorter intervals mean faster updates but more frequent API calls. Must be > 1. | 3 | 5 | | timer | The duration, in seconds, for which the main binary sensors (binarysensor.YOURSENSORNAME, binarysensor.YOURSENSORNAME_city) remain on after the last alert activity is detected in a single alert window. After this time and confirmation of no active alerts, sensors turn off. | 180 | 120 | | sensorname | The base name for all created Home Assistant entities (e.g., binarysensor.YOURNAME). Choose a unique name. Ensure it matches the name used for the inputtext and inputboolean helpers in configuration.yaml. | "tsevaadom" | "red_alert" | | save2file | Set to True to enable saving history files (.txt, .csv), GeoJSON files (latest and history), and a JSON state backup file to the /config/www directory. Requires write permissions for the AppDaemon user/container. | True | True | | hourstoshow | The duration, in hours, that the dedicated history sensors (sensor.YOURSENSORNAMEhistory*) should track and display distinct past alert events. Alerts older than this window are pruned from history attributes. | 24 | 4 | | mqtt | Set to True to publish the full JSON alert payload via MQTT when a new alert payload is received from the API. The default topic is home/YOURSENSORNAME/event. Can be set to a string (e.g., "your/custom/topic") for a different topic. | True or "alerts/rocket" | False | | event | Set to True to fire a native Home Assistant event (YOURSENSORNAME_event) with the full alert payload when a new alert payload is received from the API. | True | True | | citynames | A list of the exact city or area names you want to monitor for the city-specific sensor (binarysensor.YOURSENSORNAMEcity). Names must match the official PIKUD HA-OREF list precisely (citiesname.md). Can be an empty list []. | ืชืœ ืื‘ื™ื‘ - ืžืจื›ื– ื”ืขื™ืจ | [] |

  • Restart the AppDaemon add-on after saving apps.yaml. Check the AppDaemon logs (Settings > Add-ons > AppDaemon > Log) for errors during initialization.

Home Assistant Entities Summary

After successful installation and configuration, Home Assistant will expose several new entities based on your sensorname (default: redalert):

binarysensor.redalert: State is on during any* alert nationwide, off otherwise (controlled by timer). Attributes contain latest and cumulative data for the current window.

  • binarysensor.redalertcity: State is on only if an alert includes one of your citynames. Attributes contain same data as the main sensor for the current window.
inputtext.redalert: State shows a brief summary of the latest alert payload* when a sensor is on.
  • inputboolean.redalert_test: Toggle this to on to manually trigger a test alert sequence. It will turn off automatically when the test completes.
  • sensor.redalerthistorycities: State is the count of unique cities in the history window (hourstoshow). Attribute citiespastNh lists them.
sensor.redalerthistorylist: State is the count of distinct alert events* in the history window. Attribute lastNhalerts lists the events. sensor.redalerthistorygroup: State is the count of distinct alert events* in the history window. Attribute lastNhalerts_group provides a grouped structure.

Attribute Reference

The primary binary sensors (binarysensor.YOURSENSORNAME and binarysensor.YOURSENSORNAMEcity) expose detailed attributes about the current alert window. You can access any attribute in automations, templates, or Lovelace cards using stateattr('ENTITYID', 'attributename'). For example:
{{ stateattr('binarysensor.red_alert', 'title') }}

Full List of Sensor Attributes for binarysensor.YOURSENSORNAME and binarysensor.YOURSENSORNAME_city

These attributes reflect the current state of the alert window since the sensor last turned on. When the sensor is off, they show default/empty values or the prev_* values from the window that just ended.

| Attribute name | Description | Example | | :------------------ | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :----------------------------------------- | | active_now | true when the sensor state is on, false when off. Mirrors the sensor state. | false | | script_status | The operational status of the AppDaemon script (initializing, running, error, terminated). Useful for monitoring the script itself. | running | | id | Unique ID of the latest alert payload received during the current window. | 1721993400123456 | | cat | Category number (1-13) of the latest alert payload. Corresponds to alert type (e.g., 1 for rockets). | 1 | | title | Title/Type of the latest alert payload (e.g., "ื™ืจื™ ืจืงื˜ื•ืช ื•ื˜ื™ืœื™ื"). | ื™ืจื™ ืจืงื˜ื•ืช ื•ื˜ื™ืœื™ื | | desc | Recommended action description from the latest alert payload (e.g., "ื”ื™ื›ื ืกื• ืœืžืจื—ื‘ ื”ืžื•ื’ืŸ ื•ืฉื”ื• ื‘ื• 10 ื“ืงื•ืช"). | ื”ื™ื›ื ืกื• ืœืžืจื—ื‘ ื”ืžื•ื’ืŸ ื•ืฉื”ื• ื‘ื• 10 ื“ืงื•ืช | | special_update | true if the latest alert payload is a "special update" from Pikud HaOref, false otherwise. | false | | areas | Comma-separated string of all areas affected by any payload within the current active window. | ื’ื•ืฉ ื“ืŸ, ืงื• ื”ืขื™ืžื•ืช | | cities | A sorted list of all unique original city names affected by any payload within the current active window. | ['ืื•ืจ ื™ื”ื•ื“ื”', 'ืชืœ ืื‘ื™ื‘ - ืžืจื›ื– ื”ืขื™ืจ'] | | data | Comma-separated string of all unique original city names affected during the current active window. May be cut if very long. | ืื•ืจ ื™ื”ื•ื“ื”, ืชืœ ืื‘ื™ื‘ - ืžืจื›ื– ื”ืขื™ืจ, ื—ื•ืœื•ืŸ... | | data_count | Count of unique original city names affected during the current active window. | 5 | | duration | Recommended duration (in seconds) to stay in a safe room, extracted from the desc of the latest alert payload. | 600 | | icon | MDI icon string based on the cat of the latest alert payload. | mdi:rocket-launch | | emoji | Emoji character based on the cat of the latest alert payload. | ๐Ÿš€ | | alerts_count | The number of individual alert payloads received and processed by the script during the current active alert window (since the sensor last went on). | 3 | | last_changed | ISO timestamp string (YYYY-MM-DDTHH:MM:SS.ffffff) when this sensor's state or any of its attributes were last updated. | "2024-07-25T10:30:00.123456" | | mycities | A sorted list of the city names exactly as configured in your apps.yaml citynames list. | ['ื—ื™ืคื” - ืžืคืจืฅ', 'ืชืœ ืื‘ื™ื‘ - ืžืจื›ื– ื”ืขื™ืจ'] | | alert | One-line summary string: [Title] - [Areas]: [Cities]. Uses cumulative window data. | ื™ืจื™ ืจืงื˜ื•ืช ื•ื˜ื™ืœื™ื - ื’ื•ืฉ ื“ืŸ, ืงื• ื”ืขื™ืžื•ืช: ... | | alert_alt | Multi-line summary string: [Title]\n [Area]: [Cities]\n [Area]: [Cities].... Uses cumulative window data. | ื™ืจื™ ืจืงื˜ื•ืช ื•ื˜ื™ืœื™ื\n ื’ื•ืฉ ื“ืŸ: ืชืœ ืื‘ื™ื‘...\n ืงื• ื”ืขื™ืžื•ืช: ื›ื™ืกื•ืคื™ื | | alert_txt | One-line string listing Areas and Cities affected in the current window: [Area]: [Cities], [Area]: [Cities].... | ื’ื•ืฉ ื“ืŸ: ืชืœ ืื‘ื™ื‘ - ืžืจื›ื– ื”ืขื™ืจ, ืื•ืจ ื™ื”ื•ื“ื”... | | alert_wa | Multi-line formatted message optimized for WhatsApp, summarizing alerts by type and area based on cumulative window data. | whatsapp | | alert_tg | Multi-line formatted message optimized for Telegram, summarizing alerts by type and area based on cumulative window data. | | | prev_cat | Category number of the alert from the previous alert window (before the sensor last went off and then on again). | 1 | | prev_title | Title of the alert from the previous alert window. | ื™ืจื™ ืจืงื˜ื•ืช ื•ื˜ื™ืœื™ื | | prev_desc | Description from the previous alert window. | ื”ื™ื›ื ืกื• ืœืžืจื—ื‘ ื”ืžื•ื’ืŸ ื•ืฉื”ื• ื‘ื• 10 ื“ืงื•ืช | | prev_areas | Areas from the previous alert window. | ืงื• ื”ืขื™ืžื•ืช | | prev_cities | List of cities from the previous alert window. | ['ืฉืœื•ืžื™'] | | prev_data | Comma-separated cities string from the previous alert window. | ืฉืœื•ืžื™ | | prevdatacount | City count from the previous alert window. | 1 | | prev_duration | Duration from the previous alert window. | 600 | | prevlastchanged | ISO timestamp when the previous alert window became active (when the sensor state last went on for that window). | "2024-07-25T10:15:05.987654" | | prevalertscount | Sequence count from the previous alert window. | 2 | | prevspecialupdate | Special update flag status from the previous alert window. | false |


Usage Examples

Creating Derived Sensors for Specific Updates

The primary binary sensors (binarysensor.YOURSENSORNAME and binarysensor.YOURSENSORNAME_city) remain on for the timer duration after the last alert activity in a window. If multiple alert payloads arrive in quick succession during this window, the sensor's attributes update, but the state stays on.

To trigger automations on each new alert payload (not just the off to on state change) or specific types of updates, you can create template binary sensors that monitor attribute changes of the primary sensors.

A particularly useful attribute is specialupdate. PIKUD HA-OREF sometimes sends specific informational updates (like "Alert will trigger soon") which the script flags by setting this attribute to true. You can create binary sensors that turn on specifically when the specialupdate attribute becomes true on the main or city sensor:

Lovelace Card Example

You can add the entities to your dashboard using various cards. Here's a simple example using a Vertical Stack card:

red-alerts-sensors

Lovelace Card YAML

type: vertical-stack
cards:
  - type: tile
    entity: inputtext.redalert # Displays the main alert summary text
    vertical: true
    state_content: state # Or set to 'last-changed', 'last-updated', etc.

- type: entities entities: - entity: binarysensor.redalert # Main sensor (any alert) state_color: true # Optional: Color icon based on state - entity: binarysensor.redalert_city # City-specific sensor state_color: true # Optional: Color icon based on state - entity: sensor.redalerthistory_cities # Example history sensor - entity: inputboolean.redalert_test # Test trigger statecolor: true # Applies statecolor to entities unless overridden above

Map Visualization (GeoJSON)

GeoJSON Map Example

[!NOTE]
If the GeoJSON integration fails to load, double-check your allowlistexternalurls and the exact URL you are using in the integration setup. Also verify that the files actually exist in the /config/www folder after an alert occurs (or after script initialization for the empty/default files).

GeoJSON Setup Details

If the save2file parameter is set to True, the script automatically generates two GeoJSON files in the Home Assistant /config/www directory. This directory is typically accessible via the Home Assistant frontend at the URL /local/.

YOURSENSORNAME_latest.geojson: Contains coordinate data for the unique cities included in the currently active* alert window. This file is updated whenever a new payload arrives within an active window. YOURSENSORNAME24h.geojson: Contains coordinate data for distinct alert events* that occurred within the last hoursto_show timeframe, based on the history sensor data. This file is updated every time the primary sensor state changes (on -> off, or off -> on) or when a new payload arrives during an active window.

To display these on the Home Assistant map:

  • Ensure the www folder exists in your /config directory.
  • Ensure your configuration.yaml includes allowlistexternalurls correctly configured with the URL(s) you use to access your Home Assistant instance (as shown in the Installation steps). This allows the GeoJSON integration to fetch the files.
  • Install the GeoJSON integration in Home Assistant: Go to Settings > Devices & Services > Add Integration, search for "GeoJSON", and follow the prompts.
  • When prompted for the GeoJSON file URL, enter http://YOURHOMEASSISTANTIPORHOSTNAME:8123/local/YOURSENSORNAME24h.geojson. Replace YOURHOMEASSISTANTIPORHOSTNAME:8123 with your actual Home Assistant access address and port, and YOURSENSOR_NAME with your configured sensor base name.
  • Optionally, add a second GeoJSON integration entity pointing to http://YOURHOMEASSISTANTIPORHOSTNAME:8123/local/YOURSENSORNAMElatest.geojson to visualize only the currently active alert locations separately.
  • After adding the integration entity/entities, you can click on the created GeoJSON entity (e.g., geolocation.yoursensorname24h). In the entity's settings, you can adjust the Default maximum radius (e.g., set it to 2000-3000 km to ensure all points in Israel are visible) and Home Zone Behavior.
{28E29F42-3F7F-4625-859B-587381F81941}

Home Assistant Events

If the event parameter is set to True (default), the script fires a native Home Assistant event each time a new alert payload is received from the API. This is often the most responsive way to trigger automations, as it doesn't rely on polling sensor states.

The event name is YOURSENSORNAMEevent. You can see these events in Home Assistant's Developer Tools > Events section by subscribing to YOURSENSORNAMEevent.

>Home Assistant Event Data Structure & Example Automation

The data payload associated with the YOURSENSORNAME_event is a dictionary containing detailed information about the specific alert payload that triggered the event:

| Key | Type | Description | Example Value | | :------------- | :------- | :-------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------ | | id | integer | Unique ID of the alert payload from the API. | 1234567890123456 | | category | integer | Category number of the alert (corresponds to type, 1-13). | 1 | | title | string | Title of the alert (e.g., "ื™ืจื™ ืจืงื˜ื•ืช ื•ื˜ื™ืœื™ื"). | "ื™ืจื™ ืจืงื˜ื•ืช ื•ื˜ื™ืœื™ื" | | cities | list | A list of the original city names affected by this specific payload. | ["ืื‘ื™ืจื™ื", "ืคืกื•ื˜ื”"] | | areas | string | A comma-separated string of areas affected by this specific payload. | "ืงื• ื”ืขื™ืžื•ืช" | | description | string | The recommended action description (e.g., "ื”ื™ื›ื ืกื• ืœืžืจื—ื‘ ื”ืžื•ื’ืŸ ื•ืฉื”ื• ื‘ื• 10 ื“ืงื•ืช"). | "ื”ื™ื›ื ืกื• ืœืžืจื—ื‘ ื”ืžื•ื’ืŸ ื•ืฉื”ื• ื‘ื• 10 ื“ืงื•ืช" | | timestamp | string | ISO formatted timestamp when the event was processed by the script. | "2024-07-25T10:30:00.123456" | | alerts_count | integer | The sequence number of this alert payload within the current active alert window. This count resets when the main binary sensor goes off. | 1 (for the first in a window) or 3 | | istest | boolean | True if this event was triggered by the test inputboolean, False for real alerts from the API. | False |

Mobile Notification with Rich Map (Push)

Sends a notification with the dynamic map image directly to your phone:

image image

alias: Notify Red Alert with Map
trigger:
  - platform: state
    entityid: binarysensor.red_alert
    from: "off"
    to: "on"
action:
  - action: notify.mobileappyour_device
    data:
      title: "{{ stateattr('binarysensor.red_alert', 'title') }}"
      message: >
        {{ stateattr('binarysensor.redalert', 'datacount') }} ื™ืฉื•ื‘ื™ื ื‘{{ stateattr('binarysensor.red_alert', 'areas') }}.
      data:
        image: "{{ stateattr('binarysensor.redalert', 'mapurl') }}"

Example Automation Triggering on the Event:

You can set up an automation in Home Assistant that triggers whenever this event is fired:

Example event payload

{    "id": 1234567890123456,    "category": 1,    "title": "ื™ืจื™ ืจืงื˜ื•ืช ื•ื˜ื™ืœื™ื",    "cities": ["ืื‘ื™ืจื™ื", "ืคืกื•ื˜ื”"],    "areas": "ืขื•ื˜ืฃ ืขื–ื”",    "description": "ื”ื™ื›ื ืกื• ืœืžืจื—ื‘ ื”ืžื•ื’ืŸ ื•ืฉื”ื• ื‘ื• 10 ื“ืงื•ืช",    "timestamp": "2024-07-25T10:30:00",    "alerts_count": 2,    "is_test": false }

Example automation added to automations.yaml or configured via the UI

automation:   - alias: Respond to Red Alert Event     # Trigger when the custom event is fired     trigger:       platform: event       eventtype: redalertevent # Use your configured sensorname_event name     action:       # Example Action: Send a notification with details from the event data       - service: notify.yournotificationservice # Replace with your actual notification service entity ID         data:           title: "๐Ÿ”ด Red Alert!"           message: >             {% set data = trigger.event.data %}             {{ data.title }} in {{ data.cities | join(', ') }}             [{{ astimestamp(data.timestamp) | timestampcustom('%H:%M:%S', true) }}]             {{ data.description }}

# Example Action: Play a TTS message # - service: tts.speak # data: # mediaplayerentityid: mediaplayer.your_speaker # Replace with your speaker # language: he-IL # Set language if needed # message: > # {% set data = trigger.event.data %} # ื”ืชืจืขืช {{ data.title }} ื‘{{ data.areas }}. {{ data.description }}

# Add other actions like turning on lights, etc.

MQTT Events

If the mqtt parameter is set to True (or a custom topic string), the script publishes a JSON message to an MQTT topic each time a new alert payload is received from the API. This is useful for integrating with other systems or dashboards that consume MQTT messages.

The default MQTT topic is home/YOURSENSORNAME/event. If you set mqtt to a string (e.g., "my/alerts/topic"), that string will be used as the topic.

MQTT Payload Structure & Example Automation

The payload published to the MQTT topic is a JSON string containing details about the specific alert payload that was received.

Example Payload (JSON string) - Note: This structure matches the specific example provided in the request:

{
  "id": 1234567890123456,
  "category": 1,
  "title": "ื™ืจื™ ืจืงื˜ื•ืช ื•ื˜ื™ืœื™ื",
  "data": ["ืื‘ื™ืจื™ื", "ืคืกื•ื˜ื”"],
  "desc": "ื”ื™ื›ื ืกื• ืœืžืจื—ื‘ ื”ืžื•ื’ืŸ ื•ืฉื”ื• ื‘ื• 10 ื“ืงื•ืช",
  "alertDate": "2024-07-25 10:30:00",
}

Using the MQTT Event in Home Assistant Automations

To trigger Home Assistant automations based on these MQTT messages, configure an MQTT trigger subscribing to the topic the script publishes to (home/YOURSENSORNAME/event by default, or your custom topic).

Ensure the MQTT integration is configured in Home Assistant.

# Example automation added to automations.yaml or configured via the UI
automation:
  - alias: Respond to MQTT Alert
    # Trigger when a message arrives on the specified MQTT topic
    trigger:
      platform: mqtt
      topic: "home/redalert/event" # Match the script's publish topic (replace redalert if needed)
    action:
      # Example Action: Send a notification using data from the JSON payload
      - service: notify.yournotificationservice # Replace with your actual notification service entity ID
        data:
          title: "๐Ÿšจ MQTT Alert!"
          # Access payload data using trigger.payload_json.<key>
          # Note: Access keys match the JSON payload structure above (data, desc, alertDate)
          message: >
            {% set data = trigger.payload_json %}
            {{ data.title }} in {{ data.data | join(', ') }}
            [{{ astimestamp(data.alertDate) | timestampcustom('%H:%M:%S', true) }}]
            {{ data.desc }}

# Add other actions like playing TTS, etc.

This setup allows you to leverage the detailed JSON payload sent over MQTT directly within your Home Assistant automations, providing flexibility for advanced logic or integrating with other systems.

History & Backup Files

History and Backup File Details

If save2file is enabled, the script manages several files in the Home Assistant /config/www directory. This allows you to access historical alert data and maintain the last known alert state across AppDaemon restarts. The /config/www directory is typically mapped to http://YOURHAIP:8123/local/ in Home Assistant.

  • YOURSENSORNAME_history.txt: This file is appended with a summary of each completed alert window (when the main sensor state transitions back to off). The summary includes the date, time, alert type, areas, and cities.
  • YOURSENSORNAME_history.csv: This file is appended with structured data for each completed alert window. It includes columns for ID, Day, Date, Time, Title, City Count, Areas, Cities (string), Description, and Number of Payloads in the window. This format is suitable for importing into spreadsheet software for analysis. The CSV header is automatically created if the file doesn't exist or is empty on startup.
  • YOURSENSORNAMEhistory.json: This file is a simple backup of the last received alert payload's core data. It is saved to help the script restore the prev* attributes of the sensors after AppDaemon restarts, providing some state persistence. It does not store the full history list.
  • YOURSENSORNAME_latest.geojson: (See Map section) Stores GeoJSON point data for the cities in the currently active alert window.
  • YOURSENSORNAME24h.geojson: (See Map section) Stores GeoJSON point data for distinct alert events within the history window (hoursto_show).
The TXT and CSV history files summarize incidents after the main sensor resets to off (i.e., after the timer duration has passed and no new alerts were detected). The JSON backup is primarily for restoring the prev_* attributes on startup.

You can access these files directly via your browser using URLs like http://YOURHOMEASSISTANTIP:8123/local/YOURSENSORNAMEhistory.txt.


Script Status

image

Markdown Card YAML

# Replace 'redalert' with your configured sensorname if different.
type: markdown
content: |
   {% set status = stateattr('binarysensor.redalert', 'scriptstatus') %} {# Adjust if needd #} 
   {% if status == 'running' or status == 'idle' %}
   <ha-alert alert-type="success">Script status: {{ status }}</ha-alert>
   {% elif status == 'initializing' %}
   <ha-alert alert-type="info">Script status: {{ status }}</ha-alert>
   {% else %}
   <ha-alert alert-type="error">Script status: {{ status }} (Check appdaemon log)</ha-alert>
   {% endif %}

History Markdown Example

This example provides YAML code for a Home Assistant Markdown card that displays recent alert history grouped by alert type and area, leveraging the data available in the sensor.YOURSENSORNAMEhistorygroup sensor's attributes.

History Markdown Card Example

Markdown Card YAML

```yaml

Replace 'redalert' with your configured sensorname if different.

type: markdown content: | {% set show_history = True %} {% set show_info = True %} {% set alerts = stateattr('sensor.redalerthistorygroup', 'last24halerts_group') %} {% set oref = states('binarysensor.redalert') %}
{% if oref == 'on' %} # {{ stateattr('binarysensor.redalert', 'title') }} {{ stateattr('binarysensor.redalert', 'emoji') }}
{{ stateattr('binarysensor.redalert', 'alerttxt') }} {% else %} ## ืื™ืŸ ื”ืชืจืขื•ืช โœ… {% endif %}
{% set current_date = now().date() %} {# Check if prevlastchanged attribute exists and is in expected ISO format before parsing #} {% if stateattr('binarysensor.redalert', 'prevlastchanged') is string and stateattr('binarysensor.redalert', 'prevlastchanged') | regex_match("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?([+-]\\d{2}:\\d{2}|Z)?$") %} {% set lastchangedstr = stateattr('binarysensor.redalert', 'prevlast_changed') %} {# Attempt parsing with fromisoformat, fallback to as_timestamp if needed or pro


README truncated. View on GitHub
๐Ÿ”— More in this category

ยฉ 2026 GitRepoTrend ยท idodov/RedAlert ยท Updated daily from GitHub