m0n0lithic

Emas1.py

Apr 21st, 2014
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 13.71 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(host='172.25.1.16', 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.      def close(self):
  87.         self.cur.close()
  88.         self.db.close()
  89.  
  90. class Grafica:
  91.  
  92.      def __init__(self, datos, tipo, sensor, est, unidad):
  93.  
  94.  
  95.          p.rcParams['legend.fontsize'] = 9.5
  96.          locFmt = p.DateFormatter('%m/%d %H:00')
  97.  
  98.          now = localtime()
  99.          hoy = str(now[0]) +'-'+ str(now[1]).zfill(2)+'-'+ str(now[2]).zfill(2)
  100.  
  101.          if sensor == '0240':
  102.  
  103.  
  104.             ax = p.subplot(111)
  105.             arrFecha = datos[0]
  106.             arrValor = datos[1]
  107.  
  108.             ciudad = BuscarCiudad(est)
  109.             pos_Anota = valorMaximo(sensor,arrValor)
  110.             anota = select_Anotacion(sensor,arrValor)
  111.             rang = ConversionFecha(arrFecha)
  112.  
  113.             p.ylabel(tipo +' ('+ unidad+')', color='b')
  114.             p.title(tipo+'\n'+ciudad+'  '+'Fecha: '+hoy, size=14, color='#aaaaaa')
  115.             #p.set_xticks(array(range(0, size(arrFecha))) + 0.35)
  116.             p.plot(arrFecha, arrValor)
  117.  
  118.             p.xlabel('Tiempo 24 horas'+'\n'+'(mes/dia hora)', color='#aaaaaa')
  119.  
  120.             #p.ylim((min(arrValor),max(arrValor)))
  121.  
  122.  
  123.  
  124.             if max(arrValor) == 0:
  125.               p.axis([min(arrFecha), max(arrFecha), min(arrValor), max(arrValor)+1])
  126.               p.text(0.5, 0.5,'no se registran datos hasta el momento',horizontalalignment='center',verticalalignment='center',  transform = ax.transAxes, size=14, color='blue')
  127.  
  128.             else:
  129.               p.axis([min(arrFecha), max(arrFecha), min(arrValor)-0.5, max(arrValor)+0.5])
  130.               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)
  131.  
  132.  
  133.             loc = p.HourLocator(byhour=range(min(rang), max(rang), 4))
  134.             ax.xaxis.set_major_locator(loc)
  135.             ax.xaxis.set_major_formatter(locFmt)
  136.             ax.yaxis.set_major_formatter(OldScalarFormatter())
  137.             lbx = ax.get_xticklabels()
  138.             lby = ax.get_yticklabels()
  139.             p.setp(lbx, fontsize=8, color='#aaaaaa')
  140.             p.setp(lby, fontsize=8, color='b')
  141.  
  142.             fich=tipo[0:4]+est[8:]
  143.             p.grid(True)
  144.             p.savefig(fich+'.png')
  145.             p.close()
  146.             #p.show()
  147.          if sensor == '0068' or sensor == '0255':
  148.  
  149.            ax = p.subplot(111)
  150.            arrFecha = datos[0]
  151.            arrValor = datos[1]
  152.            rang = ConversionFecha(arrFecha)
  153.  
  154.            ciudad = BuscarCiudad(est)
  155.            pos_Anota = valorMaximo(sensor,arrValor)
  156.            anota = select_Anotacion(sensor,arrValor)
  157.            #print arrFecha
  158.            #print arrValor
  159.  
  160.  
  161.            p.ylabel(tipo +' ('+ unidad+')', color='b')
  162.            p.title(tipo+'\n'+ciudad+'  '+'Fecha: '+hoy, size=14, color='#aaaaaa')
  163.  
  164.  
  165.  
  166.            line, =  p.plot(arrFecha, arrValor)
  167.            line.set_color('b')
  168.            #line.set_marker('o')
  169.            #yloc=range(min(arrValor), max(arrValor), 2)
  170.            #p.yticks(range(min(arrValor), max(arrValor), 1.2))
  171.            loc = p.HourLocator(byhour=range(min(rang), max(rang), 4))
  172.            #loc = p.HourLocator(byhour=range(0,23,6))
  173.            p.axis([min(arrFecha), max(arrFecha), min(arrValor)-0.5, max(arrValor)+0.5])
  174.            #ax.yaxis.set_major_locator(yloc)
  175.            ax.xaxis.set_major_locator(loc)
  176.            ax.xaxis.set_major_formatter(locFmt)
  177.            ax.yaxis.set_major_formatter(OldScalarFormatter())
  178.            ax.annotate(str(pos_Anota[2]), xy=(arrFecha[pos_Anota[0]], pos_Anota[1]), size=10, color='r')
  179.            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)
  180.  
  181.            #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')
  182.            lbx = ax.get_xticklabels()
  183.            p.xlabel('Tiempo 24 horas'+'\n'+'(mes/dia hora)', color='#aaaaaa')
  184.            lby = ax.get_yticklabels()
  185.            #p.ylim((min(arrValor),max(arrValor)))
  186.            p.setp(lbx, fontsize=8, color='#aaaaaa')
  187.            p.setp(lby, fontsize=8, color='b')
  188.  
  189.  
  190.            #p.text(max(arrFecha)+.05, max(arrFecha), r'$\bar H_{20.0}$' ,fontsize=12)
  191.            #p.legend(nota ,'maxima', loc='best')
  192.            fich=tipo[0:4]+est[8:]
  193.            p.grid(True)
  194.            p.savefig(fich+'.png')
  195.            p.close()
  196.            #p.show()
  197.          if sensor == '0104':
  198.  
  199.            ax = p.subplot(111)
  200.  
  201.            list1 = datos[0]
  202.            list2 = datos[1]
  203.            ciudad = BuscarCiudad(est)
  204.  
  205.            p.ylabel('velocidad (nudos)', color='b')
  206.            #p.grid(True)
  207.            p.title(tipo+' del viento'+'\n'+ciudad+'  '+'Fecha:'+hoy,size=14,weight='bold', color='#aaaaaa')
  208.  
  209.            arrFecha = list1[0]
  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)
  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.  
  346.           Sensor=line[0][37:41]
  347.           #print ID
  348.           #print Sensor
  349.         else:
  350.           fecha = line[0][0:4]+'-'+line[0][4:6]+'-'+line[0][6:8]+' '+line[0][9:17]
  351.           dato = line[0][18:]
  352.           if not Cnx.verificar(ID, Sensor, fecha):
  353.             Cnx.insertar(ID,Sensor,fecha, dato)
  354.      else: break
  355.  
  356.  
  357. def DescargaFTP(hoy):
  358.     #descarga los ficheros .MIS por via FTP
  359.     Emas = ['CB144456','CB1462BA','CB145720']
  360.     try:
  361.  
  362.      ftp = ftplib.FTP("172.25.19.17")
  363.      ftp.login(user="cioh", passwd="lenercabeza")
  364.      ftp.cwd(hoy)
  365.      Cnx = EMAS_DB()
  366.      for ID in Emas:
  367.  
  368.        ftpfile = ftp.nlst(ID + ' ' + hoy + '*')
  369.        for archMIS in ftpfile:
  370.            ftp.retrbinary('RETR ' + archMIS, open(archMIS,'wb').write)
  371.            #ftpfile.append('CB144456 20100121 065149359' + '.MIS')      
  372.            CapturarDATOS(archMIS, Cnx)
  373.      Cnx.close()
  374.     except ftplib.error_perm, (error):
  375.                 print "Error en la conexion: %s" % (error)
  376.  
  377.  
  378.  
  379. if __name__ == '__main__':
  380.  
  381.      now = localtime()
  382.      hoy = str(now[0]) + str(now[1]).zfill(2) + str(now[2]).zfill(2)
  383.      ahora = str(now[0]) +'-'+str(now[1]).zfill(2) +'-'+ str(now[2]).zfill(2)+' '+str(now[3]).zfill(2)+':'+str(now[4]).zfill(2)
  384.      #print hoy
  385.      DescargaFTP(hoy)
  386.      listas = []
  387.      estaciones=['0000000001','0000000002','0000000003']
  388.      sensor = ['0068','0240','0255','0104']
  389.      Cnx = EMAS_DB()
  390.      for est in estaciones:
  391.        for sen in sensor:
  392.  
  393.         if sen == '0104':
  394.  
  395.           datos = Cnx.obtener(est, '0103', ahora)
  396.           dato1 = Cnx.obtener(est, '0104', ahora)
  397.           listas = datos, dato1
  398.           tipo = 'Direccion y velocidad'
  399.           unid = 'gn'
  400.           grf = Grafica(listas, tipo, sen, est, unid)
  401.         else:
  402.           datos = Cnx.obtener(est, sen, ahora)
  403.           if sen == '0068':
  404.            tipo = 'Temperatura'
  405.            unid = 'Grado Celsius'
  406.            grf1 = Grafica(datos, tipo, sen, est, unid)
  407.           if sen == '0255':
  408.            tipo = 'Presion Atmosferica'
  409.            unid = 'mb'
  410.            grf2 = Grafica(datos, tipo, sen, est, unid)
  411.           if sen == '0240':
  412.            tipo = 'Precipitacion'
  413.            unid = 'milimetros'
  414.            grf3 = Grafica(datos, tipo, sen, est, unid)
  415.      Cnx.close()
Advertisement
Add Comment
Please, Sign In to add comment