init github

This commit is contained in:
eddyem 2015-07-23 13:31:18 +03:00
parent 46de522a2e
commit 80154b79e8
41 changed files with 12173 additions and 0 deletions

3
.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
*.hg
.hgignore
.dropbox.attr

14
C/bta_pos/bta_pos.c Normal file
View File

@ -0,0 +1,14 @@
#include "bta_shdata.h"
inline double sec2deg(double angle){
return angle / 3600;
}
int main(int argc, char** argv){
get_shm_block( &sdat, ClientSide);
if(!check_shm_block(&sdat)) return -1;
printf("Access-Control-Allow-Origin: http://ishtar.sao.ru\n"
"Acess-Control-Allow-Methods: POST\nContent-type:multipart/form-data\n\n");
printf("telA=%.2f telZ=%.2f domeA=%.2f\n", sec2deg(val_A), sec2deg(val_Z), sec2deg(val_D));
}

1158
C/bta_pos/bta_shdata.h Normal file

File diff suppressed because it is too large Load Diff

1158
C/bta_shdata.h Normal file

File diff suppressed because it is too large Load Diff

1141
C/bta_shdata.h.old Normal file

File diff suppressed because it is too large Load Diff

12
C/client_cli/Makefile Normal file
View File

@ -0,0 +1,12 @@
CXX.SRCS = tempmon_cli
CC = gcc
LDFLAGS =
CPPFLAGS =
all : tempmon_cli clean
tempmon_cli : client_cli.o
$(CC) client_cli.c $(CPPFLAGS) -o tempmon_cli
clean:
/bin/rm -f *.o *~
### <DEPENDENCIES ON .h FILES GO HERE>
# name1.o : header1.h header2.h ...

1158
C/client_cli/bta_shdata.h Normal file

File diff suppressed because it is too large Load Diff

360
C/client_cli/client_cli.c Normal file
View File

@ -0,0 +1,360 @@
// client.c
//
// Copyright 2012 Edward V. Emelianoff <eddy@sao.ru>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
// MA 02110-1301, USA.
#define __CLIENT_C__
#include <string.h>
#include <getopt.h>
#include <stdarg.h>
#include <stdlib.h>
#include "defines.h"
#include "lang.h"
#define Julian(x) ((double)x/86400. + 2440587.5)
extern const char *__progname;
char *db_path = A_PATH;
off_t starting_pos = 0LL;
typedef struct shm_data shm_d;
unsigned char Lang = 1; // ÁÎÇÌÉÊÓËÉÊ
time_t t_start = 0, t_end = 0;
time_t aver_interval = 1;
int force_dbpath = 0;
int out_fd;
int only_extr = 0;
inline void minmax(float *min, float *max, float param){
if(param > *max) *max = param;
else if(param < *min) *min = param;
}
void send_data(unsigned char stat_mask){
int ii=0, j;
uint64_t data_amount = 0;
struct tm ltime;
time_t t_first=0, t_last=0;
double otemp=0., itemp=0., mtemp=0., wind=0., pres=0., hum=0.;
double otmax=-1e6,otmin=1e6,itmax=-1e6,itmin=1e6,mtmax=-1e6,mtmin=1e6,windmax=-1e6,windmin=1e6;
int ctr, status, statuses[5] = {0,0,0,0,0};
char s_time[32];
monit_d data;
if(!only_extr){
printf("OT - %s\nIT - %s\nMT - %s\nWS - %s\nP - %s\nH - %s\nS - %s\n\n",
_L(_s_Otemp_), _L(_s_Itemp_), _L(_s_Mtemp_),
_L(_s_WSpeed_), _L(_s_Pressure_), _L(_s_Humidity_),
_L(_s_State_));
printf("%s\t\tJulian date\tOT\tIT\tMT\tWS\tP\tH\tS\n", _L(_s_Date_));
}
while(read(out_fd, &data, sizeof(data)) > 0){
time_t X = (time_t) data.seconds;
//printf("time: %zd (tstart: %zd, tend: %zd) -- %s", data.seconds, t_start, t_end, ctime(&X));
if(X < t_start) continue;
if(X > t_end) break;
if(!(stat_mask & (1 << data.status))) continue;
data_amount++;
if(!only_extr){
if(t_first == 0) t_first = t_last = X;
else if((X - t_first) >= aver_interval){ // ÎÁËÏÐÉÌÉ ÄÏÓÔÁÔÏÞÎÏ ÄÁÎÎÙÈ
t_first = t_first/2 + t_last/2; // ÓÅÒÅÄÉÎÁ ×ÒÅÍÅÎÎÏÇÏ ÉÎÔÅÒ×ÁÌÁ
ltime = *localtime(&t_first);//*localtime(&t_first);
strftime(s_time, 32, "%d/%m/%Y, %H:%M:%S", &ltime);
if(ii == 0) ii = 1;
ctr = 0;
for(j = 0; j<5; j++){
if(statuses[j] > ctr){
ctr = statuses[j];
status = j;
}
statuses[j] = 0;
}
printf("%s\t%.6f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%d\n",
s_time,
Julian(t_first),
otemp/ii,
itemp/ii,
mtemp/ii,
wind/ii,
pres/ii,
hum/ii,
status);
t_first = X;
otemp=itemp=mtemp=wind=pres=hum=0.;
ii = 0;
}
t_last = X;
otemp += data.outdoor_temp;
itemp += data.indoor_temp;
mtemp += data.mirror_temp;
wind += data.wind_speed;
pres += data.pressure;
hum += data.humidity;
statuses[data.status]++;
ii++;
}
if(otmax < data.outdoor_temp) otmax = data.outdoor_temp;
if(otmin > data.outdoor_temp) otmin = data.outdoor_temp;
if(itmax < data.indoor_temp) itmax = data.indoor_temp;
if(itmin > data.indoor_temp) itmin = data.indoor_temp;
if(mtmax < data.mirror_temp) mtmax = data.mirror_temp;
if(mtmin > data.mirror_temp) mtmin = data.mirror_temp;
if(windmax < data.wind_speed) windmax = data.wind_speed;
if(windmin > data.wind_speed) windmin = data.wind_speed;
}
if(!data_amount){
printf("No data found!\n");
return;
}
printf("\n\nExtremal values (min / max):\n");
printf("%s: %g / %g\n", _L(_s_Otemp_), otmin, otmax);
printf("%s: %g / %g\n", _L(_s_Itemp_), itmin, itmax);
printf("%s: %g / %g\n", _L(_s_Mtemp_), mtmin, mtmax);
printf("%s: %g / %g\n", _L(_s_WSpeed_),windmin, windmax);
}
void find_starting_pos(){ // ÉÝÅÍ × ËÜÛÅ ÓÍÅÝÅÎÉÅ ÄÌÑ ÎÁÞÁÌÁ ÐÏÉÓËÁ
int cache_fd;
Cache cache;
if(force_dbpath){
char cname[256];
snprintf(cname, 255, "%s/.cache", db_path);
printf("using cache file %s\n", cname);
cache_fd = open(cname, O_RDONLY);
}else{
if((cache_fd = open(CACHE_FILE, O_RDONLY)) < 0)
cache_fd = open("./cache", O_RDONLY);
}
if(cache_fd < 0){
WARN(_L(_s_Cant_open_cache_));
exit(1);
}
while(read(cache_fd, &cache, sizeof(cache)) > 0){
//time_t X = (time_t) cache.time;
//printf("time: %zd -- %s", cache.time, ctime(&X));
if(cache.time < t_start)
starting_pos = cache.offset;
else break;
}
//printf("pos: %zd \n", starting_pos);
close(cache_fd);
}
time_t get_date(char *line){
time_t date = time(NULL);
struct tm time_, time_now;
time_now = *localtime(&date);
time_.tm_sec = 0;
if(sscanf(line, "%d/%d/%d-%d:%d", &time_.tm_mday, &time_.tm_mon, &time_.tm_year,
&time_.tm_hour, &time_.tm_min) == 5){time_.tm_mon -= 1;}
else if(!strchr(line, ':') && sscanf(line, "%d/%d/%d", &time_.tm_mday, &time_.tm_mon, &time_.tm_year) == 3){
date = -1; time_.tm_mon -= 1;}
else if(!strchr(line, ':') && sscanf(line, "%d/%d", &time_.tm_mday, &time_.tm_mon) == 2){
date = -1; time_.tm_mon -= 1; time_.tm_year = time_now.tm_year;}
else if(sscanf(line, "%d:%d", &time_.tm_hour, &time_.tm_min) == 2){
time_.tm_year = time_now.tm_year; time_.tm_mon = time_now.tm_mon;
time_.tm_mday = time_now.tm_mday;}
else if(!strchr(line, ':') && !strchr(line, '/') && !strchr(line, '.') && !strchr(line, '-')
&& sscanf(line, "%d", &time_.tm_mon) == 1){
date = -1; time_.tm_mon -= 1; time_.tm_year = time_now.tm_year;
time_.tm_mday = 1;}
else{
printf("\nWrong datetime format!\n");
printf("Formats: D/M/Y-hh:mm, D/M/Y, hh:mm, D/M, M\n");
exit(1);
}
if(date == -1){
time_.tm_hour = 0;
time_.tm_min = 0;
}
if(time_.tm_mon > 11 || time_.tm_mon < 0){
printf("\nMonth should be in 1..12\n");
exit(2);
}
if(time_.tm_mday > 31 || time_.tm_mday < 1){
printf("\nDate should be in 1..31, %d\n", time_.tm_mday);
exit(3);
}
if(time_.tm_year > 1900) time_.tm_year -= 1900;
else if(time_.tm_year > -1 && time_.tm_year < 100) time_.tm_year += 100;
else if(time_.tm_year < 0 || time_.tm_year > 200){
printf("\nBad year format %d\n", time_.tm_year);
exit(4);
}
if(time_.tm_hour > 23 || time_.tm_hour < 0){
printf("\nTime should be in 0..23\n");
exit(5);
}
if(time_.tm_min > 59 || time_.tm_min < 0){
printf("\nMinutes should be in 0..59\n");
exit(6);
}
date = mktime(&time_);
return date;
}
void print_dates(){
char s_time[32];
inline char *mktm(uint32_t t){
time_t X = (time_t) t;
struct tm ltime = *localtime(&X);
strftime(s_time, 32, "%d/%m/%Y, %H:%M:%S", &ltime);
return s_time;
}
monit_d data;
if(read(out_fd, &data, sizeof(data)) != sizeof(data)){
WARN("Error reading datafile!\n");
exit(1);
}
printf("Date of first record in database: %s\n", mktm(data.seconds));
lseek(out_fd, -sizeof(data), SEEK_END);
if(read(out_fd, &data, sizeof(data)) != sizeof(data)){
WARN("Error reading datafile!\n");
exit(1);
}
printf("Date of last record in database: %s\n", mktm(data.seconds));
exit(0);
}
unsigned char get_modemask(const char *optarg){
unsigned char mode = 0;
char c;
while((c = *optarg++)){
switch (c){
case 's': case 'S':
mode |= 1;
break;
case 'g': case 'G':
mode |= 2;
break;
case 'r': case 'R':
mode |= 4;
break;
case 'u': case 'U':
mode |= 8;
break;
case 'o': case 'O':
mode |= 16;
break;
default:
WARN("Bad mode: should be sgruo\n");
exit(1);
}
}
return mode;
}
void usage(char *fmt, ...){
va_list ap;
va_start(ap, fmt);
printf("\n");
if (fmt != NULL){
vprintf(fmt, ap);
printf("\n\n");
}
va_end(ap);
printf("Usage:\t%s [options]\n",
__progname);
printf("\tOptions:\n");
printf("\t-d, --dbpath\t\tPath to database files\n");
printf("\t-e, --tend\t\tEnding time (D/M/Y-hh:mm)\n");
printf("\t-h, --help\t\tShow this help\n");
printf("\t-i, --averint\t\tTime interval for data averaging (in seconds)\n");
printf("\t-l, --lookout\t\t Show date interval of stored data\n");
printf("\t-m, --mode\t\tTelescope mode (sgruo - Stopped, Guiding, Ready, Unknown, Opened)\n");
printf("\t-s, --tstart\t\tStarting time (D/M/Y-hh:mm)\n");
printf("\t-X, --extremal\t\tOnly show extremal values\n");
exit(0);
}
int main(int argc, char **argv){
unsigned char mask = 0;
struct option long_options[] = {
{"dbpath", 1, 0, 'd'},
{"tend", 1, 0, 'e'},
{"help", 0, 0, 'h'},
{"averint", 1, 0, 'i'},
{"lookout", 0, 0, 'l'},
{"mode", 1, 0, 'm'},
{"tstart", 1, 0, 's'},
{"extremal", 0, 0, 'X'}
};
char short_options[] = "d:e:hi:lm:s:X";
int lookout = 0;
while (1){
int opt;
if((opt = getopt_long(argc, argv, short_options,
long_options, NULL)) == -1) break;
switch(opt){
case 'd':
db_path = strdup(optarg);
force_dbpath = 1;
break;
case 'e':
t_end = get_date((char*)optarg);
break;
case 'h':
usage(NULL);
break;
case 'i':
aver_interval = atoi((char*)optarg);
if(aver_interval < 1) aver_interval = 1;
break;
case 'l':
lookout = 1;
break;
case 'm':
mask = get_modemask(optarg);
break;
case 's':
t_start = get_date((char*)optarg);
break;
case 'X':
only_extr = 1;
break;
default:
usage("Unknown argument");
}
}
if(argc != optind) usage("Too many arguments");
if(t_end < 1) t_end = time(NULL);
if(t_end <= t_start){
WARN("%s\n", _L(_s_Bad_date_));
return(1);
}
if(mask == 0) mask = 0xff;
if(force_dbpath){
char cname[256];
snprintf(cname, 255, "%s/.out", db_path);
printf("using DB file %s\n", cname);
out_fd = open(cname, O_RDONLY);
}else{
if((out_fd = open(OUT_FILE, O_RDONLY)) < 0)
out_fd = open("./out", O_RDONLY);
}
if(out_fd < 0){
WARN(_L(_s_Cant_open_data_));
return(1);
}
if(lookout) print_dates();
find_starting_pos();
lseek(out_fd, starting_pos, SEEK_SET);
send_data(mask);
return(0);
}

78
C/client_cli/defines.h Normal file
View File

@ -0,0 +1,78 @@
#ifndef __DEFINES_H__
#define __DEFINES_H__
#define _FILE_OFFSET_BITS 64
#define _LARGEFILE64_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <unistd.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <fcntl.h>
#include <time.h>
#include <signal.h>
#include <stdint.h>
#ifndef __CLIENT_C__
#include "bta_shdata.h"
#endif
#define WARN(...) do{fprintf(stderr, __VA_ARGS__);}while(0)
#define TIMEINTERVAL 9.99 // ÉÎÔÅÒ×ÁÌ ÕÓÒÅÄÎÅÎÉÑ ÄÁÎÎÙÈ (× ÓÅËÕÎÄÁÈ)
#define LOG_FILE "/Users/eddy/_data/.temp_daemon" // ÆÁÊÌ Ó ÌÏÇÁÍÉ
#define CACHE_FILE "/Users/eddy/_data/.cache" // ÉÎÄÅËÓÎÙÊ ÆÁÊÌ
#define OUT_FILE "/Users/eddy/_data/.out" // ÓÁÍÁ ÉÎÆÏÒÍÁÃÉÑ
#define PID_FILE "/Users/eddy/_data/.pid" // PID
#define A_PATH "/Users/eddy/_data"
#define PROC_BASE "/proc"
#define SHM_KEY 1234567890
#define CACHE_EVERY_PWR 10 // ËÜÛÉÒÕÅÍ ËÁÖÄÕÀ 2^CACHE_EVERY_PWR ÚÁÐÉÓØ
#define tell(fd) lseek(fd, 0, SEEK_CUR)
enum telescope_status{
STOP, // 0 - ÔÅÌÅÓËÏÐ ×ÙËÌÀÞÅÎ
GUIDING, // 1 - ×ÅÄÅÎÉÅ
READY, // 2 - ×ÓÅ ÏÓÔÁÎÏ×ÌÅÎÏ, ÐÉÔÁÎÉÅ ÅÓÔØ
OTHER, // 3 - ÎÁ×ÅÄÅÎÉÅ ÉÌÉ ÐÒÏÞÅÅ ÐÅÒÅÍÅÝÅÎÉÅ ÔÅÌÅÓËÏÐÁ/ËÕÐÏÌÁ
OPEN // 4 - ÚÁÂÒÁÌÏ ÏÔËÒÙÔÏ, ÉÄÕÔ ÎÁÂÌÀÄÅÎÉÑ
// 5 - úáòåúåò÷éòï÷áîï ÄÌÑ ÓÕÍÍÁÒÎÏÇÏ ×ÒÅÍÅÎÉ
};
typedef enum telescope_status Status;
typedef float data_type;
#pragma pack(4)
struct monitoring_data{
uint32_t seconds; // ×ÒÅÍÑ × ÓÅËÕÎÄÁÈ
data_type outdoor_temp; // ÍÅÄÉÁÎÁ ÔÅÍÐÅÒÁÔÕÒÙ ÚÁ TIMEINTERVAL ÓÎÁÒÕÖÉ
data_type indoor_temp; // -//- ÔÅÍÐÅÒÁÔÕÒÁ ×ÎÕÔÒÉ
data_type mirror_temp; // -//- ÔÅÍÐÅÒÁÔÕÒÁ ÚÅÒËÁÌÁ
data_type wind_speed; // ÍÁËÓÉÍÁÌØÎÁÑ ÚÁ TIMEINTERVAL ÓËÏÒÏÓÔØ ×ÅÔÒÁ
data_type pressure; // ÍÅÄÉÁÎÎÏÅ ÚÎÁÞÅÎÉÅ ÄÁ×ÌÅÎÉÑ (ÍÍ.ÒÔ.ÓÔ)
data_type humidity; // -//- ×ÌÁÖÎÏÓÔÉ
/* data_type sigma_ot; // ÓÔÁÎÄÁÒÔÎÏÅ ÏÔËÌÏÎÅÎÉÅ ×ÎÅÛÎÅÊ ÔÅÍÐÅÒÁÔÕÒÙ
data_type sigma_it; // -//- ×ÎÕÔÒÅÎÎÅÊ ÔÅÍÐÅÒÁÔÕÒÙ
data_type sigma_mt; // -//- ÔÅÍÐÅÒÁÔÕÒÙ ÚÅÒËÁÌÁ
data_type sigma_w; // -//- ÓËÏÒÏÓÔÉ ×ÅÔÒÁ
data_type sigma_p;
data_type sigma_h;
data_type avr_ot; // ÓÒÅÄÎÅÅ ÚÁ TIMEINTERVAL ÚÎÁÞÅÎÉÅ ×ÎÅÛÎÅÊ ÔÅÍÐÅÒÁÔÕÒÙ
data_type avr_it; // ...
data_type avr_mt;
data_type avr_w;
data_type avr_p;
data_type avr_h;*/
Status status; // ÓÏÓÔÏÑÎÉÅ ÔÅÌÅÓËÏÐÁ
};
typedef struct monitoring_data monit_d;
#pragma pack(4)
struct _cache{ // ÓÔÒÕËÔÕÒÁ ÄÌÑ ÈÒÁÎÅÎÉÑ ÄÁÎÎÙÈ × ËÜÛÅ
uint32_t time; // ×ÒÅÍÑ × ÓÅËÕÎÄÁÈ Ó 1.01.1970-0:0
uint64_t offset; // ÓÍÅÝÅÎÉÅ × ÌÏÇ-ÆÁÊÌÅ
};
typedef struct _cache Cache;
int *Visor = NULL; // ÓÏÓÔÏÑÎÉÅ ÚÁÂÒÁÌÁ
#endif

55
C/client_cli/lang.h Normal file
View File

@ -0,0 +1,55 @@
#define _LANG(_var, _ru, _en) char _var##ru[] = _ru;\
char _var##en[] = _en;\
char *_var[2] = {_var##ru, _var##en};
#define _L(x) (x[Lang])
_LANG(_s_Save_file_, "óÏÈÒÁÎÉÔØ ÆÁÊÌ", "Save file");
_LANG(_s_no_QS_, "ïÔÓÕÔÓÔ×ÕÅÔ ÓÔÒÏËÁ ÚÁÐÒÏÓÁ", "No query string");
_LANG(_s_no_tstart_, "ðÏÖÁÌÕÊÓÔÁ, ÚÁÐÏÌÎÉÔÅ ÆÏÒÍÕ\"ÎÁÞÁÌØÎÏÅ ×ÒÅÍÑ\"", "Please, fill the form \"starting time\"");
_LANG(_s_Date_, "äÁÔÁ É ×ÒÅÍÑ", "Date and time");
_LANG(_s_Otemp_, "÷ÎÅÛÎÑÑ ÔÅÍÐÅÒÁÔÕÒÁ", "Outdoor temperature");
_LANG(_s_Itemp_, "÷ÎÕÔÒÅÎÎÑÑ ÔÅÍÐÅÒÁÔÕÒÁ", "Indoor temperature");
_LANG(_s_Mtemp_, "ôÅÍÐÅÒÁÔÕÒÁ ÚÅÒËÁÌÁ", "Mirror temperature");
_LANG(_s_Ot_, "÷ÎÅÛÎÑÑ", "Outdoor");
_LANG(_s_It_, "÷ÎÕÔÒÅÎÎÑÑ", "Indoor");
_LANG(_s_Mt_, "úÅÒËÁÌÁ", "Mirror");
_LANG(_s_WSpeed_, "óËÏÒÏÓÔØ ×ÅÔÒÁ", "Wind speed");
_LANG(_s_Temp_, "ôÅÍÐÅÒÁÔÕÒÁ", "Temperature");
_LANG(_s_Pressure_, "äÁ×ÌÅÎÉÅ (ÍÍ.ÒÔ.ÓÔ.)", "Pressure (mmHg)");
_LANG(_s_Humidity_, "÷ÌÁÖÎÏÓÔØ (%)", "Humidity (%)");
_LANG(_s_State_, "óÏÓÔÏÑÎÉÅ ÔÅÌÅÓËÏÐÁ", "Telescope state");
_LANG(_s_Monlen_, "óÄÅÌÁÎÏ ÉÚÍÅÒÅÎÉÊ", "Number of measurements");
_LANG(_s_SVGerr_, "îÅ ÍÏÇÕ ÓÏÚÄÁÔØ ÇÒÁÆÉË", "Can't create graph");
_LANG(_s_Bad_date_, "îÅÐÒÁ×ÉÌØÎÙÊ ÆÏÒÍÁÔ ÄÁÔÙ, ÉÌÉ ÄÁÔÁ ÏËÏÎÞÁÎÉÑ ÒÁÎØÛÅ ÄÁÔÙ ÎÁÞÁÌÁ", "Bad date format, or starting date goes after ending date");
_LANG(_s_Cant_open_cache_, "îÅ ÍÏÇÕ ÏÔËÒÙÔØ ÆÁÊÌ ËÜÛÁ", "Can't open cache file");
_LANG(_s_Cant_open_data_, "îÅ ÍÏÇÕ ÏÔËÒÙÔØ ÆÁÊÌ Ó ÄÁÎÎÙÍÉ", "Can't open data file");
_LANG(_s_Cant_write_, "ïÛÉÂËÁ ÚÁÐÉÓÉ ÄÁÎÎÙÈ", "Can't write data");
_LANG(_s_noData_, "úÁ ÕËÁÚÁÎÎÙÊ ÐÅÒÉÏÄ ÎÅÔ ÄÁÎÎÙÈ", "No data for this period");
_LANG(_s_Vopen_, "úÁÂÒÁÌÏ ÏÔËÒÙÔÏ", "Visor is open");
_LANG(_s_Vclose_, "úÁÂÒÁÌÏ ÚÁËÒÙÔÏ", "Visor is close");
_LANG(_s_CurVstat_, "ôÅËÕÝÅÅ ÓÏÓÔÏÑÎÉÅ", "Current status");
_LANG(_s_ChVstat_, "óÍÅÎÉÔØ ÓÏÓÔÏÑÎÉÅ ÎÁ", "Change status to");
_LANG(_s_noVisor_, "îÅ ÍÏÇÕ ÏÐÒÅÄÅÌÉÔØ ÓÏÓÔÏÑÎÉÅ ÚÁÂÒÁÌÁ", "Can't define visor state");
_LANG(_s_No_Data_, "îÅÄÏÓÔÁÔÏÞÎÏ ÄÁÎÎÙÈ", "Not enough data");
_LANG(_s_Gtr_, "ÂÏÌØÛÅ", "greater");
_LANG(_s_Less_, "ÍÅÎØÛÅ", "less");
_LANG(_s_G_mustbe_less_L_, "þÉÓÌÏ × ÐÏÌÅ \"ÂÏÌØÛÅ\" ÄÏÌÖÎÏ ÂÙÔØ ÍÅÎØÛÅ ÞÉÓÌÁ × ÐÏÌÅ \"ÍÅÎØÛÅ\"",
"The value in field \"greater\" must be less than value in field \"less\"");
_LANG(_s_L_mustbe_less_G_, "þÉÓÌÏ × ÐÏÌÅ \"ÍÅÎØÛÅ\" ÄÏÌÖÎÏ ÂÙÔØ ÍÅÎØÛÅ ÞÉÓÌÁ × ÐÏÌÅ \"ÂÏÌØÛÅ\"",
"The value in field \"less\" must be less than value in field \"greater\"");
_LANG(_s_Max_data_, "äÁÔÙ Ó ÍÁËÓÉÍÁÌØÎÙÍ ÚÎÁÞÅÎÉÅÍ ÐÁÒÁÍÅÔÒÏ×", "Dates with maximum of paremeters");
_LANG(_s_Min_data_, "äÁÔÙ Ó ÍÉÎÉÍÁÌØÎÙÍ ÚÎÁÞÅÎÉÅÍ ÐÁÒÁÍÅÔÒÏ×", "Dates with minimum of paremeters");
_LANG(_s_Diapazon_, "äÁÎÎÙÅ ÉÚ ×ÙÂÒÁÎÎÏÇÏ ÄÉÁÐÁÚÏÎÁ:", "Data from selected range:");
_LANG(_s_Modes_, "òÅÖÉÍÙ ÒÁÂÏÔÙ", "Work modes");
_LANG(_s_And_, "É", "and");
_LANG(_s_Or_, "ÉÌÉ", "or");
_LANG(_s_Mode_Times_, "óÕÍÍÁÒÎÏÅ ×ÒÅÍÑ ÒÁÂÏÔÙ × ÒÅÖÉÍÁÈ", "Total work time in modes");
_LANG(_s_seconds_, "ÓÅËÕÎÄ", "seconds");
_LANG(_s_days_, "ÓÕÔÏË", "days");
_LANG(_s_Stopped_, "ðÏÌÎÙÊ ÏÓÔÁÎÏ×", "Full stop");
_LANG(_s_Guiding_, "óÏÐÒÏ×ÏÖÄÅÎÉÅ ÏÂßÅËÔÁ", "Object guiding");
_LANG(_s_Ready_, "çÏÔÏ×", "Ready");
_LANG(_s_Other_, "ðÒÏÞÅÅ", "Other");
_LANG(_s_Total_, "éÔÏÇÏ", "Total");
//_LANG(, "", "");

15
C/daemon/Makefile Normal file
View File

@ -0,0 +1,15 @@
CC = gcc
LDFLAGS = -lcrypt
CPPFLAGS =
all : daemon tempmon tempmon_cli clean
daemon : daemon.o
$(CC) $(LDFLAGS) daemon.c $(CPPFLAGS) -o daemon
tempmon : client.o
$(CC) client.c $(CPPFLAGS) -o tempmon
tempmon_cli : client_cli.o
$(CC) client_cli.c $(CPPFLAGS) -o tempmon_cli
clean:
/bin/rm -f *.o *~
### <DEPENDENCIES ON .h FILES GO HERE>
# name1.o : header1.h header2.h ...

1158
C/daemon/bta_shdata.h Normal file

File diff suppressed because it is too large Load Diff

682
C/daemon/client.c Normal file
View File

@ -0,0 +1,682 @@
// client.c
//
// Copyright 2012 Edward V. Emelianoff <eddy@sao.ru>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
// MA 02110-1301, USA.
#define __CLIENT_C__
#include <string.h>
#include "defines.h"
#include "lang.h"
#include "quick_median.c"
#define MAX_QUERY_SIZE 1024 // ÍÁËÓÉÍÁÌØÎÙÊ ÏÂßÅÍ ÄÁÎÎÙÈ, ÐÅÒÅÄÁ×ÁÅÍÙÈ × ÚÁÐÒÏÓÅ
#define SVG 0 // ÉÚÏÂÒÁÖÅÎÉÅ - svg (ÜÔÏÔ ÐÁÒÁÍÅÔÒ ÄÏÌÖÅÎ ÂÙÔØ ÓÁÍÙÍ ÐÅÒ×ÙÍ)
#define JPG 1
//#define JPG 1 -> GIF = 2
#define GIF 2 // ÉÚÏÂÒÁÖÅÎÉÅ - gif (ÄÏÌÖÅÎ ÂÙÔØ ÓÁÍÙÍ ÐÏÓÌÅÄÎÉÍ)
static char* Content_type = "Content-type: multipart/form-data; charset=koi8-r\n\n";
static char* SCRIPT_PATH = "/cgi-bin/eddy/tempmon"; // ÐÏÌÎÙÊ ÐÕÔØ Ë ÓËÒÉÐÔÕ
char *qs = NULL, *buf = NULL;
unsigned char Lang = 1; // ÁÎÇÌÉÊÓËÉÊ
long long starting_pos = 0LL;
typedef struct shm_data shm_d;
int Graph = 0;
time_t t_start, t_end;
time_t aver_interval = 1;
int out_fd;
void sendSVG(const int image_type, unsigned char stat_mask, int im_height);
inline void minmax(float *min, float *max, float param){
if(param > *max) *max = param;
else if(param < *min) *min = param;
}
void print_curvals(unsigned char stat_mask){ // stat_mask - ÂÉÔÏ×ÁÑ ÍÁÓËÁ ÄÌÑ Status
int i=1, f, d_len = 0;
monit_d data;
float max_otemp, min_otemp, avr_otemp, // ×ÎÅÛÎÑÑ ÔÅÍÐÅÒÁÔÕÒÁ
max_itemp, min_itemp, avr_itemp, // ×ÎÕÔÒÅÎÎÑÑ ÔÅÍÐÅÒÁÔÕÒÁ
max_mtemp, min_mtemp, avr_mtemp, // ÔÅÍÐÅÒÁÔÕÒÁ ÚÅÒËÁÌÁ
max_wind, min_wind, avr_wind, // ÓËÏÒÏÓÔØ ×ÅÔÒÁ
max_pres, min_pres, avr_pres, // ÄÁ×ÌÅÎÉÅ
max_hmd, min_hmd, avr_hmd; // ×ÌÁÖÎÏÓÔØ
printf(Content_type);
while(read(out_fd, &data, sizeof(data)) == sizeof(data)){
if(data.seconds < t_start) continue;
if(data.seconds > t_end) break;
if(!(stat_mask & (1 << data.status))) continue;
d_len++;
if(i){
max_otemp = min_otemp = avr_otemp = data.outdoor_temp;
max_itemp = min_itemp = avr_itemp = data.indoor_temp;
max_mtemp = min_mtemp = avr_mtemp = data.mirror_temp;
max_wind = min_wind = avr_wind = data.wind_speed;
max_pres = min_pres = avr_pres = data.pressure;
max_hmd = min_hmd = avr_hmd = data.humidity;
i = 0;
}else{
minmax(&min_otemp, &max_otemp, data.outdoor_temp);
minmax(&min_itemp, &max_itemp, data.indoor_temp);
minmax(&min_mtemp, &max_mtemp, data.mirror_temp);
minmax(&min_wind, &max_wind, data.wind_speed);
minmax(&min_pres, &max_pres, data.pressure);
minmax(&min_hmd, &max_hmd, data.humidity);
avr_otemp += data.outdoor_temp;
avr_itemp += data.indoor_temp;
avr_mtemp += data.mirror_temp;
avr_wind += data.wind_speed;
avr_pres += data.pressure;
avr_hmd += data.humidity;
}
}
if(d_len < 1){
printf("<ha align=center>%s</h1>", _L(_s_noData_));
return;
}
printf("<table>\n"
"<tr><th rowspan=\"2\"></th><th colspan=\"3\">%s</th><th rowspan=\"2\">%s</th>"
"<th rowspan=\"2\">%s</th><th rowspan=\"2\">%s</th></tr>\n"
"<tr><th>%s</th><th>%s</th><th>%s</th></tr>\n"
"<tr><td>min</td><td>%.2f</td><td>%.2f</td><td>%.2f</td><td>%.2f</td><td>%.2f</td><td>%.2f</td></tr>\n"
"<tr><td>max</td><td>%.2f</td><td>%.2f</td><td>%.2f</td><td>%.2f</td><td>%.2f</td><td>%.2f</td></tr>\n"
"<tr><td>avr</td><td>%.2f</td><td>%.2f</td><td>%.2f</td><td>%.2f</td><td>%.2f</td><td>%.2f</td></tr></table>\n"
"%s: %d<p>\n",
_L(_s_Temp_), _L(_s_WSpeed_), _L(_s_Pressure_), _L(_s_Humidity_),
_L(_s_Ot_), _L(_s_It_), _L(_s_Mt_),
min_otemp, min_itemp, min_mtemp, min_wind, min_pres, min_hmd,
max_otemp, max_itemp, max_mtemp, max_wind, max_pres, max_hmd,
avr_otemp/d_len, avr_itemp/d_len, avr_mtemp/d_len,
avr_wind/d_len, avr_pres/d_len, avr_hmd/d_len,
_L(_s_Monlen_), d_len);
printf("<a href=\"%s?Save=1&Tstart=%d&Tend=%d&Stat=%d&Aver=%d\"'>%s</a>\n",
SCRIPT_PATH, t_start, t_end, stat_mask, aver_interval, _L(_s_Save_file_));
}
char* get_qs(char* buf, int l){
char *m, *qs = NULL;
if((m = getenv("REQUEST_METHOD")) && strcasecmp(m, "POST") == 0)
qs = fgets(buf, l, stdin);
else if( (qs = getenv("QUERY_STRING")) )
qs = strncpy(buf, qs, l);
if(qs && strlen(qs) < 1) qs = NULL;
return qs;
}
int get_qs_param(char *qs, char *param, char *meaning, int l){
char *tok, *val, *par, *str;
int stat = 0;
str = calloc(MAX_QUERY_SIZE, 1);
strncpy(str, qs, MAX_QUERY_SIZE);
tok = strtok(str, "& \n");
do{
if((val = strchr(tok, '=')) == NULL) continue;
*val++ = '\0';
par = tok;
if(strcasecmp(par, param)==0){
if(strlen(val) > 0){
stat = 1;
strncpy(meaning, val, l);
meaning[l-1] = 0;
}
break;
}
}while((tok = strtok(NULL, "& \n"))!=NULL);
free(str);
return stat;
}
void send_data(unsigned char stat_mask){
int ii=0, j;
struct timeval tv;
struct tm ltime;
time_t t_first=0, t_last=0;
double otemp=0., itemp=0., mtemp=0., wind=0., pres=0., hum=0.;
int ctr, status, statuses[5] = {0,0,0,0,0};
char s_time[32];
monit_d data;
printf("Content-type: text/plain; charset=koi8-r\n\n");
printf("OT - %s\nIT - %s\nMT - %s\nWS - %s\nP - %s\nH - %s\nS - %s\n\n",
_L(_s_Otemp_), _L(_s_Itemp_), _L(_s_Mtemp_),
_L(_s_WSpeed_), _L(_s_Pressure_), _L(_s_Humidity_),
_L(_s_State_));
printf("%s\t\tOT\tIT\tMT\tWS\tP\tH\tS\n", _L(_s_Date_));
while(read(out_fd, &data, sizeof(data))){
if(data.seconds < t_start) continue;
if(data.seconds > t_end) break;
if(!(stat_mask & (1 << data.status))) continue;
if(t_first == 0) t_first = t_last = data.seconds;
else if((data.seconds - t_first) >= aver_interval){ // ÎÁËÏÐÉÌÉ ÄÏÓÔÁÔÏÞÎÏ ÄÁÎÎÙÈ
t_first = t_first/2 + t_last/2; // ÓÅÒÅÄÉÎÁ ×ÒÅÍÅÎÎÏÇÏ ÉÎÔÅÒ×ÁÌÁ
ltime = *localtime(&t_first);//*localtime(&t_first);
strftime(s_time, 32, "%d/%m/%Y, %H:%M:%S", &ltime);
if(ii == 0) ii = 1;
ctr = 0;
for(j = 0; j<5; j++){
if(statuses[j] > ctr){
ctr = statuses[j];
status = j;
}
statuses[j] = 0;
}
printf("%s\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%d\n",
s_time,
otemp/ii,
itemp/ii,
mtemp/ii,
wind/ii,
pres/ii,
hum/ii,
status);
t_first = data.seconds;
otemp=itemp=mtemp=wind=pres=hum=0.;
ii = 0;
}
t_last = data.seconds;
otemp += data.outdoor_temp;
itemp += data.indoor_temp;
mtemp += data.mirror_temp;
wind += data.wind_speed;
pres += data.pressure;
hum += data.humidity;
statuses[data.status]++;
ii++;
}
}
void fill_forms(const char* alert_message, const char S_flag){
int shmid, i = 0;
char tmp[16];
unsigned char mask;
int im_ht = 600;
if(S_flag == 0){
printf(Content_type);
if(alert_message) printf("<div><h1 align=center>%s</h1></div>\n", alert_message);
return;
}
if(get_qs_param(qs, "Stat", tmp, 16))
mask = atoi(tmp);
else mask = 0xff;
if(get_qs_param(qs, "height", tmp, 16)){
im_ht = atoi(tmp);
if(im_ht < 100 || im_ht > 800) im_ht = 600;
}
if(Graph){
if(get_qs_param(qs, "Gtype", tmp, 16)){
i = atoi(tmp);
if(i<SVG || i>GIF)
i = GIF;
}
else i = GIF;
sendSVG(i, mask, im_ht);
}
else{
if(S_flag == 2) send_data(mask);
else print_curvals(mask);
}
}
void sendSVG(const int image_type, unsigned char stat_mask, int im_height){
FILE *plot = NULL;
char s_time[32];
struct tm ltime;
struct timeval tv;
monit_d md, *data, *ptr;
time_t time_interval;
unsigned char Flag, Comma = 0;
int twographs = 0;
char *titles[] = {"T out", "T in", "T mir", "Wind", "Pres", "Hum"};
char *command= "/Users/eddy/bin/gnuplot";
char *types[] = {"svg", "jpeg", "gif"};
char *contents[] = {"svg+xml", "jpeg", "gif"};
int f, i, j, d_len, rb;
data = calloc(1002, sizeof(monit_d)); // ÍÁËÓÉÍÕÍ ÔÙÓÑÞÁ ÔÏÞÅË
ptr = data;
printf("Content-type: image/%s\n\n", contents[image_type]);
if(Graph < 1 || Graph > 63){
fprintf(stderr, "Graph=%d, out of range\n", Graph);
goto ret;
}
d_len = 0;
//lseek(out_fd, 0, SEEK_SET);
while(read(out_fd, &md, sizeof(md))){
//fprintf(stderr, "time=%d, t_start=%d, t_end=%d, d_len=%d, time_interval=%d\n", md.seconds, t_start, t_end, d_len, time_interval);
if(md.seconds < t_start) continue;
if(md.seconds > t_end) break;
if(d_len == 0){
t_start = md.seconds;
time_interval = (t_end - t_start) / 300;
}
*ptr++ = md;
if(++d_len > 300) break; // ÌÉÛÎÉÅ ÚÎÁÞÅÎÉÑ
t_start += time_interval;
//fprintf(stderr, ">>>time=%d, t_start=%d, t_end=%d, d_len=%d, time_interval=%d\n", md.seconds, t_start, t_end, d_len, time_interval);
}
close(f);
if(d_len < 3){
fprintf(stderr, "d_len=%d, error\n", d_len);
goto ret;
}
plot = popen(command, "w");
if(plot == NULL){
perror("can't run gnuplot\n");
goto ret;
}
//fprintf(plot, "set terminal %s size 800,%d font \"/usr/share/fonts/liberation/LiberationSans-Regular.ttf\"\nset xdata time\nset timefmt \"%%d/%%m-%%H:%%M\"\nset format x \"%%H:%%M\\n%%d/%%m\"\n",
fprintf(plot, "set terminal %s size 800,%d\nset xdata time\nset timefmt \"%%d/%%m-%%H:%%M\"\nset format x \"%%H:%%M\\n%%d/%%m\"\n",
types[image_type], im_height);
if((Graph & 16) && (Graph & 32)){ // ÐÒÉÓÕÔÓÔ×ÕÀÔ É ×ÌÁÖÎÏÓÔØ, É ÄÁ×ÌÅÎÉÅ
twographs = 1;
if(Graph & 15) // ÅÓÔØ ÅÝÅ ÄÁÎÎÙÅ
fprintf(plot, "set multiplot\nset origin 0,0\nset size 1,0.5\n");
}
else if(Graph & 48){ // ÐÒÉÓÕÔÓÔ×ÕÀÔ ÔÏÌØËÏ ×ÌÁÖÎÏÓÔØ, ÌÉÂÏ ÔÏÌØËÏ ÄÁ×ÌÅÎÉÅ
if(Graph & 15){ // ×Ù×ÏÄÉÍ ÅÝÅ ÞÔÏ-ÎÉÂÕÄØ
fprintf(plot, "set ytics nomirror\nset y2tics\nset ylabel \"degr C, m/s\"\n");
if(Graph & 16)
fprintf(plot, "set y2label \"mmHg\"\n"); // ÐÏÄÐÉÓØ ÄÌÑ ÄÁ×ÌÅÎÉÑ
else
fprintf(plot, "set y2label \"%%\"\n"); // ÐÏÄÐÉÓØ ÄÌÑ ×ÌÁÖÎÏÓÔÉ
}
}
fprintf(plot, "plot ");
for(j = 0; j < 4; j++){
Flag = Graph & (1 << j);
if(Flag){
if(Comma) fprintf(plot, ",");
Comma = 1;
//w l smooth csplines
fprintf(plot, " '-' using 1:2 w l lt %d title '%s'", j+1, titles[j]);
}
}
if(!twographs){
for(j = 4; j < 6; j++){
if(Graph & (1 << j)){
if(Comma) fprintf(plot, ",");
Comma = 1;
fprintf(plot, " '-' using 1:2 w l axes x1y2 lt %d title '%s'", j+1, titles[j]);
}
}
}
fprintf(plot, "\n");
for(j = 0; j < 6; j++){
Flag = Graph & (1 << j);
if(twographs && j > 3) break;
if(Flag){
for(i = 0; i < d_len; i++){
if(!(stat_mask & (1 << data[i].status))) continue;
time_t X = (time_t)data[i].seconds;
ltime = *localtime(&X);
strftime(s_time, 32, "%d/%m-%H:%M", &ltime);
fprintf(plot, "%s ", s_time);
switch(Flag){
case 1: fprintf(plot, "%.2f\n", data[i].outdoor_temp);
break;
case 2: fprintf(plot, "%.2f\n", data[i].indoor_temp);
break;
case 4: fprintf(plot, "%.2f\n", data[i].mirror_temp);
break;
case 8: fprintf(plot, "%.2f\n", data[i].wind_speed);
break;
case 16: fprintf(plot, "%.2f\n", data[i].pressure);
break;
case 32: fprintf(plot, "%.2f\n", data[i].humidity);
break;
}
}
fprintf(plot, "e\n");
}
}
if(twographs){
if(Graph & 15) // ÓÔÒÏÉÍ 2 ÇÒÁÆÉËÁ
fprintf(plot, "set origin 0,0.5\nset size 1,0.5\n");
fprintf(plot, "set ylabel \"mmHg\"\nset y2label \"%%\"\n");
fprintf(plot, "plot '-' using 1:2 w l lt 1 title 'Pres',");
fprintf(plot, " '-' using 1:2 w l axes x1y2 lt 2 title 'Hum'\n");
for(j = 0; j < 2; j++){
for(i = 0; i < d_len; i++){
if(!(stat_mask & (1 << data[i].status))) continue;
time_t X = (time_t)data[i].seconds;
ltime = *localtime(&X);
strftime(s_time, 32, "%d/%m-%H:%M", &ltime);
fprintf(plot, "%s ", s_time);
switch(j){
case 0: fprintf(plot, "%.2f\n", data[i].pressure); break;
case 1: fprintf(plot, "%.2f\n", data[i].humidity); break;
}
}
fprintf(plot, "e\n");
}
}
ret:
if(plot){
fflush(plot);
pclose(plot);
}
free(data);
}
void find_starting_pos(){ // ÉÝÅÍ × ËÜÛÅ ÓÍÅÝÅÎÉÅ ÄÌÑ ÎÁÞÁÌÁ ÐÏÉÓËÁ
int cache_fd;
Cache cache;
if((cache_fd = open(CACHE_FILE, O_RDONLY)) < 0){
printf(Content_type);
printf("<h1>%s</h1>", _L(_s_Cant_open_cache_));
exit(1);
}
while(read(cache_fd, &cache, sizeof(cache))){
if(cache.time < t_start)
starting_pos = cache.offset;
else break;
}
close(cache_fd);
}
void quit(int status){
if(buf) free(buf);
if(out_fd) close(out_fd);
exit(status);
}
char *switch_names(int i, char* ss){
switch(i){
case 0: ss = _L(_s_Otemp_); break;
case 1: ss = _L(_s_Itemp_); break;
case 2: ss = _L(_s_Mtemp_); break;
case 3: ss = _L(_s_WSpeed_); break;
case 4: ss = _L(_s_Pressure_); break;
case 5:
default: ss = _L(_s_Humidity_);
}
return ss;
}
char *format_time(time_t t, char *ss, int i){
struct timeval tv;
struct tm ltime = *localtime(&t);
strftime(ss, i, "%d/%m/%Y, %H:%M", &ltime);
return ss;
}
void print_string(time_t t1, time_t t2, int i){
char s_t1[32], s_t2[32], *ss;
printf("%s - %s (%s)<br>\n", format_time(t1, s_t1, 32),
format_time(t2, s_t2, 32), switch_names(i, ss));
}
void show_extremums(int ch){
int stat_mask = 0xFF, i, AndOr = 0, memsize, counter, first;
char tmp[32], g = 0, l = 0, *ss;
monit_d data;
float Greater, Less;
float extr[6], *meds[6]={NULL, NULL, NULL, NULL, NULL, NULL}; // ÜËÓÔÒÅÍÕÍÙ, ÍÅÄÉÁÎÙ
struct timeval tv;
struct tm ltime;
time_t t1[6], t2[6], t_first=0, t_last=0;
printf(Content_type);
if(get_qs_param(qs, "Stat", tmp, 16))
stat_mask = atoi(tmp);
if(stat_mask == 0) stat_mask = 0xFF;
if(get_qs_param(qs, "Graph", tmp, 16))
Graph = atoi(tmp);
if(Graph == 0) Graph = 63;
if(ch == 3){ // ÐÏÌÕÞÅÎÉÅ ÄÁÎÎÙÈ É ÐÒÏ×ÅÒËÁ ÉÈ ËÏÒÒÅËÔÎÏÓÔÉ
if(get_qs_param(qs, "AndOr", tmp, 16))
AndOr = atoi(tmp);
if((AndOr & 1) != AndOr) AndOr = 0;
if(get_qs_param(qs, "Greater", tmp, 32)){
Greater = atof(tmp);
g = 1;
}
if(get_qs_param(qs, "Less", tmp, 32)){
Less = atof(tmp);
l = 1;
}
if(!(g | l) || // ÎÅÔ ÎÉ Greater, ÎÉ Less
(AndOr && !(g & l)) // ÕËÁÚÁÎÏ "é", ÎÏ ÎÅ È×ÁÔÁÅÔ ÄÁÎÎÙÈ
){
printf("<h1>%s</h1>\n", _L(_s_No_Data_));
return;
}
if(AndOr){
if(Greater >= Less){
printf("<h1>%s</h1>\n", _L(_s_G_mustbe_less_L_));
return;
}
}
else{
if((g & l) && (Greater <= Less)){
printf("<h1>%s</h1>\n", _L(_s_L_mustbe_less_G_));
return;
}
}
}
if(aver_interval < 60) aver_interval = 60; // ÍÅÄÉÁÎÎÏÅ ÕÓÒÅÄÎÅÎÉÅ ÐÏ ËÒÁÊÎÅÊ ÍÅÒÅ ÚÁ ÍÉÎÕÔÕ
switch(ch){
case 0: ss = _L(_s_Modes_); break;
case 1: ss = _L(_s_Max_data_); break;
case 2: ss = _L(_s_Min_data_); break;
case 3:
default: ss = _L(_s_Diapazon_);
}
printf("<h2>%s ", ss);
if(ch == 3){
if(g){
printf("%s %.1f ", _L(_s_Gtr_), Greater);
if(AndOr) printf("%s ", _L(_s_And_));
else if(l) printf("%s ", _L(_s_Or_));
}
if(l) printf("%s %.1f", _L(_s_Less_), Less);
}
printf("</h2>\n");
memsize = aver_interval / TIMEINTERVAL + 3;
if(ch) for(i = 0; i < 6; i++)
if(Graph & (1<<i)) meds[i] = (float*)calloc(memsize, sizeof(float));
counter = 0;
if(ch == 1 || ch == 2) first = 1;
else for(i=0; i<6; i++) t1[i] = 0;
while(read(out_fd, &data, sizeof(data))){
if(data.seconds < t_start) continue;
if(ch == 0){
i = (int)(TIMEINTERVAL + 0.5);
t1[5] += i;
t1[data.status] += i;
}
if(!(stat_mask & (1 << data.status))){
if(ch == 0 && t_first){
t_last = data.seconds;
printf("%s - ", format_time(t_first, tmp, 32));
printf("%s<br>\n", format_time(t_last, tmp, 32));
t_first = 0;
}
continue;
}
if(ch == 0){ // ÏÃÅÎËÁ ×ÒÅÍÅÎÎùÈ ÉÎÔÅÒ×ÁÌÏ×
if(t_first == 0) t_first = t_last = data.seconds;
continue;
}
if(t_first == 0) t_first = t_last = data.seconds;
else if((data.seconds - t_first) >= aver_interval || counter > memsize || data.seconds > t_end){
t_first = t_first/2 + t_last/2; // ÓÅÒÅÄÉÎÁ ×ÒÅÍÅÎÎÏÇÏ ÉÎÔÅÒ×ÁÌÁ
for(i=0; i<6; i++)
if(Graph & (1<<i)) meds[i][0] = quick_select(meds[i], counter);
if(first){
first = 0;
for(i=0; i<6; i++){
if(Graph & (1<<i)){
extr[i] = meds[i][0];
t1[i] = t_first;
}
}
}
else if(ch != 3){
for(i=0; i<6; i++)
if(Graph & (1<<i)){
if(ch == 1){ // ÉÝÅÍ ÍÁËÓÉÍÕÍÙ
if(meds[i][0] > extr[i]){
extr[i] = meds[i][0];
t1[i] = t_first;
}
}
else{ // ch = 2 - ÉÝÅÍ ÍÉÎÉÍÕÍÙ
if(meds[i][0] < extr[i]){
extr[i] = meds[i][0];
t1[i] = t_first;
}
}
}
}
else{ // ÉÝÅÍ ÐÅÒÉÏÄÙ (ch == 3)
for(i=0; i<6; i++)
if(Graph & (1<<i)){
if(AndOr){ // ÉÝÅÍ ÂÏÌØÛÅ Greater É ÍÅÎØÛÅ Less
if(meds[i][0] > Greater && meds[i][0] < Less)
if(t1[i] == 0) t1[i] = t2[i] = t_first;
else t2[i] = t_first;
else if(t1[i] != 0){
print_string(t1[i], t2[i], i);
t1[i] = 0;
}
}
else{ // ×ÁÒÉÁÎÔ Ó "ÉÌÉ"
if( (g && meds[i][0] > Greater) || (l && meds[i][0] < Less) )
if(t1[i] == 0) t1[i] = t2[i] = t_first;
else t2[i] = t_first;
else if(t1[i] != 0){ // ×Ù×ÏÄÉÍ ÄÁÎÎÙÅ
print_string(t1[i], t2[i], i);
t1[i] = 0;
}
}
}
}
t_first = data.seconds;
counter = 0;
}
if(data.seconds > t_end) break;
t_last = data.seconds;
if(Graph & 1) meds[0][counter] = data.outdoor_temp;
if(Graph & 2) meds[1][counter] = data.indoor_temp;
if(Graph & 4) meds[2][counter] = data.mirror_temp;
if(Graph & 8) meds[3][counter] = data.wind_speed;
if(Graph & 16) meds[4][counter] = data.pressure;
if(Graph & 32) meds[5][counter] = data.humidity;
counter++;
}
if(ch == 1 || ch == 2)
for(i=0; i<6; i++){
if(Graph & (1<<i))
printf("%s %s: %.1f<br>\n", format_time(t1[i], tmp, 32),
switch_names(i, ss), extr[i]);
}
if(ch == 0){
printf("<h2>%s</h2>\n", _L(_s_Mode_Times_));
inline void fmtprnt(char **str, time_t tm){
printf("%s: %d %s (%.2f %s)<br>\n", _L(str), tm, _L(_s_seconds_),
((float)tm)/86400., _L(_s_days_));
}
fmtprnt(_s_Stopped_, t1[0]);
fmtprnt(_s_Guiding_, t1[1]);
fmtprnt(_s_Ready_, t1[2]);
fmtprnt(_s_Other_, t1[3]);
fmtprnt(_s_Vopen_, t1[4]);
fmtprnt(_s_Total_, t1[5]);
}
for(i=0; i<6; i++) if(meds[i]) free(meds[i]);
}
int main(){
char *ptr, tmp[128];
setbuf(stdout, NULL);
buf = (char*)calloc(MAX_QUERY_SIZE, 1);
ptr = getenv("HTTP_ACCEPT_LANGUAGE");
if(ptr) if(strncmp(ptr, "ru", 2) == 0) Lang = 0; // ÉÓÐÏÌØÚÕÅÍ ÒÕÓÓËÉÊ
qs = get_qs(buf, MAX_QUERY_SIZE);
if(!qs){
fill_forms(_L(_s_no_QS_), 0);
quit(0);
}
if(get_qs_param(qs, "Visor", tmp, 128)){ // ÏÔËÒÙ×ÁÅÍ/ÚÁËÒÙ×ÁÅÍ ÚÁÂÒÁÌÏ
int shmid, param = atoi(tmp);
shmid = shmget(SHM_KEY, sizeof(int), IPC_CREAT | 0666);
printf(Content_type);
if(shmid < 0) printf(_L(_s_noVisor_));
else{
Visor = (int*) shmat(shmid, NULL, 0);
if(Visor){
if(param > 0) *Visor = !(*Visor); // param >0 - ÓÍÅÎÁ ÓÏÓÔÏÑÎÉÑ
}
else printf(_L(_s_noVisor_));
}
printf("%s:<br><font color='%s'>%s</font><p style='margin-top: 25px;'>%s:<br>", _L(_s_CurVstat_),
*Visor?"green":"red", *Visor?_L(_s_Vopen_):_L(_s_Vclose_), _L(_s_ChVstat_));
printf("<input type='button' OnClick='sendrequest(\"Visor=1\", visor);' "
"value=\"%s\">", *Visor ? _L(_s_Vclose_) : _L(_s_Vopen_) );
quit(0);
}
if(!get_qs_param(qs, "Tstart", tmp, 128)){
if(!get_qs_param(qs, "Graph", tmp, 16))
fill_forms(_L(_s_no_tstart_), 0);
quit(0);
}
t_start = atoi(tmp);
if(get_qs_param(qs, "Tend", tmp, 128))
t_end = atoi(tmp);
else
t_end = time(NULL);
if(t_end <= t_start){
if(!get_qs_param(qs, "Graph", tmp, 16))
fill_forms(_L(_s_Bad_date_), 0);
quit(1);
}
if(get_qs_param(qs, "Aver", tmp, 128)){
aver_interval = atoi(tmp);
if(aver_interval < 1) aver_interval = 1;
}
find_starting_pos();
if((out_fd = open(OUT_FILE, O_RDONLY)) < 0){
exit(1);
}
lseek(out_fd, starting_pos, SEEK_SET);
if(get_qs_param(qs, "Select", tmp, 16)){
int choice = atoi(tmp);
if(choice < 0 || choice > 3){
fill_forms(NULL, 1);
quit(0);
}
show_extremums(choice);
quit(0);
}
if(get_qs_param(qs, "Graph", tmp, 16)){
Graph = atoi(tmp);
if(Graph == 0) Graph = -1;
fill_forms(NULL, 1);
quit(0);
}
if(get_qs_param(qs, "Save", tmp, 16)){
fill_forms(NULL, 2); // ÓÏÈÒÁÎÉÔØ ÄÁÎÎÙÅ
quit(0);
}
else{
fill_forms(NULL, 1); // ÐÏËÁÚÁÔØ ÜËÓÔÒÅÍÁÌØÎÙÅ ÚÎÁÞÅÎÉÑ
quit(0);
}
quit(0);
}

328
C/daemon/client_cli.c Normal file
View File

@ -0,0 +1,328 @@
// client.c
//
// Copyright 2012 Edward V. Emelianoff <eddy@sao.ru>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
// MA 02110-1301, USA.
#define __CLIENT_C__
#include <string.h>
#include <getopt.h>
#include <stdarg.h>
#include <stdlib.h>
#include "defines.h"
#include "lang.h"
#define Julian(x) ((double)x/86400. + 2440587.5)
extern const char *__progname;
char *db_path = A_PATH;
off_t starting_pos = 0LL;
typedef struct shm_data shm_d;
unsigned char Lang = 1; // ÁÎÇÌÉÊÓËÉÊ
time_t t_start = 0, t_end = 0;
time_t aver_interval = 1;
int force_dbpath = 0;
int out_fd;
inline void minmax(float *min, float *max, float param){
if(param > *max) *max = param;
else if(param < *min) *min = param;
}
void send_data(unsigned char stat_mask){
int ii=0, j;
struct tm ltime;
time_t t_first=0, t_last=0;
double otemp=0., itemp=0., mtemp=0., wind=0., pres=0., hum=0.;
int ctr, status, statuses[5] = {0,0,0,0,0};
char s_time[32];
monit_d data;
printf("OT - %s\nIT - %s\nMT - %s\nWS - %s\nP - %s\nH - %s\nS - %s\n\n",
_L(_s_Otemp_), _L(_s_Itemp_), _L(_s_Mtemp_),
_L(_s_WSpeed_), _L(_s_Pressure_), _L(_s_Humidity_),
_L(_s_State_));
printf("%s\t\tJulian date\tOT\tIT\tMT\tWS\tP\tH\tS\n", _L(_s_Date_));
while(read(out_fd, &data, sizeof(data)) > 0){
time_t X = (time_t) data.seconds;
//printf("time: %zd -- %s", data.seconds, ctime(&X));
if(X < t_start) continue;
if(X > t_end) break;
if(!(stat_mask & (1 << data.status))) continue;
if(t_first == 0) t_first = t_last = X;
else if((X - t_first) >= aver_interval){ // ÎÁËÏÐÉÌÉ ÄÏÓÔÁÔÏÞÎÏ ÄÁÎÎÙÈ
t_first = t_first/2 + t_last/2; // ÓÅÒÅÄÉÎÁ ×ÒÅÍÅÎÎÏÇÏ ÉÎÔÅÒ×ÁÌÁ
ltime = *localtime(&t_first);//*localtime(&t_first);
strftime(s_time, 32, "%d/%m/%Y, %H:%M:%S", &ltime);
if(ii == 0) ii = 1;
ctr = 0;
for(j = 0; j<5; j++){
if(statuses[j] > ctr){
ctr = statuses[j];
status = j;
}
statuses[j] = 0;
}
printf("%s\t%.6f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%d\n",
s_time,
Julian(t_first),
otemp/ii,
itemp/ii,
mtemp/ii,
wind/ii,
pres/ii,
hum/ii,
status);
t_first = X;
otemp=itemp=mtemp=wind=pres=hum=0.;
ii = 0;
}
t_last = X;
otemp += data.outdoor_temp;
itemp += data.indoor_temp;
mtemp += data.mirror_temp;
wind += data.wind_speed;
pres += data.pressure;
hum += data.humidity;
statuses[data.status]++;
ii++;
}
}
void find_starting_pos(){ // ÉÝÅÍ × ËÜÛÅ ÓÍÅÝÅÎÉÅ ÄÌÑ ÎÁÞÁÌÁ ÐÏÉÓËÁ
int cache_fd;
Cache cache;
if(force_dbpath){
char cname[256];
snprintf(cname, 255, "%s/.cache", db_path);
cache_fd = open(cname, O_RDONLY);
}else{
if((cache_fd = open(CACHE_FILE, O_RDONLY)) < 0)
cache_fd = open("./cache", O_RDONLY);
}
if(cache_fd < 0){
WARN(_L(_s_Cant_open_cache_));
exit(1);
}
while(read(cache_fd, &cache, sizeof(cache)) > 0){
//time_t X = (time_t) cache.time;
//printf("time: %zd -- %s", cache.time, ctime(&X));
if(cache.time < t_start)
starting_pos = cache.offset;
else break;
}
//printf("pos: %zd \n", starting_pos);
close(cache_fd);
}
time_t get_date(char *line){
time_t date = time(NULL);
struct tm time_, time_now;
time_now = *localtime(&date);
time_.tm_sec = 0;
if(sscanf(line, "%d/%d/%d-%d:%d", &time_.tm_mday, &time_.tm_mon, &time_.tm_year,
&time_.tm_hour, &time_.tm_min) == 5){time_.tm_mon -= 1;}
else if(!strchr(line, ':') && sscanf(line, "%d/%d/%d", &time_.tm_mday, &time_.tm_mon, &time_.tm_year) == 3){
date = -1; time_.tm_mon -= 1;}
else if(!strchr(line, ':') && sscanf(line, "%d/%d", &time_.tm_mday, &time_.tm_mon) == 2){
date = -1; time_.tm_mon -= 1; time_.tm_year = time_now.tm_year;}
else if(sscanf(line, "%d:%d", &time_.tm_hour, &time_.tm_min) == 2){
time_.tm_year = time_now.tm_year; time_.tm_mon = time_now.tm_mon;
time_.tm_mday = time_now.tm_mday;}
else if(!strchr(line, ':') && !strchr(line, '/') && !strchr(line, '.') && !strchr(line, '-')
&& sscanf(line, "%d", &time_.tm_mon) == 1){
date = -1; time_.tm_mon -= 1; time_.tm_year = time_now.tm_year;
time_.tm_mday = 1;}
else{
printf("\nWrong datetime format!\n");
printf("Formats: D/M/Y-hh:mm, D/M/Y, hh:mm, D/M, M\n");
exit(1);
}
if(date == -1){
time_.tm_hour = 0;
time_.tm_min = 0;
}
if(time_.tm_mon > 11 || time_.tm_mon < 0){
printf("\nMonth should be in 1..12\n");
exit(2);
}
if(time_.tm_mday > 31 || time_.tm_mday < 1){
printf("\nDate should be in 1..31, %d\n", time_.tm_mday);
exit(3);
}
if(time_.tm_year > 1900) time_.tm_year -= 1900;
else if(time_.tm_year > -1 && time_.tm_year < 100) time_.tm_year += 100;
else if(time_.tm_year < 0 || time_.tm_year > 200){
printf("\nBad year format %d\n", time_.tm_year);
exit(4);
}
if(time_.tm_hour > 23 || time_.tm_hour < 0){
printf("\nTime should be in 0..23\n");
exit(5);
}
if(time_.tm_min > 59 || time_.tm_min < 0){
printf("\nMinutes should be in 0..59\n");
exit(6);
}
date = mktime(&time_);
return date;
}
void print_dates(){
char s_time[32];
inline char *mktm(uint32_t t){
time_t X = (time_t) t;
struct tm ltime = *localtime(&X);
strftime(s_time, 32, "%d/%m/%Y, %H:%M:%S", &ltime);
return s_time;
}
monit_d data;
if(read(out_fd, &data, sizeof(data)) != sizeof(data)){
WARN("Error reading datafile!\n");
exit(1);
}
printf("Date of first record in database: %s\n", mktm(data.seconds));
lseek(out_fd, -sizeof(data), SEEK_END);
if(read(out_fd, &data, sizeof(data)) != sizeof(data)){
WARN("Error reading datafile!\n");
exit(1);
}
printf("Date of last record in database: %s\n", mktm(data.seconds));
exit(0);
}
unsigned char get_modemask(const char *optarg){
unsigned char mode = 0;
char c;
while((c = *optarg++)){
switch (c){
case 's': case 'S':
mode |= 1;
break;
case 'g': case 'G':
mode |= 2;
break;
case 'r': case 'R':
mode |= 4;
break;
case 'u': case 'U':
mode |= 8;
break;
case 'o': case 'O':
mode |= 16;
break;
default:
WARN("Bad mode: should be sgruo\n");
exit(1);
}
}
return mode;
}
void usage(char *fmt, ...){
va_list ap;
va_start(ap, fmt);
printf("\n");
if (fmt != NULL){
vprintf(fmt, ap);
printf("\n\n");
}
va_end(ap);
printf("Usage:\t%s [options]\n",
__progname);
printf("\tOptions:\n");
printf("\t-d, --dbpath\t\tPath to database files\n");
printf("\t-e, --tend\t\tEnding time (D/M/Y-hh:mm)\n");
printf("\t-h, --help\t\tShow this help\n");
printf("\t-i, --averint\t\tTime interval for data averaging (in seconds)\n");
printf("\t-l, --lookout\t\t Show date interval of stored data\n");
printf("\t-m, --mode\t\tTelescope mode (sgruo - Stopped, Guiding, Ready, Unknown, Opened)\n");
printf("\t-s, --tstart\t\tStarting time (D/M/Y-hh:mm)\n");
exit(0);
}
int main(int argc, char **argv){
unsigned char mask = 0;
struct option long_options[] = {
{"dbpath", 1, 0, 'd'},
{"tend", 1, 0, 'e'},
{"help", 0, 0, 'h'},
{"averint", 1, 0, 'i'},
{"lookout", 0, 0, 'l'},
{"mode", 1, 0, 'm'},
{"tstart", 1, 0, 's'}
};
char short_options[] = "d:e:hi:lm:s:";
int lookout = 0;
while (1){
int opt;
if((opt = getopt_long(argc, argv, short_options,
long_options, NULL)) == -1) break;
switch(opt){
case 'd':
db_path = strdup(optarg);
force_dbpath = 1;
break;
case 'e':
t_start = get_date((char*)optarg);
break;
case 'h':
usage(NULL);
break;
case 'i':
aver_interval = atoi((char*)optarg);
if(aver_interval < 1) aver_interval = 1;
break;
case 'l':
lookout = 1;
break;
case 'm':
mask = get_modemask(optarg);
break;
case 's':
t_start = get_date((char*)optarg);
break;
default:
usage("Unknown argument");
}
}
if(argc != optind) usage("Too many arguments");
if(t_end < 1) t_end = time(NULL);
if(t_end <= t_start){
WARN("%s\n", _L(_s_Bad_date_));
return(1);
}
if(mask == 0) mask = 0xff;
if(force_dbpath){
char cname[256];
snprintf(cname, 255, "%s/.out", db_path);
out_fd = open(cname, O_RDONLY);
}else{
if((out_fd = open(OUT_FILE, O_RDONLY)) < 0)
out_fd = open("./out", O_RDONLY);
}
if(out_fd < 0){
WARN(_L(_s_Cant_open_data_));
return(1);
}
if(lookout) print_dates();
find_starting_pos();
lseek(out_fd, starting_pos, SEEK_SET);
send_data(mask);
return(0);
}

BIN
C/daemon/daemon Executable file

Binary file not shown.

312
C/daemon/daemon.c Normal file
View File

@ -0,0 +1,312 @@
// daemon.c - gathering info daemon
//
// Copyright 2012 Edward V. Emelianoff <eddy@sao.ru>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
// MA 02110-1301, USA.
#include "defines.h"
#include "quick_median.c"
uint Nth = 1 << CACHE_EVERY_PWR; // ÛÁÇ ÐÏ ËÜÛÉÒÏ×ÁÎÉÀ
int MAX_DATA_LEN = 1; // ÄÌÉÎÁ ÍÁÓÓÉ×Ï× ÄÁÎÎÙÈ
int shmid;
int cache_fd, out_fd; // ÄÅÓËÒÉÐÔÏÒÙ ÆÁÊÌÏ× ËÜÛÁ É ×ÙÈÏÄÎÏÇÏ ÆÁÊÌÁ
FILE *F_log;
char TERMINATED[] = "Caught SIGTERM. Quit.";
char HUPPED[] = "Caught SIGHUP. Quit.";
char QUITTED[] = "Caught SIGQUIT. Quit.";
char INTTED[] = "Caught SIGINT. Quit.";
char STARTED[] = "Started.";
char *pidfilename = PID_FILE;
data_type *t_out=NULL, *t_in=NULL, *t_mir=NULL,
*pres=NULL, *hum=NULL; // ÂÕÄÕÝÉÅ ÍÁÓÓÉ×Ù ÄÌÑ ÄÁÎÎÙÈ
int readname(char *name, pid_t pid){ // ÓÞÉÔÁÔØ ÉÍÑ ÐÒÏÃÅÓÓÁ ÉÚ /proc/...
char *pp = name, byte, path[256];
int cntr = 0, file;
snprintf (path, 255, PROC_BASE "/%d/cmdline", pid);
file = open(path, O_RDONLY);
if(file == -1) return 0; // ÎÅÔ ÆÁÊÌÁ ÉÌÉ ÞÕÖÏÊ ÐÒÏÃÅÓÓ
do{ // ÓÞÉÔÙ×ÁÅÍ ÉÍÑ ÂÅÚ ÓÌÅÛÅÊ
read(file, &byte, 1);
if (byte != '/') *pp++ = byte;
else pp = name;
}
while(byte != EOF && byte != 0 && cntr++ < 255);
name[255] = 0;
close(file);
return 1;
}
void check4running(){
DIR *dir;
FILE* pidfile;
struct dirent *de;
struct stat s_buf;
pid_t pid, self, run = 0;
char name[256], myname[256];
if (!(dir = opendir(PROC_BASE))){ // ÏÔËÒÙ×ÁÅÍ ÄÉÒÅËÔÏÒÉÀ /proc
perror(PROC_BASE);
exit(1);
}
self = getpid(); // Ó×ÏÊ ÉÄÅÎÔÉÆÉËÁÔÏÒ
if(stat(pidfilename, &s_buf) == 0){ // ÅÓÔØ ÆÁÊÌ Ó pid'ÏÍ
pidfile = fopen(pidfilename, "r");
fscanf(pidfile, "%d", &run); // ÐÏÌÕÞÁÅÍ pid (×ÏÚÍÏÖÎÏ) ÚÁÐÕÝÅÎÎÏÇÏ ÐÒÏÃÅÓÓÁ
fclose(pidfile);
if(readname(name, run) && strncmp(name, myname, 255) == 0){
WARN("\nFound running process (pid=%d), exit.\n", run);
exit(0);
}
}
// ÆÁÊÌÁ Ó pid'ÏÍ ÎÅÔ, ÉÌÉ ÔÁÍ ÎÅÐÒÁ×ÉÌØÎÁÑ ÚÁÐÉÓØ
readname(myname, self); // Ó×ÏÅ ÉÍÑ ÐÒÏÃÅÓÓÁ
while ((de = readdir (dir)) != NULL){ // ÐÏËÁ ÎÅ ÄÏÊÄÅÍ ÄÏ ËÏÎÃÁ ÄÉÒÅËÔÏÒÉÉ
// ÐÒÏÐÕÓÔÉÍ, ÅÓÌÉ ÄÉÒÅËÔÏÒÉÑ ÎÅ ÕËÁÚÙ×ÁÅÔ ÎÁ ÐÒÏÃÅÓÓ, ÉÌÉ ÕËÁÚÙ×ÁÅÔ ÎÁ self
if (!(pid = (pid_t) atoi (de->d_name)) || pid == self)
continue;
readname(name, pid); // ÓÞÉÔÙ×ÁÅÍ ÉÍÑ ÐÒÏÃÅÓÓÁ
if(strncmp(name, myname, 255) == 0){ // ÅÓÌÉ ÏÎÏ ÓÏ×ÐÁÄÁÅÔ Ó myname
WARN("\nFound running process (pid=%d), exit.\n", pid);
exit(0);
}
}
closedir(dir);
unlink(pidfilename); // ÐÒÏÂÕÅÍ ÕÄÁÌÉÔØ pidfilename
WARN("my PID: %d\n", self);
pidfile = fopen(pidfilename, "w");
fprintf(pidfile, "%d\n", self); // ÚÁÐÉÓÙ×ÁÅÍ × pidfilename Ó×ÏÊ pid
fclose(pidfile);
}
inline void LOG(char* thetime, char* thetext){
fprintf(stderr, "%s\t%s\n", thetime, thetext);
fprintf(F_log, "%s\t%s\n", thetime, thetext);
}
double dtime(){
double ret;
struct timeval tv;
struct timezone tz;
gettimeofday(&tv, &tz);
ret = tv.tv_sec + tv.tv_usec / 1000000.;
return ret;
}
void printdate(char *s_time){
time_t now = time(NULL);
struct tm ltime = *localtime(&now);
strftime(s_time, 32, "%d/%m/%Y, %H:%M:%S", &ltime);
}
static void signals(int sig){
char nowatime[32];
char *str;
int u;
printdate(nowatime);
if(sig == SIGTERM)
str = TERMINATED;
else if(sig == SIGHUP)
str = HUPPED;
else if(sig == SIGQUIT)
str = QUITTED;
else if(sig == SIGINT)
str = INTTED;
LOG(nowatime, str);
shmctl(shmid, IPC_RMID, NULL); // ÕÄÁÌÑÅÍ ÓÅÇÍÅÎÔ *Visor
close(cache_fd);
close(out_fd);
fclose(F_log);
if(t_out) free(t_out); if(t_in) free(t_in);
if(t_mir) free(t_mir); if(pres) free(pres);
if(hum) free(hum);
u = unlink(pidfilename);
if(u == -1) perror("Can't delete PIDfile");
exit(sig);
}
Status current_status(){// ×ÏÚ×ÒÁÝÁÅÍ ÔÅËÕÝÅÅ ÓÏÓÔÏÑÎÉÅ ÔÅÌÅÓËÏÐÁ
/*
* STOP - ÔÅÌÅÓËÏÐ ×ÙËÌÀÞÅÎ
* GUIDING - ×ÅÄÅÎÉÅ
* READY - ×ÓÅ ÏÓÔÁÎÏ×ÌÅÎÏ, ÐÉÔÁÎÉÅ ÅÓÔØ
* OTHER - ÎÁ×ÅÄÅÎÉÅ ÉÌÉ ÐÒÏÞÅÅ ÐÅÒÅÍÅÝÅÎÉÅ ÔÅÌÅÓËÏÐÁ/ËÕÐÏÌÁ
* OPEN - ÉÄÕÔ ÎÁÂÌÀÄÅÎÉÑ
*/
time_t tt = time(NULL);
struct tm t_now = *localtime(&tt);
if(t_now.tm_hour > 7 && t_now.tm_hour < 18) *Visor = 0; // "ÚÁËÒÙ×ÁÅÍ" ÚÁÂÒÁÌÏ ÄÎÅÍ
if(*Visor) return OPEN; // ÚÁÂÒÁÌÏ ÏÔËÒÙÔÏ
if(Tel_Hardware == Hard_Off){ // ×ÁÒÉÁÎÔÙ STOP, OTHER
if(Dome_State == D_Off) return STOP; // ×ÓÅ ×ÙËÌÀÞÅÎÏ
return OTHER; // ËÕÐÏÌ Ä×ÉÖÅÔÓÑ
}
if(Tel_State == Stopping){ // ×ÁÒÉÁÎÔÙ READY, OTHER
if(Dome_State == D_Off) return READY; // ÐÉÔÁÎÉÅ ÅÓÔØ, ×ÓÅ ÏÓÔÁÎÏ×ÌÅÎÏ
return OTHER; // ËÕÐÏÌ Ä×ÉÖÅÔÓÑ
}
// ×ÁÒÉÁÎÔÙ GUIDING, OTHER
if(Tel_Mode == Automatic) return GUIDING; // ÎÁÂÌÀÄÅÎÉÑ
return OTHER; // ÎÁ×ÅÄÅÎÉÅ, ÒÕÞÎÁÑ ËÏÒÒÅËÃÉÑ
}
int get_data(monit_d *data){// ÐÏÌÕÞÁÅÍ ÄÁÎÎÙÅ
/*
ÐÒÅ×ÙÛÅÎÉÅ std 30% ÓÒÅÄÎÅÇÏ ÚÎÁÞÅÎÉÑ - ×ÏÚ×ÒÁÝÁÅÍ 0
ÐÏ ÏÛÉÂËÅ ×ÏÚ×ÒÁÝÁÅÍ -1
×ÓÅ ÎÏÒÍÁÌØÎÏ - ×ÏÚ×ÒÁÝÁÅÍ 1
*/
int nn = 0;
double tt;
data_type *to = t_out, *ti = t_in, *tm = t_mir, max_wnd = 0.,
*p = pres, *h = hum;
// óÏÓÔÏÑÎÉÅÍ ÔÅÌÅÓËÏÐÁ ÓÞÉÔÁÔØ ÐÏÓÌÅÄÎÅÅ
tt = dtime();
while(check_shm_block(&sdat) && (dtime() - tt < TIMEINTERVAL)){
*to++ = val_T1;
*ti++ = val_T2;
*tm++ = val_T3;
if(val_Wnd > max_wnd) max_wnd = val_Wnd;
*p++ = Pressure;
*h++ = val_Hmd;
if(++nn == MAX_DATA_LEN) break;
usleep(100000); // ÏÐÒÁÛÉ×ÁÅÍ 10 ÒÁÚ × ÓÅËÕÎÄÕ
// !!! ÎÁ ÃÉÆÒÅ 10 ÚÁ×ÑÚÁÎÏ ×ÙÞÉÓÌÅÎÉÅ ÏÂßÅÍÁ ÐÁÍÑÔÉ ÄÌÑ calloc, ÅÓÌÉ ÎÁÄÏ ÂÕÄÅÔ
// ÉÚÍÅÎÉÔØ ×ÅÌÉÞÉÎÕ ÐÁÕÚÙ, ÎÅÏÂÈÏÄÉÍÏ É ÓËÏÒÒÅËÔÉÒÏ×ÁÔØ MAX_DATA_LEN × main
}
if(!check_shm_block(&sdat)) return -1; // ÏÛÉÂËÁ ÐÏÌÕÞÅÎÉÑ ÄÁÎÎÙÈ
data->seconds = time(NULL) - TIMEINTERVAL/2;
// ×ÙÞÉÓÌÑÅÍ ÍÅÄÉÁÎÎÙÅ ÐÏËÁÚÁÎÉÑ
data->outdoor_temp = quick_select(t_out, nn);
data->indoor_temp = quick_select(t_in, nn);
data->mirror_temp = quick_select(t_mir, nn);
data->wind_speed = max_wnd;
data->pressure = quick_select(pres, nn);
data->humidity = quick_select(hum, nn);
data->status = current_status();
return 1;
}
void mkcache(uint *remain){
char nowatime[32];
off_t offset = 0; // × ÄÁÎÎÏÍ ÓÌÕÞÁÅ - off64_t, Ô.Å. long long
Cache s_cache;
struct stat filestat;
unsigned long long cntr = 1ULL;
uint cc = 1;
monit_d data;
printdate(nowatime);
LOG(nowatime, "Making cache");
if(read(out_fd, &data, sizeof(data)) < sizeof(data)){
LOG(nowatime, "Corrupted out file");
exit(1);
}
s_cache.offset = 0;
s_cache.time = data.seconds;
write(cache_fd, &s_cache, sizeof(s_cache));
do{
if(cc >= Nth){
s_cache.time = data.seconds;
write(cache_fd, &s_cache, sizeof(s_cache));
cc = 0;
}
cc++; cntr++;
s_cache.offset = tell(out_fd);
}while(read(out_fd, &data, sizeof(data)) == sizeof(data));
*remain = cntr && (Nth - 1);
printdate(nowatime);
LOG(nowatime, "Cache is ready");
}
int main(int argc, char** argv){
char nowatime[32];
struct stat s_stat;
uint cc = Nth + 1;
int tmp;
FILE *pidfile;
monit_d data;
Cache s_cache;
check4running();
if(!(F_log = fopen(LOG_FILE, "a"))){
fprintf(stderr, "Can't open log file, quit\n");
exit(1);
}
setbuf(F_log, NULL);
printdate(nowatime);
LOG(nowatime, STARTED);
if((cache_fd = open(CACHE_FILE, O_RDWR|O_CREAT, 00644)) < 0){
LOG(nowatime, "Can't open cache file, quit");
exit(1);
}
if((out_fd = open(OUT_FILE, O_WRONLY|O_CREAT, 00644)) < 0){
LOG(nowatime, "Can't open out file, quit");
exit(1);
}
if(stat(OUT_FILE, &s_stat) < 0){
LOG(nowatime, "Can't stat out file, quit");
exit(1);
}
if(s_stat.st_size > 0){ // ÅÓÌÉ ÆÁÊÌ Ó ÄÁÎÎÙÍÉ ÅÓÔØ, ÐÒÏ×ÅÒÑÅÍ ÎÁÌÉÞÉÅ ÚÁÐÉÓÅÊ × ËÜÛÅ
if(stat(CACHE_FILE, &s_stat) < 0){
LOG(nowatime, "Can't stat cache file, quit");
exit(1);
}
if(s_stat.st_size == 0)
mkcache(&cc);
lseek(cache_fd, 0, SEEK_END);
lseek(out_fd, 0, SEEK_END);
}
close(0); close(1); close(2);
if(fork() != 0) exit(0);
signal(SIGTERM, signals); // kill (-15)
signal(SIGHUP, SIG_IGN); // ÎÁ ÎÅÇÏ ÍÏÖÎÏ ÞÔÏ-ÎÉÂÕÄØ ÐÏ×ÅÓÉÔØ
signal(SIGINT, signals); // ctrl+C
signal(SIGQUIT, signals); // ctrl+\
signal(SIGTSTP, SIG_IGN); // ÉÇÎÏÒÉÒÕÅÍ ctrl+Z
get_shm_block( &sdat, ClientSide);
shmid = shmget(SHM_KEY, sizeof(int), IPC_CREAT | 0666);
Visor = (int*) shmat(shmid, NULL, 0);
MAX_DATA_LEN = ((int)(TIMEINTERVAL)) * 10 + 11; // 11 = ÐÏÇÒÅÛÎÏÓÔØ ÏËÒÕÇÌÅÎÉÑ + 1 ÐÒÏ ÚÁÐÁÓ
t_out = (data_type*)calloc(MAX_DATA_LEN, sizeof(data_type));
t_in = (data_type*)calloc(MAX_DATA_LEN, sizeof(data_type));
t_mir = (data_type*)calloc(MAX_DATA_LEN, sizeof(data_type));
pres = (data_type*)calloc(MAX_DATA_LEN, sizeof(data_type));
hum = (data_type*)calloc(MAX_DATA_LEN, sizeof(data_type));
while(1){
tmp = get_data(&data);
if(tmp == 0){
sleep(10);
continue;
}
if(tmp == -1){
printdate(nowatime);
LOG(nowatime, "Error getting data");
sleep(300);
continue;
}
s_cache.offset = tell(out_fd);
write(out_fd, &data, sizeof(data));
if(++cc >= Nth){
s_cache.time = data.seconds;
write(cache_fd, &s_cache, sizeof(s_cache));
cc = 0;
printdate(nowatime);
LOG(nowatime, "Add cache data");
}
}
}

145
C/daemon/datetime.css Normal file
View File

@ -0,0 +1,145 @@
/* form with data & time */
.datetime {
width: 150px;}
/* button showdate */
.dpBtn {
width: 22px;}
/* input for time value */
.dpTime {
width: 80px;}
/* the div that holds the date picker calendar */
.dpDiv {
}
/* the table (within the div) that holds the date picker calendar */
.dpTable {
font-family: Tahoma, Arial, Helvetica, sans-serif;
font-size: 12px;
text-align: center;
color: #505050;
background: #ECF5F8;
border: 0px;
width: 180px;
}
/* a table row that holds date numbers (either blank or 1-31) */
.dpTR {
}
/* the top table row that holds the month, year, and forward/backward buttons */
.dpTitleTR {
}
/* the second table row, that holds the names of days of the week (Mo, Tu, We, etc.) */
.dpDayTR {
}
/* the bottom table row, that has the "This Month" and "Close" buttons */
.dpTodayButtonTR {
}
/* a table cell that holds a date number (either blank or 1-31) */
.dpTD {
border: 0px;
width: 25px;
}
/* a table cell that holds a highlighted day (usually either today's date or the current date field value) */
.dpDayHighlightTD {
border: 0px;
background-color: #CCCCCC;
}
/* the date number table cell that the mouse pointer is currently over (you can use contrasting colors to make it apparent which cell is being hovered over) */
.dpTDHover {
border: 0px;
font-style: oblique;
background-color: #aca998;
cursor: pointer;
color: red;
}
/* the table cell that holds the name of the month and the year */
.dpTitleTD {
border: 0px;
}
/* the table cell that holds the time */
.dpFullTitleTD {
border: 0px;
}
/* a table cell that holds one of the forward/backward buttons */
.dpButtonTD {
border: 0px;
}
/* the table cell that holds the "This Month" or "Close" button at the bottom */
.dpTodayButtonTD {
border: 0px;
}
/* a table cell that holds the names of days of the week (Mo, Tu, We, etc.) */
.dpDayTD {
background-color: #CCCCCC;
border: 0px;
color: white;
}
/* additional style information for the text that indicates the month and year */
.dpTitleText {
font-size: 12px;
color: gray;
text-align: center;
font-weight: bold;
}
/* additional style information for the cell that holds a highlighted day (usually either today's date or the current date field value) */
.dpDayHighlight {
color: 4060ff;
font-weight: bold;
}
/* the forward/backward buttons at the top */
.dpButton {
font-family: Verdana, Tahoma, Arial, Helvetica, sans-serif;
font-size: 6pt;
background: #8FCADB;
padding: 2px;
width: 20pt;
border: 0px solid #64A6B9;
color: white;
font-weight: bold;
margin-bottom: 1px;
}
/* the "This Month" and "Close" buttons at the bottom */
.dpTodayButton {
font-family: Arial, Verdana, Tahoma, Helvetica, sans-serif;
font-size: 10px;
color: white;
background: #8FCADB;
font-weight: bold;
border: 0px solid #64A6B9;
padding: 1px 3px 1px 3px;
margin-right: 3px;
}

376
C/daemon/datetime.js Normal file
View File

@ -0,0 +1,376 @@
var datePickerDivID = "datepicker";
var iFrameDivID = "datepickeriframe";
var dayArray = new Array('Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa');
var monthArray = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July',
'August', 'September', 'October', 'November', 'December');
var timefieldValue = null; // óÏÄÅÒÖÉÍÏÇÏ ÐÏÌÑ "×ÒÅÍÑ"
var defaultDateSeparator = "/"; // common values would be "/" or "."
var defaultDateFormat = "mdy" // valid values are "mdy", "dmy", and "ymd"
var dateSeparator = defaultDateSeparator;
var dateFormat = defaultDateFormat;
function displayDatePicker(dateFieldName, displayBelowThisObject, dtFormat, dtSep)
{
var targetDateField = document.getElementsByName(dateFieldName).item(0);
// if we weren't told what node to display the datepicker beneath, just display it
// beneath the date field we're updating
if (!displayBelowThisObject)
displayBelowThisObject = targetDateField;
// if a date separator character was given, update the dateSeparator variable
if (dtSep)
dateSeparator = dtSep;
else
dateSeparator = defaultDateSeparator;
// if a date format was given, update the dateFormat variable
if (dtFormat)
dateFormat = dtFormat;
else
dateFormat = defaultDateFormat;
var x = displayBelowThisObject.offsetLeft;
var y = displayBelowThisObject.offsetTop + displayBelowThisObject.offsetHeight ;
// deal with elements inside tables and such
var parent = displayBelowThisObject;
while (parent.offsetParent) {
parent = parent.offsetParent;
x += parent.offsetLeft;
y += parent.offsetTop ;
}
drawDatePicker(targetDateField, x, y);
}
function drawDatePicker(targetDateField, x, y)
{
var dt = getFieldDate(targetDateField.value );
// the datepicker table will be drawn inside of a <div> with an ID defined by the
// global datePickerDivID variable. If such a div doesn't yet exist on the HTML
// document we're working with, add one.
if (!document.getElementById(datePickerDivID)) {
// don't use innerHTML to update the body, because it can cause global variables
// that are currently pointing to objects on the page to have bad references
//document.body.innerHTML += "<div id='" + datePickerDivID + "' class='dpDiv'></div>";
var newNode = document.createElement("div");
newNode.setAttribute("id", datePickerDivID);
newNode.setAttribute("class", "dpDiv");
newNode.setAttribute("style", "visibility: hidden;");
document.body.appendChild(newNode);
}
// move the datepicker div to the proper x,y coordinate and toggle the visiblity
var pickerDiv = document.getElementById(datePickerDivID);
pickerDiv.style.position = "absolute";
pickerDiv.style.left = x + "px";
pickerDiv.style.top = y + "px";
pickerDiv.style.visibility = (pickerDiv.style.visibility == "visible" ? "hidden" : "visible");
pickerDiv.style.display = (pickerDiv.style.display == "block" ? "none" : "block");
pickerDiv.style.zIndex = 10000;
// draw the datepicker table
refreshDatePicker(targetDateField.name, dt.getFullYear(), dt.getMonth(), dt.getDate());
}
function getTimeString(time){
var hourString = "00" + time.getHours();
var minuteString = "00" + time.getMinutes();
hourString = hourString.substring(hourString.length - 2);
minuteString = minuteString.substring(minuteString.length - 2);
var timeString = ' ' + hourString + ':' + minuteString;
return timeString;
}
// Fill time field with current time
function getTimeInput(){
var str = "time: <input id='dp_Time' class='dpTime' value='";
if(!timefieldValue){
var tm = new Date();
timefieldValue = getTimeString(tm);
}
str += timefieldValue;
str += "' OnChange='timefieldValue=this.value'>"
return str;
}
/**
This is the function that actually draws the datepicker calendar.
*/
function refreshDatePicker(dateFieldName, year, month, day)
{
// if no arguments are passed, use today's date; otherwise, month and year
// are required (if a day is passed, it will be highlighted later)
var thisDay = new Date();
if ((month >= 0) && (year > 0)) {
thisDay = new Date(year, month, 1);
} else {
day = thisDay.getDate();
thisDay.setDate(1);
}
// the calendar will be drawn as a table
// you can customize the table elements with a global CSS style sheet,
// or by hardcoding style and formatting elements below
var crlf = "\r\n";
var TABLE = "<table cols=7 class='dpTable'>" + crlf;
var xTABLE = "</table>" + crlf;
var TR = "<tr class='dpTR'>";
var TR_title = "<tr class='dpTitleTR'>";
var TR_days = "<tr class='dpDayTR'>";
var TR_todaybutton = "<tr class='dpTodayButtonTR'>";
var xTR = "</tr>" + crlf;
var TD = "<td class='dpTD' onMouseOut='this.className=\"dpTD\";' onMouseOver=' this.className=\"dpTDHover\";' "; // leave this tag open, because we'll be adding an onClick event
var TD_title = "<td colspan=5 class='dpTitleTD'>";
var TD_fullstring = "<td colspan=7 class='dpFullTitleTD'>";
var TD_buttons = "<td class='dpButtonTD' align='center'>";
var TD_todaybutton = "<td colspan=3 class='dpTodayButtonTD'>";
var TD_days = "<td class='dpDayTD'>";
var TD_selected = "<td class='dpDayHighlightTD' onMouseOut='this.className=\"dpDayHighlightTD\";' onMouseOver='this.className=\"dpTDHover\";' "; // leave this tag open, because we'll be adding an onClick event
var xTD = "</td>" + crlf;
var DIV_title = "<div class='dpTitleText'>";
var DIV_selected = "<div class='dpDayHighlight'>";
var xDIV = "</div>";
// start generating the code for the calendar table
var html = TABLE;
// here we add time input string
html += TR_title + TD_fullstring + getTimeInput() + xTD + xTR;
// this is the title bar, which displays the month and the buttons to
// go back to a previous month or forward to the next month
html += TR_title;
html += TD_buttons + getButtonCode(dateFieldName, thisDay, -12, "&lt;&lt;","Previous year") + '<br />' + getButtonCode(dateFieldName, thisDay, -1, "&lt;","Previous month") + xTD;
html += TD_title + DIV_title + monthArray[ thisDay.getMonth()] + " " + thisDay.getFullYear() + xDIV + xTD;
html += TD_buttons + getButtonCode(dateFieldName, thisDay, 12, "&gt;&gt;", "Next year") + '<br />' + getButtonCode(dateFieldName, thisDay, 1, "&gt;","next month") + xTD;
html += xTR;
// this is the row that indicates which day of the week we're on
html += TR_days;
for(i = 0; i < dayArray.length; i++)
html += TD_days + dayArray[i] + xTD;
html += xTR;
// now we'll start populating the table with days of the month
html += TR;
// first, the leading blanks
for (i = 0; i < thisDay.getDay(); i++)
html += TD + "&nbsp;" + xTD;
// now, the days of the month
do {
dayNum = thisDay.getDate();
TD_onclick = " onclick=\"updateDateField('" + dateFieldName + "', '" + getDateString(thisDay) + "');\">";
if (dayNum == day)
html += TD_selected + TD_onclick + DIV_selected + dayNum + xDIV + xTD;
else
html += TD + TD_onclick + dayNum + xTD;
// if this is a Saturday, start a new row
if (thisDay.getDay() == 6)
html += xTR + TR;
// increment the day
thisDay.setDate(thisDay.getDate() + 1);
} while (thisDay.getDate() > 1)
// fill in any trailing blanks
if (thisDay.getDay() > 0) {
for (i = 6; i > thisDay.getDay(); i--)
html += TD + "&nbsp;" + xTD;
}
html += xTR;
// add a button to allow the user to easily return to today, or close the calendar
var today = new Date();
html += TR_todaybutton + TD_todaybutton;
html += "<button class='dpTodayButton' onClick='refreshDatePicker(\"" + dateFieldName + "\");'>Today</button> ";
html += xTD + TD_buttons + xTD + TD_todaybutton;
html += "<button class='dpTodayButton' onClick='updateDateField(\"" + dateFieldName + "\");'>Close</button>";
html += xTD + xTR;
// and finally, close the table
html += xTABLE;
document.getElementById(datePickerDivID).innerHTML = html;
// add an "iFrame shim" to allow the datepicker to display above selection lists
adjustiFrame();
}
/**
Convenience function for writing the code for the buttons that bring us back or forward
a month.
*/
function getButtonCode(dateFieldName, dateVal, adjust, label, title)
{
var newMonth = (dateVal.getMonth () + adjust) % 12;
var newYear = dateVal.getFullYear() + parseInt((dateVal.getMonth() + adjust) / 12);
if (newMonth < 0) {
newMonth += 12;
newYear += -1;
}
return "<button title='" + title + "' class='dpButton' onClick='refreshDatePicker(\"" + dateFieldName + "\", " + newYear + ", " + newMonth + ");'>" + label + "</button>";
}
/**
Convert a JavaScript Date object to a string, based on the dateFormat and dateSeparator
variables at the beginning of this script library.
*/
function getDateString(dateVal)
{
var dayString = "00" + dateVal.getDate();
var monthString = "00" + (dateVal.getMonth()+1);
dayString = dayString.substring(dayString.length - 2);
monthString = monthString.substring(monthString.length - 2);
switch (dateFormat) {
case "dmy" :
return dayString + dateSeparator + monthString + dateSeparator + dateVal.getFullYear();
case "ymd" :
return dateVal.getFullYear() + dateSeparator + monthString + dateSeparator + dayString;
case "mdy" :
default :
return monthString + dateSeparator + dayString + dateSeparator + dateVal.getFullYear();
}
}
/**
Convert a string to a JavaScript Date object.
*/
function getFieldDate(dateString)
{
var dateVal;
var dArray;
var d, m, y;
try {
dArray = splitDateString(dateString);
if (dArray) {
switch (dateFormat) {
case "dmy" :
d = parseInt(dArray[0], 10);
m = parseInt(dArray[1], 10) - 1;
y = parseInt(dArray[2], 10);
break;
case "ymd" :
d = parseInt(dArray[2], 10);
m = parseInt(dArray[1], 10) - 1;
y = parseInt(dArray[0], 10);
break;
case "mdy" :
default :
d = parseInt(dArray[1], 10);
m = parseInt(dArray[0], 10) - 1;
y = parseInt(dArray[2], 10);
break;
}
dateVal = new Date(y, m, d);
} else if (dateString) {
dateVal = new Date(dateString);
} else {
dateVal = new Date();
}
} catch(e) {
dateVal = new Date();
}
return dateVal;
}
/**
Try to split a date string into an array of elements, using common date separators.
If the date is split, an array is returned; otherwise, we just return false.
*/
function splitDateString(dateString)
{
var dArray;
if (dateString.indexOf("/") >= 0)
dArray = dateString.split("/");
else if (dateString.indexOf(".") >= 0)
dArray = dateString.split(".");
else if (dateString.indexOf("-") >= 0)
dArray = dateString.split("-");
else if (dateString.indexOf("\\") >= 0)
dArray = dateString.split("\\");
else
dArray = false;
return dArray;
}
function updateDateField(dateFieldName, dateString)
{
var timeString = "";
if(timefieldValue && dateString){
var time = new Date;
time.setTime(Date.parse(dateString +' ' + timefieldValue));
timeString = getTimeString(time);
}
var targetDateField = document.getElementsByName(dateFieldName).item(0);
if (dateString)
targetDateField.value = dateString + timeString;
var pickerDiv = document.getElementById(datePickerDivID);
pickerDiv.style.visibility = "hidden";
pickerDiv.style.display = "none";
adjustiFrame();
targetDateField.focus();
if ((dateString) && (typeof(datePickerClosed) == "function"))
datePickerClosed(targetDateField);
}
function adjustiFrame(pickerDiv, iFrameDiv)
{
// put a try/catch block around the whole thing, just in case
try {
if (!document.getElementById(iFrameDivID)) {
// don't use innerHTML to update the body, because it can cause global variables
// that are currently pointing to objects on the page to have bad references
//document.body.innerHTML += "<iframe id='" + iFrameDivID + "' src='javascript:false;' scrolling='no' frameborder='0'>";
var newNode = document.createElement("iFrame");
newNode.setAttribute("id", iFrameDivID);
newNode.setAttribute("src", "javascript:false;");
newNode.setAttribute("scrolling", "no");
newNode.setAttribute ("frameborder", "0");
document.body.appendChild(newNode);
}
if (!pickerDiv)
pickerDiv = document.getElementById(datePickerDivID);
if (!iFrameDiv)
iFrameDiv = document.getElementById(iFrameDivID);
try {
iFrameDiv.style.position = "absolute";
iFrameDiv.style.width = pickerDiv.offsetWidth;
iFrameDiv.style.height = pickerDiv.offsetHeight ;
iFrameDiv.style.top = pickerDiv.style.top;
iFrameDiv.style.left = pickerDiv.style.left;
iFrameDiv.style.zIndex = pickerDiv.style.zIndex - 1;
iFrameDiv.style.visibility = pickerDiv.style.visibility ;
iFrameDiv.style.display = pickerDiv.style.display;
} catch(e) {
}
} catch (ee) {
}
}

78
C/daemon/defines.h Normal file
View File

@ -0,0 +1,78 @@
#ifndef __DEFINES_H__
#define __DEFINES_H__
#define _FILE_OFFSET_BITS 64
#define _LARGEFILE64_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <unistd.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <fcntl.h>
#include <time.h>
#include <signal.h>
#include <stdint.h>
#ifndef __CLIENT_C__
#include "bta_shdata.h"
#endif
#define WARN(...) do{fprintf(stderr, __VA_ARGS__);}while(0)
#define TIMEINTERVAL 9.99 // ÉÎÔÅÒ×ÁÌ ÕÓÒÅÄÎÅÎÉÑ ÄÁÎÎÙÈ (× ÓÅËÕÎÄÁÈ)
#define LOG_FILE "/home/eddy/_data/.temp_daemon" // ÆÁÊÌ Ó ÌÏÇÁÍÉ
#define CACHE_FILE "/home/eddy/_data/.cache" // ÉÎÄÅËÓÎÙÊ ÆÁÊÌ
#define OUT_FILE "/home/eddy/_data/.out" // ÓÁÍÁ ÉÎÆÏÒÍÁÃÉÑ
#define PID_FILE "/home/eddy/_data/.pid" // PID
#define A_PATH "/home/eddy/_data"
#define PROC_BASE "/proc"
#define SHM_KEY 1234567890
#define CACHE_EVERY_PWR 10 // ËÜÛÉÒÕÅÍ ËÁÖÄÕÀ 2^CACHE_EVERY_PWR ÚÁÐÉÓØ
#define tell(fd) lseek(fd, 0, SEEK_CUR)
enum telescope_status{
STOP, // 0 - ÔÅÌÅÓËÏÐ ×ÙËÌÀÞÅÎ
GUIDING, // 1 - ×ÅÄÅÎÉÅ
READY, // 2 - ×ÓÅ ÏÓÔÁÎÏ×ÌÅÎÏ, ÐÉÔÁÎÉÅ ÅÓÔØ
OTHER, // 3 - ÎÁ×ÅÄÅÎÉÅ ÉÌÉ ÐÒÏÞÅÅ ÐÅÒÅÍÅÝÅÎÉÅ ÔÅÌÅÓËÏÐÁ/ËÕÐÏÌÁ
OPEN // 4 - ÚÁÂÒÁÌÏ ÏÔËÒÙÔÏ, ÉÄÕÔ ÎÁÂÌÀÄÅÎÉÑ
// 5 - úáòåúåò÷éòï÷áîï ÄÌÑ ÓÕÍÍÁÒÎÏÇÏ ×ÒÅÍÅÎÉ
};
typedef enum telescope_status Status;
typedef float data_type;
#pragma pack(4)
struct monitoring_data{
uint32_t seconds; // ×ÒÅÍÑ × ÓÅËÕÎÄÁÈ
data_type outdoor_temp; // ÍÅÄÉÁÎÁ ÔÅÍÐÅÒÁÔÕÒÙ ÚÁ TIMEINTERVAL ÓÎÁÒÕÖÉ
data_type indoor_temp; // -//- ÔÅÍÐÅÒÁÔÕÒÁ ×ÎÕÔÒÉ
data_type mirror_temp; // -//- ÔÅÍÐÅÒÁÔÕÒÁ ÚÅÒËÁÌÁ
data_type wind_speed; // ÍÁËÓÉÍÁÌØÎÁÑ ÚÁ TIMEINTERVAL ÓËÏÒÏÓÔØ ×ÅÔÒÁ
data_type pressure; // ÍÅÄÉÁÎÎÏÅ ÚÎÁÞÅÎÉÅ ÄÁ×ÌÅÎÉÑ (ÍÍ.ÒÔ.ÓÔ)
data_type humidity; // -//- ×ÌÁÖÎÏÓÔÉ
/* data_type sigma_ot; // ÓÔÁÎÄÁÒÔÎÏÅ ÏÔËÌÏÎÅÎÉÅ ×ÎÅÛÎÅÊ ÔÅÍÐÅÒÁÔÕÒÙ
data_type sigma_it; // -//- ×ÎÕÔÒÅÎÎÅÊ ÔÅÍÐÅÒÁÔÕÒÙ
data_type sigma_mt; // -//- ÔÅÍÐÅÒÁÔÕÒÙ ÚÅÒËÁÌÁ
data_type sigma_w; // -//- ÓËÏÒÏÓÔÉ ×ÅÔÒÁ
data_type sigma_p;
data_type sigma_h;
data_type avr_ot; // ÓÒÅÄÎÅÅ ÚÁ TIMEINTERVAL ÚÎÁÞÅÎÉÅ ×ÎÅÛÎÅÊ ÔÅÍÐÅÒÁÔÕÒÙ
data_type avr_it; // ...
data_type avr_mt;
data_type avr_w;
data_type avr_p;
data_type avr_h;*/
Status status; // ÓÏÓÔÏÑÎÉÅ ÔÅÌÅÓËÏÐÁ
};
typedef struct monitoring_data monit_d;
#pragma pack(4)
struct _cache{ // ÓÔÒÕËÔÕÒÁ ÄÌÑ ÈÒÁÎÅÎÉÑ ÄÁÎÎÙÈ × ËÜÛÅ
uint32_t time; // ×ÒÅÍÑ × ÓÅËÕÎÄÁÈ Ó 1.01.1970-0:0
uint64_t offset; // ÓÍÅÝÅÎÉÅ × ÌÏÇ-ÆÁÊÌÅ
};
typedef struct _cache Cache;
int *Visor = NULL; // ÓÏÓÔÏÑÎÉÅ ÚÁÂÒÁÌÁ
#endif

