Presence detection with Keenetic or maybe other OPKG routers

Hi all, a small and definetly not complete guide for those, who want to monitor presence on Openhab by pinging network devices. To not burn your phone battery fast, i’ve set refresh interval to a rather low rate - 10 minutes, and this works, but presence detection is very slow. So i’ve found how to send POST-requests from my Keenetic router, when my phones connect or disconnect to it’s wi-fi.
First of all, i had to install OPKG to a flash drive, connected to Keenetic, and formatted to ext4. Russian-language instruction is here. Take a file mipsel-installer.tar.gz or mips-installer.tar.gz, corresponding to your router, and place it into install folder on a flash drive. On router web interface select OPKG tab, choose your flash drive and write /opt/etc/init.d/rc.unslung in initrc scenario selector, then press save. After that router should reinitialize the drive and start OPKG install, check router log to be sure everything gone right.
Now you’ll be able to login to OPKG by ssh on port 222, login root, password keenetic. To run script we’ll need to install curl, wget and jq, so:

opkg update
opkg install curl
opkg install wget
opkg install jq

On your flash drive create a file 010-neighbour.sh in /opt/etc/ndm/neighbour.d folder. Edit 010-neighbour.sh and paste following code:

#!/bin/sh
DEV1="xxxxxxxxxxxxxxxxx"
DEV2="xxxxxxxxxxxxxxxxx"
DEV3="xxxxxxxxxxxxxxxxx"
DEV4="xxxxxxxxxxxxxxxxx"
AC1="new"
AC2="del"
replacement() {
    case "$1" in
        *$DEV1* ) echo "P";;
        *$DEV2* ) echo "M";;
        *$DEV3* ) echo "D";;
        *$DEV2* ) echo "A";;
    esac
}

replaceaction() {
    case "$1" in
	*$AC1* ) echo "ON";;
	*$AC2* ) echo "OFF";;
    esac
}

if [[ "$address" = "ipv4" && "$update" = "none" ]]; then
  mac=$(wget -qO - http://127.0.0.1:79/rci/show/ip/neighbour | jq --arg num "$id" '.[$num].mac')
  who=$(replacement "$mac")
  [ -z "$who" ] && exit 0
  act=$(replaceaction "$action")
  curl -X POST --header "Content-Type: text/plain" --header "Accept: application/json" -d "$act" "http://openhabIp:8080/rest/items/$who"
fi

Replace ********* with your devices mac addresses, P, M, D, A with switchable items you use to monitor presence, openhabIp with your Openhab IP address.
Give your script permission to execute:

chmod +x 010-neighbour.sh

You are done! Now Keenetic will switch your presence items almost instantly as your devices connect to it’s wi-fi.