Merge branch 'master' of estia:weathermon
authorRoman Bazalevskiy <rvb@rvb.name>
Sat, 3 Sep 2016 18:32:52 +0000 (21:32 +0300)
committerRoman Bazalevskiy <rvb@rvb.name>
Sat, 3 Sep 2016 18:32:52 +0000 (21:32 +0300)
15 files changed:
mysql/meteo_routines.sql
mysql/meteo_units.sql
mysql/tmp_sensor_values.sql [new file with mode: 0644]
systemd/weathermon.service [new file with mode: 0644]
weathermon [new file with mode: 0755]
weathermon.lua
weathermon.sh [deleted file]
weathermon.uci
web/archive.php
web/config_local.php
web/graphs.php
web/image.php
web/image_minmax.php
web/index.php
web/send.php

index bf72780f001753081afaa6adb04b05ccddc7a6a0..5f819b3f90afaf6db21623827ca65cf3c97b9267 100644 (file)
@@ -128,4 +128,55 @@ DELIMITER ;
 /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
 /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
 
+DELIMITER $$
+CREATE DEFINER=`admin`@`%` PROCEDURE `Reduce`(pUpTo datetime,pRID integer)
+BEGIN
+  declare lNewRID integer;
+  declare lSeconds integer;
+
+  declare lStart,lEnd timestamp;
+
+  set lNewRID:=pRID+1;
+  select seconds into lSeconds from reduce_ranges where id=lNewRID;
+
+  delete from tmp_sensor_values;
+
+  insert into tmp_sensor_values(sensor_id,parameter_id,timestamp,value)
+  select sensor_id,parameter_id,from_unixtime(avg(unix_timestamp(timestamp))),avg(value) 
+    from sensor_values
+    where timestamp<pUpTo and reduced=pRID
+    group by sensor_id,parameter_id,floor(unix_timestamp(timestamp)/lSeconds);
+
+  select date(min(timestamp)),date(max(timestamp)) into lStart,lEnd from tmp_sensor_values;
+
+  delete from sensor_values where timestamp<pUpTo and reduced=pRID;
+
+  insert into sensor_values(sensor_id,parameter_id,timestamp,value,reduced)
+  select sensor_id,parameter_id,timestamp,value,lNewRID from tmp_sensor_values;
+
+  delete from sensors_ranges
+  where day>=lStart and day<=lEnd;
+
+  insert into sensors_ranges(day,sensor,parameter,timestamp,min,max)
+  select date(timestamp),sensor_id,parameter_id,max(timestamp),min(value),max(value)
+  from sensor_values
+  where timestamp>=lStart and timestamp<date_add(lEnd, interval 1 day)
+  group by date(timestamp),sensor_id,parameter_id;
+
+  delete from tmp_sensor_values; 
+
+END$$
+DELIMITER ;
+
+DELIMITER $$
+CREATE DEFINER=`admin`@`%` PROCEDURE `Cron_Reduce`(pMonths integer)
+BEGIN
+  declare lTime datetime;
+  select date_sub(date_format(now(),'%Y-%m-01'), interval pMonths month) into lTime;
+  call meteo.reduce(lTime,0);
+END$$
+DELIMITER ;
+
+
+
 -- Dump completed on 2014-09-25 14:45:45
