OpenWRT WAN-Connection Monitor

Monitoring the status of WAN connection on OpenWRT router in HomeAssistant

reference:

https://openwrt.org/docs/guide-user/base-system/hotplug

configuration.yaml:

binary_sensor:
  - platform: mqtt
    state_topic: "openwrt/pppoe-wan"
    payload_on: "ifup"
    payload_off: "ifdown"
    name: internet
    device_class: connectivity
    json_attributes_topic: "openwrt/wan-ip"

last 3 lines are not essential. Of cause, there should be one mqtt broker in the configuration:

mqtt:
  broker: mqtt_broker #your own broker address

script under /etc/hotplug.d/ directory of OpenWRT router:

#!/bin/sh
[ "$INTERFACE" = "wan" ] || exit 0
mosquitto_pub -h mqtt_broker -t openwrt/pppoe-wan -m "$ACTION"
wanip=$(ifconfig pppoe-wan | awk '/inet addr/{print substr($2,6)}')
mosquitto_pub -h mqtt_broker -t openwrt/wan-ip -m "{\"wan-ip\":\""$wanip"\"}" 

last 2 lines are not essential.

The topics should match between the script and the configuration.

link: repo on GitHub

2 Likes

optimized code:

configuration.yaml:

binary_sensor:
  - platform: mqtt
    state_topic: "openwrt/pppoe-wan"
    json_attributes_topic: "openwrt/wan-ip"
    name: internet
    device_class: connectivity

script under /etc/hotplug.d/ directory of OpenWRT router:

#!/bin/sh
[ "$INTERFACE" = "wan" ] || exit 0
[ "$ACTION" = "ifdown" ] && mosquitto_pub -h x.x.x.x -t openwrt/pppoe-wan -m OFF
[ "$ACTION" = "ifup" ] && mosquitto_pub -h x.x.x.x -t openwrt/pppoe-wan -m ON
[ "$ACTION" = "ifupdate" ] && (
    wanip=$(ifconfig pppoe-wan | awk '/inet addr/{print substr($2,6)}')
    mosquitto_pub -h x.x.x.x -t openwrt/wan-ip -m "{\"wan-ip\":\""$wanip"\"}" )
1 Like

thanks for this work, its great.
in which folder do you add the script?
I copied it into every folder, only if I restart homeassistant does it take days until the script is executed once

pls put the script under “/etc/hotplug.d/iface” directory on your openwrt router.

is not executed for me when the internet is down, only if I manually go to restart

chmod +x ?

Yes i have make the script executable

maybe the names of the interfaces are diffrent.
to make sure, you could add env > /tmp/iface.log to the begainning of the script, and check the log later