Compare commits

...

4 Commits

Author SHA1 Message Date
c8ee17854d a lot of fixes 2026-11-17 09:21:59 +03:00
Edward Emelianov
58a489f1ad convert slippers into volts 2026-10-27 23:39:45 +03:00
Edward Emelianov
aaf17cf13e some fixes + Readme 2026-10-27 23:31:06 +03:00
Edward Emelianov
4557165678 alpha pre-release 2026-10-27 21:25:07 +03:00
26 changed files with 765 additions and 208 deletions

2
.gitignore vendored
View File

@@ -4,3 +4,5 @@
*.o
.hg*
.dropbox.attr
.qtc-clangd
.qtcreator

View File

@@ -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.

View File

@@ -32,26 +32,32 @@ static cmdln_t G = {
.poll_interval = DEFAULT_INTERVAL,
.timeout_us = READ_TIMEOUT_US,
.baudrate = DEFAULT_BAUDRATE,
.sockpath = DEFAULT_SOCKPATH,
};
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)},
{"baudrate",NEED_ARG, NULL, 'b', arg_int, &G.baudrate, "default serial baudrate, default: " STR(DEFAULT_BAUDRATE)},
{"help", NO_ARGS, &help, 'h', arg_none, NULL, "show this help"},
{"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"},
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;
}

View File

@@ -19,6 +19,7 @@
#pragma once
#define DEFAULT_PIDFILE "/tmp/powerdaemon.pid"
#define DEFAULT_SOCKPATH "@poweroffdaemon"
#define DEFAULT_DEV "/dev/ttyUSB0"
#define DEFAULT_BAUDRATE 115200
#define DEFAULT_INTERVAL 1.0
@@ -28,6 +29,7 @@ typedef struct{
char *pidfile;
char *logfile;
char *serialdev;
char *sockpath;
double poll_interval;
double timeout_us;
int verbose;

View File

@@ -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.
* 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.
@@ -23,6 +41,7 @@
#include "cmdlnopts.h"
#include "serial.h"
#include "server.h"
static cmdln_t *G = NULL;
static bool isrunning = false;
@@ -37,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){
@@ -62,10 +80,9 @@ int main(int argc, char **argv){
}
/* Daemonize */
/* if (sl_daemonize() != 0) {
if(sl_daemonize() != 0){
ERR("daemonize failed");
}
*/
/* Set global timeout for sl_tty_read() */
sl_tty_tmout(G->timeout_us);
@@ -94,7 +111,7 @@ int main(int argc, char **argv){
}
lastd = t;
WARNX("Child %d died\n", childpid);
sleep(1);
sleep(5);
}else{
prctl(PR_SET_PDEATHSIG, SIGTERM); // send SIGTERM to child when parent dies
break; // go out to normal functional
@@ -110,24 +127,33 @@ int main(int argc, char **argv){
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){
bool trigger = false;
if(check_buttons()) trigger = true;
if(check_voltage()) trigger = true;
if(trigger){
LOGERR("Trigger condition met, executing poweroff");
LOGWARN("Trigger condition met, executing poweroff");
DBG("poweroff");
/* int ret = system("poweroff");
if (ret == -1) {
int ret = system("/sbin/poweroff");
if(ret){
LOGERR("Failed to execute poweroff: %s", strerror(errno));
}else{
LOGWARN("Poweroff called");
break;
}
break;
*/ }
}
usleep((useconds_t)(G->poll_interval * 1e6)); // seconds -> useconds
}
kill_server();
close_serial();
return 0;

View File

@@ -1 +1 @@
-std=c17
-std=c23

View File

@@ -1,5 +1,8 @@
Readme.md
cmdlnopts.c
cmdlnopts.h
main.c
serial.c
serial.h
server.c
server.h

View File

@@ -0,0 +1 @@
.

View File

