Работа с внешними сервисами вынесена в отдельный процесс
authorRoman Bazalevsky <rvb@rvb.name>
Thu, 15 Sep 2016 12:48:22 +0000 (15:48 +0300)
committerRoman Bazalevsky <rvb@rvb.name>
Thu, 15 Sep 2016 12:48:22 +0000 (15:48 +0300)
weathermon_cron [new file with mode: 0755]

diff --git a/weathermon_cron b/weathermon_cron
new file mode 100755 (executable)
index 0000000..30e21d8
--- /dev/null
@@ -0,0 +1,207 @@
+#!/usr/bin/python
+
+from pprint import pprint
+from os import system;
+
+import pycurl
+from urllib import urlencode
+from StringIO import StringIO
+
+import MySQLdb
+import ConfigParser
+
+import uuid
+
+def print_log(str):
+  global logging,debug
+  if debug>0:
+    print str
+  if logging == "on":
+    system("logger -t weathermon \""+str+"\"")
+
+def submit_narodmon():
+
+  global debug
+  
+  param = { 'ID':devid }
+
+  c = database.cursor()
+  c.execute(
+    '''
+select nm_id,avg(value) from meteo.ext_sensors e,meteo.sensor_values v
+where 
+e.sensor_id=v.sensor_id and e.param_id=v.parameter_id 
+and v.timestamp>DATE_SUB(CURRENT_TIMESTAMP(),INTERVAL 15 MINUTE)
+and e.nm_id is not null
+group by e.sensor_id,e.param_id,e.nm_id,e.owm_id
+    '''
+  )
+
+  queue=c.fetchall()
+
+  if debug>1:
+    pprint(queue)
+
+  for (sensor,value) in queue:
+    param[sensor] = value  
+  
+  if debug>1:
+    pprint (param)
+
+  url = "http://narodmon.ru/post.php"
+
+  try:
+      
+    response_buffer = StringIO()
+    curl = pycurl.Curl()
+                                              
+    curl.setopt(curl.URL, url)
+    curl.setopt(curl.WRITEFUNCTION, response_buffer.write)   
+    curl.setopt(curl.POST, 1)
+    curl.setopt(curl.POSTFIELDS, urlencode(param))
+                                                                  
+    curl.perform()
+    curl.close()  
+                                                                          
+    response_value = response_buffer.getvalue()
+                                                                              
+    print_log('Narodmon response: '+response_value)
+                                                                                  
+    return True
+                                                                                      
+  except:
+           
+    exc_type, exc_value, exc_traceback = sys.exc_info()
+    traceback.print_tb(exc_traceback, limit=1, file=sys.stdout)
+    traceback.print_exception(exc_type, exc_value, exc_traceback,
+                              limit=2, file=sys.stdout)  
+    return False  
+                                      
+def submit_owm():
+
+  global debug
+
+  url = "http://openweathermap.org/data/post"
+  params = {'name':owm_station, 'lat':owm_lat, 'long':owm_lon}
+
+  c = database.cursor()
+  c.execute(
+    '''
+    select owm_id,value from
+    (
+    SELECT sensor_id,parameter_id,avg(timestamp) timestamp,round(avg(value),1) value FROM meteo.sensor_values
+    where 
+    timestamp>=date_sub(current_timestamp(), INTERVAL 15 MINUTE)
+    group by sensor_id,parameter_id
+    ) v,meteo.ext_sensors e
+    where v.sensor_id=e.sensor_id and v.parameter_id=e.param_id
+    and owm_id is not null
+    '''
+  )
+
+  queue=c.fetchall()
+
+  if debug>1:
+    pprint(queue)
+
+  for (sensor,value) in queue:
+    params[sensor]=value
+  if debug>1:  
+    pprint (params)
+
+  try:
+
+    response_buffer = StringIO()
+    curl = pycurl.Curl()
+
+    curl.setopt(curl.URL, url)
+    curl.setopt(curl.USERPWD, '%s:%s' % (owmuser, owmpasswd))
+    curl.setopt(curl.WRITEFUNCTION, response_buffer.write)
+    curl.setopt(curl.POST, 1)
+    curl.setopt(curl.POSTFIELDS, urlencode(params))
+
+    curl.perform()
+    curl.close()
+    
+    response_value = response_buffer.getvalue()
+    
+    print_log('Openweathermap response: '+response_value)
+  
+    return True
+  
+  except:
+
+    exc_type, exc_value, exc_traceback = sys.exc_info()
+    traceback.print_tb(exc_traceback, limit=1, file=sys.stdout)
+    traceback.print_exception(exc_type, exc_value, exc_traceback,
+                                  limit=2, file=sys.stdout)
+    return False  
+
+def main():
+  submit_narodmon()
+  submit_owm()
+
+def init():
+
+  global logging,debug;
+  global devid;
+  global dbhost,dbuser,dbpasswd;
+  global owmuser,owmpasswd,owm_temp,owm_pres,owm_humi,owm_lat,owm_lon,owm_station;
+
+  try:
+
+    cfg = ConfigParser.RawConfigParser(allow_no_value=True)
+    cfg.readfp(open('/etc/weathermon.conf'))
+
+    try:
+      logging = cfg.get("logging","enabled")
+    except:
+      logging = None
+    try:
+      debug = int(cfg.get("logging","debug"))
+    except:
+      debug = 0
+
+    dbhost = cfg.get("mysql","host")
+    dbuser = cfg.get("mysql","user")
+    dbpasswd = cfg.get("mysql","passwd")
+    try:
+      narmon = cfg.get("narodmon","enable")
+    except:
+      narmon = 'off'  
+    try:
+      devid = cfg.get("narodmon","devid")
+    except:
+      devid = "{:0>12X}".format(getnode())   
+    try:  
+      owmuser = cfg.get("openweathermap","user")
+      owmpasswd = cfg.get("openweathermap",'passwd')
+    except:
+      owmuser = None  
+    if owmuser:
+      try:
+        owm_station=cfg.get("openweathermap","station")
+        owm_lat=cfg.get("openweathermap","lat")
+        owm_lon=cfg.get("openweathermap","lon")
+      except:
+        None  
+        
+    global database
+    database = MySQLdb.connect(host=dbhost,user=dbuser,passwd=dbpasswd,use_unicode=True,connect_timeout=10)
+    database.set_character_set('utf8')
+    c = database.cursor()
+    c.execute('SET NAMES utf8;')
+    print_log("Database connected...")
+    connected = True 
+  
+  except:
+
+    print_log("Cannot intialize system")
+    exit() 
+  
+if __name__ == "__main__":
+  import sys
+  reload(sys)
+  sys.setdefaultencoding('utf-8')
+  init()
+  main()