Compare commits

...

11 Commits

Author SHA1 Message Date
fd37853735 cont 2026-06-19 14:47:06 +03:00
413f7bf75e start new 10-micron stellarium daemon 2026-06-19 12:29:39 +03:00
e33a7b9186 fixed little bug 2026-06-15 16:27:31 +03:00
ed01d68fd2 new "run" 2026-06-10 09:23:34 +03:00
59d7701ba7 little fix 2026-06-08 09:01:16 +03:00
191b77a0b7 fixed bug with forgotten sleep 2026-06-03 11:16:30 +03:00
768d46060d little fixes 2026-05-22 09:45:35 +03:00
51869f0137 add docs, make little fixes 2026-05-21 17:38:44 +03:00
b28832fe41 seems like it works 2026-05-21 16:31:59 +03:00
bff6e06684 started weather_logger 2026-05-20 17:20:13 +03:00
7ca5498092 add documentation 2026-05-18 11:50:36 +03:00
99 changed files with 5116 additions and 656 deletions

View File

@@ -2,10 +2,10 @@
RA="17:17:08.86" RA="17:17:08.86"
DEC="+67:57:11.4" DEC="+67:57:11.4"
OBJ="GALEX171708.5" OBJ="GALEX171708.5"
EXPTIME=31000 # now exptime in seconds!
FLATTIME=40000 EXPTIME=40
OBS="Fatkhullin T.A." FLATTIME=40
BADWEATHER=1300 OBS="Emelianov E.V."
DATEEND=$(sunrise 14) DATEEND=$(sunrise 14)
# focus each N seconds # focus each N seconds
FOCUST=7200 FOCUST=7200
@@ -35,25 +35,25 @@ function focustel_new(){
let fno=$1 let fno=$1
if [[ $fno -gt 1 ]]; then if [[ $fno -gt 1 ]]; then
let curr_foc=`fli_control | tail -n 5 | head -n 1 | cut -d "=" -f 2` let curr_foc=`fli_control | grep FOCPOS | cut -d "=" -f 2`
let lowf=$curr_foc-1500 lowf=$(echo "$curr_foc - 0.3" | bc -l)
let highf=$curr_foc+1500 highf=$(echo "$curr_foc + 0.3" | bc -l)
focus_seq_FLI.py -v -c focus$(printf "%02d" $1).jpg $lowf $highf 500 focus_seq_FLI.py -v -c focus$(printf "%02d" $1).jpg $lowf $highf 0.1
retcode=$?
if [[ $? -ne 0 ]]; then if [[ $retcode -ne 0 ]]; then
echo -e "\nFOCUSSING SCRIPT RETURNED: $?" echo -e "\nFOCUSSING SCRIPT RETURNED: $retcode"
echo -e "SOMETHING WAS WRONG IN FOCUSSING SEQUENCE!!! SET FOCUS TO PREVIOUS VALUE!!\n" echo -e "SOMETHING WAS WRONG IN FOCUSSING SEQUENCE!!! SET FOCUS TO PREVIOUS VALUE!!\n"
fli_control -g $curr_foc fli_control -g $curr_foc
return $retcode
fi fi
else else
focus_seq_FLI.py --guess -v -N 7 -c focus$(printf "%02d" $1).jpg 47000 60000 500 focus_seq_FLI.py --guess -v -N 7 -c focus$(printf "%02d" $1).jpg 4.25 5.75 0.25
return $?
fi fi
FDATE=$(date +%s)
} }
function sendcmd(){ function sendcmd(){
echo $1 | nc 192.168.70.33 10001 -q10 echo $1 | nc localhost 10001 -q2
} }
function point_tel(){ function point_tel(){
@@ -73,7 +73,8 @@ if [[ $(pgrep -c run_full) -gt 1 ]]; then
exit 1 exit 1
fi fi
export http_proxy="" unset http_proxy
unset https_proxy
# set lower limit to 5degr # set lower limit to 5degr
send_command2mount ":So5#" send_command2mount ":So5#"
@@ -103,36 +104,47 @@ echo "Start taking object"
badweather=0 badweather=0
while true; do while true; do
now=$(date +%s) now=$(date +%s)
ANS=$(curl localhost:55555/status 2>/dev/null) ANS=$(curl localhost:55555/status 2>/dev/null | grep status | cut -d "=" -f2)
echo "Dome status: $ANS" echo "Dome status: $ANS"
if [ $ANS != "opened" ]; then if [[ $ANS != "opened" ]]; then
echo "Closed" echo -e "\n\nBREAK by Closed Dome\n\n"
curl localhost:55555/weather 2>/dev/null > DomeClosed curl localhost:55555/weather 2>/dev/null > DomeClosed
curl localhost:55555/status 2>/dev/null >> DomeClosed
break; break;
fi fi
chkweather ${BADWEATHER} > lastweather && badweather=0 || badweather=$((badweather+1)) WLVL=0
[ $badweather -gt 5 ] && break chkweather | sed 's/\[.*//' > lastweather && badweather=0 || WLVL=$?
[ -f stopobs ] && break [[ $x -gt 1 ]] && badweather=$((badweather+1))
[ -f exitjob ] && exit 0 eval $(cat lastweather)
if [ "$now" -lt "$DATEEND" ]; then [[ $badweather -gt 5 ]] && (echo -e "\n\nBREAK by BAD WEATHER\n\n"; break)
[[ $ForceOFF == 1 ]] && (echo -e "\n\nBREAK by FORCE OFF\n\n"; break)
[[ -f stopobs ]] && (echo -e "\n\nBREAK by STOP OBS\n\n"; break)
[[ -f exitjob ]] && (echo -e "\n\nEXIT JOB\n\n"; exit 0)
if [[ "$now" -lt "$DATEEND" ]]; then
est=$(sendcmd ":Gmte#"|sed -e 's/^0*//' -e 's/#//') est=$(sendcmd ":Gmte#"|sed -e 's/^0*//' -e 's/#//')
echo -e "\n\n\n\n\nEstimated time to flip: $est minutes" echo -e "\n\nEstimated time to flip: $est minutes\n"
if [[ ("x$est" == "x") || ($est -lt 3) ]]; then if [[ ("x$est" == "x") || ($est -lt 3) ]]; then
echo -e "\n\nRepointing: approaching flip\n\n"
point_tel "${RA}" "${DEC}" point_tel "${RA}" "${DEC}"
continue continue
fi fi
ST=$(send_coords | awk '{print $4}') ST=$(send_coords | awk '{print $4}')
[ "x$ST" == "x" ] && break [[ "x$ST" == "x" ]] && (echo -e "\n\nBREAK: have no answer from `send_coords`\n\n"; break)
if [ $ST -ne "0" ]; then if [[ $ST -ne "0" ]]; then
echo -e "\n\nRepoint: Mount status is not 'tracking'\n\n"
point_tel "${RA}" "${DEC}" point_tel "${RA}" "${DEC}"
continue continue
else else
[ $(($(date +%s) - $FDATE)) -gt $FOCUST ] && focustel_new $((FNO++)) if [[ $(($(date +%s) - $FDATE)) -gt $FOCUST ]]; then
# [ $(($(date +%s) - $FDATE)) -gt $FOCUST ] && focustel $((FNO++)) echo -e "\n\nREFOCUSING by timeout\n\n"
focustel_new $((FNO++)) && FDATE=$(date +%s) || FNO=$((--FNO))
echo "FDATE: $FDATE, FNO: $FNO"
fi
preflash preflash
fli_control -r /tmp/10micron.fitsheader -x $EXPTIME -N "${OBS}" -O "${OBJ}" "$OBJ" fli_control -x $EXPTIME -N "${OBS}" -O "${OBJ}" "$OBJ"
fi fi
else else
echo -e "\n\nBREAK: night is over\n\n"
break break
fi fi
done done
@@ -140,8 +152,8 @@ done
echo "Dome closed @ $(date)" >> closed echo "Dome closed @ $(date)" >> closed
curl localhost:55555/close curl localhost:55555/close
relay_manage -s1
park_telescope park_telescope
Flat on
for x in $(seq 1 10); do for x in $(seq 1 10); do
preflash preflash
@@ -152,7 +164,7 @@ for x in $(seq 1 10); do
fli_control -r /tmp/10micron.fitsheader -n3 -x $FLATTIME -N "${OBS}" -O "flat" flat fli_control -r /tmp/10micron.fitsheader -n3 -x $FLATTIME -N "${OBS}" -O "flat" flat
done done
relay_manage -r1 Flat off
echo "Closed @ $(date)" >> closed echo "Closed @ $(date)" >> closed
STOPobs || true STOPobs || true

View File

@@ -0,0 +1,165 @@
#!/bin/bash
RA="17:17:08.86"
DEC="+67:57:11.4"
OBJ="GALEX171708.5"
EXPTIME=31000
FLATTIME=40000
OBS="Fatkhullin T.A."
BADWEATHER=1300
DATEEND=$(sunrise 14)
# focus each N seconds
FOCUST=7200
FNO=1
FDATE=0
#
# NOTE: THIS IS A NEW VERSION OF THE OBSERVATION SCRIPT!
# CHAGLELOG:
# Oct 2024: replace focussing algorithm (T. Fatkhullin)
# At the night start the first focussing run
# uses of two-step algorithm:
# 1) rough focus astimation along full season-to-season
# focus range (as it was implemented in the old obs. script)
# 2) precise focussing along narrow range computed from
# previous rough estimation
# Next focussing runs compute range from the current focus value.
# (new function 'focustel_new')
#
# May 2025: rewrite detection of running this script process (T. Fatkhullin)
# (use of '-c' commandline option for 'pgrep' command)
function focustel_new(){
rm focus*.fit 2>/dev/null
echo "Focussing..."
let fno=$1
if [[ $fno -gt 1 ]]; then
let curr_foc=`fli_control | tail -n 5 | head -n 1 | cut -d "=" -f 2`
let lowf=$curr_foc-1500
let highf=$curr_foc+1500
focus_seq_FLI.py -v -c focus$(printf "%02d" $1).jpg $lowf $highf 500
if [[ $? -ne 0 ]]; then
echo -e "\nFOCUSSING SCRIPT RETURNED: $?"
echo -e "SOMETHING WAS WRONG IN FOCUSSING SEQUENCE!!! SET FOCUS TO PREVIOUS VALUE!!\n"
fli_control -g $curr_foc
fi
else
focus_seq_FLI.py --guess -v -N 7 -c focus$(printf "%02d" $1).jpg 47000 60000 500
fi
FDATE=$(date +%s)
}
function sendcmd(){
echo $1 | nc 192.168.70.33 10001 -q10
}
function point_tel(){
touch lastpointing
send_coords -r $1 -d $2
}
#c=$(pgrep run_full | wc -l)
# $ will run another run_full, so c=2 for single run
#if [[ $c -gt 1 ]]; then
# echo "Another process is running; exiting"
# exit 1
#fi
if [[ $(pgrep -c run_full) -gt 1 ]]; then
echo "Another process is running! Exit!"
exit 1
fi
export http_proxy=""
# set lower limit to 5degr
send_command2mount ":So5#"
echo "Time diff: $(($DATEEND-$(date +%s)))"
if [ $(($DATEEND-$(date +%s))) -lt 3600 ]; then
echo "There's less an hour for observation!"
exit 2
fi
if [ $(($DATEEND-$(date +%s))) -gt 53200 ]; then
echo "There's more than 12 hours till closing, check script data!"
exit 3
fi
#STARTobs
#send_coords
#echo "Wait a little"
#sleep 10
echo "GoTo object: ${RA} ${DEC}"
send_coords -r${RA} -d${DEC}
echo "Start taking object"
badweather=0
while true; do
now=$(date +%s)
ANS=$(curl localhost:55555/status 2>/dev/null)
echo "Dome status: $ANS"
if [ $ANS != "opened" ]; then
echo "Closed"
curl localhost:55555/weather 2>/dev/null > DomeClosed
break;
fi
chkweather ${BADWEATHER} > lastweather && badweather=0 || badweather=$((badweather+1))
[ $badweather -gt 5 ] && break
[ -f stopobs ] && break
[ -f exitjob ] && exit 0
if [ "$now" -lt "$DATEEND" ]; then
est=$(sendcmd ":Gmte#"|sed -e 's/^0*//' -e 's/#//')
echo -e "\n\n\n\n\nEstimated time to flip: $est minutes"
if [[ ("x$est" == "x") || ($est -lt 3) ]]; then
point_tel "${RA}" "${DEC}"
continue
fi
ST=$(send_coords | awk '{print $4}')
[ "x$ST" == "x" ] && break
if [ $ST -ne "0" ]; then
point_tel "${RA}" "${DEC}"
continue
else
[ $(($(date +%s) - $FDATE)) -gt $FOCUST ] && focustel_new $((FNO++))
# [ $(($(date +%s) - $FDATE)) -gt $FOCUST ] && focustel $((FNO++))
preflash
fli_control -r /tmp/10micron.fitsheader -x $EXPTIME -N "${OBS}" -O "${OBJ}" "$OBJ"
fi
else
break
fi
done
echo "Dome closed @ $(date)" >> closed
curl localhost:55555/close
relay_manage -s1
park_telescope
for x in $(seq 1 10); do
preflash
fli_control -r /tmp/10micron.fitsheader -x1 -N "${OBS}" -O "bias" -d bias
preflash
fli_control -r /tmp/10micron.fitsheader -x $EXPTIME -N "${OBS}" -O "dark" -d dark
preflash
fli_control -r /tmp/10micron.fitsheader -n3 -x $FLATTIME -N "${OBS}" -O "flat" flat
done
relay_manage -r1
echo "Closed @ $(date)" >> closed
STOPobs || true
DIR=$(basename $PWD)
echo "TAR: $DIR"
cd ..
./copy_and_xz.sh $DIR
echo "Archived, end"
echo "$DIR archived @ $(date)" >> archived

View File

@@ -0,0 +1,64 @@
cmake_minimum_required(VERSION 4.0)
set(PROJ mountdaemon_10micron)
project(${PROJ})
set(MAJOR_VERSION "0")
set(MID_VERSION "1")
set(MINOR_VERSION "1")
set(VERSION "${MAJOR_VERSION}.${MID_VERSION}.${MINOR_VERSION}")
enable_language(C)
message("VER: ${VERSION}")
# options
option(DEBUG "Compile in debug mode" OFF)
# default flags
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -W -Wextra -std=c23")
if(DEBUG)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Og -g3 -ggdb -fno-builtin-strlen -Werror")
add_definitions(-DEBUG)
set(CMAKE_BUILD_TYPE DEBUG)
set(CMAKE_VERBOSE_MAKEFILE "ON")
else()
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -O3 -march=native -fdata-sections -ffunction-sections -flto=auto")
SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,--gc-sections -flto=auto")
set(CMAKE_BUILD_TYPE RELEASE)
endif()
message("Build type: ${CMAKE_BUILD_TYPE}")
set(CMAKE_COLOR_MAKEFILE ON)
# here is one of two variants: all .c in directory or .c files in list
aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR} SOURCES)
###### pkgconfig ######
find_package(PkgConfig REQUIRED)
pkg_check_modules(MODULES REQUIRED usefull_macros>=0.3.2 erfa>=2.0.0)
# change wrong behaviour with install prefix
if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT AND CMAKE_INSTALL_PREFIX MATCHES "/usr/local")
else()
message("Change default install path to /usr/local")
set(CMAKE_INSTALL_PREFIX "/usr/local")
endif()
message("Install dir prefix: ${CMAKE_INSTALL_PREFIX}")
# executable file
add_executable(${PROJ} ${SOURCES})
# -I
target_include_directories(${PROJ} PUBLIC ${MODULES_INCLUDE_DIRS})
# -L
target_link_directories(${PROJ} PUBLIC ${MODULES_LIBRARY_DIRS})
# -l
target_link_libraries(${PROJ} ${MODULES_LIBRARIES} -lweather -lm)
# -D
add_definitions(-D_XOPEN_SOURCE=1234 -D_DEFAULT_SOURCE -D_GNU_SOURCE
-DPACKAGE_VERSION=\"${VERSION}\" -DMINOR_VERSION=\"${MINOR_VERSION}\"
-DMID_VERSION=\"${MID_VERSION}\" -DMAJOR_VERSION=\"${MAJOR_VESION}\"
)
# Installation of the program
INSTALL(TARGETS ${PROJ} DESTINATION "bin")

View File

@@ -0,0 +1,410 @@
/*
* This file is part of the mountdaemon_10micron project.
* Copyright 2026 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
#include <erfa.h>
#include <erfam.h>
#include <math.h>
#include <time.h>
#include <usefull_macros.h>
#include "angles.h"
static placeData_t place = {.slong = 0.7232763200, .slat = 0.7618977414, .salt = 2070.};
static almDut_t AlmDut = {0};
// set/get polar/DUT1 data
bool setDUT(almDut_t *D){
if(!D){
WARNX("setDUT(): no args");
return false;
}
if(fabs(D->DUT1) > 1.){
WARNX("setDUT(): DUT1 too large (%g)", D->DUT1);
return false;
}
if(fabs(D->px) > 1000. || fabs(D->py) > 1000.){
WARNX("setDUT(): bad polar coordinates (%g, %g)", D->px, D->py);
return false;
}
AlmDut = *D;
return true;
}
void getDUT(almDut_t *D){
if(!D) return;
*D = AlmDut;
}
/**
* @brief setPlaceData - correct place data to given values
* @param longitude - degrees, (-180, 180], minus to west
* @param latitude - degrees, [-90, 90], minus to south
* @param altitude - meters
* @return false if some of data wrong
*/
bool setPlaceData(double longitude, double latitude, double altitude){
if(longitude <= -180. || longitude > 180.){
WARNX("setPlaceData(): bad longitude (%g)", longitude);
return false;
}
if(latitude < -90. || latitude > 90.){
WARNX("setPlaceData(): bad latitude (%g)", latitude);
return false;
}
if(altitude < -500. || altitude > 9000.){
WARNX("setPlaceData(): bad altitude (%g)", altitude);
return false;
}
place.salt = altitude;
place.slat = latitude;
place.slong = longitude;
return true;
}
void getPlaceData(placeData_t *pd){
if(!pd) return;
*pd = place;
}
/**
* convert RA/DEC to string in forman RA: HH:MM:SS.SS, DEC: DD:MM:SS.S
*/
char *radec2str(double ra, double dec, char buf[RADEC_STR_MAXLEN]){
char sign = '+';
if(dec < 0){
sign = '-';
dec = -dec;
}
int h = (int)ra;
ra -= h; ra *= 60.;
int m = (int)ra;
ra -= m; ra *= 60.;
int d = (int) dec;
dec -= d; dec *= 60.;
int dm = (int)dec;
dec -= dm; dec *= 60.;
snprintf(buf, RADEC_STR_MAXLEN, "%d:%d:%.2f %c%d:%d:%.1f", h,m,ra, sign,d,dm,dec);
buf[RADEC_STR_MAXLEN-1] = 0;
return buf;
}
// normalize RA/DEC to [0..24) for RA and [-90, 90] for DEC
void norm_RA(double *ra){
if(!ra) return;
if(*ra >= 0. && *ra < 24.) return;
double r = fmod(*ra, 24.);
if(r < 0.) r += 24.;
*ra = r;
}
void norm_RADEC(double *ra, double *dec){
if(!ra || !dec) return;
if(*dec >= -90. && *dec <= 90.){ // need only check RA
norm_RA(ra);
return;
}
// 1: convert to (-180..+180)
norm_angle180(dec);
// 2: fix dec & ra together
if(*dec > 90.) *dec = 180. - *dec;
else *dec = -180. - *dec;
*ra += 12.;
norm_RA(ra);
}
// normalize angle to (-180, 180]
void norm_angle180(double *a){
if(!a) return;
double d = fmod(*a + 180.0, 360.0);
if(d < 0.) d += 360.0;
else d -= 180;
*a = d;
}
/**
* @brief hor2eq - convert horizontal coordinates to polar
* @param h (i) - horizontal coordinates
* @param pc (o) - polar coordinates
* @param sidTime - sidereal time
*/
void hor2eq(horizCrds_t *h, polarCrds_t *pc, double sidTime){
if(!h || !pc) return;
eraAe2hd(h->az, ERFA_DPI/2. - h->zd, place.slat, &pc->ha, &pc->dec); // A,H -> HA,DEC; phi - site latitude
pc->ra = sidTime - pc->ha;
pc->eo = 0.;
}
/**
* @brief eq2horH - convert polar coordinates to horizontal
* @param pc (i) - polar coordinates (only HA used)
* @param h (o) - horizontal coordinates
* @param sidTime - sidereal time
*/
void eq2horH(polarCrds_t *pc, horizCrds_t *h){
if(!h || !pc) return;
double alt;
eraHd2ae(pc->ha, pc->dec, place.slat, &h->az, &alt);
h->zd = ERFA_DPI/2. - alt;
}
/**
* @brief eq2hor - convert polar coordinates to horizontal
* @param pc (i) - polar coordinates (only RA used)
* @param h (o) - horizontal coordinates
* @param sidTime - sidereal time
*/
void eq2hor(polarCrds_t *pc, horizCrds_t *h, double sidTime){
if(!h || !pc) return;
double ha = sidTime - pc->ra + pc->eo;
double alt;
eraHd2ae(ha, pc->dec, place.slat, &h->az, &alt);
h->zd = ERFA_DPI/2. - alt;
}
/**
* @brief r2sHMS - convert angle in radians into string "'HH:MM:SS.SS'"
* @param radians - angle
* @param hms (o) - string
* @param len - length of hms
*/
void r2sHMS(double radians, char *hms, int len){
char pm;
int i[4];
eraA2tf(2, radians, &pm, i);
snprintf(hms, len, "'%c%02d:%02d:%02d.%02d'", pm, i[0],i[1],i[2],i[3]);
}
/**
* @brief r2sDMS - convert angle in radians into string "'DD:MM:SS.S'"
* @param radians - angle
* @param dms (o) - string
* @param len - length of hms
*/
void r2sDMS(double radians, char *dms, int len){
char pm;
int i[4];
eraA2af(1, radians, &pm, i);
snprintf(dms, len, "'%c%02d:%02d:%02d.%d'", pm, i[0],i[1],i[2],i[3]);
}
/**
* @brief get_MJDt - calculate MJD of date from argument
* @param tval (i) - given date (or NULL for current)
* @param MJD (o) - time (or NULL just to check)
* @return true if all OK
*/
bool get_MJDt(struct timeval *tval, sMJD_t *MJD){
struct tm tms;
double tSeconds;
if(!MJD){
WARNX("get_MJDt(): no input data");
return false;
}
if(!tval){
struct timespec ts;
if(clock_gettime(CLOCK_REALTIME, &ts)){
WARN("clock_gettime()");
return false;
}
gmtime_r(&ts.tv_sec, &tms);
tSeconds = tms.tm_sec + ((double)ts.tv_nsec)/1e9;
}else{
gmtime_r(&tval->tv_sec, &tms);
tSeconds = tms.tm_sec + ((double)tval->tv_usec)/1e6;
}
int y, m, d;
y = 1900 + tms.tm_year;
m = tms.tm_mon + 1;
d = tms.tm_mday;
double utc1, utc2;
/* UTC date. */
if(eraDtf2d("UTC", y, m, d, tms.tm_hour, tms.tm_min, tSeconds, &utc1, &utc2) < 0){
WARNX("get_MJDt(): eraDtf2d() error");
return false;
}
MJD->MJD = utc1 - ERFA_DJM0 + utc2;
MJD->utc1 = utc1;
MJD->utc2 = utc2;
//DBG("UTC(m): %g, %.8f\n", utc1 - 2400000.5, utc2);
if(eraUtctai(utc1, utc2, &MJD->tai1, &MJD->tai2)){
WARNX("get_MJDt(): eraUtctai() error");
return false;
}
//DBG("TAI");
if(eraTaitt(MJD->tai1, MJD->tai2, &MJD->tt1, &MJD->tt2)){
WARNX("get_MJDt(): eraTaitt() error");
return false;
}
//DBG("TT");
return true;
}
/**
* @brief get_LST - calculate local siderial time
* @param mjd (i) - date/time for LST (utc1 & tt used)
* @param dUT1 - (UT1-UTC)
* @param slong - site longitude (radians)
* @param LST (o) - local sidereal time (radians)
* @return true if all OK
*/
bool get_LST(sMJD_t *mjd, double dUT1, double slong, double *LST){
double ut11, ut12;
sMJD_t Mjd;
if(!LST) return false;
if(!mjd){
if(!get_MJDt(NULL, &Mjd)) return false;
}else Mjd = *mjd;
if(eraUtcut1(Mjd.utc1, Mjd.utc2, dUT1, &ut11, &ut12)) return false;
double ST = eraGst06a(ut11, ut12, Mjd.tt1, Mjd.tt2);
ST += slong;
if(ST > ERFA_D2PI) ST -= ERFA_D2PI;
else if(ST < 0.) ST += ERFA_D2PI;
*LST = ST;
return 0;
}
/**
* @brief get_ObsPlace - calculate observed place (without PM etc) for given date @550nm
* @param tval (i) - time
* @param p2000 (i) - polar coordinates for J2000 (only ra/dec used), ICRS (catalog)
* @param pnow (o) - polar coordinates for given epoch (or NULL)
* @param hnow (o) - horizontal coordinates for given epoch (or NULL)
* @return true if all OK
*/
bool get_ObsPlace(struct timeval *tval, polarCrds_t *p2000, polarCrds_t *pnow, horizCrds_t *hnow){
double pr = 0.0; // RA proper motion (radians/year; Note 2)
double pd = 0.0; // Dec proper motion (radians/year)
double px = 0.0; // parallax (arcsec)
double rv = 0.0; // radial velocity (km/s, positive if receding)
sMJD_t MJD;
if(!p2000){
WARNX("get_ObsPlace(): no input coordinates");
return false;
}
if(!get_MJDt(tval, &MJD)) return false;
/* Effective wavelength (microns) */
double wl = 0.55;
/* ICRS to observed. */
double aob, zob, hob, dob, rob, eo;
double p = 1000., t = 0., h = place.salt;
weather_data_t weath;
if(get_weather_data(&weath)){
WARNX("Can't get weather - use default values");
}else{
p = 1.3332239 * weath.pressure;
t = weath.exttemp;
DBG("pressure=%.1fhPa, temperature=%.1fdegC", p, t);
}
if(eraAtco13(p2000->ra, p2000->dec,
pr, pd, px, rv,
MJD.utc1, MJD.utc2,
AlmDut.DUT1,
place.slong, place.slat, place.salt,
AlmDut.px, AlmDut.py,
p, t, h,
wl,
&aob, &zob,
&hob, &dob, &rob, &eo)) return false;
if(pnow){
pnow->eo = eo;
pnow->ha = hob;
pnow->ra = rob;
pnow->dec = dob;
}
if(hnow){
hnow->az = aob;
hnow->zd = zob;
}
return true;
}
/**
* convert geocentric coordinates (nowadays, CIRS) to mean (JD2000, ICRS)
* in, out - input and output coordinates
* @return false if failed
*/
bool JnowtoJ2000(const polarCrds_t *in, polarCrds_t *out){
bool ret = false;
DBG("appRa: %gdegr, appDecl: %gdegr", RAD2DEG(in->ra), RAD2DEG(in->dec));
#define ERFA(f, ...) do{if(f(__VA_ARGS__)){WARNX("Error in " #f); goto rtn;}}while(0)
sMJD_t MJD;
if(!get_MJDt(NULL, &MJD)) return false;
double ri = 0., di = 0., eo = 0.;
eraAtic13(in->ra, in->dec, MJD.tt1, MJD.tt2, &ri, &di, &eo);
if(out){
out->ha = 0.; out->eo = 0.;
out->ra = eraAnp(ri + eo);
out->dec = di;
DBG("JnowtoJ2000: ra=%gdeg, dec=%gdeg", RAD2DEG(out->ra), RAD2DEG(out->dec));
}
ret = true;
#undef ERFA
return ret;
}
/**
* @brief J2000toJnow - convert ra/dec between epochs
* @param in - J2000 (degrees)
* @param out - Jnow (degrees)
* @return false if failed
*/
bool J2000toJnow(const polarCrds_t *in, polarCrds_t *out){
DBG("J200RA: %gdegr, J200Dec: %gdegr", RAD2DEG(in->ra), RAD2DEG(in->dec));
sMJD_t MJD;
if(!in) return false;
if(!get_MJDt(NULL, &MJD)) return false;
// these values could be changed (e.g. by user's input)
double pr = 0.0; // RA proper motion (radians/year)
double pd = 0.0; // Dec proper motion (radians/year)
double px = 0.0; // parallax (arcsec)
double rv = 0.0; // radial velocity (km/s, positive if receding)
double ri, di, eo;
eraAtci13(in->ra, in->dec, pr, pd, px, rv, MJD.tt1, MJD.tt2, &ri, &di, &eo);
if(out){
out->ra = eraAnp(ri - eo);
out->dec = di;
}
return true;
}
#if 0
typedef enum {
WEATHER_GOOD = 0, // may start observations
WEATHER_BAD = 1, // cannot start but can continue if want
WEATHER_TERRIBLE = 2, // close & park: wind, precipitation, humidity etc.
WEATHER_PROHIBITED = 3, // force closing & parking; power off equipment, ready to power off computer
} weather_condition_t;
typedef struct {
weather_condition_t weather; // conditions: field "WEATHER"
float windmax; // maximal wind for last hour, m/s: "WINDMAX1"
float wind; // current wind speed, m/s: "WIND"
float clouds; // sky "quality" (>2500 - OK): "CLOUDS"
float exttemp; // external temperature, degC: "EXTTEMP"
float pressure; // atm. pressure, mmHg: "PRESSURE"
float humidity; // humidity, percents: "HUMIDITY"
int rain; // ==1 when rainy: "PRECIP"
int forceoff; // force power off (AC power lost or lightning)
time_t last_update; // value of "TMEAS"
} weather_data_t;
int get_weather_data(weather_data_t *data);
#endif

View File

@@ -0,0 +1,89 @@
/*
* This file is part of the mountdaemon_10micron project.
* Copyright 2026 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <erfam.h>
#include <weather_data.h>
#define RADEC_STR_MAXLEN 72
#define RAD2DEG(angle) (angle * ERFA_DR2D)
#define DEG2RAD(angle) (angle * ERFA_DD2R)
#define RAD2HRS(angle) (angle * 24. / ERFA_DPI)
#define HRS2RAD(hour) (hour * ERFA_DPI / 24.)
typedef struct{
double utc1; double utc2; // UTC JD, commonly used MJD = utc1+utc2-2400000.5
double MJD;
double tai1; double tai2; // TAI JD
double tt1; double tt2; // TT JD
} sMJD_t;
// polar coordinates & equation of origins (all in radians)
typedef struct{
double ha; // hour angle
double dec; // declination
double ra; // right ascension
double eo; // equation of origins
} polarCrds_t;
// horizontal coordinates (all in radians)
typedef struct{
double az; // azimuth, 0 @ south, positive clockwise
double zd; // zenith distance
} horizCrds_t;
// observational place coordinates and altitude; all coordinates are in radians!
typedef struct{
double slong; // longitude, radians
double slat; // lattitude, radians
double salt; // altitude, m
} placeData_t;
// DUT/polar almanach data
// TODO: add function to read this data from almanach
typedef struct{
double DUT1; // UT1-UTC, sec
double px; // polar coordinates, arcsec
double py;
} almDut_t;
char *radec2str(double ra, double dec, char buf[RADEC_STR_MAXLEN]);
void norm_RA(double *ra);
void norm_RADEC(double *ra, double *dec);
void norm_angle180(double *a);
void hor2eq(horizCrds_t *h, polarCrds_t *pc, double sidTime);
void eq2horH(polarCrds_t *pc, horizCrds_t *h);
void eq2hor(polarCrds_t *pc, horizCrds_t *h, double sidTime);
void r2sHMS(double radians, char *hms, int len);
void r2sDMS(double radians, char *hms, int len);
void hor2eq(horizCrds_t *h, polarCrds_t *pc, double sidTime);
void eq2horH(polarCrds_t *pc, horizCrds_t *h);
void eq2hor(polarCrds_t *pc, horizCrds_t *h, double sidTime);
bool get_MJDt(struct timeval *tval, sMJD_t *MJD);
bool get_LST(sMJD_t *mjd, double dUT1, double slong, double *LST);
bool get_ObsPlace(struct timeval *tval, polarCrds_t *p2000, polarCrds_t *pnow, horizCrds_t *hnow);
bool setDUT(almDut_t *D);
void getDUT(almDut_t *D);
bool setPlaceData(double longitude, double latitude, double altitude);
void getPlaceData(placeData_t *pd);

View File

@@ -0,0 +1,140 @@
/*
* This file is part of the mountdaemon_10micron project.
* Copyright 2026 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
#include <string.h>
#include <usefull_macros.h>
#include "args.h"
#include "server.h"
#define DEFAULT_COMDEV "/dev/ttyUSB0"
// TCP socket port
#define DEFAULT_PORT ":10000"
#define DEFAULT_CMDNODE "localhost:10001"
// default PID filename:
#define DEFAULT_PIDFILE "/tmp/mountdaemon_10micron.pid"
// default file with headers
#define DEFAULT_FITSHDR "/tmp/10micron.fitsheader"
// baudrate - 115200
#define DEFAULT_SERSPEED 115200
// serial polling timeout - 100ms
#define DEFAULT_SERTMOUT 100000
// mount name
#define DEFAULT_MOUNT_NAME "10Micron GM4000HPS"
// non-config file options
static int help = 0;
static char *conffile = NULL;
// default command line options
static parameters_t G = {0};
// default config options
static parameters_t Conf = {0};
#define STR_HELPER(x) #x
#define STR(x) STR_HELPER(x)
#define OPTIONS(Stor) \
{"device", NEED_ARG, NULL, 'd', arg_string, APTR(&Stor.device), "serial device name"}, \
{"emulation",NO_ARGS, NULL, 'e', arg_int, APTR(&Stor.emulation), "run in emulation mode"}, \
{"logfile", NEED_ARG, NULL, 'l', arg_string, APTR(&Stor.logfile), "file to save logs"}, \
{"hdrfile", NEED_ARG, NULL, 'o', arg_string, APTR(&Stor.crdsfile), "file to save FITS-header with coordinates and time (default: " DEFAULT_FITSHDR ")"}, \
{"pidfile", NEED_ARG, NULL, 0, arg_string, APTR(&Stor.pidfile), "pidfile (default: " DEFAULT_PIDFILE ")"}, \
{"port", NEED_ARG, NULL, 'p', arg_string, APTR(&Stor.port), "port for stellaruim's connect (default: " DEFAULT_PORT ")"}, \
{"cmdport", NEED_ARG, NULL, 'P', arg_string, APTR(&Stor.cmdnode), "port or UNIX-socket path to connect for command console (default: " DEFAULT_CMDNODE ")"}, \
{"sleept", NEED_ARG, NULL, 't', arg_int, APTR(&Stor.sleept), "time of servers' sleeping in main cycle, us (default: " STR(DEFAULT_SLEEP_T) " us)"}, \
{"isunix", NO_ARGS, NULL, 'U', arg_int, APTR(&Stor.isunix), "use UNIX-socket for cmdport"}, \
{"sertmout",NEED_ARG, NULL, 'T', arg_int, APTR(&Stor.sertmout), "serial timeout, us (default: " STR(DEFAULT_SERTMOUT) " us)"}, \
{"serspeed",NEED_ARG, NULL, 'S', arg_int, APTR(&Stor.serspeed), "serial speed (default: " STR(DEFAULT_SERSPEED) ")"}, \
{"maxclients",NEED_ARG, NULL, 0, arg_int, APTR(&Stor.maxclients),"max amount of clients connected to one socket (default: " STR(DEFAULT_MAXCLIENTS) ")"}, \
{"mountname",NEED_ARG, NULL, 0, arg_string, APTR(&Stor.mountname), "mount name (default: " DEFAULT_MOUNT_NAME ")"}, \
{"verbose", NO_ARGS, NULL, 'v', arg_none, APTR(&Stor.verbose), "verbose level (each -v increases it)"}, \
static sl_option_t cmdlnopts[] = {
{"help", NO_ARGS, NULL, 'h', arg_int, APTR(&help), "show this help"},
{"config", NEED_ARG, NULL, 'c', arg_string, APTR(&conffile), "configuration file (command line options are in advantage)"},
OPTIONS(G)
end_option
};
// --help and --conf - options that should be parsed first
static sl_option_t confopts[] = {
OPTIONS(Conf)
end_option
};
static void chkstr(char **conf, char **cmd, const char *dflt){
if(!*conf){
if(!*cmd && dflt){
DBG("Set default parameter: %s", dflt);
*cmd = strdup(dflt);
}
return;
}
if(!*cmd){
DBG("Conf-only parameter %s", *conf);
*cmd = strdup(*conf);
}
FREE(*conf); // don't forget to clear
}
static void chkint(int *conf, int *cmd, int dflt){
if(!*conf){
if(!*cmd) *cmd = dflt;
return;
}
if(!*cmd){
DBG("Conf-only parameter %d", *conf);
*cmd = *conf;
}
}
#define STRCHK(field) chkstr(&Conf.field, &G.field, NULL)
#define STRCHKD(field, def) chkstr(&Conf.field, &G.field, def)
#define INTCHK(field) chkint(&Conf.field, &G.field, 0)
#define INTCHKD(field, def) chkint(&Conf.field, &G.field, def)
parameters_t *parse_cmdline(int *argc, char ***argv){
sl_parseargs(argc, argv, cmdlnopts);
if(help) sl_showhelp(-1, cmdlnopts);
if(!conffile) return &G;
// fix for conffile
if(!sl_conf_readopts(conffile, confopts)){ // show conf help
sl_conf_showhelp(-1, confopts);
return NULL;
}
// now fix for command line and check all:
DBG("Check all args");
STRCHKD(device, DEFAULT_COMDEV);
STRCHKD(port, DEFAULT_PORT);
STRCHKD(cmdnode, DEFAULT_CMDNODE);
STRCHKD(pidfile, DEFAULT_PIDFILE);
STRCHK(logfile);
STRCHKD(crdsfile, DEFAULT_FITSHDR);
STRCHKD(mountname, DEFAULT_MOUNT_NAME);
INTCHK(emulation);
INTCHK(verbose);
INTCHKD(sleept, DEFAULT_SLEEP_T);
INTCHK(isunix);
INTCHKD(sertmout, DEFAULT_SERTMOUT);
INTCHKD(serspeed, DEFAULT_SERSPEED);
INTCHKD(maxclients, DEFAULT_MAXCLIENTS);
return &G;
}

View File

@@ -0,0 +1,38 @@
/*
* This file is part of the mountdaemon_10micron project.
* Copyright 2026 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
#pragma once
typedef struct{
char *device; // serial device name
char *port; // port to connect
char *cmdnode; // port for commands sending
char *pidfile; // name of PID file
char *logfile; // logging to this file
char *crdsfile; // file where FITS-header should be written
char *mountname; // set mount name for FITS-header
int emulation; // run in emulation mode
int verbose; // verbose level
int sleept; // server's sleeping in main cycle time
int isunix; // use UNIX-socket for command port
int sertmout; // serial timeout, us
int serspeed; // serial speed, baud
int maxclients; // max amount of clients connected to one socket
} parameters_t;
parameters_t *parse_cmdline(int *argc, char ***argv);

View File

@@ -1,12 +1,10 @@
/* /*
* geany_encoding=koi8-r * This file is part of the mountdaemon_10micron project.
* emulation.c * Copyright 2026 Edward V. Emelianov <edward.emelianoff@gmail.com>.
* *
* Copyright 2018 Edward V. Emelianov <eddy@sao.ru, edward.emelianoff@gmail.com> * 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 3 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,
@@ -15,18 +13,18 @@
* 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, see <http://www.gnu.org/licenses/>.
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*
*/ */
#include "math.h"
#include "emulation.h"
#include "usefull_macro.h"
// emulation speed over RA & DEC (0.5 degr per sec) #include <math.h>
#define RA_SPEED (0.033) #include <usefull_macros.h>
#define DECL_SPEED (0.5)
#include "angles.h"
#include "emulation.h"
// emulation speed over RA & DEC (degr per sec)
#define RA_SPEED (5.)
#define DECL_SPEED (11.)
// current coordinates // current coordinates
static double RA = 0., DECL = 0.; static double RA = 0., DECL = 0.;
@@ -35,8 +33,6 @@ static double RAtarg = 0., DECLtarg = 0.;
// coordinates @ guiding start // coordinates @ guiding start
static double RA0 = 0., DECL0 = 0.; static double RA0 = 0., DECL0 = 0.;
static double raspeed = 0.; static double raspeed = 0.;
// ==1 if pointing
static int pointing = 0;
// pointing start time // pointing start time
static double tstart = -1.; static double tstart = -1.;
@@ -44,20 +40,20 @@ static double tstart = -1.;
* send coordinates to telescope emulation * send coordinates to telescope emulation
* @param ra - right ascention (hours) * @param ra - right ascention (hours)
* @param decl - declination (degrees) * @param decl - declination (degrees)
* @return 1 if all OK
*/ */
int point_emulation(double ra, double decl){ bool point_emulation(double ra, double decl){
norm_RADEC(&ra, &decl);
DBG("(emul) Send ra=%g, decl=%g", ra, decl); DBG("(emul) Send ra=%g, decl=%g", ra, decl);
putlog("(emul) Send ra=%g, decl=%g", ra, decl); LOGMSG("(emul) Send ra=%g, decl=%g", ra, decl);
// TODO: check that Z<90!
RAtarg = ra; DECLtarg = decl; RAtarg = ra; DECLtarg = decl;
RA0 = RA; DECL0 = DECL; RA0 = RA; DECL0 = DECL;
raspeed = (RAtarg > RA) ? RA_SPEED : -RA_SPEED; raspeed = (RAtarg > RA) ? RA_SPEED : -RA_SPEED;
if(fabs(RAtarg - RA) > 12.){ // go to opposite direction if(fabs(RAtarg - RA) > 12.){ // go to opposite direction
raspeed = -raspeed; raspeed = -raspeed;
} }
tstart = dtime(); tstart = sl_dtime();
pointing = 1; return true;
return 0;
} }
static double getradiff(){ static double getradiff(){
@@ -70,20 +66,19 @@ static double getradiff(){
/** /**
* get coordinates (emulation) * get coordinates (emulation)
* @return 1 if all OK
*/ */
int get_emul_coords(double *ra, double *decl){ void get_emul_coords(double *ra, double *decl){
if(pointing){ if(tstart > 0.){
DBG("RA/DEC: targ: %g/%g, cur: %g/%g, start: %g/%g", RAtarg, DECLtarg, RA, DECL, RA0, DECL0); DBG("RA/DEC: targ: %g/%g, cur: %g/%g, start: %g/%g", RAtarg, DECLtarg, RA, DECL, RA0, DECL0);
// diff < speed? stop // diff < speed? stop
if((fabs(RAtarg - RA) < RA_SPEED && fabs(DECLtarg - DECL) < DECL_SPEED)){ if((fabs(RAtarg - RA) < RA_SPEED && fabs(DECLtarg - DECL) < DECL_SPEED)){
RA = RAtarg; RA = RAtarg;
DECL = DECLtarg; DECL = DECLtarg;
pointing = 0; // guiding tstart = -1.; // "guiding"
DBG("@ target"); DBG("@ target");
}else{ // calculate new coordinates }else{ // calculate new coordinates
double radiff = getradiff(), decldiff = fabs(DECLtarg - DECL); double radiff = getradiff(), decldiff = fabs(DECLtarg - DECL);
double tdiff = dtime() - tstart; double tdiff = sl_dtime() - tstart;
RA = RA0 + raspeed * tdiff; RA = RA0 + raspeed * tdiff;
DBG("RA=%g", RA); DBG("RA=%g", RA);
if(getradiff() > radiff) RA = RAtarg; if(getradiff() > radiff) RA = RAtarg;
@@ -99,5 +94,5 @@ int get_emul_coords(double *ra, double *decl){
} }
if(ra) *ra = RA; if(ra) *ra = RA;
if(decl) *decl = DECL; if(decl) *decl = DECL;
return 1;
} }

View File

@@ -1,12 +1,10 @@
/* /*
* geany_encoding=koi8-r * This file is part of the mountdaemon_10micron project.
* emulation.h * Copyright 2026 Edward V. Emelianov <edward.emelianoff@gmail.com>.
* *
* Copyright 2018 Edward V. Emelianov <eddy@sao.ru, edward.emelianoff@gmail.com> * 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 3 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,
@@ -15,16 +13,12 @@
* 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, see <http://www.gnu.org/licenses/>.
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*
*/ */
#pragma once #pragma once
#ifndef __EMULATION_H__
#define __EMULATION_H__
int point_emulation(double ra, double decl); bool point_emulation(double ra, double decl);
int get_emul_coords(double *ra, double *decl); void get_emul_coords(double *ra, double *decl);
#endif // __EMULATION_H__

View File

@@ -1,11 +1,10 @@
/* /*
* main.c * This file is part of the Snippets project.
* Copyright 2024 Edward V. Emelianov <edward.emelianoff@gmail.com>.
* *
* Copyright 2014 Edward V. Emelianov <eddy@sao.ru, edward.emelianoff@gmail.com> * 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 3 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,
@@ -14,509 +13,106 @@
* 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, see <http://www.gnu.org/licenses/>.
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/ */
#include <arpa/inet.h> #include <fcntl.h>
#include <endian.h>
#include <math.h>
#include <netdb.h>
#include <netinet/in.h>
#include <signal.h> #include <signal.h>
#include <sys/prctl.h> #include <stdio.h>
#include <sys/socket.h> #include <string.h>
#include <sys/types.h> #include <sys/wait.h> // wait
#include <sys/wait.h> #include <sys/prctl.h> //prctl
#include <time.h> #include <usefull_macros.h>
#include "emulation.h" #include "args.h"
#include "libsofa.h" #include "server.h"
#include "main.h" #include "mount.h"
#include "socket.h"
#include "telescope.h"
// daemon.c static pid_t childpid = -1; // PID of child process
extern void check4running(char *self, char *pidfilename, void (*iffound)(pid_t pid)); static const char *pidfile = NULL;
// Max amount of connections
#define BACKLOG (10)
#define BUFLEN (1024)
// pause for incoming message waiting (out coordinates sent after that timeout)
#define SOCK_TMOUT (1)
static pid_t childpid = 1; // PID of child process
volatile int global_quit = 0;
// quit by signal
void signals(int sig){ void signals(int sig){
signal(sig, SIG_IGN); if(childpid){ // single or parent process
if(childpid){ // parent process if(pidfile) unlink(pidfile); // remove pidfile
restore_tty(); // restore all parameters if(childpid > 0) kill(childpid, SIGTERM);
unlink(GP->pidfile); // and remove pidfile
weatherserver_disconnect();
}
DBG("Get signal %d, quit.\n", sig);
global_quit = 1;
if(childpid) putlog("PID %d exit with status %d after child's %d death", getpid(), sig, childpid);
else WARNX("Child %d died with %d", getpid(), sig);
sleep(1);
exit(sig);
}
// search a first word after needle without spaces
char* stringscan(char *str, char *needle){
char *a, *e;
char *end = str + strlen(str);
a = strstr(str, needle);
if(!a) return NULL;
a += strlen(needle);
while (a < end && (*a == ' ' || *a == '\r' || *a == '\t')) a++;
if(a >= end) return NULL;
e = strchr(a, ' ');
if(e) *e = 0;
return a;
}
/**
* Send data to user
* @param data - data to send
* @param dlen - data length
* @param sockfd - socket fd for sending data
* @return 0 if failed
*/
int send_data(uint8_t *data, size_t dlen, int sockfd){
size_t sent = write(sockfd, data, dlen);
if(sent != dlen){
WARN("write()");
return 0;
} }
return 1; if(sig){
} signal(sig, SIG_IGN);
DBG("Get signal %d, quit.\n", sig);
//read: 0x14 0x0 0x0 0x0 0x5b 0x5a 0x2e 0xc6 0x8c 0x23 0x5 0x0 0x23 0x9 0xe5 0xaf 0x23 0x2e 0x34 0xed
// command: goto 16h29 24.45 -26d25 55.62
/*
LITTLE-ENDIAN!!!
from client:
LENGTH (2 bytes, integer): length of the message
TYPE (2 bytes, integer): 0
TIME (8 bytes, integer): current time on the server computer in microseconds
since 1970.01.01 UT. Currently unused.
RA (4 bytes, unsigned integer): right ascension of the telescope (J2000)
a value of 0x100000000 = 0x0 means 24h=0h,
a value of 0x80000000 means 12h
DEC (4 bytes, signed integer): declination of the telescope (J2000)
a value of -0x40000000 means -90degrees,
a value of 0x0 means 0degrees,
a value of 0x40000000 means 90degrees
to client:
LENGTH (2 bytes, integer): length of the message
TYPE (2 bytes, integer): 0
TIME (8 bytes, integer): current time on the server computer in microseconds
since 1970.01.01 UT. Currently unused.
RA (4 bytes, unsigned integer): right ascension of the telescope (J2000)
a value of 0x100000000 = 0x0 means 24h=0h,
a value of 0x80000000 means 12h
DEC (4 bytes, signed integer): declination of the telescope (J2000)
a value of -0x40000000 means -90degrees,
a value of 0x0 means 0degrees,
a value of 0x40000000 means 90degrees
STATUS (4 bytes, signed integer): status of the telescope, currently unused.
status=0 means ok, status<0 means some error
*/
#define DEG2DEC(degr) ((int32_t)(degr / 90. * ((double)0x40000000)))
#define HRS2RA(hrs) ((uint32_t)(hrs / 12. * ((double)0x80000000)))
#define DEC2DEG(i32) (((double)i32)*90./((double)0x40000000))
#define RA2HRS(u32) (((double)u32)*12. /((double)0x80000000))
typedef struct __attribute__((__packed__)){
uint16_t len;
uint16_t type;
uint64_t time;
uint32_t ra;
int32_t dec;
} indata;
typedef struct __attribute__((__packed__)){
uint16_t len;
uint16_t type;
uint64_t time;
uint32_t ra;
int32_t dec;
int32_t status;
} outdata;
/**
* convert RA/DEC to string in forman RA: HH:MM:SS.SS, DEC: DD:MM:SS.S
*/
char *radec2str(double ra, double dec){
static char buf[1024];
char sign = '+';
if(dec < 0){
sign = '-';
dec = -dec;
} }
if(childpid > 0){ // parent process
int h = (int)ra; LOGERR("PID %d exit with status %d", getpid(), sig);
ra -= h; ra *= 60.; }else{
int m = (int)ra; LOGWARN("Child %d died with %d", getpid(), sig);
ra -= m; ra *= 60.; server_stop();
int d = (int) dec;
dec -= d; dec *= 60.;
int dm = (int)dec;
dec -= dm; dec *= 60.;
snprintf(buf, 1024, "%d:%d:%.2f %c%d:%d:%.1f", h,m,ra, sign,d,dm,dec);
return buf;
}
/**
* send input RA/Decl (j2000!) coordinates to tel
* ra in hours (0..24), decl in degrees (-90..90)
* @return 1 if all OK
*/
int setCoords(double ra, double dec){
char *radec = radec2str(ra, dec);
DBG("Set RA/Decl to %s", radec);
putlog("Try to set RA/Decl to %s", radec);
int (*pointfunction)(double, double) = point_telescope;
if(GP->emulation) pointfunction = point_emulation;
return pointfunction(ra, dec);
}
/**
* @brief proc_data - process data received from Stellarium
* @param data - raw data
* @param len - its length
* @return 1 if all OK
*/
int proc_data(uint8_t *data, ssize_t len){
FNAME();
if(len != sizeof(indata)){
WARNX("Bad data size: got %zd instead of %zd!", len, sizeof(indata));
return 0;
} }
indata *dat = (indata*)data; DBG("EXIT");
uint16_t L, T;
//uint64_t tim;
uint32_t ra;
int32_t dec;
#if __BYTE_ORDER__ != __ORDER_LITTLE_ENDIAN__
L = le16toh(dat->len); T = le16toh(dat->type);
//tim = le64toh(dat->time);
ra = le32toh(dat->ra);
dec = (int32_t)le32toh((uint32_t)dat->dec);
#else
L = dat->len; T = dat->type;
//tim = dat->time;
ra = dat->ra; dec = dat->dec;
#endif
DBG("got message with len %u & type %u", L, T);
if(L != len){
WARNX("Length of message != msg->len");
return 0;
}
if(T){
WARNX("Wrong message type");
return 0;
}
// convert RA/DEC to hours/degrees
double tagRA = RA2HRS(ra), tagDec = DEC2DEG(dec);
DBG("RA: %u (%g), DEC: %d (%g)", ra, tagRA, dec, tagDec);
putlog("RA: %u (%g degr), DEC: %d (%g degr)", ra, tagRA, dec, tagDec);
// check RA/DEC
horizCrds hnow; // without refraction
polarCrds p2000, pnow;
p2000.ra = tagRA/12. * M_PI;
p2000.dec = tagDec * ERFA_DD2R;
// now J2000 obs Jnow
if(get_ObsPlace(NULL, &p2000, NULL, &pnow, &hnow)){
WARNX("Can't convert coordinates to Jnow");
return 0;
}
/*
int i[4], j[4]; char pm, pm1;
eraA2af(2, hnow.az, &pm, i);
eraA2af(2, hnow.zd, &pm1, j);
DBG("az: %c%02d %02d %02d.%2.d, zd: %c%02d %02d %02d.%2.d",
pm, i[0],i[1],i[2],i[3],
pm1,j[0],j[1],j[2],j[3]);
eraA2af(2, M_PI_2 - hnow.zd, &pm, i);
DBG("h: %c%02d %02d %02d.%2.d", pm, i[0],i[1],i[2],i[3]);
*/
if(hnow.zd > 80.*ERFA_DD2R){
WARNX("Z > 80degr (%g), stop telescope", hnow.zd * ERFA_DR2D);
putlog("Z=%.1f > 80 - stop!", hnow.zd * ERFA_DR2D);
stop_telescope();
return 0;
}
tagRA = (pnow.ra - pnow.eo) / M_PI * 12.;
tagDec = pnow.dec / ERFA_DD2R;
if(!setCoords(tagRA, tagDec)) return 0;
return 1;
}
/**
* main socket service procedure
*/
void *handle_socket(void *sockd){
FNAME();
if(global_quit) return NULL;
outdata dout;
int sock = *(int*)sockd;
dout.len = htole16(sizeof(outdata));
dout.type = 0;
int (*getcoords)(double*, double*) = get_telescope_coords;
if(GP->emulation) getcoords = get_emul_coords;
while(!global_quit){
// get coordinates
double RA = 0., Decl = 0.;
if((dout.status = getcoords(&RA, &Decl)) < 0){
WARNX("Error: can't get coordinates");
sleep(1);
continue;
}
//DBG("got : %g/%g", RA, Decl);
dout.ra = htole32(HRS2RA(RA));
dout.dec = (int32_t)htole32(DEG2DEC(Decl));
if(!send_data((uint8_t*)&dout, sizeof(outdata), sock)) break;
//DBG("sent ra = %g, dec = %g", RA2HRS(dout.ra), DEC2DEG(dout.dec));
fd_set readfds;
struct timeval timeout;
FD_ZERO(&readfds);
FD_SET(sock, &readfds);
timeout.tv_sec = SOCK_TMOUT; // wait not more than SOCK_TMOUT second
timeout.tv_usec = 0;
int sel = select(sock + 1 , &readfds , NULL , NULL , &timeout);
if(sel < 0){
if(errno != EINTR)
WARN("select()");
continue;
}
if(!(FD_ISSET(sock, &readfds))) continue;
// fill incoming buffer
uint8_t buff[BUFLEN+1];
ssize_t rd = read(sock, buff, BUFLEN);
buff[rd] = 0;
DBG("read %zd (%s)", rd, buff);
if(rd <= 0){ // error or disconnect
DBG("Nothing to read from fd %d (ret: %zd)", sock, rd);
break;
}
/**************************************
* DO SOMETHING WITH DATA *
**************************************/
if(!proc_data(buff, rd)) dout.status = -1;
else dout.status = 0;
}
close(sock);
return NULL;
}
// thread writing FITS-header file
static void *hdrthread(_U_ void *buf){
// write FITS-header at most once per second
while(!global_quit){
wrhdr();
usleep(100000); // give a chance to write/read for others
}
return NULL;
}
/**
* @brief opensocket - open socket to port `port`
* @return socket fd or <0 if failed
*/
static int opensocket(char *port){
if(!port) return -1;
int reuseaddr = 1;
int sock;
struct addrinfo hints, *res, *p;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
DBG("try to open port %s", port);
if(getaddrinfo(NULL, port, &hints, &res) != 0){
WARN("getaddrinfo()");
return 0;
}
/*
struct sockaddr_in *ia = (struct sockaddr_in*)res->ai_addr;
char str[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &(ia->sin_addr), str, INET_ADDRSTRLEN);
*/
// loop through all the results and bind to the first we can
for(p = res; p != NULL; p = p->ai_next){
if((sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1){
WARN("socket()");
continue;
}
if(setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, sizeof(int)) == -1){
WARN("setsockopt()");
close(sock);
continue;
}
if(bind(sock, p->ai_addr, p->ai_addrlen) == -1){
WARN("bind()");
close(sock);
continue;
}
break; // if we get here, we must have connected successfully
}
freeaddrinfo(res);
// Listen
if(listen(sock, BACKLOG) == -1){
WARN("listen");
putlog("listen() error");
}
DBG("listen at %s", port);
putlog("listen at %s", port);
return sock;
}
/**
* @brief waitconn
* @param sock - socket fd to accept()
* @param connthread - thread which to run when connection accepted (it's parameter - socket fd)
*/
static void waitconn(int sock, void *(*connthread)(void*)){
// Main loop
while(!global_quit){
socklen_t size = sizeof(struct sockaddr_in);
struct sockaddr_in myaddr;
int newsock;
newsock = accept(sock, (struct sockaddr*)&myaddr, &size);
if(newsock <= 0){
WARN("accept()");
sleep(1);
continue;
}
struct sockaddr_in peer;
socklen_t peer_len = sizeof(peer);
if(getpeername(newsock, (struct sockaddr*)&peer, &peer_len) == -1){
WARN("getpeername()");
close(newsock);
continue;
}
int sockport = -1;
if(getsockname(newsock, (struct sockaddr*)&peer, &peer_len) == 0){
sockport = ntohs(peer.sin_port);
}
char *peerIP = inet_ntoa(peer.sin_addr);
putlog("Got connection from %s @ %d", peerIP, sockport);
DBG("Peer's IP address is: %s (@port %d)\n", peerIP, sockport);
/*if(strcmp(peerIP, ACCEPT_IP) && strcmp(peerIP, "127.0.0.1")){
WARNX("Wrong IP");
close(newsock);
continue;
}*/
pthread_t rthrd;
if(pthread_create(&rthrd, NULL, connthread, (void*)&newsock)){
putlog("Error creating listen thread");
ERR(_("Can't create socket thread"));
}else{
DBG("Thread created, detouch");
pthread_detach(rthrd); // don't care about thread state
}
}
close(sock);
}
// thread working with terminal
static void *termthread(_U_ void *buf){
int sock = opensocket(GP->dbgport);
if(sock < 0){
putlog("Can't open debugging socket @ port %s", GP->dbgport);
ERRX("Can't open debug socket");
}
waitconn(sock, term_thread);
return NULL;
}
static inline void main_proc(){
pthread_t hthrd, termthrd;
// connect to telescope
if(!GP->emulation){
if(!connect_telescope(GP->device, GP->crdsfile)){
ERRX(_("Can't connect to telescope device"));
}
if(pthread_create(&hthrd, NULL, hdrthread, NULL))
ERR(_("Can't create writing thread"));
if(pthread_create(&termthrd, NULL, termthread, NULL))
ERR(_("Can't create terminal thread"));
}
// connect to weather daemon
if(!weatherserver_connect()){
DBG("Can't connect to weather server, will try later");
}
// open socket
int sock = opensocket(GP->port);
if(sock < 0){
putlog("Can't open socket @ port %s", GP->port);
ERRX("Can't open stellarium socket");
}
waitconn(sock, handle_socket);
usleep(10000);
pthread_cancel(hthrd); // cancel reading thread
pthread_cancel(termthrd);
pthread_join(hthrd, NULL);
pthread_join(termthrd, NULL);
} }
int main(int argc, char **argv){ int main(int argc, char **argv){
char *self = strdup(argv[0]); sl_init();
GP = parse_args(argc, argv); parameters_t *G = parse_cmdline(&argc, &argv);
initial_setup(); if(!G) return 1;
sl_loglevel_e lvl = G->verbose + LOGLEVEL_ERR;
signal(SIGTERM, signals); // kill (-15) - quit if(lvl >= LOGLEVEL_AMOUNT) lvl = LOGLEVEL_AMOUNT - 1;
signal(SIGKILL, signals); // kill (-9) - quit DBG("verb: %d, level: %d", G->verbose, lvl);
signal(SIGHUP, SIG_IGN); // hup - ignore
signal(SIGINT, signals); // ctrl+C - quit
signal(SIGQUIT, signals); // ctrl+\ - quit
signal(SIGTSTP, SIG_IGN); // ignore ctrl+Z
int fd; int fd;
if((fd = open(GP->crdsfile, O_WRONLY | O_TRUNC | O_CREAT, 0644)) < 0) // test FITS-header file for writing if((fd = open(G->crdsfile, O_WRONLY | O_TRUNC | O_CREAT, 0644)) < 0) // test FITS-header file for writing
ERR(_("Can't open %s for writing"), GP->crdsfile); ERR(_("Can't open %s for writing"), G->crdsfile);
close(fd); close(fd);
if(G->sleept < 1) ERRX("Sleeping time sould be positive value");
printf("Daemonize\n"); if(!server_setsleept(G->sleept)) ERRX("Can't set sleep time to %d", G->sleept);
#ifndef EBUG // daemonize only in release mode if(G->emulation) set_emulation_mode();
if(daemon(1, 0)){ else if(!mount_set_dev(G->device, G->serspeed, G->sertmout))
putlog("Err: daemon()"); ERRX("Can't open device %s @ %d", G->device, G->serspeed);
ERR("daemon()"); if(!mount_set_name(G->mountname))
} ERRX("Can't set mount name to %s", G->mountname);
#endif // EBUG signal(SIGTERM, signals);
check4running(self, GP->pidfile, NULL); signal(SIGINT, signals);
if(GP->logfile) openlogfile(GP->logfile); signal(SIGQUIT, signals);
putlog("Starting, master PID=%d", getpid()); signal(SIGTSTP, SIG_IGN);
signal(SIGHUP, signals);
sl_check4running((char*)__progname, G->pidfile);
if(G->logfile) OPENLOG(G->logfile, lvl, 1);
DBG("Started");
LOGMSG("Started, master PID=%d", getpid());
#ifndef EBUG #ifndef EBUG
while(1){ time_t lastd = 0;
while(1){ // guard for dead processes
childpid = fork(); childpid = fork();
if(childpid < 0){ if(childpid < 0){
putlog("fork() error"); LOGERR("fork() returns error");
ERR("ERROR on fork"); sleep(5);
continue;
} }
if(childpid){ if(childpid){
WARNX(_("Created child with PID %d\n"), childpid);
DBG("Created child with PID %d\n", childpid); DBG("Created child with PID %d\n", childpid);
wait(NULL); wait(NULL);
WARNX(_("Child %d died\n"), childpid); time_t t = time(NULL);
DBG("Child %d died\n", childpid); if(t - lastd > 600){ // at least 10 minutes of work
LOGERR("Child %d died\n", childpid);
}
lastd = t;
WARNX("Child %d died\n", childpid);
sleep(1);
}else{ }else{
prctl(PR_SET_PDEATHSIG, SIGTERM); // send SIGTERM to child when parent dies prctl(PR_SET_PDEATHSIG, SIGTERM); // send SIGTERM to child when parent dies
main_proc(); break; // go out to normal functional
return 0;
} }
} }
#else
main_proc();
#endif #endif
server_sock_t sockt = {
return 0; .cmd_isunix = G->isunix,
.cmdnode = G->cmdnode,
.stellport = G->port,
.maxclients = G->maxclients,
};
if(!server_check(&sockt)){
LOGERR("Can't run servers");
ERRX("Can't run servers");
}
DBG("Run server");
server_run();
DBG("Server died");
return 1;
} }

View File

@@ -0,0 +1,322 @@
/*
* This file is part of the mountdaemon_10micron project.
* Copyright 2026 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
#include <pthread.h>
#include <stdatomic.h>
#include <stdint.h>
#include <string.h>
#include <usefull_macros.h>
#include "emulation.h"
#include "mount.h"
#define MNAME_LEN 31
static bool isemulated = false; // ==true for emulation mode
static char mount_name[MNAME_LEN+3] = "'noname'";
static sl_tty_t *mount_dev = NULL;
// device mutex, blocking only in non-local functions
static pthread_mutex_t mntdev_mutex = PTHREAD_MUTEX_INITIALIZER;
// ring buffer for data incoming from serial port
static sl_ringbuffer_t *RBin = NULL;
// status
static atomic_int mountstatus = MNT_S_ERROR;
// input and current target coordinates
static polarCrds_t InpCoords = {0}, // input as user give (for epoch InpMJD)
TagCoords = {0}; // target for Jnow after command "point to input"
static horizCrds_t InpHoriz = {0};
// input MJD (Modified Julian Date: started from ERFA_DJM0==2400000.5
static double InpMJD = ERFA_DJM00; // J2000
// times of coords/mjd change
static double InpCTime = 0., TagTime = 0., InpHTime = 0., InpMTime = 0.;
// return time of modification
double mount_getInpCoords(polarCrds_t *c){
if(c) *c = InpCoords;
return InpCTime;
}
double mount_getTagCoords(polarCrds_t *c){
if(c) *c = TagCoords;
return TagTime;
}
double mount_getInpMJD(double *MJD){
if(MJD) *MJD = InpMJD;
return InpMTime;
}
double mount_getInpHor(horizCrds_t *c){
if(c) *c = InpHoriz;
return InpHTime;
}
// change input coordinates
/**
* @brief mount_setInpHA - set hour angle
* @param ha (HOURS!!)
* @return false if `ha` isn't in [0,24)
*/
bool mount_setInpHA(double ha){
if(ha < 0. || ha >= 24.) return false;
InpCoords.ha = HRS2RAD(ha);
InpCTime = sl_dtime();
return true;
}
/**
* @brief mount_setInpRA - set right ascension
* @param ra (DEGREES!)
* @return fale if `ra` isn't in [0, 360)
*/
bool mount_setInpRA(double ra){
if(ra < 0. || ra >= 360.) return false;
InpCoords.ra = DEG2RAD(ra);
InpCTime = sl_dtime();
return true;
}
/**
* @brief mount_setInpDec - set declination
* @param dec (DEGREES!)
* @return false if `dec` isn't in [-90, 90]
*/
bool mount_setInpDec(double dec){
if(dec < -90. || dec > 90.) return false;
InpCoords.dec = DEG2RAD(dec);
InpCTime = sl_dtime();
return true;
}
/**
* @brief mount_setInpA - set azimuth
* @param A (DEGREES)
* @return false if A isn't in [0, 360)
*/
bool mount_setInpA(double A){
if(A < 0. || A >= 360.) return false;
InpHoriz.az = DEG2RAD(A);
InpHTime = sl_dtime();
return true;
}
/**
* @brief mount_setInpZ - set zenith distance
* @param Z (DEGREES)
* @return false if Z isn't in [0, 90]
*/
bool mount_setInpZ(double Z){
if(Z < 0 || Z > 90) return false;
InpHoriz.zd = DEG2RAD(Z);
InpHTime = sl_dtime();
return true;
}
// without checking
bool mount_setInpMJD(double m){
InpMJD = m;
InpMTime = sl_dtime();
return true;
}
/**
* @brief mount_set_name - set mount name for FITS header
* @param name - new string with name
* @return false if failed
*/
bool mount_set_name(const char *name){
if(!name || !*name) return false;
int l = strlen(name);
if(l > MNAME_LEN) return false;
sprintf(mount_name, "'%s'", name);
return true;
}
/**
* @brief mount_set_dev - open mount device without checking that mount is alive
* @param dev - path to device
* @param speed - baudrate
* @return false if failed to open device `dev`
*/
bool mount_set_dev(char *dev, int speed, int timeout){
pthread_mutex_lock(&mntdev_mutex);
if(mount_dev) sl_tty_close(&mount_dev);
mount_dev = sl_tty_new(dev, speed, 4096);
if(mount_dev) mount_dev = sl_tty_open(mount_dev, 1);
if(!mount_dev){
pthread_mutex_unlock(&mntdev_mutex);
return false;
}
sl_tty_tmout(timeout);
if(!RBin) RBin = sl_RB_new(BUFSIZ);
else sl_RB_clearbuf(RBin);
pthread_mutex_unlock(&mntdev_mutex);
return true;
}
static const char *statuses[MNT_S_STATAMOUNT] = {
[MNT_S_TRACKING] = "'Tracking'",
[MNT_S_STOPHOM] = "'Stopped or homing'",
[MNT_S_PARKING] = "'Slewing to park'",
[MNT_S_UNPARKING] = "'Unparking'",
[MNT_S_HOMING] = "'Slewing to home'",
[MNT_S_PARKED] = "'Parked'",
[MNT_S_SLEWING] = "'Slewing or going to stop'",
[MNT_S_STOPPED] = "'Stopped'",
[MNT_S_INHIBITED] = "'Motors inhibited, T too low'",
[MNT_S_OUTLIMIT] = "'Outside tracking limit'",
[MNT_S_FOLSAT]= "'Following satellite'",
[MNT_S_DATINCOSIST]= "'Data inconsistency'",
[MNT_S_ERROR] = "'Error (disconnected?)'"
};
/**
* @brief strstatus - return string explanation of mount status
* @param status - integer status code
* @return statically allocated string with explanation
*/
const char* mount_status_str(){
int curst = atomic_load(&mountstatus);
if(curst > -1 && curst < MNT_S_STATAMOUNT) return statuses[curst];
return "'Unknown status'";
}
// return current mount status
mount_status_t mount_status(){
return (mount_status_t)atomic_load(&mountstatus);
}
/**
* @brief write_cmd - try to write command to mount
* @param cmd - string with command or NULL just to clear all incoming data
* @return false on write/read error; all read information is in RBin (even if `false` returned, you SHOULD read all available strings from it)
*/
static bool write_cmd(const char *cmd){
bool ret = true;
if(cmd){
size_t l = strlen(cmd);
if(sl_tty_write(mount_dev->comfd, cmd, l)) ret = false;
}
int got = 0;
while((got = sl_tty_read(mount_dev)) > 0){
if(sl_RB_write(RBin, (uint8_t*) mount_dev->buf, got)){
got = -1;
break;
}
}
if(got < 0) return false;
return ret;
}
// check if mount connected
static bool chkconn(){
int r = 0;
do{ // clear incoming buffer @ start
r = sl_tty_read(mount_dev);
}while(r > 0);
if(r < 0) return false;
write_cmd("#"); // clear cmd buffer
sl_RB_clearbuf(RBin);
bool w = write_cmd(":SB0#");
sl_RB_clearbuf(RBin);
return w;
}
// try to guess serial speed & set 115200
static bool guess_speed(){
if(!mount_dev) return false;
close(mount_dev->comfd);
#define SPDBUFSZ 7
const int speeds[SPDBUFSZ] = {57600, 38400, 19200, 9600, 4800, 2400, 1200};
int idx = 0;
for(; idx < SPDBUFSZ; ++idx){
mount_dev->speed = speeds[idx];
sl_tty_t *trydev = sl_tty_open(mount_dev, 1);
if(!trydev) continue;
if(chkconn()) break;
close(mount_dev->comfd);
}
if(idx == SPDBUFSZ) return false; // device not responding
close(mount_dev->comfd);
mount_dev->speed = 115200;
if(!sl_tty_open(mount_dev, 1)) return false;
#undef SPDBUFSZ
return true;
}
// connect to mount
bool mount_connect(){
if(isemulated){
atomic_store(&mountstatus, MNT_S_STOPPED);
return true;
}
if(!mount_dev) return false;
pthread_mutex_lock(&mntdev_mutex);
if(!chkconn() && !guess_speed()) return false;
bool ret = true;
if(!write_cmd(":STOP#")) ret = false; // stop tracking after poweron
sl_RB_clearbuf(RBin);
if(!write_cmd(":U2#")) ret = false; // set high precision
sl_RB_clearbuf(RBin);
if(!write_cmd(":So10#")) ret = false; // set minimum altitude to 10 degrees
sl_RB_clearbuf(RBin);
pthread_mutex_unlock(&mntdev_mutex);
if(ret) LOGMSG("Connected to %s@115200", mount_dev->portname);
else LOGERR("Can't write commands to mount");
return ret;
}
void mount_disconnect(){
if(isemulated) return;
pthread_mutex_trylock(&mntdev_mutex); // at least, try
if(mount_dev) close(mount_dev->comfd);
pthread_mutex_unlock(&mntdev_mutex);
}
// point to ra/dec over serial
static bool mount_pointto(double ra, double dec){
(void) ra; (void) dec;
;
return true;
}
/**
* send input RA/Decl (j2000!) coordinates to tel
* ra in hours (0..24), decl in degrees (-90..90)
* @return true if all OK
*/
bool mount_point(double ra, double dec){
char buf[RADEC_STR_MAXLEN];
radec2str(ra, dec, buf);
DBG("Set RA/Decl to %s", buf);
LOGMSG("Try to set RA/Decl to %s", buf);
norm_RADEC(&ra, &dec);
bool (*pointfunction)(double, double) = mount_pointto;
if(isemulated) pointfunction = point_emulation;
return pointfunction(ra, dec);
}
void set_emulation_mode(){
isemulated = true;
}
mount_status_t mount_getcoords(double *ra, double *dec){
if(!ra || !dec) return MNT_S_ERROR;
if(isemulated){
get_emul_coords(ra, dec);
DBG("Emulated coordinates: %g, %g", *ra, *dec);
}else{
; // get real coordinates
}
return mount_status();
}

View File

@@ -0,0 +1,64 @@
/*
* This file is part of the mountdaemon_10micron project.
* Copyright 2026 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "angles.h"
// mount statuses
typedef enum{
MNT_S_TRACKING = 0,
MNT_S_STOPHOM = 1,
MNT_S_PARKING = 2,
MNT_S_UNPARKING = 3,
MNT_S_HOMING = 4,
MNT_S_PARKED = 5,
MNT_S_SLEWING = 6,
MNT_S_STOPPED = 7,
MNT_S_INHIBITED = 8,
MNT_S_OUTLIMIT = 9,
MNT_S_FOLSAT = 10,
MNT_S_DATINCOSIST = 11,
MNT_S_ERROR = 12, // my status
MNT_S_STATAMOUNT = 13 // number of statuses
} mount_status_t;
void set_emulation_mode();
bool mount_setInpHA(double ha);
bool mount_setInpRA(double ra);
bool mount_setInpDec(double dec);
bool mount_setInpA(double A);
bool mount_setInpZ(double Z);
bool mount_setInpMJD(double m);
double mount_getInpCoords(polarCrds_t *c);
double mount_getTagCoords(polarCrds_t *c);
double mount_getInpMJD(double *MJD);
double mount_getInpHor(horizCrds_t *c);
bool mount_set_name(const char *name);
bool mount_set_dev(char *dev, int speed, int timeout);
const char* mount_status_str();
mount_status_t mount_status();
bool mount_connect();
void mount_disconnect();
mount_status_t mount_getcoords(double *ra, double *dec);
bool mount_point(double ra, double dec);

View File

@@ -0,0 +1 @@
-std=c23

View File

@@ -0,0 +1,7 @@
// Add predefined macros for your project here. For example:
// #define THE_ANSWER 42
#define _XOPEN_SOURCE 1234
#define _DEFAULT_SOURCE
#define _GNU_SOURCE
#define EBUG

View File

@@ -0,0 +1,220 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE QtCreatorProject>
<!-- Written by QtCreator 19.0.2, 2026-06-10T13:41:37. -->
<qtcreator>
<data>
<variable>EnvironmentId</variable>
<value type="QByteArray">{cf63021e-ef53-49b0-b03b-2f2570cdf3b6}</value>
</data>
<data>
<variable>ProjectExplorer.Project.ActiveTarget</variable>
<value type="qlonglong">0</value>
</data>
<data>
<variable>ProjectExplorer.Project.EditorSettings</variable>
<valuemap type="QVariantMap">
<value type="bool" key="EditorConfiguration.AutoDetect">true</value>
<value type="bool" key="EditorConfiguration.AutoIndent">true</value>
<value type="bool" key="EditorConfiguration.CamelCaseNavigation">true</value>
<valuemap type="QVariantMap" key="EditorConfiguration.CodeStyle.0">
<value type="QString" key="language">Cpp</value>
<valuemap type="QVariantMap" key="value">
<value type="QByteArray" key="CurrentPreferences">CppGlobal</value>
</valuemap>
</valuemap>
<valuemap type="QVariantMap" key="EditorConfiguration.CodeStyle.1">
<value type="QString" key="language">QmlJS</value>
<valuemap type="QVariantMap" key="value">
<value type="QByteArray" key="CurrentPreferences">QmlJSGlobal</value>
</valuemap>
</valuemap>
<value type="qlonglong" key="EditorConfiguration.CodeStyle.Count">2</value>
<value type="QByteArray" key="EditorConfiguration.Codec">KOI8-R</value>
<value type="bool" key="EditorConfiguration.ConstrainTooltips">false</value>
<value type="int" key="EditorConfiguration.IndentSize">4</value>
<value type="bool" key="EditorConfiguration.KeyboardTooltips">false</value>
<value type="int" key="EditorConfiguration.LineEndingBehavior">0</value>
<value type="int" key="EditorConfiguration.MarginColumn">80</value>
<value type="bool" key="EditorConfiguration.MouseHiding">true</value>
<value type="bool" key="EditorConfiguration.MouseNavigation">true</value>
<value type="int" key="EditorConfiguration.PaddingMode">1</value>
<value type="int" key="EditorConfiguration.PreferAfterWhitespaceComments">0</value>
<value type="bool" key="EditorConfiguration.PreferSingleLineComments">false</value>
<value type="bool" key="EditorConfiguration.ScrollWheelZooming">false</value>
<value type="bool" key="EditorConfiguration.ShowMargin">false</value>
<value type="int" key="EditorConfiguration.SmartBackspaceBehavior">1</value>
<value type="bool" key="EditorConfiguration.SmartSelectionChanging">true</value>
<value type="bool" key="EditorConfiguration.SpacesForTabs">true</value>
<value type="int" key="EditorConfiguration.TabKeyBehavior">0</value>
<value type="int" key="EditorConfiguration.TabSize">8</value>
<value type="bool" key="EditorConfiguration.UseGlobal">true</value>
<value type="bool" key="EditorConfiguration.UseIndenter">false</value>
<value type="int" key="EditorConfiguration.Utf8BomBehavior">1</value>
<value type="bool" key="EditorConfiguration.addFinalNewLine">true</value>
<value type="bool" key="EditorConfiguration.cleanIndentation">true</value>
<value type="bool" key="EditorConfiguration.cleanWhitespace">true</value>
<value type="QString" key="EditorConfiguration.ignoreFileTypes">*.md, *.MD, Makefile</value>
<value type="bool" key="EditorConfiguration.inEntireDocument">true</value>
<value type="bool" key="EditorConfiguration.skipTrailingWhitespace">true</value>
<value type="bool" key="EditorConfiguration.tintMarginArea">true</value>
</valuemap>
</data>
<data>
<variable>ProjectExplorer.Project.PluginSettings</variable>
<valuemap type="QVariantMap">
<valuemap type="QVariantMap" key="AutoTest.ActiveFrameworks">
<value type="bool" key="AutoTest.Framework.Boost">true</value>
<value type="bool" key="AutoTest.Framework.CTest">false</value>
<value type="bool" key="AutoTest.Framework.Catch">true</value>
<value type="bool" key="AutoTest.Framework.GTest">true</value>
<value type="bool" key="AutoTest.Framework.QtQuickTest">true</value>
<value type="bool" key="AutoTest.Framework.QtTest">true</value>
</valuemap>
<value type="bool" key="AutoTest.ApplyFilter">false</value>
<valuemap type="QVariantMap" key="AutoTest.CheckStates"/>
<valuelist type="QVariantList" key="AutoTest.PathFilters"/>
<value type="int" key="AutoTest.RunAfterBuild">0</value>
<value type="bool" key="AutoTest.UseGlobal">true</value>
<valuemap type="QVariantMap" key="ClangTools">
<value type="bool" key="ClangTools.AnalyzeOpenFiles">true</value>
<value type="bool" key="ClangTools.BuildBeforeAnalysis">true</value>
<value type="QString" key="ClangTools.DiagnosticConfig">Builtin.DefaultTidyAndClazy</value>
<value type="int" key="ClangTools.ParallelJobs">4</value>
<value type="bool" key="ClangTools.PreferConfigFile">true</value>
<valuelist type="QVariantList" key="ClangTools.SelectedDirs"/>
<valuelist type="QVariantList" key="ClangTools.SelectedFiles"/>
<valuelist type="QVariantList" key="ClangTools.SuppressedDiagnostics"/>
<value type="bool" key="ClangTools.UseGlobalSettings">true</value>
</valuemap>
<value type="int" key="RcSync">0</value>
</valuemap>
</data>
<data>
<variable>ProjectExplorer.Project.Target.0</variable>
<valuemap type="QVariantMap">
<value type="QString" key="DeviceType">Desktop</value>
<value type="bool" key="HasPerBcDcs">true</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Desktop</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName">Desktop</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">{91347f2c-5221-46a7-80b1-0a054ca02f79}</value>
<value type="qlonglong" key="ProjectExplorer.Target.ActiveBuildConfiguration">0</value>
<value type="qlonglong" key="ProjectExplorer.Target.ActiveDeployConfiguration">0</value>
<value type="qlonglong" key="ProjectExplorer.Target.ActiveRunConfiguration">0</value>
<valuemap type="QVariantMap" key="ProjectExplorer.Target.BuildConfiguration.0">
<value type="QString" key="ProjectExplorer.BuildConfiguration.BuildDirectory">/home/eddy/Docs/SAO/10micron/C-sources/mountdaemon_10micron</value>
<valuemap type="QVariantMap" key="ProjectExplorer.BuildConfiguration.BuildStepList.0">
<valuemap type="QVariantMap" key="ProjectExplorer.BuildStepList.Step.0">
<valuelist type="QVariantList" key="GenericProjectManager.GenericMakeStep.BuildTargets">
<value type="QString">all</value>
</valuelist>
<value type="bool" key="ProjectExplorer.BuildStep.Enabled">true</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">GenericProjectManager.GenericMakeStep</value>
</valuemap>
<value type="qlonglong" key="ProjectExplorer.BuildStepList.StepsCount">1</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Build</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName">Build</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">ProjectExplorer.BuildSteps.Build</value>
</valuemap>
<valuemap type="QVariantMap" key="ProjectExplorer.BuildConfiguration.BuildStepList.1">
<valuemap type="QVariantMap" key="ProjectExplorer.BuildStepList.Step.0">
<valuelist type="QVariantList" key="GenericProjectManager.GenericMakeStep.BuildTargets">
<value type="QString">clean</value>
</valuelist>
<value type="bool" key="ProjectExplorer.BuildStep.Enabled">true</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">GenericProjectManager.GenericMakeStep</value>
</valuemap>
<value type="qlonglong" key="ProjectExplorer.BuildStepList.StepsCount">1</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Clean</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName">Clean</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">ProjectExplorer.BuildSteps.Clean</value>
</valuemap>
<value type="int" key="ProjectExplorer.BuildConfiguration.BuildStepListCount">2</value>
<value type="bool" key="ProjectExplorer.BuildConfiguration.ClearSystemEnvironment">false</value>
<valuelist type="QVariantList" key="ProjectExplorer.BuildConfiguration.CustomParsers"/>
<value type="bool" key="ProjectExplorer.BuildConfiguration.ParseStandardOutput">false</value>
<valuelist type="QVariantList" key="ProjectExplorer.BuildConfiguration.UserEnvironmentChanges"/>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName">По умолчанию</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">GenericProjectManager.GenericBuildConfiguration</value>
<value type="qlonglong" key="ProjectExplorer.Target.ActiveDeployConfiguration">0</value>
<value type="qlonglong" key="ProjectExplorer.Target.ActiveRunConfiguration">0</value>
<valuemap type="QVariantMap" key="ProjectExplorer.Target.DeployConfiguration.0">
<valuemap type="QVariantMap" key="ProjectExplorer.BuildConfiguration.BuildStepList.0">
<value type="qlonglong" key="ProjectExplorer.BuildStepList.StepsCount">0</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Deploy</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName">Deploy</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">ProjectExplorer.BuildSteps.Deploy</value>
</valuemap>
<value type="int" key="ProjectExplorer.BuildConfiguration.BuildStepListCount">1</value>
<valuemap type="QVariantMap" key="ProjectExplorer.DeployConfiguration.CustomData"/>
<value type="bool" key="ProjectExplorer.DeployConfiguration.CustomDataEnabled">false</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">ProjectExplorer.DefaultDeployConfiguration</value>
</valuemap>
<value type="qlonglong" key="ProjectExplorer.Target.DeployConfigurationCount">1</value>
<valuemap type="QVariantMap" key="ProjectExplorer.Target.RunConfiguration.0">
<value type="bool" key="Analyzer.Perf.Settings.UseGlobalSettings">true</value>
<value type="bool" key="Analyzer.QmlProfiler.Settings.UseGlobalSettings">true</value>
<value type="int" key="Analyzer.Valgrind.Callgrind.CostFormat">0</value>
<value type="bool" key="Analyzer.Valgrind.Settings.UseGlobalSettings">true</value>
<valuelist type="QVariantList" key="Analyzer.Valgrind.SuppressionFiles"/>
<value type="QList&lt;int&gt;" key="Analyzer.Valgrind.VisibleErrorKinds"></value>
<valuelist type="QVariantList" key="CustomOutputParsers"/>
<value type="int" key="PE.EnvironmentAspect.Base">2</value>
<valuelist type="QVariantList" key="PE.EnvironmentAspect.Changes"/>
<value type="bool" key="PE.EnvironmentAspect.PrintOnRun">false</value>
<value type="QString" key="PerfRecordArgsId">-e cpu-cycles --call-graph dwarf,4096 -F 250</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">ProjectExplorer.CustomExecutableRunConfiguration</value>
<value type="QString" key="ProjectExplorer.RunConfiguration.BuildKey"></value>
<value type="bool" key="ProjectExplorer.RunConfiguration.Customized">false</value>
<value type="QString" key="ProjectExplorer.RunConfiguration.UniqueId"></value>
<value type="bool" key="RunConfiguration.UseCppDebuggerAuto">true</value>
<value type="bool" key="RunConfiguration.UseQmlDebuggerAuto">true</value>
</valuemap>
<value type="qlonglong" key="ProjectExplorer.Target.RunConfigurationCount">1</value>
</valuemap>
<value type="qlonglong" key="ProjectExplorer.Target.BuildConfigurationCount">1</value>
<valuemap type="QVariantMap" key="ProjectExplorer.Target.DeployConfiguration.0">
<valuemap type="QVariantMap" key="ProjectExplorer.BuildConfiguration.BuildStepList.0">
<value type="qlonglong" key="ProjectExplorer.BuildStepList.StepsCount">0</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Deploy</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName">Deploy</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">ProjectExplorer.BuildSteps.Deploy</value>
</valuemap>
<value type="int" key="ProjectExplorer.BuildConfiguration.BuildStepListCount">1</value>
<valuemap type="QVariantMap" key="ProjectExplorer.DeployConfiguration.CustomData"/>
<value type="bool" key="ProjectExplorer.DeployConfiguration.CustomDataEnabled">false</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">ProjectExplorer.DefaultDeployConfiguration</value>
</valuemap>
<value type="qlonglong" key="ProjectExplorer.Target.DeployConfigurationCount">1</value>
<valuemap type="QVariantMap" key="ProjectExplorer.Target.RunConfiguration.0">
<value type="bool" key="Analyzer.Perf.Settings.UseGlobalSettings">true</value>
<value type="bool" key="Analyzer.QmlProfiler.Settings.UseGlobalSettings">true</value>
<value type="int" key="Analyzer.Valgrind.Callgrind.CostFormat">0</value>
<value type="bool" key="Analyzer.Valgrind.Settings.UseGlobalSettings">true</value>
<valuelist type="QVariantList" key="Analyzer.Valgrind.SuppressionFiles"/>
<value type="QList&lt;int&gt;" key="Analyzer.Valgrind.VisibleErrorKinds"></value>
<valuelist type="QVariantList" key="CustomOutputParsers"/>
<value type="int" key="PE.EnvironmentAspect.Base">2</value>
<valuelist type="QVariantList" key="PE.EnvironmentAspect.Changes"/>
<value type="bool" key="PE.EnvironmentAspect.PrintOnRun">false</value>
<value type="QString" key="PerfRecordArgsId">-e cpu-cycles --call-graph dwarf,4096 -F 250</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">ProjectExplorer.CustomExecutableRunConfiguration</value>
<value type="QString" key="ProjectExplorer.RunConfiguration.BuildKey"></value>
<value type="bool" key="ProjectExplorer.RunConfiguration.Customized">false</value>
<value type="QString" key="ProjectExplorer.RunConfiguration.UniqueId"></value>
<value type="bool" key="RunConfiguration.UseCppDebuggerAuto">true</value>
<value type="bool" key="RunConfiguration.UseQmlDebuggerAuto">true</value>
</valuemap>
<value type="qlonglong" key="ProjectExplorer.Target.RunConfigurationCount">1</value>
</valuemap>
</data>
<data>
<variable>ProjectExplorer.Project.TargetCount</variable>
<value type="qlonglong">1</value>
</data>
<data>
<variable>Version</variable>
<value type="int">22</value>
</data>
</qtcreator>

View File

@@ -0,0 +1,16 @@
angles.c
angles.h
args.c
args.h
astrosib_proto.h
dome.c
dome.h
emulation.c
emulation.h
main.c
server.c
server.h
mount.c
mount.h
stellarium.c
stellarium.h

View File

@@ -0,0 +1,191 @@
/*
* This file is part of the Snippets project.
* Copyright 2024 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
#include <inttypes.h>
#include <pthread.h>
#include <stdio.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <usefull_macros.h>
#include <weather_data.h>
#include "mount.h"
#include "server.h"
#include "stellarium.h"
// max age time of last status - 30s
#define STATUS_MAX_AGE (30.)
// commands
#define CMD_UNIXT "unixt"
#define CMD_STATUS "status"
#define CMD_RELAY "relay"
#define CMD_OPEN "open"
#define CMD_CLOSE "close"
#define CMD_STOP "stop"
#define CMD_HALF "half"
// main command socket
static sl_sock_t *cmd_socket = NULL;
// socket for stellarium purposes
static int stellarium_sockfd = -1;
// sleep time (us)
static unsigned int sleept = DEFAULT_SLEEP_T;
// running flag
static volatile bool isrunning = false;
unsigned int server_getsleept(){ return sleept; }
bool server_setsleept(unsigned int t){
if(t == 0 || t > MAX_SLEEP_T) return false;
sleept = t;
return true;
}
/////// handlers
// unixt - send to ALL clients
static sl_sock_hresult_e dtimeh(sl_sock_t *c, _U_ sl_sock_hitem_t *item, _U_ const char *req){
char buf[32];
snprintf(buf, 31, "%s=%.2f\n", item->key, sl_dtime());
LOGDBG("Client %d asks time: %s", c->fd, buf);
sl_sock_sendstrmessage(c, buf);
return RESULT_SILENCE;
}
// statust - text format status
static sl_sock_hresult_e status(sl_sock_t *c, sl_sock_hitem_t *item, _U_ const char *req){
char buf[BUFSIZ];
snprintf(buf, BUFSIZ-1, "%s=%s\n", item->key, mount_status_str());
LOGDBG("Client %d asks status: %s", c->fd, buf);
sl_sock_sendstrmessage(c, buf);
return RESULT_SILENCE;
}
// and all handlers collection
static sl_sock_hitem_t handlers[] = {
{dtimeh, CMD_UNIXT, "get server's UNIX time", NULL},
{status, CMD_STATUS, "get mount status", NULL},
{NULL, NULL, NULL, NULL}
};
// Too much clients handler
static void toomuch(int fd){
const char m[] = "Try later: too much clients connected\n";
send(fd, m, sizeof(m)-1, MSG_NOSIGNAL);
shutdown(fd, SHUT_WR);
DBG("shutdown, wait");
double t0 = sl_dtime();
uint8_t buf[8];
while(sl_dtime() - t0 < 11.){
if(sl_canread(fd)){
ssize_t got = read(fd, buf, 8);
DBG("Got=%zd", got);
if(got < 1) break;
}
}
DBG("Disc after %gs", sl_dtime() - t0);
LOGWARN("Client fd=%d tried to connect after MAX reached", fd);
}
// new connections handler: can check IP and reject client by returning FALSE
static int connected(sl_sock_t *c){
if(c->type == SOCKT_UNIX) LOGMSG("New client fd=%d connected", c->fd);
else LOGMSG("New client fd=%d, IP=%s connected", c->fd, c->IP);
return TRUE;
}
// disconnected handler
static void disconnected(sl_sock_t *c){
if(c->type == SOCKT_UNIX) LOGMSG("Disconnected client fd=%d", c->fd);
else LOGMSG("Disconnected client fd=%d, IP=%s", c->fd, c->IP);
}
bool server_check(server_sock_t *sockt){
sl_socktype_e type = (sockt->cmd_isunix) ? SOCKT_UNIX : SOCKT_NETLOCAL;
cmd_socket = sl_sock_run_server(type, sockt->cmdnode, BUFSIZ, handlers);
if(!cmd_socket){
LOGERR("Can't start main server");
return false;
}
LOGMSG("Main server started: %s", sockt->cmdnode);
sl_sock_changemaxclients(cmd_socket, sockt->maxclients);
sl_sock_maxclhandler(cmd_socket, toomuch);
sl_sock_connhandler(cmd_socket, connected);
sl_sock_dischandler(cmd_socket, disconnected);
stellarium_sockfd = sl_sock_open(SOCKT_NET, sockt->stellport, 1, 0);
if(stellarium_sockfd < 0){
LOGERR("Can't start stellarium socket");
sl_sock_delete(&cmd_socket);
return false;
}
if(listen(stellarium_sockfd, sockt->maxclients) == -1){
WARN("listen() for stellarium socket");
LOGERR("Can't run listen() for stellarium socket");
sl_sock_delete(&cmd_socket);
close(stellarium_sockfd);
return false;
}
int enable = 0;
if(ioctl(stellarium_sockfd, FIONBIO, (void *)&enable) < 0){ // make socket blocking again
WARN("ioctl()");
LOGERR("Can't make stellarium socket blocking");
}
DBG("stellarium_sockfd=%d", stellarium_sockfd);
LOGMSG("Prepared stellarium socket: %s", sockt->stellport);
DBG("Prepared stellarium socket: %s", sockt->stellport);
return true;
}
void server_run(){
if(isrunning){
LOGERR("server_run(): still running!");
return;
}
if(stellarium_sockfd == -1 || !cmd_socket){
LOGERR("server_run(): not initialized");
if(cmd_socket) sl_sock_delete(&cmd_socket);
ERRX("server_run(): not initialized");
}
if(!stellarium_start(stellarium_sockfd)){
LOGERR("Can't start stellarium server");
return;
}
if(!mount_connect()){
LOGERR("Can't connect to mount");
sl_sock_delete(&cmd_socket);
return;
}
isrunning = true;
DBG("While");
while(isrunning && cmd_socket && cmd_socket->connected){
usleep(sleept);
if(!cmd_socket->rthread){
LOGERR("Server handlers thread is dead");
break;
}
// finite state machine polling
//dome_poll(DOME_POLL, 0);
}
DBG("Stop command socket");
sl_sock_delete(&cmd_socket);
WARNX("Server is dead");
LOGERR("Server is dead");
isrunning = false;
}
void server_stop(){
isrunning = false;
}

View File

@@ -0,0 +1,39 @@
/*
* This file is part of the mountdaemon_10micron project.
* Copyright 2025 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <usefull_macros.h>
// default and max available time for "usleep"
#define DEFAULT_SLEEP_T 100
#define MAX_SLEEP_T 10000
#define DEFAULT_MAXCLIENTS 5
typedef struct{
int cmd_isunix; // UNIX-socket instead of INET for `cmdnode`
const char *stellport; // port of stellarium server; could be "localhost:port" for local-only work
const char *cmdnode; // node of command socket
int maxclients; // maximal amount of clients connected
} server_sock_t;
bool server_check(server_sock_t *sockt);
void server_run();
void server_stop();
unsigned int server_getsleept();
bool server_setsleept(unsigned int t);

View File

@@ -0,0 +1,296 @@
/*
* This file is part of the mountdaemon_10micron project.
* Copyright 2026 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
// base functions for sending/receiving data in stellarium protocol
#include <stdint.h>
#include <usefull_macros.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "angles.h"
#include "mount.h"
#include "stellarium.h"
#define BUFLEN 256
// running flag
static volatile bool isrunning = false;
static pthread_t mainthread;
//read: 0x14 0x0 0x0 0x0 0x5b 0x5a 0x2e 0xc6 0x8c 0x23 0x5 0x0 0x23 0x9 0xe5 0xaf 0x23 0x2e 0x34 0xed
// command: goto 16h29 24.45 -26d25 55.62
/*
LITTLE-ENDIAN!!!
from client:
LENGTH (2 bytes, integer): length of the message
TYPE (2 bytes, integer): 0
TIME (8 bytes, integer): current time on the server computer in microseconds
since 1970.01.01 UT. Currently unused.
RA (4 bytes, unsigned integer): right ascension of the telescope (J2000)
a value of 0x100000000 = 0x0 means 24h=0h,
a value of 0x80000000 means 12h
DEC (4 bytes, signed integer): declination of the telescope (J2000)
a value of -0x40000000 means -90degrees,
a value of 0x0 means 0degrees,
a value of 0x40000000 means 90degrees
to client:
LENGTH (2 bytes, integer): length of the message
TYPE (2 bytes, integer): 0
TIME (8 bytes, integer): current time on the server computer in microseconds
since 1970.01.01 UT. Currently unused.
RA (4 bytes, unsigned integer): right ascension of the telescope (J2000)
a value of 0x100000000 = 0x0 means 24h=0h,
a value of 0x80000000 means 12h
DEC (4 bytes, signed integer): declination of the telescope (J2000)
a value of -0x40000000 means -90degrees,
a value of 0x0 means 0degrees,
a value of 0x40000000 means 90degrees
STATUS (4 bytes, signed integer): status of the telescope, currently unused.
status=0 means ok, status<0 means some error
*/
#define DEG2DEC(degr) ((int32_t)(degr / 90. * ((double)0x40000000)))
#define DEG2RA(degr) ((uint32_t)(degr / 180. * ((double)0x80000000)))
#define HRS2RA(degr) ((uint32_t)(degr / 12. * ((double)0x80000000)))
#define DEC2DEG(i32) (((double)i32)*90./((double)0x40000000))
#define RA2DEG(u32) (((double)u32)*180. /((double)0x80000000))
#define RA2HRS(u32) (((double)u32)*12. /((double)0x80000000))
typedef struct __attribute__((__packed__)){
uint16_t len;
uint16_t type;
uint64_t time;
uint32_t ra;
int32_t dec;
} indata;
typedef struct __attribute__((__packed__)){
uint16_t len;
uint16_t type;
uint64_t time;
uint32_t ra;
int32_t dec;
int32_t status;
} outdata;
/**
* @brief proc_data - process data received from Stellarium
* @param data - raw data
* @param len - its length
* @return true if all OK
*/
static bool proc_data(uint8_t *data, ssize_t len){
FNAME();
if(len != sizeof(indata)){
WARNX("Bad data size: got %zd instead of %zd!", len, sizeof(indata));
return false;
}
indata *dat = (indata*)data;
uint16_t L, T;
uint32_t ra;
int32_t dec;
#if __BYTE_ORDER__ != __ORDER_LITTLE_ENDIAN__
L = le16toh(dat->len); T = le16toh(dat->type);
ra = le32toh(dat->ra);
dec = (int32_t)le32toh((uint32_t)dat->dec);
#else
L = dat->len; T = dat->type;
ra = dat->ra; dec = dat->dec;
#endif
DBG("got message with len %u & type %u", L, T);
if(L != len){
WARNX("Length of message != msg->len");
return false;
}
if(T){
WARNX("Wrong message type");
return false;
}
// convert RA/DEC to degrees
double tagRA = RA2DEG(ra), tagDec = DEC2DEG(dec);
DBG("RA: %u (%g degr), DEC: %d (%g degr)", ra, tagRA, dec, tagDec);
LOGMSG("(stellarium) RA: %u (%g degr), DEC: %d (%g degr)", ra, tagRA, dec, tagDec);
#if 0
// check RA/DEC
horizCrds_t hnow; // without refraction
polarCrds_t p2000, pnow;
p2000.ra = DEG2RAD(tagRA);
p2000.dec = DEG2RAD(tagDec);
// now J2000 obs Jnow
if(!get_ObsPlace(NULL, &p2000, &pnow, &hnow)){
WARNX("Can't convert coordinates to Jnow");
return false;
}
tagRA = RAD2DEG(pnow.ra - pnow.eo);
tagDec = RAD2DEG(pnow.dec);
#endif
return (mount_setInpRA(tagRA) && mount_setInpDec(tagDec) && mount_setInpMJD(ERFA_DJM00));
}
/**
* Send data to user
* @param data - data to send
* @param dlen - data length
* @param sockfd - socket fd for sending data
* @return false if client disconnected
*/
float send_data(uint8_t *data, size_t dlen, int sockfd){
ssize_t sent = send(sockfd, data, dlen, MSG_NOSIGNAL);
if(sent != (ssize_t)dlen){
if(sent == -1 && errno != EINTR){
WARN("Disconnected?");
return false;
}
WARN("write()");
}
return true;
}
/**
* main socket service procedure
*/
static void *handle_socket(void *sockd){
FNAME();
if(!isrunning) return NULL;
outdata dout;
int sock = *(int*)sockd;
dout.len = htole16(sizeof(outdata));
dout.type = 0;
while(isrunning){
// get coordinates
double RA = 0., Decl = 0.;
if((dout.status = mount_getcoords(&RA, &Decl)) == MNT_S_ERROR){
WARNX("Error: can't get coordinates");
sleep(1);
continue;
}
//DBG("got : %g/%g", RA, Decl);
dout.ra = htole32(HRS2RA(RA));
dout.dec = (int32_t)htole32(DEG2DEC(Decl));
if(!send_data((uint8_t*)&dout, sizeof(outdata), sock)) break;
//DBG("sent ra = %g, dec = %g", RA2HRS(dout.ra), DEC2DEG(dout.dec));
if(!sl_canread(sock)){
sleep(1);
continue;
}
// fill incoming buffer
uint8_t buff[BUFLEN];
ssize_t rd = read(sock, buff, BUFLEN-1);
if(rd <= 0){ // error or disconnect
DBG("Nothing to read from fd %d (ret: %zd)", sock, rd);
WARNX("Client disconnected?");
break;
}
buff[rd] = 0;
DBG("read %zd (%s)", rd, buff);
if(!proc_data(buff, rd)) dout.status = -1;
else{
DBG("sent OK");
dout.status = 0;
}
}
close(sock);
return NULL;
}
// Main loop thread: wait connections over socket and create one thread for each
static void* start(void *F){
if(isrunning){
WARNX("already running");
return NULL;
}
if(!F){
WARNX("start(): No arg");
return NULL;
}
int sockfd = *((int*)F);
if(sockfd < 0){
WARNX("start(): sockfd=%d", sockfd);
return NULL;
}
DBG("Start main loop, sockfd=%d", sockfd);
isrunning = true;
// Main loop
while(isrunning){
socklen_t size = sizeof(struct sockaddr_in);
struct sockaddr_in myaddr;
int newsock;
DBG("ACCEPT");
newsock = accept(sockfd, (struct sockaddr*)&myaddr, &size);
if(newsock <= 0){
if(errno == EAGAIN){
usleep(1000);
continue; // nothing available
}
WARN("accept()");
LOGWARN("Stellarium socket error in accept()");
sleep(1);
continue;
}
struct sockaddr_in peer;
socklen_t peer_len = sizeof(peer);
if(getpeername(newsock, (struct sockaddr*)&peer, &peer_len) == -1){
LOGWARN("Stellarium socket error in getpeername()");
WARN("getpeername()");
close(newsock);
continue;
}
int sockport = -1;
if(getsockname(newsock, (struct sockaddr*)&peer, &peer_len) == 0){
sockport = ntohs(peer.sin_port);
}
char *peerIP = inet_ntoa(peer.sin_addr);
LOGMSG("Got connection from %s @ %d", peerIP, sockport);
DBG("Peer's IP address is: %s (@port %d)\n", peerIP, sockport);
/*if(strcmp(peerIP, ACCEPT_IP) && strcmp(peerIP, "127.0.0.1")){
WARNX("Wrong IP");
close(newsock);
continue;
}*/
pthread_t rthrd;
if(pthread_create(&rthrd, NULL, handle_socket, (void*)&newsock)){
WARN("Can't create socket thread");
LOGERR("Stellarium socket: error creating listen thread");
}else{
DBG("Thread created, detouch");
pthread_detach(rthrd); // don't care about thread state
}
}
close(sockfd);
return NULL;
}
bool stellarium_start(int sockfd){
int fd = sockfd;
if(pthread_create(&mainthread, NULL, start, (void*)&fd)){
WARN("pthread_create()");
return false;
}
DBG("Stellarium server started");
return true;
}
void stellarium_stop(){
if(!isrunning) return;
isrunning = false;
pthread_join(mainthread, NULL);
}

View File

@@ -0,0 +1,22 @@
/*
* This file is part of the mountdaemon_10micron project.
* Copyright 2026 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
#pragma once
bool stellarium_start(int sockfd);
void stellarium_stop();

View File

@@ -4,15 +4,11 @@ Different daemons & tools
- *10micron_stellarium* - simple daemon for 10-micron mount management from stellarium interface - *10micron_stellarium* - simple daemon for 10-micron mount management from stellarium interface
- *astrosib* - some scripts used during observations - *astrosib* - some scripts used during observations
- *deprecated* - deprecated code - *deprecated* - deprecated code
- *domedaemon-astrosib* - deprecated astrosib daemon - *domedaemon-astrosib* - daemon for "Astrosib" all-sky dome management
- *domedaemon_baader* - open/close Baaden dome by network query - *domedaemon_baader* - daemon for "Baader Planetarium" all-sky dome management
- *domedaemon-astrosib* - open/close Astrosib dome by network query
- *netdaemon* - template for net-daemons
- *netsocket* - scripts for management of network 220V-socket - *netsocket* - scripts for management of network 220V-socket
- *send_coordinates* - get/send coordinates to 10-micron mount through stellarium daemon (almost deprecated) - *send_coordinates* - get/send coordinates to 10-micron mount through stellarium daemon (almost deprecated)
- *teldaemon_astrosib* - open/close Astrosib-500 scope covers by network query - *teldaemon_astrosib* - work with Astrosib-500 scope equipment by network query
- *weatherdaemon* - weather daemon for old meteostation (almost deprecated) - *weatherdaemon_multimeteo* - weather daemon for ALL meteo sensors on "Astro-M" complex
- *weatherdaemon_multimeteo* - (pre-developed) version of weather daemon for ALL sensors on "Astro-M" complex - *weather_logger* - make file-based database for all meteo sensors
- *weatherdaemon_newmeteo* - daemon for new (chinese) meteostation (almost deprecated) - *weather_proxy* - daemon gathering meteo data from `weatherdaemon_multimeteo` and sharing it on localhost over SHM
- *weather_database* - make database by data of almost deprecated weather daemons
- *weather_proxy* - (pre-developed) daemon gathering meteo data and sharing it on localhost over SHM

View File

@@ -0,0 +1,103 @@
/*
* geany_encoding=koi8-r
* emulation.c
*
* Copyright 2018 Edward V. Emelianov <eddy@sao.ru, edward.emelianoff@gmail.com>
*
* 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 "math.h"
#include "emulation.h"
#include "usefull_macro.h"
// emulation speed over RA & DEC (0.5 degr per sec)
#define RA_SPEED (0.033)
#define DECL_SPEED (0.5)
// current coordinates
static double RA = 0., DECL = 0.;
// target coordinates
static double RAtarg = 0., DECLtarg = 0.;
// coordinates @ guiding start
static double RA0 = 0., DECL0 = 0.;
static double raspeed = 0.;
// ==1 if pointing
static int pointing = 0;
// pointing start time
static double tstart = -1.;
/**
* send coordinates to telescope emulation
* @param ra - right ascention (hours)
* @param decl - declination (degrees)
* @return 1 if all OK
*/
int point_emulation(double ra, double decl){
DBG("(emul) Send ra=%g, decl=%g", ra, decl);
putlog("(emul) Send ra=%g, decl=%g", ra, decl);
RAtarg = ra; DECLtarg = decl;
RA0 = RA; DECL0 = DECL;
raspeed = (RAtarg > RA) ? RA_SPEED : -RA_SPEED;
if(fabs(RAtarg - RA) > 12.){ // go to opposite direction
raspeed = -raspeed;
}
tstart = dtime();
pointing = 1;
return 0;
}
static double getradiff(){
double diff = RAtarg - RA;
if(raspeed < 0.) diff = -diff;
if(diff > 12.) diff -= 24.;
else if(diff < -12.) diff += 24.;
return fabs(diff);
}
/**
* get coordinates (emulation)
* @return 1 if all OK
*/
int get_emul_coords(double *ra, double *decl){
if(pointing){
DBG("RA/DEC: targ: %g/%g, cur: %g/%g, start: %g/%g", RAtarg, DECLtarg, RA, DECL, RA0, DECL0);
// diff < speed? stop
if((fabs(RAtarg - RA) < RA_SPEED && fabs(DECLtarg - DECL) < DECL_SPEED)){
RA = RAtarg;
DECL = DECLtarg;
pointing = 0; // guiding
DBG("@ target");
}else{ // calculate new coordinates
double radiff = getradiff(), decldiff = fabs(DECLtarg - DECL);
double tdiff = dtime() - tstart;
RA = RA0 + raspeed * tdiff;
DBG("RA=%g", RA);
if(getradiff() > radiff) RA = RAtarg;
DBG("RA=%g", RA);
if(RA < 0.) RA += 24.;
else if(RA > 24.) RA -= 24.;
DBG("RA=%g", RA);
double sign = (DECLtarg > DECL) ? 1. : -1.;
DECL = DECL0 + sign * DECL_SPEED * tdiff;
if(fabs(DECLtarg - DECL) > decldiff) DECL = DECLtarg;
DBG("RA/DEC: targ: %g/%g, cur: %g/%g, start: %g/%g", RAtarg, DECLtarg, RA, DECL, RA0, DECL0);
}
}
if(ra) *ra = RA;
if(decl) *decl = DECL;
return 1;
}

View File

@@ -0,0 +1,30 @@
/*
* geany_encoding=koi8-r
* emulation.h
*
* Copyright 2018 Edward V. Emelianov <eddy@sao.ru, edward.emelianoff@gmail.com>
*
* 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.
*
*/
#pragma once
#ifndef __EMULATION_H__
#define __EMULATION_H__
int point_emulation(double ra, double decl);
int get_emul_coords(double *ra, double *decl);
#endif // __EMULATION_H__

View File

@@ -0,0 +1,522 @@
/*
* main.c
*
* Copyright 2014 Edward V. Emelianov <eddy@sao.ru, edward.emelianoff@gmail.com>
*
* 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 <arpa/inet.h>
#include <endian.h>
#include <math.h>
#include <netdb.h>
#include <netinet/in.h>
#include <signal.h>
#include <sys/prctl.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <time.h>
#include "emulation.h"
#include "libsofa.h"
#include "main.h"
#include "socket.h"
#include "telescope.h"
// daemon.c
extern void check4running(char *self, char *pidfilename, void (*iffound)(pid_t pid));
// Max amount of connections
#define BACKLOG (10)
#define BUFLEN (1024)
// pause for incoming message waiting (out coordinates sent after that timeout)
#define SOCK_TMOUT (1)
static pid_t childpid = 1; // PID of child process
volatile int global_quit = 0;
// quit by signal
void signals(int sig){
signal(sig, SIG_IGN);
if(childpid){ // parent process
restore_tty(); // restore all parameters
unlink(GP->pidfile); // and remove pidfile
weatherserver_disconnect();
}
DBG("Get signal %d, quit.\n", sig);
global_quit = 1;
if(childpid) putlog("PID %d exit with status %d after child's %d death", getpid(), sig, childpid);
else WARNX("Child %d died with %d", getpid(), sig);
sleep(1);
exit(sig);
}
// search a first word after needle without spaces
char* stringscan(char *str, char *needle){
char *a, *e;
char *end = str + strlen(str);
a = strstr(str, needle);
if(!a) return NULL;
a += strlen(needle);
while (a < end && (*a == ' ' || *a == '\r' || *a == '\t')) a++;
if(a >= end) return NULL;
e = strchr(a, ' ');
if(e) *e = 0;
return a;
}
/**
* Send data to user
* @param data - data to send
* @param dlen - data length
* @param sockfd - socket fd for sending data
* @return 0 if failed
*/
int send_data(uint8_t *data, size_t dlen, int sockfd){
size_t sent = write(sockfd, data, dlen);
if(sent != dlen){
WARN("write()");
return 0;
}
return 1;
}
//read: 0x14 0x0 0x0 0x0 0x5b 0x5a 0x2e 0xc6 0x8c 0x23 0x5 0x0 0x23 0x9 0xe5 0xaf 0x23 0x2e 0x34 0xed
// command: goto 16h29 24.45 -26d25 55.62
/*
LITTLE-ENDIAN!!!
from client:
LENGTH (2 bytes, integer): length of the message
TYPE (2 bytes, integer): 0
TIME (8 bytes, integer): current time on the server computer in microseconds
since 1970.01.01 UT. Currently unused.
RA (4 bytes, unsigned integer): right ascension of the telescope (J2000)
a value of 0x100000000 = 0x0 means 24h=0h,
a value of 0x80000000 means 12h
DEC (4 bytes, signed integer): declination of the telescope (J2000)
a value of -0x40000000 means -90degrees,
a value of 0x0 means 0degrees,
a value of 0x40000000 means 90degrees
to client:
LENGTH (2 bytes, integer): length of the message
TYPE (2 bytes, integer): 0
TIME (8 bytes, integer): current time on the server computer in microseconds
since 1970.01.01 UT. Currently unused.
RA (4 bytes, unsigned integer): right ascension of the telescope (J2000)
a value of 0x100000000 = 0x0 means 24h=0h,
a value of 0x80000000 means 12h
DEC (4 bytes, signed integer): declination of the telescope (J2000)
a value of -0x40000000 means -90degrees,
a value of 0x0 means 0degrees,
a value of 0x40000000 means 90degrees
STATUS (4 bytes, signed integer): status of the telescope, currently unused.
status=0 means ok, status<0 means some error
*/
#define DEG2DEC(degr) ((int32_t)(degr / 90. * ((double)0x40000000)))
#define HRS2RA(hrs) ((uint32_t)(hrs / 12. * ((double)0x80000000)))
#define DEC2DEG(i32) (((double)i32)*90./((double)0x40000000))
#define RA2HRS(u32) (((double)u32)*12. /((double)0x80000000))
typedef struct __attribute__((__packed__)){
uint16_t len;
uint16_t type;
uint64_t time;
uint32_t ra;
int32_t dec;
} indata;
typedef struct __attribute__((__packed__)){
uint16_t len;
uint16_t type;
uint64_t time;
uint32_t ra;
int32_t dec;
int32_t status;
} outdata;
/**
* convert RA/DEC to string in forman RA: HH:MM:SS.SS, DEC: DD:MM:SS.S
*/
char *radec2str(double ra, double dec){
static char buf[1024];
char sign = '+';
if(dec < 0){
sign = '-';
dec = -dec;
}
int h = (int)ra;
ra -= h; ra *= 60.;
int m = (int)ra;
ra -= m; ra *= 60.;
int d = (int) dec;
dec -= d; dec *= 60.;
int dm = (int)dec;
dec -= dm; dec *= 60.;
snprintf(buf, 1024, "%d:%d:%.2f %c%d:%d:%.1f", h,m,ra, sign,d,dm,dec);
return buf;
}
/**
* send input RA/Decl (j2000!) coordinates to tel
* ra in hours (0..24), decl in degrees (-90..90)
* @return 1 if all OK
*/
int setCoords(double ra, double dec){
char *radec = radec2str(ra, dec);
DBG("Set RA/Decl to %s", radec);
putlog("Try to set RA/Decl to %s", radec);
int (*pointfunction)(double, double) = point_telescope;
if(GP->emulation) pointfunction = point_emulation;
return pointfunction(ra, dec);
}
/**
* @brief proc_data - process data received from Stellarium
* @param data - raw data
* @param len - its length
* @return 1 if all OK
*/
int proc_data(uint8_t *data, ssize_t len){
FNAME();
if(len != sizeof(indata)){
WARNX("Bad data size: got %zd instead of %zd!", len, sizeof(indata));
return 0;
}
indata *dat = (indata*)data;
uint16_t L, T;
//uint64_t tim;
uint32_t ra;
int32_t dec;
#if __BYTE_ORDER__ != __ORDER_LITTLE_ENDIAN__
L = le16toh(dat->len); T = le16toh(dat->type);
//tim = le64toh(dat->time);
ra = le32toh(dat->ra);
dec = (int32_t)le32toh((uint32_t)dat->dec);
#else
L = dat->len; T = dat->type;
//tim = dat->time;
ra = dat->ra; dec = dat->dec;
#endif
DBG("got message with len %u & type %u", L, T);
if(L != len){
WARNX("Length of message != msg->len");
return 0;
}
if(T){
WARNX("Wrong message type");
return 0;
}
// convert RA/DEC to hours/degrees
double tagRA = RA2HRS(ra), tagDec = DEC2DEG(dec);
DBG("RA: %u (%g), DEC: %d (%g)", ra, tagRA, dec, tagDec);
putlog("RA: %u (%g degr), DEC: %d (%g degr)", ra, tagRA, dec, tagDec);
// check RA/DEC
horizCrds hnow; // without refraction
polarCrds p2000, pnow;
p2000.ra = tagRA/12. * M_PI;
p2000.dec = tagDec * ERFA_DD2R;
// now J2000 obs Jnow
if(get_ObsPlace(NULL, &p2000, NULL, &pnow, &hnow)){
WARNX("Can't convert coordinates to Jnow");
return 0;
}
/*
int i[4], j[4]; char pm, pm1;
eraA2af(2, hnow.az, &pm, i);
eraA2af(2, hnow.zd, &pm1, j);
DBG("az: %c%02d %02d %02d.%2.d, zd: %c%02d %02d %02d.%2.d",
pm, i[0],i[1],i[2],i[3],
pm1,j[0],j[1],j[2],j[3]);
eraA2af(2, M_PI_2 - hnow.zd, &pm, i);
DBG("h: %c%02d %02d %02d.%2.d", pm, i[0],i[1],i[2],i[3]);
*/
if(hnow.zd > 80.*ERFA_DD2R){
WARNX("Z > 80degr (%g), stop telescope", hnow.zd * ERFA_DR2D);
putlog("Z=%.1f > 80 - stop!", hnow.zd * ERFA_DR2D);
stop_telescope();
return 0;
}
tagRA = (pnow.ra - pnow.eo) / M_PI * 12.;
tagDec = pnow.dec / ERFA_DD2R;
if(!setCoords(tagRA, tagDec)) return 0;
return 1;
}
/**
* main socket service procedure
*/
void *handle_socket(void *sockd){
FNAME();
if(global_quit) return NULL;
outdata dout;
int sock = *(int*)sockd;
dout.len = htole16(sizeof(outdata));
dout.type = 0;
int (*getcoords)(double*, double*) = get_telescope_coords;
if(GP->emulation) getcoords = get_emul_coords;
while(!global_quit){
// get coordinates
double RA = 0., Decl = 0.;
if((dout.status = getcoords(&RA, &Decl)) < 0){
WARNX("Error: can't get coordinates");
sleep(1);
continue;
}
//DBG("got : %g/%g", RA, Decl);
dout.ra = htole32(HRS2RA(RA));
dout.dec = (int32_t)htole32(DEG2DEC(Decl));
if(!send_data((uint8_t*)&dout, sizeof(outdata), sock)) break;
//DBG("sent ra = %g, dec = %g", RA2HRS(dout.ra), DEC2DEG(dout.dec));
fd_set readfds;
struct timeval timeout;
FD_ZERO(&readfds);
FD_SET(sock, &readfds);
timeout.tv_sec = SOCK_TMOUT; // wait not more than SOCK_TMOUT second
timeout.tv_usec = 0;
int sel = select(sock + 1 , &readfds , NULL , NULL , &timeout);
if(sel < 0){
if(errno != EINTR)
WARN("select()");
continue;
}
if(!(FD_ISSET(sock, &readfds))) continue;
// fill incoming buffer
uint8_t buff[BUFLEN+1];
ssize_t rd = read(sock, buff, BUFLEN);
buff[rd] = 0;
DBG("read %zd (%s)", rd, buff);
if(rd <= 0){ // error or disconnect
DBG("Nothing to read from fd %d (ret: %zd)", sock, rd);
break;
}
/**************************************
* DO SOMETHING WITH DATA *
**************************************/
if(!proc_data(buff, rd)) dout.status = -1;
else dout.status = 0;
}
close(sock);
return NULL;
}
// thread writing FITS-header file
static void *hdrthread(_U_ void *buf){
// write FITS-header at most once per second
while(!global_quit){
wrhdr();
usleep(100000); // give a chance to write/read for others
}
return NULL;
}
/**
* @brief opensocket - open socket to port `port`
* @return socket fd or <0 if failed
*/
static int opensocket(char *port){
if(!port) return -1;
int reuseaddr = 1;
int sock;
struct addrinfo hints, *res, *p;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
DBG("try to open port %s", port);
if(getaddrinfo(NULL, port, &hints, &res) != 0){
WARN("getaddrinfo()");
return 0;
}
/*
struct sockaddr_in *ia = (struct sockaddr_in*)res->ai_addr;
char str[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &(ia->sin_addr), str, INET_ADDRSTRLEN);
*/
// loop through all the results and bind to the first we can
for(p = res; p != NULL; p = p->ai_next){
if((sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1){
WARN("socket()");
continue;
}
if(setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, sizeof(int)) == -1){
WARN("setsockopt()");
close(sock);
continue;
}
if(bind(sock, p->ai_addr, p->ai_addrlen) == -1){
WARN("bind()");
close(sock);
continue;
}
break; // if we get here, we must have connected successfully
}
freeaddrinfo(res);
// Listen
if(listen(sock, BACKLOG) == -1){
WARN("listen");
putlog("listen() error");
}
DBG("listen at %s", port);
putlog("listen at %s", port);
return sock;
}
/**
* @brief waitconn
* @param sock - socket fd to accept()
* @param connthread - thread which to run when connection accepted (it's parameter - socket fd)
*/
static void waitconn(int sock, void *(*connthread)(void*)){
// Main loop
while(!global_quit){
socklen_t size = sizeof(struct sockaddr_in);
struct sockaddr_in myaddr;
int newsock;
newsock = accept(sock, (struct sockaddr*)&myaddr, &size);
if(newsock <= 0){
WARN("accept()");
sleep(1);
continue;
}
struct sockaddr_in peer;
socklen_t peer_len = sizeof(peer);
if(getpeername(newsock, (struct sockaddr*)&peer, &peer_len) == -1){
WARN("getpeername()");
close(newsock);
continue;
}
int sockport = -1;
if(getsockname(newsock, (struct sockaddr*)&peer, &peer_len) == 0){
sockport = ntohs(peer.sin_port);
}
char *peerIP = inet_ntoa(peer.sin_addr);
putlog("Got connection from %s @ %d", peerIP, sockport);
DBG("Peer's IP address is: %s (@port %d)\n", peerIP, sockport);
/*if(strcmp(peerIP, ACCEPT_IP) && strcmp(peerIP, "127.0.0.1")){
WARNX("Wrong IP");
close(newsock);
continue;
}*/
pthread_t rthrd;
if(pthread_create(&rthrd, NULL, connthread, (void*)&newsock)){
putlog("Error creating listen thread");
ERR(_("Can't create socket thread"));
}else{
DBG("Thread created, detouch");
pthread_detach(rthrd); // don't care about thread state
}
}
close(sock);
}
// thread working with terminal
static void *termthread(_U_ void *buf){
int sock = opensocket(GP->dbgport);
if(sock < 0){
putlog("Can't open debugging socket @ port %s", GP->dbgport);
ERRX("Can't open debug socket");
}
waitconn(sock, term_thread);
return NULL;
}
static inline void main_proc(){
pthread_t hthrd, termthrd;
// connect to telescope
if(!GP->emulation){
if(!connect_telescope(GP->device, GP->crdsfile)){
ERRX(_("Can't connect to telescope device"));
}
if(pthread_create(&hthrd, NULL, hdrthread, NULL))
ERR(_("Can't create writing thread"));
if(pthread_create(&termthrd, NULL, termthread, NULL))
ERR(_("Can't create terminal thread"));
}
// connect to weather daemon
if(!weatherserver_connect()){
DBG("Can't connect to weather server, will try later");
}
// open socket
int sock = opensocket(GP->port);
if(sock < 0){
putlog("Can't open socket @ port %s", GP->port);
ERRX("Can't open stellarium socket");
}
waitconn(sock, handle_socket);
usleep(10000);
pthread_cancel(hthrd); // cancel reading thread
pthread_cancel(termthrd);
pthread_join(hthrd, NULL);
pthread_join(termthrd, NULL);
}
int main(int argc, char **argv){
char *self = strdup(argv[0]);
GP = parse_args(argc, argv);
initial_setup();
signal(SIGTERM, signals); // kill (-15) - quit
signal(SIGKILL, signals); // kill (-9) - quit
signal(SIGHUP, SIG_IGN); // hup - ignore
signal(SIGINT, signals); // ctrl+C - quit
signal(SIGQUIT, signals); // ctrl+\ - quit
signal(SIGTSTP, SIG_IGN); // ignore ctrl+Z
int fd;
if((fd = open(GP->crdsfile, O_WRONLY | O_TRUNC | O_CREAT, 0644)) < 0) // test FITS-header file for writing
ERR(_("Can't open %s for writing"), GP->crdsfile);
close(fd);
printf("Daemonize\n");
#ifndef EBUG // daemonize only in release mode
if(daemon(1, 0)){
putlog("Err: daemon()");
ERR("daemon()");
}
#endif // EBUG
check4running(self, GP->pidfile, NULL);
if(GP->logfile) openlogfile(GP->logfile);
putlog("Starting, master PID=%d", getpid());
#ifndef EBUG
while(1){
childpid = fork();
if(childpid < 0){
putlog("fork() error");
ERR("ERROR on fork");
}
if(childpid){
WARNX(_("Created child with PID %d\n"), childpid);
DBG("Created child with PID %d\n", childpid);
wait(NULL);
WARNX(_("Child %d died\n"), childpid);
DBG("Child %d died\n", childpid);
}else{
prctl(PR_SET_PDEATHSIG, SIGTERM); // send SIGTERM to child when parent dies
main_proc();
return 0;
}
}
#else
main_proc();
#endif
return 0;
}

View File

@@ -0,0 +1 @@
Deprecated (old versions) of daemons; marked for further removal.

View File

@@ -1,4 +1,5 @@
Collect weather data from new meteostation in sqlite3 database. Collect weather data from new meteostation in sqlite3 database.
// This is old version and need to be modificated for working with modern weather daemon)
Parameters: Parameters:

View File

@@ -0,0 +1 @@
[General]

View File

@@ -0,0 +1 @@
-std=c++17

View File

@@ -1,5 +1,204 @@
New version of "Astrosib" dome daemon. # domedaemonastrosib
Based on snippets_library ver. >= 0.3.2 **domedaemonastrosib** is a daemon that controls an [**Astrosib**](https://astrosib.ru/) allsky
Allow more functionality than old one. dome via a serial line. It provides a TCP/UNIX socket interface for clients, integrates with a
weather proxy to enforce safety rules, and generates a FITSstyle header file with current dome
status.
---
## Features
- **Dome open/close** fully open or close the dome
- **Stop movement** immediately stop any ongoing dome motion
- **Independent cover control** open or close only the northern or southern cover
- **Relay control** switch three auxiliary relays (power, light, etc.)
- **Status reporting** cover states, encoder angles, relay states, rain sensor, motor currents,
temperatures
- **Weather integration** automatically closes the dome and prevents opening when weather is bad
or data is stale
- **Manual override** via `SIGUSR1` (forbid) / `SIGUSR2` (allow) signals
- **FITS header file** writes current dome state into a FITSstyle header file (e.g., for later
use by image processing pipelines)
- **Network interface** supports both INET (TCP) and UNIX domain sockets
- **Daemon mode** forks, writes PID file, restarts child on crash
---
## Commandline options
| Option | Argument | Default | Description |
|----------------------|-------------------|-----------------------------------|-------------------------------------------------------------------|
| `-h`, `--help` | | | Show help |
| `-d`, `--device` | *path* | | Full path to serial device (e.g. `/dev/ttyUSB0`) |
| `-n`, `--node` | *string* | `55555` | Node specification: port number for TCP, or path for UNIX socket |
| `-l`, `--logfile` | *path* | | Full path to log file |
| `-u`, `--unix` | | 0 | Use UNIX socket instead of TCP |
| `-v`, `--verbose` | | 0 | Increase verbosity (each `-v` adds 1 level) |
| `-p`, `--pidfile` | *path* | `/tmp/domedaemon.pid` | PID file path |
| `-H`, `--headerfile` | *path* | `/tmp/dome.fits` | Output file for FITSstyle header |
| `-N`, `--domename` | *name* | `Astrosib` | Dome name inserted into the header |
---
## Socket protocol
The daemon listens for textbased commands on the configured socket. Each command returns one or
more lines of output, terminated by newline (`\n`).
### Commands
| Command | Description | Example |
|---------------------------------|----------------------------------------------------------------------------|----------------------------------------------|
| `unixt` | Return servers current UNIX time (seconds with two decimal places) | `unixt``unixt=1704067200.12` |
| `status` | Get dome status in old format (four numbers) | `status``status=3,3,0,0` |
| `statust` | Get dome status in humanreadable format | `statust` → (see example below) |
| `relay1``relay3` | Get/set relay state (0 = off, 1 = on) | `relay1``relay1=1` (if queried without argument) |
| `open` | Fully open dome (only if weather permits and observations not forbidden) | `open` |
| `close` | Fully close dome | `close` |
| `stop` | Immediately stop dome movement | `stop` |
| `half1``half2` | Get/set state of a single cover (0 = closed, 1 = opened) | `half1 0` |
Each setter returns an `OK` answer in case of success or error code like `BADVAL` for bad value of
setter.
### Example `statust` response
```
status=3,3,0,0
operations=permitted
cover1=closed
cover2=closed
angle1=0
angle2=0
relay1=0
relay2=0
relay3=0
reqtime=1779087731.049449921
```
- `operations` can be `permitted` or `forbidden` (manual override).
- `cover1` / `cover2` report `closed`, `opened` or `intermediate`.
- `angle1` / `angle2` are encoder values (degrees).
- `relay1``relay3` show the current state of each relay.
- `reqtime` is the time when the status was last read from the hardware.
---
## Weather integration
The daemon retrieves weather data via the **weather_proxy** shared memory interface (`get_weather_data()`).
Safety rules:
- If `weather.forceoff`, `weather.rain`, or `weather.weather > WEATHER_BAD` → dome is closed and opening is blocked.
- If the weather data is older than **300 seconds** (`WEATHER_LOST`) → treated as lost communication → dome is closed and blocked.
- When weather becomes good again, the daemon automatically resets the `BadWeather` flag and allows normal operation.
The weather is polled every **5 seconds** (`WEATH_POLL`).
---
## Signal handling
| Signal | Effect (in child process) |
|----------|------------------------------------------------------|
| `SIGUSR1`| Forbid observations close dome and block open |
| `SIGUSR2`| Allow observations remove manual block |
| `SIGTERM`| Stop the daemon and remove PID file |
| `SIGINT` | Same as `SIGTERM` |
| `SIGHUP` | Same as `SIGTERM` |
---
## FITS header file
The daemon writes a text file (default `/tmp/dome.fits`) with **FITSlike** keyword/value pairs.
The file is updated every polling cycle (every 5 seconds) and can be used by external pipelines to record dome state.
Example content:
```
DOME = 'Astrosib' / Dome manufacturer/name
DOMESTAT= 'idle' / Dome status
DOMECVR1= 'closed' / Dome cover 1 status
DOMECVR2= 'closed' / Dome cover 2 status
DOMEANG1= 0 / Dome cover 1 angle
DOMEANG2= 0 / Dome cover 2 angle
DOMERLY1= 0 / Dome relay1 state
DOMERLY2= 0 / Dome relay2 state
DOMERLY3= 0 / Dome relay3 state
TDOMMEAS= 1779090474.704 / Measurement time: 2026-05-18 10:47:54
```
The file is created atomically using `mkstemp()` + `rename()`.
---
## Building and dependencies
### Dependencies
- [libusefull_macros](https://github.com/eddyem/snippets_library) common macros and helpers
- [libweather_proxy](https://github.com/eddyem/small_tel/tree/master/Daemons/weather_proxy) shared memory weather data
- `pthread`, `libc`
### Build
```bash
git clone --depth=1 https://github.com/eddyem/small_tel.git
cd small_tel/Daemons/domedaemon-astrosib
mkdir build
cd build
cmake ..
make
```
The resulting binary is `domedaemon`.
### Installation
Copy the binary to a suitable location (e.g. `/usr/local/bin`) or run `sudo make install`.
It is recommended to run the daemon as a system service (using init script, e.g. in `/etc/local.d/`)
so that it starts automatically at boot.
---
## Usage example
Start the daemon with a UNIX socket and weatheraware header:
```bash
domedaemon -vv -d /dev/ttyS3 -l /var/log/telescope/domedaemon.log
```
Connect to the socket using `socat`, `nc` or my [`tty_term`](https://github.com/eddyem/tty_term):
```bash
nc localhost 55555
> statust
```
Send `SIGUSR1` to forbid observations (e.g. before maintenance):
```bash
killall -USR1 domedaemon
```
---
## Notes
- The serial protocol is specific to Astrosib hardware (commands like `STATUS`, `OPENDOME`,
`CLOSEDOME`, `STOPDOME`, `SHUTTERMOVEDEG`, `SWITCHTOGGILE` are hardcoded).
- Encoder values are reported as raw integers; interpretation depends on the physical setup.
- The daemon polls the dome every **5 seconds** (`T_INTERVAL`). During that interval it also
processes client requests and checks weather.
- If the serial device becomes unresponsive, the status will return an error and the header will
not be updated.
---
## License
**GNU General Public License v3.0** or later.
See the `LICENSE` file in repository's root directory or <http://www.gnu.org/licenses/> for details.

View File

@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE QtCreatorProject> <!DOCTYPE QtCreatorProject>
<!-- Written by QtCreator 19.0.1, 2026-05-15T14:43:04. --> <!-- Written by QtCreator 19.0.1, 2026-05-18T10:54:40. -->
<qtcreator> <qtcreator>
<data> <data>
<variable>EnvironmentId</variable> <variable>EnvironmentId</variable>

View File

@@ -1,3 +1,4 @@
Readme.md
astrosib_proto.h astrosib_proto.h
dome.c dome.c
dome.h dome.h

View File

@@ -137,7 +137,6 @@ int main(int argc, char **argv){
signal(SIGINT, signals); signal(SIGINT, signals);
signal(SIGQUIT, signals); signal(SIGQUIT, signals);
signal(SIGTSTP, SIG_IGN); signal(SIGTSTP, SIG_IGN);
signal(SIGHUP, signals);
signal(SIGUSR1, SIG_IGN); signal(SIGUSR1, SIG_IGN);
signal(SIGUSR2, SIG_IGN); signal(SIGUSR2, SIG_IGN);
#ifndef EBUG #ifndef EBUG

View File

@@ -259,6 +259,7 @@ void server_run(sl_socktype_e type, const char *node, sl_tty_t *serial){
} }
} }
} else cmdclosed = 0; } else cmdclosed = 0;
sleep(1);
} }
sl_sock_delete(&s); sl_sock_delete(&s);
ERRX("Server handlers thread is dead"); ERRX("Server handlers thread is dead");

View File

@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE QtCreatorProject> <!DOCTYPE QtCreatorProject>
<!-- Written by QtCreator 19.0.1, 2026-05-15T14:02:48. --> <!-- Written by QtCreator 19.0.1, 2026-05-18T11:16:57. -->
<qtcreator> <qtcreator>
<data> <data>
<variable>EnvironmentId</variable> <variable>EnvironmentId</variable>

View File

@@ -0,0 +1,219 @@
# domedaemon_baader
**domedaemon_baader** is a daemon that controls a [**Baader
Planetarium**](https://www.baader-planetarium.com/) allsky dome via a serial line. It provides a
TCP/UNIX socket interface for clients, integrates with a weather proxy to enforce safety rules, and
generates a FITSstyle header file with current dome status and weather sensor data.
---
## Features
- **Dome open/close** fully open or close the dome
- **Stop movement** immediately stop any ongoing dome motion
- **Weather sensor integration** reads rain/cloud status from the domes internal sensor
- **Error reporting** reports rain, timeout, and powerloss error codes
- **Weather proxy integration** automatically closes the dome and blocks opening when external
weather is bad or data is stale
- **Manual override** via `SIGUSR1` (forbid) / `SIGUSR2` (allow) signals
- **FITS header file** writes current dome state and weather sensor status into a FITSstyle
header file (e.g., for later use by image processing pipelines)
- **Network interface** supports both INET (TCP) and UNIX domain sockets
- **Daemon mode** forks, writes PID file, restarts child on crash
---
## Commandline options
| Option | Argument | Default | Description |
|----------------------|-------------------|---------------------------------|----------------------------------------------------------------------------|
| `-h`, `--help` | | | Show help |
| `-d`, `--serialdev` | *path* | | Full path to serial device (e.g. `/dev/ttyS1`) |
| `-n`, `--node` | *string* | | Node specification: IP, `name:IP`, or path for UNIX socket. For anonymous UNIX socket use `\0path` or `@path`. |
| `-l`, `--logfile` | *path* | | Full path to log file |
| `-u`, `--unixsock` | | 0 | Use UNIX socket instead of INET |
| `-v`, `--verbose` | | 0 | Increase verbosity (each `-v` adds 1 level; 0: only errors, 1: +warnings, 2: +messages, 3: +debug info) |
| `-p`, `--pidfile` | *path* | `/tmp/domedaemon.pid` | PID file path |
| `-H`, `--headerfile` | *path* | `/tmp/dome.fits` | Output file for FITSstyle header |
| `-N`, `--domename` | *name* | `Baader` | Dome name inserted into the header |
| `-b`, `--baudrate` | *speed* | 9600 | Serial baud rate |
| `-T`, `--sertmout` | *microseconds* | 5000 | Serial read timeout (µs) |
| `-m`, `--maxclients` | *number* | 2 | Maximum number of simultaneously connected clients |
---
## Socket protocol
The daemon listens for textbased commands on the configured socket. Each command returns one or
more lines of output, terminated by newline (`\n`).
### Commands
| Command | Description | Example |
|---------------------------------|-----------------------------------------------------------------------------|----------------------------------------------|
| `open` | Fully open dome (only if weather permits and observations not forbidden) | `open` |
| `close` | Fully close dome | `close` |
| `stop` | Immediately stop dome movement | `stop` |
| `status` | Get dome status and temperatures | `status` → (see example below) |
| `weather` | Get weather sensor status | `weather``weather=good` |
| `dtime` | Return servers current UNIX time (seconds with milliseconds) | `dtime``UNIXT=1704067200.123` |
| `help` | Show available commands (default handler) | `help` |
Each setter returns an `OK` answer in case of success or error code like `BADVAL` for bad value of
setter.
### Example `status` response
```
status=opened
measuret=1704067200.123
error=closed@timeout@powerloss
FORBIDDEN
BADWEATHER
errored_command=open
```
- `status` can be `opened`, `closed`, `intermediate` or `unknown`.
- `measuret` is the time when the status was last read from the hardware.
- `error` appears when the dome reports an error. It encodes up to three flags:
- `closed` base error (dome closed due to error)
- `@rain` rain sensor triggered
- `@timeout` watchdog timeout
- `@powerloss` power loss detected
- `FORBIDDEN` appears when observations have been manually disabled (`SIGUSR1`).
- `BADWEATHER` appears when weather proxy reports unsafe conditions.
- `errored_command` shows the last command that failed.
---
## Weather integration
The daemon retrieves external weather data via the **weather_proxy** shared memory interface
(`get_weather_data()`).
Safety rules:
- If `weather.forceoff`, `weather.rain`, or `weather.weather > WEATHER_BAD` → dome is closed and opening is blocked.
- If the weather data is older than **300 seconds** (`WEATHER_LOST`) → treated as lost communication → dome is closed and blocked.
- When weather becomes good again, the daemon automatically resets the `BADWEATHER` flag and allows normal operation.
The weather is polled every **5 seconds** (`T_INTERVAL`).
---
## Domeinternal weather sensor
The daemon also reads the domes builtin weather sensor via the `d#ask_wea` command.
Possible states:
- `0``good` (no rain/clouds)
- `1``rain/clouds`
- other → `unknown`
This status is written into the FITS header as `DOMEWEAT`.
---
## Signal handling
| Signal | Effect (in child process) |
|----------|------------------------------------------------------|
| `SIGUSR1`| Forbid observations close dome and block open |
| `SIGUSR2`| Allow observations remove manual block |
| `SIGTERM`| Stop the daemon and remove PID file |
| `SIGINT` | Same as `SIGTERM` |
| `SIGQUIT`| Same as `SIGTERM` |
---
## FITS header file
The daemon writes a text file (default `/tmp/dome.fits`) with **FITSlike** keyword/value pairs.
The file is updated every polling cycle (every 5 seconds) and can be used by external pipelines to
record dome state.
Example content:
```
OPERATIO= 'FORBIDDEN' / Observations are forbidden
DOME = 'Baader' / Dome manufacturer/name
DOMESTAT= 'closed' / Dome status
DOMEWEAT= 'good' / Dome weather sensor status
DOMEECOD= 0 / Dome error code: Rain|Watchdog|Power
TDOMMEAS= 1779091627.907 / Measurement time: 2026-05-18 11:07:07
```
The `OPERATIO` keyword appears only when observations are manually forbidden via `SIGUSR1`.
The file is created atomically using `mkstemp()` + `rename()`.
---
## Building and dependencies
### Dependencies
- [libusefull_macros](https://github.com/eddyem/snippets_library) common macros and helpers
- [libweather_proxy](https://github.com/eddyem/small_tel/tree/master/Daemons/weather_proxy) shared memory weather data
- `pthread`, `libc`
### Build
```bash
git clone --depth=1 https://github.com/eddyem/small_tel.git
cd small_tel/Daemons/domedaemon_baader
make
```
The resulting binary is `domedaemon`.
### Installation
Copy the binary to a suitable location (e.g. `/usr/local/bin`).
It is recommended to run the daemon as a system service (using init script, e.g. in `/etc/local.d/`)
so that it starts automatically at boot.
---
## Usage example
Start the daemon with a TCP local-only socket and weatheraware header:
```bash
domedaemon -d /dev/ttyS2 -l /var/log/telescope/domedaemon.log -vv \
-n localhost:55555 -H /tmp/dome.fitsheader
```
Connect to the socket using `socat`, `nc` or my [`tty_term`](https://github.com/eddyem/tty_term):
```bash
nc localhost 55555
> status
```
Send `SIGUSR1` to forbid observations (e.g. before maintenance):
```bash
killall -USR1 domedaemon
```
Don't send signals USR1/USR2 to father process (its PID stored in pidfile): it simply ignores them.
Send them by `killall` to both processes, or by `kill` to daughter process.
---
## Notes
- The serial protocol is specific to Baader Planetarium hardware. Commands such as `d#opendom`, `d#closdom`, `d#stopdom`, `d#get_dom`, `d#ask_wea`, and `d#warning` are hardcoded in `commands.h`.
- The dome returns numerical values:
- Position codes: `1111` = fully opened, `2222` = fully closed, anything else = intermediate.
- Weather codes: `0` = good, `1` = rain/clouds, other = unknown.
- Error codes are bitencoded: `1` = rain, `10` = timeout, `100` = power loss.
- The daemon polls the dome every **5 seconds** (`T_INTERVAL`). During that interval it also processes client requests and checks external weather.
- If the serial device becomes unresponsive, the status will show `unknown` and the header will not be updated.
---
## License
**GNU General Public License v3.0** or later.
See the `LICENSE` file in repository's root directory or <http://www.gnu.org/licenses/> for details.

View File

@@ -1,3 +1,4 @@
Readme.md
commands.h commands.h
header.c header.c
header.h header.h

View File

@@ -1 +1,2 @@
A simple tool to send/receive coordinates from telescope A simple tool to send/receive coordinates to/from telescope over `10micron_stellarium` daemon.

View File

@@ -0,0 +1,215 @@
# teldaemon_astrosib
**teldaemon_astrosib** is a daemon that controls an [**Astrosib**](https://astrosib.ru/) telescope
equipment via a serial line or virtual serial port over TCP. It provides a TCP/UNIX socket
interface for clients, integrates with a
[`weather_proxy`](https://github.com/eddyem/small_tel/tree/master/Daemons/weather_proxy) to enforce
safety rules, and generates a FITSheader file with current telescope status.
---
## Features
- **Shutter control** open / close
- **Focuser control** absolute move, relative move, stop
- **Cooler control** switch primary mirror cooler on/off
- **Heater control** switch secondary mirror heater on/off
- **Status reporting** shutters state, focuser position, cooler/heater status, mirror and ambient
temperatures
- **Weather integration** automatically closes shutters and prevents opening when weather is bad
or data is stale
- **Manual override** via `SIGUSR1` (forbid) / `SIGUSR2` (allow) signals
- **FITS header file** writes current telescope state into a FITSstyle header file (e.g., for
later use by image processing pipelines)
- **Network interface** supports both INET (TCP) and UNIX domain sockets
- **Daemon mode** forks, writes PID file, restarts child on crash
---
## Commandline options
| Option | Argument | Default | Description |
|----------------------|-------------------|-----------------------------|-----------------------------------------------------------------------------|
| `-h`, `--help` | | | Show help |
| `-v`, `--verbose` | | 0 | Increase verbosity (each `-v` adds 1 level) |
| `-l`, `--logfile` | *path* | | Full path to log file (otherwise stderr) |
| `-n`, `--node` | *string* | | Node specification: IP, `name:IP`, or path for UNIX socket. For anonymous UNIX socket use `\0path` or `@path`. |
| `-u`, `--unixsock` | | 0 | Use UNIX socket instead of INET |
| `-m`, `--maxclients` | *number* | 2 | Maximum number of simultaneously connected clients |
| `-p`, `--pidfile` | *path* | `/tmp/teldaemon.pid` | PID file path |
| `-d`, `--serialdev` | *path* | | Full path to serial device (e.g. `/dev/ttyUSB0`) |
| `-b`, `--baudrate` | *speed* | 9600 | Serial baud rate |
| `-t`, `--sertmout` | *microseconds* | 1000000 (1 sec) | Serial read timeout (µs) |
| `-H`, `--headerfile` | *path* | `/tmp/telescope.fits` | Output file for FITSstyle header |
| `-N`, `--telname` | *name* | `Astro-M (1)` | Telescope name inserted into the header |
| `-M`, `--headermask` | *bitmask* | `0xff` (all bits set) | Mask controlling which information appears in the header. Use `-1` to list bits. |
### Header mask bits (used with `-M`)
| Bit | Description |
|-----|--------------------------|
| 0 | telescope name |
| 1 | focuser status |
| 2 | cooler status |
| 3 | heater status |
| 4 | external temperature |
| 5 | mirror temperature |
| 6 | measurement time |
For example, if you are using an external focuser and want to prevent the possibility of its data
being overwritten by the telescope data, use a mask `-M125` (alternatively: `-M0x7D` or `-M0b1111101`).
---
## Socket protocol
The daemon listens for textbased commands on the configured socket. Each command returns one or
more lines of output, terminated by newline (`\n`).
### Commands
| Command | Description | Example |
|---------------------------------|-----------------------------------------------------------------------------|-----------------------------------|
| `focrel <steps>` | Move focuser relatively (negative = inward, positive = outward) | `focrel = -500` |
| `focabs <position>` | Move focuser to absolute position (0 … 65000) | `focabs = 32000` |
| `focpos` | Get current focuser position | `focpos``focpos=12345` |
| `open` | Open shutters (only if weather permits and observations not forbidden) | `open` |
| `close` | Close shutters | `close` |
| `status` | Get shutters state, temperatures, last error, and safety flags | `status` → (see example below) |
| `focstop` | Immediately stop focuser movement | `focstop` |
| `cooler <0/1>` | Switch primary mirror cooler off (0) or on (1) | `cooler = 1` |
| `heater <0/1>` | Switch secondary mirror heater off (0) or on (1) | `heater = 0` |
| `dtime` | Return servers current UNIX time (seconds with milliseconds) | `dtime``UNIXT=1704067200.123` |
| `help` | Show available commands (default handler) | `help` |
Each setter returns an `OK` answer in case of success or error code like `BADVAL` for bad value of setter.
### Example `status` response
```
status=closed
measuret=1779086249.480
mirrortemp=6.2
ambienttemp=6.3
```
- `status` can be `opened`, `closed`, `intermediate` or `unknown`.
- `measuret` is the time when the status was last read from the hardware.
- `errored_command` appears if the last attempted command failed.
- `FORBIDDEN` appears when observations have been manually disabled (`SIGUSR1`).
- `BADWEATHER` appears when weather proxy reports unsafe conditions.
---
## Weather integration
The daemon retrieves weather data via the **weather_proxy** shared memory interface (`get_weather_data()`).
Safety rules:
- If `weather.forceoff`, `weather.rain`, or `weather.weather > WEATHER_TERRIBLE` → shutters are closed and opening is blocked.
- If the weather data is older than **900 seconds** (`WEATHER_LOST`) → treated as lost communication → shutters are closed and blocked.
- When weather becomes good again, the daemon automatically resets the `BADWEATHER` flag and allows normal operation.
---
## Signal handling
| Signal | Effect (in child process) |
|----------|------------------------------------------------------|
| `SIGUSR1`| Forbid observations close shutters and block open |
| `SIGUSR2`| Allow observations remove manual block |
| `SIGTERM`| Stop the daemon and remove PID file |
| `SIGINT` | Same as `SIGTERM` |
---
## FITS header file
The daemon writes a text file (default `/tmp/telescope.fits`) with **FITSlike** keyword/value
pairs. The file is updated every polling cycle (every 2 seconds) and can be used by external
pipelines to record telescope state.
Example content:
```
TELESCOP= 'Astro-M (1)' / Telescope name
TELSTAT = 'closed' / Telescope shutters' status
TELCOOLR= 0 / Primary mirror cooler status: 0/1 (off/on)
TELHEATR= 0 / Secondary mirror heater status: 0/1 (off/on)
TDOME = 6.3 / In-dome temperature, degC
TMIRROR = 6.0 / Mirror temperature, degC
TTELMEAS= 1779086301.494 / Measurement time: 2026-05-18 09:38:21
```
The file is created atomically using `mkstemp()` + `rename()`.
---
## Building and dependencies
### Dependencies
- [libusefull_macros](https://github.com/eddyem/snippets_library) common macros and helpers
- [libweather_proxy](https://github.com/eddyem/weather_proxy) shared memory weather data
- `pthread`, `libc`
### Build
```bash
git clone --depth=1 https://github.com/eddyem/small_tel.git
cd small_tel/Daemons/teldaemon_astrosib
make
```
The resulting binary is `teldaemon_astrosib`.
### Installation
Copy the binary to a suitable location (e.g. `/usr/local/bin`).
It is recommended to run the daemon as a system service (using init script, e.g. in `/etc/local.d/`)
so that it starts automatically at boot.
---
## Usage example
Start the daemon with a UNIX socket and weatheraware header:
```bash
teldaemon_astrosib -u -n "/var/run/teldaemon.sock" \
-d /dev/ttyUSB0 -b 115200 \
-H /var/state/telescope.fits \
-N "Astrosib-500" -M 0x7f
```
Connect to the socket using `socat`, `nc` or my [`tty_term`](https://github.com/eddyem/tty_term):
```bash
socat UNIX-CONNECT:/var/run/teldaemon.sock -
> status
```
Send `SIGUSR1` to forbid observations (e.g. before maintenance):
```bash
kill -USR1 $(cat /tmp/teldaemon.pid)
```
---
## Notes
- The serial protocol is specific to Astrosib hardware (commands like `FOCUSERGO?`,
`SHUTTEROPEN?1,1,1,1,1`, etc. are hardcoded).
- Focuser absolute position range is **0 … 65000** (values outside this range are ignored).
- The daemon polls the telescope every **2 seconds** (`T_INTERVAL`). During that interval it also
processes client requests and checks weather.
- If the serial device becomes unresponsive, the status will show `unknown` and the header will not
be updated.
---
## License
**GNU General Public License v3.0** or later.
See the `LICENSE` file in repository's root directory or <http://www.gnu.org/licenses/> for details.

View File

@@ -1,3 +1,4 @@
Readme.md
commands.h commands.h
header.c header.c
header.h header.h

View File

@@ -0,0 +1,99 @@
cmake_minimum_required(VERSION 4.0)
set(PROJ meteologger)
set(MINOR_VERSION "1")
set(MID_VERSION "0")
set(MAJOR_VERSION "0")
set(VERSION "${MAJOR_VERSION}.${MID_VERSION}.${MINOR_VERSION}")
project(${PROJ} VERSION ${VERSION} LANGUAGES C)
message("${PROJ} version: ${VERSION}")
option(DEBUG "Compile in debug mode" OFF)
# option()
# default flags
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -W -Wextra -fPIC")
set(CMAKE_COLOR_MAKEFILE ON)
# here is one of two variants: all .c in directory or .c files in list
aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR} SOURCES)
#list(REMOVE_ITEM SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/<file to remove>)
#set(SOURCES list_of_c_files)
# we can change file list
#if(NOT DEFINED something)
# set(SOURCES ${SOURCES} one_more_list)
# add_definitions(-DSOME_DEFS)
#endif()
# cmake -DDEBUG=1 -> debugging
if(DEBUG)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Og -g3 -ggdb -Werror")
add_definitions(-DEBUG)
set(CMAKE_BUILD_TYPE DEBUG)
set(CMAKE_VERBOSE_MAKEFILE "ON")
else()
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -O3 -march=native -fdata-sections -ffunction-sections -flto=auto")
SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,--gc-sections -flto=auto")
set(CMAKE_BUILD_TYPE RELEASE)
endif()
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}")
###### pkgconfig ######
find_package(PkgConfig REQUIRED)
pkg_check_modules(${PROJ} REQUIRED usefull_macros>=0.3.5)
# external modules like OpenMP:
#include(FindOpenMP)
#if(OPENMP_FOUND)
# set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${OpenMP_C_FLAGS}")
# set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS}")
# set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${OpenMP_EXE_LINKER_FLAGS}")
#endif()
# append data from find_package:
#list(APPEND ${PROJ}_INCLUDE_DIRS ${<pkg1>_INCLUDE_DIR} ${<pkg2>_INCLUDE_DIR})
#list(APPEND ${PROJ}_LIBRARIES ${<pkg1>_LIBRARY} ${<pkg2>_LIBRARY})
#list(APPEND ${${PROJ}_LIBRARY_DIRS} ${<pkg1>_LIBRARY_DIRS})
# static library
#set(LIBSRC fd.c weathlib.c)
#set(LIBHEADER weathlib.h)
#add_library(${PROJLIB} STATIC ${LIBSRC})
#set_target_properties(${PROJLIB} PROPERTIES VERSION ${VERSION})
# exe file
add_executable(${PROJ} ${SOURCES})
# another exe, depending on some other files
#add_executable(test_client client.c usefull_macros.c parceargs.c)
# -I
include_directories(${${PROJ}_INCLUDE_DIRS})
# -L
link_directories(${${PROJ}_LIBRARY_DIRS})
# -D
add_definitions(-D_XOPEN_SOURCE=1234 -D_DEFAULT_SOURCE -D_GNU_SOURCE
-DPACKAGE_VERSION=\"${VERSION}\" -DMINOR_VERSION=\"${MINOR_VERSION}\" -DMID_VERSION=\"${MID_VERSION}\"
-DMAJOR_VERSION=\"${MAJOR_VERSION}\")
###### pthreads ######
#find_package(Threads REQUIRED)
#if(THREADS_HAVE_PTHREAD_ARG)
# set_property(TARGET ${PROJ} PROPERTY COMPILE_OPTIONS "-pthread")
# set_property(TARGET ${PROJ} PROPERTY INTERFACE_COMPILE_OPTIONS "-pthread")
#endif()
#if(CMAKE_THREAD_LIBS_INIT)
# list(APPEND ${PROJ}_LIBRARIES "${CMAKE_THREAD_LIBS_INIT}")
#endif()
# target libraries
target_link_libraries(${PROJ} ${${PROJ}_LIBRARIES} ${CMAKE_DL_LIBS})
# install
include(GNUInstallDirs)
install(TARGETS ${PROJ} DESTINATION "bin")
# Script to be executed at installation time (kind of post-intallation script) to
# change the right accesses on the installed files
#INSTALL(SCRIPT inst.cmake)
# subdirs
#add_subdirectory("plugins")

View File

@@ -0,0 +1,140 @@
# meteologger
**meteologger** is a client that collects meteorological data from the
[`weatherdaemon_multimeteo`](https://github.com/eddyem/small_tel/tree/master/Daemons/weatherdaemon_multimeteo)
daemon. It connects to the daemon over a TCP or UNIX socket, periodically requests data from all
available weather stations, and saves the received values into separate files (one per station).
The project is written in C and uses the
[`usefull_macros`](https://github.com/eddyem/snippets_library) library for socket handling,
logging, argument parsing, and helper macros.
## Repository
Source code is located in the [small_tel](https://github.com/eddyem/small_tel) repository under
`Daemons/weather_logger`.
### Dependencies
- Linux (uses Linuxspecific calls: `prctl`, `fork`, `waitpid`, signals)
- CMake ≥ 4.0
- C compiler (GCC, Clang)
- `usefull_macros` library ≥ 0.3.5 (must be installed and discoverable via `pkg-config`)
### Building
```bash
git clone --depth=1 https://github.com/eddyem/small_tel.git
cd small_tel/Daemons/weather_logger
mkdir build && cd build
cmake .. # or -DDEBUG=on for debug build
make
```
The executable `meteologger` will be placed in `build/` (or `bin/` after installation).
### Installation
```bash
su -c "make install"
```
By default the program is installed into `bin` (usually `/usr/local/bin`).
## Usage
```
meteologger -n <node> -o <directory> [options]
```
### Required arguments
| Option | Long form | Description |
|--------|----------------|-------------|
| `-n` | `--node` | Node to connect to: `<host>:<port>` (e.g., `127.0.0.1:5555`) or a UNIX socket path when `-u` is given. |
| `-o` | `--output` | Directory where database files will be stored (must exist and be writable). |
### Optional arguments
| Option | Long form | Default | Description |
|--------|----------------|-----------------------------|-------------|
| `-h` | `--help` | - | Show help and exit. |
| `-u` | `--isunix` | - | Use a UNIX socket instead of TCP. |
| `-l` | `--logfile` | (none) | File to write logs |
| `-p` | `--pidfile` | `/tmp/meteologger.pid` | File where the process PID is written. |
| `-v` | `--verbose` | 0 | Increase logging verbosity (each `-v` raises the level). |
| `-i` | `--interval` | `0.5` | Request interval in seconds. Allowed range: `[0.2, 900]`. |
| `-t` | `--timeout` | `1.0` | Network timeout for server responses (seconds). Allowed range: `[0.1, 30]`. |
### Rotation of database files
The daemon keeps all DB files opened during its work, so for correct log rotation after renaming
all files (like `rename log log00 *.log`) you should send SIGUSR1 or SIGUSR2 to daemon, like
```bash
kill -USR1 $(cat /tmp/meteologger.pid)
```
After receiving of this signal daemon will open new DB files and you will be able to compress old
files.
### Examples
1. Connect to a local daemon on port 5555 and store data in `/var/log/weather`:
```bash
meteologger -n 127.0.0.1:5555 -o /var/log/weather
```
2. Use a UNIX socket `/tmp/weather.sock`, write PID to `/run/meteologger.pid`:
```bash
meteologger -n /tmp/weather.sock -o /data/weather -u -p /run/meteologger.pid
```
3. Enable verbose logging to a file:
```bash
meteologger -n localhost:5555 -o /srv/weather -vv -l /var/log/meteologger.log
```
## Output file format
Files are stored in the directory given by `-o` and are named `weatherXX.log`, where `XX` is a
twodigit station number (from `00` to `99`). If a file already exists for a station (matching the
station name in the header comment), new data is appended.
File structure:
```
# <station_name>
# Station #<number>, format: KEYWORD[level],...
# TIMESTAMP, <key1>[<level1>], <key2>[<level2>], ...
<timestamp>, <value1>, <value2>, ...
```
Example:
```
# WXA100-06 ultrasonic meteostation @ D:/dev/pl2303_0
# Station #0, format: KEYWORD[level],...
# TIMESTAMP, WIND[1], WINDDIR[2], HUMIDITY[1], EXTTEMP[1], PRESSURE[1], PRECIP[3], PRECIPLV[3], PRECRATE[3]
1779369905, 0.50, 120.70, 76.90, 8.40, 590.00, 1, 374.70, 0.00
1779369907, 0.60, 128.20, 76.90, 8.40, 590.00, 1, 374.70, 0.00
1779369909, 0.70, 130.30, 76.90, 8.40, 590.00, 1, 374.70, 0.00
...
```
- First line: comment with station name.
- Second line: station number and format description.
- Third line: column headers: `TIMESTAMP` followed by keys with their levels.
- Following lines: data Unix timestamp (integer) and values (floatingpoint, integer or string).
-----
## License
Copyright © 2026 Edward V. Emelianov.
**GNU General Public License v3.0** or later.
See the `LICENSE` file in repository's root directory or [http://www.gnu.org/licenses/](http://www.gnu.org/licenses/)
for details.

View File

@@ -0,0 +1,141 @@
/*
* This file is part of the meteologger project.
* Copyright 2026 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
#include <linux/prctl.h>
#include <signal.h>
#include <stdatomic.h>
#include <sys/prctl.h>
#include <sys/wait.h>
#include <unistd.h>
#include <usefull_macros.h>
#include "parseargs.h"
#include "server.h"
static volatile atomic_int catchsig = 0;
static pid_t childpid = 0;
void signals(int signo){
signal(signo, SIG_IGN);
if(catchsig == 0){
DBG("superloop not inited");
exit(signo);
}
if(0 == childpid){
if(signo == SIGUSR1){ // reload logs after rotating
DBG("Got USR1 -> reinit logs");
if(!reinit_logs()){
stop_server();
catchsig = signo;
}else signal(signo, signals);
}else{ // kill
DBG("Got %d -> kill", signo);
stop_server();
catchsig = signo; // could be 0 or error code / signo
}
}else{ // throw signal to child
if(signo > 0){
kill(childpid, signo);
LOGMSG("Send received signal %d to child", signo);
if(signo != SIGUSR1) catchsig = signo;
else signal(signo, signals);
}else catchsig = signo;
}
}
static void prepare_and_run(glob_pars *G){
if(!G) return;
sl_socktype_e stype = (G->isunix) ? SOCKT_UNIX : SOCKT_NET;
set_reqinterval(G->req_interval);
set_nettimeout(G->net_timeout);
DBG("Run server");
run_server(G->node, stype, G->bddir);
DBG("Server died");
}
int main(int argc, char **argv){
sl_init();
glob_pars *G = parseargs(&argc, &argv);
if(!G) return 1;
sl_check4running(NULL, G->pidfile);
signal(SIGTERM, signals);
signal(SIGINT, signals);
signal(SIGQUIT, signals);
signal(SIGPIPE, SIG_IGN); // for sockets
signal(SIGSTOP, SIG_IGN);
signal(SIGTSTP, SIG_IGN);
signal(SIGUSR1, signals); // reload DB
signal(SIGUSR2, signals); // reload DB
#ifndef EBUG
if(sl_daemonize()) ERRX("Can't daemonize");
#endif
if(G->logfile){
sl_loglevel_e lvl = LOGLEVEL_ERR + G->verb;
if(lvl >= LOGLEVEL_AMOUNT) lvl = LOGLEVEL_AMOUNT - 1;
DBG("Loglevel: %d", lvl);
OPENLOG(G->logfile, lvl, 1);
}
LOGMSG("Started");
#ifndef EBUG
catchsig = INT_MAX; // now `signals` won't run exit()
while(catchsig == INT_MAX){ // guard for dead processes
childpid = fork();
if(childpid){
LOGDBG("create child with PID %d\n", childpid);
DBG("Created child with PID %d\n", childpid);
pid_t expid = 0;
while(catchsig == INT_MAX){
expid = waitpid(childpid, NULL, WNOHANG);
if(expid < 0){
LOGERR("waitpid() returns -1; exit");
ERRX("waitpid() returns -1; exit");
}
if(expid == childpid) break;
usleep(50000);
}
WARNX("Child %d died\n", childpid);
LOGWARN("Child %d died\n", childpid);
sleep(1);
}else{
prctl(PR_SET_PDEATHSIG, SIGTERM); // send SIGTERM to child when parent dies
break; // go out to normal functional
}
}
#else
// init for DEBUG mode
catchsig = INT_MAX;
#endif
if(childpid){
LOGERR("Main process exits with status %d", catchsig);
if(G->pidfile) unlink(G->pidfile);
}else{
pid_t self = getpid();
prepare_and_run(G);
if(catchsig == INT_MAX){
LOGERR("Child process %d died", self);
catchsig = 0; // like normal exit
}else LOGERR("Child process %d exits with status %d", self, catchsig);
; // cleanup child here
#ifdef EBUG
if(G->pidfile) unlink(G->pidfile); // unlink PID-file in debug-mode
#endif
usleep(10000); // wait processes to die
}
return catchsig;
}

View File

@@ -0,0 +1 @@
-std=c23

View File

@@ -0,0 +1,3 @@
#define _XOPEN_SOURCE=1234
#define _DEFAULT_SOURCE
#define _GNU_SOURCE

View File

@@ -0,0 +1 @@
[General]

View File

@@ -0,0 +1 @@
-std=c++23

View File

@@ -0,0 +1,7 @@
CMakeLists.txt
Readme.md
main.c
parseargs.c
parseargs.h
server.c
server.h

View File

@@ -0,0 +1,79 @@
/*
* This file is part of the meteologger project.
* Copyright 2026 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
#include <string.h>
#include <usefull_macros.h>
#include "parseargs.h"
#include "server.h"
#define DEFAULT_PID "/tmp/meteologger.pid"
#define MIN_REQ_INTERVAL (0.2)
#define MAX_REQ_INTERVAL (900.)
#define MIN_NET_TMOUT (0.1)
#define MAX_NET_TMOUT (30.)
static int help;
static glob_pars G = {
.pidfile = DEFAULT_PID,
.req_interval = 0.5,
.net_timeout = 1.,
};
static sl_option_t opts[] = {
{"help", NO_ARGS, NULL, 'h', arg_int, APTR(&help), "show this help"},
{"node", NEED_ARG, NULL, 'n', arg_string, APTR(&G.node), "node to connect (host:port or UNIX socket name)"},
{"logfile", NEED_ARG, NULL, 'l', arg_string, APTR(&G.logfile), "save logs to file"},
{"pidfile", NEED_ARG, NULL, 'p', arg_string, APTR(&G.pidfile), "pidfile name (default: " DEFAULT_PID ")"},
{"isunix", NO_ARGS, NULL, 'u', arg_string, APTR(&G.isunix), "use UNIX socket instead of network"},
{"verbose", NO_ARGS, NULL, 'v', arg_none, APTR(&G.verb), "verbose level (each -v increases)"},
{"output", NEED_ARG, NULL, 'o', arg_string, APTR(&G.bddir), "output directory to store database"},
{"interval",NEED_ARG, NULL, 'i', arg_double, APTR(&G.req_interval), "weather request interval, s (min: 0.2, max: 900)"},
{"timeout", NEED_ARG, NULL, 't', arg_double, APTR(&G.net_timeout),"timeout for server's answer, s (min: 0.1, max: 30)"},
end_option
};
glob_pars *parseargs(int *argc, char ***argv){
sl_parseargs(argc, argv, opts);
if(help){
sl_showhelp(-1, opts);
return NULL;
}
if(!G.node) ERRX("Point node to correct");
if(!G.bddir) ERRX("Need to know path to save DB");
if(!checkDBpath(G.bddir)) ERRX("Can't create logs in %s", G.bddir);
// remove trailing '/'
int eol = strlen(G.bddir) - 1;
DBG("eol=%d", eol);
while(eol > 0){ // don't remove leading slash in case of "/"
DBG("before: %s", G.bddir);
if(G.bddir[eol] == '/') G.bddir[eol] = 0;
else break;
DBG("after: %s", G.bddir);
--eol;
}
if(G.req_interval < MIN_REQ_INTERVAL || G.req_interval > MAX_REQ_INTERVAL)
ERRX("Wrong time interval %g, should be in [%g, %g]", G.req_interval, MIN_REQ_INTERVAL, MAX_REQ_INTERVAL);
if(G.net_timeout < MIN_NET_TMOUT || G.net_timeout > MAX_NET_TMOUT)
ERRX("Wrong network timeout %g, should be in [%g, %g]", G.net_timeout, MIN_NET_TMOUT, MAX_NET_TMOUT);
if(G.logfile){
if(*G.logfile != '/') ERRX("Logging file path should be absolute!");
}
return &G;
}

View File

@@ -0,0 +1,32 @@
/*
* This file is part of the meteologger project.
* Copyright 2026 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
#pragma once
typedef struct{
int isunix; // use UNIX-sockets instead of net
int verb; // verbocity level
double req_interval; // requests interval
double net_timeout; // network timeout
char *bddir; // directory to store all data
char *logfile; // logfile name
char *node; // node of server
char *pidfile; // pidfile name
} glob_pars;
glob_pars *parseargs(int *argc, char ***argv);

View File

@@ -0,0 +1,689 @@
/*
* This file is part of the meteologger project.
* Copyright 2026 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
#include <dirent.h>
#include <fcntl.h>
#include <regex.h>
#include <stdatomic.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "server.h"
// max available delta for timestamp if it's in future to current time
// USE NTP everywhere!!11111
#define TIME_IN_FUTURE_MAX (60)
// some "standard" keys from server
static const char *key_pluginname = "PLUGIN";
static const char *key_nvalues = "NVALUES";
static const char *key_timestamp = "TWEATH";
// sensor's db filename mask: DBpath/weatherXX.log
static const char *dbfilename_mask = "%s/weather%02d.log";
// and search regex inside DB directory
static const char *dbfilename_regex = "^weather[[:digit:]]{2}\\.log$";
static volatile atomic_bool isrunning = true;
static volatile atomic_bool logreinit = false;
static double req_interval = 0.5; // request interval, s
static double net_timeout = 1.; // timeout for server's answer, s
static char *DBpath = NULL; // path to storage
typedef struct{
int fd; // log file descriptor
int idx; // index of station for requests
int nvalues; // maximal amount of values
bool initialized; // `sensor` is fully initialized
char path[PATH_MAX];// path to file
char *sensname; // sensor's name
char **keys; // keyword names for header and index in string
int *levels; // array of `weather level` for each keyword
time_t lasttimestamp;// timestamp of last received data
char buf[BUFSIZ]; // string buffer for file writing operations
int buflen; // current length of `buf`
int lastvalidx; // index of last value stored in `buf`
} senslog_t;
static int Nsensors = 0; // amount of sensors for logging
static senslog_t *sensors = NULL; // array of files for logging
// commands for communication with server
typedef enum{
CMD_LIST,
CMD_GET,
CMD_CHKLEVEL,
CMD_TIME,
CMD_AMOUNT
} req_commands;
static const char *commands[CMD_AMOUNT] = {
[CMD_LIST] = "list",
[CMD_GET] = "get",
[CMD_CHKLEVEL] = "chklevel",
[CMD_TIME] = "time",
};
static void delete_senskeys(senslog_t *sensor){
if(!sensor) return;
for(int j = 0; j < sensor->nvalues; ++j)
FREE(sensor->keys[j]);
FREE(sensor->keys);
sensor->nvalues = 0;
}
static void sensors_delete(){
if(!sensors) return;
for(int i = 0; i < Nsensors; ++i){
senslog_t *sensor = &sensors[i];
if(sensor->fd > -1){
close(sensor->fd);
sensor->fd = -1;
}
delete_senskeys(sensor);
FREE(sensor->levels);
FREE(sensor->sensname);
}
FREE(sensors);
}
// stop server process
void stop_server(){
FNAME();
isrunning = false;
}
// set request interval to this value
void set_reqinterval(double dt){
req_interval = dt; // all checking is in `parseargs.c`
}
// set network timeout
void set_nettimeout(double dt){
net_timeout = dt;
}
/**
* @brief write2fd - tries to write into file; in case of error close this file and set `sensor->fd=-1`
* @param sensor - "sensor" to write
* @param str - input string
* @param len - length of string
* @return true if all OK
*/
static bool write2fd(senslog_t *sensor, const char *str, size_t len){
if(!sensor || !str || len < 1) return false;
const char *ptr = str;
size_t written = 0;
while(len){
ssize_t l = write(sensor->fd, ptr, len);
if(l < 0) break;
len -= l;
ptr += l;
}
if(written != len){
LOGERR("Can't write '%s' to file %s: %s", str, sensor->path, strerror(errno));
WARNX("Can't write data to file");
close(sensor->fd);
sensor->fd = -1;
return false;
}
return true;
}
/**
* @brief send_request - send request to server
* @param cmd - command index
* @return true if OK, false if disconnected
*/
static bool send_request(sl_sock_t *sock, const char *req){
if(sl_sock_sendstrmessage(sock, req) < 1){
WARNX("Can't send request '%s'", req);
LOGERR("Can't send request '%s'", req);
return false;
}
return true;
}
/**
* @brief get_answer_line - read one line of server's answer with timeout
* @param sock - socket to read
* @param buf - input buffer
* @param buflen - its length
* @return length of receiving data, 0 if nothing received, -1 in case of error (and clear all sensor's list)
*/
static ssize_t get_answer_line(sl_sock_t *sock, char *buf, size_t buflen){
FNAME();
double t0 = sl_dtime();
DBG("tstart=%g", t0);
ssize_t len = -1;
while(sl_dtime() - t0 < net_timeout){
len = sl_sock_readline(sock, buf, buflen-1);
if(len > 0) break;
else if(len < 0){
WARNX("Seems like server disconnected");
LOGWARN("Error reading server answer, disconnected?");
sensors_delete();
}
}
DBG("len=%zd, tend=%g", len, sl_dtime());
return len;
}
// reinit logs at start or after rotating
// @return false if failed
bool reinit_logs(){
FNAME();
LOGMSG("Got 'reinit' command");
logreinit = true;
return true;
}
bool checkDBpath(const char *path){
struct stat path_stat;
if(stat(path, &path_stat)){
WARNX("Can't stat() %s", path);
return false; // `stat` failed
}
if(!S_ISDIR(path_stat.st_mode)){
WARNX("%s isn't a directory", path);
return false; // not a directory
}
// now check if we can write there
if(access(path, W_OK)){
WARNX("Can't write to %s", path);
return false;
}
return true;
}
// find if this sensor already have opened BD;
// if have, modify sensor->fd and sensor->path, open file for appending and return `true`
static bool find_old_file(senslog_t *sensor){
if(sensor->fd > -1){
DBG("found opened file %s with fd %d -> close", sensor->path, sensor->fd);
close(sensor->fd);
sensor->fd = -1;
}
LOGMSG("Try to find old file");
regex_t regex;
// Compile regex
if(regcomp(&regex, dbfilename_regex, REG_EXTENDED | REG_NOSUB) != 0){
LOGERR("find_old_file(): error in regcomp(), %s", strerror(errno));
WARNX("regcomp()");
return false;
}
bool ret = false;
DIR *d = opendir(DBpath);
if(d){
struct dirent *dir;
while((dir = readdir(d))){
// Check if filename matches regex
if(regexec(&regex, dir->d_name, 0, NULL, 0) == 0){
DBG("Found: %s", dir->d_name);
char line[BUFSIZ];
snprintf(sensor->path, PATH_MAX, "%s/%s", DBpath, dir->d_name);
FILE *fp = fopen(sensor->path, "r");
if(!fp){
LOGWARN("Cannot open %s for reading: %s", sensor->path, strerror(errno));
DBG("Can't open");
continue;
}
if(fgets(line, sizeof(line), fp) == NULL){
LOGWARN("Found empty BD file %s - WTF???", sensor->path);
fclose(fp);
continue;
}
fclose(fp);
int len = strlen(line);
if(len > 0 && line[len-1] == '\n') line[len-1] = 0; // remove trailing newline
if(line[0] != '#' || line[1] != ' '){ // should starts from comment with station's name
LOGWARN("Found broken database file: %s", sensor->path);
continue;
}
const char *stname = line + 2; // station name from comment
DBG("Check name: '%s' and '%s'", stname, sensor->sensname);
if(0 == strcmp(stname, sensor->sensname)){ // good, we found this file!
DBG("Found existant file %s -> append to it", sensor->path);
int newfd = open(sensor->path, O_WRONLY | O_APPEND);
if(newfd < 0){
LOGWARN("Can't open existant BD file %s for append, try to create new", sensor->path);
continue;
}
LOGMSG("Station '%s': opened existant DB file '%s'", sensor->sensname, sensor->path);
sensor->fd = newfd;
ret = true;
break;
}
}
}
closedir(d);
}else{
LOGERR("Can't open %s: %s", DBpath, strerror(errno));
}
if(sensor->fd < 0) LOGERR("Error opening DB file for '%s'", sensor->sensname);
regfree(&regex);
return ret;
}
// create new database file in `DBpath`
// `sensor` obligate to be fully initialized
static bool create_db_file(senslog_t *sensor){
FNAME();
if(!sensor || !sensor->initialized){
WARNX("create_db_file() should be called only with fully initialized `sensor`");
return false;
}
LOGMSG("Try to create new DB file for '%s'", sensor);
int num = sensor->idx; // try to start from sensor's index
for(; num <= 99; ++num){
snprintf(sensor->path, PATH_MAX, dbfilename_mask, DBpath, num);
DBG("Try to create %s", path);
if(access(sensor->path, F_OK) != 0) break; // no such file
}
if(num > 99){
LOGERR("Can't find free filename for station '%s', all numbers from 0 to 99 are busy! WTF???",
sensor->sensname);
WARNX("No free numbers for sensors");
return false;
}
// create and open write-only
int newfd = open(sensor->path, O_WRONLY | O_CREAT, 0644);
if(newfd < 0){
LOGERR("Can't open file %s for station %s: %s", sensor->path, sensor->sensname, strerror(errno));
WARNX("Can't open %s", sensor->path);
return false;
}
DBG("OK, %s opened, try to write header", path);
sensor->fd = newfd;
char path[2*PATH_MAX];
ssize_t len = snprintf(path, 2*PATH_MAX, "# %s\n", sensor->sensname);
if(!write2fd(sensor, path, len)) return false;
len = snprintf(path, 2*PATH_MAX, "# Station #%d, format: KEYWORD[level],...\n# TIMESTAMP, ", sensor->idx);
if(!write2fd(sensor, path, len)) return false;
char *ptr = path;
len = 0;
for(int i = 0; i < sensor->nvalues; ++i){
ssize_t L = snprintf(ptr, 2*PATH_MAX-len, "%s%s[%d]", i ? ", " : "", sensor->keys[i], sensor->levels[i]);
len += L;
ptr += L;
}
len += snprintf(ptr, 2*PATH_MAX-len, "\n");
if(!write2fd(sensor, path, len)) return false;
DBG("%s now have descriptor %d: %s", sensor->sensname, newfd, sensor->path);
LOGMSG("OK, data for '%s' now will be stored @ '%s'", sensor->sensname, sensor->path);
return true;
}
/**
* @brief get_sensor_keys - fill `sensor->keys` and `sensor->levels` using `chklevel` request
* @param sensor - "sensor" with inited `nvalues`, `idx` and `sensname`; allocated `keys` and `levels`
* @param sock - socket for request
* @return
*/
static bool get_sensor_keys(senslog_t *sensor, sl_sock_t *sock){
if(!sensor || !sock) return false;
char str[BUFSIZ], key[SL_KEY_LEN], value[SL_VAL_LEN];
LOGMSG("Send request to receive all keys for sensors");
snprintf(str, BUFSIZ, "%s=%d\n", commands[CMD_CHKLEVEL], sensor->idx);
if(!send_request(sock, str)){
LOGERR("Can't send request '%s'", commands[CMD_CHKLEVEL]);
return false;
}
ssize_t got = -1;
int valueidx = 0;
while(valueidx < sensor->nvalues && (got = get_answer_line(sock, str, BUFSIZ)) > 0 ){
DBG("valueidx=%d, nvalues=%d, got answer: %s", valueidx, sensor->nvalues, str);
if(2 != sl_get_keyval(str, key, value)){
LOGWARN("Wrong answer for `chklevel`: %s", str);
continue;
}
DBG("key=%s", key);
int sensidx;
if(2 != sscanf(key, "[%[^]]][%d]", str, &sensidx)){
DBG("header? '%s' (str=%s)", key, str);
continue; // omit two heading lines: `PLUGIN` and `NVALUES`
}
DBG("str=%s, sensidx=%d", str, sensidx);
if(sensor->idx != sensidx){
LOGWARN("Got wrong key answer for sensor with idx=%d: '%s'", sensor->idx, key);
continue;
}
// OK - it's our value, increment number and fill name
sensor->keys[valueidx] = strdup(str);
sensor->levels[valueidx] = atoi(value);
DBG("now sensor->keys[%d]=%s, levels=%d", valueidx, sensor->keys[valueidx], sensor->levels[valueidx]);
++valueidx;
}
if(got < 0 || valueidx != sensor->nvalues) return false;
sensor->initialized = true;
sensor->lastvalidx = -1;
return true;
}
// prepare BD files and fill `sensors[i].fd` fields; make header in new file or move write pointer to the end of existant
// `sensors` should be prepared already
// this function called at start and on any logs reinit
static bool prepare_files(sl_sock_t *sock){
if(!sock || !DBpath || Nsensors < 1) return false;
LOGMSG("Prepare files for DB");
for(int i = 0; i < Nsensors; ++i){
senslog_t *sensor = &sensors[i];
if(!sensor->initialized && !get_sensor_keys(sensor, sock)) return false;
DBG("Check if there's something for sensor[%d]", i);
if(!find_old_file(sensor)){ // create new file
DBG("Nothing found, try to create new");
if(!create_db_file(sensor)){
DBG("Oops: can't create");
return false;
}
}
sensor->buflen = 0;
sensor->lastvalidx = -1;
}
DBG("All ready!");
return true;
}
static bool analyse_list(sl_sock_t *sock){
FNAME();
char str[BUFSIZ], key[SL_KEY_LEN], value[SL_VAL_LEN];
ssize_t got;
while((got = get_answer_line(sock, str, BUFSIZ)) > 0){
DBG("Got answer: %s", str);
if(2 != sl_get_keyval(str, key, value)){
LOGWARN("Wrong answer from meteodaemon for 'list' request: %s", str);
continue;
}
DBG("key: '%s', value: '%s'", key, value);
int idx;
// we don't need `str` now and can use it again
if(2 != sscanf(key, "%[^[][%d]", str, &idx)){
LOGWARN("Wrong key format: '%s'", key);
continue;
}
DBG("Got key '%s' with idx=%d", str, idx);
if(Nsensors <= idx){
int oldN = Nsensors;
Nsensors = idx + 1;
senslog_t *old_sensors = sensors;
sensors = realloc(sensors, Nsensors * sizeof(senslog_t));
if(!sensors){
sensors = old_sensors; // restore old pointer instead of NULL
sensors_delete();
LOGERR("analyse_list(): error in realloc()");
WARNX("analyse_list(): error in realloc()");
return false;
}
bzero(&sensors[oldN], sizeof(senslog_t)*(Nsensors - oldN));
}
senslog_t *sensor = &sensors[idx];
if(0 == strcmp(str, key_pluginname)){ // found plugin name -> fill this field
if(sensor->sensname) free(sensor->sensname);
sensor->sensname = strdup(value);
sensor->idx = idx;
sensor->fd = -1; // not inited yet
DBG("name[%d]=%s", idx, sensor->sensname);
}else if(0 == strcmp(str, key_nvalues)){
int nvalues = atoi(value);
if(nvalues < 1){
LOGWARN("wrong server's responce for sensor[%d] values amount: %d", idx, nvalues);
continue;
}
if(sensor->nvalues) delete_senskeys(sensor);
sensor->nvalues = nvalues;
DBG("sensor[%d] have %d values", idx, sensor->nvalues);
sensor->keys = MALLOC(char*, nvalues); // prepare empty array for keywords
sensor->levels = MALLOC(int, nvalues);
}
}
if(got < 0) return false; // disconnection?
// now check all we got
if(Nsensors < 1){
LOGWARN("Found 0 sensors in server's answer");
WARNX("Found 0 sensors in server's answer");
return false;
}
bool ans = true;
for(int i = 0; i < Nsensors; ++i){
senslog_t *sensor = &sensors[i];
DBG("Check sensor %s with values %d", sensor->sensname, sensor->nvalues);
if(sensor->nvalues < 1){
LOGWARN("Zero keys for station %s", sensor->sensname);
ans = false; break;
}else LOGMSG("Found station '%s' with %d keys", sensor->sensname, sensor->nvalues);
}
if(ans) ans = prepare_files(sock);
if(ans == false) sensors_delete();
return ans;
}
// prepare DB files at start
static bool prepare_logfiles(sl_sock_t *sock, const char *path){
FNAME();
char buf[PATH_MAX];
if(DBpath) return false; // already inited??
if(!checkDBpath(path)) return false;
DBpath = strdup(path);
if(!DBpath){
WARN("strdup()");
return false;
}
DBG("Store files in %s; send `list` request", DBpath);
LOGMSG("Store files in %s; send `list` request", DBpath);
snprintf(buf, 255, "%s\n", commands[CMD_LIST]);
if(!send_request(sock, buf)){
LOGERR("Can't send inited request");
return false;
}
// now we have an answer: 2*N strings a la "PLUGIN[i]=...\nNVALUES[i]=...\n" ->
// prepare `sensors` and try to find opened files like `sensorXX.log`
if(!analyse_list(sock)) return false;
return true;
}
// send `get=x` request for each sensor; return true if all sent OK
static bool send_get_req(sl_sock_t *sock){
char str[128];
if(!sock || !sensors || Nsensors < 1) return false;
for(int i = 0; i < Nsensors; ++i){
if(sensors[i].nvalues < 1) continue;
snprintf(str, 128, "%s=%d\n", commands[CMD_GET], sensors[i].idx);
if(!send_request(sock, str)) return false;
}
return true;
}
// get answers and fill database
// we consider that answers comes in sequence order, from least sensno to timestamp
// @return false only in case of error
static bool poll_server_answers(sl_sock_t *sock){
char str[BUFSIZ], key[SL_KEY_LEN], value[SL_VAL_LEN];;
ssize_t len = sl_sock_readline(sock, str, BUFSIZ-1);
if(len < 0) return false; // error
else if(len == 0) return true; // nothing to read
DBG("Got line: '%s'", str);
int sensidx;
if(2 != sl_get_keyval(str, key, value) || 2 != sscanf(key, "%[^[][%d]", str, &sensidx)){
WARNX("not key=value");
LOGWARN("Wrong answer for `get`: %s", str);
return false;
}
if(sensidx < 0 || sensidx >= Nsensors){
WARNX("Wrong sensor index");
LOGWARN("Got station with index (%d) out of bounds [0, %d]", sensidx, Nsensors-1);
return false;
}
// omit header
if(0 == strcmp(key_pluginname, str) || 0 == strcmp(key_nvalues, str)) return true;
senslog_t *sensor = &sensors[sensidx];
if(0 == strcmp(key_timestamp, str)){ // check timestamps and write data to disk
time_t ts = (time_t)atol(value);
DBG("Got timestamp: %zd (last timestamp: %zd)", ts, sensor->lasttimestamp);
bool allOK = true;
if(ts > sensor->lasttimestamp){ // don't store old data
time_t curt = time(NULL);
DBG("Timestamp minus current time = %zd", ts - curt);
if(ts > curt && ts - curt > TIME_IN_FUTURE_MAX){
WARNX("timestamp is in future");
LOGWARN("got future timestamp for sensor %d: %ld", sensidx, ts);
allOK = false;
}else{ // all OK - we can save data
if(sensor->lastvalidx > -1){ // only if at least one keyword received
int trailingcommas = sensor->nvalues - sensor->lastvalidx - 2; // amount of commas after our last record
DBG("trailing commas = %d", trailingcommas);
if(trailingcommas > 0){
if(sensor->buflen + 2*trailingcommas > BUFSIZ-1){
WARNX("Sensor's buffer overfull");
LOGWARN("Sensor %s: writing buffer overfull", sensor->idx);
}else{ // write trailing zeros to buffer
for(int i = 0; i < trailingcommas; ++i){
sprintf(sensor->buf + sensor->buflen, ", ");
sensor->buflen += 2;
}
}
}
// write timestamp without error checking
size_t l = snprintf(str, BUFSIZ, "%zd, ", ts);
write2fd(sensor, str, l);
// now throw data to disk
DBG("throw '%s' with length %d to disk", sensor->buf, sensor->buflen);
allOK = write2fd(sensor, sensor->buf, sensor->buflen);
if(allOK){
write2fd(sensor, "\n", 1);
fsync(sensor->fd); // sync last full record
sensor->lasttimestamp = ts;
}
DBG("Data for %d is %swritten to disk", sensor->idx, allOK ? "" : "not ");
}
}
}
// clear gathred data
sensor->buflen = 0;
sensor->lastvalidx = -1;
return allOK;
}
// now we need to find index of current keyword
int idx = 0, nvalues = sensor->nvalues;
for(; idx < nvalues; ++idx){
if(0 == strcmp(str, sensor->keys[idx])) break;
}
DBG("key index=%d", idx);
if(idx == nvalues){
WARNX("Not found in keylist");
LOGWARN("Weird keyword for station %d: '%s'", sensidx, str);
return false;
}
if(sensor->lastvalidx >= idx){
WARNX("Missed timestamp?");
LOGWARN("Missed timestamp for station %d?", sensidx);
sensor->lastvalidx = -1;
sensor->buflen = 0;
return false;
}
// add current raw value to sensor's buffer (there's could be a text fields, so don't make atof
char *comment = strchr(value, '/');
if(comment){
*comment = 0; // remove comment mark
if(comment != value && comment[-1] == ' ') comment[-1] = 0; // remove last space
}
DBG("VALUE: %s", value);
// add spaces if need
int trailingcommas = idx - sensor->lastvalidx - 1; // amount of commas after our last record before current
DBG("Commas: %d", trailingcommas);
if(trailingcommas > 0){
if(sensor->buflen + 2*trailingcommas > BUFSIZ-1){
WARNX("Buffer overfull");
LOGWARN("Sensor %d: writing buffer overfull", sensor->idx);
}else{ // write trailing zeros to buffer
for(int i = 0; i < trailingcommas; ++i){
sprintf(sensor->buf + sensor->buflen, ", ");
sensor->buflen += 2;
}
}
}
int avail = BUFSIZ - sensor->buflen;
if(avail <= 0){
LOGWARN("Sensor %d: writing buffer overfull", sensor->idx);
WARNX("Overfull; clear all");
sensor->lastvalidx = -1;
sensor->buflen = 0;
return false;
}
int n = snprintf(sensor->buf + sensor->buflen, avail, "%s%s",
value, sensor->nvalues-1 != idx ? ", " : "");
if(n >= avail){
// Data would be truncated  handle error or discard
n = avail - 1;
LOGWARN("Sensor %d: writing buffer truncated", sensor->idx);
}
sensor->buflen += n;
sensor->lastvalidx = idx;
DBG("Now buf[%d]=%s", sensor->idx, sensor->buf);
return true;
}
/**
* @brief run_server - run main server: send weather requests and store data
* @param node - node to connect
* @param type - socket type
* @param path - directory where to store data logs
*/
void run_server(const char *node, sl_socktype_e type, const char *path){
if(!node || !path) return;
//char str[BUFSIZ];
sl_sock_t *sock = sl_sock_run_client(type, node, BUFSIZ);
if(!sock){
DBG("Can't connect");
LOGERR("Can't connect to %s", node);
return;
}
if(!prepare_logfiles(sock, path)) return;
DBG("Superloop");
int errctr = 0;
double tlast = 0.;
while(isrunning){
bool allOK = true;
if(logreinit){
if(!prepare_files(sock)) allOK = false;
else logreinit = false;
}
double tnow = sl_dtime();
if(tnow - tlast > req_interval){ // send next requests
DBG("\n\n\nSend next request; deltaT=%g", tnow - tlast);
if(!send_get_req(sock)) allOK = false;
else tlast = tnow;
}
// now poll everything from server
if(!poll_server_answers(sock)) allOK = false;
;
if(!allOK){
if(++errctr > 5){
LOGERR("Too much errors -> exit");
WARNX("Too much errors -> exit");
break;
}
}else errctr = 0;
usleep(1000);
}
if(sock) sl_sock_delete(&sock);
sensors_delete();
}

View File

@@ -0,0 +1,28 @@
/*
* This file is part of the meteologger project.
* Copyright 2026 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <usefull_macros.h>
bool checkDBpath(const char *path);
void stop_server();
void set_reqinterval(double dt);
void set_nettimeout(double dt);
void run_server(const char *node, sl_socktype_e type, const char *path);
bool reinit_logs();

View File

@@ -0,0 +1,245 @@
The `weather_proxy` package offers a lightweight daemon (`weather_proxy`) that receives data from
[`supermeteodaemon`](https://github.com/eddyem/small_tel/tree/master/Daemons/weatherdaemon_multimeteo)
via a TCP or UNIX socket, parses it, and makes it available locally through a
shared memory segment. A client library (`libweather.so`) and a simple command-line utility
(`chkweather`) are also provided to easily retrieve and check weather conditions.
---
## Overview
The main daemon (`weather_proxy`) connects to a running `supermeteodaemon` process, parses the
incoming FITS-header-style data stream, and regularly updates a POSIX shared memory segment
(`/weather_shm`). A named semaphore (`/weather_sem`) protects the shared data. The client library
offers the `get_weather_data()` function to read this shared memory and return the data in a
`weather_data_t` structure. The `chkweather` utility uses this function to quickly check the
current weather status and produce an exit code suitable for scripting.
## Components
The project consists of the following source files:
| File | Description |
|------|-------------|
| `weather_daemon.c` | The main proxy daemon. |
| `weather_client.c` | The client library (`libweather.so`) with `get_weather_data()`. |
| `weather_data.h` | Common data structure and definitions. |
| `chkweather.c` | A simple commandline tool to check weather status. |
| `weather_clt_example.c` | Example usage of the client library. |
| `Makefile` | Builds the daemon, client library, and utilities. |
## Building
The package requires a C compiler (e.g., `gcc`) and the [`usefull_macros` library](https://github.com/eddyem/snippets_library).
To install the latter clone its code and use `cmake`/`make`:
```bash
git clone --depth=1 https://github.com/eddyem/snippets_library
cd snippets_library
mkdir build
cd build
cmake ..
make
su -c "make install"
# or "sudo make install" if you have "sudo" configured
```
Then build the project:
```bash
make
```
This produces:
- `weather_proxy` the main daemon
- `libweather.so` the shared client library
- `chkweather` the weather check utility
- `weather_clt_example` an example client
To install:
```bash
su -c "make install"
```
This copies `libweather.so` to `/usr/local/lib`, installs `weather_data.h` in `/usr/local/include`,
and places the executables in `/usr/local/bin`.
## Usage
### Running the proxy daemon (`weather_proxy`)
```bash
weather_proxy -n <node> [-u] [-l <logfile>] [-p <pidfile>] [-f <fitsheader>] [-v]
```
#### Options
| Option | Description |
|--------|-------------|
| `-n <node>` | Connection endpoint. For TCP: `host:port`. For UNIX sockets: path to socket. Required. |
| `-u` | Use a UNIX socket instead of TCP. |
| `-l <file>` | Write log messages to the specified file. |
| `-p <file>` | PID file (default `/tmp/weather_proxy.pid`). |
| `-f <file>` | Save the latest weather data as a FITSheader file. |
| `-v` | Increase verbosity (can be used multiple times). |
#### Example
Connect to `supermeteodaemon` on TCP port 12345 at `localhost`:
```bash
weather_proxy -n localhost:12345 -v -l /var/log/weather_proxy.log
```
Use a UNIX socket and store the FITS header:
```bash
weather_proxy -n /tmp/superweather.sock -u -f /tmp/latest_weather.header
```
### Checking weather (`chkweather`)
`chkweather` reads the shared memory and prints the current weather data. It returns an exit code
according to the weather condition:
| Exit Code | Meaning |
|-----------|---------|
| `0` | Weather is good observations may start. |
| `1` | Weather is bad cannot start, but ongoing observations may continue. |
| `2` | Weather is terrible close the dome, park. |
| `3` | Weather is prohibited power off equipment, prepare to shut down the computer (or data is too old). |
Example:
```bash
if ./chkweather; then
echo "Conditions are good - starting observations"
else
echo "Bad weather - stopping"
fi
```
### Using the client library in your own code
The library provides a single function:
```c
#include "weather_data.h"
int get_weather_data(weather_data_t *data);
```
It fills the `weather_data_t` structure with the latest weather information. Returns `0` on
success, `-1` on failure.
#### `weather_data_t` structure
```c
typedef struct {
weather_condition_t weather; // condition (0..3)
float windmax; // max wind in last hour (m/s)
float wind; // current wind speed (m/s)
float clouds; // sky "quality" (>2500 = good)
float exttemp; // external temperature (°C)
float pressure; // atmospheric pressure (mmHg)
float humidity; // relative humidity (%)
int rain; // 1 if rain is detected
int forceoff; // forced poweroff flag
time_t last_update; // timestamp of the data
} weather_data_t;
```
The `weather_condition_t` enum:
| Value | Meaning |
|-------|---------|
| `WEATHER_GOOD` (0) | Clear for observations |
| `WEATHER_BAD` (1) | Unfavourable but not critical |
| `WEATHER_TERRIBLE` (2) | Dangerous conditions close and park |
| `WEATHER_PROHIBITED` (3) | Emergency close, park and prepare for powering off |
Example client:
```c
#include "weather_data.h"
#include <stdio.h>
int main() {
weather_data_t wd;
if (get_weather_data(&wd) == 0) {
printf("Weather: %d, Temp: %.1f C\n", wd.weather, wd.exttemp);
}
return 0;
}
```
Compile with:
```bash
gcc -o myclient myclient.c -lweather
```
## Data Flow
1. **supermeteodaemon** collects data from various sensors and outputs it as lines of `KEY=VALUE`
pairs (FITS-header style).
2. **weather_proxy** connects to the socket, sends a `"get\n"` command, and parses the incoming
lines.
3. It extracts the fields: `WEATHER`, `WINDMAX1`, `PRECIP`, `CLOUDS`, `WIND`, `EXTTEMP`,
`PRESSURE`, `HUMIDITY`, `FORCEOFF`, and `TMEAS` (the timestamp).
4. The data is stored in a POSIX shared memory segment (`/weather_shm`) and is protected by a named
semaphore (`/weather_sem`).
5. Client applications (like `chkweather` or your own code) use `get_weather_data()` to read the
shared memory safely.
## Signals
The daemon responds to:
- **SIGUSR1** Forbid observations (sets an internal `forbidden` flag which overrides the current
weather to `WEATHER_PROHIBITED`).
- **SIGUSR2** Permit observations (clears the `forbidden` flag).
These signals are only handled by the worker child process; the parent monitor process ignores
them. So you can send them simply by `killall -sUSR1 weather_proxy`.
## FITSHeader Output
If the `-f <file>` option is given, the daemon writes each received `KEY=VALUE` line to a temporary
file and, when the data set is complete (i.e., the `TWEATH` line is received), it atomically
replaces the target file. This produces a plaintext file that can be used as a FITS header or for
other applications.
Example generated file:
```
WIND = 4.30 / Wind, m/s
WINDMAX = 5.90 / Maximal wind speed for last 24 hours
WINDMAX1= 5.90 / Maximal wind speed for last hour
WINDDIR = 32.75 / Wind direction, degr (CW from north to FROM)
WINDDIR1= 25.97 / Mean wind speed direction for last hour
WINDDIR2= 35.37 / Mean wind speed^2 direction for last hour
HUMIDITY= 57.50 / Humidity, percent
EXTTEMP = 9.00 / Ambient temperature, degC
PRESSURE= 585.72 / Atmospheric pressure, mmHg
PRECIP = 0 / Precipitation (1 - yes, 0 - no)
PRECIPLV= 0.00 / Cumulative precipitation level (mm)
CLOUDS = 2399.50 / Integral sky quality value (bigger - better)
WEATHER = 0 / Weather (0..3: good/bad/terrible/prohibited)
TSINCERN= 20 / Minutes since rain (20 means a lot of)
RAINPOW = 0 / Rain strength, 0..255
RAINAVG = 0 / Average rain strength, 0..255
RSAMBL = 48 / Ambient light by rain sensor, 0..255
RSFREEZ = 0 / Rain sensor is freezed
TWEATH = 1779085104 / Last weather time: 2026-05-18 09:18:24
```
----
## License
Copyright © 2026 Edward V. Emelianov.
**GNU General Public License v3.0** or later.
See the `LICENSE` file in repository's root directory or [http://www.gnu.org/licenses/](http://www.gnu.org/licenses/)
for details.

View File

@@ -1,3 +1,4 @@
Readme.md
weather_client.c weather_client.c
weather_clt_example.c weather_clt_example.c
weather_daemon.c weather_daemon.c

View File

@@ -44,14 +44,14 @@ emerge net-analyzer/net-snmp
``` ```
Available plugin options: Available plugin options:
- `DUMMY`  Dummy weather station for testing. - `DUMMY` Dummy weather station for testing.
- `FDEXAMPLE`  Example file descriptor plugin. - `FDEXAMPLE` Example file descriptor plugin.
- `HYDREON`  Hydreon RG-11 rain sensor. - `HYDREON` Hydreon RG-11 rain sensor.
- `BTAMETEO`  BTA 6-m telescope main meteostation (shared memory). - `BTAMETEO` BTA 6-m telescope main meteostation (shared memory).
- `REINHARDT`  Old Reinhardt meteostation. - `REINHARDT` Old Reinhardt meteostation.
- `WXA100`  Vaisala WXA100 ultrasonic station. - `WXA100` Vaisala WXA100 ultrasonic station.
- `SNMP`  UPS monitoring via SNMP. - `SNMP` UPS monitoring via SNMP.
- `LIGHTNING`  AS3935-based lightning sensor. - `LIGHTNING` AS3935-based lightning sensor.
4. Building: 4. Building:
@@ -94,7 +94,7 @@ Format:
``` ```
- `library`: path to the shared library, e.g. `libwxa100.so`. - `library`: path to the shared library, e.g. `libwxa100.so`.
- `type`: Connection type  `D` for serial device, `U` for UNIX socket, `N` for INET socket. - `type`: Connection type `D` for serial device, `U` for UNIX socket, `N` for INET socket.
- `parameter`: device path and optional speed (`/dev/ttyS0:9600`), UNIX socket name, or `host:port` for INET. - `parameter`: device path and optional speed (`/dev/ttyS0:9600`), UNIX socket name, or `host:port` for INET.
Examples: Examples:
@@ -150,7 +150,7 @@ Run with:
superweatherdaemon -c /etc/weather.conf superweatherdaemon -c /etc/weather.conf
``` ```
To run on system start you can use OpenRó `rc.local` mechanism. To run on system start you can use OpenRС `rc.local` mechanism.
## Plugins ## Plugins
@@ -185,8 +185,8 @@ daemon will try to reconnect every `reinit_delay` seconds.
| Library | Sensor | Type | | Library | Sensor | Type |
|---------|--------|------| |---------|--------|------|
| `libwsdummy.so` | Dummy station  outputs random walk data around realistic values. | Test / Development | | `libwsdummy.so` | Dummy station outputs random walk data around realistic values. | Test / Development |
| `libfdex.so` | Example of a filedescriptor based plugin. Prompts for commaseparated values. | Example | | `libfdex.so` | Example of a filedescriptor based plugin. Prompts for commaseparated values. | Example |
| `libhydreon.so` | Hydreon RG-11 optical rain sensor. | Serial | | `libhydreon.so` | Hydreon RG-11 optical rain sensor. | Serial |
| `libbtameteo.so` | BTA 6-m telescope main meteostation (shared memory). | Shared Memory | | `libbtameteo.so` | BTA 6-m telescope main meteostation (shared memory). | Shared Memory |
| `libreinhardt.so` | Old Reinhardt meteostation (serial, `?U` command). | Serial | | `libreinhardt.so` | Old Reinhardt meteostation (serial, `?U` command). | Serial |
@@ -216,22 +216,22 @@ Use the existing plugins as templates. A minimal plugin must:
The daemon combines data from all active plugins and continuously evaluates a global **weather The daemon combines data from all active plugins and continuously evaluates a global **weather
level**: level**:
- `0`  **GOOD**: observations can start safely. - `0` **GOOD**: observations can start safely.
- `1`  **BAD**: risky to start, but can continue. - `1` **BAD**: risky to start, but can continue.
- `2`  **TERRIBLE**: dome must close, instruments park. - `2` **TERRIBLE**: dome must close, instruments park.
- `3`  **PROHIBITED**: complete shutdown, power off equipment. - `3` **PROHIBITED**: complete shutdown, power off equipment.
### Criteria ### Criteria
Each weather parameter (wind speed, humidity, clouds, sky temperature, lightning distance, Each weather parameter (wind speed, humidity, clouds, sky temperature, lightning distance,
precipitation, etc.) has configurable thresholds: precipitation, etc.) has configurable thresholds:
- `good`  below/above this (depending on sign) the condition is good. - `good` below/above this (depending on sign) the condition is good.
- `bad`  above this the condition is bad. - `bad` above this the condition is bad.
- `terrible`  above this the condition is terrible. - `terrible` above this the condition is terrible.
- `prohibited`  (if defined) above this the condition goes directly to PROHIBITED. - `prohibited` (if defined) above this the condition goes directly to PROHIBITED.
- `negflag`  if `1`, a smaller value is worse (e.g., clouds). - `negflag` if `1`, a smaller value is worse (e.g., clouds).
- `shtdnflag`  if `1`, entering the terrible/prohibited range also sets the **FORCE SHUTDOWN** flag. - `shtdnflag` if `1`, entering the terrible/prohibited range also sets the **FORCE SHUTDOWN** flag.
### Special Flags ### Special Flags
@@ -251,9 +251,9 @@ passed since the last serious event. This prevents rapid toggling.
The daemon listens on two interfaces: The daemon listens on two interfaces:
1. **Network socket** (TCP, default port 12345)  read-only (in meaning they cannot change any 1. **Network socket** (TCP, default port 12345) read-only (in meaning they cannot change any
parameters) access for remote clients. parameters) access for remote clients.
2. **Local UNIX socket** (abstract or filesystem, default `@weather`)  full control for local applications. 2. **Local UNIX socket** (abstract or filesystem, default `@weather`) full control for local applications.
Commands are sent as plain text strings, terminated by a newline. Commands are sent as plain text strings, terminated by a newline.
@@ -285,7 +285,7 @@ Commands are sent as plain text strings, terminated by a newline.
Reply format: each line is a FITS-like `KEY = value / comment` string; commands that set something Reply format: each line is a FITS-like `KEY = value / comment` string; commands that set something
usually echo back the variable and its new value. For `get=<N>` each `KEY` have a suffix in square usually echo back the variable and its new value. For `get=<N>` each `KEY` have a suffix in square
brackets  number of plugin, e.g. `WIND[1]= 10.1 / Wind speed, m/s`. brackets number of plugin, e.g. `WIND[1]= 10.1 / Wind speed, m/s`.
## Signals ## Signals

View File

@@ -64,11 +64,11 @@ enum{
// they would be changed later in `fix_new_data` to lowest level // they would be changed later in `fix_new_data` to lowest level
static val_t collected_data[NAMOUNT_OF_DATA] = { static val_t collected_data[NAMOUNT_OF_DATA] = {
[NWIND] = {.sense = VAL_BROKEN, .type = VALT_FLOAT, .meaning = IS_WIND}, [NWIND] = {.sense = VAL_BROKEN, .type = VALT_FLOAT, .meaning = IS_WIND},
[NWINDMAX] = {.sense = VAL_RECOMMENDED, .type = VALT_FLOAT, .meaning = IS_OTHER, .name = "WINDMAX", .comment = "Maximal wind speed for last 24 hours"}, [NWINDMAX] = {.sense = VAL_BROKEN, .type = VALT_FLOAT, .meaning = IS_OTHER, .name = "WINDMAX", .comment = "Maximal wind speed for last 24 hours"},
[NWINDMAX1] = {.sense = VAL_RECOMMENDED, .type = VALT_FLOAT, .meaning = IS_OTHER, .name = "WINDMAX1", .comment = "Maximal wind speed for last hour"}, [NWINDMAX1] = {.sense = VAL_BROKEN, .type = VALT_FLOAT, .meaning = IS_OTHER, .name = "WINDMAX1", .comment = "Maximal wind speed for last hour"},
[NWINDDIR] = {.sense = VAL_BROKEN, .type = VALT_FLOAT, .meaning = IS_WINDDIR}, [NWINDDIR] = {.sense = VAL_BROKEN, .type = VALT_FLOAT, .meaning = IS_WINDDIR},
[NWINDDIR1] = {.sense = VAL_RECOMMENDED, .type = VALT_FLOAT, .meaning = IS_OTHER, .name = "WINDDIR1", .comment = "Mean wind speed direction for last hour"}, [NWINDDIR1] = {.sense = VAL_BROKEN, .type = VALT_FLOAT, .meaning = IS_OTHER, .name = "WINDDIR1", .comment = "Mean wind speed direction for last hour"},
[NWINDDIR2] = {.sense = VAL_RECOMMENDED, .type = VALT_FLOAT, .meaning = IS_OTHER, .name = "WINDDIR2", .comment = "Mean wind speed^2 direction for last hour"}, [NWINDDIR2] = {.sense = VAL_BROKEN, .type = VALT_FLOAT, .meaning = IS_OTHER, .name = "WINDDIR2", .comment = "Mean wind speed^2 direction for last hour"},
[NHUMIDITY] = {.sense = VAL_BROKEN, .type = VALT_FLOAT, .meaning = IS_HUMIDITY}, [NHUMIDITY] = {.sense = VAL_BROKEN, .type = VALT_FLOAT, .meaning = IS_HUMIDITY},
[NAMB_TEMP] = {.sense = VAL_BROKEN, .type = VALT_FLOAT, .meaning = IS_AMB_TEMP}, [NAMB_TEMP] = {.sense = VAL_BROKEN, .type = VALT_FLOAT, .meaning = IS_AMB_TEMP},
[NPRESSURE] = {.sense = VAL_BROKEN, .type = VALT_FLOAT, .meaning = IS_PRESSURE}, [NPRESSURE] = {.sense = VAL_BROKEN, .type = VALT_FLOAT, .meaning = IS_PRESSURE},
@@ -80,8 +80,8 @@ static val_t collected_data[NAMOUNT_OF_DATA] = {
// [NLIGHTDIST] = {.sense = VAL_FORCEDSHTDN, .type = VALT_FLOAT, .meaning = IS_LIGTDIST}, // [NLIGHTDIST] = {.sense = VAL_FORCEDSHTDN, .type = VALT_FLOAT, .meaning = IS_LIGTDIST},
// these are calculated values // these are calculated values
[NCOMMWEATH] = {.sense = VAL_OBLIGATORY, .type = VALT_UINT, .meaning = IS_OTHER, .name = "WEATHER", .comment = "Weather (0..3: good/bad/terrible/prohibited)"}, [NCOMMWEATH] = {.sense = VAL_OBLIGATORY, .type = VALT_UINT, .meaning = IS_OTHER, .name = "WEATHER", .comment = "Weather (0..3: good/bad/terrible/prohibited)"},
[NLASTAHTUNG] = {.sense = VAL_RECOMMENDED, .type = VALT_UINT, .meaning = IS_OTHER, .name = "EVTTIME", .comment = "UNIX-time of last weather level changing"}, [NLASTAHTUNG] = {.sense = VAL_BROKEN, .type = VALT_UINT, .meaning = IS_OTHER, .name = "EVTTIME", .comment = "UNIX-time of last weather level changing"},
[NAHTUNGRSN] = {.sense = VAL_RECOMMENDED, .type = VALT_STRING, .meaning = IS_OTHER, .name = "EVTRSN", .comment = "Last weather level increasing reason"}, [NAHTUNGRSN] = {.sense = VAL_BROKEN, .type = VALT_STRING, .meaning = IS_OTHER, .name = "EVTRSN", .comment = "Last weather level increasing reason"},
// virtual values for weather level / flags changing // virtual values for weather level / flags changing
[NBADWEATH] = {.sense = VAL_BROKEN, .type = VALT_UINT, .meaning = IS_BADWEATH, .name = "BADWEATH", .comment = "Flag changing weather level to 'BAD'"}, [NBADWEATH] = {.sense = VAL_BROKEN, .type = VALT_UINT, .meaning = IS_BADWEATH, .name = "BADWEATH", .comment = "Flag changing weather level to 'BAD'"},
[NTERRWEATH] = {.sense = VAL_BROKEN, .type = VALT_UINT, .meaning = IS_TERRIBLEWEATH, .name = "TERWEATH", .comment = "Flag changing weather level to 'TERRIBLE'"}, [NTERRWEATH] = {.sense = VAL_BROKEN, .type = VALT_UINT, .meaning = IS_TERRIBLEWEATH, .name = "TERWEATH", .comment = "Flag changing weather level to 'TERRIBLE'"},
@@ -282,6 +282,38 @@ static void fix_new_data(val_t *collected, const val_t *fresh, int force){
//DBG("Refresh collected value"); //DBG("Refresh collected value");
//LOGDBGADD("Refresh time"); //LOGDBGADD("Refresh time");
collected->time = fresh->time; collected->time = fresh->time;
// check windmax/winddir
double curvalue = val2d(fresh), dir1 = -100., dir2 = -100.;
switch(fresh->meaning){ // fill winddir/windmax
case IS_WIND:
collected_data[NWINDMAX].sense = fresh->sense;
collected_data[NWINDMAX1].sense = fresh->sense;
add_windspeed(&windspeeds, curvalue, fresh->time);
collected_data[NWINDMAX].value.f = (float) get_current_max(&windspeeds);
collected_data[NWINDMAX].time = fresh->time;
collected_data[NWINDMAX1].value.f = (float) get_max_forT(&windspeeds, fresh->time - T_ONE_HOUR);
collected_data[NWINDMAX1].time = fresh->time;
break;
case IS_WINDDIR:
collected_data[NWINDDIR].sense = fresh->sense;
collected_data[NWINDDIR1].sense = fresh->sense;
collected_data[NWINDDIR2].sense = fresh->sense;
wind_dir_add(collected_data[NWIND].value.f, fresh->value.f, &dir1, &dir2);
// refresh max
if(dir1 >= 0.){
collected_data[NWINDDIR1].value.f = (float) dir1;
collected_data[NWINDDIR1].time = fresh->time;
}
if(dir2 >= 0.){
collected_data[NWINDDIR2].value.f = (float) dir2;
collected_data[NWINDDIR2].time = fresh->time;
}
break;
default:
break;
}
if(collected->type == fresh->type){ // good case if(collected->type == fresh->type){ // good case
memcpy(&collected->value, &fresh->value, sizeof(num_t)); memcpy(&collected->value, &fresh->value, sizeof(num_t));
//DBG("Types are the same"); //DBG("Types are the same");
@@ -418,29 +450,20 @@ void refresh_sensval(sensordata_t *s){
static time_t lasttupdate = 0; // last update time of weather level static time_t lasttupdate = 0; // last update time of weather level
time_t curtime = time(NULL); time_t curtime = time(NULL);
time_t tpoll = get_pollT(), _3tpoll = 3*tpoll; time_t tpoll = get_pollT(), _3tpoll = 3*tpoll;
double dir = -100., dir2 = -100.; // mean wind directions
//DBG("%d meteo values", s->Nvalues); //DBG("%d meteo values", s->Nvalues);
for(int i = 0; i < s->Nvalues; ++i){ for(int i = 0; i < s->Nvalues; ++i){
//DBG("\nTry to get %dth value", i); //DBG("\nTry to get %dth value", i);
if(!s->get_value(s, &value, i) || value.sense > VAL_RECOMMENDED) continue; if(!s->get_value(s, &value, i) || value.sense > VAL_UNNECESSARY) continue;
//DBG("got value"); //DBG("got value");
int idx = -1; int idx = -1;
double curvalue = val2d(&value);
const weather_cond_t *curcond = NULL; const weather_cond_t *curcond = NULL;
switch(value.meaning){ switch(value.meaning){
case IS_WIND: case IS_WIND:
idx = NWIND; idx = NWIND;
curcond = &WeatherConf.wind; curcond = &WeatherConf.wind;
// protect collected wind speeds from destruction in case of simultaneous acces from different plugins
pthread_mutex_lock(&datamutex);
add_windspeed(&windspeeds, curvalue, curtime);
pthread_mutex_unlock(&datamutex);
break; break;
case IS_WINDDIR: case IS_WINDDIR:
idx = NWINDDIR; idx = NWINDDIR;
pthread_mutex_lock(&datamutex);
wind_dir_add(collected_data[NWIND].value.f, value.value.f, &dir, &dir2);
pthread_mutex_unlock(&datamutex);
break; break;
case IS_HUMIDITY: case IS_HUMIDITY:
idx = NHUMIDITY; idx = NHUMIDITY;
@@ -455,11 +478,9 @@ void refresh_sensval(sensordata_t *s){
case IS_PRECIP: case IS_PRECIP:
idx = NPRECIP; idx = NPRECIP;
curcond = &prohibweathflag; curcond = &prohibweathflag;
if(curvalue > 0.) DBG("IS_PRECIP == 1 !!!");
break; break;
case IS_PRECIP_LEVEL: case IS_PRECIP_LEVEL:
idx = NPRECIP_LEVEL; idx = NPRECIP_LEVEL;
curcond = &terrweathflag;
break; break;
case IS_MIST: case IS_MIST:
idx = NMIST; idx = NMIST;
@@ -496,13 +517,15 @@ void refresh_sensval(sensordata_t *s){
update_additional(&value); update_additional(&value);
continue; continue;
} }
if(idx < 0 || idx >= NAMOUNT_OF_DATA) continue; if(idx < 0 || idx >= NAMOUNT_OF_DATA) continue; // wrong index?
if(value.sense > collected_data[idx].sense &&
curtime - collected_data[idx].time < WeatherConf.ahtung_delay) continue; // bad level
//DBG("IDX=%d", idx); //DBG("IDX=%d", idx);
pthread_mutex_lock(&datamutex); pthread_mutex_lock(&datamutex);
int force = 0; int force = 0;
if(curcond){ if(curcond && value.sense <= collected_data[idx].sense){
int oldshtdn = collected_data[NFORCEDSHTDN].value.u; int oldshtdn = collected_data[NFORCEDSHTDN].value.u;
if(1 == chkweatherlevel(&curlevel, curvalue, curcond)){ if(1 == chkweatherlevel(&curlevel, val2d(&value), curcond)){
get_fieldnameval(&value, reason); // copy to `reason` reason of last level increasing get_fieldnameval(&value, reason); // copy to `reason` reason of last level increasing
force = 1; force = 1;
DBG("reason: %s; forceflag=%u, old=%d", reason, collected_data[NFORCEDSHTDN].value.u, oldshtdn); DBG("reason: %s; forceflag=%u, old=%d", reason, collected_data[NFORCEDSHTDN].value.u, oldshtdn);
@@ -520,22 +543,6 @@ void refresh_sensval(sensordata_t *s){
pthread_mutex_unlock(&datamutex); pthread_mutex_unlock(&datamutex);
} }
pthread_mutex_lock(&datamutex); pthread_mutex_lock(&datamutex);
// refresh max
if(dir >= 0.){
collected_data[NWINDDIR1].value.f = (float) dir;
collected_data[NWINDDIR1].time = curtime;
}
if(dir2 >= 0.){
collected_data[NWINDDIR2].value.f = (float) dir2;
collected_data[NWINDDIR2].time = curtime;
}
if(curtime - collected_data[NWIND].time < tpoll + 1){
//LOGDBG("Update max wind");
collected_data[NWINDMAX].value.f = (float) get_current_max(&windspeeds);
collected_data[NWINDMAX].time = curtime;
collected_data[NWINDMAX1].value.f = (float) get_max_forT(&windspeeds, curtime - T_ONE_HOUR);
collected_data[NWINDMAX1].time = curtime;
}
//DBG("check ahtung"); //DBG("check ahtung");
time_t _2update = lasttupdate + _3tpoll; time_t _2update = lasttupdate + _3tpoll;
//LOGDBG("curtime: %ld, _2update: %ld", curtime, lasttupdate); //LOGDBG("curtime: %ld, _2update: %ld", curtime, lasttupdate);

View File

@@ -31,16 +31,17 @@ enum{
}; };
static const val_t values[NAMOUNT] = { static const val_t values[NAMOUNT] = {
[NWIND] = {.sense = VAL_RECOMMENDED, .type = VALT_FLOAT, .meaning = IS_WIND}, [NWIND] = {.sense = VAL_UNNECESSARY, .type = VALT_FLOAT, .meaning = IS_WIND},
[NHUMIDITY] = {.sense = VAL_RECOMMENDED, .type = VALT_FLOAT, .meaning = IS_HUMIDITY}, [NHUMIDITY] = {.sense = VAL_UNNECESSARY, .type = VALT_FLOAT, .meaning = IS_HUMIDITY},
[NAMB_TEMP] = {.sense = VAL_RECOMMENDED, .type = VALT_FLOAT, .meaning = IS_AMB_TEMP}, [NAMB_TEMP] = {.sense = VAL_UNNECESSARY, .type = VALT_FLOAT, .meaning = IS_AMB_TEMP},
[NPRESSURE] = {.sense = VAL_RECOMMENDED, .type = VALT_FLOAT, .meaning = IS_PRESSURE}, [NPRESSURE] = {.sense = VAL_UNNECESSARY, .type = VALT_FLOAT, .meaning = IS_PRESSURE},
[NPRECIP] = {.sense = VAL_RECOMMENDED, .type = VALT_UINT, .meaning = IS_PRECIP}, [NPRECIP] = {.sense = VAL_UNNECESSARY, .type = VALT_UINT, .meaning = IS_PRECIP},
}; };
static void *mainthread(void *s){ static void *mainthread(void *s){
FNAME(); FNAME();
sensordata_t *sensor = (sensordata_t *)s; sensordata_t *sensor = (sensordata_t *)s;
double t0 = sl_dtime();
while(sensor->fdes > -1){ while(sensor->fdes > -1){
if(check_shm_block(&sdat)){ if(check_shm_block(&sdat)){
//DBG("Got next"); //DBG("Got next");
@@ -57,7 +58,8 @@ static void *mainthread(void *s){
pthread_mutex_unlock(&sensor->valmutex); pthread_mutex_unlock(&sensor->valmutex);
if(sensor->freshdatahandler) sensor->freshdatahandler(sensor); if(sensor->freshdatahandler) sensor->freshdatahandler(sensor);
}else break; // no connection? }else break; // no connection?
sleep(1); while(sl_dtime() - t0 < sensor->tpoll) usleep(500);
t0 = sl_dtime();
} }
return NULL; return NULL;
} }

View File

@@ -109,7 +109,7 @@ static void *mainthread(void *s){
sensordata_t *sensor = (sensordata_t *)s; sensordata_t *sensor = (sensordata_t *)s;
while(sensor->fdes > -1){ while(sensor->fdes > -1){
time_t tnow = time(NULL); time_t tnow = time(NULL);
if(tnow - tpoll > sensor->tpoll){ if(tnow - tpoll > sensor->tpoll){ // tpoll + 1 second
int dlen = sprintf(buf, "%s0\n%s1\n", commands[CMD_DISTANCE], commands[CMD_DISTANCE]); int dlen = sprintf(buf, "%s0\n%s1\n", commands[CMD_DISTANCE], commands[CMD_DISTANCE]);
if(dlen != write(sensor->fdes, buf, dlen)){ if(dlen != write(sensor->fdes, buf, dlen)){
WARN("Can't ask new data from lightning monitor"); WARN("Can't ask new data from lightning monitor");
@@ -144,15 +144,19 @@ static void *mainthread(void *s){
int idx = parse_string(buf, &val, &nsens); int idx = parse_string(buf, &val, &nsens);
if(idx > -1){ if(idx > -1){
DBG("Got index=%d", idx); DBG("Got index=%d", idx);
gotfresh = TRUE;
if(idx == NINTERRUPT && val == ANS_LIGHTNING){ if(idx == NINTERRUPT && val == ANS_LIGHTNING){
DBG("Interrupt: lightning"); DBG("Interrupt: lightning");
sensor->values[NSENSNO].value.u = nsens; sensor->values[NSENSNO].value.u = nsens;
sensor->values[NSENSNO].time = tnow; sensor->values[NSENSNO].time = tnow;
} }
sensor->values[idx].value.u = val; if(idx == NDISTANCE && val == 63){
sensor->values[idx].time = tnow; // do nothing: this is just polling signal
}else{
gotfresh = TRUE;
sensor->values[idx].value.u = val;
sensor->values[idx].time = tnow;
}
} }
}else break; }else break;
} }

View File

@@ -43,7 +43,7 @@ static const val_t values[NAMOUNT] = {
[NAMB_TEMP] = {.sense = VAL_RECOMMENDED, .type = VALT_FLOAT, .meaning = IS_AMB_TEMP}, [NAMB_TEMP] = {.sense = VAL_RECOMMENDED, .type = VALT_FLOAT, .meaning = IS_AMB_TEMP},
[NPRESSURE] = {.sense = VAL_BROKEN, .type = VALT_FLOAT, .meaning = IS_PRESSURE}, // broken on our meteostation [NPRESSURE] = {.sense = VAL_BROKEN, .type = VALT_FLOAT, .meaning = IS_PRESSURE}, // broken on our meteostation
[NCLOUDS] = {.sense = VAL_OBLIGATORY, .type = VALT_FLOAT, .meaning = IS_CLOUDS}, [NCLOUDS] = {.sense = VAL_OBLIGATORY, .type = VALT_FLOAT, .meaning = IS_CLOUDS},
[NPRECIP] = {.sense = VAL_RECOMMENDED, .type = VALT_UINT, .meaning = IS_PRECIP}, [NPRECIP] = {.sense = VAL_UNNECESSARY, .type = VALT_UINT, .meaning = IS_PRECIP},
[NPRECIPLVL]= {.sense = VAL_UNNECESSARY,.type = VALT_FLOAT, .meaning = IS_PRECIP_LEVEL}, [NPRECIPLVL]= {.sense = VAL_UNNECESSARY,.type = VALT_FLOAT, .meaning = IS_PRECIP_LEVEL},
}; };
@@ -77,7 +77,7 @@ static void *mainthread(void *s){
sensordata_t *sensor = (sensordata_t *)s; sensordata_t *sensor = (sensordata_t *)s;
while(sensor->fdes > -1){ while(sensor->fdes > -1){
time_t tnow = time(NULL); time_t tnow = time(NULL);
if(tnow - tpoll > sensor->tpoll){ if(tnow - tpoll >= sensor->tpoll){
if(4 != write(sensor->fdes, "?U\r\n", 4)){ if(4 != write(sensor->fdes, "?U\r\n", 4)){
WARN("Can't ask new data"); WARN("Can't ask new data");
break; break;

View File

@@ -39,13 +39,13 @@ enum{
static const val_t values[NAMOUNT] = { static const val_t values[NAMOUNT] = {
[NWIND] = {.sense = VAL_OBLIGATORY, .type = VALT_FLOAT, .meaning = IS_WIND}, [NWIND] = {.sense = VAL_OBLIGATORY, .type = VALT_FLOAT, .meaning = IS_WIND},
[NWINDDIR] = {.sense = VAL_RECOMMENDED,.type = VALT_FLOAT, .meaning = IS_WINDDIR}, [NWINDDIR] = {.sense = VAL_OBLIGATORY,.type = VALT_FLOAT, .meaning = IS_WINDDIR},
[NHUMIDITY] = {.sense = VAL_OBLIGATORY, .type = VALT_FLOAT, .meaning = IS_HUMIDITY}, [NHUMIDITY] = {.sense = VAL_OBLIGATORY, .type = VALT_FLOAT, .meaning = IS_HUMIDITY},
[NAMB_TEMP] = {.sense = VAL_OBLIGATORY, .type = VALT_FLOAT, .meaning = IS_AMB_TEMP}, [NAMB_TEMP] = {.sense = VAL_OBLIGATORY, .type = VALT_FLOAT, .meaning = IS_AMB_TEMP},
[NPRESSURE] = {.sense = VAL_OBLIGATORY, .type = VALT_FLOAT, .meaning = IS_PRESSURE}, [NPRESSURE] = {.sense = VAL_OBLIGATORY, .type = VALT_FLOAT, .meaning = IS_PRESSURE},
[NPRECIP] = {.sense = VAL_UNNECESSARY, .type = VALT_UINT, .meaning = IS_PRECIP}, // this sensor lies [NPRECIP] = {.sense = VAL_BROKEN, .type = VALT_UINT, .meaning = IS_PRECIP}, // this sensor lies
[NPRECIPLVL]= {.sense = VAL_UNNECESSARY,.type = VALT_FLOAT, .meaning = IS_PRECIP_LEVEL}, [NPRECIPLVL]= {.sense = VAL_BROKEN,.type = VALT_FLOAT, .meaning = IS_PRECIP_LEVEL},
[NPRECIPINT]= {.sense = VAL_UNNECESSARY,.type = VALT_FLOAT, .meaning = IS_OTHER, .name = "PRECRATE", .comment = "Precipitation rate, mm/h"}, [NPRECIPINT]= {.sense = VAL_BROKEN,.type = VALT_FLOAT, .meaning = IS_OTHER, .name = "PRECRATE", .comment = "Precipitation rate, mm/h"},
}; };
typedef struct{ typedef struct{
@@ -126,7 +126,7 @@ static void *mainthread(void *s){
sensordata_t *sensor = (sensordata_t *)s; sensordata_t *sensor = (sensordata_t *)s;
while(sensor->fdes > -1){ while(sensor->fdes > -1){
time_t tnow = time(NULL); time_t tnow = time(NULL);
if(tnow - tpoll > sensor->tpoll){ if(tnow - tpoll >= sensor->tpoll){
if(6 != write(sensor->fdes, "!0R0\r\n", 6)){ if(6 != write(sensor->fdes, "!0R0\r\n", 6)){
WARN("Can't ask new data"); WARN("Can't ask new data");
break; break;

View File

@@ -1,2 +1,9 @@
# small_tel # small_tel
Different utilities for small telescopes Different utilities for small telescopes
## Directories:
- Auxiliary_utils - some frequently used over observations utils and scripts
- Daemons - main daemons (weather, dome, telescope equipment, mount)
- Docs - some documentation (Russian)