Skip to content

Instantly share code, notes, and snippets.

@mkyral
Created January 25, 2018 20:48
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mkyral/ba1b0eee1e76778c7a27b9650e9375e6 to your computer and use it in GitHub Desktop.
Save mkyral/ba1b0eee1e76778c7a27b9650e9375e6 to your computer and use it in GitHub Desktop.
BigClown - mqtt microservice - convert voltage to percentage
import paho.mqtt.client as mqtt
# Configuration
################
## Server
mqtt_server = "turris"
mqtt_port = 1883
# Core module minimal voltage
module_critical_voltage = 2.0
# List of nodes
nodes = { "836d1982196f": { "cells": 2,
"cell_voltage": 1.6
},
"836d19820e43": { "cells": 4,
"cell_voltage": 1.6
},
"AAA": { "cells": 2,
"cell_voltage": 1.6
}
}
# Functions
###########
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
client.subscribe("node/+/battery/+/voltage")
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
print("Topic: "+msg.topic+", payload: "+str(msg.payload))
if str(msg.payload) == "b''":
print("Null message!")
return
node_id = msg.topic.split("/")[1]
node_type = msg.topic.split("/")[3]
if nodes.get(node_id) == None:
print("Unknown node: {0}".format(node_id))
return
topic_pct = "node/{0}/battery/{1}/percentage".format(node_id, node_type)
topic_level= "node/{0}/battery/{1}/level".format(node_id, node_type)
percentage = int(100 * (float(msg.payload) - module_critical_voltage) / (nodes[node_id]["cells"] * nodes[node_id]["cell_voltage"] - module_critical_voltage))
if percentage > 100 :
percentage = 100
elif percentage < 0 :
percentage = 0
client.publish(topic_pct, percentage);
if percentage > 80 :
level = "high"
elif percentage > 20 :
level = "middle"
elif percentage > 5 :
level = "low"
else :
level = "critical"
client.publish(topic_level, level);
########
# Main #
########
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect(mqtt_server, mqtt_port, 60)
# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.
client.loop_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment