import logging
from threading import Thread
import time
import threading
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 grove_rgb_lcd import *

import os
import glob
import time

os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')

base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'

def read_temp_raw():
    f = open(device_file, 'r')
    lines = f.readlines()
    f.close()
    return lines

def read_temp():
    lines = read_temp_raw()
    while lines[0].strip()[-3:] != 'YES':
        time.sleep(0.2)
        lines = read_temp_raw()
    equals_pos = lines[1].find('t=')
    if equals_pos != -1:
        temp_string = lines[1][equals_pos+2:]
        temp_c = float(temp_string) / 1000.0
        temp_f = temp_c * 9.0 / 5.0 + 32.0
        return temp_c#, temp_f

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

	actions = {
		'GetTemp': [
			ServiceActionArgument('Temp','out','Temp')
		]
	}
	
	stateVariables = [
		# Variables
		ServiceStateVariable('Temp','string',sendEvents=True)	,	
		ServiceStateVariable('ListeningTemp','boolean',sendEvents=True)

	]
		
	state=EventProperty('ListeningTemp')
	temp=EventProperty('Temp')

	@register_action('GetTemp')
	def getState(self):
		return {
			'Temp' : str(read_temp())
		}
		
	def listen_to_temp_sensor(self, s):
		print "Listening for temp sensor values"
		while True:
			try:
				self.temp = read_temp()
				time.sleep(3)
			except IOError as e:
				print "I/O error({0}): {1}".format(e.errno, e.strerror)
				time.sleep(0.5)
		return
		
		
	def startListening(self):
		self.state=True
		
		self.thread = threading.Thread(target=TemperatureService.listen_to_temp_sensor, args = (self,0))
		self.thread.daemon = True
		self.thread.start();
		return {
			'ListeningTemp':True
		}