Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #! /usr/bin/env python
- import MySQLdb
- import ftplib
- #import numpy as n
- import pylab as p
- import datetime
- #import math
- from time import localtime #,mktime,strftime
- from matplotlib.ticker import OldScalarFormatter, FuncFormatter
- import matplotlib.text
- class EMAS_DB:
- db = None #inicializa la variable para el manejo de la conexion a la BD
- def __init__(self):
- try:
- self.db = MySQLdb.connect(user='root', passwd='lenercabeza', db='BD_Emas')
- #self.db = MySQLdb.connect(host='172.25.1.16', user='root', passwd='jupAja02', db='BD_Emas')
- self.cur = self.db.cursor(MySQLdb.cursors.DictCursor)
- except MySQLdb.Error, (errno, strerror):
- print "(%s): %s" % (errno, strerror)
- def verificar(self, ID, sensor, fecha):
- str_ = "SELECT ID, sensor, fecha FROM datos_EMAS WHERE ID = %s AND sensor = %s AND fecha = %s"
- self.cur.execute(str_, (ID, sensor, fecha))
- resl = self.cur.fetchone() #fetch the query
- if resl:
- return True
- else: return False
- def insertar(self, ID, sensor, fecha, dato):
- str_ = "INSERT INTO datos_EMAS VALUES (%s, %s, %s, %s)"
- self.cur.execute(str_, (ID, sensor, fecha, dato))
- def obtener(self, ID, sensor, fecha):
- tiempo = []
- valor = []
- if sensor == '0068' or sensor == '0255':
- str_ = "SELECT ID, sensor, fecha, valor FROM datos_EMAS WHERE ID = %s AND sensor = %s AND fecha <= %s ORDER BY fecha DESC LIMIT 24"
- self.cur.execute(str_, (ID, sensor, fecha ))
- while True:
- row_ = self.cur.fetchone()
- if row_:
- fechReg = row_['fecha']
- tiempo.append(fechReg)
- valor.append(round(row_['valor'], 2))
- else: break
- tiempo.reverse()
- valor.reverse()
- tiempo = p.array(tiempo)
- #print tiempo
- #print valor
- else:
- 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"
- self.cur.execute(str_, (ID, sensor, fecha ))
- while True:
- row_ = self.cur.fetchone()
- if row_:
- fechReg = row_['fecha']
- tiempo.append(fechReg)
- valor.append(round(row_['valor'], 2))
- else: break
- tiempo.reverse()
- valor.reverse()
- tiempo = p.array(tiempo)
- #print tiempo
- #print valor
- return tiempo, valor
- def close(self):
- self.cur.close()
- self.db.close()
- class Grafica:
- def __init__(self, datos, tipo, sensor, est, unidad):
- p.rcParams['legend.fontsize'] = 9.5
- locFmt = p.DateFormatter('%m/%d %H:00')
- now = localtime()
- hoy = str(now[0]) +'-'+ str(now[1]).zfill(2)+'-'+ str(now[2]).zfill(2)
- if sensor == '0240':
- ax = p.subplot(111)
- arrFecha = datos[0]
- arrValor = datos[1]
- ciudad = BuscarCiudad(est)
- pos_Anota = valorMaximo(sensor,arrValor)
- anota = select_Anotacion(sensor,arrValor)
- rang = ConversionFecha(arrFecha)
- p.ylabel(tipo +' ('+ unidad+')', color='b')
- p.title(tipo+'\n'+ciudad+' '+'Fecha: '+hoy, size=14, color='#aaaaaa')
- #p.set_xticks(array(range(0, size(arrFecha))) + 0.35)
- p.plot(arrFecha, arrValor)
- p.xlabel('Tiempo 24 horas'+'\n'+'(mes/dia hora)', color='#aaaaaa')
- #p.ylim((min(arrValor),max(arrValor)))
- if max(arrValor) == 0:
- p.axis([min(arrFecha), max(arrFecha), min(arrValor), max(arrValor)+1])
- p.text(0.5, 0.5,'no se registran datos hasta el momento',horizontalalignment='center',verticalalignment='center', transform = ax.transAxes, size=14, color='blue')
- else:
- p.axis([min(arrFecha), max(arrFecha), min(arrValor)-0.5, max(arrValor)+0.5])
- 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)
- loc = p.HourLocator(byhour=range(min(rang), max(rang), 4))
- ax.xaxis.set_major_locator(loc)
- ax.xaxis.set_major_formatter(locFmt)
- ax.yaxis.set_major_formatter(OldScalarFormatter())
- lbx = ax.get_xticklabels()
- lby = ax.get_yticklabels()
- p.setp(lbx, fontsize=8, color='#aaaaaa')
- p.setp(lby, fontsize=8, color='b')
- fich=tipo[0:4]+est[8:]
- p.grid(True)
- p.savefig(fich+'.png')
- p.close()
- #p.show()
- if sensor == '0068' or sensor == '0255':
- ax = p.subplot(111)
- arrFecha = datos[0]
- arrValor = datos[1]
- rang = ConversionFecha(arrFecha)
- ciudad = BuscarCiudad(est)
- pos_Anota = valorMaximo(sensor,arrValor)
- anota = select_Anotacion(sensor,arrValor)
- #print arrFecha
- #print arrValor
- p.ylabel(tipo +' ('+ unidad+')', color='b')
- p.title(tipo+'\n'+ciudad+' '+'Fecha: '+hoy, size=14, color='#aaaaaa')
- line, = p.plot(arrFecha, arrValor)
- line.set_color('b')
- #line.set_marker('o')
- #yloc=range(min(arrValor), max(arrValor), 2)
- #p.yticks(range(min(arrValor), max(arrValor), 1.2))
- loc = p.HourLocator(byhour=range(min(rang), max(rang), 4))
- #loc = p.HourLocator(byhour=range(0,23,6))
- p.axis([min(arrFecha), max(arrFecha), min(arrValor)-0.5, max(arrValor)+0.5])
- #ax.yaxis.set_major_locator(yloc)
- ax.xaxis.set_major_locator(loc)
- ax.xaxis.set_major_formatter(locFmt)
- ax.yaxis.set_major_formatter(OldScalarFormatter())
- ax.annotate(str(pos_Anota[2]), xy=(arrFecha[pos_Anota[0]], pos_Anota[1]), size=10, color='r')
- 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)
- #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')
- lbx = ax.get_xticklabels()
- p.xlabel('Tiempo 24 horas'+'\n'+'(mes/dia hora)', color='#aaaaaa')
- lby = ax.get_yticklabels()
- #p.ylim((min(arrValor),max(arrValor)))
- p.setp(lbx, fontsize=8, color='#aaaaaa')
- p.setp(lby, fontsize=8, color='b')
- #p.text(max(arrFecha)+.05, max(arrFecha), r'$\bar H_{20.0}$' ,fontsize=12)
- #p.legend(nota ,'maxima', loc='best')
- fich=tipo[0:4]+est[8:]
- p.grid(True)
- p.savefig(fich+'.png')
- p.close()
- #p.show()
- if sensor == '0104':
- ax = p.subplot(111)
- list1 = datos[0]
- list2 = datos[1]
- ciudad = BuscarCiudad(est)
- p.ylabel('velocidad (nudos)', color='b')
- #p.grid(True)
- p.title(tipo+' del viento'+'\n'+ciudad+' '+'Fecha:'+hoy,size=14,weight='bold', color='#aaaaaa')
- arrFecha = list1[0]
- arrValor = list1[1]
- rang = ConversionFecha(arrFecha)
- lineV, = p.plot(arrFecha, arrValor)
- lineV.set_color('b')
- lineV.set_markersize(5)
- lineV.set_linestyle('-')
- lineV.set_markerfacecolor('b')
- #ax.axis([min(arrFecha), max(arrFecha), min(arrValor)-0.5, max(arrValor)+0.5])
- #ax.xaxis.set_major_locator(loc)
- ax.xaxis.set_major_formatter(locFmt)
- lbx = ax.get_xticklabels()
- lby = ax.get_yticklabels()
- p.setp(lbx, fontsize=8, color='#aaaaaa')
- p.xlabel('Tiempo 24 horas'+'\n'+'(mes/dia hora)', color='#aaaaaa')
- p.setp(lby, fontsize=8, color='b')
- ax2 = p.twinx()
- arrFecha1 = list2[0]
- arrValor1 = list2[1]
- p.ylabel('Direccion (Grados)', color='r')
- lineD, = p.plot(arrFecha1, arrValor1)
- lineD.set_color('r')
- lineD.set_markersize(5)
- lineD.set_linestyle('--')
- lineD.set_markerfacecolor('r')
- #loc = p.HourLocator(byhour=range(0,23,6))
- loc = p.HourLocator(byhour=range(min(rang), max(rang), 4))
- p.axis([min(arrFecha1), max(arrFecha1), min(arrValor1), max(arrValor1)])
- ax2.xaxis.set_major_locator(loc)
- ax2.xaxis.set_major_formatter(locFmt)
- lbx = ax2.get_xticklabels()
- lby = ax2.get_yticklabels()
- p.setp(lbx, fontsize=8, color='#aaaaaa')
- p.xlabel('Tiempo 24 horas'+'\n'+'(mes/dia hora)', color='#aaaaaa')
- p.setp(lby, fontsize=8, color='r')
- p.legend((lineD,lineV),('Direccion','Velocidad'), loc='best')
- #p.show()
- fich=tipo[0:4]+est[8:]
- p.grid(True)
- p.savefig(fich+'.png') #,dpi=70
- p.close()
- #print arrFecha1
- #print arrValor1
- def select_Anotacion(sens,listV):
- num = 0.0
- if max(listV)== 0:
- anota = 'no registra datos'
- else :
- if sens == '0068':
- anota = 'maxima temperatura en las ultimas 24 horas'
- num = max(listV)
- if sens == '0255':
- anota = 'minima presion en las ultimas 24 horas'
- num = min(listV)
- if sens == '0240':
- anota = 'max_precipitacion en las ultimas 24 horas'
- num = max(listV)
- return anota, num
- def valorMaximo(sens,listV):
- #esta funcion es buscar la mejor posicion de la anotacion para avisar el valor maximo o minimo de las graficas
- if sens != '0255':
- valor = max(listV)
- posicion_Y=valor
- posicion = 0
- for pV in listV:
- if pV == valor:
- break
- posicion = posicion+1
- #if posicion >= 8:
- # posiciontexto_X=posicion-1
- #else: posiciontexto_X = posicion+1
- else:
- valor = min(listV)
- posicion_Y=valor-0.1
- posicion = 0
- for pV in listV:
- if pV == valor:
- break
- posicion = posicion+1
- #if posicion >= 8:
- #posiciontexto_X=posicion-1
- #else: posiciontexto_X = posicion+1
- return posicion,posicion_Y, valor
- def BuscarCiudad(est):
- ciudad = 'Covenas'
- if est == '0000000001':
- ciudad = 'Covenas'
- if est == '0000000002':
- ciudad = 'Mantuntugo'
- if est == '0000000003':
- ciudad = 'Providencia'
- return ciudad
- def ConversionFecha(fechas):
- rango = []
- hora = []
- for dfecha in fechas:
- hora.append(str(dfecha)[11:13])
- for sfecha in hora:
- rango.append(int(sfecha))
- return rango
- def CapturarDATOS(archMIS, Cnx):
- #escanea los ficheros .MIS para extraer sus datos
- fn = open(archMIS, 'r')
- while True:
- line = fn.readline().split('\t')
- ta = len(line[0])
- #print ta
- #print line
- if len(line[0])!= 0:
- if len(line[0])==85:
- ID = line[0][9:19]
- Sensor=line[0][37:41]
- #print ID
- #print Sensor
- else:
- fecha = line[0][0:4]+'-'+line[0][4:6]+'-'+line[0][6:8]+' '+line[0][9:17]
- dato = line[0][18:]
- if not Cnx.verificar(ID, Sensor, fecha):
- Cnx.insertar(ID,Sensor,fecha, dato)
- else: break
- def DescargaFTP(hoy):
- #descarga los ficheros .MIS por via FTP
- Emas = ['CB144456','CB1462BA','CB145720']
- try:
- ftp = ftplib.FTP("172.25.19.17")
- ftp.login(user="cioh", passwd="lenercabeza")
- ftp.cwd(hoy)
- Cnx = EMAS_DB()
- for ID in Emas:
- ftpfile = ftp.nlst(ID + ' ' + hoy + '*')
- for archMIS in ftpfile:
- ftp.retrbinary('RETR ' + archMIS, open(archMIS,'wb').write)
- #ftpfile.append('CB144456 20100121 065149359' + '.MIS')
- CapturarDATOS(archMIS, Cnx)
- Cnx.close()
- except ftplib.error_perm, (error):
- print "Error en la conexion: %s" % (error)
- if __name__ == '__main__':
- now = localtime()
- hoy = str(now[0]) + str(now[1]).zfill(2) + str(now[2]).zfill(2)
- ahora = str(now[0]) +'-'+str(now[1]).zfill(2) +'-'+ str(now[2]).zfill(2)+' '+str(now[3]).zfill(2)+':'+str(now[4]).zfill(2)
- #print hoy
- DescargaFTP(hoy)
- listas = []
- estaciones=['0000000001','0000000002','0000000003']
- sensor = ['0068','0240','0255','0104']
- Cnx = EMAS_DB()
- for est in estaciones:
- for sen in sensor:
- if sen == '0104':
- datos = Cnx.obtener(est, '0103', ahora)
- dato1 = Cnx.obtener(est, '0104', ahora)
- listas = datos, dato1
- tipo = 'Direccion y velocidad'
- unid = 'gn'
- grf = Grafica(listas, tipo, sen, est, unid)
- else:
- datos = Cnx.obtener(est, sen, ahora)
- if sen == '0068':
- tipo = 'Temperatura'
- unid = 'Grado Celsius'
- grf1 = Grafica(datos, tipo, sen, est, unid)
- if sen == '0255':
- tipo = 'Presion Atmosferica'
- unid = 'mb'
- grf2 = Grafica(datos, tipo, sen, est, unid)
- if sen == '0240':
- tipo = 'Precipitacion'
- unid = 'milimetros'
- grf3 = Grafica(datos, tipo, sen, est, unid)
- Cnx.close()
Advertisement
Add Comment
Please, Sign In to add comment