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
from grovepi import *

led = 4
sensor = 14
sensor2 = 15
pinMode(sensor,"INPUT")
pinMode(sensor2,"INPUT")


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

	actions = {
		'SetUselessLEDState': [
			ServiceActionArgument('Disco','in','Disco'),
			
			ServiceActionArgument('IsThePartyOn', 'out', 'PartyOn')
		],
		'StartListening': [
			ServiceActionArgument('Listening', 'out', 'Listening')
		]
	}
	
	stateVariables = [        
		# Variables
		ServiceStateVariable('Disco','boolean',sendEvents=False),
		ServiceStateVariable('PartyOn','boolean',sendEvents=True),
		ServiceStateVariable('Listening','boolean',sendEvents=True),
		ServiceStateVariable('IsTurnedOn', 'boolean', sendEvents=True),
		ServiceStateVariable('TouchValue','string', sendEvents=True)
	]
	
	state=EventProperty('Listening')
	turnedon=EventProperty('IsTurnedOn')
	touchvalue=EventProperty('TouchValue')
	
	def listen_to_touch_sensor(self, s):
		print "Listening for touch sensor things"
		while True:
			try:
				x = analogRead(sensor) < 200
				y = analogRead(sensor2) < 200
				if (x and not y):
					self.turnedon = not self.turnedon
					self.touchvalue = "1"
				elif (x and y):
					self.touchvalue = "3"
				elif(not x and y):
					self.touchvalue = "2"
				else:
					self.touchvalue = "0"
				
				time.sleep(1)
			except IOError as e:
				print "I/O error({0}): {1}".format(e.errno, e.strerror)
				time.sleep(0.5)
		return
	
	@register_action('SetUselessLEDState')
	def beUseless(self, param):
		digitalWrite(led, 0 if param == "0" else 1)
		return {
            'IsThePartyOn': param
        }

	@register_action('StartListening')
	def startListening(self):
		self.state=True
		
		self.thread = threading.Thread(target=TouchService.listen_to_touch_sensor, args = (self,0))
		self.thread.daemon = True
		self.thread.start();
		return {
			'Listening':True
		}
