Advertisement
Guest User

rpi

a guest
Jan 29th, 2020
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 16.34 KB | None | 0 0
  1.  
  2. import sys
  3. import bluetooth
  4. import time
  5. import os.path
  6. import datetime
  7. import json
  8. import simplejson
  9. import os
  10. import random
  11. import numpy
  12. import threading
  13.  
  14. import pandas as pd
  15. from pandas import ExcelWriter
  16. from pandas import ExcelFile
  17.  
  18. service_matches = None
  19. port = None
  20. name = None
  21. host = None
  22. sock = None
  23.  
  24. dataExcel = None
  25. dataExcelLength = 0
  26. leerExcelCounter = 0
  27.  
  28. actualDate = 0
  29. totalTiempoSec = 0
  30.  
  31. promedioExito = 0
  32. mayorTiempo = 0
  33. menorTiempo = 1
  34. promedioTiempo = 0
  35. totalEnviados = 0
  36. totalRegistrados = 0
  37. totalErrores = 0
  38. lecturaDate = 0
  39. tiempoEnvio = 0
  40.  
  41. tiempoInicio = ""
  42. tiempoFinal = ""
  43.  
  44. #------------------------------------------ EXCEL ---------------------------------------------------
  45.  
  46. def crearExcel():
  47.     df = pd.DataFrame({'% de exito':[0],
  48.                        'Mayor tiempo de registro (seg.)':[0],
  49.                        'Menor tiempo de registro (seg.)':[1],
  50.                        'Promedio tiempo de envio (seg.)':[0],
  51.                        'Total de datos enviados':[0],
  52.                        'Total errores':[0],
  53.                        'Total de datos registrados':[0]})
  54.  
  55.     writer = ExcelWriter('/home/pi/Desktop/promedio_datos.xlsx')
  56.     df.to_excel(writer, 'Promedios',index=False)
  57.     writer.save()
  58.        
  59. def leerExcel():
  60.     global dataExcel
  61.     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'
  62.    
  63.     global dataExcelLength
  64.     dataExcelLength = len(dataExcel)
  65.    
  66. def obtenerColumna(index):
  67.     columna = dataExcel.iloc[index]
  68.     return columna
  69.  
  70. def leerColumnaCrearArray(columna):
  71.     arrayColumna = []
  72.    
  73.     corriente = columna.values[0]
  74.     voltaje = columna.values[1]
  75.    
  76.     estimacionSoc = columna.values[4]
  77.     confIntervalSoc1 = columna.values[5]
  78.     confIntervalSoc2 = columna.values[6]
  79.    
  80.     estimacionRin = columna.values[7]
  81.     confIntervalRin1 = columna.values[8]
  82.     confIntervalRin2 = columna.values[9]
  83.    
  84.     estimacionSompa = columna.values[10]
  85.     confIntervalSompa1 = columna.values[11]
  86.     confIntervalSompa2 = columna.values[12]
  87.    
  88.    
  89.     arrayColumna = [[corriente, voltaje, estimacionSoc, confIntervalSoc1, confIntervalSoc2, estimacionRin, confIntervalRin1, confIntervalRin2, estimacionSompa, confIntervalSompa1, confIntervalSompa2]]
  90.    
  91.     return arrayColumna
  92.  
  93. def registerDataStatus(status, array, dateAntesEnviar, dateDespuesEnviar, _tiempoEnvio):
  94.  
  95.     global promedioExito
  96.     global mayorTiempo
  97.     global menorTiempo
  98.     global promedioTiempo
  99.     global totalEnviados
  100.     global totalRegistrados
  101.     global totalErrores
  102.     global tiempoInicio
  103.     global tiempoFinal
  104.     global tiempoEnvio
  105.     global tiempoApp
  106.  
  107.     tiempoEnvio = _tiempoEnvio
  108.  
  109.     #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'
  110.  
  111.     totalRegistrados = totalRegistrados + 1
  112.     print("reg: "+str(totalRegistrados))
  113.  
  114.     tiempoInicio = dateAntesEnviar
  115.  
  116.     if status is 1: #
  117.  
  118.         tiempoFinal = dateDespuesEnviar
  119.        
  120.         if tiempoEnvio > mayorTiempo:
  121.             mayorTiempo = tiempoEnvio
  122.        
  123.         if tiempoEnvio < menorTiempo:
  124.             menorTiempo = tiempoEnvio
  125.        
  126.         global totalTiempoSec
  127.         totalEnviados = totalEnviados + 1
  128.         totalTiempoSec = totalTiempoSec + tiempoEnvio
  129.         promedioTiempo = totalTiempoSec / totalEnviados
  130.        
  131.         promedioExito = (totalEnviados / totalRegistrados) * 100
  132.         print("OK SAVED")
  133.        
  134.     if status is 0: #
  135.  
  136.         totalErrores = totalErrores + 1
  137.        
  138.         tiempoFinal = "-"
  139.         promedioExito = "-"
  140.         promedioTiempo = "-"
  141.         tiempoEnvio = "-"
  142.         print("ERROR SAVED")
  143.     #registrosIndividuales(array, tiempoEnvio)
  144.    
  145.  
  146. def registrosIndividuales(array, tiempoEnvio):
  147.    
  148.     data = None
  149.  
  150.     for js in array:
  151.  
  152.         with open('registros.json', 'r') as file_read:
  153.             data = json.load(file_read)
  154.             data.append(js + " : " + str(tiempoEnvio) + " segundos")
  155.             #print("***escribirEnArchivo***: " + str(data))
  156.             #print("***************************************")
  157.            
  158.         with open('registros.json', 'w') as file:
  159.             json.dump(data, file)
  160.        
  161. #---------------------------------------- FIN EXCEL -------------------------------------------------
  162.  
  163.  
  164.  
  165. def sendDataToApp2(array, dispositivo):
  166.     #print(">>> sendDataToApp()")
  167.  
  168.     jsonArray0 = createJson(array)
  169.     jsonArray = leerArchivo(jsonArray0)
  170.     #print("Json Concatenado: "+str(jsonArray))
  171.     print("Objeetos enviados: "+str(len(jsonArray)))
  172.    
  173.     return sendDataBluetooth(jsonArray, dispositivo)
  174.  
  175.  
  176.        
  177. def findDevice():
  178.     print(">>> findDevice()")
  179.     uuid = "08C2B2EF-7C87-3D00-0CDC-9A2ADC420BFF"
  180.     buscando = True
  181.     cont = 6
  182.    
  183.    
  184.     while buscando:
  185.        
  186.         global service_matches
  187.         service_matches = bluetooth.find_service(name = "RosieProject", uuid = uuid )
  188.  
  189.         if len(service_matches) == 0:
  190.             cont = cont-1
  191.             print ("couldn't find the FooBar service: "+str(cont))
  192.            
  193.             if cont == 0:
  194.                 cont = -1
  195.                 buscando = False
  196.             else:
  197.                 buscando = True
  198.                
  199.  
  200.         else:
  201.             buscando = False
  202.    
  203.    
  204.     if buscando is False:
  205.         inicializarBTConf()
  206.  
  207.     if cont == -1:
  208.         print("False " +str(cont))
  209.        
  210.         return False
  211.     else:
  212.         print("True " +str(cont))
  213.         return True
  214.        
  215. #Retorna el dispositivo como objeto
  216. def findDevice2():
  217.     print(">>> findDevice()")
  218.     uuid = "08C2B2EF-7C87-3D00-0CDC-9A2ADC420BFF"
  219.     buscando = True
  220.     cont = 6
  221.    
  222.    
  223.     while buscando:
  224.        
  225.         global service_matches
  226.         service_matches = bluetooth.find_service(name = "RosieProject", uuid = uuid )
  227.  
  228.         if len(service_matches) == 0:
  229.             cont = cont-1
  230.             print ("couldn't find the FooBar service: "+str(cont))
  231.            
  232.             if cont == 0:
  233.                 cont = -1
  234.                 buscando = False
  235.             else:
  236.                 buscando = True
  237.                
  238.  
  239.         else:
  240.             buscando = False
  241.    
  242.    
  243.     #if buscando is False:
  244.         #inicializarBTConf()
  245.  
  246.     if cont == -1:
  247.         print("False " +str(cont))
  248.        
  249.         return None
  250.     else:
  251.         print("True " +str(cont))
  252.         return service_matches
  253.        
  254.        
  255. def inicializarBTConf():
  256.    
  257.     global service_matches
  258.     global port
  259.     global name
  260.     global host
  261.    
  262.     first_match = service_matches[0]
  263.     port = first_match["port"]
  264.     name = first_match["name"]
  265.     host = first_match["host"]
  266.  
  267.     print ("connecting to \"%s\" on %s" % (name, host))
  268.     print ("Name: " + str(name))
  269.     print ("Port: " + str(port))
  270.     print ("Host: " + str(host))
  271.    
  272. def sendDataBluetooth(jsonArray, dispositivo):
  273.     #print(">>> sendDataBluetooth()")
  274.    
  275.  
  276.     #print ("connecting to \"%s\" on %s" % (name, host))
  277.     #print ("Name: " + str(name))
  278.     #print ("Port: " + str(port))
  279.     #print ("Host: " + str(host))
  280.  
  281.     limpiarArchivo()
  282.     datos = str(jsonArray)
  283.     #actualDate = float(time.mktime(datetime.datetime.now().timetuple())) * 1000
  284.    
  285.     dateInicio = datetime.datetime.strptime(lecturaDate, '%Y-%m-%d %H:%M:%S.%f')
  286.    
  287.     try:  
  288.        
  289.         print("hola")  
  290.  
  291.        
  292.         print("chao")
  293.    
  294.         sock.send(datos)
  295.         #getData = sock.recv(1024)
  296.                
  297.         #sock.close()
  298.  
  299.         dateWithMill2 = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
  300.  
  301.         dateTermino = datetime.datetime.strptime(dateWithMill2, '%Y-%m-%d %H:%M:%S.%f')
  302.         delta = dateTermino - dateInicio
  303.         milliseconds = int(delta.total_seconds() * 1000)
  304.         tiempoEnvio = milliseconds / 1000
  305.          
  306.         print("Final Envio: "+ dateWithMill2)
  307.         print("tiempo envio: " + str(tiempoEnvio))
  308.         registerDataStatus(1, jsonArray, lecturaDate, dateWithMill2, tiempoEnvio)
  309.         return True
  310.  
  311.         #-------- EXCEL ------------  
  312.        
  313.  
  314.     except Exception as e:
  315.         print("Inicio Catch envio bluetooth")  
  316.         #service_matches = None
  317.         #-------- EXCEL ------------
  318.         registerDataStatus(0, jsonArray, lecturaDate, 0, 0)
  319.         escribirEnArchivo(jsonArray)
  320.                
  321.         print("Error - " + str(e) + ": catch send data bluetooth...")
  322.         return False
  323.    
  324.  
  325.  
  326. def timeout(socket, host, port):
  327.     print("Connecting...")
  328.     socket.connect((host, port))
  329.  
  330. def createJson(array):
  331.    
  332.     jsonArray = []
  333.  
  334.            
  335.     for x in array:
  336.  
  337.    
  338.         corriente = x[0]
  339.         voltaje = x[1]
  340.  
  341.         estimacionSoc = x[2]
  342.         confIntervalSoc1 = x[3]
  343.         confIntervalSoc2 = x[4]
  344.  
  345.         estimacionRin = x[5]
  346.         confIntervalRin1 = x[6]
  347.         confIntervalRin2 = x[7]
  348.  
  349.         estimacionSompa = x[8]
  350.         confIntervalSompa1 = x[9]
  351.         confIntervalSompa2 = x[10]
  352.  
  353.         time = datetime.datetime.now().strftime("%d/%m/%Y %H:%M:%S")
  354.  
  355.         jsona = {
  356.         "FechaHoraString": time,
  357.         "EstimacionSoc": estimacionSoc,
  358.         "ConfIntervalSoc1": confIntervalSoc1,
  359.         "ConfIntervalSoc2": confIntervalSoc2,
  360.         "EstimacionSompa": estimacionSompa,
  361.         "ConfIntervalSompa1": confIntervalSompa1,
  362.         "ConfIntervalSompa2": confIntervalSompa2,
  363.         "EstimacionRin": estimacionRin,
  364.         "ConfIntervalRin1": confIntervalRin1,
  365.         "ConfIntervalRin2": confIntervalRin2,
  366.         "Corriente": corriente,
  367.         "Voltaje": voltaje,
  368.         "PromedioExito": promedioExito,
  369.         "MayorTiempo": mayorTiempo,
  370.         "MenorTiempo": menorTiempo,
  371.         "PromedioTiempo": promedioTiempo,
  372.         "TotalEnviados": totalEnviados,
  373.         "TotalRegistrados": totalRegistrados,
  374.         "TotalErrores": totalErrores,
  375.         "TiempoInicio": tiempoInicio,
  376.         "TiempoFinal": tiempoFinal,
  377.         "TiempoEnvio": tiempoEnvio}
  378.        
  379.         jsona = str(jsona)
  380.         jsonArray.append(jsona)
  381.        
  382.     return jsonArray
  383.    
  384.    
  385. def createJsonSinFecha(array):
  386.    
  387.     jsonArray = []
  388.  
  389.            
  390.     for x in array:
  391.  
  392.         estimacionSoc = x[0]
  393.         confIntervalSoc1 = x[1]
  394.         confIntervalSoc2 = x[2]
  395.         estimacionSompa = x[3]
  396.         confIntervalSompa1 = x[4]
  397.         confIntervalSompa2 = x[5]
  398.         estimacionRin = x[6]
  399.         confIntervalRin1 = x[7]
  400.         confIntervalRin2 = x[8]
  401.         corriente = x[9]
  402.         voltaje = x[10]
  403.         time = x[11]
  404.  
  405.         jsona = {
  406.         "Fecha": time,
  407.         "EstimacionSoc": estimacionSoc,
  408.         "ConfIntervalSoc1": confIntervalSoc1,
  409.         "ConfIntervalSoc2": confIntervalSoc2,
  410.         "EstimacionSompa": estimacionSompa,
  411.         "ConfIntervalSompa1": confIntervalSompa1,
  412.         "ConfIntervalSompa2": confIntervalSompa2,
  413.         "EstimacionRin": estimacionRin,
  414.         "ConfIntervalRin1": confIntervalRin1,
  415.         "ConfIntervalRin2": confIntervalRin2,
  416.         "Corriente": corriente,
  417.         "Voltaje": voltaje}
  418.        
  419.         jsona = str(jsona)
  420.         jsonArray.append(jsona)
  421.        
  422.        
  423.     return jsonArray
  424.    
  425.  
  426. def inicializarDirectorios():
  427.     existe = os.path.isfile("test_file.json")
  428.     if existe:
  429.         print("test_file.json exists")
  430.  
  431.         empty = os.stat("test_file.json").st_size == 0
  432.         #print("Is empty: " + str(empty))
  433.        
  434.         if empty:
  435.             opfile = open("test_file.json", "a")
  436.             opfile.write("[]")
  437.             opfile.close()
  438.            
  439.    
  440.     else:
  441.         opfile = open("test_file.json", "a")
  442.         opfile.write("[]")
  443.         opfile.close()
  444.        
  445.     existe = os.path.isfile("registros.json")
  446.     if existe:
  447.         print("registros.json exists")
  448.  
  449.         empty = os.stat("registros.json").st_size == 0
  450.         #print("Is empty: " + str(empty))
  451.        
  452.         if empty:
  453.             opfile = open("registros.json", "a")
  454.             opfile.write("[]")
  455.             opfile.close()
  456.            
  457.  
  458.     else:
  459.         opfile = open("registros.json", "a")
  460.         opfile.write("[]")
  461.         opfile.close()
  462.        
  463. def escribirEnArchivo(jsonActual):
  464.    
  465.     data = None
  466.    
  467.     for js in jsonActual:
  468.        
  469.         with open('test_file.json', 'r') as file_read:
  470.             data = json.load(file_read)
  471.             data.append(js)
  472.             #print("***escribirEnArchivo***: " + str(data))
  473.             #print("***************************************")
  474.            
  475.         with open('test_file.json', 'w') as file:
  476.             json.dump(data, file)
  477.        
  478.    
  479. def leerArchivo(jsonActual):
  480.    
  481.     #print ("leerArchivo: " + str(jsonActual))
  482.     file_empty = os.stat('test_file.json').st_size
  483.     #print(file_empty)
  484.    
  485.     if file_empty == 0:
  486.         print("test_file.json is empty")
  487.         return jsonActual
  488.  
  489.     else:
  490.         with open('test_file.json', 'r') as file_read:
  491.             d = json.load(file_read)
  492.             #d.append(jsonActual)
  493.             #print("***LEIDO***: " + str(d))
  494.             #print("***************************************")
  495.            
  496.             arr = d + jsonActual
  497.            
  498.             return arr
  499.            
  500.            
  501. def limpiarArchivo():
  502.     open('test_file.json', 'w').close()
  503.     opfile = open("test_file.json", "a")
  504.     opfile.write("[]")
  505.     opfile.close()
  506.  
  507. def buscarDispositivo():
  508.     global service_matches
  509.     if service_matches is None:
  510.         print("service_matches is null")
  511.        
  512.         dispositivoEncontrado = findDevice()
  513.         if dispositivoEncontrado:
  514.             sendDataBluetooth(jsonArray)
  515.         else:
  516.             service_matches = None
  517.             #limpiarArchivo()
  518.             escribirEnArchivo(jsonArray)
  519.            
  520.             #------ Excel -------
  521.             #registerDataStatus(2)# device not found
  522.            
  523.             print("______________________________________________________________________________")
  524.             print(" ")
  525.             print("No se ha encontrado ningun dispositivo.")
  526.             print("______________________________________________________________________________")
  527.             print(" ")
  528.        
  529.     else:
  530.         #print("service_matches is not null")
  531.         sendDataBluetooth(jsonArray)
  532.  
  533.    
  534.  
  535. def leerFilaTimer(dispositivo):
  536.     threading.Timer(1, leerFilaTimer, [dispositivo]).start()
  537.    
  538.     global leerExcelCounter
  539.     indexFilaActual = leerExcelCounter
  540.     leerExcelCounter = leerExcelCounter + 1
  541.  
  542.     print("--------------------Comienza Iteracion "+str(indexFilaActual)+"-------")
  543.  
  544.     if leerExcelCounter >= dataExcelLength:
  545.         return 0
  546.    
  547.     columnaActual = obtenerColumna(indexFilaActual)
  548.     array = leerColumnaCrearArray(columnaActual)
  549.    
  550.     global lecturaDate
  551.     lecturaDate = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
  552.     print("Hora Lectura: " + lecturaDate)
  553.    
  554.     #array = [[0.143076849365, 58.4144236031, 0.908374498589, 0.908429886515, 0.908429886515, 0.0202934879008, 0.0203150239871, 0.0203150239871, 2895.66821488, 2895.64630704, 2895.64630704]]
  555.     #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)]]
  556.    
  557.     exito = sendDataToApp2(array, dispositivo)
  558.     #ademas de escribir los promedio/maxios/minimos etc, poner los valores del ciclo anterior en variable global
  559.    
  560.     #registerDataStatus(1, jsonArray0)
  561.     if exito:
  562.         print("============= EXITO "+str(indexFilaActual)+" ================")
  563.     else:
  564.         print("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ERROR "+str(indexFilaActual)+" xxxxxxxxxxx")
  565.  
  566.  
  567. def inicializar():  
  568.    
  569.    
  570.     crearExcel()
  571.     leerExcel()
  572.     inicializarDirectorios()
  573.     limpiarArchivo()
  574.     service_matches = findDevice2()
  575.    
  576.     first_match = service_matches[0]
  577.     port = first_match["port"]
  578.     name = first_match["name"]
  579.     host = first_match["host"]
  580.    
  581.     global sock
  582.     sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM )
  583.     sock.connect((host, port))
  584.    
  585.     leerFilaTimer(service_matches)
  586.  
  587.     return 0
  588.    
  589.  
  590.        
  591. inicializar()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement