#!/usr/bin/python

# Banco di Test per SP-AIR

from acmepins import GPIO
from time import sleep

import serial
import time
import sys
import getopt
import string 
import datetime
import select
import termios
import tty
import os.path

modem_power  = GPIO('PB10','LOW') 
wifi_power  = GPIO('PA24','LOW') 
rear_pushbutton = GPIO('PB3','INPUT') 

def menu():
	print ""
	print "--------------------------"
	print " SP-AIR Test"
	print "--------------------------"
	print "w) WiFi ON"
	print "W) WiFi OFF"
	print "--------------------------"
	print "m) Modem ON"
	print "M) Modem OFF"
	print "o) Open serial port to the Modem"
	print "O) Close serial port to the Modem"
	print "a) Send ATH"
	print "--------------------------"
	print "p) ping www.acmesystems.it"
	print "--------------------------"
	print "h) Help"
	print "q or ESC) Exit"

def isData():
	return select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], [])

color_warning = "\x1B[30;41m" 
color_pass = "\x1B[30;42m" 
color_normal = "\x1B[0m" 

old_settings = termios.tcgetattr(sys.stdin)

menu()

token=""
modem_serial=0
line = ""

try:
	tty.setcbreak(sys.stdin.fileno())

	while 1:

		#Lettura righe da Modem
		if modem_serial:
			for c in modem_serial.read():
				line+=c
				if c == '\n':
					sys.stdout.write(line)
					sys.stdout.flush()
					line=""
					break

		#Test pulsante posteriore
		if rear_pushbutton.get_value()==0:
			print "Tasto premuto"
			time.sleep(0.5)

		#Lettura comandi da tastiera
		if isData():
			c = sys.stdin.read(1)
				
			if c == "m":
				print "Modem ON"
				modem_power.on()
				continue

			if c == "M":
				print "Modem OFF"
				modem_power.off()
				continue

			if c == "w":
				print "WiFi ON"
				wifi_power.on()
				continue

			if c == "W":
				print "WiFi OFF"
				wifi_power.off()
				continue
				
			if c=="o":	
				print " Open modem serial port"
				if os.path.exists("/dev/ttyUSB0"):
					print " Opened"
			
					print "Open the /dev/ttyUSB0 serial port"
					modem_serial = serial.Serial(
						port="/dev/ttyUSB0", 
						baudrate=115200, 
						timeout=1,
						parity=serial.PARITY_NONE,
						stopbits=serial.STOPBITS_ONE,
						bytesize=serial.EIGHTBITS)
				else:
					print "Fail"

				continue	

			if c=="a":	
				print "Send ATH\r"
				if modem_serial:
					modem_serial.write("ATH\r")
					continue	

			if c=="O":	
				print "CLOSE modem serial port"
				modem_serial.close()
				modem_serial=0
				continue	

			if c == '\x1b' or c=='q':
				print "Exit"
				termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)
				quit()
  
			if c == "p":
				ser.write("ping -c 4 www.acmesystems.it\r");
				continue

			if c == "h":
				menu()

finally:
	termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)