mirror of
https://github.com/eddyem/eddys_snippets.git
synced 2026-11-22 13:50:17 +03:00
Compare commits
3 Commits
bd1b8babe9
...
58a489f1ad
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
58a489f1ad | ||
|
|
aaf17cf13e | ||
|
|
4557165678 |
@@ -1,3 +1,253 @@
|
|||||||
Simple daemon checking voltage & button0 state of my 'fan controller'.
|
# poweroff_daemon
|
||||||
|
|
||||||
Under development, wait pre-release...
|
`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.
|
||||||
|
|||||||
@@ -32,26 +32,32 @@ static cmdln_t G = {
|
|||||||
.poll_interval = DEFAULT_INTERVAL,
|
.poll_interval = DEFAULT_INTERVAL,
|
||||||
.timeout_us = READ_TIMEOUT_US,
|
.timeout_us = READ_TIMEOUT_US,
|
||||||
.baudrate = DEFAULT_BAUDRATE,
|
.baudrate = DEFAULT_BAUDRATE,
|
||||||
|
.sockpath = DEFAULT_SOCKPATH,
|
||||||
};
|
};
|
||||||
|
|
||||||
static int help = 0;
|
static int help = 0;
|
||||||
|
|
||||||
static sl_option_t options[] = {
|
static sl_option_t options[] = {
|
||||||
{"pidfile", NEED_ARG, NULL, 'p', arg_string, &G.pidfile, "PID file path, default: " STR(DEFAULT_PIDFILE)},
|
{"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, default: none"},
|
{"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)},
|
{"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)},
|
{"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"},
|
{"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, "default serial baudrate, default: " STR(DEFAULT_BAUDRATE)},
|
{"baudrate",NEED_ARG, NULL, 'b', arg_int, &G.baudrate, "serial baudrate, default: " STR(DEFAULT_BAUDRATE)},
|
||||||
{"help", NO_ARGS, &help, 'h', arg_none, NULL, "show this help"},
|
{"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"},
|
||||||
end_option
|
end_option
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
cmdln_t *parseargs(int *argc, char ***argv){
|
cmdln_t *parseargs(int *argc, char ***argv){
|
||||||
sl_parseargs(argc, argv, options);
|
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);
|
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;
|
return &G;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,6 +19,7 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#define DEFAULT_PIDFILE "/tmp/powerdaemon.pid"
|
#define DEFAULT_PIDFILE "/tmp/powerdaemon.pid"
|
||||||
|
#define DEFAULT_SOCKPATH "@poweroffdaemon"
|
||||||
#define DEFAULT_DEV "/dev/ttyUSB0"
|
#define DEFAULT_DEV "/dev/ttyUSB0"
|
||||||
#define DEFAULT_BAUDRATE 115200
|
#define DEFAULT_BAUDRATE 115200
|
||||||
#define DEFAULT_INTERVAL 1.0
|
#define DEFAULT_INTERVAL 1.0
|
||||||
@@ -28,6 +29,7 @@ typedef struct{
|
|||||||
char *pidfile;
|
char *pidfile;
|
||||||
char *logfile;
|
char *logfile;
|
||||||
char *serialdev;
|
char *serialdev;
|
||||||
|
char *sockpath;
|
||||||
double poll_interval;
|
double poll_interval;
|
||||||
double timeout_us;
|
double timeout_us;
|
||||||
int verbose;
|
int verbose;
|
||||||
|
|||||||
@@ -1,7 +1,25 @@
|
|||||||
|
/*
|
||||||
|
* This file is part of the poweroff_daemon 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/>.
|
||||||
|
*/
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* monitor_daemon.c - daemon that monitors serial device /dev/ttyUSB0.
|
* monitor_daemon.c - daemon that monitors serial device /dev/ttyUSB0.
|
||||||
* It sends commands "B\n" and "V\n", parses responses, and triggers poweroff
|
* 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').
|
* Protocol uses only '\n' as line separator (no '\r').
|
||||||
* USB CDC device: port settings (baudrate, format) are irrelevant.
|
* USB CDC device: port settings (baudrate, format) are irrelevant.
|
||||||
@@ -23,6 +41,7 @@
|
|||||||
|
|
||||||
#include "cmdlnopts.h"
|
#include "cmdlnopts.h"
|
||||||
#include "serial.h"
|
#include "serial.h"
|
||||||
|
#include "server.h"
|
||||||
|
|
||||||
static cmdln_t *G = NULL;
|
static cmdln_t *G = NULL;
|
||||||
static bool isrunning = false;
|
static bool isrunning = false;
|
||||||
@@ -37,11 +56,10 @@ void signals(int sig){
|
|||||||
LOGERR("Main process exits with status %d", sig);
|
LOGERR("Main process exits with status %d", sig);
|
||||||
if(G->pidfile) // remove unnesessary PID file
|
if(G->pidfile) // remove unnesessary PID file
|
||||||
unlink(G->pidfile);
|
unlink(G->pidfile);
|
||||||
|
exit(sig);
|
||||||
}else{
|
}else{
|
||||||
isrunning = false;
|
isrunning = false;
|
||||||
sleep(2); // let child to graceful out
|
|
||||||
}
|
}
|
||||||
exit(sig);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
int main(int argc, char **argv){
|
int main(int argc, char **argv){
|
||||||
@@ -62,10 +80,9 @@ int main(int argc, char **argv){
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* Daemonize */
|
/* Daemonize */
|
||||||
/* if (sl_daemonize() != 0) {
|
if(sl_daemonize() != 0){
|
||||||
ERR("daemonize failed");
|
ERR("daemonize failed");
|
||||||
}
|
}
|
||||||
*/
|
|
||||||
|
|
||||||
/* Set global timeout for sl_tty_read() */
|
/* Set global timeout for sl_tty_read() */
|
||||||
sl_tty_tmout(G->timeout_us);
|
sl_tty_tmout(G->timeout_us);
|
||||||
@@ -94,7 +111,7 @@ int main(int argc, char **argv){
|
|||||||
}
|
}
|
||||||
lastd = t;
|
lastd = t;
|
||||||
WARNX("Child %d died\n", childpid);
|
WARNX("Child %d died\n", childpid);
|
||||||
sleep(1);
|
sleep(5);
|
||||||
}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
|
||||||
break; // go out to normal functional
|
break; // go out to normal functional
|
||||||
@@ -110,24 +127,33 @@ int main(int argc, char **argv){
|
|||||||
|
|
||||||
isrunning = true;
|
isrunning = true;
|
||||||
|
|
||||||
|
if(!run_server(G->sockpath)){
|
||||||
|
LOGERR("Can't run server @ %s", G->sockpath);
|
||||||
|
ERRX("Can't run server @ %s", G->sockpath);
|
||||||
|
}
|
||||||
|
|
||||||
while(isrunning){
|
while(isrunning){
|
||||||
bool trigger = false;
|
bool trigger = false;
|
||||||
if(check_buttons()) trigger = true;
|
if(check_buttons()) trigger = true;
|
||||||
if(check_voltage()) trigger = true;
|
if(check_voltage()) trigger = true;
|
||||||
|
|
||||||
if(trigger){
|
if(trigger){
|
||||||
LOGERR("Trigger condition met, executing poweroff");
|
LOGWARN("Trigger condition met, executing poweroff");
|
||||||
DBG("poweroff");
|
DBG("poweroff");
|
||||||
/* int ret = system("poweroff");
|
int ret = system("/sbin/poweroff");
|
||||||
if (ret == -1) {
|
if(ret){
|
||||||
LOGERR("Failed to execute poweroff: %s", strerror(errno));
|
LOGERR("Failed to execute poweroff: %s", strerror(errno));
|
||||||
|
}else{
|
||||||
|
LOGWARN("Poweroff called");
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
break;
|
}
|
||||||
*/ }
|
|
||||||
|
|
||||||
usleep((useconds_t)(G->poll_interval * 1e6)); // seconds -> useconds
|
usleep((useconds_t)(G->poll_interval * 1e6)); // seconds -> useconds
|
||||||
}
|
}
|
||||||
|
|
||||||
|
kill_server();
|
||||||
|
|
||||||
close_serial();
|
close_serial();
|
||||||
|
|
||||||
return 0;
|
return 0;
|
||||||
|
|||||||
@@ -1 +1 @@
|
|||||||
-std=c17
|
-std=c23
|
||||||
@@ -1,5 +1,8 @@
|
|||||||
|
Readme.md
|
||||||
cmdlnopts.c
|
cmdlnopts.c
|
||||||
cmdlnopts.h
|
cmdlnopts.h
|
||||||
main.c
|
main.c
|
||||||
serial.c
|
serial.c
|
||||||
serial.h
|
serial.h
|
||||||
|
server.c
|
||||||
|
server.h
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
.
|
||||||
|
|||||||
@@ -30,13 +30,15 @@ bool open_serial(const char *path, int baudrate){
|
|||||||
tty = sl_tty_new((char*)path, baudrate, 1024);
|
tty = sl_tty_new((char*)path, baudrate, 1024);
|
||||||
if(!tty) return false;
|
if(!tty) return false;
|
||||||
/* Do not call sl_tty_setformat: default 8N1 is fine. */
|
/* 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;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
void close_serial(){
|
void close_serial(){
|
||||||
sl_tty_close(&tty);
|
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];
|
char k[SL_KEY_LEN], v[SL_VAL_LEN];
|
||||||
int res = sl_get_keyval(line, k, v);
|
int res = sl_get_keyval(line, k, v);
|
||||||
if(res == 2 && strcmp(k, key) == 0){
|
if(res == 2 && strcmp(k, key) == 0){
|
||||||
*val = atoi(v);
|
int I;
|
||||||
|
if(!sl_str2i(&I, v)) continue;
|
||||||
free(copy);
|
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;
|
return true;
|
||||||
}
|
}
|
||||||
line = strtok(NULL, "\n");
|
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);
|
free(copy);
|
||||||
return false;
|
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){
|
static bool get_int(const char *cmdstring, const char *key, int *answer){
|
||||||
if(!tty || !cmdstring || !key) return false;
|
if(!tty || !cmdstring || !key) return false;
|
||||||
static int errcnt = 0;
|
static int errcnt = 0;
|
||||||
|
char buf[BUFSIZ];
|
||||||
DBG("Ask parameter '%s' from command %s", key, cmdstring);
|
DBG("Ask parameter '%s' from command %s", key, cmdstring);
|
||||||
pthread_mutex_lock(&serial_mutex);
|
pthread_mutex_lock(&serial_mutex);
|
||||||
|
while(sl_tty_read(tty) > 0); // clear incoming buffer
|
||||||
if(sl_tty_write(tty->comfd, cmdstring, strlen(cmdstring))){
|
if(sl_tty_write(tty->comfd, cmdstring, strlen(cmdstring))){
|
||||||
WARNX("Write error");
|
WARNX("Write error");
|
||||||
LOGERR("Serial writing 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);
|
int n = sl_tty_read(tty);
|
||||||
if(n <= 0){
|
if(n <= 0){
|
||||||
char buf[BUFSIZ];
|
|
||||||
strncpy(buf, cmdstring, BUFSIZ-1);
|
strncpy(buf, cmdstring, BUFSIZ-1);
|
||||||
|
buf[BUFSIZ-1] = 0;
|
||||||
char *n = strchr(buf, '\n');
|
char *n = strchr(buf, '\n');
|
||||||
if(n) *n = 0;
|
if(n) *n = 0;
|
||||||
WARNX("No response");
|
WARNX("No response");
|
||||||
LOGERR("No response to command '%s'", buf);
|
LOGERR("No response to command '%s'", buf);
|
||||||
pthread_mutex_unlock(&serial_mutex);
|
pthread_mutex_unlock(&serial_mutex);
|
||||||
if(++errcnt > MAX_RERR_CNT){
|
if(++errcnt > MAX_RERR_CNT){
|
||||||
LOGERR("No answers -> go off");
|
LOGERR("No answers -> die");
|
||||||
ERRX("No answers -> go off");
|
ERRX("No answers -> die");
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
errcnt = 0;
|
|
||||||
int i = 0;
|
int i = 0;
|
||||||
bool gotint = parse_int_from_response(tty->buf, key, &i);
|
bool gotint = parse_int_from_response(tty->buf, key, &i);
|
||||||
if(!gotint) DBG("Didn't get int from %s", tty->buf);
|
if(!gotint) DBG("Didn't get int from %s", tty->buf);
|
||||||
pthread_mutex_unlock(&serial_mutex);
|
pthread_mutex_unlock(&serial_mutex);
|
||||||
if(!gotint) return false;
|
if(!gotint) return false;
|
||||||
|
errcnt = 0;
|
||||||
DBG("Got int: %d", i);
|
DBG("Got int: %d", i);
|
||||||
if(answer) *answer = i;
|
if(answer) *answer = i;
|
||||||
return true;
|
return true;
|
||||||
@@ -116,13 +124,26 @@ bool check_buttons(){
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Check voltage: returns 1 if V12 < 9700 */
|
#define VOLTAGE(v) (((double)(v)) * 0.01432)
|
||||||
|
|
||||||
|
/* Check voltage: returns 1 if V12 < 970 */
|
||||||
bool check_voltage(){
|
bool check_voltage(){
|
||||||
int voltage = 0;
|
int voltage = 0;
|
||||||
|
static double tlog = -1.;
|
||||||
if(!get_int(CMD_GETVOLTAGE, ANS_V12, &voltage)) return false;
|
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){
|
if(voltage < LOWEST_V12){
|
||||||
LOGERR("V12 low: %d (%.2f V)", voltage, (double)voltage / 100.);
|
LOGERR("V12 low: %d (%.2f V)", voltage, VOLTAGE(voltage));
|
||||||
return true;
|
return true;
|
||||||
|
}else if(voltage < LOG_V12){ // log once per minute
|
||||||
|
double tnow = sl_dtime();
|
||||||
|
if(tnow - tlog > LOG_VOLTAGE_DT){
|
||||||
|
LOGMSG("Voltage now: %d (%.2f V)", voltage, VOLTAGE(voltage));
|
||||||
|
tlog = tnow;
|
||||||
|
}
|
||||||
|
}else if(tlog > 0.){
|
||||||
|
LOGMSG("Power restored, now: %d (%.2f V)", voltage, VOLTAGE(voltage));
|
||||||
|
tlog = -1.;
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -130,11 +151,31 @@ bool check_voltage(){
|
|||||||
bool send_custom_command(const char *command, char *answer, size_t anslen){
|
bool send_custom_command(const char *command, char *answer, size_t anslen){
|
||||||
if(!tty || !command) return false;
|
if(!tty || !command) return false;
|
||||||
bool ret = false;
|
bool ret = false;
|
||||||
|
size_t L = anslen;
|
||||||
pthread_mutex_lock(&serial_mutex);
|
pthread_mutex_lock(&serial_mutex);
|
||||||
if(sl_tty_write(tty->comfd, command, strlen(command)) && sl_tty_read(tty) > 0){
|
DBG("Send command '%s'", command);
|
||||||
if(answer && anslen > 1) strncpy(answer, tty->buf, anslen-1);
|
if(0 == sl_tty_write(tty->comfd, command, strlen(command))){
|
||||||
ret = true;
|
sl_tty_write(tty->comfd, "\n", 1); // fix for newline
|
||||||
}
|
int got = sl_tty_read(tty);
|
||||||
|
if(got < 0) WARNX("Can't read");
|
||||||
|
else while(got > 0){
|
||||||
|
DBG("got: %d", got);
|
||||||
|
ret = true;
|
||||||
|
DBG("Got ans: %s", tty->buf);
|
||||||
|
if(answer && anslen > 1){
|
||||||
|
size_t len = tty->buflen;
|
||||||
|
if(tty->buflen > anslen) len = anslen;
|
||||||
|
strncpy(answer, tty->buf, len);
|
||||||
|
answer += len;
|
||||||
|
anslen -= len;
|
||||||
|
}else break;
|
||||||
|
got = sl_tty_read(tty);
|
||||||
|
}
|
||||||
|
}else WARNX("Can't write to TTY");
|
||||||
pthread_mutex_unlock(&serial_mutex);
|
pthread_mutex_unlock(&serial_mutex);
|
||||||
|
if(L > 0 && answer){
|
||||||
|
if(anslen < 1) answer[-1] = 0;
|
||||||
|
else *answer = 0;
|
||||||
|
}
|
||||||
return ret;
|
return ret;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,6 +23,8 @@
|
|||||||
|
|
||||||
#define CMD_GETVOLTAGE "V\n"
|
#define CMD_GETVOLTAGE "V\n"
|
||||||
#define ANS_V12 "V12"
|
#define ANS_V12 "V12"
|
||||||
|
#define LOG_V12 1150
|
||||||
|
#define LOG_VOLTAGE_DT 60
|
||||||
#define LOWEST_V12 970
|
#define LOWEST_V12 970
|
||||||
|
|
||||||
#define MAX_WERR_CNT 5
|
#define MAX_WERR_CNT 5
|
||||||
|
|||||||
61
Poweroff_daemon/server.c
Normal file
61
Poweroff_daemon/server.c
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
/*
|
||||||
|
* This file is part of the poweroff_daemon 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 <usefull_macros.h>
|
||||||
|
|
||||||
|
#include "serial.h"
|
||||||
|
#include "server.h"
|
||||||
|
|
||||||
|
static sl_sock_t *s = NULL;
|
||||||
|
|
||||||
|
static sl_sock_hresult_e defhandler(struct sl_sock *s, const char *str){
|
||||||
|
if(!s || !str) return RESULT_FAIL;
|
||||||
|
char buf[BUFSIZ];
|
||||||
|
if(!send_custom_command(str, buf, BUFSIZ)) return false;
|
||||||
|
LOGDBG("Send command '%s', answer:\n%s\n", str, buf);
|
||||||
|
sl_sock_sendstrmessage(s, buf);
|
||||||
|
return RESULT_SILENCE;
|
||||||
|
}
|
||||||
|
|
||||||
|
static sl_sock_hresult_e helphandler(struct sl_sock *s, sl_sock_hitem_t _U_ *item, const char _U_ *req){
|
||||||
|
if(!s) return RESULT_FAIL;
|
||||||
|
char buf[BUFSIZ];
|
||||||
|
if(!send_custom_command("help", buf, BUFSIZ)) return false;
|
||||||
|
LOGDBG("Send command 'help', answer:\n%s\n", buf);
|
||||||
|
sl_sock_sendstrmessage(s, buf);
|
||||||
|
return RESULT_SILENCE;
|
||||||
|
}
|
||||||
|
|
||||||
|
static sl_sock_hitem_t handlers[] = {
|
||||||
|
{sl_comment, NULL, " Enter any message for USB", NULL},
|
||||||
|
{helphandler, "_help", "Send 'help' to serial", NULL},
|
||||||
|
{NULL, NULL, NULL, NULL}
|
||||||
|
};
|
||||||
|
|
||||||
|
bool run_server(const char *sockpath){
|
||||||
|
if(!sockpath) return false;
|
||||||
|
s = sl_sock_run_server(SOCKT_UNIX, sockpath, -1, handlers);
|
||||||
|
if(!s) return false;
|
||||||
|
sl_sock_defmsghandler(s, defhandler);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void kill_server(){
|
||||||
|
if(!s) return;
|
||||||
|
sl_sock_delete(&s);
|
||||||
|
}
|
||||||
22
Poweroff_daemon/server.h
Normal file
22
Poweroff_daemon/server.h
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
/*
|
||||||
|
* This file is part of the poweroff_daemon 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 run_server(const char *sockpath);
|
||||||
|
void kill_server();
|
||||||
Reference in New Issue
Block a user