index 110b39d0de86224f09da057571b034e6e23db3ab..76d81aa6add48d768899d6738b5271d253411cb0 100644 (file)
@@ -27,6 +27,7 @@ CREATE TABLE `units` (
   `name` varchar(32) CHARACTER SET utf8 NOT NULL,
   `name_short` varchar(8) CHARACTER SET utf8 NOT NULL,
   `unit_group` int(11) NOT NULL,
+  `prec` int(11) DEFAULT NULL,
   PRIMARY KEY (`id`),
   KEY `fk_units_group_idx` (`unit_group`),
   CONSTRAINT `fk_units_group` FOREIGN KEY (`unit_group`) REFERENCES `unit_groups` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
diff --git a/mysql/tmp_sensor_values.sql b/mysql/tmp_sensor_values.sql
new file mode 100644 (file)
index 0000000..696c073
--- /dev/null
@@ -0,0 +1,8 @@
+CREATE TABLE `tmp_sensor_values` (
+  `id` int(11) NOT NULL DEFAULT '0',
+  `sensor_id` int(11) NOT NULL,
+  `timestamp` datetime NOT NULL,
+  `value` float NOT NULL,
+  `parameter_id` int(11) NOT NULL,
+  `reduced` int(11) DEFAULT '0'
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;
diff --git a/systemd/weathermon.service b/systemd/weathermon.service
new file mode 100644 (file)
index 0000000..6212a08
--- /dev/null
@@ -0,0 +1,14 @@
+[Unit]
+Description=Weather Station Monitor 
+Requires=network.target mysql.service
+After=network.target
+
+[Service]
+User=root
+Type=simple
+ExecStart=/usr/local/bin/weathermon
+Restart=always
+RestartSec=30s
+
+[Install]
+WantedBy=multi-user.target
diff --git a/weathermon b/weathermon
new file mode 100755 (executable)
index 0000000..19688cb
--- /dev/null
@@ -0,0 +1,446 @@
+#!/usr/bin/python
+
+import serial
+
+from os import listdir,system
+from os.path import isfile, join
+
+from pprint import pprint
+
+from termios import tcflush, TCIOFLUSH
+
+from time import sleep,time
+
+from uuid import getnode
+
+from hashlib import md5
+
+import socket
+
+import sys,traceback
+
+import pycurl
+from urllib import urlencode
+from StringIO import StringIO
+
+searchpath = '/dev/serial/by-id/'
+path = None
+baud = None
+timeout = None
+
+proc = None
+
+external_submit_interval = 320
+owm_submit_interval = 320
+expire_interval = 1200
+submit_time = time()
+submit_time_owm = time()
+
+import MySQLdb
+import ConfigParser
+
+import thread
+from threading import Timer
+
+def find_port():
+
+  global serial_num
+  global path
+
+  files = listdir(searchpath)
+  for f in files:
+    if serialnum in f:
+      return join(searchpath,f)
+  return None
+
+def open_port(path):
+
+  global proc, debug
+
+  if debug>0:
+    print "Opening path "+path
+
+  if path == "-":
+    return sys.stdin
+
+  if path[0] == "=":
+    import subprocess
+    sleep(3)
+    command=path[1:]
+    try:
+      command,args=command.split(' ',1)
+      proc = subprocess.Popen([command,args],stdout=subprocess.PIPE)
+    except:
+      proc = subprocess.Popen([command],stdout=subprocess.PIPE)
+    import subprocess
+    return proc.stdout
+
+  ser = serial.Serial(path,baud,timeout=timeout)
+  if ser.portstr:
+    tcflush(ser,TCIOFLUSH);
+  return ser
+  
+def read_port(ser):
+
+  try: 
+    timeout_timer = Timer(timeout, thread.interrupt_main)
+    timeout_timer.start()
+
+    line=''
+    while line=='':
+      line = ser.readline()
+      line = line.strip()
+      
+    return line
+    
+  except KeyboardInterrupt:
+    return "<<TIMEOUT>>"
+  finally:
+    timeout_timer.cancel()
+  
+def read_loop(ser,callback):
+
+  global proc
+
+  while True:
+  
+    try:
+      line=read_port(ser)
+      if line=="<<TIMEOUT>>":
+        if debug>0:
+          print "Reopening port..."
+          print line
+        ser.close()
+        if proc:
+          try:
+            if debug>0:
+              print "Terminating process..."
+            proc.terminate()
+            sleep(5)
+          finally:
+            None  
+        ser=open_port(path)
+      if line:
+        callback(line)
+    except KeyboardInterrupt:
+      break
+    finally:
+      None
+
+def print_log(str):
+  global logging
+  if debug>0:
+    print str
+  if logging == "on":
+    system("logger -t weathermon \""+str+"\"")
+
+def submit_narodmon():
+
+  param = { 'ID':devid }
+
+  c = database.cursor()
+  c.execute(
+    '''
+    select nm_id,value from
+    (
+    SELECT sensor_id,parameter_id,max(timestamp) timestamp,round(avg(value),1) value FROM meteo.sensor_values
+    where 
+    timestamp>=date_add(now(), INTERVAL -300 SECOND)
+    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 nm_id is not null
+    '''
+  )
+
+  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():
+
+  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,max(timestamp) timestamp,round(avg(value),1) value FROM meteo.sensor_values
+    where 
+    timestamp>=date_add(now(), INTERVAL -300 SECOND)
+    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 submit_data(sensor_type,sensor_id,sensor_param,param_value):
+  global submit_time
+  global submit_time_owm
+  global external_submit_interval
+  global owm_submit_interval
+  c = database.cursor()
+  c.execute('CALL meteo.submit_value(%s,%s,%s,%s,NULL)', (sensor_type,sensor_id,sensor_param,param_value))
+  database.commit()
+  if narmon=='on' and time()>submit_time+external_submit_interval:
+    submit_narodmon()
+    submit_time=time()
+  if owmuser and time()>submit_time_owm+owm_submit_interval:
+    submit_owm()
+    submit_time_owm=time()        
+def process_str(str):
+  print_log("Received: "+str)
+  try:
+    msg_type, msg_body = str.split(':')
+  except:
+    return
+  try:  
+    if msg_type == 'STATUS':
+      print_log('Status: '+msg_body)
+    elif msg_type == 'ERROR':
+      print_log('Error: '+ msg_body)
+    elif msg_type == 'SENSOR':
+      sens = msg_body.split(',')
+      sensor = {}
+      sensor_type = None
+      sensor_id = None
+      for rec in sens:
+        key,value = rec.split('=')
+       value=value.strip()
+       if len(value)>0:
+          if key == 'TYPE':
+            sensor_type = value
+          elif key == 'ID':
+            sensor_id = value  
+          else:  
+            sensor[key] = value
+      if sensor_type:    
+        if not sensor_id:
+          sensor_id=devid;    
+      for key in sensor:
+       if sensor[key]:
+          print_log('Type = '+sensor_type+', ID = '+sensor_id+', Param = '+key+', Value = '+sensor[key])
+          submit_data(sensor_type,sensor_id,key,sensor[key])
+        else:
+          print_log('Error: got empty parameter value for '+sensor_type+'.'+sensor_id+'.'+key)
+    elif msg_type == "ALARM":
+      alarm = msg_body.split(',')
+      device_type = None
+      device_id = None
+      for rec in alarm:
+        key,value = rec.split('=')
+        value=value.strip()
+        if len(value)>0:
+          if key == 'TYPE':
+            device_type = value
+          if key == 'ID':
+            device_id = value
+      if device_type:
+        if not device_id:
+          device_id=devid;
+        print_log("Alarm: Type = "+device_type+", ID = "+device_id)
+        if alarm_script:
+          try:
+            proc = subprocess.Popen([alarm_script,device_type,device_id,msg_body])
+          except:
+            print_log("Failed to execute alarm script")          
+  except:
+    print_log('Exception processing...')
+    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=5, file=sys.stdout)  
+    try:
+      database.close()
+    except:
+      None
+    reconnect()
+
+def weather_mon():
+
+  global path
+
+  if path is None:
+    path = find_port()
+  ser = open_port(path)
+  read_loop(ser,process_str)
+
+def reconnect():
+
+  connected = False
+
+  while not connected:            
+
+    try:
+
+      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("Error connecting database")
+      sleep(30)
+      
+def main():
+  weather_mon()
+
+def init():
+
+  global dbhost,dbuser,dbpasswd,path,serialnum,logging,debug;
+  global timeout,baud,narmon,devid;
+  global owmuser,owmpasswd,owm_temp,owm_pres,owm_humi,owm_lat,owm_lon,owm_station;
+  global alarm_script;
+
+  try:
+
+    cfg = ConfigParser.RawConfigParser(allow_no_value=True)
+    cfg.readfp(open('/etc/weathermon.conf'))
+    dbhost = cfg.get("mysql","host")
+    dbuser = cfg.get("mysql","user")
+    dbpasswd = cfg.get("mysql","passwd")
+    try:
+      debug = cfg.get("logging","debug")
+    except:
+      debug = 0  
+    try:
+      path = cfg.get("serial","port");
+    except:
+      path = None
+    try:    
+      serialnum = cfg.get("serial","id")
+    except:
+      serialnum = None  
+    try:
+      logging = cfg.get("logging","enabled")
+    except:
+      logging = None
+    try:
+      timeout = int(cfg.get("serial","timeout"))
+    except:
+      timeout = 120
+    try:
+      baud = int(cfg.get("serial","baud"))
+    except:
+      baud = 57600
+    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:
+      owm_temp = cfg.get("openweathermap",'temp')
+      owm_pres = cfg.get("openweathermap",'pres')
+      owm_humi = cfg.get("openweathermap",'humi')
+      owm_lat = cfg.get("openweathermap",'lat')
+      owm_lon = cfg.get("openweathermap",'lon')
+      owm_station = cfg.get("openweathermap",'station')
+    try:
+      alarm_script = cfg.get("alarm","exec")
+      import subprocess
+    except:
+      alarm_script = None
+        
+    reconnect()
+  except:
+
+    print_log("Cannot intialize system")
+    exit() 
+  
+if __name__ == "__main__":
+  import sys
+  reload(sys)
+  sys.setdefaultencoding('utf-8')
+  init()
+  main()
index 20f5aca9fa194d32e9a1b9d128dfa65d86a43ffc..19cd912b13ffa8612f36eea9fdba9c71c43c4aa4 100755 (executable)
@@ -10,16 +10,28 @@ function getConfig()
   web_user = cur.get(config,"web","user")
   web_pass = cur.get(config,"web","password")
   web_devid = cur.get(config,"web","devid")
+
+  web_iface = cur.get(config,"web","iface")
   
-  io.input("/sys/class/net/eth0/address")
+  if web_iface then
+    io.input("/sys/class/net/"..web_iface.."/address")
+  else
+    io.input("/sys/class/net/eth0/address")
+  end
+
   mac = io.read("*line")
   mac = mac:gsub(":","")
   mac = mac:upper()
 
   web_devid = web_devid or mac
-
   logging = cur.get(config,"logging","enabled") 
 
+  serial_port = cur.get(config,"serial","port")
+  serial_baud = cur.get(config,"serial","baud")
+
+  command = "stty -F  "..serial_port.." "..serial_baud
+  os.execute(command)
+
 end
 
 require "socket"
@@ -59,21 +71,21 @@ end
 
 function submitValue(type,id,param,val)
 
-  printLog("URL="..web_url)
-
   url = web_url.."?stype="..type.."&sid="..id.."&param="..param.."&value="..val
 
-  printLog(url)
-
   command = "curl"
 
+  if web_iface then
+    command = command.." --interface "..web_iface
+  end
+
   if web_user then
     command = command.." -u "..web_user..":"..web_pass
   end
 
   command = command.." \""..url.."\""
 
-  printLog("COMMAND=\""..command.."\"")
+  print(command)
   os.execute(command)
   print("")
 
@@ -110,8 +122,8 @@ function processLine(str)
       end
     end
     for k,v in pairs(sensor) do
-      printLog("Type = "..sensor_type..", ID = "..sensor_id..", Param = "..key..", Value = "..value)
-      submitValue(sensor_type,sensor_id,key,value)
+      printLog("Type = "..sensor_type..", ID = "..sensor_id..", Param = "..k..", Value = "..v)
+      submitValue(sensor_type,sensor_id,k,v)
     end
   end
 
@@ -119,6 +131,9 @@ end
 
 getConfig()
 
-line=arg[1]
-print(line)
-processLine(line)
+serialin=io.open(serial_port,"r")
+while 1 do
+  line=serialin:read()
+  print(line)
+  processLine(line)
+end
diff --git a/weathermon.sh b/weathermon.sh
deleted file mode 100755 (executable)
index 3f42275..0000000
+++ /dev/null
@@ -1,9 +0,0 @@
-#!/bin/sh
-
-ARDUINO_PORT=`uci get weathermon.serial.port`
-BAUD=`uci get weathermon.serial.baud`
-stty -F $ARDUINO_PORT $BAUD
-
-while read LINE; do
-  weathermon.lua $LINE
-done < $ARDUINO_PORT
index 490ba91f742aa0290dd69bf078ba698ebb07a319..27631ac5a8d8978c4b0af25586e1222a1b8a66a5 100644 (file)
@@ -2,6 +2,7 @@ config internal 'web'
        option url http://estia.rvb-home.lan/meteo/send.php
        option user meteo
        option password somestrictpassword
+       option iface eth0
 
 config internal 'serial'
        option port /dev/ttyUSB0
index c40386389e5a7e5bea9d368c16ee2b31ed688369..1b21599236fb7866428a04c4ab09fd0fbb4d46b0 100644 (file)
@@ -23,7 +23,7 @@
     }                                          
     a:visited { text-decoration: none; color:darkblue; }
     a:link { text-decoration: none; color:blue; }
-    a:hover { text-decoration: none; color:navy; }  
+    a:hover { text-decoration: underline; color:navy; }  
   </style>
 </head>
 <body text="black" bgcolor="silver" link="blue" vlink="#000080" alink="#FF0000">         
@@ -33,6 +33,21 @@ include('config_local.php');
 include('calendar.php');
 include('units.php');
 
+  $client_ip = $_SERVER["REMOTE_ADDR"];
+
+  if ((strpos($client_ip, "192.168.") === 0) || (strpos($client_ip, "10.8.") === 0)
+     || (strpos($client_ip, "2a02:578:5002:8174:") === 0)
+     || (strpos($client_ip, "2a02:578:5002:196::2") === 0)) {
+
+    $local_net = True;
+
+  } else {
+
+    $local_net = False;
+
+  }
+
+
 $year = $_REQUEST['year']; 
 $month = $_REQUEST['month'];
 $day = $_REQUEST['day'];
@@ -58,7 +73,7 @@ if (! $year) {
 <?php
   while ($row = $q -> fetch(PDO::FETCH_ASSOC)) {
 ?> 
-  <a class="year" href="?year=<?php echo $row['year']; ?>">Данные за <?php echo $row['year']; ?> год</a><br>
+  <a class="year" href="?year=<?php echo $row['year']; ?>">Данные за <?php echo $row['year']; ?> год</a>
 <?php
   }
       
@@ -114,6 +129,18 @@ if (! $year) {
     
     $next_year = $year+1;
 
+    if (!$local_net) {
+
+      $filter = ' and s.is_public=1';
+  
+    } else {
+  
+      $filter = '';
+    
+    }  
+    
+    
+
     $q = $db -> prepare (
       'select 
          s.id sensor,p.id param,s.s_description sensor_name,p.st_description param_name,
@@ -128,7 +155,7 @@ if (! $year) {
          v.parameter=p.id and
          p.st_unit=u.id and
          v.day>=str_to_date(\''.$year.'-01-01\',\'%Y-%m-%d\') and 
-         v.day<str_to_date(\''.$next_year.'-01-01\',\'%Y-%m-%d\')
+         v.day<str_to_date(\''.$next_year.'-01-01\',\'%Y-%m-%d\''.$filter.')
       group by s.id,p.id,s.s_description,p.st_description
       order by s.id,p.id'
       );
@@ -181,14 +208,26 @@ if (! $year) {
       $month      = sprintf('%02d',$month);
       $year      = sprintf('%04d',$year);
 
+      if (!$local_net) {
+
+        $filter = ' and s.is_public=1';
+  
+      } else {
+  
+        $filter = '';
+    
+      }  
+    
+
       $q = $db -> prepare( 
           'select  
              date_format(day,\'%d\') as day
            from 
-             sensors_ranges
+             sensors_ranges r,sensors s 
            where 
+             s.id=r.sensor and
              day>=str_to_date(\''.$year.'-'.$month.'-01\',\'%Y-%m-%d\') and 
-             day<str_to_date(\''.$next_year.'-'.$next_month.'-01\',\'%Y-%m-%d\')
+             day<str_to_date(\''.$next_year.'-'.$next_month.'-01\',\'%Y-%m-%d\')'.$filter.'
            group by day
            order by day'
           );
@@ -206,6 +245,17 @@ if (! $year) {
       }
 
       calendar($year,$month,$days,'?year='.$year.'&month='.$month.'&day=%s',3);
+             
+      if (!$local_net) {
+      
+        $filter = ' and s.is_public=1';
+                
+      } else {
+                        
+        $filter = '';
+                                    
+      }
+                                                       
               
       $q = $db -> prepare (
           'select 
@@ -221,7 +271,7 @@ if (! $year) {
              v.parameter=p.id and
              p.st_unit=u.id and
              v.day>=str_to_date(\''.$year.'-'.$month.'-01\',\'%Y-%m-%d\') and 
-             v.day<str_to_date(\''.$next_year.'-'.$next_month.'-01\',\'%Y-%m-%d\')
+             v.day<str_to_date(\''.$next_year.'-'.$next_month.'-01\',\'%Y-%m-%d\')'.$filter.'
            group by s.id,p.id,s.s_description,p.st_description
            order by s.id,p.id'
         );
@@ -262,6 +312,17 @@ if (! $year) {
       $year      = sprintf('%04d',$year);
       $day       = sprintf('%02d',$day);
 
+      if (!$local_net) {
+
+        $filter = ' and s.is_public=1';
+  
+      } else {
+  
+        $filter = '';
+    
+      }
+
+
       $q = $db -> prepare(
            'select 
                distinct v.sensor as sensor_id,s.s_description,p.id as param_id,p.st_description 
@@ -270,7 +331,7 @@ if (! $year) {
             where 
                 v.day=str_to_date(\''.$year.'-'.$month.'-'.$day.'\',\'%Y-%m-%d\')
                 and v.sensor=s.id 
-                and v.parameter=p.id'
+                and v.parameter=p.id'.$filter
             );
       $q -> execute();
 
index eef21349d8f264ae1cf2f68aa733d5d38d4be3bd..d6cce97947bfa30399bdc49702bf09383ba64cbf 100644 (file)
@@ -3,15 +3,12 @@
   $mysql_host = 'host';
   $mysql_schema = 'meteo';
   $mysql_user = 'meteo';
-  $mysql_pwd = 'somestrictpasswd';
+  $mysql_pwd = 'somestrongpasswd';
   $mysql_port = 3306;
 
   setlocale(LC_ALL,'ru_RU.UTF8');
-<<<<<<< HEAD
-=======
 
-  $valid_ip_start = ip2long('192.168.1.161');
-  $valid_ip_end   = ip2long('192.168.1.190');
->>>>>>> 438eca78d7802bd2758a4969b80bb0be6b9f14f6
+  $valid_ip_start = ip2long('192.168.1.0');
+  $valid_ip_end   = ip2long('192.168.1.255');
                 
 ?>
\ No newline at end of file
index dfc7450d7463a2cdafaed2c21458f068bcb4bdeb..850d9d78f3fed173c2c76dcc620f744db0673e1f 100644 (file)
@@ -8,7 +8,7 @@
   <style type="text/css">
      a:visited { text-decoration: none; color:darkblue; }
      a:link { text-decoration: none; color:blue; }
-     a:hover { text-decoration: none; color:navy; }
+     a:hover { text-decoration: underline; color:navy; }
   </style>
 </head>
 <body text="black" bgcolor="silver" link="blue" vlink="#000080" alink="#FF0000">         
 
 include('config_local.php');
 
+$client_ip = $_SERVER["REMOTE_ADDR"];
+  
+if ((strpos($client_ip, "192.168.") === 0) || (strpos($client_ip, "10.8.") === 0)
+   || (strpos($client_ip, "2a02:578:5002:8174:") === 0)
+   || (strpos($client_ip, "2a02:578:5002:196::2") === 0)) {
+              
+   $local_net = True;
+                  
+} else {
+                    
+   $local_net = False;
+               
+}
+                         
+
 if (! ($db = new PDO("mysql:host=$mysql_host;port=$mysql_port;dbname=$mysql_schema",$mysql_user,$mysql_pwd,array( PDO::ATTR_PERSISTENT => false)))) {
   die($err);
   }  
 
 $db -> exec('SET CHARACTER SET utf8');
 
+if (!$local_net) {
+
+  $filter = ' and s.is_public=1';
+
+} else {
+
+  $filter = '';
+
+}  
+
 $q = $db -> prepare(
   'select 
     distinct v.sensor_id,s.s_description,p.id as param_id,p.st_description 
@@ -31,7 +56,7 @@ $q = $db -> prepare(
     v.timestamp>adddate(now(), -1) 
     and v.sensor_id=s.id 
     and s.st_id=p.st_id
-    and p.id>=0
+    and p.id>=0'.$filter.'
   order by s_description,st_description'
   );
 $q -> execute();
index 16fbafb89f28de2b801b3c34d77564875159cf43..9b6ca84e3209b5de7b07c08e83b292488f16dc2c 100644 (file)
@@ -1,6 +1,6 @@
 <?php // content="text/plain; charset=utf-8"
 
-error_reporting(E_ALL & ~E_STRICT & ~E_NOTICE);
+error_reporting(E_ALL & ~E_STRICT & ~E_NOTICE & ~E_DEPRECATED);
 
 include ('config_local.php');
 
@@ -12,7 +12,7 @@ require_once ('jpgraph/jpgraph_regstat.php');
 
 if (! ($db = new PDO("mysql:host=$mysql_host;port=$mysql_port;dbname=$mysql_schema",$mysql_user,$mysql_pwd,array( PDO::ATTR_PERSISTENT => false)))) {
 
-  die('Не могу подключиться к БД');
+  die('Ð\9dе Ð¼Ð¾Ð³Ñƒ Ð¿Ð¾Ð´ÐºÐ»ÑŽÑ‡Ð¸Ñ‚ÑŒÑ\81Ñ\8f Ðº Ð‘Д');
 
 }  
 
@@ -65,12 +65,13 @@ if ($type and $param) {
   }  
 
   $q = $db -> prepare(
-    'select u.name_short from units u where u.id='.$to_unit
+    'select u.name_short,u.prec from units u where u.id='.$to_unit
   );
   $q -> execute();
 
   while ($row = $q -> fetch(PDO::FETCH_ASSOC)) {
     $param_unit = $row['name_short'];
+    $precision = $row['prec'];
   }                                                                
   
   $xdata = array();
@@ -198,18 +199,24 @@ if ($type and $param) {
     $g->xaxis->HideLabels(True);
   }
   $g->xaxis->SetPos("min");
+  $g->yaxis->SetLabelFormat("%0.".$precision."f");
 #  $g->xaxis->scale->SetTimeAlign( HOURADJ_1 );
 
-  // We use a scatterplot to illustrate the original
-  // contro points.
-  $splot = new ScatterPlot($ydata,$xdata);
-  $g->Add($splot);
 
-  // 
-  $splot->mark->SetFillColor($dot_color);
-  $splot->mark->SetColor($dot_color);
-  $splot->mark->SetType(MARK_FILLEDCIRCLE);
-  $splot->mark->SetSize(2);
+  if ($type!="last24small") {
+
+    // We use a scatterplot to illustrate the original
+    // contro points.
+    $splot = new ScatterPlot($ydata,$xdata);
+    $g->Add($splot);
+
+    // 
+    $splot->mark->SetFillColor($dot_color);
+    $splot->mark->SetColor($dot_color);
+    $splot->mark->SetType(MARK_FILLEDCIRCLE);
+    $splot->mark->SetSize(2);
+
+  }
 
   $fplot = new LinePlot($f_ydata,$xdata);
   $g->Add($fplot);
@@ -234,7 +241,7 @@ if ($type and $param) {
 } else {
 
   header("Content-Type: text/html; charset=UTF-8");
-  die('СенÑ\81оÑ\80 Ð½Ðµ Ð²Ñ\8bбÑ\80ан!');
+  die('Ã\90¡Ã\90µÃ\90½Ã\91Â\81Ã\90¾Ã\91â\82¬ Ã\90½Ã\90µ Ã\90²Ã\91â\80¹Ã\90±Ã\91â\82¬Ã\90°Ã\90½!');
 
 }  
 
index dfa66d202a3aecdafd81a7a7ef9faccfb734b0ca..edc1708e600cea7c60627655209218c38c150ce2 100644 (file)
@@ -48,8 +48,7 @@ if ($type and $param) {
   }                                                                
 
   $q = $db -> prepare(
-    'select st.st_fill_color_top,st.st_fill_color_bottom,st.st_description,u.id,u.unit_group from st_parameters st,units u where st.id='.$param.' and st.st_unit=u.id
-'
+    'select st.st_fill_color_top,st.st_fill_color_bottom,st.st_description,u.id,u.unit_group from st_parameters st,units u where st.id='.$param.' and st.st_unit=u.id'
   );
   $q -> execute();
 
@@ -84,23 +83,27 @@ if ($type and $param) {
     $next_year = $year;
     $next_month = $month+1;
 
-    if ($month==13) {
+    if ($month==12) {
     
       $next_year++;
       $next_month=1;
-    
+
     }
 
     $curr = date("Ym");
+    $ym=sprintf('%04d%02d',$next_year,$next_month);
     
-    if ($curr>$next_year.$next_month) {
+    if ($curr>$ym) {
     
       $cachefilename='meteo.month.'.$sensor.'.'.$param.'.'.$to_unit.'.'.$year.'-'.$month.'.'.$img_format;
     
     }
 
+    $datestr=sprintf("%04d%02d01",$year,$month);
+    $nextdatestr=sprintf("%04d%02d01",$next_year,$next_month);
+
     $q = $db -> prepare(
-      '
+     '
         select 
           x,
           unitconv(min(min),'.$from_unit.','.$to_unit.') min_value,
@@ -113,14 +116,14 @@ if ($type and $param) {
           from 
             sensors_ranges 
           where 
-            day>=str_to_date(\''.$year.$month.'\',\'%Y%m\')
-            and day<str_to_date(\''.$next_year.$next_month.'\',\'%Y%m\')
+            day>=STR_TO_DATE(\''.$datestr.'\',\'%Y%m%d\')
+            and day<STR_TO_DATE(\''.$nextdatestr.'\',\'%Y%m%d\')
             and sensor='.$sensor.'
             and parameter='.$param.'
           ) t group by x
         order by x'
     );
-    
+
   } elseif ($type == "year") {
 
     $next_year = $year+1;
@@ -133,6 +136,9 @@ if ($type and $param) {
                           
     }
 
+    $datestr=sprintf("%04d0101",$year);
+    $nextdatestr=sprintf("%04d0101",$next_year);
+
     $q = $db -> prepare(
       '
         select 
@@ -149,8 +155,8 @@ if ($type and $param) {
           from 
             sensors_ranges
           where 
-            day>=str_to_date(\''.$year.'\',\'%Y\')
-            and day<str_to_date(\''.$next_year.'\',\'%Y\')
+            day>=STR_TO_DATE(\''.$datestr.'\',\'%Y%m%d\')
+            and day<STR_TO_DATE(\''.$nextdatestr.'\',\'%Y%m%d\')
             and sensor='.$sensor.'
             and parameter='.$param.'
           ) t group by x
@@ -186,7 +192,6 @@ if ($type and $param) {
     
   }                                                                
 
-
   // Create the graph
   $g->graph_theme = null;
 
index 37251e653214c0b70ed45d4e11408103d0fe3f1b..92a8e8e6a2dd384896fa8aa01311dcbee353680a 100644 (file)
@@ -9,7 +9,7 @@
   <style type="text/css">
      a:visited { text-decoration: none; color:darkblue; }
      a:link { text-decoration: none; color:blue; }
-     a:hover { text-decoration: none; color:navy; }
+     a:hover { text-decoration: underline; color:navy; }
      .header { font-size: 16; float: left; margin: 10px;}
      .timestamp { font-size: 16; margin: 10px;}
      .value { font-size: 60; margin: 10px; }
 <div class="container">
 <?php
 
+  $client_ip = $_SERVER["REMOTE_ADDR"];
+
+  if ((strpos($client_ip, "192.168.") === 0) || (strpos($client_ip, "10.8.") === 0)
+     || (strpos($client_ip, "2a02:578:5002:8174:") === 0)
+     || (strpos($client_ip, "2a02:578:5002:196::2") === 0)) {
+   
+    $local_net = True;
+            
+  } else {
+  
+    $local_net = False;
+  
+  }
+
 include('config_local.php');
 include('units.php');
 
@@ -31,6 +45,16 @@ if (! ($db = new PDO("mysql:host=$mysql_host;port=$mysql_port;dbname=$mysql_sche
 
 $db -> exec('SET CHARACTER SET utf8');
 
+if (!$local_net) {
+
+  $filter = ' and s.is_public=1'; 
+
+} else {
+
+  $filter = '';
+
+}
+
 $q = $db -> prepare(
   'select 
     distinct v.sensor_id,s.s_description,p.id as param_id,p.st_description 
@@ -38,9 +62,10 @@ $q = $db -> prepare(
     sensor_values v,st_parameters p,sensors s 
   where 
     v.timestamp>adddate(now(), -1) 
-    and v.sensor_id=s.id 
+    and v.sensor_id=s.id
+    and v.parameter_id=p.id  
     and s.st_id=p.st_id
-    and p.id>=0
+    and p.id>=0'.$filter.'
   order by s_description,st_description'
   );
 $q -> execute();
@@ -65,7 +90,7 @@ $ql =  $db -> prepare(
 $ql -> execute();
 
 $printable_ts = "?";
-$value = "?";
+$val = "?";
 
 if ($rowl = $ql -> fetch(PDO::FETCH_ASSOC)) {
 
@@ -77,15 +102,17 @@ if ($rowl = $ql -> fetch(PDO::FETCH_ASSOC)) {
   $from_unit = $units['from'];
   $to_unit = $units['to'];
   $param_unit = $units['name'];
-                        
+
   $val = convert_unit($db,$value,$from_unit,$to_unit);
                               
 }
                                   
-echo '<div class="timestamp">'.$printable_ts.'</div>';
-echo '<div class="value">'.$val.' '.$param_unit.'</div>';
+if ($printable_ts != '?') { 
+  echo '<div class="timestamp">'.$printable_ts.'</div>';
+  echo '<div class="value">'.$val.' '.$param_unit.'</div>';
+}
 ?>
-<div class="graph"><img src="image.php?sensor=<?php echo $row['sensor_id']; ?>&param=<?php echo $row['param_id']?>&type=last24small"></div>
+<div class="graph"><a href="image.php?sensor=<?php echo $row['sensor_id']; ?>&param=<?php echo $row['param_id']?>&type=last24"><img src="image.php?sensor=<?php echo $row['sensor_id']; ?>&param=<?php echo $row['param_id']?>&type=last24small"></a></div>
 <?php  
 
 echo "</div>";
index 7a698389538913b30237a4518f22d55723d8026c..60d21dbbc704bfedb1c8826a2b3c74ad0a779f7b 100644 (file)
     }
         
     $str = "CALL meteo.submit_value('".$stype."','".$sid."','".$param."',".$value.",NULL)";
-        if (!$connection->query($str)) {
-            header('HTTP/1.1 500 Internal Server Error');
-            exit;    
-        } else {
-            $connection->commit();
-?>        
-<html>
-<head>
-  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
-  <title>Meteo logger</title>
-</head>
-<body>
-OK Logged
-</body>
-</html>
-<?
+    if (!$connection->query($str)) {
+        header('HTTP/1.1 500 Internal Server Error');
+        exit;    
+    } else {
+        $connection->commit();
+        echo "OK Logged";    
     }
 
-?>