Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import sys
- import bluetooth
- import time
- import os.path
- import datetime
- import json
- import simplejson
- import os
- import random
- import numpy
- import threading
- import pandas as pd
- from pandas import ExcelWriter
- from pandas import ExcelFile
- service_matches = None
- port = None
- name = None
- host = None
- sock = None
- dataExcel = None
- dataExcelLength = 0
- leerExcelCounter = 0
- actualDate = 0
- totalTiempoSec = 0
- promedioExito = 0
- mayorTiempo = 0
- menorTiempo = 1
- promedioTiempo = 0
- totalEnviados = 0
- totalRegistrados = 0
- totalErrores = 0
- lecturaDate = 0
- tiempoEnvio = 0
- tiempoInicio = ""
- tiempoFinal = ""
- #------------------------------------------ EXCEL ---------------------------------------------------
- def crearExcel():
- df = pd.DataFrame({'% de exito':[0],
- 'Mayor tiempo de registro (seg.)':[0],
- 'Menor tiempo de registro (seg.)':[1],
- 'Promedio tiempo de envio (seg.)':[0],
- 'Total de datos enviados':[0],
- 'Total errores':[0],
- 'Total de datos registrados':[0]})
- writer = ExcelWriter('/home/pi/Desktop/promedio_datos.xlsx')
- df.to_excel(writer, 'Promedios',index=False)
- writer.save()
- def leerExcel():
- global dataExcel
- dataExcel = pd.read_excel (r'/home/pi/Desktop/datos_raspy_to_database.xlsx') #for an earlier version of Excel, you may need to use the file extension of 'xls'
- global dataExcelLength
- dataExcelLength = len(dataExcel)
- def obtenerColumna(index):
- columna = dataExcel.iloc[index]
- return columna
- def leerColumnaCrearArray(columna):
- arrayColumna = []
- corriente = columna.values[0]
- voltaje = columna.values[1]
- estimacionSoc = columna.values[4]
- confIntervalSoc1 = columna.values[5]
- confIntervalSoc2 = columna.values[6]
- estimacionRin = columna.values[7]
- confIntervalRin1 = columna.values[8]
- confIntervalRin2 = columna.values[9]
- estimacionSompa = columna.values[10]
- confIntervalSompa1 = columna.values[11]
- confIntervalSompa2 = columna.values[12]
- arrayColumna = [[corriente, voltaje, estimacionSoc, confIntervalSoc1, confIntervalSoc2, estimacionRin, confIntervalRin1, confIntervalRin2, estimacionSompa, confIntervalSompa1, confIntervalSompa2]]
- return arrayColumna
- def registerDataStatus(status, array, dateAntesEnviar, dateDespuesEnviar, _tiempoEnvio):
- global promedioExito
- global mayorTiempo
- global menorTiempo
- global promedioTiempo
- global totalEnviados
- global totalRegistrados
- global totalErrores
- global tiempoInicio
- global tiempoFinal
- global tiempoEnvio
- global tiempoApp
- tiempoEnvio = _tiempoEnvio
- #data = pd.read_excel (r'/home/pi/Desktop/promedio_datos.xlsx') #for an earlier version of Excel, you may need to use the file extension of 'xls'
- totalRegistrados = totalRegistrados + 1
- print("reg: "+str(totalRegistrados))
- tiempoInicio = dateAntesEnviar
- if status is 1: #
- tiempoFinal = dateDespuesEnviar
- if tiempoEnvio > mayorTiempo:
- mayorTiempo = tiempoEnvio
- if tiempoEnvio < menorTiempo:
- menorTiempo = tiempoEnvio
- global totalTiempoSec
- totalEnviados = totalEnviados + 1
- totalTiempoSec = totalTiempoSec + tiempoEnvio
- promedioTiempo = totalTiempoSec / totalEnviados
- promedioExito = (totalEnviados / totalRegistrados) * 100
- print("OK SAVED")
- if status is 0: #
- totalErrores = totalErrores + 1
- tiempoFinal = "-"
- promedioExito = "-"
- promedioTiempo = "-"
- tiempoEnvio = "-"
- print("ERROR SAVED")
- #registrosIndividuales(array, tiempoEnvio)
- def registrosIndividuales(array, tiempoEnvio):
- data = None
- for js in array:
- with open('registros.json', 'r') as file_read:
- data = json.load(file_read)
- data.append(js + " : " + str(tiempoEnvio) + " segundos")
- #print("***escribirEnArchivo***: " + str(data))
- #print("***************************************")
- with open('registros.json', 'w') as file:
- json.dump(data, file)
- #---------------------------------------- FIN EXCEL -------------------------------------------------
- def sendDataToApp2(array, dispositivo):
- #print(">>> sendDataToApp()")
- jsonArray0 = createJson(array)
- jsonArray = leerArchivo(jsonArray0)
- #print("Json Concatenado: "+str(jsonArray))
- print("Objeetos enviados: "+str(len(jsonArray)))
- return sendDataBluetooth(jsonArray, dispositivo)
- def findDevice():
- print(">>> findDevice()")
- uuid = "08C2B2EF-7C87-3D00-0CDC-9A2ADC420BFF"
- buscando = True
- cont = 6
- while buscando:
- global service_matches
- service_matches = bluetooth.find_service(name = "RosieProject", uuid = uuid )
- if len(service_matches) == 0:
- cont = cont-1
- print ("couldn't find the FooBar service: "+str(cont))
- if cont == 0:
- cont = -1
- buscando = False
- else:
- buscando = True
- else:
- buscando = False
- if buscando is False:
- inicializarBTConf()
- if cont == -1:
- print("False " +str(cont))
- return False
- else:
- print("True " +str(cont))
- return True
- #Retorna el dispositivo como objeto
- def findDevice2():
- print(">>> findDevice()")
- uuid = "08C2B2EF-7C87-3D00-0CDC-9A2ADC420BFF"
- buscando = True
- cont = 6
- while buscando:
- global service_matches
- service_matches = bluetooth.find_service(name = "RosieProject", uuid = uuid )
- if len(service_matches) == 0:
- cont = cont-1
- print ("couldn't find the FooBar service: "+str(cont))
- if cont == 0:
- cont = -1
- buscando = False
- else:
- buscando = True
- else:
- buscando = False
- #if buscando is False:
- #inicializarBTConf()
- if cont == -1:
- print("False " +str(cont))
- return None
- else:
- print("True " +str(cont))
- return service_matches
- def inicializarBTConf():
- global service_matches
- global port
- global name
- global host
- first_match = service_matches[0]
- port = first_match["port"]
- name = first_match["name"]
- host = first_match["host"]
- print ("connecting to \"%s\" on %s" % (name, host))
- print ("Name: " + str(name))
- print ("Port: " + str(port))
- print ("Host: " + str(host))
- def sendDataBluetooth(jsonArray, dispositivo):
- #print(">>> sendDataBluetooth()")
- #print ("connecting to \"%s\" on %s" % (name, host))
- #print ("Name: " + str(name))
- #print ("Port: " + str(port))
- #print ("Host: " + str(host))
- limpiarArchivo()
- datos = str(jsonArray)
- #actualDate = float(time.mktime(datetime.datetime.now().timetuple())) * 1000
- dateInicio = datetime.datetime.strptime(lecturaDate, '%Y-%m-%d %H:%M:%S.%f')
- try:
- print("hola")
- print("chao")
- sock.send(datos)
- #getData = sock.recv(1024)
- #sock.close()
- dateWithMill2 = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
- dateTermino = datetime.datetime.strptime(dateWithMill2, '%Y-%m-%d %H:%M:%S.%f')
- delta = dateTermino - dateInicio
- milliseconds = int(delta.total_seconds() * 1000)
- tiempoEnvio = milliseconds / 1000
- print("Final Envio: "+ dateWithMill2)
- print("tiempo envio: " + str(tiempoEnvio))
- registerDataStatus(1, jsonArray, lecturaDate, dateWithMill2, tiempoEnvio)
- return True
- #-------- EXCEL ------------
- except Exception as e:
- print("Inicio Catch envio bluetooth")
- #service_matches = None
- #-------- EXCEL ------------
- registerDataStatus(0, jsonArray, lecturaDate, 0, 0)
- escribirEnArchivo(jsonArray)
- print("Error - " + str(e) + ": catch send data bluetooth...")
- return False
- def timeout(socket, host, port):
- print("Connecting...")
- socket.connect((host, port))
- def createJson(array):
- jsonArray = []
- for x in array:
- corriente = x[0]
- voltaje = x[1]
- estimacionSoc = x[2]
- confIntervalSoc1 = x[3]
- confIntervalSoc2 = x[4]
- estimacionRin = x[5]
- confIntervalRin1 = x[6]
- confIntervalRin2 = x[7]
- estimacionSompa = x[8]
- confIntervalSompa1 = x[9]
- confIntervalSompa2 = x[10]
- time = datetime.datetime.now().strftime("%d/%m/%Y %H:%M:%S")
- jsona = {
- "FechaHoraString": time,
- "EstimacionSoc": estimacionSoc,
- "ConfIntervalSoc1": confIntervalSoc1,
- "ConfIntervalSoc2": confIntervalSoc2,
- "EstimacionSompa": estimacionSompa,
- "ConfIntervalSompa1": confIntervalSompa1,
- "ConfIntervalSompa2": confIntervalSompa2,
- "EstimacionRin": estimacionRin,
- "ConfIntervalRin1": confIntervalRin1,
- "ConfIntervalRin2": confIntervalRin2,
- "Corriente": corriente,
- "Voltaje": voltaje,
- "PromedioExito": promedioExito,
- "MayorTiempo": mayorTiempo,
- "MenorTiempo": menorTiempo,
- "PromedioTiempo": promedioTiempo,
- "TotalEnviados": totalEnviados,
- "TotalRegistrados": totalRegistrados,
- "TotalErrores": totalErrores,
- "TiempoInicio": tiempoInicio,
- "TiempoFinal": tiempoFinal,
- "TiempoEnvio": tiempoEnvio}
- jsona = str(jsona)
- jsonArray.append(jsona)
- return jsonArray
- def createJsonSinFecha(array):
- jsonArray = []
- for x in array:
- estimacionSoc = x[0]
- confIntervalSoc1 = x[1]
- confIntervalSoc2 = x[2]
- estimacionSompa = x[3]
- confIntervalSompa1 = x[4]
- confIntervalSompa2 = x[5]
- estimacionRin = x[6]
- confIntervalRin1 = x[7]
- confIntervalRin2 = x[8]
- corriente = x[9]
- voltaje = x[10]
- time = x[11]
- jsona = {
- "Fecha": time,
- "EstimacionSoc": estimacionSoc,
- "ConfIntervalSoc1": confIntervalSoc1,
- "ConfIntervalSoc2": confIntervalSoc2,
- "EstimacionSompa": estimacionSompa,
- "ConfIntervalSompa1": confIntervalSompa1,
- "ConfIntervalSompa2": confIntervalSompa2,
- "EstimacionRin": estimacionRin,
- "ConfIntervalRin1": confIntervalRin1,
- "ConfIntervalRin2": confIntervalRin2,
- "Corriente": corriente,
- "Voltaje": voltaje}
- jsona = str(jsona)
- jsonArray.append(jsona)
- return jsonArray
- def inicializarDirectorios():
- existe = os.path.isfile("test_file.json")
- if existe:
- print("test_file.json exists")
- empty = os.stat("test_file.json").st_size == 0
- #print("Is empty: " + str(empty))
- if empty:
- opfile = open("test_file.json", "a")
- opfile.write("[]")
- opfile.close()
- else:
- opfile = open("test_file.json", "a")
- opfile.write("[]")
- opfile.close()
- existe = os.path.isfile("registros.json")
- if existe:
- print("registros.json exists")
- empty = os.stat("registros.json").st_size == 0
- #print("Is empty: " + str(empty))
- if empty:
- opfile = open("registros.json", "a")
- opfile.write("[]")
- opfile.close()
- else:
- opfile = open("registros.json", "a")
- opfile.write("[]")
- opfile.close()
- def escribirEnArchivo(jsonActual):
- data = None
- for js in jsonActual:
- with open('test_file.json', 'r') as file_read:
- data = json.load(file_read)
- data.append(js)
- #print("***escribirEnArchivo***: " + str(data))
- #print("***************************************")
- with open('test_file.json', 'w') as file:
- json.dump(data, file)
- def leerArchivo(jsonActual):
- #print ("leerArchivo: " + str(jsonActual))
- file_empty = os.stat('test_file.json').st_size
- #print(file_empty)
- if file_empty == 0:
- print("test_file.json is empty")
- return jsonActual
- else:
- with open('test_file.json', 'r') as file_read:
- d = json.load(file_read)
- #d.append(jsonActual)
- #print("***LEIDO***: " + str(d))
- #print("***************************************")
- arr = d + jsonActual
- return arr
- def limpiarArchivo():
- open('test_file.json', 'w').close()
- opfile = open("test_file.json", "a")
- opfile.write("[]")
- opfile.close()
- def buscarDispositivo():
- global service_matches
- if service_matches is None:
- print("service_matches is null")
- dispositivoEncontrado = findDevice()
- if dispositivoEncontrado:
- sendDataBluetooth(jsonArray)
- else:
- service_matches = None
- #limpiarArchivo()
- escribirEnArchivo(jsonArray)
- #------ Excel -------
- #registerDataStatus(2)# device not found
- print("______________________________________________________________________________")
- print(" ")
- print("No se ha encontrado ningun dispositivo.")
- print("______________________________________________________________________________")
- print(" ")
- else:
- #print("service_matches is not null")
- sendDataBluetooth(jsonArray)
- def leerFilaTimer(dispositivo):
- threading.Timer(1, leerFilaTimer, [dispositivo]).start()
- global leerExcelCounter
- indexFilaActual = leerExcelCounter
- leerExcelCounter = leerExcelCounter + 1
- print("--------------------Comienza Iteracion "+str(indexFilaActual)+"-------")
- if leerExcelCounter >= dataExcelLength:
- return 0
- columnaActual = obtenerColumna(indexFilaActual)
- array = leerColumnaCrearArray(columnaActual)
- global lecturaDate
- lecturaDate = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
- print("Hora Lectura: " + lecturaDate)
- #array = [[0.143076849365, 58.4144236031, 0.908374498589, 0.908429886515, 0.908429886515, 0.0202934879008, 0.0203150239871, 0.0203150239871, 2895.66821488, 2895.64630704, 2895.64630704]]
- #array = [[random.randint(1,20),random.randint(1,20),random.randint(1,20),random.randint(1,20),random.randint(1,20),random.randint(1,20),random.randint(1,20),random.randint(1,20),random.randint(1,20),random.randint(1,20),random.randint(1,20)]]
- exito = sendDataToApp2(array, dispositivo)
- #ademas de escribir los promedio/maxios/minimos etc, poner los valores del ciclo anterior en variable global
- #registerDataStatus(1, jsonArray0)
- if exito:
- print("============= EXITO "+str(indexFilaActual)+" ================")
- else:
- print("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ERROR "+str(indexFilaActual)+" xxxxxxxxxxx")
- def inicializar():
- crearExcel()
- leerExcel()
- inicializarDirectorios()
- limpiarArchivo()
- service_matches = findDevice2()
- first_match = service_matches[0]
- port = first_match["port"]
- name = first_match["name"]
- host = first_match["host"]
- global sock
- sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM )
- sock.connect((host, port))
- leerFilaTimer(service_matches)
- return 0
- inicializar()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement