I have a Voltcraft co-20 connected to another machine (Raspberry Pi) that I want to read into HA sensor. Managed to get it connected and I thought to share.
On the remote machine with the Voltcraft connected:
- install usb-sensor-linux → GitHub - tuxedo0801/usb-sensors-linux: Automatically exported from code.google.com/p/usb-sensors-linux
- copy the executable to /usr/bin
Create the following script and save as aqi2mqtt.py after changing line 3 to connect to your own MQTT server:
import sys, os, time, json
import paho.mqtt.client as paho
broker="mqtt.server"
#define callback
def on_message(client, userdata, message):
time.sleep(1)
print("received message =",str(message.payload.decode("utf-8")))
######
stream = os.popen('airsensor -o')
output = stream.read()
start = output.index("VOC:") + 5
einde = output.index(",", start)
score = output[start:einde]
result = output[einde+10:].strip()
print(result)
data_set = {"timestamp": output[:start - 7], "airquality": score}
json_string = json.dumps(data_set)
if result == "OK":
client= paho.Client("client-001") #create client object client1.on_publish = on_publish #assign function to callback client1.connect(broker,por$
######Bind function to callback
client.on_message=on_message
#####
print("connecting to broker ",broker)
client.connect(broker)#connect
client.loop_start() #start loop to process received messages
print("subscribing ")
client.subscribe("home/out/voltcraft")#subscribe
time.sleep(2)
print("publishing ")
client.publish("home/out/voltcraft",json_string)#publish
time.sleep(4)
client.disconnect() #disconnect
client.loop_stop() #stop loop
else:
print(result)
add the following line to your crontab:
*/15 * * * * python3 /home/pi/airsensor/aqi2mqtt.py >/dev/null 2>&1
on your HA add the following to your configuration.yaml:
- platform: mqtt
unique_id: sensor.air_quality
state_topic: "home/out/voltcraft"
unit_of_measurement: "ppm"
name: "air_quality"
icon: "mdi:hvac"
value_template: "{{value_json.airquality}}"
Good luck & remember your mileage may vary!