diff --git a/Daemons/domedaemon-astrosib-v3/CMakeLists.txt b/Daemons/domedaemon-astrosib-v3/CMakeLists.txt new file mode 100644 index 0000000..da40070 --- /dev/null +++ b/Daemons/domedaemon-astrosib-v3/CMakeLists.txt @@ -0,0 +1,65 @@ +cmake_minimum_required(VERSION 3.30) + +set(PROJ domedaemon) +project(${PROJ}) + +set(MINOR_VERSION "0") +set(MID_VERSION "1") +set(MAJOR_VERSION "0") +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 -fno-builtin-strlen ") + SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,--gc-sections") + 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) + +# 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) +# -D +add_definitions( + -DPACKAGE_VERSION=\"${VERSION}\" -DMINOR_VERSION=\"${MINOR_VERSION}\" + -DMID_VERSION=\"${MID_VERSION}\" -DMAJOR_VERSION=\"${MAJOR_VESION}\" + -D_GNU_SOURCE + ) + +# Installation of the program +INSTALL(TARGETS ${PROJ} DESTINATION "bin") diff --git a/Daemons/domedaemon-astrosib-v3/Readme.md b/Daemons/domedaemon-astrosib-v3/Readme.md new file mode 100644 index 0000000..496a047 --- /dev/null +++ b/Daemons/domedaemon-astrosib-v3/Readme.md @@ -0,0 +1,207 @@ +# domedaemon‑astrosib + +**domedaemon‑astrosib** is a daemon that controls an [**Astrosib**](https://astrosib.ru/) all‑sky +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 FITS‑style header file with current dome +status. + +This version written for Dome5 of "Astro-M" complex; the key changes are in status (0 - closed, +1 - opened, 3 - intermediate) and temporarily absent of drivers' relay control. + +--- + +## 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 FITS‑style 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 + +--- + +## Command‑line 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 FITS‑style header | +| `-N`, `--domename` | *name* | `Astrosib` | Dome name inserted into the header | + +--- + +## Socket protocol + +The daemon listens for text‑based commands on the configured socket. Each command returns one or +more lines of output, terminated by newline (`\n`). + +### Commands + +| Command | Description | Example | +|---------------------------------|----------------------------------------------------------------------------|----------------------------------------------| +| `unixt` | Return server’s 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 human‑readable 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 **FITS‑like** 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 weather‑aware 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 hard‑coded). +- 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 for details. diff --git a/Daemons/domedaemon-astrosib-v3/astrosib_proto.h b/Daemons/domedaemon-astrosib-v3/astrosib_proto.h new file mode 100644 index 0000000..d5d70e1 --- /dev/null +++ b/Daemons/domedaemon-astrosib-v3/astrosib_proto.h @@ -0,0 +1,27 @@ +/* + * This file is part of the domedaemon-astrosib project. + * Copyright 2025 Edward V. Emelianov . + * + * 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 . + */ + +#pragma once + +#define ASIB_CMD_STATUS "STATUS" +#define ASIB_CMD_RELAY "SWITCHTOGGILE" +#define ASIB_CMD_STOP "STOPDOME" +#define ASIB_CMD_OPEN "OPENDOME" +#define ASIB_CMD_CLOSE "CLOSEDOME" +#define ASIB_CMD_MOVEONE "SHUTTERMOVEDEG" +#define ASIB_CMD_RELAY "SWITCHTOGGILE" diff --git a/Daemons/domedaemon-astrosib-v3/dome.c b/Daemons/domedaemon-astrosib-v3/dome.c new file mode 100644 index 0000000..56adbca --- /dev/null +++ b/Daemons/domedaemon-astrosib-v3/dome.c @@ -0,0 +1,279 @@ +/* + * This file is part of the domedaemon-astrosib project. + * Copyright 2025 Edward V. Emelianov . + * + * 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 . + */ + +#include +#include + +#include "astrosib_proto.h" +#include "dome.h" +#include "header.h" + +// number of relay turning on/off motors power +#define MOTRELAY_NO 1 +// state of relay to turn power on/off +#define MOTRELAY_ON 1 +#define MOTRELAY_OFF 0 + +// time interval for requiring current dome status in idle state (e.g. trigger watchdog) +#define STATUSREQ_IDLE 10. +// update interval in moving state +#define STATUSREQ_MOVE 0.5 + +// dome status by polling (each STATUSREQ_IDLE seconds) +static dome_status_t dome_status = {0}; +// finite state machine state +static dome_state_t state = DOME_S_IDLE; +// last time dome_status was updated +static double last_status_time = 0.; +// current update interval +static double status_req_interval = STATUSREQ_MOVE; +// serial device +static sl_tty_t *serialdev = NULL; +static pthread_mutex_t serialmutex = PTHREAD_MUTEX_INITIALIZER; + +void dome_serialdev(sl_tty_t *serial){ + serialdev = serial; +} +/** + * @brief serial_write - write buffer without "\r" on end to port + * @param cmd - data to send + * @param answer - buffer for answer (or NULL if not need) + * @param anslen - length of `answer` + * @return error code + */ +static int serial_write(const char *cmd, char *answer, int anslen){ + if(!serialdev || !cmd || !answer || anslen < 2) return FALSE; + static char *buf = NULL; + static size_t buflen = 0; + DBG("Write %s", cmd); + size_t cmdlen = strlen(cmd); + if(buflen < cmdlen + 2){ + buflen = (cmdlen + 4096) / 4096; + buflen *= 4096; + if(!(buf = realloc(buf, buflen))){ + LOGERR("serial_write(): realloc() failed!"); + ERRX("serial_write(): realloc() failed!"); + } + } + size_t _2write = snprintf(buf, buflen-1, "%s\r", cmd); + DBG("try to send %zd bytes", _2write); + if(sl_tty_write(serialdev->comfd, buf, _2write)) return FALSE; + int got = 0, totlen = 0; + --anslen; // for /0 + do{ + got = sl_tty_read(serialdev); + if(got > 0){ + if(got > anslen) return FALSE; // buffer overflow + memcpy(answer, serialdev->buf, got); + totlen += got; + answer += got; + anslen -= got; + answer[0] = 0; + } + DBG("got = %d", got); + }while(got > 0 && anslen); + if(got < 0){ + LOGERR("serial_write(): serial device disconnected!"); + ERRX("serial_write(): serial device disconnected!"); + } + if(totlen < 1) return FALSE; // no answer received + if(answer[-1] == '\r') answer[-1] = 0; // remove trailing trash + return TRUE; +} + +// return TRUE if can parse status +static int parsestatus(const char *buf){ + if(!buf) return FALSE; + DBG("buf=%s", buf); + int n = sscanf(buf, ASIB_CMD_STATUS "%d,%d,%d,%d,%f,%f,%f,%f,%f,%f,%d,%d,%d,%d,%d", + &dome_status.coverstate[0], &dome_status.coverstate[1], + &dome_status.encoder[0], &dome_status.encoder[1], + &dome_status.Tin, &dome_status.Tout, + &dome_status.Imot[0], &dome_status.Imot[1], &dome_status.Imot[2], &dome_status.Imot[3], + &dome_status.relay[0], &dome_status.relay[1], &dome_status.relay[2], + &dome_status.rainArmed, &dome_status.israin); + DBG("n=%d", n); + if(n != 15){ + WARNX("Something wrong with STATUS answer"); + LOGWARN("Something wrong with STATUS answer"); + LOGWARNADD("%s", buf); + return FALSE; + } + return TRUE; +} + +// check status; return FALSE if failed +static int check_status(){ + char buf[BUFSIZ]; + // clear input buffers + int got = sl_tty_read(serialdev); + if(got > 0) printf("Got from serial %zd bytes of trash: `%s`\n", serialdev->buflen, serialdev->buf); + else if(got < 0){ + LOGERR("Serial device disconnected?"); + ERRX("Serial device disconnected?"); + } + DBG("Require status"); + if(!serial_write(ASIB_CMD_STATUS, buf, BUFSIZ)) return FALSE; + int ret = FALSE; + if(parsestatus(buf)){ + last_status_time = sl_dtime(); + ret = TRUE; + } + return ret; +} + +// run naked command or command with parameters +static int runcmd(const char *cmd, const char *par){ + char buf[256]; + if(!cmd) return FALSE; + DBG("Send command %s with par %s", cmd, par); + if(!par) snprintf(buf, 255, "%s", cmd); + else snprintf(buf, 255, "%s%s", cmd, par); + if(!serial_write(buf, buf, 255)) return FALSE; + if(strncmp(buf, "OK", 2)) return FALSE; + return TRUE; +} + +// check current state and turn on/off relay if need +static void chkrelay(){ + static dome_state_t oldstate = DOME_S_MOVING; + static double t0 = 0.; + if(state != DOME_S_MOVING) return; + if(dome_status.coverstate[0] == COVER_INTERMEDIATE || + dome_status.coverstate[1] == COVER_INTERMEDIATE){ // still moving + oldstate = DOME_S_MOVING; + return; + } + DBG("state=%d, oldstate=%d", state, oldstate); + // OK, we are on place - turn off motors' power after 5 seconds + if(oldstate == DOME_S_MOVING){ // just stopped - fire pause + t0 = sl_dtime(); + oldstate = DOME_S_IDLE; + DBG("START 5s pause"); + return; + }else{ // check pause + if(sl_dtime() - t0 < POWER_STOP_TIMEOUT) return; + } + DBG("5s out -> turn off power"); + /* + char buf[128]; + snprintf(buf, 127, "%s%d,%d", ASIB_CMD_RELAY, MOTRELAY_NO, MOTRELAY_OFF); + if(serial_write(buf, buf, 128) && check_status()){ + DBG("Check are motors really off"); + if(dome_status.relay[MOTRELAY_NO-1] == MOTRELAY_OFF){ + DBG("OK state->IDLE"); + state = DOME_S_IDLE; + oldstate = DOME_S_MOVING; + } + } + */ +} + +// turn ON motors' relay +#if 0 +static int motors_on(){ + char buf[128]; + snprintf(buf, 127, "%s%d,%d", ASIB_CMD_RELAY, MOTRELAY_NO, MOTRELAY_ON); + if(serial_write(buf, buf, 128) && check_status()){ + DBG("Check are motors really on"); + if(dome_status.relay[MOTRELAY_NO-1] == MOTRELAY_ON){ + DBG("OK state->MOVING"); + state = DOME_S_MOVING; + return TRUE; + } + } + return FALSE; +} +#endif + +// just get current status +double get_dome_status(dome_status_t *s){ + if(s){ + pthread_mutex_lock(&serialmutex); + *s = dome_status; + pthread_mutex_unlock(&serialmutex); + } + return last_status_time; +} + +dome_state_t get_dome_state(){return state;} + +dome_state_t dome_poll(dome_cmd_t cmd, int par){ + char buf[128]; + int st = DOME_S_ERROR; + double curtime = sl_dtime(); + //DBG("curtime-lasttime=%g", curtime - last_status_time); + // simple polling and there's a lot of time until next serial device poll + if(cmd == DOME_POLL && curtime - last_status_time < status_req_interval) + return state; + pthread_mutex_lock(&serialmutex); + // check if we need to turn ON motors' relay + switch(cmd){ + case DOME_OPEN: + case DOME_CLOSE: + case DOME_OPEN_ONE: + case DOME_CLOSE_ONE: + //if(!motors_on()) goto ret; + break; + default: + break; + } + switch(cmd){ + case DOME_STOP: + if(!runcmd(ASIB_CMD_STOP, NULL)) goto ret; + break; + case DOME_OPEN: + if(!runcmd(ASIB_CMD_OPEN, NULL)) goto ret; + break; + case DOME_CLOSE: + if(!runcmd(ASIB_CMD_CLOSE, NULL)) goto ret; + break; + case DOME_OPEN_ONE: // due to bug in documentation, 0 - OPEN + if(par < 1 || par > 2) goto ret; + snprintf(buf, 127, "%d,0", par-1); + if(!runcmd(ASIB_CMD_MOVEONE, buf)) goto ret; + break; + case DOME_CLOSE_ONE: // due to bug in documentation, 90 - CLOSE + if(par < 1 || par > 2) goto ret; + snprintf(buf, 127, "%d,90", par-1); + if(!runcmd(ASIB_CMD_MOVEONE, buf)) goto ret; + break; + case DOME_RELAY_ON: + if(par < NRELAY_MIN || par > NRELAY_MAX) goto ret; + snprintf(buf, 127, "%d,1", par); + if(!runcmd(ASIB_CMD_RELAY, buf)) goto ret; + break; + case DOME_RELAY_OFF: + if(par < NRELAY_MIN || par > NRELAY_MAX) goto ret; + snprintf(buf, 127, "%d,0", par); + if(!runcmd(ASIB_CMD_RELAY, buf)) goto ret; + break; + default: + break; + } +ret: + if(check_status()){ + chkrelay(); + st = state; + } + if(state == DOME_S_IDLE) status_req_interval = STATUSREQ_IDLE; + else status_req_interval = STATUSREQ_MOVE; + pthread_mutex_unlock(&serialmutex); + write_header(); + return st; +} diff --git a/Daemons/domedaemon-astrosib-v3/dome.h b/Daemons/domedaemon-astrosib-v3/dome.h new file mode 100644 index 0000000..e1b6349 --- /dev/null +++ b/Daemons/domedaemon-astrosib-v3/dome.h @@ -0,0 +1,68 @@ +/* + * This file is part of the domedaemon-astrosib project. + * Copyright 2025 Edward V. Emelianov . + * + * 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 . + */ +#pragma once + +#include + +#define NRELAY_MIN 1 +#define NRELAY_MAX 3 + +// pause to clear power after stop - 5 seconds +#define POWER_STOP_TIMEOUT (5.) + +// dome finite state machine state +typedef enum{ + DOME_S_IDLE, // idle, motors disabled + DOME_S_MOVING, // moving, motors enabled + DOME_S_ERROR // some kind of error +} dome_state_t; + +// commands through dome_poll interface +typedef enum{ + DOME_POLL, // just poll state maching + DOME_STOP, // stop any moving + DOME_OPEN, // fully open dome + DOME_CLOSE, // fully close dome + DOME_OPEN_ONE, // open only one part # `par` (1-2) + DOME_CLOSE_ONE, // close only one part # `par` + DOME_RELAY_ON, // turn on relay # `par` (1-3) + DOME_RELAY_OFF, // turn off relay # `par` +} dome_cmd_t; + +// cover states +enum{ + COVER_CLOSED = 0, + COVER_OPENED = 1, + COVER_INTERMEDIATE = 3, +}; + +typedef struct{ + int coverstate[2]; // north/south covers state (3 - closed, 2 - opened, 0 - intermediate) + int encoder[2]; // encoders values + float Tin; // temperatures (unavailable) + float Tout; + float Imot[4]; // motors' currents + int relay[3]; // relays' state + int rainArmed; // rain sensor closes the dome + int israin; // arm sensor signal +} dome_status_t; + +double get_dome_status(dome_status_t *s); +dome_state_t get_dome_state(); +dome_state_t dome_poll(dome_cmd_t cmd, int par); +void dome_serialdev(sl_tty_t *serial); diff --git a/Daemons/domedaemon-astrosib-v3/domedaemon-astrosib.cflags b/Daemons/domedaemon-astrosib-v3/domedaemon-astrosib.cflags new file mode 100644 index 0000000..a07354f --- /dev/null +++ b/Daemons/domedaemon-astrosib-v3/domedaemon-astrosib.cflags @@ -0,0 +1 @@ +-std=c23 \ No newline at end of file diff --git a/Daemons/domedaemon-astrosib-v3/domedaemon-astrosib.config b/Daemons/domedaemon-astrosib-v3/domedaemon-astrosib.config new file mode 100644 index 0000000..24e2ef7 --- /dev/null +++ b/Daemons/domedaemon-astrosib-v3/domedaemon-astrosib.config @@ -0,0 +1,3 @@ +// Add predefined macros for your project here. For example: +// #define THE_ANSWER 42 +#define _XOPEN_SOURCE 666 diff --git a/Daemons/domedaemon-astrosib-v3/domedaemon-astrosib.creator b/Daemons/domedaemon-astrosib-v3/domedaemon-astrosib.creator new file mode 100644 index 0000000..e94cbbd --- /dev/null +++ b/Daemons/domedaemon-astrosib-v3/domedaemon-astrosib.creator @@ -0,0 +1 @@ +[General] diff --git a/Daemons/domedaemon-astrosib-v3/domedaemon-astrosib.creator.user b/Daemons/domedaemon-astrosib-v3/domedaemon-astrosib.creator.user new file mode 100644 index 0000000..42cc270 --- /dev/null +++ b/Daemons/domedaemon-astrosib-v3/domedaemon-astrosib.creator.user @@ -0,0 +1,220 @@ + + + + + + EnvironmentId + {cf63021e-ef53-49b0-b03b-2f2570cdf3b6} + + + ProjectExplorer.Project.ActiveTarget + 0 + + + ProjectExplorer.Project.EditorSettings + + true + true + true + + Cpp + + CppGlobal + + + + QmlJS + + QmlJSGlobal + + + 2 + KOI8-R + false + 4 + false + 0 + 80 + true + true + 1 + 0 + false + false + false + 1 + true + true + 0 + 8 + true + false + 1 + true + true + true + *.md, *.MD, Makefile + true + true + true + + + + ProjectExplorer.Project.PluginSettings + + + true + false + true + true + true + true + + false + + + 0 + true + + true + true + Builtin.DefaultTidyAndClazy + 4 + true + + + + true + + 0 + + + + ProjectExplorer.Project.Target.0 + + Desktop + true + Desktop + Desktop + {91347f2c-5221-46a7-80b1-0a054ca02f79} + 0 + 0 + 0 + + /home/eddy/Docs/SAO/10micron/C-sources/domedaemon-astrosib + + + + all + + true + GenericProjectManager.GenericMakeStep + + 1 + Build + Build + ProjectExplorer.BuildSteps.Build + + + + + clean + + true + GenericProjectManager.GenericMakeStep + + 1 + Clean + Clean + ProjectExplorer.BuildSteps.Clean + + 2 + false + + false + + По умолчанию + GenericProjectManager.GenericBuildConfiguration + 0 + 0 + + + 0 + Deploy + Deploy + ProjectExplorer.BuildSteps.Deploy + + 1 + + false + ProjectExplorer.DefaultDeployConfiguration + + 1 + + true + true + 0 + true + + + + 2 + + false + -e cpu-cycles --call-graph dwarf,4096 -F 250 + + ProjectExplorer.CustomExecutableRunConfiguration + + false + + true + true + + 1 + + 1 + + + 0 + Deploy + Deploy + ProjectExplorer.BuildSteps.Deploy + + 1 + + false + ProjectExplorer.DefaultDeployConfiguration + + 1 + + true + true + 0 + true + + + + 2 + + false + -e cpu-cycles --call-graph dwarf,4096 -F 250 + + ProjectExplorer.CustomExecutableRunConfiguration + + false + + true + true + + 1 + + + + ProjectExplorer.Project.TargetCount + 1 + + + Version + 22 + + diff --git a/Daemons/domedaemon-astrosib-v3/domedaemon-astrosib.cxxflags b/Daemons/domedaemon-astrosib-v3/domedaemon-astrosib.cxxflags new file mode 100644 index 0000000..ea5966d --- /dev/null +++ b/Daemons/domedaemon-astrosib-v3/domedaemon-astrosib.cxxflags @@ -0,0 +1 @@ +-std=c++23 \ No newline at end of file diff --git a/Daemons/domedaemon-astrosib-v3/domedaemon-astrosib.files b/Daemons/domedaemon-astrosib-v3/domedaemon-astrosib.files new file mode 100644 index 0000000..f84502f --- /dev/null +++ b/Daemons/domedaemon-astrosib-v3/domedaemon-astrosib.files @@ -0,0 +1,9 @@ +Readme.md +astrosib_proto.h +dome.c +dome.h +header.c +header.h +main.c +server.c +server.h diff --git a/Daemons/domedaemon-astrosib-v3/domedaemon-astrosib.includes b/Daemons/domedaemon-astrosib-v3/domedaemon-astrosib.includes new file mode 100644 index 0000000..e69de29 diff --git a/Daemons/domedaemon-astrosib-v3/header.c b/Daemons/domedaemon-astrosib-v3/header.c new file mode 100644 index 0000000..7d5a641 --- /dev/null +++ b/Daemons/domedaemon-astrosib-v3/header.c @@ -0,0 +1,132 @@ +/* + * This file is part of the baader_dome project. + * Copyright 2026 Edward V. Emelianov . + * + * 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 . + */ + +#include +#include +#include +#include + +#include "header.h" +#include "dome.h" +#include "server.h" + +#define VAL_LEN 22 + +static char *headername = NULL; +static char *dome_name = NULL; + +static int printhdr(int fd, const char *key, const char *val, const char *cmnt){ + char tmp[81]; + char tk[9]; + if(strlen(key) > 8){ + snprintf(tk, 8, "%s", key); + key = tk; + } + if(cmnt){ + snprintf(tmp, 81, "%-8s= %-21s / %s", key, val, cmnt); + }else{ + snprintf(tmp, 81, "%-8s= %s", key, val); + } + size_t l = strlen(tmp); + tmp[l] = '\n'; + ++l; + if(write(fd, tmp, l) != (ssize_t)l){ + WARN("write()"); + return 1; + } + return 0; +} + +// return TRUE if can write to given header file +int header_create(const char *file){ + if(!file) return FALSE; + FILE *hf = fopen(file, "w"); + if(!hf) return FALSE; + unlink(file); + if(headername) FREE(headername); + headername = strdup(file); + return TRUE; +} + +// set given `name` for telescope name +void domename(const char *name){ + if(dome_name) FREE(dome_name); + if(name){ + int l = strlen(name) + 3; + dome_name = MALLOC(char, l); + snprintf(dome_name, l, "'%s'", name); + } +} + +const char* stringst[] = { + [DOME_S_IDLE] = "idle", + [DOME_S_MOVING] = "moving", + [DOME_S_ERROR] = "error", +}; + +void write_header(){ + if(!headername) return; + char aname[PATH_MAX]; + char val[VAL_LEN]; +#define WRHDR(k, v, c) do{if(printhdr(fd, k, v, c)){goto returning;}}while(0) + snprintf(aname, PATH_MAX-1, "%sXXXXXX", headername); + int fd = mkstemp(aname); + if(fd < 0){ + LOGWARN("Can't write header file: mkstemp()"); + return; + } + fchmod(fd, 0644); + dome_status_t st; + dome_state_t curstate = get_dome_state(); + double stattime = get_dome_status(&st); + if(get_forbidden()) WRHDR("OPERATIO", "'FORBIDDEN'", "Observations are forbidden"); + if(dome_name) WRHDR("DOME", dome_name, "Dome manufacturer/name"); + int idx = (int)curstate; + if(idx < 0 || idx > DOME_S_ERROR) idx = DOME_S_ERROR; + snprintf(val, VAL_LEN, "'%s'", stringst[idx]); + WRHDR("DOMESTAT", val, "Dome status"); + snprintf(val, VAL_LEN, "'%s'", textst(st.coverstate[0])); + WRHDR("DOMECVR1", val, "Dome cover 1 status"); + snprintf(val, VAL_LEN, "'%s'", textst(st.coverstate[1])); + WRHDR("DOMECVR2", val, "Dome cover 2 status"); + snprintf(val, VAL_LEN, "%d", st.encoder[0]); + WRHDR("DOMEANG1", val, "Dome cover 1 angle"); + snprintf(val, VAL_LEN, "%d", st.encoder[1]); + WRHDR("DOMEANG2", val, "Dome cover 2 angle"); + snprintf(val, VAL_LEN, "%d", st.relay[0]); + WRHDR("DOMERLY1", val, "Dome relay1 state"); + snprintf(val, VAL_LEN, "%d", st.relay[1]); + WRHDR("DOMERLY2", val, "Dome relay2 state"); + snprintf(val, VAL_LEN, "%d", st.relay[2]); + WRHDR("DOMERLY3", val, "Dome relay3 state"); + if(st.israin) WRHDR("DOMERAIN", "1", "Dome rain sensor armed"); + snprintf(val, VAL_LEN, "%.3f", stattime); + char timebuf[BUFSIZ]; + time_t t = (time_t) stattime; + struct tm *tmp; + tmp = localtime(&t); + if(!tmp || 0 == strftime(timebuf, BUFSIZ, "Measurement time: %F %T", tmp)){ + LOGERR("localtime() returned NULL"); + goto returning; + } + WRHDR("TDOMMEAS", val, timebuf); +#undef WRHDR +returning: + close(fd); + rename(aname, headername); +} diff --git a/Daemons/domedaemon-astrosib-v3/header.h b/Daemons/domedaemon-astrosib-v3/header.h new file mode 100644 index 0000000..553e7b1 --- /dev/null +++ b/Daemons/domedaemon-astrosib-v3/header.h @@ -0,0 +1,23 @@ +/* + * This file is part of the domedaemon-astrosib project. + * Copyright 2026 Edward V. Emelianov . + * + * 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 . + */ + +#pragma once + +void write_header(); +int header_create(const char *file); +void domename(const char *name); diff --git a/Daemons/domedaemon-astrosib-v3/main.c b/Daemons/domedaemon-astrosib-v3/main.c new file mode 100644 index 0000000..7a245de --- /dev/null +++ b/Daemons/domedaemon-astrosib-v3/main.c @@ -0,0 +1,176 @@ +/* + * This file is part of the Snippets project. + * Copyright 2024 Edward V. Emelianov . + * + * 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 . + */ + +#include +#include +#include +#include // wait +#include //prctl +#include + +#include "header.h" +#include "server.h" + +// TCP socket port +#define DEFAULT_PORT "55555" +// baudrate - 9600 +#define DEFAULT_SERSPEED 9600 +// serial polling timeout - 250ms +#define DEFAULT_SERTMOUT 250000 +#define DEFAULT_PIDFILE "/tmp/domedaemon.pid" +#define DEFAULT_HEADERFILE "/tmp/dome.fits" +#define DEFAULT_DOMENAME "Astrosib" + +static pid_t childpid = 0; +static sl_tty_t *serial = NULL; + +typedef struct{ + int help; + char *device; // serial device name + char *node; // port to connect or UNIX socket name + char *logfile; // logfile name + char *pidfile; // PID-file path + char *headerfile; // path to FITS-header with dome parameters + char *dome_name; // name of dome + int isunix; // open UNIX-socket instead of TCP + int verbose; // verbose level +} parameters; + + +static parameters G = { + .node = DEFAULT_PORT, + .pidfile = DEFAULT_PIDFILE, + .headerfile = DEFAULT_HEADERFILE, + .dome_name = DEFAULT_DOMENAME, +}; + +static sl_option_t cmdlnopts[] = { + {"help", NO_ARGS, NULL, 'h', arg_int, APTR(&G.help), "show this help"}, + {"device", NEED_ARG, NULL, 'd', arg_string, APTR(&G.device), "serial device name"}, + {"node", NEED_ARG, NULL, 'n', arg_string, APTR(&G.node), "UNIX socket name or network port to connect (default: " DEFAULT_PORT ")"}, + {"logfile", NEED_ARG, NULL, 'l', arg_string, APTR(&G.logfile), "save logs to file"}, + {"unix", NO_ARGS, NULL, 'u', arg_int, APTR(&G.isunix), "open UNIX-socket instead of TCP"}, + {"verbose", NO_ARGS, NULL, 'v', arg_none, APTR(&G.verbose), "logging verbose level (each -v adds one)"}, + {"pidfile", NEED_ARG, NULL, 'p', arg_string, APTR(&G.pidfile), "full path to PID-file (default: " DEFAULT_PIDFILE ")"}, + {"headerfile",NEED_ARG, NULL, 'H', arg_string, APTR(&G.headerfile),"full path to output FITS-header (default: " DEFAULT_HEADERFILE ")"}, + {"domename",NEED_ARG, NULL, 'N', arg_string, APTR(&G.dome_name), "dome name in FITS-header (default: " DEFAULT_DOMENAME ")"}, + end_option +}; + +void sl_iffound_deflt(pid_t pid){ + WARNX("Another copy of this process found, pid=%d. Exit.", pid); + exit(1); // don't run `signals` to protect foreign PID-file from removal +} + +// SIGUSR1 - FORBID observations +// SIGUSR2 - allow +void signals(int sig){ + if(sig){ + if(signals != signal(sig, SIG_IGN)) exit(sig); // function called "as is", before sig registration + if(childpid == 0){ // child -> test USR1/USR2 + LOGDBG("Child gotta signal %d", sig); + if(sig == SIGUSR1){ + forbid_observations(1); + LOGMSG("Got signal `observations forbidden`"); + signal(sig, signals); + return; + }else if(sig == SIGUSR2){ + forbid_observations(0); + LOGMSG("Got signal `observations permitted`"); + signal(sig, signals); + return; + } + } + LOGDBG("Get signal %d, quit.\n", sig); + } + if(childpid == 0){ + DBG("Stop server"); + LOGMSG("Stop server"); + stopserver(); + DBG("Close terminal"); + LOGMSG("Close terminal"); + if(serial) sl_tty_close(&serial); + }else{ + if(G.pidfile){ + LOGMSG("Unlink %s", G.pidfile); + usleep(10000); + unlink(G.pidfile); + } + } + LOGERR("Exit with status %d", sig); + exit(sig); +} + +int main(int argc, char **argv){ + sl_init(); + sl_parseargs(&argc, &argv, cmdlnopts); + if(G.help) sl_showhelp(-1, cmdlnopts); + if(!G.node) ERRX("Point node"); + if(!G.device) ERRX("Point path to serial device"); + if(!header_create(G.headerfile)) + ERRX("Cannot write into '%s'", G.headerfile); + domename(G.dome_name); + sl_check4running((char*)__progname, G.pidfile); +#ifndef EBUG + if(sl_daemonize()) ERR("Can't daemonize!"); +#endif + sl_loglevel_e lvl = G.verbose + LOGLEVEL_ERR; + if(lvl >= LOGLEVEL_AMOUNT) lvl = LOGLEVEL_AMOUNT - 1; + if(G.logfile) OPENLOG(G.logfile, lvl, 1); + LOGMSG("Started"); + signal(SIGTERM, signals); + signal(SIGINT, signals); + signal(SIGQUIT, signals); + signal(SIGTSTP, SIG_IGN); + signal(SIGUSR1, SIG_IGN); + signal(SIGUSR2, SIG_IGN); +#ifndef EBUG + time_t lastd = 0; + while(1){ // guard for dead processes + pid_t childpid = fork(); + if(childpid){ + DBG("Created child with PID %d\n", childpid); + LOGMSG("Created child with PID %d\n", childpid); + wait(NULL); + time_t t = time(NULL); + 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{ + prctl(PR_SET_PDEATHSIG, SIGTERM); // send SIGTERM to child when parent dies + break; // go out to normal functional + } + } +#endif + sl_socktype_e type = (G.isunix) ? SOCKT_UNIX : SOCKT_NETLOCAL; + serial = sl_tty_new(G.device, DEFAULT_SERSPEED, 4096); + if(serial) serial = sl_tty_open(serial, 1); + if(!serial){ + LOGERR("Can't open serial device %s", G.device); + ERRX("Can't open serial device %s", G.device); + } + signal(SIGUSR1, signals); + signal(SIGUSR2, signals); + sl_tty_tmout(DEFAULT_SERTMOUT); + server_run(type, G.node, serial); + LOGERR("Unreacheable code reached!"); + return 1; +} diff --git a/Daemons/domedaemon-astrosib-v3/server.c b/Daemons/domedaemon-astrosib-v3/server.c new file mode 100644 index 0000000..4a8c75b --- /dev/null +++ b/Daemons/domedaemon-astrosib-v3/server.c @@ -0,0 +1,290 @@ +/* + * This file is part of the Snippets project. + * Copyright 2024 Edward V. Emelianov . + * + * 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 . + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "dome.h" +#include "server.h" + +// max age time of last status - 30s +#define STATUS_MAX_AGE (30.) + +// if there's no signal from weather over `WEATHER_LOST` seconds, close the dome +#define WEATHER_LOST (300.) +// interval of weather polling +#define WEATH_POLL (5.) + +// commands +#define CMD_UNIXT "unixt" +#define CMD_STATUS "status" +#define CMD_STATUST "statust" +#define CMD_RELAY "relay" +#define CMD_OPEN "open" +#define CMD_CLOSE "close" +#define CMD_STOP "stop" +#define CMD_HALF "half" + +// main socket +static sl_sock_t *s = NULL; + +// external (manual) signal "deny/allow" +static atomic_bool ForbidObservations = 0; // ==1 if all is forbidden -> close dome and not allow to open +// weather don't allow to open +static atomic_bool BadWeather = 0; + +#define CHKALLOWED() do{if(ForbidObservations || BadWeather){return RESULT_FAIL;}}while(0) + +/////// 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()); + sl_sock_sendstrmessage(c, buf); + return RESULT_SILENCE; +} +// status - get current dome status in old format (first four numbers) +static sl_sock_hresult_e statush(sl_sock_t *c, _U_ sl_sock_hitem_t *item, _U_ const char *req){ + char buf[128]; + dome_status_t dome_status; + double lastt = get_dome_status(&dome_status); + if(sl_dtime() - lastt > STATUS_MAX_AGE) return RESULT_FAIL; + snprintf(buf, 127, "%s=%d,%d,%d,%d\n", item->key, dome_status.coverstate[0], + dome_status.coverstate[1], dome_status.encoder[0], dome_status.encoder[1]); + sl_sock_sendstrmessage(c, buf); + return RESULT_SILENCE; +} +const char *textst(int coverstate){ + switch(coverstate){ + case COVER_INTERMEDIATE: return "intermediate"; + case COVER_OPENED: return "opened"; + case COVER_CLOSED: return "closed"; + default: return "undefined"; + } + return NULL; +} +// statust - text format status +static sl_sock_hresult_e statusth(sl_sock_t *c, _U_ sl_sock_hitem_t *item, _U_ const char *req){ + char buf[BUFSIZ]; + dome_status_t dome_status; + double lastt = get_dome_status(&dome_status); + if(sl_dtime() - lastt > STATUS_MAX_AGE) return RESULT_FAIL; + if(BUFSIZ - 1 > snprintf(buf, BUFSIZ-1, "operations=%s\ncover1=%s\ncover2=%s\nangle1=%d\nangle2=%d\nrelay1=%d\nrelay2=%d\nrelay3=%d\nreqtime=%.9f\n", + get_forbidden() ? "forbidden" : "permitted", + textst(dome_status.coverstate[0]), textst(dome_status.coverstate[1]), + dome_status.encoder[0], dome_status.encoder[1], + dome_status.relay[0], dome_status.relay[1], dome_status.relay[2], + lastt)) buf[BUFSIZ-1] = 0; + sl_sock_sendstrmessage(c, buf); + return RESULT_SILENCE; +} +// relay on/off +static sl_sock_hresult_e relays(int Nrelay, int Stat){ + dome_cmd_t cmd = Stat ? DOME_RELAY_ON : DOME_RELAY_OFF; + if(DOME_S_ERROR == dome_poll(cmd, Nrelay)) return RESULT_FAIL; + return RESULT_OK; +} +static sl_sock_hresult_e relay(sl_sock_t *c, sl_sock_hitem_t *item, const char *req){ + char buf[128]; + int N = item->key[sizeof(CMD_RELAY) - 1] - '0'; + if(N < NRELAY_MIN|| N > NRELAY_MAX) return RESULT_BADKEY; + if(!req || !*req){ // getter + dome_status_t dome_status; + double lastt = get_dome_status(&dome_status); + if(sl_dtime() - lastt > STATUS_MAX_AGE) return RESULT_FAIL; + snprintf(buf, 127, "%s=%d\n", item->key, dome_status.relay[N-1]); + sl_sock_sendstrmessage(c, buf); + return RESULT_SILENCE; + } + int Stat = *req - '0'; + return relays(N, Stat); +} +// dome open/close/stop +static sl_sock_hresult_e domecmd(dome_cmd_t cmd){ + if(DOME_S_ERROR == dome_poll(cmd, 0)) return RESULT_FAIL; + return RESULT_OK; +} +static sl_sock_hresult_e opendome(_U_ sl_sock_t *c, _U_ sl_sock_hitem_t *item, _U_ const char *req){ + CHKALLOWED(); + return domecmd(DOME_OPEN); +} +static sl_sock_hresult_e closedome(_U_ sl_sock_t *c, _U_ sl_sock_hitem_t *item, _U_ const char *req){ + return domecmd(DOME_CLOSE); +} +static sl_sock_hresult_e stopdome(_U_ sl_sock_t *c, _U_ sl_sock_hitem_t *item, _U_ const char *req){ + CHKALLOWED(); // don't allow to stop closing on forbidden state + return domecmd(DOME_STOP); +} +// half open/close +static sl_sock_hresult_e halfmove(sl_sock_t *c, sl_sock_hitem_t *item, const char *req){ + CHKALLOWED(); + char buf[128]; + int N = item->key[sizeof(CMD_HALF) - 1] - '0'; + if(N < 1 || N > 2) return RESULT_BADKEY; + if(!req || !*req){ // getter + dome_status_t dome_status; + double lastt = get_dome_status(&dome_status); + if(sl_dtime() - lastt > STATUS_MAX_AGE) return RESULT_FAIL; + int s = dome_status.coverstate[N-1]; + int S = -1; + switch(s){ + case COVER_OPENED: S = 1; break; + case COVER_CLOSED: S = 0; break; + default: break; + } + snprintf(buf, 127, "%s=%d\n", item->key, S); + sl_sock_sendstrmessage(c, buf); + return RESULT_SILENCE; + } + int Stat = *req - '0'; + dome_cmd_t cmd = Stat ? DOME_OPEN_ONE : DOME_CLOSE_ONE; + green("\n\nstat=%d, cmd=%d, N=%d\n\n", Stat, cmd, N); + if(DOME_S_ERROR == dome_poll(cmd, N)) return RESULT_FAIL; + return RESULT_OK; +} + +// and all handlers collection +static sl_sock_hitem_t handlers[] = { + {dtimeh, CMD_UNIXT, "get server's UNIX time", NULL}, + {statush, CMD_STATUS, "get dome's status in old format", NULL}, + {statusth, CMD_STATUST, "get dome's status in full text format", NULL}, + {relay, CMD_RELAY "1", "turn on/off (=1/0) relay 1", NULL}, + {relay, CMD_RELAY "2", "turn on/off (=1/0) relay 2", NULL}, + {relay, CMD_RELAY "3", "turn on/off (=1/0) relay 3", NULL}, + {opendome, CMD_OPEN, "open dome", NULL}, + {closedome, CMD_CLOSE, "close dome", NULL}, + {stopdome, CMD_STOP, "stop moving", NULL}, + {halfmove, CMD_HALF "1", "open/close (=1/0) north half of dome", NULL}, + {halfmove, CMD_HALF "2", "open/close (=1/0) south half of dome", 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 +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); +} + +void server_run(sl_socktype_e type, const char *node, sl_tty_t *serial){ + if(!node || !serial){ + LOGERR("server_run(): wrong parameters"); + ERRX("server_run(): wrong parameters"); + } + weather_data_t weather; + dome_serialdev(serial); + s = sl_sock_run_server(type, node, -1, handlers); + if(!s) ERRX("Can't create socket and/or run threads"); + sl_sock_changemaxclients(s, 5); + sl_sock_maxclhandler(s, toomuch); + sl_sock_connhandler(s, connected); + sl_sock_dischandler(s, disconnected); + double tnow = 0., tweather = 0.; + int cmdclosed = 0; + while(s && s->connected){ + usleep(100000); + tnow = sl_dtime(); + if(!s->rthread){ + LOGERR("Server handlers thread is dead"); + break; + } + if(tnow - tweather > WEATH_POLL){ + DBG("Poll weather"); + if(0 == get_weather_data(&weather)){ // got OK -> check if observations are forbidden + DBG("Got weather data"); + tweather = tnow; + int bad = 0; + if(tnow - (double)weather.last_update > WEATHER_LOST){ bad = 1; DBG("weather measurements are too old"); } + if(weather.forceoff || weather.rain || weather.weather > WEATHER_BAD){ bad = 1; DBG("Bad weather"); } + if(bad) BadWeather = 1; + else BadWeather = 0; + }else{ + DBG("Can't get weather"); + if(tnow - tweather > WEATHER_LOST){ + DBG("Lost weather timeout"); + BadWeather = 1; // lost weather IPC + } + } + } + // finite state machine polling + dome_poll(DOME_POLL, 0); + if(ForbidObservations || BadWeather){ + if(0 == cmdclosed){ + if(DOME_S_ERROR != dome_poll(DOME_CLOSE, 0)){ + LOGERR("Send command 'close' due to forbidden state"); + cmdclosed = 1; + } + } + } else cmdclosed = 0; + sleep(1); + } + sl_sock_delete(&s); + ERRX("Server handlers thread is dead"); +} + +void stopserver(){ + if(s && s->connected){ + s->connected = 0; + usleep(5000); + if(s) sl_sock_delete(&s); + } +} + +void forbid_observations(int forbid){ + if(forbid){ + ForbidObservations = true; + LOGWARN("Got forbidden signal"); + }else{ + ForbidObservations = false; + LOGWARN("Got allowed signal"); + } + DBG("Change ForbidObservations=%d", forbid); +} + +int get_forbidden(){ + return (ForbidObservations || BadWeather); +} diff --git a/Daemons/domedaemon-astrosib-v3/server.h b/Daemons/domedaemon-astrosib-v3/server.h new file mode 100644 index 0000000..98504a0 --- /dev/null +++ b/Daemons/domedaemon-astrosib-v3/server.h @@ -0,0 +1,32 @@ +/* + * This file is part of the domedaemon-astrosib project. + * Copyright 2025 Edward V. Emelianov . + * + * 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 . + */ + +#pragma once + +#include + +// size of weather/status buffers +#define STATBUF_SZ 256 +// dome polling interval (clear watchdog & get status) +#define T_INTERVAL (5.0) + +void server_run(sl_socktype_e type, const char *node, sl_tty_t *serial); +const char *textst(int coverstate); +void stopserver(); +void forbid_observations(int forbid); +int get_forbidden();