CurrentCost Script

Until now I used DomotiGa to get the date off my CurrentCost EnviR energy sensor.

Since I’ve moved all my automations to Home-Assistant, the only bit that was not supported by HA was the CurrentCost device. I didn’t want to run DomotiGa just to get the data off the EnviR and then send it to HA via MQTT.

I’ve finally finished a script thanks to Robin Wilson that gets the EnviR data from the serial port and sends it to HA. DomotiGa can now truly rest in peace.

The final script is this one:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import untangle
import serial
import json, requests, simplejson

def get_data(port='/dev/ttyUSB1', verbose=False):
	"""port: the port that the CurrentCost meter is attached to. Something like /dev/ttyUSB0 or COM1
	Returns:
	(sensor, temperature, usage), with sensor as the number of the interface a device is assigned to, temperature in degrees C, and usage in Watts
	"""
	ser = serial.Serial(port, 57600)
	xmldata = ser.readline()
	if verbose:
		print(xmldata)
	ser.close()
	p = untangle.parse(xmldata)
	temperature = float(p.msg.tmpr.cdata)
	watts = int(p.msg.ch1.watts.cdata)
	sensor = int(p.msg.sensor.cdata)
	return [sensor, watts, temperature]

def HA_API_State(Device_Id, Value, Unit):
	#https://home-assistant.io/developers/rest_api/#post-apistatesltentity_id
	url = "http://192.168.0.24:8123/api/states/" + str(Device_Id) + "?api_password=SECRET" 
	data={"state":"" + str(Value) + "", "attributes": {"unit_of_measurement": "" + str(Unit) + ""}}
	headers = {'Content-type':'application/json', 'Accept-Encoding': 'text/plain', 'Accept': 'text/plain'}
	r = requests.post(url, data=json.dumps(data), headers=headers)
	c = r.content
	result = simplejson.loads(c)

Temperature = 0
Sky = 0
Dehumidifier = 0
Total = 0

while(True):
	try:
		Temp = get_data()
		#print Temp[0]
		if (Temperature <> Temp[2]):
			print "Temperature: %s" % Temp[2]
			Temperature = Temp[2]
			HASS_API_State("sensor.CurrentCost_Temperature", Temperature, "°C")
		if (Temp[0] == 1):
			if (Total <> Temp[1]):
				print "Total: %s" % Temp[1]
				Total = Temp[1]
				HASS_API_State("sensor.CurrentCost_Power", Total, "Wh")
		if (Temp[0] == 2):
			if (Dehumidifier <> Temp[1]):
				print "Dehumidifier: %s" % Temp[1]
				Dehumidifier = Temp[1]
				HASS_API_State("sensor.Dehumidifier_Power", Dehumidifier, "Wh")
		if [Temp[0] == "9"]:
			if (Sky <> Temp[1]):
				print "Sky: %s" % Temp[1]
				Sky = Temp[1]
				HASS_API_State("sensor.CurrentCost_Sky", Sky, "Wh")
			
	except:
		pass