Pre-requirements:
Raspberry Pi 3, 4, or 5
USB cable to connect the Pi to the UPS
Blank microsd for the operating system
Install an OS using the Raspberry PI imager - install a minimal image onto your blank microsd. For this example, I used the Trixie version of the Raspberry PI OS
Specify the following recommended details as part of the image customization:
hostname: modbus
userid: soqis-adm
password: use a good one! (more than 12 letters, numbers, capitals, and special characters)
If using wireless:
Configure wireless SSID
Configure US for wireless country
Set to US locale
After the installation completes, connect it to a network, login, and execute the following commands:
sudo apt update
sudo apt upgrade
sudo apt autoremove
sudo apt install nut
sudo nano /etc/nut/ups.conf
add the following but include your model of UPS in the description
[ups]
driver = usbhid-ups
port = auto
desc = APC SMI1500
sudo nano /etc/nut/upsd.conf
Uncomment the LISTEN lines for local access such as
LISTEN 127.0.0.1 3493
LISTEN 0.0.0.0 3493
LISTEN ::1 3493
sudo nano /etc/nut/upsmon.conf
add
MONITOR ups@localhost 1 monuser secret master
sudo nano /etc/nut/nut.conf
Change
MODE=standalone
sudo systemctl enable nut-server
sudo systemctl restart nut-server
Issue the command
lsusb
to see if the UPS is listed. If it isn't, be sure it is connected before continuing.
upsc ups@localhost
Should display something along the lines of:
battery.charge: 100
battery.runtime: 3600
input.voltage: 120.0
output.voltage: 120.0
ups.load: 24
ups.status: OL
sudo apt install python3-pip -y
pip3 install pymodbus
Execute the following command to insure pymodbus is running:
python3 -c "import pymodbus; print('OK')"
Create a new file called ups_modbus_gateway.py and place the following code in it:
#!/usr/bin/env python3
import subprocess
import threading
import time
from pymodbus.datastore import ModbusSequentialDataBlock
from pymodbus.datastore import ModbusSlaveContext
from pymodbus.datastore import ModbusServerContext
from pymodbus.server import StartTcpServer
UPS_NAME = "ups"
#
# Register Map
#
# 40001 -> battery.charge
# 40002 -> battery.runtime (seconds)
# 40003 -> battery.voltage * 10
# 40004 -> battery.voltage.nominal * 10
# 40005 -> ups.status code
# 40006 -> ups.delay.shutdown
# 40007 -> ups.timer.shutdown
# 40008 -> ups.timer.reboot
# 40009 -> gateway health
# 40010 -> UPS communication health
#
REGISTER_COUNT = 32
def get_ups_data():
"""
Read all UPS values from NUT.
Returns a dictionary or None on failure.
"""
try:
output = subprocess.check_output(
["upsc", UPS_NAME],
stderr=subprocess.DEVNULL,
text=True,
timeout=10
)
data = {}
for line in output.splitlines():
if ":" not in line:
continue
key, value = line.split(":", 1)
data[key.strip()] = value.strip()
return data
except Exception as e:
print(f"NUT read error: {e}")
return None
def status_to_code(status):
"""
Convert UPS status strings into integer codes.
"""
if "LB" in status:
return 3
if "OB" in status:
return 2
if "CHRG" in status:
return 4
if "OL" in status:
return 1
return 5
def as_int(value, scale=1):
"""
Convert string numeric values into integers.
"""
try:
return int(float(value) * scale)
except Exception:
return 0
def modbus_safe(value):
"""
Convert NUT timer values into unsigned Modbus values.
"""
try:
value = int(float(value))
if value < 0:
return 65535
return value
except Exception:
return 65535
def update_loop(context):
while True:
try:
data = get_ups_data()
#
# UPS comm failure
#
if not data:
regs = [0] * REGISTER_COUNT
regs[8] = 1 # gateway healthy
regs[9] = 0 # UPS unavailable
context[0].setValues(
3,
0,
regs
)
print("UPS communication lost")
time.sleep(5)
continue
gateway_health = 1
ups_health = 1
regs = [0] * REGISTER_COUNT
regs[0] = as_int(
data.get("battery.charge", 0)
)
regs[1] = as_int(
data.get("battery.runtime", 0)
)
regs[2] = as_int(
data.get("battery.voltage", 0),
10
)
regs[3] = as_int(
data.get("battery.voltage.nominal", 0),
10
)
regs[4] = status_to_code(
data.get("ups.status", "")
)
regs[5] = modbus_safe(
data.get("ups.delay.shutdown", 0)
)
regs[6] = modbus_safe(
data.get("ups.timer.shutdown", -1)
)
regs[7] = modbus_safe(
data.get("ups.timer.reboot", -1)
)
#
# Health Registers
#
regs[8] = gateway_health
regs[9] = ups_health
context[0].setValues(
3,
0,
regs
)
print(
f"Battery={regs[0]}% "
f"Runtime={regs[1]}s "
f"Voltage={regs[2] / 10:.1f}V "
f"Status={regs[4]} "
f"Gateway={regs[8]} "
f"UPS={regs[9]}"
)
except Exception as e:
print(f"Update error: {e}")
time.sleep(5)
def main():
store = ModbusSlaveContext(
hr=ModbusSequentialDataBlock(
0,
[0] * REGISTER_COUNT
)
)
context = ModbusServerContext(
slaves=store,
single=True
)
updater = threading.Thread(
target=update_loop,
args=(context,),
daemon=True
)
updater.start()
print("Starting Modbus TCP server on port 1502")
StartTcpServer(
context=context,
address=("0.0.0.0", 1502)
)
if __name__ == "__main__":
main()
sudo mkdir -p /opt/ups-modbus
sudo cp ups_modbus_gateway.py /opt/ups-modbus/
sudo chmod +x /opt/ups-modbus/ups_modbus_gateway.py
sudo nano /etc/systemd/system/ups-modbus.service
Add the following to it and save it:
[Unit]
Description=APC Smart-UPS to Modbus TCP Gateway
After=network-online.target nut-server.service
Wants=network-online.target
[Service]
Type=simple
User=soqis_adm
Group=soqis_adm
WorkingDirectory=/opt/ups-modbus
ExecStart=/usr/bin/python3 /opt/ups-modbus/ups_modbus_gateway.py
Restart=always
RestartSec=10
# Give Python time to start after NUT
ExecStartPre=/bin/sleep 10
[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl enable ups-modbus
sudo systemctl start ups-modbus
sudo systemctl status ups-modbus
Should display:
Active: active (running)
View live logs using:
journalctl -u ups-modbus -f
Now, validate it is listening:
sudo ss -lntp | grep 1502
You should see something similar to:
LISTEN 0 128 0.0.0.0:1502
You can also see the logs using the command:
sudo journalctl -u ups-modbus -n 50 -o cat
Another way is to use mbpoll to access the server. Install it with
sudo apt install mbpoll
After installing it, query it with
mbpoll -m tcp 127.0.0.1 -p 1502 -a 1 -r 1 -c 8