55
C/daemon/lang.h Normal file
View File

@ -0,0 +1,55 @@
#define _LANG(_var, _ru, _en) char _var##ru[] = _ru;\
char _var##en[] = _en;\
char *_var[2] = {_var##ru, _var##en};
#define _L(x) (x[Lang])
_LANG(_s_Save_file_, "óÏÈÒÁÎÉÔØ ÆÁÊÌ", "Save file");
_LANG(_s_no_QS_, "ïÔÓÕÔÓÔ×ÕÅÔ ÓÔÒÏËÁ ÚÁÐÒÏÓÁ", "No query string");
_LANG(_s_no_tstart_, "ðÏÖÁÌÕÊÓÔÁ, ÚÁÐÏÌÎÉÔÅ ÆÏÒÍÕ\"ÎÁÞÁÌØÎÏÅ ×ÒÅÍÑ\"", "Please, fill the form \"starting time\"");
_LANG(_s_Date_, "äÁÔÁ É ×ÒÅÍÑ", "Date and time");
_LANG(_s_Otemp_, "÷ÎÅÛÎÑÑ ÔÅÍÐÅÒÁÔÕÒÁ", "Outdoor temperature");
_LANG(_s_Itemp_, "÷ÎÕÔÒÅÎÎÑÑ ÔÅÍÐÅÒÁÔÕÒÁ", "Indoor temperature");
_LANG(_s_Mtemp_, "ôÅÍÐÅÒÁÔÕÒÁ ÚÅÒËÁÌÁ", "Mirror temperature");
_LANG(_s_Ot_, "÷ÎÅÛÎÑÑ", "Outdoor");
_LANG(_s_It_, "÷ÎÕÔÒÅÎÎÑÑ", "Indoor");
_LANG(_s_Mt_, "úÅÒËÁÌÁ", "Mirror");
_LANG(_s_WSpeed_, "óËÏÒÏÓÔØ ×ÅÔÒÁ", "Wind speed");
_LANG(_s_Temp_, "ôÅÍÐÅÒÁÔÕÒÁ", "Temperature");
_LANG(_s_Pressure_, "äÁ×ÌÅÎÉÅ (ÍÍ.ÒÔ.ÓÔ.)", "Pressure (mmHg)");
_LANG(_s_Humidity_, "÷ÌÁÖÎÏÓÔØ (%)", "Humidity (%)");
_LANG(_s_State_, "óÏÓÔÏÑÎÉÅ ÔÅÌÅÓËÏÐÁ", "Telescope state");
_LANG(_s_Monlen_, "óÄÅÌÁÎÏ ÉÚÍÅÒÅÎÉÊ", "Number of measurements");
_LANG(_s_SVGerr_, "îÅ ÍÏÇÕ ÓÏÚÄÁÔØ ÇÒÁÆÉË", "Can't create graph");
_LANG(_s_Bad_date_, "îÅÐÒÁ×ÉÌØÎÙÊ ÆÏÒÍÁÔ ÄÁÔÙ, ÉÌÉ ÄÁÔÁ ÏËÏÎÞÁÎÉÑ ÒÁÎØÛÅ ÄÁÔÙ ÎÁÞÁÌÁ", "Bad date format, or starting date goes after ending date");
_LANG(_s_Cant_open_cache_, "îÅ ÍÏÇÕ ÏÔËÒÙÔØ ÆÁÊÌ ËÜÛÁ", "Can't open cache file");
_LANG(_s_Cant_open_data_, "îÅ ÍÏÇÕ ÏÔËÒÙÔØ ÆÁÊÌ Ó ÄÁÎÎÙÍÉ", "Can't open data file");
_LANG(_s_Cant_write_, "ïÛÉÂËÁ ÚÁÐÉÓÉ ÄÁÎÎÙÈ", "Can't write data");
_LANG(_s_noData_, "úÁ ÕËÁÚÁÎÎÙÊ ÐÅÒÉÏÄ ÎÅÔ ÄÁÎÎÙÈ", "No data for this period");
_LANG(_s_Vopen_, "úÁÂÒÁÌÏ ÏÔËÒÙÔÏ", "Visor is open");
_LANG(_s_Vclose_, "úÁÂÒÁÌÏ ÚÁËÒÙÔÏ", "Visor is close");
_LANG(_s_CurVstat_, "ôÅËÕÝÅÅ ÓÏÓÔÏÑÎÉÅ", "Current status");
_LANG(_s_ChVstat_, "óÍÅÎÉÔØ ÓÏÓÔÏÑÎÉÅ ÎÁ", "Change status to");
_LANG(_s_noVisor_, "îÅ ÍÏÇÕ ÏÐÒÅÄÅÌÉÔØ ÓÏÓÔÏÑÎÉÅ ÚÁÂÒÁÌÁ", "Can't define visor state");
_LANG(_s_No_Data_, "îÅÄÏÓÔÁÔÏÞÎÏ ÄÁÎÎÙÈ", "Not enough data");
_LANG(_s_Gtr_, "ÂÏÌØÛÅ", "greater");
_LANG(_s_Less_, "ÍÅÎØÛÅ", "less");
_LANG(_s_G_mustbe_less_L_, "þÉÓÌÏ × ÐÏÌÅ \"ÂÏÌØÛÅ\" ÄÏÌÖÎÏ ÂÙÔØ ÍÅÎØÛÅ ÞÉÓÌÁ × ÐÏÌÅ \"ÍÅÎØÛÅ\"",
"The value in field \"greater\" must be less than value in field \"less\"");
_LANG(_s_L_mustbe_less_G_, "þÉÓÌÏ × ÐÏÌÅ \"ÍÅÎØÛÅ\" ÄÏÌÖÎÏ ÂÙÔØ ÍÅÎØÛÅ ÞÉÓÌÁ × ÐÏÌÅ \"ÂÏÌØÛÅ\"",
"The value in field \"less\" must be less than value in field \"greater\"");
_LANG(_s_Max_data_, "äÁÔÙ Ó ÍÁËÓÉÍÁÌØÎÙÍ ÚÎÁÞÅÎÉÅÍ ÐÁÒÁÍÅÔÒÏ×", "Dates with maximum of paremeters");
_LANG(_s_Min_data_, "äÁÔÙ Ó ÍÉÎÉÍÁÌØÎÙÍ ÚÎÁÞÅÎÉÅÍ ÐÁÒÁÍÅÔÒÏ×", "Dates with minimum of paremeters");
_LANG(_s_Diapazon_, "äÁÎÎÙÅ ÉÚ ×ÙÂÒÁÎÎÏÇÏ ÄÉÁÐÁÚÏÎÁ:", "Data from selected range:");
_LANG(_s_Modes_, "òÅÖÉÍÙ ÒÁÂÏÔÙ", "Work modes");
_LANG(_s_And_, "É", "and");
_LANG(_s_Or_, "ÉÌÉ", "or");
_LANG(_s_Mode_Times_, "óÕÍÍÁÒÎÏÅ ×ÒÅÍÑ ÒÁÂÏÔÙ × ÒÅÖÉÍÁÈ", "Total work time in modes");
_LANG(_s_seconds_, "ÓÅËÕÎÄ", "seconds");
_LANG(_s_days_, "ÓÕÔÏË", "days");
_LANG(_s_Stopped_, "ðÏÌÎÙÊ ÏÓÔÁÎÏ×", "Full stop");
_LANG(_s_Guiding_, "óÏÐÒÏ×ÏÖÄÅÎÉÅ ÏÂßÅËÔÁ", "Object guiding");
_LANG(_s_Ready_, "çÏÔÏ×", "Ready");
_LANG(_s_Other_, "ðÒÏÞÅÅ", "Other");
_LANG(_s_Total_, "éÔÏÇÏ", "Total");
//_LANG(, "", "");

49
C/daemon/quick_median.c Normal file
View File

@ -0,0 +1,49 @@
/*
* This Quickselect routine is based on the algorithm described in
* "Numerical recipes in C", Second Edition,
* Cambridge University Press, 1992, Section 8.5, ISBN 0-521-43108-5
* This code by Nicolas Devillard - 1998. Public domain.
*/
#define ELEM_SWAP(a,b) { register data_type t=(a);(a)=(b);(b)=t; }
data_type quick_select(data_type arr[], int n)
{
int low, high ;
int median;
int middle, ll, hh;
low = 0 ; high = n-1 ; median = (low + high) / 2;
for (;;) {
if (high <= low) /* One element only */
return arr[median] ;
if (high == low + 1) { /* Two elements only */
if (arr[low] > arr[high])
ELEM_SWAP(arr[low], arr[high]) ;
return arr[median] ;
}
/* Find median of low, middle and high items; swap into position low */
middle = (low + high) / 2;
if (arr[middle] > arr[high]) ELEM_SWAP(arr[middle], arr[high]) ;
if (arr[low] > arr[high]) ELEM_SWAP(arr[low], arr[high]) ;
if (arr[middle] > arr[low]) ELEM_SWAP(arr[middle], arr[low]) ;
/* Swap low item (now in position middle) into position (low+1) */
ELEM_SWAP(arr[middle], arr[low+1]) ;
/* Nibble from each end towards middle, swapping items when stuck */
ll = low + 1;
hh = high;
for (;;) {
do ll++; while (arr[low] > arr[ll]) ;
do hh--; while (arr[hh] > arr[low]) ;
if (hh < ll)
break;
ELEM_SWAP(arr[ll], arr[hh]) ;
}
/* Swap middle item (in position low) back into correct position */
ELEM_SWAP(arr[low], arr[hh]) ;
/* Re-set active partition */
if (hh <= median)
low = ll;
if (hh >= median)
high = hh - 1;
}
}
#undef ELEM_SWAP

222
C/daemon/temp.html Normal file
View File

@ -0,0 +1,222 @@
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=koi8-r">
<title>íÏÎÉÔÏÒÉÎÇ</title>
<link rel="stylesheet" href="temp2.css" type="text/css">
<link rel="stylesheet" href="datetime.css" type="text/css">
<script src="datetime.js" type="text/javascript" charset="koi8-r" language="javascript"></script>
<script language="JavaScript"><!--
var request;
var timeout_id, monit_tid;
var CGI_PATH = '/cgi-bin/eddy/tempmon';
var ShowOnGraph = 0;
var isRunning = 0, t_start = 0, t_end = 0;
function $(Id){
return document.getElementById(Id);
}
var utf2koi={
1025:179,
1072:193,
1073:194,
1074:215,
1075:199,
1076:196,
1077:197,
1078:214,
1079:218,
1080:201,
1081:202,
1082:203,
1083:204,
1084:205,
1085:206,
1086:207,
1087:208,
1088:210,
1089:211,
1090:212,
1091:213,
1092:198,
1093:200,
1094:195,
1095:222,
1096:219,
1097:221,
1098:223,
1099:217,
1100:216,
1101:220,
1102:192,
1103:209,
1105:163
};
function hexdump(str){
var ret = "";
var l = str.length;
var i, ch, code;
for(i=0; i<l; i++){
ch = str.charCodeAt(i);
if(utf2koi[ch] != null)
code = utf2koi[ch];
else if(utf2koi[ch+32] != null)
code = utf2koi[ch+32]+32;
else code = ch;
ch = code.toString(16);
ret += "%" + ch;
}
return ret;
}
function TimeOut(){
request.abort();
handleError("Time over");
}
function handleError(message) {
ch_status("<h1>ïÛÉÂËÁ xmlhttprequest:<br>" + message + "</h1>")
}
function sendrequest(req_STR){
request = new XMLHttpRequest();
request.open("POST", CGI_PATH, true);
/*
var params = 'name=' + encodeURIComponent(name) + '&surname=' + encodeURIComponent(surname)
xmlhttp.open("POST", '/script.html', true)
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
request.setRequestHeader("Accept-Language", "ru, en");
*/
request.setRequestHeader("Accept-Charset", "koi8-r");
request.overrideMimeType("multipart/form-data; charset=koi8-r");
request.onreadystatechange=function(){
if (request.readyState == 4){
if (request.status == 200){
clearTimeout(timeout_id);
ch_status(request.responseText);
var scripts = $('body').getElementsByTagName("script");
for(var i=0,len=scripts.length; i<len; i++)
eval.call(window, scripts[i].innerHTML);
}
else handleError(request.statusText);
}
}
request.send(req_STR);
timeout_id = setTimeout(TimeOut, 10000);
}
function ch_status(stat){
$('body').innerHTML = stat;
}
function submit_form(){
var rs = "", i;
var F = $('datetime').elements;
for(i = 0; i < F.length; i++)
if(F[i].name && F[i].value)
rs += F[i].name + '=' + F[i].value + ' ';
sendrequest(rs);
}
function refresh_all(){
clearTimeout(monit_tid);
sendrequest("Show=1");
chkvals();
// $('widecen').style.display = 'block';
}
function chkvals(){
var Boxes = document.getElementsByName('show');
ShowOnGraph = 0;
for(i = 0; i < Boxes.length; i++)
if(Boxes[i].checked) ShowOnGraph += parseInt(Boxes[i].value);
if(isRunning)
mkImage();
}
var CHK = 1;
function checkAll(ii){
var Boxes = document.getElementsByName('show');
var i;
if(!ii) ii = Boxes.length;
for(i = 0; i < ii; i++)
Boxes[i].checked = CHK;
CHK = !CHK;
chkvals();
}
function get_seconds(blkid){
var td_value = $(blkid).value;
var seconds = Math.round(Date.parse(td_value) / 1000);
return seconds;
}
function mkImage(){
if(ShowOnGraph == 0) return;
var str = CGI_PATH + '?Graph=' + ShowOnGraph;
if(t_start) str += '&Tstart=' + t_start;
else return;
if(t_end) str += '&Tend=' + t_end;
$('IMG').src = str + '?' + Math.random();
}
function make_request(){
if(!$('t_beg').value){
alert("÷×ÅÄÉÔÅ ÎÁÞÁÌØÎÏÅ ×ÒÅÍÑ");
return;
}
var td = new Date();
var t_now = Math.round(td / 1000);
t_start = get_seconds('t_beg');
if(t_start >= t_now){
alert("îÁÞÁÌØÎÏÅ ×ÒÅÍÑ × ÂÕÄÕÝÅÍ :)");
return;
}
var str = 'Tstart=' + t_start;
if($('t_end').value){
t_end = get_seconds('t_end');
str += ' Tend=' + t_end}
sendrequest(str);
chkvals();
if(ShowOnGraph > 0)
mkImage();
isRunning = 1;
}
//--></script>
</head>
<body>
<noscript><h1 align=center>÷ËÌÀÞÉÔÅ ÐÏÄÄÅÒÖËÕ JavaScript<br>Turn on Javascript</noscript>
<h2>úÁÇÏÌÏ×ÏË</h2>
<div id='body'></div>
<div id='widecen'>
<div id='fsttwo'>
<div id='lefcol'>
<div style='text-align: center;'>
äÁÔÁ É ×ÒÅÍÑ<p>
(MM/DD/YY HH:MM)<p>
</div>
<form id='datetime' OnSubmit='submit_form()' style='text-align: right;'>
Ó: <input name='t_beg' class='datetime' id='t_beg'>
<img OnClick='displayDatePicker("t_beg", false, "mdy", "/");' class='dpBtn' src='cal.jpg'><br>
ÐÏ: <input name='t_end' class='datetime' id='t_end'>
<img OnClick='displayDatePicker("t_end", false, "mdy", "/");' class='dpBtn' src='cal.jpg'>
</form>
<input type='button' OnClick='make_request();' value="OK">
</div>
<div id='cencol'>
<!--<embed id='IMG' src='scene.svg' type='image/svg-xml'></embed>-->
<img src='' type='image/gif' id='IMG'>
</div>
</div>
<div id='rigcol'>
<b OnClick='checkAll();'>ïÔÏÂÒÁÚÉÔØ (×ÓÅ)</b><p>
<form id='temper'>
<b OnClick='checkAll(3);'>ÔÅÍÐÅÒÁÔÕÒÕ:</b>
<div><input type='checkbox' name='show' value='1' OnChange='chkvals();'>×ÎÅÛÎÀÀ</div>
<div><input type='checkbox' name='show' value='2' OnChange='chkvals();'>×ÎÕÔÒÅÎÎÀÀ</div>
<div><input type='checkbox' name='show' value='4' OnChange='chkvals();'>ÚÅÒËÁÌÁ</div></form><p>
<div><input type='checkbox' name='show' value='8' OnChange='chkvals();'>óËÏÒÏÓÔØ ×ÅÔÒÁ</div>
</div>
</div>
</body>
</html>

71
C/daemon/temp2.css Normal file
View File

@ -0,0 +1,71 @@
body{
padding: 1px; margin: 20px;
background: #CCC;
font-family: "Liberation Serif", serif;
font-style: normal;
font-weight: normal;
text-indent: 20px; text-indent: 0px;}
p {
margin-top: 10px; margin-bottom: 2px;}
.hid{
display: none;}
h1 {
text-align: center;
margin: 20px; padding: 0px;
letter-spacing: 3pt; font-size: 160%;}
h2 {
text-align: center;
margin: 10px; padding: 0px;
letter-spacing: 1pt; font-size: 140%;}
h3 {
text-align: left; font-style: italic;
margin: 5px; padding: 0px; font-size: 120%;}
div {
text-align: justify;}
.C {text-align: center;}
.Cb {text-align: center; padding: 5pt;
border: solid 1px black;}
#lefcol{
float: left; width: 220px; margin-left: 205px; text-indent: 0px;
text-align: right;}
#fsttwo{
float: left; width: 100%; margin-left: -205px; text-indent: 0px;}
#rigcol{
padding-left: 100%; margin-left: -200px; text-indent: 0px;}
#cencol{
margin-left: 430px; min-width: 300px; vertical-align: top;
text-align: center; text-indent: 0px;}
#widecen {
min-width: 800px; width: 100%; margin-top: 20px; min-height: 300px;
vertical-align: middle; text-align: center; text-indent: 0px;}
#IMG {
width: 100%; margin: 0px; height: 75%; position: relative;
vertical-align: top; text-align: center; text-indent: 0px;}
/********************* ôÁÂÌÉÃÙ: *******************/
table {
margin: 0 auto; text-align: center;
border: 5px double; padding: 5px;
border-collapse: collapse;}
th {
text-align: center; border: 3px solid black;
padding: 7px;}
td {
border: 3px inset black;}

71
C/daemon/temp2.html Normal file
View File

@ -0,0 +1,71 @@
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=koi8-r">
<link rel="shortcut icon" href="favicon.ico">
<title>íÏÎÉÔÏÒÉÎÇ</title>
<link rel="stylesheet" href="temp2.css" type="text/css">
<link rel="stylesheet" href="datetime.css" type="text/css">
<script src="datetime.js" type="text/javascript" charset="koi8-r" language="javascript"></script>
<script src="temp2.js" type="text/javascript" charset="koi8-r" language="javascript"></script>
</head>
<body OnLoad='init();'>
<noscript><h1 align=center>÷ËÌÀÞÉÔÅ ÐÏÄÄÅÒÖËÕ JavaScript<br>Turn on Javascript</noscript>
<h2 id='header'></h2>
<div id='body'></div>
<div id='widecen'>
<div id='fsttwo'>
<div id='lefcol'>
<div class='C'>
äÁÔÁ É ×ÒÅÍÑ<p>
(MM/DD/YYYY HH:MM)<p>
</div>
Ó: <input name='t_beg' class='datetime' id='t_beg'>
<img OnClick='displayDatePicker("t_beg", false, "mdy", "/");' class='dpBtn' src='cal.jpg'><br>
ÐÏ: <input name='t_end' class='datetime' id='t_end'>
<img OnClick='displayDatePicker("t_end", false, "mdy", "/");' class='dpBtn' src='cal.jpg'><br>
<span id='avertime' class='hid'>
ÉÎÔÅÒ×ÁÌ ÕÓÒÅÄÎÅÎÉÑ:<br>
<input id='averinterval' size=8 value='1'>&nbsp;
<select id='averval'>
<option value='60'>ÍÉÎÕÔ
<option value='3600'>ÞÁÓÏ×
<option value='86400'>ÓÕÔÏË
</select>
</span>
<input type='button' OnClick='make_request();' value="OK"><p>
<div class='C' OnClick='checkAll(5,"mask");'>
<b>ðÏËÁÚÁÔØ ÄÁÎÎÙÅ:</b>
</div><div>
<input type='checkbox' name='mask' value='1' OnChange='chkvals();'>ÐÏÌÎÙÊ ÏÓÔÁÎÏ×<br>
<input type='checkbox' name='mask' value='2' OnChange='chkvals();'>ÒÅÖÉÍ ÓÏÐÒÏ×ÏÖÄÅÎÉÑ<br>
<input type='checkbox' name='mask' value='4' OnChange='chkvals();'>ÇÏÔÏ×<br>
<input type='checkbox' name='mask' value='8' OnChange='chkvals();'>ÐÒÏÞÅÅ<br>
<input type='checkbox' name='mask' value='16' OnChange='chkvals();'>ÚÁÂÒÁÌÏ ÏÔËÒÙÔÏ<br>
</div><p style="margin-top: 20px;">
<div class='C'><input type='button' id='Statbtn' OnClick='statistics();' value="ðÏËÁÚÁÔØ ÓÔÁÔÉÓÔÉËÕ"></div>
<p style="margin-top: 40px;">
<div class='Cb' id='visorbtn'></div>
</div>
<div id='cencol' class='C'>
</div>
</div><!--frsttwo-->
<div id='rigcol'>
<b OnClick='checkAll();'>ïÔÏÂÒÁÚÉÔØ (×ÓÅ)</b><p>
<b OnClick='checkAll(3);'>ÔÅÍÐÅÒÁÔÕÒÕ:</b><br>
<input type='checkbox' name='show' value='1' OnChange='chkvals();'>×ÎÅÛÎÀÀ<br>
<input type='checkbox' name='show' value='2' OnChange='chkvals();'>×ÎÕÔÒÅÎÎÀÀ<br>
<input type='checkbox' name='show' value='4' OnChange='chkvals();'>ÚÅÒËÁÌÁ<p>
<input type='checkbox' name='show' value='8' OnChange='chkvals();'>óËÏÒÏÓÔØ ×ÅÔÒÁ<br>
<input type='checkbox' name='show' value='16' OnChange='chkvals();'>äÁ×ÌÅÎÉÅ<br>
<input type='checkbox' name='show' value='32' OnChange='chkvals();'>÷ÌÁÖÎÏÓÔØ<br>
<p style="margin-top: 25px;">
<div id='imcontrols'>
æÏÒÍÁÔ ÉÚÏÂÒÁÖÅÎÉÑ:<br>
<input type='radio' name='type' value='0' checked OnChange='chkvals();'>SVG<br>
<input type='radio' name='type' value='1' OnChange='chkvals();'>JPEG<br>
<input type='radio' name='type' value='2' OnChange='chkvals();'>GIF
</div>
</div>
</div><!--widecen-->
</body>
</html>

285
C/daemon/temp2.js Normal file
View File

@ -0,0 +1,285 @@
var request;
var timeout_id, monit_tid;
var CGI_PATH = '/cgi-bin/eddy/tempmon';
var ShowOnGraph = 0, ImType = '1';
var isRunning = 0, t_start = 0, t_end = 0, Stat = 0;
function $(Id){
return document.getElementById(Id);
}
var utf2koi={
1025:179,
1072:193,
1073:194,
1074:215,
1075:199,
1076:196,
1077:197,
1078:214,
1079:218,
1080:201,
1081:202,
1082:203,
1083:204,
1084:205,
1085:206,
1086:207,
1087:208,
1088:210,
1089:211,
1090:212,
1091:213,
1092:198,
1093:200,
1094:195,
1095:222,
1096:219,
1097:221,
1098:223,
1099:217,
1100:216,
1101:220,
1102:192,
1103:209,
1105:163
};
function hexdump(str){
var ret = "";
var l = str.length;
var i, ch, code;
for(i=0; i<l; i++){
ch = str.charCodeAt(i);
if(utf2koi[ch] != null)
code = utf2koi[ch];
else if(utf2koi[ch+32] != null)
code = utf2koi[ch+32]+32;
else code = ch;
ch = code.toString(16);
ret += "%" + ch;
}
return ret;
}
function TimeOut(){
request.abort();
handleError("Time over");
}
function handleError(msg) {
$('body').innerHTML = "<h1>ïÛÉÂËÁ xmlhttprequest:<br>" + msg + "</h1>";
}
function ch_status(){
$('body').innerHTML = request.responseText;
var scripts = $('body').getElementsByTagName("script");
for(var i=0,len=scripts.length; i<len; i++)
eval.call(window, scripts[i].innerHTML);
}
function sendrequest(req_STR, fn_OK){
request = new XMLHttpRequest();
request.open("POST", CGI_PATH, true);
request.setRequestHeader("Accept-Charset", "koi8-r");
request.overrideMimeType("multipart/form-data; charset=koi8-r");
request.onreadystatechange=function(){
if (request.readyState == 4){
if (request.status == 200){
clearTimeout(timeout_id);
fn_OK();
}
else handleError(request.statusText);
}
}
request.send(req_STR);
timeout_id = setTimeout(TimeOut, 10000);
}
function chkvals(){
var i;
var Boxes = document.getElementsByName('show');
ShowOnGraph = 0;
for(i = 0; i < Boxes.length; i++)
if(Boxes[i].checked) ShowOnGraph += parseInt(Boxes[i].value);
var Type = document.getElementsByName('type');
for(i = 0; i < Type.length; i++)
if(Type[i].checked){
ImType = Type[i].value;
break;
}
var mask = 0;
Boxes = document.getElementsByName('mask');
for(i = 0; i < Boxes.length; i++)
if(Boxes[i].checked) mask += parseInt(Boxes[i].value);
if(isRunning && !Stat)
mkImage(mask);
return mask;
}
function checkAll(ii, name){
if(!name) name = 'show';
var Boxes = document.getElementsByName(name);
var i;
if(!ii) ii = Boxes.length;
for(i = 0; i < ii; i++)
Boxes[i].checked = !Boxes[i].checked;
chkvals();
}
function get_seconds(blkid){
var td_value = $(blkid).value;
var seconds = Math.round(Date.parse(td_value) / 1000);
return seconds;
}
function clear_cencol(){
var cencol = $('cencol');
if(!cencol.childNodes) return;
while(cencol.childNodes.length > 0)
cencol.removeChild(cencol.lastChild);
}
function mkImage(mask){
if(ShowOnGraph == 0) return;
clear_cencol();
if(!mask) return;
if(ImType == '0')
var image_ = document.createElement('embed');
else
var image_ = document.createElement('img');
image_.id = 'IMG';
$('cencol').appendChild(image_);
var str = CGI_PATH + '?Graph=' + ShowOnGraph + '&' + 'Gtype=' + ImType;
if(t_start) str += '&Tstart=' + t_start;
else return;
if(t_end) str += '&Tend=' + t_end;
str += '&Stat=' + mask;
$('IMG').src = str + '?' + Math.random();
}
function make_request(stat_type){
if(!$('t_beg').value){
alert("÷×ÅÄÉÔÅ ÎÁÞÁÌØÎÏÅ ×ÒÅÍÑ");
return;
}
var averval = "";
if(Stat){
var value = parseInt($('averinterval').value);
if(!value || value < 1){
alert("÷×ÅÄÉÔÅ ÐÒÁ×ÉÌØÎÙÊ ÉÎÔÅÒ×ÁÌ ÕÓÒÅÄÎÅÎÉÑ");
return;
}
var mul = parseInt($('averval').value);
value *= mul;
averval = ' Aver=' + value + ' ';
}
var str1 = averval;
if(typeof(stat_type) != "undefined"){
averval += ' Select='+stat_type+' ';
if(stat_type == 3){
var morethan = parseFloat($('morethan').value);
var lessthan = parseFloat($('lessthan').value);
var and_or = parseInt($('and_or').value);
if(!morethan && !lessthan){
alert("îÅ ÚÁÐÏÌÎÅÎÙ ÐÏÌÑ");
return;
}
if(and_or){
if(!morethan || !lessthan){
alert("úÁÐÏÌÎÉÔÅ ÏÂÁ ÐÏÌÑ (\"ÂÏÌØÛÅ\" É \"ÍÅÎØÛÅ\")");
return;
}
if(morethan >= lessthan){
alert("÷ÅÌÉÞÉÎÁ × ÐÏÌÅ \"ÂÏÌØÛÅ\" ÄÏÌÖÎÁ ÂÙÔØ ÍÅÎØÛÅ ×ÅÌÉÞÉÎÙ × ÐÏÌÅ \"ÍÅÎØÛÅ\"\n"+
"ìÉÂÏ ÉÚÍÅÎÉÔÅ ÌÏÇÉËÕ ÎÁ \"éìé\"");
return;
}
}
else{
if(morethan <= lessthan){
alert("÷ÅÌÉÞÉÎÁ × ÐÏÌÅ \"ÂÏÌØÛÅ\" ÄÏÌÖÎÁ ÂÙÔØ ÂÏÌØÛÅ ×ÅÌÉÞÉÎÙ × ÐÏÌÅ \"ÍÅÎØÛÅ\"\n"+
"ìÉÂÏ ÉÚÍÅÎÉÔÅ ÌÏÇÉËÕ ÎÁ \"é\"");
return;
}
}
if(morethan) averval += ' Greater='+morethan+' ';
if(lessthan) averval += ' Less='+lessthan+' ';
averval += ' AndOr='+and_or+' ';
}
averval += ' Graph=' + ShowOnGraph + ' ';
}
var td = new Date();
var fd = new Date();
var t_now = Math.round(td / 1000);
t_start = get_seconds('t_beg');
if(t_start >= t_now){
alert("îÁÞÁÌØÎÏÅ ×ÒÅÍÑ × ÂÕÄÕÝÅÍ :)");
return;
}
var str = 'Tstart=' + t_start;
if($('t_end').value){
t_end = get_seconds('t_end');
str += ' Tend=' + t_end;
td.setTime(t_end * 1000);}
else t_end = 0;
isRunning = 1;
var mask = chkvals();
str += ' Stat=' + mask;
str1 += str;
str += averval;
function getstat(){$('Stat').innerHTML = request.responseText;
if(mask) sendrequest(str1, ch_status);}
function ok(){visor(); if(typeof(stat_type) != "undefined") sendrequest(str, getstat);
else if(mask) sendrequest(str1, ch_status);}
sendrequest("Visor=-1", ok);
fd.setTime(t_start * 1000);
$('header').innerHTML = 'äÁÎÎÙÅ Ó ' + fd.toLocaleFormat("%H:%M %d/%m/%Y") +
' ÐÏ ' + td.toLocaleFormat("%H:%M %d/%m/%Y");
}
function visor(){
$('visorbtn').innerHTML = request.responseText;
}
function init(){
sendrequest("Visor=-1", visor);
}
function Show(id){
$(id).style.display = 'block';
}
function Hide(id){
$(id).style.display = 'none';
}
function statistics(){
if(Stat){
Stat = 0;
clear_cencol();
$('Statbtn').value = 'ðÏËÁÚÁÔØ ÓÔÁÔÉÓÔÉËÕ';
Show('imcontrols');
Hide('avertime');
chkvals();
}
else{
Stat = 1;
clear_cencol();
$('Statbtn').value = "õÂÒÁÔØ ÓÔÁÔÉÓÔÉËÕ";
var stat_div = document.createElement('div');
stat_div.id = 'Stat';
var stat_btns = document.createElement('div');
stat_btns.className = 'C';
stat_btns.innerHTML = "<h3>ïÔÏÂÒÁÚÉÔØ ÉÎÔÅÒ×ÁÌÙ ×ÒÅÍÅÎÉ Ó ÈÁÒÁËÔÅÒÉÓÔÉËÁÍÉ:</h3><p>\n"+
"<input type='button' OnClick='make_request(1);' value='íÁËÓÉÍÕÍ'>&nbsp;&nbsp;&nbsp;\n"+
"<input type='button' OnClick='make_request(2);' value='íÉÎÉÍÕÍ'>&nbsp;&nbsp;&nbsp;\n"+
"<input type='button' OnClick='make_request(0);' value='òÅÖÉÍ ÒÁÂÏÔÙ'><p>"+
"÷ ÄÉÁÐÁÚÏÎÅ: ÂÏÌØÛÅ <input id='morethan' size=8> "+
"<select id='and_or'><option value='1'>é<option value='0'>éìé</select>"+
" ÍÅÎØÛÅ <input id='lessthan' size=8> "+
"<input type='button' OnClick='make_request(3);' value='OK'><p>\n";
$('cencol').appendChild(stat_btns);
$('cencol').appendChild(stat_div);
Hide('imcontrols');
Show('avertime');
}
}

BIN
C/daemon/tempmon Executable file

Binary file not shown.

1113
C/test/bta_shdata.h Normal file

File diff suppressed because it is too large Load Diff

31
C/test/lang.h Normal file
View File

