m0n0lithic

scriptEMAS/Emas1.py

Apr 21st, 2014
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 13.72 KB | None | 0 0
  1. #! /usr/bin/env python
  2.  
  3. import MySQLdb
  4. import ftplib
  5. #import numpy as n
  6. import pylab as p
  7. import datetime
  8. #import math    
  9. from time import localtime #,mktime,strftime
  10. from matplotlib.ticker import OldScalarFormatter, FuncFormatter
  11. import matplotlib.text
  12. class EMAS_DB:
  13.  
  14.      db = None #inicializa la variable para el manejo de la conexion a la BD
  15.      def __init__(self):
  16.         try:
  17.  
  18.           # self.db = MySQLdb.connect(user='root', passwd='lenercabeza', db='BD_Emas')
  19.            self.db = MySQLdb.connect(user='root', passwd='jupAja02', db='BD_Emas')
  20.            self.cur = self.db.cursor(MySQLdb.cursors.DictCursor)
  21.  
  22.         except MySQLdb.Error, (errno, strerror):
  23.                 print "(%s): %s" % (errno, strerror)
  24.  
  25.      def verificar(self, ID, sensor, fecha):
  26.  
  27.                 str_ = "SELECT ID, sensor, fecha FROM datos_EMAS WHERE ID = %s AND sensor = %s AND fecha = %s"
  28.                 self.cur.execute(str_, (ID, sensor, fecha))
  29.                 resl = self.cur.fetchone()              #fetch the query
  30.                 if resl:
  31.                    return True
  32.                 else: return False
  33.  
  34.      def insertar(self, ID, sensor, fecha, dato):
  35.  
  36.         str_ = "INSERT INTO datos_EMAS VALUES (%s, %s, %s, %s)"
  37.         self.cur.execute(str_, (ID, sensor, fecha, dato))
  38.  
  39.      def obtener(self, ID, sensor, fecha):
  40.  
  41.         tiempo = []
  42.         valor = []
  43.         if sensor == '0068' or sensor == '0255':
  44.           str_ = "SELECT ID, sensor, fecha, valor FROM datos_EMAS WHERE ID = %s AND sensor = %s AND fecha <= %s ORDER BY fecha DESC LIMIT 24"
  45.  
  46.           self.cur.execute(str_, (ID, sensor, fecha ))
  47.           while True:
  48.               row_ = self.cur.fetchone()
  49.               if row_:
  50.                  fechReg = row_['fecha']
  51.                  tiempo.append(fechReg)
  52.                  valor.append(round(row_['valor'], 2))
  53.  
  54.  
  55.               else: break
  56.           tiempo.reverse()
  57.           valor.reverse()
  58.           tiempo = p.array(tiempo)
  59.           #print tiempo
  60.           #print valor  
  61.         else:
  62.  
  63.           str_ = "SELECT ID, sensor, fecha, valor FROM datos_EMAS WHERE ID = %s AND sensor = %s AND fecha <= %s AND (RIGHT(fecha,5)) = '50:00' ORDER BY fecha DESC LIMIT 24"
  64.  
  65.           self.cur.execute(str_, (ID, sensor, fecha ))
  66.           while True:
  67.               row_ = self.cur.fetchone()
  68.               if row_:
  69.                  fechReg = row_['fecha']
  70.                  tiempo.append(fechReg)
  71.                  valor.append(round(row_['valor'], 2))
  72.  
  73.  
  74.  
  75.               else: break
  76.           tiempo.reverse()
  77.           valor.reverse()
  78.           tiempo = p.array(tiempo)
  79.           #print tiempo
  80.           #print valor  
  81.         return tiempo, valor
  82.  
  83.  
  84.  
  85.  
  86.  
  87.      def close(self):
  88.         self.cur.close()
  89.         self.db.close()
  90.  
  91. class Grafica:
  92.  
  93.      def __init__(self, datos, tipo, sensor, est, unidad):
  94.  
  95.  
  96.          p.rcParams['legend.fontsize'] = 9.5
  97.          locFmt = p.DateFormatter('%m/%d %H:00')
  98.  
  99.          now = localtime()
  100.          hoy = str(now[0]) +'-'+ str(now[1]).zfill(2)+'-'+ str(now[2]).zfill(2)
  101.  
  102.          if sensor == '0240':
  103.  
  104.  
  105.             ax = p.subplot(111)
  106.             arrFecha = datos[0]
  107.             arrValor = datos[1]
  108.  
  109.             ciudad = BuscarCiudad(est)
  110.             pos_Anota = valorMaximo(sensor,arrValor)
  111.             anota = select_Anotacion(sensor,arrValor)
  112.             rang = ConversionFecha(arrFecha)
  113.  
  114.             p.ylabel(tipo +' ('+ unidad+')', color='b')
  115.             p.title(tipo+'\n'+ciudad+'  '+'Fecha: '+hoy, size=14, color='#aaaaaa')
  116.             #p.set_xticks(array(range(0, size(arrFecha))) + 0.35)
  117.             p.plot(arrFecha, arrValor)
  118.  
  119.             p.xlabel('Tiempo 24 horas'+'\n'+'(mes/dia hora)', color='#aaaaaa')
  120.  
  121.             #p.ylim((min(arrValor),max(arrValor)))
  122.  
  123.  
  124.  
  125.             if max(arrValor) == 0:
  126.               p.axis([min(arrFecha), max(arrFecha), min(arrValor), max(arrValor)+1])
  127.               p.text(0.5, 0.5,'no se registran datos hasta el momento',horizontalalignment='center',verticalalignment='center',  transform = ax.transAxes, size=14, color='blue')
  128.  
  129.             else:
  130.               p.axis([min(arrFecha), max(arrFecha), min(arrValor)-0.5, max(arrValor)+0.5])
  131.               p.text(0.1, -0.08,anota[0]+':'+str(anota[1]),horizontalalignment='center',verticalalignment='center',  transform = ax.transAxes, bbox=dict(facecolor='red', alpha=0.5), size=9)
  132.  
  133.  
  134.             loc = p.HourLocator(byhour=range(min(rang), max(rang), 4))
  135.             ax.xaxis.set_major_locator(loc)
  136.             ax.xaxis.set_major_formatter(locFmt)
  137.             ax.yaxis.set_major_formatter(OldScalarFormatter())
  138.             lbx = ax.get_xticklabels()
  139.             lby = ax.get_yticklabels()
  140.             p.setp(lbx, fontsize=8, color='#aaaaaa')
  141.             p.setp(lby, fontsize=8, color='b')
  142.  
  143.             fich=tipo[0:4]+est[8:]
  144.             p.grid(True)
  145.             p.savefig(fich+'.png')
  146.             p.close()
  147.             #p.show()
  148.          if sensor == '0068' or sensor == '0255':
  149.  
  150.            ax = p.subplot(111)
  151.            arrFecha = datos[0]
  152.            arrValor = datos[1]
  153.            rang = ConversionFecha(arrFecha)
  154.  
  155.            ciudad = BuscarCiudad(est)
  156.            pos_Anota = valorMaximo(sensor,arrValor)
  157.            anota = select_Anotacion(sensor,arrValor)
  158.            #print arrFecha
  159.            #print arrValor
  160.  
  161.  
  162.            p.ylabel(tipo +' ('+ unidad+')', color='b')
  163.            p.title(tipo+'\n'+ciudad+'  '+'Fecha: '+hoy, size=14, color='#aaaaaa')
  164.  
  165.  
  166.  
  167.            line, =  p.plot(arrFecha, arrValor)
  168.            line.set_color('b')
  169.            #line.set_marker('o')
  170.            #yloc=range(min(arrValor), max(arrValor), 2)
  171.            #p.yticks(range(min(arrValor), max(arrValor), 1.2))
  172.            loc = p.HourLocator(byhour=range(min(rang), max(rang), 4))
  173.            #loc = p.HourLocator(byhour=range(0,23,6))
  174.            p.axis([min(arrFecha), max(arrFecha), min(arrValor)-0.5, max(arrValor)+0.5])
  175.            #ax.yaxis.set_major_locator(yloc)
  176.            ax.xaxis.set_major_locator(loc)
  177.            ax.xaxis.set_major_formatter(locFmt)
  178.            ax.yaxis.set_major_formatter(OldScalarFormatter())
  179.            ax.annotate(str(pos_Anota[2]), xy=(arrFecha[pos_Anota[0]], pos_Anota[1]), size=10, color='r')
  180.            p.text(0.1, -0.08,anota[0]+':'+str(anota[1]),horizontalalignment='center',verticalalignment='center',  transform = ax.transAxes, bbox=dict(facecolor='red', alpha=0.5), size=9)
  181.  
  182.            #ax.annotate(tipo+' '+anota+':'+str(max(arrValor)), xy=(arrFecha[pos_Anota[0]], max(arrValor)), xytext=(arrFecha[pos_Anota[1]], max(arrValor)+0.5), arrowprops=dict(facecolor='red', shrink=0.03), size=10, color='r')
  183.            lbx = ax.get_xticklabels()
  184.            p.xlabel('Tiempo 24 horas'+'\n'+'(mes/dia hora)', color='#aaaaaa')
  185.            lby = ax.get_yticklabels()
  186.            #p.ylim((min(arrValor),max(arrValor)))
  187.            p.setp(lbx, fontsize=8, color='#aaaaaa')
  188.            p.setp(lby, fontsize=8, color='b')
  189.  
  190.  
  191.            #p.text(max(arrFecha)+.05, max(arrFecha), r'$\bar H_{20.0}$' ,fontsize=12)
  192.            #p.legend(nota ,'maxima', loc='best')
  193.            fich=tipo[0:4]+est[8:]
  194.            p.grid(True)
  195.            p.savefig(fich+'.png')
  196.            p.close()
  197.            #p.show()
  198.          if sensor == '0104':
  199.  
  200.            ax = p.subplot(111)
  201.  
  202.            list1 = datos[0]
  203.            list2 = datos[1]
  204.            ciudad = BuscarCiudad(est)
  205.  
  206.            p.ylabel('velocidad (nudos)', color='b')
  207.            #p.grid(True)
  208.            p.title(tipo+' del viento'+'\n'+ciudad+'  '+'Fecha:'+hoy,size=14,weight='bold', color='#aaaaaa')
  209.  
  210.                 arrValor = list1[1]
  211.  
  212.            rang = ConversionFecha(arrFecha)
  213.  
  214.            lineV, = p.plot(arrFecha, arrValor)
  215.            lineV.set_color('b')
  216.            lineV.set_markersize(5)
  217.            lineV.set_linestyle('-')
  218.            lineV.set_markerfacecolor('b')
  219.  
  220.  
  221.            #ax.axis([min(arrFecha), max(arrFecha), min(arrValor)-0.5, max(arrValor)+0.5])
  222.            #ax.xaxis.set_major_locator(loc)
  223.            ax.xaxis.set_major_formatter(locFmt)
  224.            lbx = ax.get_xticklabels()
  225.            lby = ax.get_yticklabels()
  226.            p.setp(lbx, fontsize=8, color='#aaaaaa')
  227.            p.xlabel('Tiempo 24 horas'+'\n'+'(mes/dia hora)', color='#aaaaaa')
  228.            p.setp(lby, fontsize=8, color='b')
  229.  
  230.  
  231.            ax2 = p.twinx()
  232.  
  233.            arrFecha1 = list2[0]
  234.            arrValor1 = list2[1]
  235.  
  236.  
  237.  
  238.            p.ylabel('Direccion (Grados)', color='r')
  239.  
  240.            lineD, = p.plot(arrFecha1, arrValor1)
  241.            lineD.set_color('r')
  242.            lineD.set_markersize(5)
  243.            lineD.set_linestyle('-')
  244.            lineD.set_markerfacecolor('r')
  245.  
  246.  
  247.  
  248.  
  249.  
  250.            #loc = p.HourLocator(byhour=range(0,23,6))
  251.            loc = p.HourLocator(byhour=range(min(rang), max(rang), 4))
  252.            p.axis([min(arrFecha1), max(arrFecha1), min(arrValor1), max(arrValor1)])
  253.  
  254.            ax2.xaxis.set_major_locator(loc)      arrFecha = list1[0]
  255.            ax2.xaxis.set_major_formatter(locFmt)
  256.            lbx = ax2.get_xticklabels()
  257.            lby = ax2.get_yticklabels()
  258.            p.setp(lbx, fontsize=8, color='#aaaaaa')
  259.            p.xlabel('Tiempo 24 horas'+'\n'+'(mes/dia hora)', color='#aaaaaa')
  260.            p.setp(lby, fontsize=8, color='r')
  261.  
  262.            p.legend((lineD,lineV),('Direccion','Velocidad'), loc='best')
  263.            #p.show()
  264.            fich=tipo[0:4]+est[8:]
  265.            p.grid(True)
  266.            p.savefig(fich+'.png') #,dpi=70
  267.            p.close()
  268.            #print arrFecha1
  269.            #print arrValor1
  270. def select_Anotacion(sens,listV):
  271.     num = 0.0
  272.     if max(listV)== 0:
  273.           anota = 'no registra datos'
  274.     else :
  275.        if sens == '0068':
  276.           anota = 'maxima temperatura en las ultimas 24 horas'
  277.           num = max(listV)
  278.        if sens == '0255':
  279.           anota = 'minima presion en las ultimas 24 horas'
  280.           num = min(listV)
  281.        if sens == '0240':
  282.           anota = 'max_precipitacion en las ultimas 24 horas'
  283.           num = max(listV)
  284.     return anota, num
  285. def valorMaximo(sens,listV):
  286. #esta funcion es buscar la mejor posicion de la anotacion para avisar el valor maximo o minimo de las graficas
  287.    if sens != '0255':
  288.      valor = max(listV)
  289.      posicion_Y=valor
  290.      posicion = 0
  291.      for pV in listV:
  292.         if pV == valor:
  293.            break
  294.         posicion = posicion+1
  295.      #if posicion >= 8:
  296.       #  posiciontexto_X=posicion-1
  297.      #else: posiciontexto_X = posicion+1
  298.    else:
  299.      valor = min(listV)
  300.     posicion_Y=valor-0.1
  301.      posicion = 0
  302.      for pV in listV:
  303.         if pV == valor:
  304.            break
  305.         posicion = posicion+1
  306.      #if posicion >= 8:
  307.         #posiciontexto_X=posicion-1
  308.      #else: posiciontexto_X = posicion+1      
  309.    return posicion,posicion_Y, valor
  310.  
  311. def BuscarCiudad(est):
  312.     ciudad = 'Covenas'
  313.     if est == '0000000001':
  314.        ciudad = 'Covenas'
  315.     if est == '0000000002':
  316.        ciudad = 'Mantuntugo'
  317.     if est == '0000000003':
  318.        ciudad = 'Providencia'
  319.  
  320.     return ciudad
  321.  
  322.  
  323. def ConversionFecha(fechas):
  324.     rango = []
  325.     hora = []
  326.     for dfecha in fechas:
  327.         hora.append(str(dfecha)[11:13])
  328.  
  329.     for sfecha in hora:
  330.         rango.append(int(sfecha))
  331.     return rango
  332.  
  333. def CapturarDATOS(archMIS, Cnx):
  334.      #escanea los ficheros .MIS para extraer sus datos  
  335.     fn = open(archMIS, 'r')
  336.  
  337.     while True:
  338.      line = fn.readline().split('\t')
  339.      ta = len(line[0])
  340.      #print ta
  341.      #print line
  342.      if len(line[0])!= 0:
  343.         if len(line[0])==85:
  344.           ID = line[0][9:19]
  345.           Sensor=line[0][37:41]
  346.           #print ID
  347.           #print Sensor
  348.         else:
  349.           fecha = line[0][0:4]+'-'+line[0][4:6]+'-'+line[0][6:8]+' '+line[0][9:17]
  350.           dato = line[0][18:]
  351.           if not Cnx.verificar(ID, Sensor, fecha):
  352.             Cnx.insertar(ID,Sensor,fecha, dato)
  353.      else: break
  354.  
  355.  
  356. def DescargaFTP(hoy):
  357.     #descarga los ficheros .MIS por via FTP
  358.     Emas = ['CB144456','CB1462BA','CB145720']
  359.     try:
  360.  
  361.      ftp = ftplib.FTP("172.25.19.17")
  362.      ftp.login(user="cioh", passwd="lenercabeza")
  363.      ftp.cwd(hoy)
  364.      print hoy
  365.      Cnx = EMAS_DB()
  366.      for ID in Emas:
  367.  
  368.  
  369.        ftpfile = ftp.nlst(ID + ' ' + hoy + '*')
  370.  
  371.        for archMIS in ftpfile:
  372.            ftp.retrbinary('RETR ' + archMIS, open(archMIS,'wb').write)
  373.            #ftpfile.append('CB144456 20100121 065149359' + '.MIS')
  374.            print archMIS
  375.            CapturarDATOS(archMIS, Cnx)
  376.      Cnx.close()
  377.     except ftplib.error_perm, (error):
  378.                 print "Error en la conexion: %s" % (error)
  379.  
  380.  
  381.  
  382. if __name__ == '__main__':
  383.  
  384.      now = localtime()
  385.      hoy = str(now[0]) + str(now[1]).zfill(2) + str(now[2]).zfill(2)
  386.      ahora = str(now[0]) +'-'+str(now[1]).zfill(2) +'-'+ str(now[2]).zfill(2)+' '+str(now[3]).zfill(2)+':'+str(now[4]).zfill(2)
  387.      #print hoy
  388.      DescargaFTP(hoy)
  389.     listas = []
  390.      estaciones=['0000000001','0000000002','0000000003']
  391.      sensor = ['0068','0240','0255','0104']
  392.      Cnx = EMAS_DB()
  393.      for est in estaciones:
  394.        for sen in sensor:
  395.  
  396.         if sen == '0104':
  397.  
  398.           datos = Cnx.obtener(est, '0103', ahora)
  399.           dato1 = Cnx.obtener(est, '0104', ahora)
  400.           listas = datos, dato1
  401.           tipo = 'Direccion y velocidad'
  402.           unid = 'gn'
  403.           grf = Grafica(listas, tipo, sen, est, unid)
  404.         else:
  405.           datos = Cnx.obtener(est, sen, ahora)
  406.           if sen == '0068':
  407.            tipo = 'Temperatura'
  408.            unid = 'Grado Celsius'
  409.            grf1 = Grafica(datos, tipo, sen, est, unid)
  410.           if sen == '0255':
  411.            tipo = 'Presion Atmosferica'
  412.            unid = 'MB'
  413.            grf2 = Grafica(datos, tipo, sen, est, unid)
  414.           if sen == '0240':
  415.            tipo = 'Precipitacion'
  416.            unid = 'milimetros'
  417.            grf3 = Grafica(datos, tipo, sen, est, unid)
  418.      Cnx.close()
Advertisement
Add Comment
Please, Sign In to add comment