routeros: Add script to publish poe power to mqtt

This commit is contained in:
Timo Makinen 2025-04-19 19:20:02 +00:00
parent ae59e21a2e
commit e790276359
4 changed files with 4247 additions and 1 deletions

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,54 @@
#!/bin/sh
set -eu
umask 077
community="public"
mqtt_send() {
topic="$1"
value="$2"
tlsdir="$(openssl version -d | sed -e 's/^OPENSSLDIR: "\(.\+\)"$/\1/')"
mosquitto_pub -h mqtt02.home.foo.sh -t "$topic" -m "$value" \
--cafile "${tlsdir}/certs/ca.crt" \
--key "${tlsdir}/private/$(hostname -f).key" \
--cert "${tlsdir}/certs/$(hostname -f).crt"
}
snmp_get() {
host="$1"
key="$2"
snmpget -v 1 -c "$community" "$host" -Oqv -m MIKROTIK-MIB "$key" | tr -d '"'
}
# only run script if first vrrp interface is in master state
for state in /run/keepalived/*.state ; do
if [ "$(cat "$state")" != "MASTER" ]; then
exit 0
fi
break
done
ldapsearch -Q -LLL "(&(objectClass=device)(description=MikroTik *))" cn | \
awk '{ if ($1 == "cn:") print $2 }' | while read -r name
do
snmpwalk -v 1 -c "$community" "$name" -Oq -m MIKROTIK-MIB \
MIKROTIK-MIB::mtxrPOEStatus | while read -r port status
do
port="$(echo "$port" | cut -d "." -f 2)"
[ "$status" = "poweredOn" ] || continue
device="$(snmp_get "$name" "SNMPv2-SMI::mib-2.31.1.1.1.18.${port}")"
[ -z "$device" ] && continue
location="$(ldapsearch -Q -LLL "(&(objectClass=device)(cn=${device}))" l | \
sed -n 's/^l: \(.\+\)/\1/p' | tr '[:upper:]' '[:lower:]' | tr ' ' '_')"
[ -z "$location" ] && continue
for key in Current Power Voltage ; do
topic="home/${location}/${device}/$(echo "$key" | tr '[:upper:]' '[:lower:]')"
value="$(snmp_get "$name" "MIKROTIK-MIB::mtxrPOE${key}.${port}")"
mqtt_send "$topic" "$value"
done
done
done

View file

@ -0,0 +1,3 @@
---
dependencies:
- {role: ldap}

View file

@ -1,4 +1,20 @@
---
- name: Install packages
ansible.builtin.package:
name: "{{ item }}"
state: installed
with_items:
- mosquitto
- net-snmp-utils
- name: Install routeros mib
ansible.builtin.copy:
dest: /usr/share/snmp/mibs/MIKROTIK-MIB.txt
src: mikrotik.mib
mode: "0644"
owner: root
group: "{{ ansible_wheel }}"
- name: Create group
ansible.builtin.group:
name: routeros
@ -38,10 +54,24 @@
owner: root
group: "{{ ansible_wheel }}"
- name: Install cron job
- name: Install download cron job
ansible.builtin.cron:
name: download-routeros-firmware
job: /usr/local/bin/download-routeros-firmware
user: routeros
hour: "05"
minute: "25"
- name: Install mqtt publish script
ansible.builtin.copy:
dest: /usr/local/bin/routeros-poe-mqtt-publish
src: routeros-poe-mqtt-publish.sh
mode: "0755"
owner: root
group: "{{ ansible_wheel }}"
- name: Install mqtt publish cron job
ansible.builtin.cron:
name: routeros-poe-mqtt-publish
job: /usr/local/bin/routeros-poe-mqtt-publish
minute: "*/5"