# SENSOR:<integer>
# DEBUG:<string>
# FORECAST:<integer>
# 
# SENSOR:0
# SENSOR:1
# DEBUG:anything ending in a newline...

from BeautifulSoup import BeautifulSoup
import urllib2, serial, time, sys
from serial.serialutil import SerialException

port = '/dev/tty.usbmodem411'
ser = serial.Serial(port, 9600)

SEPARATOR = '\t'
DEBUG = 0
SENSOR = 1
FORECAST = 2

rainylist=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,35,37,38,39,40,41
,42,43,45,46,47]

def check(c,l):
        if c in l:
                #it will rain tomorrow
                return 0
        else:
                #it will not rain tomorrow
                return 1

def process_sensor(message):
	print "Got sensor message: ", repr(message)
	if message[0] == "1":
		pg=urllib2.urlopen('http://weather.yahooapis.com/forecastrss?w=2380633').read()
		soup = BeautifulSoup(pg)
	
		tag=soup.findAll('yweather:forecast')

		forecast=tag[1]['text']
		code=tag[1]['code']
		newcode = int(code)

		rainOrShine = check(newcode,rainylist)
		rainOrShine = str(rainOrShine)
		
		# send message back to arduino
		# must send message as a string for some reason
		#send_message(FORECAST, "0")
		print "forecast: ", forecast
		print "rain (0) or shine (1)?", rainOrShine
		send_message(FORECAST, rainOrShine)
		#written = ser.write(rainOrShine)
	elif message[0]=="2":
		pass
	else:
		print "invalid"

def process_debug(message):
	print "DEBUG", repr(message)

def read_message(indata):
	#try:
	type, message = indata.split(SEPARATOR,1)
	#except ValueError:
		#print "Invalid message: ", indata
		#return
	
	if type == str(SENSOR):
		process_sensor(message)
	elif type == str(DEBUG):
		process_debug(message)

def send_message(type, message):
	type, message = str(type).encode('ascii'), str(message).encode('ascii')
	outdata = SEPARATOR.join((type, message)) + '\n'
	print 'send_message:', repr(outdata)
	ser.write(outdata)
	print 'sent'

# always waiting for inbyte
try:
	indata = ''
	inbyte = ''
	while True:
		while ser.inWaiting() > 0:
			try:
				inbyte = ser.read()
			except SerialException:
				continue
			# except OSError as e:
			# 	if e.errno == 35:
			# 		continue
			# 	else:
			# 		raise
			if inbyte == '\n':
				read_message(indata)
				indata = inbyte = ''
				continue
			indata += inbyte
		else:
			continue
		time.sleep(1)
except KeyboardInterrupt:
	print 'Existing gracefully'
	sys.exit(0)