#!/usr/bin/env python

import logging
import threading
import time
from twisted.internet import reactor
from pyupnp.event import EventProperty
from pyupnp.device import Device, DeviceIcon
from pyupnp.logr import Logr
from pyupnp.services import register_action, Service, ServiceActionArgument, ServiceStateVariable
from pyupnp.ssdp import SSDP
from pyupnp.upnp import UPnP

import time
import pigpio

FAN_GPIO=17
calibrationFactor = 7.5
pi = pigpio.pi() # Connect to local Pi.
callback = pi.callback(FAN_GPIO) # Create default tally callback.
start = time.time()

class WaterFlowService(Service):
	version = (1, 0)
	serviceType = "urn:schemas-upnp-org:service:WaterFlowService:1"
	serviceId = "urn:upnp-org:serviceId:WaterFlowService"
	flowRate = 0	

	actions = {
		'GetFlowRate': [
			ServiceActionArgument('FlowRate','out','FlowRateState')
		],
		'StartListeningFlow': [
			ServiceActionArgument('ListeningFlow', 'out', 'ListeningFlow')
		]
	}
	
	stateVariables = [
		# Variables
		ServiceStateVariable('FlowRateState','string',sendEvents=True),
		ServiceStateVariable('ListeningFlow','boolean',sendEvents=True)
	]
	
	state=EventProperty('ListeningFlow')
	flow=EventProperty('FlowRateState')

	@register_action('GetFlowRate')
	def getFlowRate(self):
		return {
			'FlowRate': flowRate
		}

	
	def WaterFlowThread(self,s):
		last_count = callback.tally()
		while True:
			try:
				count = callback.tally()
				#Divide the flow rate which is in pulses/minute and multiply it
				#by the pulse frequency to convert in liters. Result = Liters/min
				flowRate = ((count-last_count)*calibrationFactor)/60
				self.flow = flowRate
				last_count = count
				time.sleep(1.0)
			except KeyboardInterrupt:
				break
		return
		
	
	@register_action('StartListeningFlow')
	def startListening(self):
		self.state=True
		
		self.thread = threading.Thread(target=WaterFlowService.WaterFlowThread, args = (self,0))
		self.thread.daemon = True
		self.thread.start();
		return {
			'ListeningFlow':True
		}
		
