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

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.