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