import sys import time import datetime import smtplib from email.mime.text import MIMEText from android import Android from http.server import BaseHTTPRequestHandler, HTTPServer import urllib.request # SMTP parameters smtp_server = "smtp.gmail.com" smtp_port = 587 smtp_username = "" smtp_password = "" # WEB SERVER parameters hostName = "0.0.0.0" hostPort = 9000 class MyServer(BaseHTTPRequestHandler): def do_POST(self): global droid global myServer length = int(self.headers['Content-Length']) raw_post_data = self.rfile.read(length).decode('utf-8') post_data = urllib.parse.parse_qs(raw_post_data, keep_blank_values=True) get_url = self.path print("POST:" + get_url) if get_url == "/send_multiple_sms.htm": data = str(post_data['messages'][0]).splitlines() ShowProgressDialog("Invio...", "sms multipli", len(data)) count = 0 for m in data: print("L=" + m) count += 1 SetProgressDialog(count) pos = m.find(",") if pos == -1: continue else: phone = m[0:pos] message = m[pos+1:] print(str(phone) + "=" + message) SendSms(phone, message) time.sleep(2) CloseDialog() self.send_redirect_header("/") return if get_url == "/send_sms.htm": SendSms(str(post_data['phone'][0]), str(post_data['message'][0])) self.send_redirect_header("/") return if get_url == "/send_email.htm": SendMail(str(post_data['email_from'][0]), str(post_data['email_to'][0]), str(post_data['email_subject'][0]), str(post_data['email_body'][0])) self.send_redirect_header("/") return if get_url == "/send_tts.htm": TextToSpeech(str(post_data['message'][0])) self.send_redirect_header("/") return if get_url == "/get_gps_location.htm": lat,lon,addr = GetGpsLocation(3) self.send_html_headers() self.send("""
Latitudine%s
Longitudine%s
Indirizzo%s


Torna indietro """ % (lat,lon,addr)) return if get_url == "/view_gps_location.htm": lat,lon,addr = GetGpsLocation(3) self.send_html_headers() self.send("""


Torna indietro """) return if get_url == "/close_server.htm": self.send_html_headers() self.send("Server closed") myServer.server_close() return def do_GET(self): global droid global myServer # referer = self.headers.get('Referer') get_url = self.path print("GET:" + get_url) if get_url.find("?") >= 0: get_data = urllib.parse.parse_qs(get_url[get_url.find("?")+1:]) get_url = get_url[:get_url.find("?")] print("data: " + str(get_data)) if get_url == "/" or get_url == "/index.htm": self.send_html_headers() self.send("""
Invia SMS
Telefono
Messaggio
 
Invia SMS multipli (numero,testo)
Messaggi
Invia Email
Mittente
Destinatario
Oggetto
Messaggio


Text To Speech
Messaggio


   
GPS



Esci""") return elif get_url == "/speak.htm": global droid message = str(get_data['text'][0]) print("tts:" + message) droid.ttsSpeak(message) # TextToSpeech(str(get_data['text'][0])) return elif get_url == "/close_server.htm": self.send_html_headers() self.send("Server closed") myServer.server_close() return def send_html_headers(self): self.send_response(200) self.send_header("Content-type", "text/html;charset=UTF-8") self.end_headers() def send_redirect_header(self, newpage): self.send_response(301) if not newpage.startswith("http") and not newpage.startswith("about"): newpage = "http://" + self.headers.get('Host') + newpage self.send_header("Location", newpage) self.end_headers() def send(self, message): self.wfile.write(bytes(message, "utf-8")) # SUPPORT functions def ShowQuestionYesNo(title, message): #create dialog droid.dialogCreateAlert(title, message) droid.dialogSetPositiveButtonText('Si') droid.dialogSetNegativeButtonText('No') droid.dialogShow() #get response response = droid.dialogGetResponse().result droid.dialogDismiss() #convert response to False / True if not 'which' in response or response['which'] != 'positive': return False else: return True def ShowProgressDialog(title, message, num_steps): droid.dialogCreateHorizontalProgress(title, message, num_steps) droid.dialogShow() def SetProgressDialog(current_step): droid.dialogSetCurrentProgress(current_step) def CloseDialog(): droid.dialogDismiss() def GetInput(title, message, def_value=''): res = droid.dialogGetInput(title, message, def_value).result return res def GetMaskInput(title, message): res = droid.dialogGetPassword(title, message).result return res def GetGpsLocation(timeout): droid.startLocating() time.sleep(timeout) loc = droid.readLocation().result if loc == {}: loc = droid.getLastKnownLocation().result if loc != {}: try: n = loc['gps'] except KeyError: n = loc['network'] if n is None: la = 0.0 lo = 0.0 addr = {} else: la = n['latitude'] lo = n['longitude'] # addr = droid.geocode(la, lo).result # use Google Maps with urllib.request.urlopen("http://nominatim.openstreetmap.org/reverse?format=xml&lat=" + str(la) + "&lon=" + str(lo) + "&zoom=18&addressdetails=0") as webdata: addr = webdata.read().decode() droid.stopLocating() return la,lo,addr def TextToSpeech(message): droid.ttsSpeak(message) def SpeechToText(): message = droid.recognizeSpeech() return message def SendMail(sender, to, subject, body): conn = smtplib.SMTP(smtp_server,smtp_port) conn.starttls() conn.ehlo() conn.login(smtp_username, smtp_password) msg = MIMEText(body) msg['Subject'] = subject msg['From'] = sender msg['To'] = to conn.send_message(msg) conn.quit() def SendSms(phone_number, message): droid.smsSend(phone_number, message) #start the program droid = Android() #how to use TextToSpeech # s = GetInput("TTS", "dimmi cosa dire") # droid.ttsSpeak(s) #how to detect SmartPhone position #lat,lon,addr = GetGpsLocation(5) #print(lat,lon,addr) #start web server myServer = HTTPServer((hostName, hostPort), MyServer) print(time.asctime(), "Server Starts - %s:%s" % (hostName, hostPort)) #process browser requests try: myServer.serve_forever() except Exception as err: print ('client exit request, shutting down the web server') #stop web server try: myServer.server_close() print(time.asctime(), "Server Stops - %s:%s" % (hostName, hostPort)) except: pass