This commit is contained in:
Edward Emelianov 2025-06-10 11:42:19 +03:00
parent 288cfcb2b9
commit 1e829a8ca8
10 changed files with 1917 additions and 848 deletions

View File

@ -56,7 +56,7 @@ void send_data(unsigned char stat_mask){
char s_time[32]; char s_time[32];
monit_d data; monit_d data;
if(!only_extr){ if(!only_extr){
printf("OT - %s\nIT - %s\nMT - %s\nWS - %s\nP - %s\nH - %s\nS - %s\n\n", printf("OT - %s\nIT - %s\nMT - %s\nWS - %s\nP - %s\nH - %s\nS - %s (0 - off, 1 - guiding, 2 - ready, 3 - moving, 4 - opened)\n\n",
_L(_s_Otemp_), _L(_s_Itemp_), _L(_s_Mtemp_), _L(_s_Otemp_), _L(_s_Itemp_), _L(_s_Mtemp_),
_L(_s_WSpeed_), _L(_s_Pressure_), _L(_s_Humidity_), _L(_s_WSpeed_), _L(_s_Pressure_), _L(_s_Humidity_),
_L(_s_State_)); _L(_s_State_));

File diff suppressed because it is too large Load Diff

View File

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

BIN
C/daemon/html/cal.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 488 B

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
C/daemon/html/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/html/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/html/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
C/daemon/html/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
C/daemon/html/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');
}
}