@ -0,0 +1,31 @@
#define _LANG(_var, _ru, _en) char _var##ru[] = _ru;\
char _var##en[] = _en;\
char *_var[2] = {_var##ru, _var##en};
#define _L(x) (x[Lang])
_LANG(_s_Name_, "÷ÁÛÉ æ.é.ï.", "Your name");
_LANG(_s_Stop_n_write_, "ïÓÔÁÎÏ×ÉÔØ ÚÁÐÉÓØ É ÓÏÈÒÁÎÉÔØ ÆÁÊÌ", "Stop writing and save file");
_LANG(_s_Mon_didnt_start_, "ó ×ÁÛÅÇÏ IP ÍÏÎÉÔÏÒÉÎÇ ÎÅ ÚÁÐÕÓËÁÌÓÑ", "Monitoring didn't start from your IP");
_LANG(_s_Err_, "ïÛÉÂËÁ!", "Error!");
_LANG(_s_Cant_shmat_, "îÅ ÍÏÇÕ ÐÏÄËÌÀÞÉÔØ ÏÂÌÁÓÔØ ÒÁÚÄÅÌÑÅÍÏÊ ÐÁÍÑÔÉ", "Can't get shared memory segment");
_LANG(_s_Try_again_, "ðÏÐÒÏÂÕÊÔÅ ÅÝÅ ÒÁÚ ÐÏÚÖÅ", "Try again later");
_LANG(_s_Cant_find_IP_, "îÅ ÍÏÇÕ ÎÁÊÔÉ ×ÁÛ IP-ÁÄÒÅÓ × ÔÁÂÌÉÃÅ", "Can't find your IP in table");
_LANG(_s_Cant_shmget_, "îÅ ÍÏÇÕ ÐÏÌÕÞÉÔØ ÄÏÓÔÕÐ Ë ÒÁÚÄÅÌÑÅÍÏÊ ÐÁÍÑÔÉ", "Can't get a memory segment");
_LANG(_s_Mon_running_, "ó ×ÁÛÅÇÏ IP ÍÏÎÉÔÏÒÉÎÇ ÕÖÅ ÚÁÐÕÝÅÎ", "Monitoring from your IP is running");
_LANG(_s_Startmon_, "îÁÞÉÎÁÀ ÍÏÎÉÔÏÒÉÎÇ", "Starting monitoring");
_LANG(_s_Can_close_, "íÏÖÅÔÅ ÚÁËÒÙÔØ ÜÔÏ ÏËÎÏ", "You can close this window");
_LANG(_s_No_IP_, "îÅ ÍÏÇÕ ÏÐÒÅÄÅÌÉÔØ ×ÁÛ IP-ÁÄÒÅÓ", "Can't determine your IP");
_LANG(_s_Solvethis_, "ðÏÖÁÌÕÊÓÔÁ, ÒÅÛÉÔÅ ÜÔÕ ÐÒÏÂÌÅÍÕ É ÐÏÐÒÏÂÕÊÔÅ ÓÎÏ×Á", "Please, solve this problem and try again");
_LANG(_s_Fillname_, "ðÏÖÁÌÕÊÓÔÁ, ÚÁÐÏÌÎÉÔÅ ÆÏÒÍÕ\"éÍÑ\"", "Please, fill the form \"Name\"");
_LANG(_s_Refresh_, "ïÂÎÏ×ÉÔØ", "Refresh");
_LANG(_s_Refreshing_, "óÒÅÄÎÉÅ ÄÁÎÎÙÅ ÂÕÄÕÔ ÏÂÎÏ×ÌÑÔØÓÑ ËÁÖÄÙÅ 60 ÓÅËÕÎÄ", "Average data will refresh every 60 seconds");
_LANG(_s_Otemp_, "÷ÎÅÛÎÑÑ", "Outdoor");
_LANG(_s_Itemp_, "÷ÎÕÔÒÅÎÎÑÑ", "Indoor");
_LANG(_s_Mtemp_, "úÅÒËÁÌÁ", "Mirror");
_LANG(_s_WSpeed_, "óËÏÒÏÓÔØ ×ÅÔÒÁ", "Wind speed");
_LANG(_s_Temp_, "ôÅÍÐÅÒÁÔÕÒÁ", "Temperature");
_LANG(_s_Monlen_, "óÄÅÌÁÎÏ ÉÚÍÅÒÅÎÉÊ", "Number of measurements");
_LANG(_s_SVGerr_, "îÅ ÍÏÇÕ ÓÏÚÄÁÔØ ÇÒÁÆÉË", "Can't create graph");
_LANG(_s_FIFOerr_, "ïÛÉÂËÁ FIFO", "FIFO error");
//_LANG(, "", "");

104
C/test/scene.svg Normal file
View File

@ -0,0 +1,104 @@
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20001102//EN" "svg-20001102.dtd">
<svg viewBox="0 0 600 480"
xmlns:xlink="http://www.w3.org/1999/xlink">
<desc>Produced by GNUPLOT 4.0 patchlevel 0 </desc>
<defs>
<circle id='gpDot' r='1'/>
<path id='gpPt0' style='stroke-width:0.286' d='M-1,0 h2 M0,-1 v2'/>
<path id='gpPt1' style='stroke-width:0.286' d='M-1,-1 L1,1 M1,-1 L-1,1'/>
<path id='gpPt2' style='stroke-width:0.286' d='M-1,0 L1,0 M0,-1 L0,1 M-1,-1 L1,1 M-1,1 L1,-1'/>
<rect id='gpPt3' style='stroke-width:0.286' x='-1' y='-1' width='2' height='2'/>
<use xlink:href='#gpPt3' id='gpPt4' style='fill:currentColor; stroke:none'/>
<circle id='gpPt5' style='stroke-width:0.286' cx='0' cy='0' r='1'/>
<use xlink:href='#gpPt5' id='gpPt6' style='fill:currentColor; stroke:none'/>
<path id='gpPt7' style='stroke-width:0.286' d='M0,-1.33 L-1.33,0.67 L1.33,0.67 z'/>
<use xlink:href='#gpPt7' id='gpPt8' style='fill:currentColor; stroke:none'/>
<use xlink:href='#gpPt7' id='gpPt9' transform='rotate(180)'/>
<use xlink:href='#gpPt9' id='gpPt10' style='fill:currentColor; stroke:none'/>
<use xlink:href='#gpPt3' id='gpPt11' transform='rotate(45)'/>
<use xlink:href='#gpPt11' id='gpPt12' style='fill:currentColor; stroke:none'/>
</defs>
<g style="fill:none; color:black; stroke:currentColor; stroke-width:1.00">
<path d='M42,450 L49,450 M578,450 L571,450 '></path>
<g transform="translate(35,454)" style="stroke:none; fill:black; font-family:arial; font-size:11.00; text-anchor:end">
<text><tspan>-10</tspan>
</text>
</g>
<path d='M42,341 L49,341 M578,341 L571,341 '></path>
<g transform="translate(35,345)" style="stroke:none; fill:black; font-family:arial; font-size:11.00; text-anchor:end">
<text><tspan>-5</tspan>
</text>
</g>
<path d='M42,232 L49,232 M578,232 L571,232 '></path>
<g transform="translate(35,236)" style="stroke:none; fill:black; font-family:arial; font-size:11.00; text-anchor:end">
<text><tspan> 0</tspan>
</text>
</g>
<path d='M42,123 L49,123 M578,123 L571,123 '></path>
<g transform="translate(35,127)" style="stroke:none; fill:black; font-family:arial; font-size:11.00; text-anchor:end">
<text><tspan> 5</tspan>
</text>
</g>
<path d='M42,14 L49,14 M578,14 L571,14 '></path>
<g transform="translate(35,18)" style="stroke:none; fill:black; font-family:arial; font-size:11.00; text-anchor:end">
<text><tspan> 10</tspan>
</text>
</g>
<path d='M42,450 L42,443 M42,14 L42,21 '></path>
<g transform="translate(42,469)" style="stroke:none; fill:black; font-family:arial; font-size:11.00; text-anchor:middle">
<text><tspan>-10</tspan>
</text>
</g>
<path d='M176,450 L176,443 M176,14 L176,21 '></path>
<g transform="translate(176,469)" style="stroke:none; fill:black; font-family:arial; font-size:11.00; text-anchor:middle">
<text><tspan>-5</tspan>
</text>
</g>
<path d='M310,450 L310,443 M310,14 L310,21 '></path>
<g transform="translate(310,469)" style="stroke:none; fill:black; font-family:arial; font-size:11.00; text-anchor:middle">
<text><tspan> 0</tspan>
</text>
</g>
<path d='M444,450 L444,443 M444,14 L444,21 '></path>
<g transform="translate(444,469)" style="stroke:none; fill:black; font-family:arial; font-size:11.00; text-anchor:middle">
<text><tspan> 5</tspan>
</text>
</g>
<path d='M578,450 L578,443 M578,14 L578,21 '></path>
<g transform="translate(578,469)" style="stroke:none; fill:black; font-family:arial; font-size:11.00; text-anchor:middle">
<text><tspan> 10</tspan>
</text>
</g>
<path d='M42,450 L578,450 L578,14 L42,14 L42,450 '></path>
</g>
<g style="fill:none; color:red; stroke:currentColor; stroke-width:1.00">
</g>
<g style="fill:none; color:black; stroke:currentColor; stroke-width:1.00">
<g transform="translate(522,32)" style="stroke:none; fill:black; font-family:arial; font-size:11.00; text-anchor:end">
<text><tspan>X</tspan>
<tspan font-size="8.8" y="3.30">1</tspan>
</text>
</g>
</g>
<g style="fill:none; color:red; stroke:currentColor; stroke-width:1.00">
<path d='M529,28 L564,28 M42,450 L47,446 L53,441 L58,437 L64,432 L69,428 L74,424 L80,419
L85,415 L91,410 L96,406 L102,402 L107,397 L112,393 L118,388 L123,384 L129,380 L134,375
L139,371 L145,366 L150,362 L156,358 L161,353 L167,349 L172,344 L177,340 L183,335 L188,331
L194,327 L199,322 L204,318 L210,313 L215,309 L221,305 L226,300 L231,296 L237,291 L242,287
L248,283 L253,278 L259,274 L264,269 L269,265 L275,261 L280,256 L286,252 L291,247 L296,243
L302,239 L307,234 L313,230 L318,225 L324,221 L329,217 L334,212 L340,208 L345,203 L351,199
L356,195 L361,190 L367,186 L372,181 L378,177 L383,173 L389,168 L394,164 L399,159 L405,155
L410,151 L416,146 L421,142 L426,137 L432,133 L437,129 L443,124 L448,120 L453,115 L459,111
L464,106 L470,102 L475,98 L481,93 L486,89 L491,84 L497,80 L502,76 L508,71 L513,67
L518,62 L524,58 L529,54 L535,49 L540,45 L546,40 L551,36 L556,32 L562,27 L567,23
L573,18 L578,14 '></path>
</g>
<g style="fill:none; color:black; stroke:currentColor; stroke-width:1.00">
<path d='M42,450 L578,450 L578,14 L42,14 L42,450 '></path>
</g>
</svg>

After

Width:  |  Height:  |  Size: 5.0 KiB

176
C/test/temp.html Normal file
View File

@ -0,0 +1,176 @@
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=koi8-r">
<title>íÏÎÉÔÏÒÉÎÇ</title>
<link rel="stylesheet" href="temper.css" type="text/css">
<script language="JavaScript"><!--
var request;
var timeout_id, monit_tid;
var CGI_PATH = '/cgi-bin/eddy/test';
var ShowOnGraph = 0;
function $(Id){
return document.getElementById(Id);
}
var utf2koi={
1025:179,
1072:193,
1073:194,
1074:215,
1075:199,
1076:196,
1077:197,
1078:214,
1079:218,
1080:201,
1081:202,
1082:203,
1083:204,
1084:205,
1085:206,
1086:207,
1087:208,
1088:210,
1089:211,
1090:212,
1091:213,
1092:198,
1093:200,
1094:195,
1095:222,
1096:219,
1097:221,
1098:223,
1099:217,
1100:216,
1101:220,
1102:192,
1103:209,
1105:163
};
function hexdump(str){
var ret = "";
var l = str.length;
var i, ch, code;
for(i=0; i<l; i++){
ch = str.charCodeAt(i);
if(utf2koi[ch] != null)
code = utf2koi[ch];
else if(utf2koi[ch+32] != null)
code = utf2koi[ch+32]+32;
else code = ch;
ch = code.toString(16);
ret += "%" + ch;
}
return ret;
}
function TimeOut(){
request.abort();
handleError("Time over");
}
function handleError(message) {
ch_status("<h1>ïÛÉÂËÁ xmlhttprequest:<br>" + message + "</h1>")
}
function sendrequest(req_STR){
request = new XMLHttpRequest();
request.open("POST", CGI_PATH, true);
/*
var params = 'name=' + encodeURIComponent(name) + '&surname=' + encodeURIComponent(surname)
xmlhttp.open("POST", '/script.html', true)
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
request.setRequestHeader("Accept-Language", "ru, en");
*/
request.setRequestHeader("Accept-Charset", "koi8-r");
request.overrideMimeType("multipart/form-data; charset=koi8-r");
request.onreadystatechange=function(){
if (request.readyState == 4){
if (request.status == 200){
clearTimeout(timeout_id);
ch_status(request.responseText);
var scripts = $('body').getElementsByTagName("script");
for(var i=0,len=scripts.length; i<len; i++)
eval.call(window, scripts[i].innerHTML);
}
else handleError(request.statusText);
}
}
request.send(req_STR);
timeout_id = setTimeout(TimeOut, 10000);
}
function ch_status(stat){
$('body').innerHTML = stat;
}
function submit_form(){
var rs = "", i;
var F = $('body').childNodes;
for(i = 0; i < F.length; i++)
if(F[i].name && F[i].value)
rs += F[i].name + '=' + hexdump(F[i].value) + ' ';
sendrequest(rs);
}
function refresh_all(){
clearTimeout(monit_tid);
sendrequest("Show=1");
chkvals();
// $('widecen').style.display = 'block';
}
function start_monitoring(val){
var tt = (val) ? val : 60000;
monit_tid = setTimeout(refresh_all, tt);
}
function chkvals(){
var Boxes = document.getElementsByName('show');
ShowOnGraph = 0;
for(i = 0; i < Boxes.length; i++)
if(Boxes[i].checked) ShowOnGraph += parseInt(Boxes[i].value);
$('IMG').src = CGI_PATH + '?Graph=' + ShowOnGraph + '&' + Math.random();
}
var CHK = 1;
function checkAll(ii){
var Boxes = document.getElementsByName('show');
var i;
if(!ii) ii = Boxes.length;
for(i = 0; i < ii; i++)
Boxes[i].checked = CHK;
CHK = !CHK;
chkvals();
}
//--></script>
</head>
<body onLoad='sendrequest("");'>
<noscript><h1 align=center>÷ËÌÀÞÉÔÅ ÐÏÄÄÅÒÖËÕ JavaScript<br>Turn on Javascript</noscript>
<h2>úÁÇÏÌÏ×ÏË</h2>
<div id='body'></div>
<div id='widecen'>
<div id='fsttwo'>
<div id='lefcol'>
</div>
<div id='cencol'>
<!--<embed id='IMG' width=100% height=75% src='scene.svg' type='image/svg-xml'></embed>-->
<img id='IMG' src='scene.svg' type='image/svg-xml'></embed>
</div>
</div>
<div id='rigcol'>
<b OnClick='checkAll();'>ïÔÏÂÒÁÚÉÔØ (×ÓÅ)</b><p>
<form id='temper'>
<b OnClick='checkAll(3);'>ÔÅÍÐÅÒÁÔÕÒÕ:</b>
<div><input type='checkbox' name='show' value='1' OnChange='chkvals();'>×ÎÅÛÎÀÀ</div>
<div><input type='checkbox' name='show' value='2' OnChange='chkvals();'>×ÎÕÔÒÅÎÎÀÀ</div>
<div><input type='checkbox' name='show' value='4' OnChange='chkvals();'>ÚÅÒËÁÌÁ</div></form><p>
<div><input type='checkbox' name='show' value='8' OnChange='chkvals();'>óËÏÒÏÓÔØ ×ÅÔÒÁ</div>
</div>
</div>
</body>
</html>

62
C/test/temper.css Normal file
View File

@ -0,0 +1,62 @@
body{
padding: 1px; margin: 20px;
background: #CCC;
font-family: "Liberation Serif", serif;
font-style: normal;
font-weight: normal;
text-indent: 20px;}
p {
margin-top: 10px; margin-bottom: 2px;}
.hid{
display: none;}
h1 {
text-align: center;
margin: 20px; padding: 0px;
letter-spacing: 3pt; font-size: 160%;}
h2 {
text-align: center;
margin: 10px; padding: 0px;
letter-spacing: 1pt; font-size: 140%;}
h3 {
text-align: left; font-style: italic;
margin: 5px; padding: 0px; font-size: 120%;}
div {
text-align: justify;}
#lefcol{
float: left; width: 200px; margin-left: 200px;}
#fsttwo{
float: left; width: 100%; margin-left: -200px;}
#rigcol{
padding-left: 100%; margin-left: -200px;}
#cencol{
margin-left: 400px; min-width: 300px; vertical-align: top;
text-align: center; text-indent: 0px;}
#widecen {
min-width: 800px; width: 100%; margin-top: 20px;
vertical-align: middle; text-align: center;}
/********************* ôÁÂÌÉÃÙ: *******************/
table {
text-align: center;
border: 5px double; padding: 5px;
border-collapse: collapse;}
th {
text-align: center; border: 3px solid black;
padding: 7px;}
td {
border: 3px inset black;}

605
C/test/test.c Normal file
View File

@ -0,0 +1,605 @@
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/time.h>
#include <signal.h>
#include <time.h>
#include "lang.h"
#include "bta_shdata.h"
#define MAX_QUERY_SIZE 1024 // ÍÁËÓÉÍÁÌØÎÙÊ ÏÂßÅÍ ÄÁÎÎÙÈ, ÐÅÒÅÄÁ×ÁÅÍÙÈ × ÚÁÐÒÏÓÅ
#define MAX_IPs 20
#define SHMSZ ((MAX_IPs + 1) * sizeof(struct shm_data)) // ÒÅÚÅÒ×ÉÒÕÅÍ ÎÁ ËÁÖÄÙÊ key ÐÁÍÑÔØ ÄÌÑ MAX_IPs IP
#define TIMEINTERVAL 60 // ÉÎÔÅÒ×ÁÌ × ÓÅËÕÎÄÁÈ ÍÅÖÄÕ ÚÁÐÒÏÓÁÍÉ ÄÁÎÎÙÈ
#define MAX_MONITORING_TIME 86400 // ÍÁËÓÉÍÁÌØÎÏÅ ×ÒÅÍÑ, × ÔÅÞÅÎÉÅ ËÏÔÏÒÏÇÏ ÂÕÄÅÔ ×ÙÐÏÌÎÑÔØÓÑ ÍÏÎÉÔÏÒÉÎÇ
static char* SCRIPT_PATH = "/cgi-bin/eddy/test"; // ÐÏÌÎÙÊ ÐÕÔØ Ë ÓËÒÉÐÔÕ
int MAXLEN = MAX_MONITORING_TIME/TIMEINTERVAL;
unsigned char Lang = 1; // ÁÎÇÌÉÊÓËÉÊ
key_t key;
char IP[16];
struct shm_data{ // ÄÁÎÎÙÅ, ÒÁÚÍÅÝÁÅÍÙÅ ÄÌÑ ËÁÖÄÏÇÏ key × ÒÁÚÄÅÌÑÅÍÏÊ ÐÁÍÑÔÉ
char IP[16]; // IP-ÁÄÒÅÓ
pid_t pid; // pid, ÓÏÏÔ×ÅÔÓÔ×ÕÀÝÉÊ ÐÒÏÃÅÓÓÕ ÄÌÑ ÜÔÏÇÏ IP
};
typedef struct shm_data shm_d;
struct monitoring_data{
time_t seconds; // ×ÒÅÍÑ × ÓÅËÕÎÄÁÈ
float outdoor_temp; // ÔÅÍÐÅÒÁÔÕÒÁ ÓÎÁÒÕÖÉ
float indoor_temp; // ÔÅÍÐÅÒÁÔÕÒÁ ×ÎÕÔÒÉ
float mirror_temp; // ÔÅÍÐÅÒÁÔÕÒÁ ÚÅÒËÁÌÁ
float wind_speed; // ÓËÏÒÏÓÔØ ×ÅÔÒÁ
};
typedef struct monitoring_data monit_d;
monit_d *Monitoring;
int Monit_length = 0;
int Kill = 0;
unsigned char Graph = 0;
void detouch_shm();
void print_curvals();
void sendSVG(pid_t pid);
void blankSVG();
double dtime(){
double ret;
struct timeval tv;
struct timezone tz;
gettimeofday(&tv, &tz);
ret = tv.tv_sec + tv.tv_usec / 1000000.;
return ret;
}
static void signals(int sig){
if(sig == SIGTERM || sig == SIGUSR1){
char FIFO[32];
int f, i;
snprintf(FIFO, 32, "/tmp/%d-%d", getpid(), sig);
mkfifo(FIFO, 0666);
if((f = open(FIFO, O_WRONLY)) >0){
unlink(FIFO);
for(i = 0; i< Monit_length; i++)
write(f, &Monitoring[i], sizeof(monit_d));
close(f);
}
}
else if(sig == SIGHUP) print_curvals();
if(sig == SIGTERM){
detouch_shm();
exit(0);
}
signal(sig, signals);
}
void unhexdump(char *inp){
char tmp[512], *o_ptr = inp, *tok;
unsigned char ch;
unsigned int a;
strncpy(tmp, inp, 512);
tok = strtok(tmp, "%");
do{
sscanf(tok, "%x", &a);
ch = a;
*o_ptr++ = ch;
}while(tok = strtok(NULL, "%"));
*o_ptr = 0;
}
void minmax(float *min, float *max, float param){
if(param > *max) *max = param;
else if(param < *min) *min = param;
}
void print_curvals(){
int i, f;
char FIFO[32], *cur_stat;
monit_d *ptr = Monitoring;
float max_otemp, min_otemp,
max_itemp, min_itemp,
max_mtemp, min_mtemp,
max_wind, min_wind;
max_otemp = min_otemp = ptr->outdoor_temp;
max_itemp = min_itemp = ptr->indoor_temp;
max_mtemp = min_mtemp = ptr->mirror_temp;
max_wind = min_wind = ptr->wind_speed;
for(i = 1; i< Monit_length; i++){
ptr++;
minmax(&min_otemp, &max_otemp, ptr->outdoor_temp);
minmax(&min_itemp, &max_itemp, ptr->indoor_temp);
minmax(&min_mtemp, &max_mtemp, ptr->mirror_temp);
minmax(&min_wind, &max_wind, ptr->wind_speed);
}
cur_stat = (char*)calloc(1024, 1);
/* ôÁÂÌÉÞËÁ:
îÁÒÕÖ.Ô ÷ÎÕÔ.Ô. ô.ÚÅÒË. óË.×ÅÔÒÁ
min
max
*/
snprintf(cur_stat, 1024, "<div><table>\n"
"<tr><th rowspan=\"2\"></th><th colspan=\"3\">%s</th><th rowspan=\"2\">%s</th></tr>\n"
"<tr><th>%s</th><th>%s</th><th>%s</th></tr>\n"
"<tr><td>min</td><td>%.1f</td><td>%.1f</td><td>%.1f</td><td>%.1f</td></tr>\n"
"<tr><td>max</td><td>%.1f</td><td>%.1f</td><td>%.1f</td><td>%.1f</td></tr></table>\n"
"%s: %d</div>\n",
_L(_s_Temp_), _L(_s_WSpeed_),
_L(_s_Otemp_), _L(_s_Itemp_), _L(_s_Mtemp_),
min_otemp, min_itemp, min_mtemp, min_wind,
max_otemp, max_itemp, max_mtemp, max_wind,
_L(_s_Monlen_), Monit_length);
snprintf(FIFO, 32, "/tmp/%d", getpid());
mkfifo(FIFO, 0666);
if((f = open(FIFO, O_WRONLY)) >0){
unlink(FIFO);
write(f, cur_stat, 1024);
close(f);
}
free(cur_stat);
}
char* get_qs(char* buf, int l){
char *m, *qs = NULL;
if((m = getenv("REQUEST_METHOD")) && strcasecmp(m, "POST") == 0)
qs = fgets(buf, l, stdin);
else if( (qs = getenv("QUERY_STRING")) )
qs = strncpy(buf, qs, l);
if(qs && strlen(qs) < 1) qs = NULL;
return qs;
}
int get_qs_param(char *qs, char *param, char *meaning, int l){
char *tok, *val, *par, str[l+1];
int stat = 0;
strncpy(str, qs, l);
tok = strtok(str, "& \n");
do{
if((val = strchr(tok, '=')) == NULL) continue;
*val++ = '\0';
par = tok;
if(strcasecmp(par, param)==0){
if(strlen(val) > 0){
stat = 1;
strncpy(meaning, val, l);
}
break;
}
}while((tok = strtok(NULL, "& \n"))!=NULL);
return stat;
}
void getkey(){ // key ×ÙÞÉÓÌÑÅÔÓÑ ËÁË ÐÏÓÌÅÄÎÉÅ ÔÒÉ ÂÁÊÔÁ IP-ÁÄÒÅÓÁ
int cntr=0;
char IPnum[13], tmp[4], ipaddr[16];
char *tok = strtok(IP, ".");
strncpy(ipaddr, IP, 16);
IPnum[0] = 0;
do{
strncpy(tmp, tok, 4);
if(cntr > 0)
sprintf(IPnum, "%s%s", IPnum, tmp);
cntr++;
if(cntr > 4) break;
}while((tok = strtok(NULL, "."))!=NULL);
key = atoi(IPnum);
}
void Refresh(){
printf("<div><button type='submit' OnClick='refresh_all();'>%s</button></div>\n", _L(_s_Refresh_));
printf("<script language=\"JavaScript\">$('widecen').style.display='block';</script>\n");
}
void mk_starting_form(){
printf("%s:<input type='text' name='Name' OnChange='submit_form();' size=50>\n", _L(_s_Name_));
printf("<button type='submit' OnClick='submit_form();'>OK</button>\n");
printf("<script language=\"JavaScript\">$('widecen').style.display='none';</script>\n");
}
void mk_stopping_form(char *timeout){
printf("<a href=\"%s?Kill=1\" OnClick='sleep(5);window.location.reload();'>%s</a>\n", SCRIPT_PATH, _L(_s_Stop_n_write_));
printf("<script language=\"JavaScript\">start_monitoring(%s);</script>\n", timeout);
Refresh();
}
void detouch_shm(){
shm_d *Data, *ptr;
int i = 0, shmid;
if ((shmid = shmget(key, SHMSZ, 0666)) < 0)
return;
if((Data = (shm_d*)shmat(shmid, NULL, 0)) == (shm_d *) -1)
return;
ptr = Data;
do{
if(!*(ptr->IP)){
i = MAX_IPs;
break;
}
if(strcmp(ptr->IP, IP) == 0) break;
ptr++;
}while(i < MAX_IPs);
if(i != MAX_IPs){
i++;
if(i == MAX_IPs) *(ptr->IP) = 0; // ÎÁÛÁ ÚÁÐÉÓØ - ÐÏÓÌÅÄÎÑÑ
else
while(i < MAX_IPs){ // ÐÅÒÅÄ×ÉÇÁÅÍ ÓÌÅÄÕÀÝÉÅ ÚÁÐÉÓÉ
if(!*((ptr+1)->IP)){
*(ptr->IP) = 0;
break;
}
strcpy(ptr->IP, (ptr+1)->IP);
ptr->pid = (ptr+1)->pid;
ptr++; i++;
}
}
}
void printdata(monit_d data){
struct tm ltime = *localtime(&data.seconds);
char s_time[32];
strftime(s_time, 32, "%d/%m/%Y, %H:%M:%S", &ltime);
printf("%s\t%.1f\t%.1f\t%.1f\t%.1f\n",
s_time,
data.outdoor_temp,
data.indoor_temp,
data.mirror_temp,
data.wind_speed);
}
void kill_and_save(pid_t pid){
/*
ðÅÒÅÄÁÅÍ ÐÒÏÃÅÓÓÕ pid ÉÍÑ ÆÁÊÌÁ ÄÌÑ ÓÏÈÒÁÎÅÎÉÑ É ÐÏÓÙÌÁÅÍ ÓÉÇÎÁÌ ÚÁ×ÅÒÛÅÎÉÑ;
ÌÉÂÏ ÕÚÎÁÅÍ Õ pid, ËÕÄÁ ÐÉÛÅÔ, ÐÒÉÈÌÏÐÙ×ÁÅÍ ÅÇÏ É ÓÏÈÒÁÎÑÅÍ ÆÁÊÌ;
*/
char FIFO[32], *cur_stat;
int f, i, rb, sig_;
struct timeval tv;
fd_set rfds;
monit_d data;
if(pid == 0) exit(0);
sig_ = (Kill) ? SIGTERM : SIGHUP;
if(Kill) snprintf(FIFO, 32, "/tmp/%d-%d", pid, SIGTERM);
else snprintf(FIFO, 32, "/tmp/%d", pid);
mkfifo(FIFO, 0666);
if((f = open(FIFO, O_RDONLY|O_NONBLOCK)) < 0) return;
if(kill(pid, sig_) != 0){ // ÐÏÓÙÌÁÅÍ ÓÉÇÎÁÌ Ï ÇÏÔÏ×ÎÏÓÔÉ Ë ÞÔÅÎÉÀ
unlink(FIFO);
detouch_shm();
close(f);
exit(0);
}
FD_ZERO(&rfds);
FD_SET(f, &rfds);
tv.tv_sec = 5; tv.tv_usec = 0; // ÖÄÅÍ ÇÏÔÏ×ÎÏÓÔÉ ÎÅ ÂÏÌÅÅ 5 ÓÅËÕÎÄ
select(f+1, &rfds, NULL, NULL, &tv);
i = 0;
if(Kill) do{
FD_ZERO(&rfds);
FD_SET(f, &rfds);
tv.tv_sec = 1; tv.tv_usec = 0; // 1 ÓÅËÕÎÄÁ ÎÁ ÏÖÉÄÁÎÉÅ
if(select(f+1, &rfds, NULL, NULL, &tv) > 0)
if(FD_ISSET(f, &rfds)){
rb = read(f, &data, sizeof(data));
if(rb > 0){
printdata(data);
i++;
}
else break;
}
else {printf("no data...\n"); break;}
}while(i < MAXLEN);
else {
cur_stat = (char*)calloc(1024, 1);
FD_ZERO(&rfds);
FD_SET(f, &rfds);
tv.tv_sec = 1; tv.tv_usec = 0; // 1 ÓÅËÕÎÄÁ ÎÁ ÏÖÉÄÁÎÉÅ
if(select(f+1, &rfds, NULL, NULL, &tv) > 0)
if(FD_ISSET(f, &rfds)){
rb = read(f, cur_stat, 1024);
if(rb > 0){
printf("%s\n", cur_stat);
}
}
free(cur_stat);
mk_stopping_form("");
}
close(f);
exit(0);
}
void fill_forms(const char* alert_message, const char S_flag){
/*
÷ ÚÁÇÏÌÏ×ÏË ÓÔÒÁÎÉÃÙ ×Ù×ÏÄÉÍ alert_message;
ÐÒÏ×ÅÒÑÅÍ, ÎÅ ÚÁÐÕÝÅÎ ÌÉ ÕÖÅ ÐÒÏÃÅÓÓ Ó IP
ÅÓÌÉ ÚÁÐÕÝÅÎ - ÇÅÎÅÒÉÒÕÅÍ ÆÏÒÍÕ ÏÓÔÁÎÏ×ËÉ ÍÏÎÉÔÏÒÉÎÇÁ É ÓÏÈÒÁÎÅÎÉÑ ÒÅÚÕÌØÔÁÔÏ× × ÆÁÊÌ
ÉÎÁÞÅ - ÇÅÎÅÒÉÒÕÅÍ ÎÁÞÁÌØÎÕÀ ÆÏÒÍÕ
*/
int shmid, i = 0;
shm_d *Data, *ptr;
if(alert_message) printf("<div><h1 align=center>%s</h1></div>\n", alert_message);
if ((shmid = shmget(key, SHMSZ, 0666)) < 0){ // ÄÌÑ ÜÔÏÇÏ ËÌÀÞÁ ÅÝÅ ÎÅ ×ÙÄÅÌÑÌÁÓØ ÐÁÍÑÔØ
if(Graph){
// blankSVG();
exit(0);
}
if(S_flag) // ÈÏÔÉÍ ÕÄÁÌÉÔØ ÐÒÏÃÅÓÓ, ÄÌÑ ËÏÔÏÒÏÇÏ ÎÅÔ ÚÁÐÉÓÅÊ
printf("<div><h1 align=center>%s</h1></div>\n", _L(_s_Mon_didnt_start_));
mk_starting_form(); // ÇÅÎÅÒÉÒÕÅÍ ÎÁÞÁÌØÎÕÀ ÆÏÒÍÕ
return;
}
if((Data = (shm_d*)shmat(shmid, NULL, 0)) == (shm_d *) -1){
if(Graph){
// blankSVG();
exit(0);
}
printf("<div><h1 align=center>%s:<p>%s</h1></div>\n", _L(_s_Err_), _L(_s_Cant_shmat_));
return;
}
// ÔÅÐÅÒØ ÐÒÏ×ÅÒÑÅÍ, ÚÁÐÕÝÅÎ ÌÉ ÐÒÏÃÅÓÓ ÄÌÑ ÄÁÎÎÏÇÏ IP
ptr = Data; i = 0;
do{
if(!*(ptr->IP)){ // ÓÐÉÓÏË ÚÁËÏÎÞÉÌÓÑ
i = MAX_IPs;
break;
}
if(strcmp(ptr->IP, IP) == 0) break;
ptr++;
}while(i < MAX_IPs);
if(i == MAX_IPs){ // ÔÁËÏÊ ËÌÀÞ ÕÖÅ ÅÓÔØ, ÎÏ ÄÌÑ ÄÁÎÎÏÇÏ IP ÐÒÏÃÅÓÓÁ ÎÅ ÓÕÝÅÓÔ×ÕÅÔ
if(Graph){
// blankSVG();
exit(0);
}
if(S_flag) printf("<div><h1 align=center>%s</h1></div>\n", _L(_s_Cant_find_IP_));
mk_starting_form();
return;
}
// äÌÑ ÄÁÎÎÏÇÏ IP ÕÖÅ ÚÁÐÕÝÅÎ ÐÒÏÃÅÓÓ
if(Graph) sendSVG(ptr->pid);
else kill_and_save(ptr->pid);
}
void get_data(){// ÐÏÌÕÞÁÅÍ ÄÁÎÎÙÅ
int nn = 0;
double tt;
double t1=0., t2=0., t3=0., wnd=0.;
monit_d *ptr = &Monitoring[Monit_length];
tt = dtime();
while(check_shm_block(&sdat) && (dtime() - tt < 9.99)){
t1 += val_T1;
t2 += val_T2;
t3 += val_T3;
wnd += val_Wnd;
nn++;
usleep(100000);
}
ptr-> seconds = time(NULL);// - starting_time;
ptr->outdoor_temp = t1 / nn;
ptr->indoor_temp = t2 / nn;
ptr->mirror_temp = t3 / nn;
ptr->wind_speed = wnd / nn;
Monit_length++;
}
void start_monitoring(char *Name){
int shmid, i = 0;
unsigned char not_first = 1;
shm_d *Data, *ptr;
pid_t pid;
printf("<div>%s</div>\n", Name);
if ((shmid = shmget(key, SHMSZ, 0666)) < 0){ // ÐÁÍÑÔØ ÅÝÅ ÎÅ ×ÙÄÅÌÑÌÁÓØ - ×ÙÄÅÌÑÅÍ
not_first = 0;
if ((shmid = shmget(key, SHMSZ, IPC_CREAT | 0666)) < 0){
printf("<div><h1 align=center>%s<br>%s</h1></div>\n", _L(_s_Err_), _L(_s_Cant_shmget_));
return;
}
}
if((Data = (shm_d*)shmat(shmid, NULL, 0)) == (shm_d *) -1){
printf("<div><h1 align=center>%s<p>%s</h1></div>\n", _L(_s_Err_), _L(_s_Cant_shmat_));
return;
}
ptr = Data;
if(not_first){
i = 0;
do{
if(!*(ptr->IP)){ // ÓÐÉÓÏË ÚÁËÏÎÞÉÌÓÑ
i = MAX_IPs;
break;
}
if(strcmp(ptr->IP, IP) == 0) break;
ptr++; i++;
}while(i < MAX_IPs);
if(i != MAX_IPs){
printf("<div><h1 align=center>%s (pid: %d)</h1></div>\n", _L(_s_Mon_running_), ptr->pid);
kill_and_save(i);
return;
}
}
printf("<div><h1 align=center>%s<p>%s</h1>\n", _L(_s_Startmon_), _L(_s_Can_close_));
printf("<h1>%s</h1></div>\n", _L(_s_Refreshing_));
mk_stopping_form("5000");
fclose(stdin);
fclose(stdout);
fclose(stderr);
if((pid = fork()) != 0){exit(0);}
strncpy(ptr->IP, IP, 16);
ptr->pid = getpid();
signal(SIGTERM, signals);
signal(SIGHUP, signals);
signal(SIGUSR1, signals);
get_shm_block( &sdat, ClientSide);
time_t t0 = time(NULL);
time_t tt, t1 = t0;
int size_ = MAX_MONITORING_TIME / TIMEINTERVAL + 1;
Monitoring = calloc(size_, sizeof(monit_d));
do{
get_data();
while( ((tt = time(NULL)) - t1) < TIMEINTERVAL )
usleep(1000);
t1 = tt;
} while((tt - t0) < MAX_MONITORING_TIME);
detouch_shm();
exit(1);
}
void blankSVG(){printf("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n"
"<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.0//EN\"\n"
"\"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd\">\n"
"<?xmlstylesheet url=\"index.xsl\"?>\n"
"<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">\n"
"<g></g></svg>");
}
void sendSVG(pid_t pid){
FILE *plot;
char FIFO[32], *cur_stat, s_time[32];
struct tm ltime;
struct timeval tv;
fd_set rfds;
monit_d *data, *ptr;
unsigned char Flag, Comma = 0;
char *titles[4] = {"T out", "T in", "T mir", "Wind"};
//char *startplot = "plot '-' with lines title ";
char *command= "/usr/bin/gnuplot";
// char *set_term = "set terminal svg\nset xdata time\nset timefmt \"\%d/\%m-\%H:\%M\"\nset format x \"\%H:\%M\"\n";
char *set_term = "set terminal gif size 800,600\nset xdata time\nset timefmt \"\%d/\%m-\%H:\%M\"\nset format x \"\%H:\%M\"\n";
int f, i, j, d_len, rb;
data = calloc(MAXLEN+1, sizeof(monit_d));
ptr = data;
if(pid == 0 || Graph == 0 || Graph > 15){
// blankSVG();
exit(0);
}
snprintf(FIFO, 32, "/tmp/%d-%d", pid, SIGUSR1);
mkfifo(FIFO, 0666);
if((f = open(FIFO, O_RDONLY|O_NONBLOCK)) < 0){
// blankSVG();
exit(0);
}
if(kill(pid, SIGUSR1) != 0){ // ÐÏÓÙÌÁÅÍ ÓÉÇÎÁÌ Ï ÇÏÔÏ×ÎÏÓÔÉ Ë ÞÔÅÎÉÀ
// blankSVG();
close(f);
exit(0);
}
FD_ZERO(&rfds);
FD_SET(f, &rfds);
tv.tv_sec = 5; tv.tv_usec = 0; // ÖÄÅÍ ÇÏÔÏ×ÎÏÓÔÉ ÎÅ ÂÏÌÅÅ 5 ÓÅËÕÎÄ
select(f+1, &rfds, NULL, NULL, &tv);
d_len = 0;
do{
FD_ZERO(&rfds);
FD_SET(f, &rfds);
tv.tv_sec = 1; tv.tv_usec = 0; // 1 ÓÅËÕÎÄÁ ÎÁ ÏÖÉÄÁÎÉÅ
if(select(f+1, &rfds, NULL, NULL, &tv) > 0)
if(FD_ISSET(f, &rfds)){
rb = read(f, ptr, sizeof(monit_d));
if(rb > 0){
d_len++;
ptr++;
}
else break;
}
else break;
}while(d_len < MAXLEN);
close(f);
if(d_len < 2){
// blankSVG();
exit(0);
}
plot = popen(command, "w");
if(plot == NULL){
// blankSVG();
exit(0);
}
fprintf(plot, "%s", set_term);
fprintf(plot, "plot ");
for(j = 0; j < 4; j++){
Flag = Graph & (1 << j);
if(Flag){
if(Comma) fprintf(plot, ",");
Comma = 1;
fprintf(plot, " '-' using 1:2 with lines lt %d title '%s'", j+1, titles[j]);
}
}
fprintf(plot, "\n");
for(j = 0; j < 4; j++){
Flag = Graph & (1 << j);
if(Flag){
for(i = 0; i < d_len; i++){
ltime = *localtime(&data[i].seconds);
strftime(s_time, 32, "%d/%m-%H:%M", &ltime);
fprintf(plot, "%s ", s_time);
switch(Flag){
case 1: fprintf(plot, "%.1f\n", data[i].outdoor_temp); break;
case 2: fprintf(plot, "%.1f\n", data[i].indoor_temp); break;
case 4: fprintf(plot, "%.1f\n", data[i].mirror_temp); break;
case 8: fprintf(plot, "%.1f\n", data[i].wind_speed); break;
}
}
fprintf(plot, "e\n");
}
}
fflush(plot);
pclose(plot);
fflush(stdout);
printf("<?xmlstylesheet url=\"index.xsl\"?>\n");
free(data);
}
int main(){
char *qs, *buf, Name[512], *ptr, tmp[16];
void quit(int status){
free(buf);
exit(status);
}
setbuf(stdout, NULL);
buf = (char*)calloc(MAX_QUERY_SIZE, 1);
qs = get_qs(buf, 1024);
ptr = getenv("HTTP_ACCEPT_LANGUAGE");
if(ptr) if(strncmp(ptr, "ru", 2) == 0) Lang = 0; // ÉÓÐÏÌØÚÕÅÍ ÒÕÓÓËÉÊ
ptr = getenv("REMOTE_ADDR");
if(!ptr){
printf("Content-type: multipart/form-data; charset=koi8-r\n\n");
printf("<div><h1 align=center>%s</h1>\n", _L(_s_No_IP_));
printf("%s</div>\n", _L(_s_Solvethis_));
quit(0);
}
strncpy(IP, ptr, 16);
getkey();
if(!qs){
printf("Content-type: multipart/form-data; charset=koi8-r\n\n");
fill_forms(NULL, 0);
quit(0);
}
if(get_qs_param(qs, "Graph", tmp, 16)){
printf("Content-type: image/gif\n\n");
// printf("Content-type: image/svg+xml\n\n");
Graph = atoi(tmp);
if(Graph == 0) Graph = 16;
fill_forms(NULL, 1);
quit(0);
}
if(get_qs_param(qs, "Kill", tmp, 16)){
printf("Content-type: text/plain; charset=koi8-r\n\n");
Kill = 1;
fill_forms(NULL, 1);
quit(0);
}
printf("Content-type: multipart/form-data; charset=koi8-r\n\n");
if(get_qs_param(qs, "Show", tmp, 16)){
fill_forms(NULL, 1);
quit(0);
}
if(!get_qs_param(qs, "Name", Name, 512)){
fill_forms(_L(_s_Fillname_), 0);
quit(0);
}
unhexdump(Name);
start_monitoring(Name);
quit(0);
}

BIN
cal.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 488 B

5
cgi-bin/bta_print.cgi Executable file
View File

@ -0,0 +1,5 @@
#!/bin/bash
echo -e "Access-Control-Allow-Origin: http://ishtar.sao.ru\n"
echo -e "Access-Control-Allow-Methods: POST\n"
echo -e "Content-type: multipart/form-data\n\n"
/usr/local/bin/bta_print 2>/dev/null

134
contexthelp.js Normal file
View File

@ -0,0 +1,134 @@
var tipobj=null;
function startHelp(evt){
evt.stopPropagation();
evt.preventDefault();
document.body.style.cursor = "help";
document.body.onclick = Help;
document.body.onmouseover = stoponclick;
}
function Help(evt){
evt.stopPropagation();
evt.preventDefault();
if(!helptip(evt)) return;
document.body.onclick = '';
document.body.style.cursor = "default";
document.body.onmouseover = '';
}
var oldclc, oldmout;
function stoponclick(evt){
var obj = evt.target;
if(obj == document.body) return;
oldclc = obj.onclick;
oldmout = obj.onmouseout;
obj.onclick = Help;
obj.onmouseout = releaseonclick;
obj.style.cursor = "help";
}
function releaseonclick(evt){
var obj = evt.target;
obj.onmouseout = oldmout;
obj.onclick = oldclc;
obj.style.cursor = "default";
}
function helptip(evt){
var ss = helpgen(evt), helper;
if(ss.length > 0){
tipobj = document.createElement("DIV");
tipobj.id = 'helptip';
tipobj.setAttribute("name", "helptip");
tipobj.onclick = rmtip;
tipobj.innerHTML = ss;
helper = document.createElement("DIV");
helper.className = 'redtxt';
helper.innerHTML = "Чтобы закрыть это окно, щелкните по нему левой кнопкой мыши или нажмите клавишу ESCAPE";
helper.onclick = function(evt){evt.stopPropagation();
document.body.removeChild(evt.target.parentNode);};
tipobj.appendChild(helper);
document.body.appendChild(tipobj);
positiontip(evt);
}
releaseonclick(evt);
return (ss.length);
}
function helpgen(evt){
var obj = evt.target;
var objid, objname, ss="", nm;
onkey(27);
objid = obj.id; objname = obj.name;
if(objid == "" && objname == null){
objid = obj.parentNode.id;
objname = obj.parentNode.name;
}
if(objid == "" && objname == null) return (ss);
if(objid == "" && objname != null) nm = objname;
else nm = objid;
ss = HelpText[nm];
if(ss == null) ss = HelpText[obj.parentNode.id];
return (ss);
}
function positiontip(e){
var wd = tipobj.offsetWidth, ht = tipobj.offsetHeight;
var curX = e.clientX + 25;
var curY = e.clientY - ht/2;
var btmedge = document.body.clientHeight - curY - 15;
var rightedge = document.body.clientWidth - curX - 15;
if(rightedge < wd) curX -= wd+50;
if(btmedge < ht) curY -= ht-btmedge+15;
if(curY < 15) curY = 15;
tipobj.style.left = curX+"px";
tipobj.style.top = curY+"px";
}
function onkey(code){
if(code != 27) return;
var helps = document.getElementsByName('helptip');
var l = helps.length-1;
for(var i=l; i>-1; i--) document.body.removeChild(helps[i]);
}
function rmtip(evt){
document.body.removeChild(evt.target);
}
const HelpText = {
dtheader: "Ниже расположены поля, в которые необходимо ввести начальное и (опционально) конечное значения интервала времени, по которому будет производиться выбор данных.<p></p>Вы можете воспользоваться простым календарем (щелкнув на иконке справа от формы ввода даты и времени) или же ввести данные вручную.<p></p>При вводе данных вручную обратите внимание на формат даты и времени: дата вводится в формате МЕСЯЦ/ЧИСЛО/ГОД, затем через пробел вводится время в формате ЧАСЫ:МИНУТЫ. ГОД необходимо писать полным (т.е. 2010, а не просто 10).<p></p>Например, время \"7 часов 35 минут 10 марта 2010 года\" необходимо вводить так:<p></p>\"03/10/2010 7:35\".",
t_beg: "Введите в это поле время, начиная с которого вы хотите получить статистические данные.",
t_end: "Ввведите в это поле время окончания интервала.<p></p>Если вы оставите поле пустым, конечным будет считаться текущее время.",
cal: "Нажмите сюда, если вы хотите выбрать время и дату при помощи простого календаря.<p></p>В форму календаря сначала введите нужное время, затем выберите нужный год и месяц и щелкните по нужной дате.",
reqbtn: "После ввода начального и (опционально) конечного значения интересующего Вас интервала времени, нажмите на эту кнопку для построения графиков и получения статистической информации.",
avertime: "Это поле позволяет выбрать интервал времени, по которому будет производиться медианное усреднение данных, получаемых Вами при нажатии на ссылку \"Сохранить файл\".",
averinterval: "Введите в это поле промежуток времени, по которому будет производиться медианное усреднение.",
averval: "Выберите единицу измерения времени: минуты, часы или сутки.",
modes: "Выберите интересующие режимы работы телескопа.<p></p>При щелчке по этой надписи выбор всех режимов инвертируется.",
Mstp: "Питание телескопа и купола отключено.",
Mgd: "Режим сопровождения объекта (скорее всего, в это время проводились наблюдения).",
Mrd: "Основной режим простоя: телескоп готов к работе.",
Moth: "Режим, не попадающий в предыдущие (например, наведение на объект).",
Mopn: "На телескопе проводятся наблюдения.<p></p>Внимание! Этот режим не устанавливается автоматически и зависит от того, не забудет ли оператор при начале наблюдений нажать кнопку \"Забрало открыто\", а после их окончаний - кнопку \"Забрало закрыто\".",
Statbtn: "При нажатии этой кнопки отображается/скрывается форма для запроса дополнительной статистики: экстремальные значения метеопараметров, интересующий диапазон метеопараметров.",
Visorbtn: "При нажатии на эту кнопку активируется режим \"Забрало открыто/закрыто\".<p></p>Текущий статус отображается текстовой строкой.",
StMax: "Нажмите на эту кнопку для отображения максимальных значений всех метеопараметров за выбранный промежуток времени.",
StMin: "Нажмите на эту кнопку для отображения минимальных значений всех метеопараметров за выбранный промежуток времени.",
StMode: "Нажмите на эту кнопку, если хотите узнать, сколько времени телескоп провел в каждом из режимов за выбранный промежуток времени.",
morethan: "Введите в это поле нижнюю границу значения интересующего метеопараметра.<p></p>Параметр должен быть отмечен \"галочкой\" на форме \"Отобразить\".",
and_or: "Выбор логики, возможные значения: \"И\" и \"ИЛИ\". Примеры:<ul><li>для поиска значений больше заданного заполните поле \"больше\", оставьте пустым поле \"меньше\", выберите логику \"ИЛИ\";</li><li>для поиска значений меньше заданного оставьте незаполненным поле \"больше\", заполните поле \"меньше\", логика - \"ИЛИ\";</li><li>если Вы выберете логику \"ИЛИ\" и заполните оба поля, будут найдены значения <b>вне</b> диапазона между \"меньше\" и \"больше\", число в поле \"меньше\" должно быть меньше числа в поле \"больше\";</li><li>при выборе логики \"И\" оба поля должны быть обязательно заполнены, отображаются данные <b>внутри</b> диапазона между \"больше\" и \"меньше\", число в поле \"меньше\" должно быть больше числа в поле \"больше\".</li></ul>Если в результате запроса никакие результаты не отобразились, значит, выбранные метеопараметры имели значения внутри заданного диапазона в течение всего выбранного времени.",
lessthan: "Введите в это поле верхнюю границу значения интересующего метеопараметра.<p></p>Параметр должен быть отмечен \"галочкой\" на форме \"Отобразить\".",
MkStat: "После заполнения полей слева, нажмите эту кнопку для получения статистики.",
Sall: "Отметьте те метеопараметры, которые вы хотите видеть на графике, или по которым вы хотите запросить диапазоны времени с интересующими значениями.<p></p>При щелчке по этой надписи инвертируется выбор всех метеопараметров.",
Stemp: "Щелкните по этой надписи для инвертирования выбора температур.",
Sout: "Отобразить данные по внешней температуре.",
Sin: "Отобразить данные по внутренней температуре.",
Smr: "Отобразить данные по температуре зеркала.",
Swnd: "Отобразить данные по скорости ветра.",
Sprs: "Отобразить данные по атмосферному давлению.",
Shmd: "Отобразить данные по относительной влажности.",
imcontrols: "Выберите формат изображения для отображения графиков.",
SVG: "Векторный формат SVG лучше всего подходит для отображения графиков, может быть вставлен в любую презентацию или отчет (во втором случае конвертируйте его в eps при помощи утилиты convert пакета ImageMagic).<p><p>Внимание! Старые браузеры не способны отобразить этот формат. Если ваш браузер не будет отображать графики, либо обновите его, либо выберите другой формат изображения.",
JPEG: "Наиболее популярный формат для хранения растровых изображения. Имеет наихудшее качество, в чем вы можете убедиться.",
GIF: "Растровый формат, немногим лучше JPEG.<p></p>JPEG и GIF неудобны для помещения в презентации или отчеты, т.к. плохо масштабируются (из-за своей растровой природы)."
}

145
datetime.css Normal file
View File

@ -0,0 +1,145 @@
/* form with data & time */
.datetime {
width: 150px;}
/* button showdate */
.dpBtn {
width: 22px;}
/* input for time value */
.dpTime {
width: 80px;}
/* the div that holds the date picker calendar */
.dpDiv {
}
/* the table (within the div) that holds the date picker calendar */
.dpTable {
font-family: Tahoma, Arial, Helvetica, sans-serif;
font-size: 12px;
text-align: center;
color: #505050;
background: #ECF5F8;
border: 0px;
width: 180px;
}
/* a table row that holds date numbers (either blank or 1-31) */
.dpTR {
}
/* the top table row that holds the month, year, and forward/backward buttons */
.dpTitleTR {
}
/* the second table row, that holds the names of days of the week (Mo, Tu, We, etc.) */
.dpDayTR {
}
/* the bottom table row, that has the "This Month" and "Close" buttons */
.dpTodayButtonTR {
}
/* a table cell that holds a date number (either blank or 1-31) */
.dpTD {
border: 0px;
width: 25px;
}
/* a table cell that holds a highlighted day (usually either today's date or the current date field value) */
.dpDayHighlightTD {
border: 0px;
background-color: #CCCCCC;
}
/* the date number table cell that the mouse pointer is currently over (you can use contrasting colors to make it apparent which cell is being hovered over) */
.dpTDHover {
border: 0px;
font-style: oblique;
background-color: #aca998;
cursor: pointer;
color: red;
}
/* the table cell that holds the name of the month and the year */
.dpTitleTD {
border: 0px;
}
/* the table cell that holds the time */
.dpFullTitleTD {
border: 0px;
}
/* a table cell that holds one of the forward/backward buttons */
.dpButtonTD {
border: 0px;
}
/* the table cell that holds the "This Month" or "Close" button at the bottom */
.dpTodayButtonTD {
border: 0px;
}
/* a table cell that holds the names of days of the week (Mo, Tu, We, etc.) */
.dpDayTD {
background-color: #CCCCCC;
border: 0px;
color: white;
}
/* additional style information for the text that indicates the month and year */
.dpTitleText {
font-size: 12px;
color: gray;
text-align: center;
font-weight: bold;
}
/* additional style information for the cell that holds a highlighted day (usually either today's date or the current date field value) */
.dpDayHighlight {
color: 4060ff;
font-weight: bold;
}
/* the forward/backward buttons at the top */
.dpButton {
font-family: Verdana, Tahoma, Arial, Helvetica, sans-serif;
font-size: 6pt;
background: #8FCADB;
padding: 2px;
width: 20pt;
border: 0px solid #64A6B9;
color: white;
font-weight: bold;
margin-bottom: 1px;
}
/* the "This Month" and "Close" buttons at the bottom */
.dpTodayButton {
font-family: Arial, Verdana, Tahoma, Helvetica, sans-serif;
font-size: 10px;
color: white;
background: #8FCADB;
font-weight: bold;
border: 0px solid #64A6B9;
padding: 1px 3px 1px 3px;
margin-right: 3px;
}

376
datetime.js Normal file
View File

