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 *
import paho.mqtt.client as mqtt

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

# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))

    # Subscribing in on_connect() means that if we lose the connection and
    # reconnect then subscriptions will be renewed.
    client.subscribe("/Manchon/Value")

# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
    print(msg.topic+" "+str(msg.payload))

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)
	]
	
	state=EventProperty('Listening')
	turnedon=EventProperty('IsTurnedOn')
	
	def listen_to_touch_sensor(self, s):
		print "Listening for touch sensor things"
		client = mqtt.Client()
		client.connect("iot.eclipse.org", 1883, 60)
		client.loop_start()
		while True:
			try:
				x = analogRead(sensor) < 200
				if x:
					self.turnedon = not self.turnedon
					client.publish("/manchon/sensors/touch",str(self.turnedon),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
		}