bc4eb88504a0d981f90d203c6d299c01c14d5a71
[weathermon.git] / weathermon_cron
1 #!/usr/bin/python
2
3 from pprint import pprint
4 from os import system;
5
6 import pycurl
7 from urllib import urlencode
8 from StringIO import StringIO
9
10 import MySQLdb
11 import ConfigParser
12
13 import uuid
14
15 debug = True
16
17 def print_log(str):
18   global logging,debug
19   if debug>0:
20     print str
21   if logging == "on":
22     system("logger -t weathermon \""+str+"\"")
23
24 def submit_narodmon():
25
26   global debug
27   
28   param = { 'ID':devid }
29
30   c = database.cursor()
31   c.execute(
32     '''
33 select nm_id,avg(value) from meteo.ext_sensors e,meteo.sensor_values v
34 where 
35 e.sensor_id=v.sensor_id and e.param_id=v.parameter_id 
36 and v.timestamp>DATE_SUB(CURRENT_TIMESTAMP(),INTERVAL 15 MINUTE)
37 and e.nm_id is not null
38 group by e.sensor_id,e.param_id,e.nm_id,e.owm_id
39     '''
40   )
41
42   queue=c.fetchall()
43
44   if debug>1:
45     pprint(queue)
46
47   for (sensor,value) in queue:
48     param[sensor] = value  
49   
50   if debug>1:
51     pprint (param)
52
53   url = "http://narodmon.ru/post.php"
54
55   try:
56       
57     response_buffer = StringIO()
58     curl = pycurl.Curl()
59                                               
60     curl.setopt(curl.URL, url)
61     curl.setopt(curl.WRITEFUNCTION, response_buffer.write)   
62     curl.setopt(curl.POST, 1)
63     curl.setopt(curl.POSTFIELDS, urlencode(param))
64                                                                   
65     curl.perform()
66     curl.close()  
67                                                                           
68     response_value = response_buffer.getvalue()
69                                                                               
70     print_log('Narodmon response: '+response_value)
71                                                                                   
72     return True
73                                                                                       
74   except:
75            
76     exc_type, exc_value, exc_traceback = sys.exc_info()
77     traceback.print_tb(exc_traceback, limit=1, file=sys.stdout)
78     traceback.print_exception(exc_type, exc_value, exc_traceback,
79                               limit=2, file=sys.stdout)  
80     return False  
81                                       
82 def submit_owm():
83
84   global debug
85
86   url = "http://openweathermap.org/data/post"
87   params = {'name':owm_station, 'lat':owm_lat, 'long':owm_lon}
88
89   c = database.cursor()
90   c.execute(
91     '''
92     select owm_id,value from
93     (
94     SELECT sensor_id,parameter_id,avg(timestamp) timestamp,round(avg(value),1) value FROM meteo.sensor_values
95     where 
96     timestamp>=date_sub(current_timestamp(), INTERVAL 15 MINUTE)
97     group by sensor_id,parameter_id
98     ) v,meteo.ext_sensors e
99     where v.sensor_id=e.sensor_id and v.parameter_id=e.param_id
100     and owm_id is not null
101     '''
102   )
103
104   queue=c.fetchall()
105
106   if debug>1:
107     pprint(queue)
108
109   for (sensor,value) in queue:
110     params[sensor]=value
111   if debug>1:  
112     pprint (params)
113
114   try:
115
116     response_buffer = StringIO()
117     curl = pycurl.Curl()
118
119     curl.setopt(curl.URL, url)
120     curl.setopt(curl.USERPWD, '%s:%s' % (owmuser, owmpasswd))
121     curl.setopt(curl.WRITEFUNCTION, response_buffer.write)
122     curl.setopt(curl.POST, 1)
123     curl.setopt(curl.POSTFIELDS, urlencode(params))
124
125     curl.perform()
126     curl.close()
127     
128     response_value = response_buffer.getvalue()
129     
130     print_log('Openweathermap response: '+response_value)
131   
132     return True
133   
134   except:
135
136     exc_type, exc_value, exc_traceback = sys.exc_info()
137     traceback.print_tb(exc_traceback, limit=1, file=sys.stdout)
138     traceback.print_exception(exc_type, exc_value, exc_traceback,
139                                   limit=2, file=sys.stdout)
140     return False  
141
142 def main():
143   submit_narodmon()
144   submit_owm()
145
146 def init():
147
148   global logging,debug;
149   global devid;
150   global dbhost,dbuser,dbpasswd;
151   global owmuser,owmpasswd,owm_temp,owm_pres,owm_humi,owm_lat,owm_lon,owm_station;
152
153   try:
154
155     cfg = ConfigParser.RawConfigParser(allow_no_value=True)
156     cfg.readfp(open('/etc/weathermon.conf'))
157
158     try:
159       logging = cfg.get("logging","enabled")
160     except:
161       logging = None
162     try:
163       debug = int(cfg.get("logging","debug"))
164     except:
165       debug = 0
166
167     dbhost = cfg.get("mysql","host")
168     dbuser = cfg.get("mysql","user")
169     dbpasswd = cfg.get("mysql","passwd")
170     try:
171       narmon = cfg.get("narodmon","enable")
172     except:
173       narmon = 'off'  
174     try:
175       devid = cfg.get("narodmon","devid")
176     except:
177       devid = "{:0>12X}".format(getnode())   
178     try:  
179       owmuser = cfg.get("openweathermap","user")
180       owmpasswd = cfg.get("openweathermap",'passwd')
181     except:
182       owmuser = None  
183     if owmuser:
184       try:
185         owm_station=cfg.get("openweathermap","station")
186         owm_lat=cfg.get("openweathermap","lat")
187         owm_lon=cfg.get("openweathermap","lon")
188       except:
189         None  
190         
191     global database
192     database = MySQLdb.connect(host=dbhost,user=dbuser,passwd=dbpasswd,use_unicode=True,connect_timeout=10)
193     database.set_character_set('utf8')
194     c = database.cursor()
195     c.execute('SET NAMES utf8;')
196     print_log("Database connected...")
197     connected = True 
198   
199   except:
200
201     print_log("Cannot intialize system")
202     exit() 
203   
204 if __name__ == "__main__":
205   import sys
206   reload(sys)
207   sys.setdefaultencoding('utf-8')
208   init()
209   main()