Last active
August 19, 2020 04:02
-
-
Save mkfink/11797518282643ca159e9e0f2dcd6381 to your computer and use it in GitHub Desktop.
Track power on/off status of sonoff attached to 3d printer for Octopi PSU Control plugin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# /home/pi/power_tracker.py | |
#!/usr/bin/env python3 | |
import paho.mqtt.client as mqtt | |
def on_message(c, userdata, msg): | |
global state | |
payload = msg.payload.decode('utf-8') | |
if payload == 'ON' or payload == 'OFF': | |
state = payload | |
state = 'OFF' | |
state_old = '' | |
host = 'sirius.lan' | |
stat_topic = 'stat/vulcan/power/POWER' | |
com_topic = 'cmnd/vulcan/power/POWER' | |
c = mqtt.Client(clean_session=True, client_id='power_tracker') | |
c.reinitialise() | |
c.message_callback_add(stat_topic, on_message) | |
c.connect(host) | |
c.subscribe(stat_topic) | |
c.publish(com_topic, '') | |
while True: | |
c.loop(timeout=1) | |
if state != state_old: | |
print(state) | |
with open ('/home/pi/power', 'w') as f: | |
if state == 'ON': | |
f.write('0') | |
elif state == 'OFF': | |
f.write('1') | |
state_old = state | |
#################################### | |
# Also needs: | |
#################################### | |
# /home/pi/pow.sh | |
# run every 5 seconds by PSU Control plugin | |
#----------------------------------- | |
# #!/bin/sh | |
# test $(cat /home/pi/power) = 0 | |
# exit $? | |
# | |
#################################### | |
# Add systemd service: | |
# /lib/systemd/system/power_tracker.service | |
#----------------------------------- | |
# [Unit] | |
# Description=track power of 3d printer sonoff | |
# After=multi-user.target | |
# [Service] | |
# Type=idle | |
# ExecStart=/usr/bin/python3 /home/pi/power_tracker.py | |
# [Install] | |
# WantedBy=multi-user.target | |
#----------------------------------- | |
# setup commands | |
# sudo chmod 644 /lib/systemd/system/power_tracker.service | |
# sudo systemctl daemon-reload | |
# sudo systemctl enable power_tracker.service | |
# sudo reboot | |
# sudo systemctl status power_tracker.service | |
#################################### |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment