diff --git a/Poweroff_daemon/Readme.md b/Poweroff_daemon/Readme.md index 2dc6168..158f77d 100644 --- a/Poweroff_daemon/Readme.md +++ b/Poweroff_daemon/Readme.md @@ -1,3 +1,253 @@ -Simple daemon checking voltage & button0 state of my 'fan controller'. +# poweroff_daemon -Alpha-version, there may be some problems... +`poweroff_daemon` is a small Linux daemon that monitors a serial-attached [power/fan control +module](https://github.com/eddyem/stm32samples/tree/master/F0%3AF030%2CF042%2CF072/Socket_fans) of a +single-board computer. The board is powered by four 18650 cells and an external 16.8 V supply. The daemon +polls the module for button state and conditional battery voltage and calls `/sbin/poweroff` when a shutdown +condition is detected. + +The daemon is intended for headless systems where the power module must shut the computer down before the +batteries are deeply discharged, or when a physical `BUTTON0` is pressed. + +## Features + +- Polls a serial device for: + - `BUTTON0` state; + - `V12` voltage value (in arbitrary units, not hundreds of Volts!). +- Triggers `/sbin/poweroff` when: + - `BUTTON0` is pressed; + - `V12` falls below the configured low-voltage threshold. +- Runs as a daemon. +- Supervises a child process and restarts it if it exits unexpectedly. +- Provides a UNIX-domain socket for sending custom commands to the serial device. +- Supports optional logging to a file. +- Uses newline-terminated serial protocol (`\n`, no `\r`). + +## Project files + +| File | Purpose | +|------|---------| +| `main.c` | Program entry point, daemonization, child supervision, main polling loop, poweroff trigger. | +| `cmdlnopts.c` / `cmdlnopts.h` | Command-line option parsing and default configuration values. | +| `serial.c` / `serial.h` | Serial port handling, command/response parsing, button and voltage checks. | +| `server.c` / `server.h` | UNIX-domain socket server and request handlers. | + +## Requirements + +- Linux. +- C compiler and build tools. +- [`usefull_macros`](https://github.com/eddyem/snippets_library) library. +- `pthread` support. +- A serial device connected to the power/fan control module, usually `/dev/ttyUSB0`. +- Root privileges or suitable permissions for: + - opening the serial device; + - executing `/sbin/poweroff`; + - creating the PID file and socket, depending on paths. + +Build with `make` commands, supporting several targets: + +- `release` (default) - release build; +- `debug` - build with debugging on; +- `clean` - clear temporarily build files; +- `xclean` - also clean binary file. + +There's no option `install`, so you should manually copy binary file into some destination. + + +## Usage + +```sh +./poweroff_daemon [options] +``` + +Example: + +```sh +./poweroff_daemon \ + --device /dev/ttyUSB0 \ + --baudrate 115200 \ + --interval 1.0 \ + --sockpath @poweroffdaemon \ + --log /var/log/poweroff_daemon.log \ + --verbose +``` + +The daemon normally needs to run as root because it calls `/sbin/poweroff`. + +## Command-line options + +| Short | Long | Argument | Default | Description | +|-------|------|----------|---------|-------------| +| `-p` | `--pidfile` | string | `/tmp/powerdaemon.pid` | PID file path. | +| `-l` | `--log` | string | none | Log file path. If not set, no logging. | +| `-i` | `--interval` | double | `1.0` | Poll interval in seconds. | +| `-t` | `--timeout` | double | `100000` | Serial read timeout in microseconds. | +| `-v` | `--verbose` | none | warning level | Increases verbosity. Each `-v` adds a level. | +| `-d` | `--device` | string | `/dev/ttyUSB0` | Serial device path. | +| `-b` | `--baudrate` | integer | `115200` | Serial baudrate. For USB CDC devices this is often irrelevant. | +| `-s` | `--sockpath` | string | `@poweroffdaemon` | UNIX-domain socket path. The leading `@` means the Linux abstract socket namespace. | +| `-h` | `--help` | none | | Show help and exit. | + +## Serial protocol + +The daemon communicates with the power/fan module using newline-terminated text commands. Only `\n` is used +as a line separator; `\r` is not expected. + +Built-in commands: + +| Command | Expected key | Meaning | +|---------|--------------|---------| +| `B\n` | `BUTTON0` | Read button state. A non-zero value triggers poweroff. | +| `V\n` | `V12` | Read voltage value. | + +For more information read documentation for [power/fan control +module](https://github.com/eddyem/stm32samples/tree/master/F0%3AF030%2CF042%2CF072/Socket_fans). + +Responses are parsed line by line. Each relevant line is expected to contain a key/value pair, for example: + +```text +BUTTON0 = 0 +V12 = 1200 +``` + +For USB CDC serial devices, port settings such as baudrate and data format are usually ignored by the device. +The `--baudrate` option is retained for compatibility or connection over USB-UART adapter. + +## Shutdown conditions + +The current code triggers poweroff when either condition is true: + +1. `BUTTON0` value is non-zero. +2. `V12` value is below `LOWEST_V12`. + +Relevant constants are defined in `serial.h`: + +```c +#define CMD_BTNCHECK "B\n" +#define ANS_BTN0STATE "BUTTON0" + +#define CMD_GETVOLTAGE "V\n" +#define ANS_V12 "V12" +#define LOG_V12 1150 +#define LOG_VOLTAGE_DT 60 +#define LOWEST_V12 970 + +#define MAX_WERR_CNT 5 +#define MAX_RERR_CNT 15 +``` + +The code logs voltage (in arbitrary units depending on voltage divider configuration) as: + +```c +(double)voltage / 100. +``` + +For current device configuration value of 11.73 V means 16.8 V. + +So with the current constants, `LOWEST_V12 == 970` is logged as `9.70 V` (near 13.9 V for my configuration) +and `LOG_V12 == 1150` is logged as `11.50 V` (near 16.5 V - started working after power lost). Verify that +these values match the actual units and safe thresholds of your battery pack and power module before +deploying the daemon. + +Additional behavior: + +- If `V12` is below `LOG_V12` but not below `LOWEST_V12`, the voltage is logged at most once per +`LOG_VOLTAGE_DT` seconds. +- When voltage returns above `LOG_V12`, a "power restored" message is logged. +- The current implementation does not implement multi-sample confirmation, debounce, or hysteresis. A single +reading can trigger poweroff. + +## UNIX socket interface + +The daemon starts a UNIX-domain socket server. By default it uses the Linux abstract socket name: + +```text +@poweroffdaemon +``` + +Clients can connect and send text commands. + +Default behavior: + +- Any message received by the default handler is forwarded to the serial device. +- The serial response is sent back to the client. +- The special request `_help` sends the literal command `help` to the serial device and returns its response. + +Important: the socket interface currently forwards arbitrary client input to the serial device. It does not +implement authentication or command filtering. On a multi-user system, use a filesystem socket with +restrictive permissions or add peer credential checks and a command whitelist. + +## Runtime behavior + +1. The program initializes logging and parses command-line options. +2. It checks whether another instance is already running using the PID file. +3. If a log file is configured, it opens the log. +4. The process daemonizes. +5. The parent process supervises a child process: + - if the child exits, the parent waits 5 seconds and starts a new child; + - the parent logs child deaths. +6. The child process: + - sets `PR_SET_PDEATHSIG` so that it receives `SIGTERM` if the parent dies; + - opens the serial device; + - starts the UNIX socket server; + - enters the polling loop. +7. On each poll, the child checks buttons and voltage. +8. If a shutdown condition is met, it logs the event and executes: + + ```c + system("/sbin/poweroff"); + ``` + +9. On normal loop exit, it stops the socket server and closes the serial port. + +## Signals + +The daemon handles `SIGTERM`, `SIGINT`, and `SIGQUIT`; `SIGTSTP` is ignored. `SIGHUP` ignored by `sl_daemonize()`. + +The current signal handler is simple and calls logging and cleanup functions directly. For production use, +consider replacing it with an async-signal-safe handler that only sets a flag or writes to a self-pipe, and +perform cleanup in the main loop. + +## Logging + +Logging is implemented through `usefull_macros`. + +- By default, the log level is warning. +- Each `--verbose` option increases the log level. +- If `--log` is specified, the daemon opens the given log file before daemonizing. +- If the log file cannot be created, a warning is emitted. + +## Safety and deployment notes + +This daemon can power off the machine. Before deploying it, verify the following: + +- The `V12` units and thresholds match your hardware. +- The low-voltage threshold is safe for your four-cell battery pack. +- A single noisy reading cannot cause an unwanted shutdown, or add filtering/debounce if needed. +- Loss of serial communication has the desired behavior. In the current code, repeated serial errors cause +the child process to exit and be restarted by the parent; they do not directly call `poweroff`. +- The socket interface is appropriately protected. +- The PID file path is safe. The default `/tmp/powerdaemon.pid` may be unsuitable for a root daemon on a +multi-user system. +- Only one process can access the serial device. The current code does not set an exclusive serial lock. +- `/sbin/poweroff` exists and works on the target system. + +## Usage example + +Because the program daemonizes itself, you can run it over OpenRC's `local` service, creating bash-script +`powerdaemon.start` in `/etc/local.d`: + +```bash +#!/bin/bash + +/usr/local/sbin/powerdaemon -vvv -l /RAID/powerdaemon.log -p /tmp/powerdaemon.pid & +``` + +The main process doesn't run `fork()`, so you can start it even with `supervise-daemon` or other services. + +Adjust paths, user, and permissions to match your system. + +## License + +This project is licensed under the GNU General Public License, version 3 or later. See the source file +headers for details. diff --git a/Poweroff_daemon/cmdlnopts.c b/Poweroff_daemon/cmdlnopts.c index c93ccd1..f829002 100644 --- a/Poweroff_daemon/cmdlnopts.c +++ b/Poweroff_daemon/cmdlnopts.c @@ -38,22 +38,26 @@ static cmdln_t G = { static int help = 0; static sl_option_t options[] = { - {"pidfile", NEED_ARG, NULL, 'p', arg_string, &G.pidfile, "PID file path, default: " STR(DEFAULT_PIDFILE)}, - {"log", NEED_ARG, NULL, 'l', arg_string, &G.logfile, "log file path, default: none"}, + {"pidfile", NEED_ARG, NULL, 'p', arg_string, &G.pidfile, "PID file path (absolute!), default: " STR(DEFAULT_PIDFILE)}, + {"log", NEED_ARG, NULL, 'l', arg_string, &G.logfile, "log file path (absolute!), default: none"}, {"interval",NEED_ARG, NULL, 'i', arg_double, &G.poll_interval, "poll interval (seconds), default:" STR(DEFAULT_INTERVAL)}, {"timeout", NEED_ARG, NULL, 't', arg_double, &G.timeout_us, "serial in timeout (useconds), default: " STR(READ_TIMEOUT_US)}, {"verbose", NO_ARGS, NULL, 'v', arg_none, &G.verbose, "verbose output (each -v adds level), default: WARN"}, - {"device", NEED_ARG, NULL, 'd', arg_string, &G.serialdev, "serial device, default: " STR(DEFAULT_DEV)}, + {"device", NEED_ARG, NULL, 'd', arg_string, &G.serialdev, "serial device path (absolute!), default: " STR(DEFAULT_DEV)}, {"baudrate",NEED_ARG, NULL, 'b', arg_int, &G.baudrate, "serial baudrate, default: " STR(DEFAULT_BAUDRATE)}, {"sockpath",NEED_ARG, NULL, 's', arg_string, &G.sockpath, "UNIX-socket path, default: " STR(DEFAULT_SOCKPATH)}, - {"help", NO_ARGS, NULL, 'h', arg_none, &help, "show this help"}, + {"help", NO_ARGS, NULL, 'h', arg_none, &help, "show this help"}, end_option }; cmdln_t *parseargs(int *argc, char ***argv){ sl_parseargs(argc, argv, options); - if(*argc > 0) ERRX("%d unknown opions"); + if(*argc > 0) ERRX("%d unknown opions", *argc); if (help) sl_showhelp(-1, options); + // for 32-bit useconds_t max poll_interval could be near 4000 + if(G.poll_interval < 1e-3 || G.poll_interval > 900) ERRX("poll interval should be from 1 ms to 15 minutes"); + if(G.timeout_us < 100 || G.timeout_us > 5000000) ERRX("timeout (us) should be from 100 us to 5 seconds"); + if(G.baudrate < 1200 || G.baudrate > 4000000) ERRX("Wrong baudrate: should be from 1200 to 4000000"); return &G; } diff --git a/Poweroff_daemon/main.c b/Poweroff_daemon/main.c index 84a9baf..cefd513 100644 --- a/Poweroff_daemon/main.c +++ b/Poweroff_daemon/main.c @@ -1,7 +1,25 @@ +/* + * This file is part of the poweroff_daemon 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 . + */ + /* * monitor_daemon.c - daemon that monitors serial device /dev/ttyUSB0. * It sends commands "B\n" and "V\n", parses responses, and triggers poweroff - * if BUTTON0 is pressed or V12 is below 9700. + * if BUTTON0 is pressed or V12 is below 970. * * Protocol uses only '\n' as line separator (no '\r'). * USB CDC device: port settings (baudrate, format) are irrelevant. @@ -26,7 +44,7 @@ #include "server.h" static cmdln_t *G = NULL; -bool isrunning = false; +static bool isrunning = false; static pid_t childpid = 0; void signals(int sig){ @@ -38,11 +56,10 @@ void signals(int sig){ LOGERR("Main process exits with status %d", sig); if(G->pidfile) // remove unnesessary PID file unlink(G->pidfile); + exit(sig); }else{ isrunning = false; - sleep(2); // let child to graceful out } - exit(sig); } int main(int argc, char **argv){ @@ -124,7 +141,7 @@ int main(int argc, char **argv){ LOGWARN("Trigger condition met, executing poweroff"); DBG("poweroff"); int ret = system("/sbin/poweroff"); - if(ret == -1){ + if(ret){ LOGERR("Failed to execute poweroff: %s", strerror(errno)); }else{ LOGWARN("Poweroff called"); diff --git a/Poweroff_daemon/poweroff_daemon.files b/Poweroff_daemon/poweroff_daemon.files index 5a88634..e641374 100644 --- a/Poweroff_daemon/poweroff_daemon.files +++ b/Poweroff_daemon/poweroff_daemon.files @@ -1,3 +1,4 @@ +Readme.md cmdlnopts.c cmdlnopts.h main.c diff --git a/Poweroff_daemon/serial.c b/Poweroff_daemon/serial.c index 05821f8..17864f7 100644 --- a/Poweroff_daemon/serial.c +++ b/Poweroff_daemon/serial.c @@ -30,13 +30,15 @@ bool open_serial(const char *path, int baudrate){ tty = sl_tty_new((char*)path, baudrate, 1024); if(!tty) return false; /* Do not call sl_tty_setformat: default 8N1 is fine. */ - if(!sl_tty_open(tty, 1)) return false; + if(!sl_tty_open(tty, 1)){ + if(tty) sl_tty_close(&tty); + return false; + } return true; } void close_serial(){ sl_tty_close(&tty); - tty = NULL; } /* @@ -52,14 +54,18 @@ static bool parse_int_from_response(const char *buf, const char *key, int *val) char k[SL_KEY_LEN], v[SL_VAL_LEN]; int res = sl_get_keyval(line, k, v); if(res == 2 && strcmp(k, key) == 0){ - *val = atoi(v); + int I; + if(!sl_str2i(&I, v)) continue; free(copy); - DBG("Buf: %s, key: %s, val: %d", buf, key, *val); + if(val){ + *val = I; + DBG("Buf: %s, key: %s, val: %d", buf, key, *val); + } return true; } line = strtok(NULL, "\n"); } - DBG("Buf: %s, key: %s, val: %d", buf, key, *val); + if(val) DBG("Buf: %s, key: %s, val: %d", buf, key, *val); free(copy); return false; } @@ -67,8 +73,10 @@ static bool parse_int_from_response(const char *buf, const char *key, int *val) static bool get_int(const char *cmdstring, const char *key, int *answer){ if(!tty || !cmdstring || !key) return false; static int errcnt = 0; + char buf[BUFSIZ]; DBG("Ask parameter '%s' from command %s", key, cmdstring); pthread_mutex_lock(&serial_mutex); + while(sl_tty_read(tty) > 0); // clear incoming buffer if(sl_tty_write(tty->comfd, cmdstring, strlen(cmdstring))){ WARNX("Write error"); LOGERR("Serial writing error"); @@ -81,25 +89,25 @@ static bool get_int(const char *cmdstring, const char *key, int *answer){ } int n = sl_tty_read(tty); if(n <= 0){ - char buf[BUFSIZ]; strncpy(buf, cmdstring, BUFSIZ-1); + buf[BUFSIZ-1] = 0; char *n = strchr(buf, '\n'); if(n) *n = 0; WARNX("No response"); LOGERR("No response to command '%s'", buf); pthread_mutex_unlock(&serial_mutex); if(++errcnt > MAX_RERR_CNT){ - LOGERR("No answers -> go off"); - ERRX("No answers -> go off"); + LOGERR("No answers -> die"); + ERRX("No answers -> die"); } return false; } - errcnt = 0; int i = 0; bool gotint = parse_int_from_response(tty->buf, key, &i); if(!gotint) DBG("Didn't get int from %s", tty->buf); pthread_mutex_unlock(&serial_mutex); if(!gotint) return false; + errcnt = 0; DBG("Got int: %d", i); if(answer) *answer = i; return true; @@ -116,11 +124,12 @@ bool check_buttons(){ return false; } -/* Check voltage: returns 1 if V12 < 9700 */ +/* Check voltage: returns 1 if V12 < 970 */ bool check_voltage(){ int voltage = 0; static double tlog = -1.; if(!get_int(CMD_GETVOLTAGE, ANS_V12, &voltage)) return false; + if(voltage < 0 || voltage > LOG_V12*2) return false; // trash in answer if(voltage < LOWEST_V12){ LOGERR("V12 low: %d (%.2f V)", voltage, (double)voltage / 100.); return true; @@ -162,7 +171,7 @@ bool send_custom_command(const char *command, char *answer, size_t anslen){ } }else WARNX("Can't write to TTY"); pthread_mutex_unlock(&serial_mutex); - if(L > 0){ + if(L > 0 && answer){ if(anslen < 1) answer[-1] = 0; else *answer = 0; } diff --git a/Poweroff_daemon/server.c b/Poweroff_daemon/server.c index 4fc254a..09549ea 100644 --- a/Poweroff_daemon/server.c +++ b/Poweroff_daemon/server.c @@ -21,7 +21,6 @@ #include "serial.h" #include "server.h" -extern bool isrunning; static sl_sock_t *s = NULL; static sl_sock_hresult_e defhandler(struct sl_sock *s, const char *str){