5 from os import listdir,system
6 from os.path import isfile, join
8 from pprint import pprint
10 from termios import tcflush, TCIOFLUSH
12 from time import sleep,time
14 from uuid import getnode
16 from hashlib import md5
23 from urllib import urlencode
24 from StringIO import StringIO
26 searchpath = '/dev/serial/by-id/'
31 external_submit_interval = 320
32 expire_interval = 1200
44 files = listdir(searchpath)
47 return join(searchpath,f)
52 ser = serial.Serial(path,baud,timeout)
54 tcflush(ser,TCIOFLUSH);
62 def read_loop(ser,callback):
70 except KeyboardInterrupt:
79 system("logger -t weathermon \""+str+"\"")
81 def submit_narodmon(queue):
83 param = { 'ID':"{:X}".format(getnode())}
88 value = submit_queue[sensor]['val']
89 timestamp = submit_queue[sensor]['timestamp']
90 digest = md5(sensor).hexdigest()[:18]
91 param[digest] = value;
95 url = "http://narodmon.ru/post.php"
99 response_buffer = StringIO()
102 curl.setopt(curl.URL, url)
103 curl.setopt(curl.WRITEFUNCTION, response_buffer.write)
104 curl.setopt(curl.POST, 1)
105 curl.setopt(curl.POSTFIELDS, urlencode(param))
110 response_value = response_buffer.getvalue()
112 print_log('Content: '+response_value)
118 exc_type, exc_value, exc_traceback = sys.exc_info()
119 traceback.print_tb(exc_traceback, limit=1, file=sys.stdout)
120 traceback.print_exception(exc_type, exc_value, exc_traceback,
121 limit=2, file=sys.stdout)
124 def submit_owm(queue):
126 url = "http://openweathermap.org/data/post"
127 params = {'name':owm_station, 'lat':owm_lat, 'long':owm_lon}
132 params['temp'] = queue[owm_temp]['val']
133 params['pressure'] = queue[owm_pres]['val']
134 params['humidity'] = queue[owm_humi]['val']
138 response_buffer = StringIO()
141 curl.setopt(curl.URL, url)
142 curl.setopt(curl.USERPWD, '%s:%s' % (owmuser, owmpasswd))
143 curl.setopt(curl.WRITEFUNCTION, response_buffer.write)
144 curl.setopt(curl.POST, 1)
145 curl.setopt(curl.POSTFIELDS, urlencode(params))
150 response_value = response_buffer.getvalue()
152 print_log('Content: '+response_value)
158 exc_type, exc_value, exc_traceback = sys.exc_info()
159 traceback.print_tb(exc_traceback, limit=1, file=sys.stdout)
160 traceback.print_exception(exc_type, exc_value, exc_traceback,
161 limit=2, file=sys.stdout)
167 for key in submit_queue:
168 if submit_queue[key]['timestamp'] < time()-expire_interval:
169 print_log("Expired value for "+key)
174 def submit_data(sensor_type,sensor_id,sensor_param,param_value):
177 c = database.cursor()
178 c.execute('CALL meteo.submit_value(%s,%s,%s,%s,NULL)', (sensor_type,sensor_id,sensor_param,param_value))
180 submit_queue[sensor_type+'.'+sensor_id+'.'+sensor_param]={'val':param_value,'timestamp':time()}
181 if time()>submit_time+external_submit_interval:
182 if submit_narodmon(submit_queue):
184 submit_owm(submit_queue)
185 print_log('Purging queue...')
190 def process_str(str):
191 print_log("Received: "+str)
193 msg_type, msg_body = str.split(':')
197 if msg_type == 'STATUS':
198 print_log('Status: '+msg_body)
199 elif msg_type == 'ERROR':
200 print_log('Error: '+ msg_body)
201 elif msg_type == 'SENSOR':
202 sens = msg_body.split(',')
207 key,value = rec.split('=')
218 if sensor[key] is not None:
219 print_log('Type = '+sensor_type+', ID = '+sensor_id+', Param = '+key+', Value = '+sensor[key])
220 submit_data(sensor_type,sensor_id,key,sensor[key])
222 print_log('Error: got empty parameter value for '+sensor_type+'.'+sensor_id+'.'+key)
224 print_log('Exception processing...')
225 exc_type, exc_value, exc_traceback = sys.exc_info()
226 traceback.print_tb(exc_traceback, limit=1, file=sys.stdout)
227 traceback.print_exception(exc_type, exc_value, exc_traceback,
228 limit=5, file=sys.stdout)
241 ser = open_port(path)
242 read_loop(ser,process_str)
253 database = MySQLdb.connect(host=dbhost,user=dbuser,passwd=dbpasswd,use_unicode=True,connect_timeout=10)
254 database.set_character_set('utf8')
255 c = database.cursor()
256 c.execute('SET NAMES utf8;')
257 print_log("Database connected...")
262 print_log("Error connecting database")
270 cfg = ConfigParser.RawConfigParser(allow_no_value=True)
271 cfg.readfp(open('/etc/weathermon.conf'))
272 dbhost = cfg.get("mysql","host")
273 dbuser = cfg.get("mysql","user")
274 dbpasswd = cfg.get("mysql","passwd")
276 path = cfg.get("serial","port");
280 serialnum = cfg.get("serial","id")
284 logging = cfg.get("logging","enabled")
287 owmuser = cfg.get("openweathermap","user")
288 owmpasswd = cfg.get("openweathermap",'passwd')
290 owm_temp = cfg.get("openweathermap",'temp')
291 owm_pres = cfg.get("openweathermap",'pres')
292 owm_humi = cfg.get("openweathermap",'humi')
293 owm_lat = cfg.get("openweathermap",'lat')
294 owm_lon = cfg.get("openweathermap",'lon')
295 owm_station = cfg.get("openweathermap",'station')
300 print_log("Cannot intialize system")
303 if __name__ == "__main__":
306 sys.setdefaultencoding('utf-8')