@@ -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,13 +124,26 @@ bool check_buttons(){
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(){
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.);
LOGERR("V12 low: %d (%.2f V)", voltage, VOLTAGE(voltage));
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;
}
@@ -130,11 +151,31 @@ bool check_voltage(){
bool send_custom_command(const char *command, char *answer, size_t anslen){
if(!tty || !command) return false;
bool ret = false;
size_t L = anslen;
pthread_mutex_lock(&serial_mutex);
if(sl_tty_write(tty->comfd, command, strlen(command)) && sl_tty_read(tty) > 0){
if(answer && anslen > 1) strncpy(answer, tty->buf, anslen-1);
ret = true;
}
DBG("Send command '%s'", command);
if(0 == sl_tty_write(tty->comfd, command, strlen(command))){
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);
if(L > 0 && answer){
if(anslen < 1) answer[-1] = 0;
else *answer = 0;
}
return ret;
}

View File

@@ -23,6 +23,8 @@
#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

61
Poweroff_daemon/server.c Normal file
View 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
View 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();

View File

@@ -12,5 +12,5 @@ getinputs : A02.12 # read discrete input terminal state
getoutputs : A02.13 # read discrete output terminal state
setoutputs : 0x300A # write virtual discrete outputs bitmask
state1 : 0x6000 # 1 - cw, 2 - ccw, 3 - stop, 4 - damage, 5 - low voltage
state2 : # bits: 0 - ready (0), 1,2 - motor No, 3 - async (0), 4 - alarm overloading (0), 5,6 - keypad (0), 485 (10)
#state2 : # bits: 0 - ready (0), 1,2 - motor No, 3 - async (0), 4 - alarm overloading (0), 5,6 - keypad (0), 485 (10)
errcode : 0x6002 # last error code

View File

@@ -5,7 +5,7 @@ LDFLAGS += -lusefull_macros -lmodbus
SRCS := $(wildcard *.c)
DEFINES := $(DEF) -D_GNU_SOURCE -D_XOPEN_SOURCE=1111
OBJDIR := mk
CFLAGS += -O2 -Wall -Wextra -Wno-trampolines
CFLAGS += -O2 -Wall -Wextra -Wno-trampolines -std=gnu23
OBJS := $(addprefix $(OBJDIR)/, $(SRCS:%.c=%.o))
DEPS := $(OBJS:.o=.d)
TARGFILE := $(OBJDIR)/TARGET

View File

@@ -61,37 +61,40 @@ modbus_params [options]
| Option | Argument | Description |
|--------|-------------------|-------------|
| `-h`, `--help` | – | Show help and exit |
| `-v`, `--verbose` | – | Increase verbosity (can be used multiple times) |
| `-D`, `--dictionary` | *file* | Dictionary file (format: `code register value readonly`). *Required for most operations.* |
| `-a`, `--alias` | *file* | Aliases file (format: `name : command`). Optional. |
| `-s`, `--slave` | *ID* | Modbus slave ID (default: 1) |
| `-d`, `--device` | *path* | Serial device (default: `/dev/ttyUSB0`) |
| `-b`, `--baudrate` | *rate* | Baud rate (default: 9600) |
| `-d`, `--device` | *path* | Serial device (default: `/dev/ttyUSB0`) |
| `-D`, `--dictionary` | *file* | Dictionary file (format: `code register value readonly`). *Required for most operations.* |
| `-f`, `--format` | *fmt* | Serial port format: databitss parity stopbits (default: "8N1") |
| `-h`, `--help` | – | Show help and exit |
| `-s`, `--slave` | *ID* | Modbus slave ID (default: 1) |
| `-v`, `--verbose` | – | Increase verbosity (can be used multiple times) |
### Read/write operations
| Option | Description |
|--------|-------------|
| `-C`, `--clone` | Write all read-write entries of the `-D` dictionary to the device. Read-only entries are skipped. On completion prints written N, errors M.|
| `-O`, `--outdic` *file* | Read **all** registers listed in the dictionary and save them (with current values) into a new dictionary file |
| `-r`, `--readr` *addr* | Read register by address (multiply: `-r 100 -r 200`) |
| `-R`, `--readc` *code* | Read register by dictionary code (multiply) |
| `-w`, `--writer` *addr=val* | Write value to register by address (multiply) |
| `-W`, `--writec` *code=val* | Write value to register by dictionary code (multiply) |
| `-O`, `--outdic` *file* | Read **all** registers listed in the dictionary and save them (with current values) into a new dictionary file |
### Discrete I/O sizes
| Option | Argument | Description |
|--------|-------------------|-------------|
| `-i`, `--inputs` | N | Number of bytes for discrete inputs (default: 1) |
| `-c`, `--coils` | N | Number of bytes for coils/outputs (default: 1) |
| `-i`, `--inputs` | N | Number of bytes for discrete inputs (default: 1) |
### Dumping (periodic TSV output)
| Option | Description |
|--------|-------------|
| `-k`, `--dumpkey` *code* | Add a dictionary key to the dump list (multiply) |
| `-o`, `--outfile` *file* | TSV file for the dump |
| `-o`, `--outfile` *file* | TSV file for the dump (path relative to `/tmp/`) |
| `-t`, `--dumptime` *seconds* | Dump interval (default: 0.1 s) |
### Server mode
@@ -120,7 +123,7 @@ Format:
- `value` – initial/default value (16‑bit, not used by the tool except for documentation).
- `readonly` – `0` (writable) or `1` (read‑only).
Example (from `dictionary.dic`):
Example (from `ESQ770.dic`):
```
F00.00 61440 1 0 # Motor management (V/F)
@@ -169,6 +172,8 @@ Example:
0.102 1 5000
```
For sequrity reasons dump file name is relative to `/tmp` and shouldn't have `../` inside.
## Server protocol
The server listens for plain text commands, terminated by newline (`\n`).
@@ -260,19 +265,19 @@ readinputs[0] = 1
### 1. Simple read by address
```bash
modbus_params -D dictionary.txt -s 1 -d /dev/ttyUSB0 -b 9600 -r 61440
modbus_params -D dictionary.dic -s 1 -d /dev/ttyUSB0 -b 9600 -r 61440
```
### 2. Write a value using a code
```bash
modbus_params -D dictionary.txt -W "F00.00=1"
modbus_params -D dictionary.dic -W "F00.00=1"
```
### 3. Dump two registers every 0.5 seconds to `data.tsv`
```bash
modbus_params -D dictionary.txt -k F00.00 -k F00.11 -o data.tsv -t 0.5
modbus_params -D dictionary.dic -k F00.00 -k F00.11 -o data.tsv -t 0.5
```
(No server started – the program will dump until interrupted.)
@@ -280,7 +285,7 @@ modbus_params -D dictionary.txt -k F00.00 -k F00.11 -o data.tsv -t 0.5
### 4. Start a local server with dumping already active
```bash
modbus_params -D dictionary.txt -k F00.00 -o /tmp/dump.csv -t 1 -N localhost:5020
modbus_params -D dictionary.dic -k F00.00 -o /tmp/dump.csv -t 1 -N localhost:5020
```
Now you can connect to port 5020 and use `newdump` to change the output file, or `clodump` to stop.

View File

@@ -55,19 +55,31 @@ size_t get_aliasessize(){ return aliasessize; }
// functions for `qsort` (`needle` and `straw` are pointers to pointers)
static int sort_by_code(const void *needle, const void *straw){
if(!needle && !straw) return 0;
if(!needle) return -1;
if(!straw) return 1;
const char *c1 = (*(dicentry_t**)needle)->code, *c2 = (*(dicentry_t**)straw)->code;
return strcmp(c1, c2);
}
static int sort_by_reg(const void *needle, const void *straw){
if(!needle && !straw) return 0;
if(!needle) return -1;
if(!straw) return 1;
const int r1 = (int)(*(dicentry_t**)needle)->reg, r2 = (int)(*(dicentry_t**)straw)->reg;
return r1 - r2;
}
// functions for `binsearch`
static int search_by_code(const void *code, const void *straw){
if(!code && !straw) return 0;
if(!code) return -1;
if(!straw) return 1;
const char *c1 = (const char*)code, *c2 = ((dicentry_t*)straw)->code;
return strcmp(c1, c2);
}
static int search_by_reg(const void *reg, const void *straw){
if(!reg && !straw) return 0;
if(!reg) return -1;
if(!straw) return 1;
const int r1 = (int)(*(uint16_t*)reg), r2 = (int)((dicentry_t*)straw)->reg;
return r1 - r2;
}
@@ -92,14 +104,14 @@ static char *getcomment(char *str){
// all after "#" is comment;
// dictionary format: "'code' 'register' 'value' 'readonly flag'\n", e.g.
// "F00.09 61444 5000 1"
int opendict(const char *dic){
if(!dic) return FALSE;
bool opendict(const char *dic){
if(!dic || !*dic) return false;
DBG("Open %s", dic);
closedict(); // close early opened dictionary to prevent problems
FILE *f = fopen(dic, "r");
if(!f){
WARN("Can't open %s", dic);
return FALSE;
return false;
}
size_t dicsz = 0;
size_t linesz = BUFSIZ;
@@ -107,7 +119,7 @@ int opendict(const char *dic){
dicentry_t curentry;
curentry.code = MALLOC(char, BUFSIZ);
// `help` field of `curentry` isn't used here
int retcode = TRUE;
bool retcode = true;
char formatbuf[64];
snprintf(formatbuf, 64, "%%%ds %%" SCNu16 " %%" SCNu16 " %%" SCNu8, BUFSIZ-1);
while(1){
@@ -123,21 +135,26 @@ int opendict(const char *dic){
WARNX("Can't understand this line: '%s'", line);
continue;
}
DBG("Got line: '%s %" PRIu16 " %" PRIu16 " %" PRIu8, curentry.code, curentry.reg, curentry.value, curentry.readonly);
DBG("Got line: '%s %" PRIu16 " %" PRIu16 " %" PRIu8, curentry.code, curentry.reg, curentry.value, curentry.readonly);
if(++dictsize >= dicsz){
size_t newsize = dicsz + 50;
dicentry_t *newdic = realloc(dictionary, sizeof(dicentry_t) * newsize);
if(!newdic){
WARN("Can't allocate memory for dictionary");
retcode = FALSE;
retcode = false;
--dictsize;
goto ret;
WARN("Can't allocate memory for dictionary; got only %zd entries", dictsize);
break;
}
dictionary = newdic;
dicsz = newsize;
}
dicentry_t *entry = &dictionary[dictsize-1];
entry->code = strdup(curentry.code);
if(!entry->code){
WARN("strdup()");
--dictsize;
continue;
}
entry->reg = curentry.reg;
entry->value = curentry.value;
entry->readonly = curentry.readonly;
@@ -146,13 +163,14 @@ int opendict(const char *dic){
//DBG("Add entry; now dictsize is %d", dictsize);
}
// init dictionaries for sort
dictbycode = MALLOC(dicentry_t*, dictsize);
dictbyreg = MALLOC(dicentry_t*, dictsize);
for(size_t i = 0; i < dictsize; ++i)
dictbyreg[i] = dictbycode[i] = &dictionary[i];
qsort(dictbycode, dictsize, sizeof(dicentry_t*), sort_by_code);
qsort(dictbyreg, dictsize, sizeof(dicentry_t*), sort_by_reg);
ret:
if(dictsize > 0){
dictbycode = MALLOC(dicentry_t*, dictsize);
dictbyreg = MALLOC(dicentry_t*, dictsize);
for(size_t i = 0; i < dictsize; ++i)
dictbyreg[i] = dictbycode[i] = &dictionary[i];
qsort(dictbycode, dictsize, sizeof(dicentry_t*), sort_by_code);
qsort(dictbyreg, dictsize, sizeof(dicentry_t*), sort_by_reg);
}
fclose(f);
FREE(curentry.code);
FREE(line);
@@ -163,12 +181,12 @@ ret:
* @brief chkdict - check if dictionary is opened
* @return TRUE if dictionary opened
*/
int chkdict(){
bool chkdict(){
if(dictsize < 1){
WARNX("Init dictionary first");
return FALSE;
return false;
}
return TRUE;
return true;
}
void closedict(){
@@ -210,15 +228,14 @@ dicentry_t *findentry_by_code(const char *code){
dicentry_t *findentry_by_reg(uint16_t reg){
if(!chkdict()) return NULL;
return binsearch(dictbyreg, (const void*)(&reg), search_by_reg);
return NULL;
}
/** dump functions **/
/** dump functions (thread-unsafe!) **/
// prepare a list with dump parameters (new call will rewrite previous list)
int setdumppars(char **pars){
if(!pars || !*pars) return FALSE;
if(!chkdict()) return FALSE;
bool setdumppars(char **pars){
if(!pars || !*pars) return false;
if(!chkdict()) return false;
FNAME();
char **p = pars;
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
@@ -231,7 +248,7 @@ int setdumppars(char **pars){
WARNX("Can't find entry with code %s", *p);
pthread_mutex_unlock(&mutex);
dumpsize = 0;
return FALSE;
return false;
}
DBG("found entry do dump, reg=%d", e->reg);
if(cursz <= N){
@@ -241,7 +258,7 @@ int setdumppars(char **pars){
if(!newpars){
WARN("realloc()");
pthread_mutex_unlock(&mutex);
return FALSE;
return false;
}else{
dumppars = newpars;
cursz = newsz;
@@ -254,45 +271,53 @@ int setdumppars(char **pars){
dumppars[N] = *e;
dumppars[N].code = strdup(e->code);
if(e->help) dumppars[N].help = strdup(e->help);
else dumppars[N].help = NULL;
DBG("Add %s", e->code);
++N; ++p;
}
dumpsize = N;
pthread_mutex_unlock(&mutex);
return TRUE;
return true;
}
// open dump file and add header; return FALSE if failed
int opendumpfile(const char *name){
if(!chkdict()) return FALSE;
// open dump file (path relative to "/tmp") and add header; return FALSE if failed
bool opendumpfile(const char *name){
if(!chkdict()) return false;
if(dumpsize < 1){
WARNX("Set dump parameters first");
return FALSE;
return false;
}
if(!name) return FALSE;
if(!name || !*name) return false;
if(strstr(name, "../")) return false; // don't allow change to upper level
closedumpfile();
dumpfile = fopen(name, "w+");
char path[PATH_MAX];
ssize_t L;
if(*name == '/') L = snprintf(path, PATH_MAX-1, "/tmp%s", name);
else L = snprintf(path, PATH_MAX-1, "/tmp/%s", name);
if(L < 1) return false;
if(L >= PATH_MAX-1) path[PATH_MAX-1] = 0;
dumpfile = fopen(path, "w+");
if(!dumpfile){
WARN("Can't open %s", name);
return FALSE;
WARN("Can't open %s", path);
return false;
}
dumpname = strdup(name);
dumpname = strdup(path);
fprintf(dumpfile, "# time,s ");
for(int i = 0; i < dumpsize; ++i){
fprintf(dumpfile, "%s ", dumppars[i].code);
}
fprintf(dumpfile, "\n");
return TRUE;
return true;
}
char *getdumpname(){ return dumpname;}
const char *getdumpname(){ return dumpname;}
void closedumpfile(){
int stpd = atomic_load(&isstopped);
if(dumpfile){
if(!stpd){
atomic_store(&stopdump, 1);
while(!atomic_load(&isstopped));
while(!atomic_load(&isstopped)) usleep(1000);
}
fclose(dumpfile);
dumpfile = NULL;
@@ -320,29 +345,30 @@ static void *dumpthread(void *p){
return NULL;
}
int setDumpT(double dT){
if(dT < 0.){
WARNX("Time interval should be > 0");
return FALSE;
bool setDumpT(double dT){
if(dT < 0. || dT > 60.){
WARNX("Time interval should be > 0 and <= 60.");
return false;
}
dumpTime = dT;
DBG("user give dT: %g", dT);
return TRUE;
return true;
}
int rundump(){
bool rundump(){
if(!dumpfile){
WARNX("Open dump file first");
return FALSE;
return false;
}
pthread_t thread;
if(pthread_create(&thread, NULL, dumpthread, (void*)&dumpTime)){
WARN("Can't create dumping thread");
return FALSE;
return false;
}
while(atomic_load(&isstopped)) usleep(1000); // wait until thread starts
DBG("Thread created, detach");
pthread_detach(thread);
return TRUE;
return true;
}
/**
@@ -356,7 +382,7 @@ int rundump(){
char *dicentry_descr(dicentry_t *entry, char *buf, size_t bufsize){
//DBG("descr of %s", entry->code);
if(!entry || !buf || !bufsize) return NULL;
size_t L;
ssize_t L;
if(entry->help){
L = snprintf(buf, bufsize, "%s %4" PRIu16 " %4" PRIu16 " %" PRIu8 " # %s\n",
entry->code, entry->reg, entry->value, entry->readonly, entry->help);
@@ -364,7 +390,8 @@ char *dicentry_descr(dicentry_t *entry, char *buf, size_t bufsize){
L = snprintf(buf, bufsize, "%s %4" PRIu16 " %4" PRIu16 " %" PRIu8 "\n",
entry->code, entry->reg, entry->value, entry->readonly);
}
if(L >= bufsize) buf[bufsize-1] = 0;
if(L < 1) return NULL;
else if(L >= (ssize_t)bufsize) buf[bufsize-1] = 0;
return buf;
}
@@ -375,7 +402,7 @@ char *dicentry_descrN(size_t N, char *buf, size_t bufsize){
// dump all registers by input dictionary into output; also modify values of registers in dictionary
int read_dict_entries(const char *outdic){
if(!chkdict()) return -1;
if(!outdic || !chkdict()) return -1;
int got = 0;
FILE *o = fopen(outdic, "w");
if(!o){
@@ -388,7 +415,7 @@ int read_dict_entries(const char *outdic){
verbose(LOGLEVEL_MSG, "Read register %d, value: %d\n", dictionary[i].reg, dictionary[i].value);
if(dicentry_descrN(i, buf, BUFSIZ)){
++got;
fprintf(o, "%s\n", buf);
fprintf(o, "%s", buf);
}
}else verbose(LOGLEVEL_WARN, "Can't read value of register %d\n", dictionary[i].reg);
}
@@ -396,6 +423,35 @@ int read_dict_entries(const char *outdic){
return got;
}
/**
* @brief write_dict_entries - write all read-write dictionary entries to device
* @param errors - out: number of failed writes (may be NULL)
* @return number of successfully written entries, or -1 if dictionary isn't opened
*
* Entries with `readonly != 0` are skipped silently (not counted as errors).
*/
int write_dict_entries(int *errors){
if(errors) *errors = 0;
if(!chkdict()) return -1;
int written = 0, failed = 0;
for(size_t i = 0; i < dictsize; ++i){
dicentry_t *e = &dictionary[i];
if(e->readonly) continue; // read-only => skip, not an error
if(write_entry(e)){
verbose(LOGLEVEL_MSG, "Wrote %u to register %u (%s)\n",
e->value, e->reg, e->code);
++written;
}else{
// write_entry() already emitted WARNX with details;
// add context with mnemonic code
verbose(LOGLEVEL_WARN, "Can't write %u to register %u (%s)\n",
e->value, e->reg, e->code);
++failed;
}
}
if(errors) *errors = failed;
return written;
}
/********** Aliases **********/
@@ -415,14 +471,15 @@ static int sortalias(const void *l, const void *r){
}
// open file with aliases and fill structure
int openaliases(const char *filename){
closealiases();
bool openaliases(const char *filename){
if(!filename) return false;
FILE *f = fopen(filename, "r");
if(!f){
WARN("Can't open %s", filename);
return FALSE;
return false;
}
int retcode = TRUE;
closealiases();
int retcode = true;
size_t linesz = BUFSIZ, asz = 0;
char *line = MALLOC(char, linesz);
while(1){
@@ -457,7 +514,7 @@ int openaliases(const char *filename){
alias_t *newaliases = realloc(aliases, sizeof(alias_t) * newsize);
if(!newaliases){
WARNX("Can't allocate memory for aliases list");
retcode = FALSE;
retcode = false;
--aliasessize;
goto ret;
}
@@ -471,7 +528,7 @@ int openaliases(const char *filename){
else cur->help = NULL;
DBG("Read alias; name='%s', expr='%s', comment='%s'", cur->name, cur->expr, cur->help);
}
if(aliasessize == 0) retcode = FALSE;
if(aliasessize == 0) retcode = false;
qsort(aliases, aliasessize, sizeof(alias_t), sortalias);
ret:
fclose(f);
@@ -480,12 +537,12 @@ ret:
}
// return TRUE if aliases list inited
int chkaliases(){
bool chkaliases(){
if(aliasessize < 1){
WARNX("Init aliases first");
return FALSE;
return false;
}
return TRUE;
return true;
}
// remove aliases
void closealiases(){

View File

@@ -35,9 +35,9 @@ typedef struct{
char *help; // help message
} alias_t;
int opendict(const char *dic);
bool opendict(const char *dic);
void closedict();
int chkdict();
bool chkdict();
size_t get_dictsize();
char *dicentry_descr(dicentry_t *entry, char *buf, size_t bufsize);
char *dicentry_descrN(size_t N, char *buf, size_t bufsize);
@@ -45,17 +45,18 @@ char *dicentry_descrN(size_t N, char *buf, size_t bufsize);
dicentry_t *findentry_by_code(const char *code);
dicentry_t *findentry_by_reg(uint16_t reg);
int setdumppars(char **pars);
int opendumpfile(const char *name);
bool setdumppars(char **pars);
bool opendumpfile(const char *name);
void closedumpfile();
int setDumpT(double dT);
int rundump();
char *getdumpname();
bool setDumpT(double dT);
bool rundump();
const char *getdumpname();
int read_dict_entries(const char *outdic);
int write_dict_entries(int *errors);
int openaliases(const char *filename);
int chkaliases();
bool openaliases(const char *filename);
bool chkaliases();
void closealiases();
size_t get_aliasessize();
alias_t *find_alias(const char *name);

View File

@@ -32,6 +32,7 @@ typedef struct{
int isunix; // Unix-socket
int inputs; // number of bytes for discrete inputs
int coils; // number of bytes for coils
int clone; // clone dictionary onto device
char **read_keycodes; // keycodes to dump into file
char **writeregs; // reg=val to write
char **writecodes; // keycode=val to write
@@ -43,6 +44,7 @@ typedef struct{
char *aliasesfile; // file with aliases
char *device; // serial device
char *node; // server port or path
char *portformat; // serial port format
int baudrate; // baudrate
double dTdump; // dumping time interval (s)
} parameters;
@@ -54,6 +56,7 @@ static parameters G = {
.dTdump = 0.1,
.inputs = 1,
.coils = 1,
.portformat = "8N1",
};
static sl_option_t cmdlnopts[] = {
@@ -66,8 +69,10 @@ static sl_option_t cmdlnopts[] = {
{"slave", NEED_ARG, NULL, 's', arg_int, APTR(&G.slave), "slave ID (default: 1)"},
{"device", NEED_ARG, NULL, 'd', arg_string, APTR(&G.device), "modbus device (default: /dev/ttyUSB0)"},
{"baudrate", NEED_ARG, NULL, 'b', arg_int, APTR(&G.baudrate), "modbus baudrate (default: 9600)"},
{"format", NEED_ARG, NULL, 'f', arg_string, APTR(&G.portformat),"serial port format (default: 8N1)"},
{"writer", MULT_PAR, NULL, 'w', arg_string, APTR(&G.writeregs), "write new value to register (format: reg=val); multiply parameter"},
{"writec", MULT_PAR, NULL, 'W', arg_string, APTR(&G.writecodes),"write new value to register by keycode (format: keycode=val); multiply parameter"},
{"clone", NO_ARGS, NULL, 'C', arg_int, APTR(&G.clone), "write all read-write dictionary entries (from -D) to device"},
{"outdic", NEED_ARG, NULL, 'O', arg_string, APTR(&G.outdic), "output dictionary for full device dump by input dictionary registers"},
{"readr", MULT_PAR, NULL, 'r', arg_int, APTR(&G.readregs), "registers (by address) to read; multiply parameter"},
{"readc", MULT_PAR, NULL, 'R', arg_string, APTR(&G.readcodes), "registers (by keycodes, checked by dictionary) to read; multiply parameter"},
@@ -79,12 +84,15 @@ static sl_option_t cmdlnopts[] = {
end_option
};
static bool isrunning = true;
void signals(int sig){
if(sig > 0) WARNX("Exig with signal %d", sig);
close_modbus();
closedict();
closealiases();
exit(sig);
if(sig > 0){
WARNX("Exit with signal %d", sig);
signal(sig, SIG_IGN);
}
stop_server();
isrunning = false;
}
int main(int argc, char **argv){
@@ -92,8 +100,9 @@ int main(int argc, char **argv){
sl_parseargs(&argc, &argv, cmdlnopts);
if(G.help) sl_showhelp(-1, cmdlnopts);
sl_loglevel_e lvl = G.verbose + LOGLEVEL_ERR;
set_verbose_level(lvl);
if(lvl >= LOGLEVEL_AMOUNT) lvl = LOGLEVEL_AMOUNT - 1;
set_verbose_level(&lvl);
// here we can also open log-file with given level
if(!G.dicfile) WARNX("Dictionary is absent");
else if(!opendict(G.dicfile)) signals(-1);
DBG("dictionary %s opened", G.dicfile);
@@ -103,7 +112,7 @@ int main(int argc, char **argv){
if(G.read_keycodes && !setdumppars(G.read_keycodes)) signals(-1);
if(G.dumpfile) DBG("Dump file: %s", G.dumpfile);
if(G.dumpfile && !opendumpfile(G.dumpfile)) signals(-1);
if(!open_modbus(G.device, G.baudrate)) signals(-1);
if(!open_modbus(G.device, G.portformat, G.baudrate)) signals(-1);
if(!set_slave(G.slave)) signals(-1);
signal(SIGTERM, signals); // kill (-15) - quit
signal(SIGHUP, SIG_IGN); // hup - ignore
@@ -113,13 +122,23 @@ int main(int argc, char **argv){
if(G.writeregs){
DBG("writeregs");
green("Write user registers to slave %d\n", G.slave);
green("Total: %d written successfully", write_regval(G.writeregs));
green("Total: %d written successfully\n", write_regval(G.writeregs));
fflush(stdout);
}
if(G.writecodes){
DBG("writecodes");
green("Write user registers coded by keycode to slave %d\n", G.slave);
green("Total: %d written successfully", write_codeval(G.writecodes));
green("Total: %d written successfully\n", write_codeval(G.writecodes));
fflush(stdout);
}
if(G.clone){
DBG("clone");
green("Write all read-write dictionary entries to slave %d\n", G.slave);
fflush(stdout);
int errors = 0;
int N = write_dict_entries(&errors);
if(N < 0) WARNX("Clone failed: dictionary is not opened");
else green("Clone done: written %d, errors %d\n", N, errors);
fflush(stdout);
}
if(G.outdic){
@@ -140,10 +159,12 @@ int main(int argc, char **argv){
set_io_sizes(G.inputs, G.coils);
DBG("Create server");
if(!runserver(G.node, G.isunix)) signals(-1); // this function exits only after server death
}else if(G.dumpfile){
green("Dump is running, wait for ctrl+C");
while(isrunning) usleep(100000);
}
if(G.dumpfile){
DBG("Done, wait for ctrl+C");
while(1) usleep(100000);
}
close_modbus();
closedict();
closealiases();
return 0;
}

View File

@@ -18,6 +18,7 @@
#include <inttypes.h>
#include <modbus/modbus.h>
#include <stdatomic.h>
#include <stdio.h>
#include <string.h>
#include <usefull_macros.h>
@@ -29,6 +30,9 @@
#define MAX_READ_BITS 64
#define MAX_WRITE_BITS 64
// slave ID
static atomic_int slaveID = 1;
static modbus_t *modbus_ctx = NULL;
static pthread_mutex_t modbus_mutex = PTHREAD_MUTEX_INITIALIZER;
@@ -44,35 +48,39 @@ void close_modbus(){
}
// read register and modify entry->reg; return FALSE if failed
int read_entry(dicentry_t *entry){
if(!modbus_ctx) return FALSE;
bool read_entry(dicentry_t *entry){
if(!modbus_ctx) return false;
if(!entry){
WARNX("NULL instead of entry");
return FALSE;
return false;
}
int ret = TRUE;
bool ret = true;
pthread_mutex_lock(&modbus_mutex);
if(modbus_read_registers(modbus_ctx, entry->reg, 1, &entry->value) < 0 &&
modbus_read_input_registers(modbus_ctx, entry->reg, 1, &entry->value) < 0){
int rc = modbus_read_registers(modbus_ctx, entry->reg, 1, &entry->value);
if(rc < 0){
modbus_flush(modbus_ctx);
rc = modbus_read_input_registers(modbus_ctx, entry->reg, 1, &entry->value);
}
if(rc < 0){
WARNX("Can't read entry by reg %u", entry->reg);
ret = FALSE;
ret = false;
}
pthread_mutex_unlock(&modbus_mutex);
return ret;
}
// write register value; FALSE - if failed or read-only
int write_entry(dicentry_t *entry){
if(!modbus_ctx) return FALSE;
bool write_entry(dicentry_t *entry){
if(!modbus_ctx) return false;
if(!entry || entry->readonly){
if(!entry) WARNX("NULL instead of entry");
else WARNX("Can't write readonly entry %u", entry->reg);
return FALSE;
return false;
}
int ret = TRUE;
bool ret = true;
pthread_mutex_lock(&modbus_mutex);
if(modbus_write_register(modbus_ctx, entry->reg, entry->value) < 0){
WARNX("Error writing %u to %u", entry->value, entry->reg);
ret = FALSE;
ret = false;
}
pthread_mutex_unlock(&modbus_mutex);
return ret;
@@ -108,7 +116,7 @@ int write_regval(char **regval){
// write multiply regs by NULL-terminated array "keycode=val" (checking `keycode`); return amount of items written
int write_codeval(char **codeval){
if(!chkdict()) return FALSE;
if(!chkdict()) return 0;
int written = 0;
dicentry_t entry = {0};
while(*codeval){
@@ -143,11 +151,17 @@ int write_codeval(char **codeval){
return written;
}
int open_modbus(const char *path, int baudrate){
int ret = FALSE;
bool open_modbus(const char *path, const char *format, int baudrate){
if(!path || !format) return false;
bool ret = false;
if(strlen(format) != 3) return false; // linux doesn't support 1.5 stop bits
char parity = format[1];
int databits = format[0] - '0', stopbits = format[2] - '0';
DBG("Try to open modbus @%s with speed %d, parity: %c, %d data bits and %d stop bits",
path, baudrate, parity, databits, stopbits);
if(modbus_ctx) close_modbus();
pthread_mutex_lock(&modbus_mutex);
modbus_ctx = modbus_new_rtu(path, baudrate, 'N', 8, 1);
modbus_ctx = modbus_new_rtu(path, baudrate, parity, databits, stopbits);
if(!modbus_ctx){
WARNX("Can't open device %s @ %d", path, baudrate);
goto rtn;
@@ -159,24 +173,30 @@ int open_modbus(const char *path, int baudrate){
modbus_ctx = NULL;
goto rtn;
}
ret = TRUE;
ret = true;
rtn:
pthread_mutex_unlock(&modbus_mutex);
return ret;
}
int set_slave(int ID){
int ret = TRUE;
if(!modbus_ctx) return FALSE;
bool set_slave(int ID){
bool ret = true;
if(!modbus_ctx) return false;
pthread_mutex_lock(&modbus_mutex);
modbus_flush(modbus_ctx); // flush modbus to clear trash
if(modbus_set_slave(modbus_ctx, ID)){
WARNX("Can't set slave ID to %d", ID);
ret = FALSE;
}
ret = false;
}else atomic_store(&slaveID, ID);
pthread_mutex_unlock(&modbus_mutex);
return ret;
}
int get_slave(){
int slave = atomic_load(&slaveID);
return slave;
}
// read dump register values (not checking in dict) and dump to stdout (not modifying dictionary)
void read_registers(int **addresses){
dicentry_t entry = {0};
@@ -213,61 +233,61 @@ void read_keycodes(char **keycodes){
printf("\n");
}
int read_coils(int nbytes, uint8_t *dest){
bool read_coils(int nbytes, uint8_t *dest){
if(!modbus_ctx || !dest || nbytes < 1 || nbytes > MAX_READ_BITS / 8){
WARNX("Bad coils read request");
return FALSE;
return false;
}
int ret = TRUE;
bool ret = true;
DBG("Try to read %d bits", nbytes * 8);
pthread_mutex_lock(&modbus_mutex);
if(modbus_read_bits(modbus_ctx, 0, nbytes * 8, dest) < 0){
WARNX("Can't read coils");
ret = FALSE;
ret = false;
}
pthread_mutex_unlock(&modbus_mutex);
return ret;
}
int read_inputs(int nbytes, uint8_t *dest){
bool read_inputs(int nbytes, uint8_t *dest){
if(!modbus_ctx || !dest || nbytes < 1 || nbytes > MAX_READ_BITS / 8){
WARNX("Bad inputs read request");
return FALSE;
return false;
}
int ret = TRUE;
bool ret = true;
pthread_mutex_lock(&modbus_mutex);
if(modbus_read_input_bits(modbus_ctx, 0, nbytes * 8, dest) < 0){
WARNX("Can't read discrete inputs");
ret = FALSE;
ret = false;
}
pthread_mutex_unlock(&modbus_mutex);
return ret;
}
int write_coils(int nbytes, const uint8_t *src){
bool write_coils(int nbytes, const uint8_t *src){
if(!modbus_ctx || !src || nbytes < 1 || nbytes > MAX_WRITE_BITS / 8){
WARNX("Bad coils write request");
return FALSE;
return false;
}
int ret = TRUE;
bool ret = true;
pthread_mutex_lock(&modbus_mutex);
if(modbus_write_bits(modbus_ctx, 0, nbytes * 8, src) < 0){
WARNX("Can't write coils");
ret = FALSE;
ret = false;
}
pthread_mutex_unlock(&modbus_mutex);
return ret;
}
int write_coil(int index, int value){
bool write_coil(int index, int value){
if(!modbus_ctx || index < 0 || index > MAX_WRITE_BITS - 1){
WARNX("Bad coil write request");
return FALSE;
return false;
}
int ret = TRUE;
bool ret = true;
pthread_mutex_lock(&modbus_mutex);
if(modbus_write_bit(modbus_ctx, index, value) < 0){
ret = FALSE;
ret = false;
WARNX("Can't set coil %d to %d", index, value);
}
pthread_mutex_unlock(&modbus_mutex);

View File

@@ -20,17 +20,18 @@
#include "dictionary.h"
int open_modbus(const char *path, int baudrate);
bool open_modbus(const char *path, const char *format, int baudrate);
void close_modbus();
int set_slave(int ID);
bool set_slave(int ID);
int get_slave();
int read_coils(int nbytes, uint8_t *dest);
int read_inputs(int nbytes, uint8_t *dest);
int write_coils(int nbytes, const uint8_t *src);
int write_coil(int index, int value);
bool read_coils(int nbytes, uint8_t *dest);
bool read_inputs(int nbytes, uint8_t *dest);
bool write_coils(int nbytes, const uint8_t *src);
bool write_coil(int index, int value);
int read_entry(dicentry_t *entry);
int write_entry(dicentry_t *entry);
bool read_entry(dicentry_t *entry);
bool write_entry(dicentry_t *entry);
int write_regval(char **regval);
int write_codeval(char **codeval);

View File

@@ -1 +1 @@
-std=c17
-std=gnu23

View File

@@ -1 +1 @@
-std=c++17
-std=c++23

View File

@@ -30,6 +30,8 @@ static sl_sock_t *s = NULL;
// amount of input/output bytes
static int input_bytes = 0;
static int coils_bytes = 0;
// if exitjob == 1 we should stop server
static bool exitjob = false;
// specific bit to read/write
static sl_sock_keyno_t rinputs = SL_SOCK_KEYNO_DEFAULT,
@@ -42,26 +44,26 @@ void set_io_sizes(int inputs, int coils){
coils_bytes = (coils > 0) ? coils : 0;
}
static int bytes_to_num(const uint8_t *buf, int n, uint64_t *out){
if(!buf || !out || n < 1 || n > 64) return FALSE;
static bool bytes_to_num(const uint8_t *buf, int n, uint64_t *out){
if(!buf || !out || n < 1 || n > 64) return false;
uint64_t result = 0;
for(int i = n - 1; i > -1; --i){
result <<= 1;
if(buf[i]) result |= 1;
}
*out = result;
return TRUE;
return true;
}
static int num_to_bytes(uint64_t in, uint8_t *buf, int n){
if(!buf || n < 1 || n > 64) return FALSE;
static bool num_to_bytes(uint64_t in, uint8_t *buf, int n){
if(!buf || n < 1 || n > 64) return false;
uint64_t mask = 1;
for(int i = 0; i < n; ++i){
if(in & mask) buf[i] = 1;
else buf[i] = 0;
mask <<= 1;
}
return TRUE;
return true;
}
// stop dump and close dump file
@@ -73,7 +75,8 @@ static sl_sock_hresult_e closedump(_U_ sl_sock_t *client, _U_ sl_sock_hitem_t *i
static sl_sock_hresult_e newdump(sl_sock_t *client, _U_ sl_sock_hitem_t *item, const char *req){
char buf[BUFSIZ];
if(!req){ // getter
snprintf(buf, BUFSIZ-1, "%s = %s\n", item->key, getdumpname());
const char *n = getdumpname();
snprintf(buf, BUFSIZ-1, "%s = %s\n", item->key, n ? n : "(none)");
sl_sock_sendstrmessage(client, buf);
return RESULT_SILENCE;
}else{
@@ -195,31 +198,47 @@ static sl_sock_hresult_e writecoils(_U_ sl_sock_t *client, _U_ sl_sock_hitem_t *
return RESULT_BADVAL;
}
bits = (uint64_t) ll;
int ok = FALSE;
bool ok = false;
if(no > -1){ // change state of specific coil
ok = write_coil(no, bits);
}else{
if(!num_to_bytes(bits, buf, coils_bytes*8)){
WARNX("Bad HEX string for writecoils");
WARNX("Bad parameters for writecoils");
return RESULT_BADVAL;
}
ok = write_coils(coils_bytes, buf);
}
if(0 == get_slave()) return RESULT_SILENCE;
return ok ? RESULT_OK : RESULT_FAIL;
}
static sl_sock_hresult_e setid(sl_sock_t *client, _U_ sl_sock_hitem_t *item, const char *req){
char buf[BUFSIZ];
int slaveID;
if(!req){ // getter
slaveID = get_slave();
snprintf(buf, BUFSIZ-1, "%s = %d\n", item->key, slaveID);
sl_sock_sendstrmessage(client, buf);
return RESULT_SILENCE;
}
if(!sl_str2i(&slaveID, req)) return RESULT_BADVAL;
if(!set_slave(slaveID)) return RESULT_FAIL;
return RESULT_OK;
}
static sl_sock_hitem_t handlers[] = {
{closedump, "clodump", "stop dump and close current dump file", NULL},
{newdump, "newdump", "open new dump file or get name of current", NULL},
{listdict, "list", "list all dictionary (as getter) or given register (as setter: by codename or value)", NULL},
{listaliases, "alias", "list all of aliases (as getter) or with given name (by setter)", NULL},
{listdict, "list", "list all dictionary (as getter) or given register (as setter: by codename or value)", NULL},
{newdump, "newdump", "open new dump file or get name of current", NULL},
{readcoils, "readcoils", "read all coils as HEX (uses --coils bytes)", (void*)&rcoils},
{readinputs, "readinputs", "read all discrete inputs as HEX (uses --inputs bytes)", (void*)&rinputs},
{setid, "setid", "set slave's ID", NULL},
{writecoils, "writecoils", "write all coils from HEX number (uses --coils bytes)", (void*)&wcoils},
{NULL, NULL, NULL, NULL}
};
// new connections handler (return FALSE to reject client)
// new connections handler (return FALSE to reject client); should be INT!
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);
@@ -243,6 +262,7 @@ static sl_sock_hresult_e defhandler(sl_sock_t *s, const char *str){
int n = sl_get_keyval(str, key, value);
if(n == 0){
WARNX("Can't parse `%s` as reg[=val]", str);
deepcounter = 0;
return RESULT_BADKEY;
}
dicentry_t *entry = NULL;
@@ -262,41 +282,52 @@ static sl_sock_hresult_e defhandler(sl_sock_t *s, const char *str){
}
}
WARNX("Entry %s not found", key);
deepcounter = 0;
return RESULT_BADKEY;
}
deepcounter = 0;
if(n == 1){ // getter
if(!read_entry(entry)) return RESULT_FAIL;
if(!read_entry(entry)){
return RESULT_FAIL;
}
snprintf(value, SL_VAL_LEN-1, "%s=%u\n", key, entry->value);
}else{ // setterrunserver
if(!sl_str2i(&N, value)){
}else{ // setter
if(!sl_str2i(&N, value) || N < 0 || N > 0xffff){
WARNX("%s isn't a value of register", value);
return RESULT_BADVAL;
}
entry->value = (uint16_t)N;
if(entry->readonly){
WARNX("%s is readonly register", entry->code);
return RESULT_FAIL;
}
if(0 == get_slave()){ // we can't read anything by broadcast address
write_entry(entry);
return RESULT_SILENCE;
}
if(!write_entry(entry)) return RESULT_FAIL;
entry->value = (uint16_t)N;
return RESULT_OK;
}
sl_sock_sendstrmessage(s, value);
return RESULT_SILENCE;
}
int runserver(const char *node, int isunix){
bool runserver(const char *node, int isunix){
if(!node){
WARNX("Point node");
return FALSE;
return false;
}
sl_socktype_e type = (isunix) ? SOCKT_UNIX : SOCKT_NET;
if(s) sl_sock_delete(&s);
s = sl_sock_run_server(type, node, -1, handlers);
if(!s){
WARNX("Can't run server");
return FALSE;
return false;
}
sl_sock_connhandler(s, connected);
sl_sock_dischandler(s, disconnected);
sl_sock_defmsghandler(s, defhandler);
while(s && s->connected){
while(!exitjob && s && s->connected ){
if(!s->rthread){
WARNX("Server handlers thread is dead");
break;
@@ -305,5 +336,7 @@ int runserver(const char *node, int isunix){
}
DBG("Close");
sl_sock_delete(&s);
return TRUE;
return true;
}
void stop_server(){exitjob = true; }

View File

@@ -20,5 +20,6 @@
#include <usefull_macros.h>
int runserver(const char *node, int isunix);
bool runserver(const char *node, int isunix);
void set_io_sizes(int inputs, int coils);
void stop_server();

View File

@@ -23,10 +23,12 @@
static sl_loglevel_e verblvl = LOGLEVEL_WARN;
void set_verbose_level(sl_loglevel_e level){
if(level >= LOGLEVEL_AMOUNT) level = LOGLEVEL_AMOUNT - 1;
else if(level < 0) level = 0;
verblvl = level;
void set_verbose_level(sl_loglevel_e *level){
if(!level) return;
sl_loglevel_e l = *level;
if(l >= LOGLEVEL_AMOUNT) l = LOGLEVEL_AMOUNT - 1;
else if(l < 0) l = 0;
verblvl = *level = l;
}
void verbose(sl_loglevel_e lvl, const char *fmt, ...){

View File

@@ -20,5 +20,5 @@
#include <usefull_macros.h>
void set_verbose_level(sl_loglevel_e level);
void set_verbose_level(sl_loglevel_e *level);
void verbose(sl_loglevel_e lvl, const char *fmt, ...);