
I have watering system managed by domoticz, I'd like to add watermeter. As a hardware I have popular flow sensor from Aliexpress, powered by 3.3V, output is connected to GPIO4 (physical pin 7 on GPIO). Flowmeter is working I checked by oscilloscope, that on this pin there is a sq vawe, freq proportional to flow, so hw works perfectly.
Next I adapted a description found here on this forum:
viewtopic.php?f=36&t=10272
My adaptation: I deleted Gas section and changed ELEC into WATER, added a WATER.GPIO=4 and WATER.IDX=5 (according to idx of my dummy water counter in domoticz):
Code: Select all
#!/usr/bin/env python
import time
import json
import urllib2
import threading
import logging
import logging.handlers
import os
from gpiozero import DigitalInputDevice
GET_URL = 'http://127.0.0.1:8080/json.htm?type=devices&rid=%d'
SET_URL = 'http://127.0.0.1:8080/json.htm?type=command¶m=udevice&idx=%d&svalue=%d'
WATER_DELTA = 0
WATER_IDX = 5
WATER_GPIO = 4
WATER_COUNTER_LOCK = threading.Lock()
WATER_LAST_TIME = 0
WATER_POST_TIME = 0
def water_intr():
tme = time.time()
global WATER_DELTA
global WATER_LAST_TIME
global WATER_POST_TIME
with WATER_COUNTER_LOCK:
WATER_LAST_TIME = tme
if WATER_POST_TIME == 0:
WATER_POST_TIME = WATER_LAST_TIME
else:
WATER_DELTA += 1
logging.debug( 'Water counter tick: %d' % WATER_DELTA )
def main():
global WATER_DELTA
global WATER_LAST_TIME
global WATER_POST_TIME
global WATER_COUNTER
syslog = logging.handlers.SysLogHandler(address='/dev/log', facility='local1')
syslog.setFormatter(logging.Formatter('local_sensors.py: %(levelname)s %(message)s'))
logging.getLogger().addHandler(syslog)
logging.getLogger().setLevel(logging.INFO)
while True:
try:
res = json.load(urllib2.urlopen(GET_URL % WATER_IDX))
if res['status'] != 'OK':
raise Exception('Domoticz json error')
break
except Exception as e:
logging.warning( e )
time.sleep(30.0)
WATER_COUNTER = int(float(res['result'][0]['Data'][:-4]) * 1000)
# WATER_COUNTER = <Your initial count here * 1000, don't forget to remove after Domoticz updated!>
logging.info( 'Current water counter is: %d' % WATER_COUNTER )
waterSensor = DigitalInputDevice(WATER_GPIO, pull_up=True)
waterSensor.when_deactivated = water_intr
os.nice(-20)
logging.info('Polling loop starting')
while True:
time.sleep(60)
with WATER_COUNTER_LOCK:
if WATER_LAST_TIME > WATER_POST_TIME:
WATER_LOAD = WATER_DELTA * 3600 / ( WATER_LAST_TIME - WATER_POST_TIME )
else:
WATER_LOAD = 0
WATER_COUNTER += WATER_DELTA
WATER_DELTA = 0
WATER_POST_TIME = WATER_LAST_TIME
if WATER_LOAD != 0:
try:
res = json.load(urllib2.urlopen((SET_URL+';%d') % (WATER_IDX, int(WATER_LOAD), WATER_COUNTER)))
if res['status'] != 'OK':
raise Exception('Domoticz json error')
logging.info('Water load %.2f counter %d' % (WATER_LOAD, WATER_COUNTER) )
except Exception as e:
logging.warning( e )
if __name__=="__main__":
main()
So, where I'm wrong, or what should I do else? My domoticz is a new installation, maybe there should be something installed else?