@ -0,0 +1,376 @@
var datePickerDivID = "datepicker";
var iFrameDivID = "datepickeriframe";
var dayArray = new Array('Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa');
var monthArray = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July',
'August', 'September', 'October', 'November', 'December');
var timefieldValue = null; // óÏÄÅÒÖÉÍÏÇÏ ÐÏÌÑ "×ÒÅÍÑ"
var defaultDateSeparator = "/"; // common values would be "/" or "."
var defaultDateFormat = "mdy" // valid values are "mdy", "dmy", and "ymd"
var dateSeparator = defaultDateSeparator;
var dateFormat = defaultDateFormat;
function displayDatePicker(dateFieldName, displayBelowThisObject, dtFormat, dtSep)
{
var targetDateField = document.getElementsByName(dateFieldName).item(0);
// if we weren't told what node to display the datepicker beneath, just display it
// beneath the date field we're updating
if (!displayBelowThisObject)
displayBelowThisObject = targetDateField;
// if a date separator character was given, update the dateSeparator variable
if (dtSep)
dateSeparator = dtSep;
else
dateSeparator = defaultDateSeparator;
// if a date format was given, update the dateFormat variable
if (dtFormat)
dateFormat = dtFormat;
else
dateFormat = defaultDateFormat;
var x = displayBelowThisObject.offsetLeft;
var y = displayBelowThisObject.offsetTop + displayBelowThisObject.offsetHeight ;
// deal with elements inside tables and such
var parent = displayBelowThisObject;
while (parent.offsetParent) {
parent = parent.offsetParent;
x += parent.offsetLeft;
y += parent.offsetTop ;
}
drawDatePicker(targetDateField, x, y);
}
function drawDatePicker(targetDateField, x, y)
{
var dt = getFieldDate(targetDateField.value );
// the datepicker table will be drawn inside of a <div> with an ID defined by the
// global datePickerDivID variable. If such a div doesn't yet exist on the HTML
// document we're working with, add one.
if (!document.getElementById(datePickerDivID)) {
// don't use innerHTML to update the body, because it can cause global variables
// that are currently pointing to objects on the page to have bad references
//document.body.innerHTML += "<div id='" + datePickerDivID + "' class='dpDiv'></div>";
var newNode = document.createElement("div");
newNode.setAttribute("id", datePickerDivID);
newNode.setAttribute("class", "dpDiv");
newNode.setAttribute("style", "visibility: hidden;");
document.body.appendChild(newNode);
}
// move the datepicker div to the proper x,y coordinate and toggle the visiblity
var pickerDiv = document.getElementById(datePickerDivID);
pickerDiv.style.position = "absolute";
pickerDiv.style.left = x + "px";
pickerDiv.style.top = y + "px";
pickerDiv.style.visibility = (pickerDiv.style.visibility == "visible" ? "hidden" : "visible");
pickerDiv.style.display = (pickerDiv.style.display == "block" ? "none" : "block");
pickerDiv.style.zIndex = 10000;
// draw the datepicker table
refreshDatePicker(targetDateField.name, dt.getFullYear(), dt.getMonth(), dt.getDate());
}
function getTimeString(time){
var hourString = "00" + time.getHours();
var minuteString = "00" + time.getMinutes();
hourString = hourString.substring(hourString.length - 2);
minuteString = minuteString.substring(minuteString.length - 2);
var timeString = ' ' + hourString + ':' + minuteString;
return timeString;
}
// Fill time field with current time
function getTimeInput(){
var str = "time: <input id='dp_Time' class='dpTime' value='";
if(!timefieldValue){
var tm = new Date();
timefieldValue = getTimeString(tm);
}
str += timefieldValue;
str += "' OnChange='timefieldValue=this.value'>"
return str;
}
/**
This is the function that actually draws the datepicker calendar.
*/
function refreshDatePicker(dateFieldName, year, month, day)
{
// if no arguments are passed, use today's date; otherwise, month and year
// are required (if a day is passed, it will be highlighted later)
var thisDay = new Date();
if ((month >= 0) && (year > 0)) {
thisDay = new Date(year, month, 1);
} else {
day = thisDay.getDate();
thisDay.setDate(1);
}
// the calendar will be drawn as a table
// you can customize the table elements with a global CSS style sheet,
// or by hardcoding style and formatting elements below
var crlf = "\r\n";
var TABLE = "<table cols=7 class='dpTable'>" + crlf;
var xTABLE = "</table>" + crlf;
var TR = "<tr class='dpTR'>";
var TR_title = "<tr class='dpTitleTR'>";
var TR_days = "<tr class='dpDayTR'>";
var TR_todaybutton = "<tr class='dpTodayButtonTR'>";
var xTR = "</tr>" + crlf;
var TD = "<td class='dpTD' onMouseOut='this.className=\"dpTD\";' onMouseOver=' this.className=\"dpTDHover\";' "; // leave this tag open, because we'll be adding an onClick event
var TD_title = "<td colspan=5 class='dpTitleTD'>";
var TD_fullstring = "<td colspan=7 class='dpFullTitleTD'>";
var TD_buttons = "<td class='dpButtonTD' align='center'>";
var TD_todaybutton = "<td colspan=3 class='dpTodayButtonTD'>";
var TD_days = "<td class='dpDayTD'>";
var TD_selected = "<td class='dpDayHighlightTD' onMouseOut='this.className=\"dpDayHighlightTD\";' onMouseOver='this.className=\"dpTDHover\";' "; // leave this tag open, because we'll be adding an onClick event
var xTD = "</td>" + crlf;
var DIV_title = "<div class='dpTitleText'>";
var DIV_selected = "<div class='dpDayHighlight'>";
var xDIV = "</div>";
// start generating the code for the calendar table
var html = TABLE;
// here we add time input string
html += TR_title + TD_fullstring + getTimeInput() + xTD + xTR;
// this is the title bar, which displays the month and the buttons to
// go back to a previous month or forward to the next month
html += TR_title;
html += TD_buttons + getButtonCode(dateFieldName, thisDay, -12, "&lt;&lt;","Previous year") + '<br />' + getButtonCode(dateFieldName, thisDay, -1, "&lt;","Previous month") + xTD;
html += TD_title + DIV_title + monthArray[ thisDay.getMonth()] + " " + thisDay.getFullYear() + xDIV + xTD;
html += TD_buttons + getButtonCode(dateFieldName, thisDay, 12, "&gt;&gt;", "Next year") + '<br />' + getButtonCode(dateFieldName, thisDay, 1, "&gt;","next month") + xTD;
html += xTR;
// this is the row that indicates which day of the week we're on
html += TR_days;
for(i = 0; i < dayArray.length; i++)
html += TD_days + dayArray[i] + xTD;
html += xTR;
// now we'll start populating the table with days of the month
html += TR;
// first, the leading blanks
for (i = 0; i < thisDay.getDay(); i++)
html += TD + "&nbsp;" + xTD;
// now, the days of the month
do {
dayNum = thisDay.getDate();
TD_onclick = " onclick=\"updateDateField('" + dateFieldName + "', '" + getDateString(thisDay) + "');\">";
if (dayNum == day)
html += TD_selected + TD_onclick + DIV_selected + dayNum + xDIV + xTD;
else
html += TD + TD_onclick + dayNum + xTD;
// if this is a Saturday, start a new row
if (thisDay.getDay() == 6)
html += xTR + TR;
// increment the day
thisDay.setDate(thisDay.getDate() + 1);
} while (thisDay.getDate() > 1)
// fill in any trailing blanks
if (thisDay.getDay() > 0) {
for (i = 6; i > thisDay.getDay(); i--)
html += TD + "&nbsp;" + xTD;
}
html += xTR;
// add a button to allow the user to easily return to today, or close the calendar
var today = new Date();
html += TR_todaybutton + TD_todaybutton;
html += "<button class='dpTodayButton' onClick='refreshDatePicker(\"" + dateFieldName + "\");'>Today</button> ";
html += xTD + TD_buttons + xTD + TD_todaybutton;
html += "<button class='dpTodayButton' onClick='updateDateField(\"" + dateFieldName + "\");'>Close</button>";
html += xTD + xTR;
// and finally, close the table
html += xTABLE;
document.getElementById(datePickerDivID).innerHTML = html;
// add an "iFrame shim" to allow the datepicker to display above selection lists
adjustiFrame();
}
/**
Convenience function for writing the code for the buttons that bring us back or forward
a month.
*/
function getButtonCode(dateFieldName, dateVal, adjust, label, title)
{
var newMonth = (dateVal.getMonth () + adjust) % 12;
var newYear = dateVal.getFullYear() + parseInt((dateVal.getMonth() + adjust) / 12);
if (newMonth < 0) {
newMonth += 12;
newYear += -1;
}
return "<button title='" + title + "' class='dpButton' onClick='refreshDatePicker(\"" + dateFieldName + "\", " + newYear + ", " + newMonth + ");'>" + label + "</button>";
}
/**
Convert a JavaScript Date object to a string, based on the dateFormat and dateSeparator
variables at the beginning of this script library.
*/
function getDateString(dateVal)
{
var dayString = "00" + dateVal.getDate();
var monthString = "00" + (dateVal.getMonth()+1);
dayString = dayString.substring(dayString.length - 2);
monthString = monthString.substring(monthString.length - 2);
switch (dateFormat) {
case "dmy" :
return dayString + dateSeparator + monthString + dateSeparator + dateVal.getFullYear();
case "ymd" :
return dateVal.getFullYear() + dateSeparator + monthString + dateSeparator + dayString;
case "mdy" :
default :
return monthString + dateSeparator + dayString + dateSeparator + dateVal.getFullYear();
}
}
/**
Convert a string to a JavaScript Date object.
*/
function getFieldDate(dateString)
{
var dateVal;
var dArray;
var d, m, y;
try {
dArray = splitDateString(dateString);
if (dArray) {
switch (dateFormat) {
case "dmy" :
d = parseInt(dArray[0], 10);
m = parseInt(dArray[1], 10) - 1;
y = parseInt(dArray[2], 10);
break;
case "ymd" :
d = parseInt(dArray[2], 10);
m = parseInt(dArray[1], 10) - 1;
y = parseInt(dArray[0], 10);
break;
case "mdy" :
default :
d = parseInt(dArray[1], 10);
m = parseInt(dArray[0], 10) - 1;
y = parseInt(dArray[2], 10);
break;
}
dateVal = new Date(y, m, d);
} else if (dateString) {
dateVal = new Date(dateString);
} else {
dateVal = new Date();
}
} catch(e) {
dateVal = new Date();
}
return dateVal;
}
/**
Try to split a date string into an array of elements, using common date separators.
If the date is split, an array is returned; otherwise, we just return false.
*/
function splitDateString(dateString)
{
var dArray;
if (dateString.indexOf("/") >= 0)
dArray = dateString.split("/");
else if (dateString.indexOf(".") >= 0)
dArray = dateString.split(".");
else if (dateString.indexOf("-") >= 0)
dArray = dateString.split("-");
else if (dateString.indexOf("\\") >= 0)
dArray = dateString.split("\\");
else
dArray = false;
return dArray;
}
function updateDateField(dateFieldName, dateString)
{
var timeString = "";
if(timefieldValue && dateString){
var time = new Date;
time.setTime(Date.parse(dateString +' ' + timefieldValue));
timeString = getTimeString(time);
}
var targetDateField = document.getElementsByName(dateFieldName).item(0);
if (dateString)
targetDateField.value = dateString + timeString;
var pickerDiv = document.getElementById(datePickerDivID);
pickerDiv.style.visibility = "hidden";
pickerDiv.style.display = "none";
adjustiFrame();
targetDateField.focus();
if ((dateString) && (typeof(datePickerClosed) == "function"))
datePickerClosed(targetDateField);
}
function adjustiFrame(pickerDiv, iFrameDiv)
{
// put a try/catch block around the whole thing, just in case
try {
if (!document.getElementById(iFrameDivID)) {
// don't use innerHTML to update the body, because it can cause global variables
// that are currently pointing to objects on the page to have bad references
//document.body.innerHTML += "<iframe id='" + iFrameDivID + "' src='javascript:false;' scrolling='no' frameborder='0'>";
var newNode = document.createElement("iFrame");
newNode.setAttribute("id", iFrameDivID);
newNode.setAttribute("src", "javascript:false;");
newNode.setAttribute("scrolling", "no");
newNode.setAttribute ("frameborder", "0");
document.body.appendChild(newNode);
}
if (!pickerDiv)
pickerDiv = document.getElementById(datePickerDivID);
if (!iFrameDiv)
iFrameDiv = document.getElementById(iFrameDivID);
try {
iFrameDiv.style.position = "absolute";
iFrameDiv.style.width = pickerDiv.offsetWidth;
iFrameDiv.style.height = pickerDiv.offsetHeight ;
iFrameDiv.style.top = pickerDiv.style.top;
iFrameDiv.style.left = pickerDiv.style.left;
iFrameDiv.style.zIndex = pickerDiv.style.zIndex - 1;
iFrameDiv.style.visibility = pickerDiv.style.visibility ;
iFrameDiv.style.display = pickerDiv.style.display;
} catch(e) {
}
} catch (ee) {
}
}

BIN
pdf/description.pdf Normal file

Binary file not shown.

78
temp2.css Normal file
View File

@ -0,0 +1,78 @@
body{
padding: 1px; margin: 20px;
background: #CCC; font-family: "Liberation Serif", serif;
font-style: normal; font-weight: normal;
text-indent: 0px;}
p {margin-top: 10px; margin-bottom: 2px;}
.hid{
display: none;}
h1 {
text-align: center;
margin: 20px; padding: 0px;
letter-spacing: 3pt; font-size: 160%;}
h2 {
text-align: center;
margin: 10px; padding: 0px;
letter-spacing: 1pt; font-size: 140%;}
h3 {
text-align: left; font-style: italic;
margin: 5px; padding: 0px; font-size: 120%;}
div {text-align: justify;}
.C {text-align: center;}
.Cb {text-align: center; padding: 5pt;
border: solid 1px black;}
#helptip{
position: fixed; background-color: #BFE; -moz-border-radius: 5px;
color: black; max-width: 400px; max-height: 500px; padding: 5px;
}
.redtxt {color: red; margin-top: 20px;}
.helper {position: fixed; right: 0px; top: 0px;}
.man {position: fixed; left: 0px; top: 0px;}
#lefcol{
float: left; width: 220px; margin-left: 205px; text-indent: 0px;
text-align: right;}
#fsttwo{
float: left; width: 100%; margin-left: -205px; text-indent: 0px;}
#rigcol{
padding-left: 100%; margin-left: -200px; text-indent: 0px;}
#cencol{
margin-left: 430px; min-width: 300px; vertical-align: top;
text-align: center; text-indent: 0px;}
#widecen {
min-width: 800px; width: 100%; margin-top: 20px; min-height: 300px;
vertical-align: middle; text-align: center; text-indent: 0px;}
#IMG {
width: 100%; margin: 0px; height: 75%; position: relative;
vertical-align: top; text-align: center; text-indent: 0px;}
/********************* ôÁÂÌÉÃÙ: *******************/
table {
margin: 0 auto; text-align: center;
border: 5px double; padding: 5px;
border-collapse: collapse;}
th {
text-align: center; border: 3px solid black;
padding: 7px;}
td {
border: 3px inset black;}

74
temp2.html Normal file
View File

@ -0,0 +1,74 @@
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=koi8-r">
<link rel="shortcut icon" href="favicon.ico">
<title>íÏÎÉÔÏÒÉÎÇ</title>
<link rel="stylesheet" href="temp2.css" type="text/css">
<link rel="stylesheet" href="datetime.css" type="text/css">
<script src="datetime.js" type="text/javascript" language="javascript"></script>
<script src="temp2.js" type="text/javascript" language="javascript"></script>
<script src="contexthelp.js" type="text/javascript" language="javascript"></script>
</head>
<body onload='init();' onkeydown="onkey(event.keyCode);">
<noscript><h1 align=center>÷ËÌÀÞÉÔÅ ÐÏÄÄÅÒÖËÕ JavaScript<br>Turn on Javascript</noscript>
<h2 id='header'></h2>
<div class='helper'><a href='#' onclick="startHelp(event);" id='helper'>ëÏÎÔÅËÓÔÎÁÑ ÐÏÍÏÝØ</a></div>
<div class='man'><a href="pdf/description.pdf">óÐÒÁ×ËÁ</a></div>
<div id='body'></div>
<div id='widecen'>
<div id='fsttwo'>
<div id='lefcol'>
<div class='C' id='dtheader'>
äÁÔÁ É ×ÒÅÍÑ<br>
(MM/DD/YYYY HH:MM)
</div><p></p>
Ó: <input name='t_beg' class='datetime' id='t_beg'>
<img OnClick='displayDatePicker("t_beg", false, "mdy", "/");' class='dpBtn' src='cal.jpg' name='cal'><br>
ÐÏ: <input name='t_end' class='datetime' id='t_end'>
<img OnClick='displayDatePicker("t_end", false, "mdy", "/");' class='dpBtn' src='cal.jpg' name='cal'><br>
<span id='avertime' class='hid'>
ÉÎÔÅÒ×ÁÌ ÕÓÒÅÄÎÅÎÉÑ:<br>
<input id='averinterval' size=8 value='1'>&nbsp;
<select id='averval'>
<option value='60'>ÍÉÎÕÔ
<option value='3600'>ÞÁÓÏ×
<option value='86400'>ÓÕÔÏË
</select>
</span>
<input type='button' OnClick='make_request();' value="OK" id='reqbtn'><p></p>
<b><div class='C' OnClick='checkAll(5,"mask");' id='modes'>
ðÏËÁÚÁÔØ ÄÁÎÎÙÅ:
</div></b><div>
<span id='Mstp'><input type='checkbox' name='mask' value='1' OnChange='chkvals();'>ÐÏÌÎÙÊ ÏÓÔÁÎÏ×</span><br>
<span id='Mgd'><input type='checkbox' name='mask' value='2' OnChange='chkvals();'>ÒÅÖÉÍ ÓÏÐÒÏ×ÏÖÄÅÎÉÑ</span><br>
<span id='Mrd'><input type='checkbox' name='mask' value='4' OnChange='chkvals();'>ÇÏÔÏ×</span><br>
<span id='Moth'><input type='checkbox' name='mask' value='8' OnChange='chkvals();'>ÐÒÏÞÅÅ</span><br>
<span id='Mopn'><input type='checkbox' name='mask' value='16' OnChange='chkvals();'>ÚÁÂÒÁÌÏ ÏÔËÒÙÔÏ</span><br>
</div><p style="margin-top: 20px;">
<div class='C'><input type='button' id='Statbtn' OnClick='statistics();' value="ðÏËÁÚÁÔØ ÓÔÁÔÉÓÔÉËÕ"></div>
<p style="margin-top: 40px;">
<div class='Cb' id='visorbtn'></div>
</div>
<div id='cencol' class='C'>
</div>
</div><!--frsttwo-->
<div id='rigcol'>
<b OnClick='checkAll();' id='Sall'>ïÔÏÂÒÁÚÉÔØ (×ÓÅ)</b><p></p>
<b OnClick='checkAll(3);' id='Stemp'>ÔÅÍÐÅÒÁÔÕÒÕ:</b><br>
<span id='Sout'><input type='checkbox' name='show' value='1' OnChange='chkvals();'>×ÎÅÛÎÀÀ</span><br>
<span id='Sin'><input type='checkbox' name='show' value='2' OnChange='chkvals();'>×ÎÕÔÒÅÎÎÀÀ</span><br>
<span id='Smr'><input type='checkbox' name='show' value='4' OnChange='chkvals();'>ÚÅÒËÁÌÁ<p></p>
<span id='Swnd'><input type='checkbox' name='show' value='8' OnChange='chkvals();'>óËÏÒÏÓÔØ ×ÅÔÒÁ</span><br>
<span id='Sprs'><input type='checkbox' name='show' value='16' OnChange='chkvals();'>äÁ×ÌÅÎÉÅ</span><br>
<span id='Shmd'><input type='checkbox' name='show' value='32' OnChange='chkvals();'>÷ÌÁÖÎÏÓÔØ</span><br>
<p style="margin-top: 25px;">
<div id='imcontrols'>
æÏÒÍÁÔ ÉÚÏÂÒÁÖÅÎÉÑ:<br>
<span id='SVG'><input type='radio' name='type' value='0' checked OnChange='chkvals();'>SVG</span><br>
<span id='JPEG'><input type='radio' name='type' value='1' OnChange='chkvals();'>JPEG</span><br>
<span id='GIF'><input type='radio' name='type' value='2' OnChange='chkvals();'>GIF</span>
</div>
</div>
</div><!--widecen-->
</body>
</html>

286
temp2.js Normal file
View File

@ -0,0 +1,286 @@
var request;
var timeout_id, monit_tid;
var CGI_PATH = '/cgi-bin/eddy/tempmon';
var ShowOnGraph = 0, ImType = '1';
var isRunning = 0, t_start = 0, t_end = 0, Stat = 0;
function $(Id){
return document.getElementById(Id);
}
var utf2koi={
1025:179,
1072:193,
1073:194,
1074:215,
1075:199,
1076:196,
1077:197,
1078:214,
1079:218,
1080:201,
1081:202,
1082:203,
1083:204,
1084:205,
1085:206,
1086:207,
1087:208,
1088:210,
1089:211,
1090:212,
1091:213,
1092:198,
1093:200,
1094:195,
1095:222,
1096:219,
1097:221,
1098:223,
1099:217,
1100:216,
1101:220,
1102:192,
1103:209,
1105:163
};
function hexdump(str){
var ret = "";
var l = str.length;
var i, ch, code;
for(i=0; i<l; i++){
ch = str.charCodeAt(i);
if(utf2koi[ch] != null)
code = utf2koi[ch];
else if(utf2koi[ch+32] != null)
code = utf2koi[ch+32]+32;
else code = ch;
ch = code.toString(16);
ret += "%" + ch;
}
return ret;
}
function TimeOut(){
request.abort();
handleError("Time over");
}
function handleError(msg) {
$('body').innerHTML = "<h1>ïÛÉÂËÁ xmlhttprequest:<br>" + msg + "</h1>";
}
function ch_status(){
$('body').innerHTML = request.responseText;
var scripts = $('body').getElementsByTagName("script");
for(var i=0,len=scripts.length; i<len; i++)
eval.call(window, scripts[i].innerHTML);
}
function sendrequest(req_STR, fn_OK){
request = new XMLHttpRequest();
request.open("POST", CGI_PATH, true);
request.setRequestHeader("Accept-Charset", "koi8-r");
request.overrideMimeType("multipart/form-data; charset=koi8-r");
request.onreadystatechange=function(){
if (request.readyState == 4){
if (request.status == 200){
clearTimeout(timeout_id);
fn_OK();
}
else handleError(request.statusText);
}
}
request.send(req_STR);
timeout_id = setTimeout(TimeOut, 10000);
}
function chkvals(){
var i;
var Boxes = document.getElementsByName('show');
ShowOnGraph = 0;
for(i = 0; i < Boxes.length; i++)
if(Boxes[i].checked) ShowOnGraph += parseInt(Boxes[i].value);
var Type = document.getElementsByName('type');
for(i = 0; i < Type.length; i++)
if(Type[i].checked){
ImType = Type[i].value;
break;
}
var mask = 0;
Boxes = document.getElementsByName('mask');
for(i = 0; i < Boxes.length; i++)
if(Boxes[i].checked) mask += parseInt(Boxes[i].value);
if(isRunning && !Stat)
mkImage(mask);
return mask;
}
function checkAll(ii, name){
if(!name) name = 'show';
var Boxes = document.getElementsByName(name);
var i;
if(!ii) ii = Boxes.length;
for(i = 0; i < ii; i++)
Boxes[i].checked = !Boxes[i].checked;
chkvals();
}
function get_seconds(blkid){
var td_value = $(blkid).value;
var seconds = Math.round(Date.parse(td_value) / 1000);
return seconds;
}
function clear_cencol(){
var cencol = $('cencol');
if(!cencol.childNodes) return;
while(cencol.childNodes.length > 0)
cencol.removeChild(cencol.lastChild);
}
function mkImage(mask){
if(ShowOnGraph == 0) return;
clear_cencol();
if(!mask) return;
if(ImType == '0')
var image_ = document.createElement('embed');
else
var image_ = document.createElement('img');
image_.id = 'IMG';
$('cencol').appendChild(image_);
var str = CGI_PATH + '?Graph=' + ShowOnGraph + '&' + 'Gtype=' + ImType;
if(t_start) str += '&Tstart=' + t_start;
else return;
if(t_end) str += '&Tend=' + t_end;
str += '&Stat=' + mask;
$('IMG').src = str + '?' + Math.random();
}
function make_request(stat_type){
if(!$('t_beg').value){
alert("÷×ÅÄÉÔÅ ÎÁÞÁÌØÎÏÅ ×ÒÅÍÑ");
return;
}
var averval = "";
if(Stat){
var value = parseInt($('averinterval').value);
if(!value || value < 1){
alert("÷×ÅÄÉÔÅ ÐÒÁ×ÉÌØÎÙÊ ÉÎÔÅÒ×ÁÌ ÕÓÒÅÄÎÅÎÉÑ");
return;
}
var mul = parseInt($('averval').value);
value *= mul;
averval = ' Aver=' + value + ' ';
}
var str1 = averval;
if(typeof(stat_type) != "undefined"){
averval += ' Select='+stat_type+' ';
if(stat_type == 3){
var morethan = parseFloat($('morethan').value);
var lessthan = parseFloat($('lessthan').value);
var and_or = parseInt($('and_or').value);
if(!morethan && !lessthan){
alert("îÅ ÚÁÐÏÌÎÅÎÙ ÐÏÌÑ");
return;
}
if(and_or){
if(!morethan || !lessthan){
alert("úÁÐÏÌÎÉÔÅ ÏÂÁ ÐÏÌÑ (\"ÂÏÌØÛÅ\" É \"ÍÅÎØÛÅ\")");
return;
}
if(morethan >= lessthan){
alert("÷ÅÌÉÞÉÎÁ × ÐÏÌÅ \"ÂÏÌØÛÅ\" ÄÏÌÖÎÁ ÂÙÔØ ÍÅÎØÛÅ ×ÅÌÉÞÉÎÙ × ÐÏÌÅ \"ÍÅÎØÛÅ\"\n"+
"ìÉÂÏ ÉÚÍÅÎÉÔÅ ÌÏÇÉËÕ ÎÁ \"éìé\"");
return;
}
}
else{
if(morethan <= lessthan){
alert("÷ÅÌÉÞÉÎÁ × ÐÏÌÅ \"ÂÏÌØÛÅ\" ÄÏÌÖÎÁ ÂÙÔØ ÂÏÌØÛÅ ×ÅÌÉÞÉÎÙ × ÐÏÌÅ \"ÍÅÎØÛÅ\"\n"+
"ìÉÂÏ ÉÚÍÅÎÉÔÅ ÌÏÇÉËÕ ÎÁ \"é\"");
return;
}
}
if(morethan) averval += ' Greater='+morethan+' ';
if(lessthan) averval += ' Less='+lessthan+' ';
averval += ' AndOr='+and_or+' ';
}
averval += ' Graph=' + ShowOnGraph + ' ';
}
var td = new Date();
var fd = new Date();
var t_now = Math.round(td / 1000);
t_start = get_seconds('t_beg');
if(t_start >= t_now){
alert("îÁÞÁÌØÎÏÅ ×ÒÅÍÑ × ÂÕÄÕÝÅÍ :)");
return;
}
var str = 'Tstart=' + t_start;
if($('t_end').value){
t_end = get_seconds('t_end');
str += ' Tend=' + t_end;
td.setTime(t_end * 1000);}
else t_end = 0;
isRunning = 1;
var mask = chkvals();
str += ' Stat=' + mask;
str1 += str;
str += averval;
function getstat(){$('Stat').innerHTML = request.responseText;
if(mask) sendrequest(str1, ch_status);}
function ok(){visor(); if(typeof(stat_type) != "undefined") sendrequest(str, getstat);
else if(mask) sendrequest(str1, ch_status);}
sendrequest("Visor=-1", ok);
fd.setTime(t_start * 1000);
$('header').innerHTML = 'äÁÎÎÙÅ Ó ' + fd.toLocaleFormat("%H:%M %d/%m/%Y") +
' ÐÏ ' + td.toLocaleFormat("%H:%M %d/%m/%Y");
}
function visor(){
$('visorbtn').innerHTML = request.responseText;
}
function init(){
sendrequest("Visor=-1", visor);
}
function Show(id){
$(id).style.display = 'block';
}
function Hide(id){
$(id).style.display = 'none';
}
function statistics(){
if(Stat){
Stat = 0;
clear_cencol();
$('Statbtn').value = 'ðÏËÁÚÁÔØ ÓÔÁÔÉÓÔÉËÕ';
Show('imcontrols');
Hide('avertime');
chkvals();
}
else{
Stat = 1;
clear_cencol();
$('Statbtn').value = "õÂÒÁÔØ ÓÔÁÔÉÓÔÉËÕ";
var stat_div = document.createElement('div');
stat_div.id = 'Stat';
var stat_btns = document.createElement('div');
stat_btns.className = 'C';
stat_btns.innerHTML = "<h3>ïÔÏÂÒÁÚÉÔØ ÉÎÔÅÒ×ÁÌÙ ×ÒÅÍÅÎÉ Ó ÈÁÒÁËÔÅÒÉÓÔÉËÁÍÉ:</h3><p>\n"+
"<input type='button' OnClick='make_request(1);' value='íÁËÓÉÍÕÍ' id='StMax'>&nbsp;&nbsp;&nbsp;\n"+
"<input type='button' OnClick='make_request(2);' value='íÉÎÉÍÕÍ' id='StMin'>&nbsp;&nbsp;&nbsp;\n"+
"<input type='button' OnClick='make_request(0);' value='òÅÖÉÍ ÒÁÂÏÔÙ' id='StMode'><p>"+
"÷ ÄÉÁÐÁÚÏÎÅ: ÂÏÌØÛÅ <input id='morethan' size=8> "+
"<select id='and_or'><option value='1'>é<option value='0'>éìé</select>"+
" ÍÅÎØÛÅ <input id='lessthan' size=8> "+
"<input type='button' OnClick='make_request(3);' value='OK' id='MkStat'><p>\n";
$('cencol').appendChild(stat_btns);
$('cencol').appendChild(stat_div);
Hide('imcontrols');
Show('avertime');
}
}