def registro(): global usersLogged accessGranted = False if request.remote_addr in usersLogged: accessGranted = True else: if request.method == 'POST': user = request.form.get('user') passwd = request.form.get('passwd') description = request.form.get('description') try: uH = userHandler.USERHANDLER() accessGranted = uH.newUser(user, passwd, description, request.remote_addr) if accessGranted: fH = fileHandler.FILEHANDLER() timers[request.remote_addr] = threading.Timer( int(fH.readParam('usertimeout')), logoutUser, [request.remote_addr]) timers[request.remote_addr].start() usersLogged[request.remote_addr] = user return redirect('/') except Exception as e: print(str(e)) finally: uH.close() print(str(usersLogged)) return render_template("register.html", accessGranted=accessGranted)
def resetTimeout(ip): global usersLogged global timers fH = fileHandler.FILEHANDLER() timers[ip].cancel() #parar el timeout timers[ip] = threading.Timer(int(fH.readParam('usertimeout')), logoutUser, [ip]) #crear nuevo timeout timers[ip].start() #iniciar timeout
def nfcAddUserList(user, ip): print('addinf nfc user') global usersLogged global timers if (ip not in usersLogged): fH = fileHandler.FILEHANDLER() usersLogged[ip] = user print(usersLogged) timers[ip] = threading.Timer(int(fH.readParam('usertimeout')), logoutUser, [ip]) timers[ip].start()
def estadisticas(): global usersLogged if request.remote_addr in usersLogged: resetTimeout(request.remote_addr) fHandler = fileHandler.FILEHANDLER() numeroItemsPlot = int(fHandler.readParam('numberxaxis')) interval = float(fHandler.readParam('plotintervaltime')) dataHandler.readDataFile('lecturas.txt', interval) dataHandler.plotStatistics(numeroItemsPlot) return render_template("estadisticas.html") else: return redirect('/')
def calefaccionModoAutomatico(): global usersLogged if request.remote_addr in usersLogged: resetTimeout(request.remote_addr) try: fHandler = fileHandler.FILEHANDLER() fHandler.writeParam('Modo', 'automatico') s = socket.socket() s.connect(('127.0.0.1', 65000)) s.send(b'x00x03') s.close() except Exception as e: print(str(e)) return redirect("/menu/calefaccion", code=302) else: return redirect('/')
def sendNotification(self, msg, bot=None, telGroup=None, persona=None): server = smtplib.SMTP('smtp.gmail.com:587') server.connect("smtp.gmail.com", 587) server.ehlo() server.starttls() server.ehlo() fileH = fileHandler.FILEHANDLER() server.login(fileH.readParam('emaillogin'), fileH.readParam('emailpasswd')) server.sendmail(fileH.readParam('email'), fileH.readParam('email'), msg) server.quit() if (len(msg) < 140): self._tweepyapi.update_status(msg) if (bot is not None): if (persona is None): persona = '' bot.sendMessage(telGroup, msg + persona)
def index(): global usersLogged global timers accessGranted = False if (request.remote_addr in usersLogged): accessGranted = True if request.method == 'POST': print('***POST***') user = request.form.get('user') passwd = request.form.get('passwd') ip = request.remote_addr try: uH = userHandler.USERHANDLER() accessGranted = uH.getAccess(user, passwd, ip) except Exception as e: print(str(e)) finally: uH.close() if (accessGranted): fH = fileHandler.FILEHANDLER() timers[ip] = threading.Timer(int(fH.readParam('usertimeout')), logoutUser, [ip]) timers[ip].start() usersLogged[ip] = user templateData = { 'warningAccess': False, 'accesGranted': accessGranted, 'user': user } return render_template('index.html', **templateData) else: templateData = { 'warningAccess': True, 'accesGranted': accessGranted } return render_template('index.html', **templateData) templateData = {'warningAccess': False, 'accesGranted': accessGranted} return render_template('index.html', **templateData)
def readParameters(self): fileH = fileHandler.FILEHANDLER() self._consumer_key = fileH.readParam('twitterconsumerkey') self._consumer_secret = fileH.readParam('twitterconsumersecret') self._access_token = fileH.readParam('twitteraccesstoken') self._access_token_secret = fileH.readParam('twitteraccesstokensecret')
def robotStateChange(cond, kill, persona=None): #global variables needed global alarmSet global collected global led global noti global bot global telGroup global temp global mode global notification global killAlarm #print('Temperatura: '+str(temp)+' -- '+'modo: '+str(mode)+' --- ') cond.acquire() wEvent = open("eventos.txt", "a") #var to write events fileH = fileHandler.FILEHANDLER() if (collected == 'x00x01' or collected == 'x00x02'): fileH.writeParam('Modo', 'manual') wEvent.write( format(datetime.datetime.now()) + "\t" + str(temp) + "\tcambio a modo manual\n") elif (collected == 'x00x04'): fileH.writeParam('Modo', 'automatico') noti.sendNotification( 'Calefaccion automatica activada --- temperatura actual: ' + str(temp) + ' Celsius ' + str(datetime.datetime.now()), bot, telGroup, persona) wEvent.write( format(datetime.datetime.now()) + "\t" + str(temp) + "\tcambio a modo automatico\n") elif (collected == 'x00x05'): kill.set() if collected == 'x00x01': led.on() noti.sendNotification( 'Manual: se enciende la calefaccion --- temperatura actual: ' + str(temp) + ' Celsius ' + str(datetime.datetime.now()), bot, telGroup, persona) wEvent.write( format(datetime.datetime.now()) + "\t" + str(temp) + "\tencendido\n") elif collected == 'x00x02': led.off() noti.sendNotification( 'Manual: se apaga la calefaccion --- temperatura actual: ' + str(temp) + ' Celsius ' + str(datetime.datetime.now()), bot, telGroup, persona) wEvent.write( format(datetime.datetime.now()) + "\t" + str(temp) + "\tencendido\n") elif collected == 'x00x03': led.off() #momentaneamente noti.sendNotification( 'Cambio de modo desde el servidor --- temperatura actual: ' + str(temp) + ' Celsius ' + str(datetime.datetime.now()), bot, telGroup, persona) wEvent.write( format(datetime.datetime.now()) + "\t" + str(temp) + "\tcambio de modo desde el servidor web\n") elif collected == 'x00x06': wEvent.write(format(datetime.datetime.now()) + "\tAlarma activada\n") noti.sendNotification( 'La alarma ha sido activada. Puedes ver que esta sucediendo en: http://192.168.1.102:5000/menu/video ' + str(datetime.datetime.now()), bot, telGroup) if (alarmSet == False): alarm() elif collected == 'x00x07': wEvent.write( format(datetime.datetime.now()) + "\tAlarma desactivada\n") alarmSet = False killAlarm.set() noti.sendNotification( 'La alarma ha sido desactivada. ' + str(datetime.datetime.now()), bot, telGroup) elif collected == 'x00x08': print('*NOTIFICAR ENTRADA CON TARJETA*') print(str(persona)) #wEvent.write(format(datetime.datetime.now())+"\t"+persona+" ha entrado a casa con tarjeta NFC\n") noti.sendNotification( persona + ' ha entrado en casa con tarjeta nfc. ' + str(datetime.datetime.now()), bot, telGroup) elif collected == 'x00x09': print('*NOTIFICAR SALIDA CON TARJETA*') wEvent.write( format(datetime.datetime.now()) + "\t" + persona + " ha salido de casa con tarjeta NFC\n") noti.sendNotification( persona + ' ha salido de casa con tarjeta nfc. ' + str(datetime.datetime.now()), bot, telGroup) elif collected == 'x00x0A': print('*NOTIFICAR ENTRADA CON SMARTP*') wEvent.write( format(datetime.datetime.now()) + "\t" + persona + " ha entrado a casa con smartphone\n") noti.sendNotification( persona + ' ha entrado a casa con smartphone. ' + str(datetime.datetime.now()), bot, telGroup) elif collected == 'x00x0B': print('*NOTIFICAR SALIDA CON SMARTP*') wEvent.write( format(datetime.datetime.now()) + "\t" + persona + " ha salido de casa con smartphone\n") noti.sendNotification( persona + ' ha salido de casa con smartphone. ' + str(datetime.datetime.now()), bot, telGroup) elif collected == 'x00x0C': led.on() wEvent.write( format(datetime.datetime.now()) + "\t" + str(temp) + "\tencendido\n") noti.sendNotification( 'Auto: se enciende la calefaccion --- temperatura actual: ' + str(temp) + ' Celsius ' + str(datetime.datetime.now()), bot, telGroup) notification = True elif collected == 'x00x0D': led.off() wEvent.write( format(datetime.datetime.now()) + "\t" + str(temp) + "\tapagado\n") noti.sendNotification( 'Auto: se apaga la calefaccion --- temperatura actual: ' + str(temp) + ' Celsius ' + str(datetime.datetime.now()), bot, telGroup) notification = False wEvent.close() #reset collected data collected = None cond.release()
def main(args): global collected global cond #needed for thread sync global noti global kill global sensor global cond try: led.off() fileH = fileHandler.FILEHANDLER() #var to read from config file noti = notificationHandler.NOTIFICATIONHANDLER() #the main thread will be reading temp global temp sensor = proxy.PROXY() #creating sensor kill = threading.Event() #initializing telegram thread global telToken telToken = fileH.readParam('telegramtoken') global telGroup telGroup = fileH.readParam('telegramidgrupo') global bot bot = telepot.Bot(telToken) #initializing the rest of the threads #starting the other threads cond = threading.Condition() #starting telegram thread MessageLoop(bot, lecturaMensajesBot).run_as_thread() servWeb = threading.Thread(target=servWebThread, args=(cond, kill)) serv = threading.Thread(target=serverThread, args=( cond, kill, )) #thread which communicates with web server robot = threading.Thread(target=robotThread, args=(cond, kill)) #distance = threading.Thread(target=distanceThread, args=(cond, kill)) nfc = threading.Thread(target=nfcThread, args=(cond, kill)) #voice = threading.Thread(target=voiceThread, args=(cond, kill)) #displayT = threading.Thread(target=displayThread, args=(cond, kill)) servWeb.start() serv.start() robot.start() #distance.start() nfc.start() #voice.start() #displayT.start() while (not kill.is_set()): temp = sensor.leerTem() time.sleep(1) sensor.close() print('sale bucle en el main') #finish the program servWeb.join() serv.join() robot.join() #distance.join() nfc.join() #voice.join() #displayT.join() except Exception as e: print(e)
def robotThread(cond, kill): time.sleep(1) #global variables needed for the robot to run global bot global temp global led global noti global collected global notification #var to read from config file fileH = fileHandler.FILEHANDLER() while (not kill.is_set()): #read parameters tempMin = float(fileH.readParam('tempmin')) tempMax = float(fileH.readParam('tempmax')) hume = float(fileH.readParam('hume')) #reading notification variables global telToken telToken = fileH.readParam('telegramtoken') global telGroup telGroup = fileH.readParam('telegramidgrupo') noti.readParameters() #reading time interval lec = float(fileH.readParam('intervalolectura')) #reading mode global mode mode = fileH.readParam('modo') #robot tasks if (mode == 'automatico'): #robot starts processing information bot = telepot.Bot(telToken) #var to send messages notification = False #number of notifications is limit to 1 per on/off cond.acquire() while collected == None: cond.notify() cond.release() if (tempMax > temp): if (notification == False): collected = 'x00x0C' if (tempMax < temp): if notification: collected = 'x00x0D' time.sleep(lec) cond.acquire() cond.notify() cond.release() else: #manual mode #wait for user interaction cond.acquire() while collected == None: print('voy a dormir') cond.wait() print('estoy despierto') cond.release() robotStateChange(cond, kill) #change state print('termina hilo robot')
def valores(): global usersLogged if request.remote_addr in usersLogged: resetTimeout(request.remote_addr) fHandler = fileHandler.FILEHANDLER() minTemp = None maxTemp = None try: minTemp = fHandler.readParam('tempmin') maxTemp = fHandler.readParam('tempmax') hume = fHandler.readParam('hume') email = fHandler.readParam('email') emaillogin = fHandler.readParam('emaillogin') emailpasswd = fHandler.readParam('emailpasswd') telegramtoken = fHandler.readParam('telegramtoken') telegramidgrupo = fHandler.readParam('telegramidgrupo') twitterconsumerkey = fHandler.readParam('twitterconsumerkey') twitterconsumersecret = fHandler.readParam( 'twitterconsumersecret') twitteraccesstoken = fHandler.readParam('twitteraccesstoken') twitteraccesstokensecret = fHandler.readParam( 'twitteraccesstokensecret') intervalolectura = fHandler.readParam('intervalolectura') modo = fHandler.readParam('modo') except Exception as e: print('No se ha podido leer el fichero bien') if request.method == 'POST': minTemp = request.form.get('minTemp') if (minTemp is not ''): fHandler.writeParam('TempMin', minTemp) maxTemp = request.form.get('maxTemp') if (maxTemp is not ''): fHandler.writeParam('TempMax', maxTemp) hume = request.form.get('hume') if (hume is not ''): fHandler.writeParam('hume', hume) email = request.form.get('email') if (email is not ''): fHandler.writeParam('email', email) emaillogin = request.form.get('emaillogin') if (emaillogin is not ''): fHandler.writeParam('emaillogin', emaillogin) emailpasswd = request.form.get('emailpasswd') if (emailpasswd is not ''): fHandler.writeParam('emailpasswd', emailpasswd) telegramtoken = request.form.get('telegramtoken') if (telegramtoken is not ''): fHandler.writeParam('telegramtoken', telegramtoken) telegramidgrupo = request.form.get('telegramidgrupo') if (telegramidgrupo is not ''): fHandler.writeParam('telegramidgrupo', telegramidgrupo) twitterconsumerkey = request.form.get('twitterconsumerkey') if (twitterconsumerkey is not ''): fHandler.writeParam('twitterconsumerkey', twitterconsumerkey) twitterconsumersecret = request.form.get( 'twitterconsumersecret') if (twitterconsumersecret is not ''): fHandler.writeParam('twitterconsumersecret', twitterconsumersecret) twitteraccesstoken = request.form.get('twitteraccesstoken') if (twitteraccesstoken is not ''): fHandler.writeParam('twitteraccesstoken', twitteraccesstoken) twitteraccesstokensecret = request.form.get( 'twitteraccesstokensecret') if (twitteraccesstokensecret is not ''): fHandler.writeParam('twitteraccesstokensecret', twitteraccesstokensecret) intervalolectura = request.form.get('intervalolectura') if (intervalolectura is not ''): fHandler.writeParam('intervalolectura', intervalolectura) modo = request.form.get('modo') if (modo is not ''): fHandler.writeParam('modo', modo) #tell the robot to read again the params from file try: s = socket.socket() s.connect(('127.0.0.1', 65000)) s.send(b'x00x03') s.close() except Exception as e: raise e #print('tempMax: '+ str(maxTemp)) #print('tempMin: '+ str(minTemp)) tempData = { 'minTemp': minTemp, 'maxTemp': maxTemp, 'hume': hume, 'email': email, 'emaillogin': emaillogin, 'emailpasswd': emailpasswd, 'telegramtoken': telegramtoken, 'telegramidgrupo': telegramidgrupo, 'twitterconsumerkey': twitterconsumerkey, 'twitterconsumersecret': twitterconsumersecret, 'twitteraccesstoken': twitteraccesstoken, 'twitteraccesstokensecret': twitteraccesstokensecret, 'intervalolectura': intervalolectura, 'modo': modo } return render_template("cambioValores.html", **tempData) else: return redirect('/')