zondag 11 juni 2017

Domoticz KWh usage input with DDS238-2 SW (Pulse Input)



Hi Everyone,


Today i set up my new breaker board and i installed a DDS238-2 SW KWH meter on it do report my power usage to Domoticz.


This meter has a pulse counter (so no serial port) to send pulses to your controller (In my case a Raspberry Pi 3). So i use 3,3V GPIO input to pin 3 on the KWh meter and pin 4 to the inputpin of the Pi. My version has 1600 pulses per KWh, but i noticed there are versions with different pulse rates. If that is the case, just replace the formula below (replace the 1.6 value with for example 3.2 if you have a 3200 pulse/KWh version)


I will share the steps below in case you want to implement this the same way i did.


1. First create a virtual sensor in domoticz


2. Then create the deamon wich collects the data.

I use a very simple bash script to achieve this:

Replace the X's with your controllers IP and the Y's with the Domoticz Virtual sensor ID


# vi readpulse.sh

-----------------------------
#!/bin/bash
timer=`date +%s`
i="0"
n=0
while [ $i -lt 4 ]
do
kwhpulse=$(gpio read 0)
if [ $kwhpulse -eq 1 ]
then
   n=$((n+1))
   #echo $n
        while [ $kwhpulse -eq 1 ]
                do
                kwhpulse =$(gpio read 0)
                sleep 0.02
                done
fi
sleep 0.03
time_now=`date +%s`
time_elapsed=$((time_now - timer))
if [ $time_elapsed -ge 300 ]
then
   power=$(echo "scale=1;$n/1.6" | bc)
   #echo "KWH laatste 5 minuten" $power "KW"
   timer=`date +%s`
   n=0
   curl -s --connect-timeout 2 --max-time 5 "http://xxx.xxx.xxx.xxx/json.htm?type=command&param=udevice&idx=YY&nvalue=0&svalue=$power"
fi

done
---------------------------

Make it executable and give proper rights;
chmod +x readpulse.sh
chmod 755 readpulse.sh


3. Make it into a service. (the initgpio service is allso a custom service, so please change this to reflect your situation(after you exported the GPIO's)

# vi /etc/systemd/system/kwhpulse.service
[Unit]
After=initgpio.service

[Service]
ExecStart=/home/jef/readpulse.sh

[Install]
WantedBy=default.target

4. reload systemctl and enable service
systemctl daemon-reload
systemctl enable kwhpulse.service

systemctl start kwhpulse.service

This script has a pretty high CPU usage since it has to poll the input every 30 milliseconds. It uses between 6 and 9% CPU. While this is not a problem for my envirement, it can be good to know in advance.


That should be all. You should start to see the data coming into Domoticz now. (i had a NTP desync wich i solved while making this, so hence the datagap in the graph, but then atleast i can show something :))