under development

This commit is contained in:
Edward Emelianov
2026-10-22 00:43:30 +03:00
parent fc80bf0766
commit bd1b8babe9
13 changed files with 474 additions and 0 deletions

57
Poweroff_daemon/Makefile Normal file
View File

@@ -0,0 +1,57 @@
# run `make DEF=...` to add extra defines
PROGRAM := powerdaemon
LDFLAGS := -fdata-sections -ffunction-sections -Wl,--gc-sections -Wl,--discard-all
LDFLAGS += -lusefull_macros
SRCS := $(wildcard *.c)
DEFINES := $(DEF) -D_GNU_SOURCE -D_XOPEN_SOURCE=1111
OBJDIR := mk
CFLAGS += -O2 -Wall -Wextra -Wno-trampolines -std=c23
OBJS := $(addprefix $(OBJDIR)/, $(SRCS:%.c=%.o))
DEPS := $(OBJS:.o=.d)
TARGFILE := $(OBJDIR)/TARGET
CC = gcc
#TARGET := RELEASE
ifeq ($(shell test -e $(TARGFILE) && echo -n yes),yes)
TARGET := $(file < $(TARGFILE))
else
TARGET := RELEASE
endif
ifeq ($(TARGET), DEBUG)
.DEFAULT_GOAL := debug
endif
release: $(PROGRAM)
debug: CFLAGS += -DEBUG -Werror
debug: TARGET := DEBUG
debug: $(PROGRAM)
$(TARGFILE): $(OBJDIR)
@echo -e "\t\tTARGET: $(TARGET)"
@echo "$(TARGET)" > $(TARGFILE)
$(PROGRAM) : $(TARGFILE) $(OBJS)
@echo -e "\t\tLD $(PROGRAM)"
$(CC) $(OBJS) $(LDFLAGS) -o $(PROGRAM)
$(OBJDIR):
@mkdir $(OBJDIR)
ifneq ($(MAKECMDGOALS),clean)
-include $(DEPS)
endif
$(OBJDIR)/%.o: %.c
@echo -e "\t\tCC $<"
$(CC) $< -MD -c $(LDFLAGS) $(CFLAGS) $(DEFINES) -o $@
clean:
@echo -e "\t\tCLEAN"
@rm -rf $(OBJDIR) 2>/dev/null || true
xclean: clean
@rm -f $(PROGRAM)
.PHONY: clean xclean

View File

@@ -0,0 +1,3 @@
Simple daemon checking voltage & button0 state of my 'fan controller'.
Under development, wait pre-release...

View File

@@ -0,0 +1,57 @@
/*
* 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 "cmdlnopts.h"
#ifndef STR
#define STRINGIFY(x) #x
#define STR(x) STRINGIFY(x)
#endif
// initial (default) options
static cmdln_t G = {
.pidfile = DEFAULT_PIDFILE,
.serialdev = DEFAULT_DEV,
.poll_interval = DEFAULT_INTERVAL,
.timeout_us = READ_TIMEOUT_US,
.baudrate = DEFAULT_BAUDRATE,
};
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"},
{"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"},
end_option
};
cmdln_t *parseargs(int *argc, char ***argv){
sl_parseargs(argc, argv, options);
if(*argc > 0) ERRX("%d unknown opions");
if (help) sl_showhelp(-1, options);
return &G;
}

View File

@@ -0,0 +1,37 @@
/*
* 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
#define DEFAULT_PIDFILE "/tmp/powerdaemon.pid"
#define DEFAULT_DEV "/dev/ttyUSB0"
#define DEFAULT_BAUDRATE 115200
#define DEFAULT_INTERVAL 1.0
#define READ_TIMEOUT_US 100000.
typedef struct{
char *pidfile;
char *logfile;
char *serialdev;
double poll_interval;
double timeout_us;
int verbose;
int baudrate;
} cmdln_t;
cmdln_t *parseargs(int *argc, char ***argv);

134
Poweroff_daemon/main.c Normal file
View File

@@ -0,0 +1,134 @@
/*
* 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.
*
* Protocol uses only '\n' as line separator (no '\r').
* USB CDC device: port settings (baudrate, format) are irrelevant.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <linux/prctl.h>
#include <sys/prctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <time.h>
#include <usefull_macros.h>
#include "cmdlnopts.h"
#include "serial.h"
static cmdln_t *G = NULL;
static bool isrunning = false;
static pid_t childpid = 0;
void signals(int sig){
if(sig > 0){
signal(sig, SIG_IGN);
DBG("Get signal %d, quit.\n", sig);
}
if(childpid){
LOGERR("Main process exits with status %d", sig);
if(G->pidfile) // remove unnesessary PID file
unlink(G->pidfile);
}else{
isrunning = false;
sleep(2); // let child to graceful out
}
exit(sig);
}
int main(int argc, char **argv){
sl_init();
G = parseargs(&argc, &argv);
sl_check4running(NULL, G->pidfile);
sl_loglevel_e lvl = LOGLEVEL_WARN;
if(G->verbose){
lvl += G->verbose;
if(lvl >= LOGLEVEL_AMOUNT) lvl = LOGLEVEL_ANY;
}
/* Open log file before daemonizing */
if(G->logfile){
OPENLOG(G->logfile, lvl, 1);
if(!sl_globlog) WARNX("Can't create log file %s", G->logfile);
}
/* Daemonize */
/* if (sl_daemonize() != 0) {
ERR("daemonize failed");
}
*/
/* Set global timeout for sl_tty_read() */
sl_tty_tmout(G->timeout_us);
LOGMSG("Monitor daemon started, polling every %.2f seconds", G->poll_interval);
signal(SIGTERM, signals);
signal(SIGINT, signals);
signal(SIGTSTP, SIG_IGN);
signal(SIGQUIT, signals);
time_t lastd = 0;
/* Main loop */
while(true){
childpid = fork();
if(childpid < 0){
LOGERR("fork() returns error");
sleep(5);
continue;
}
if(childpid){
DBG("Created child with PID %d\n", childpid);
wait(NULL);
time_t t = time(NULL);
if(t - lastd > 600){ // at least 10 minutes of work
LOGERR("Child %d died\n", childpid);
}
lastd = t;
WARNX("Child %d died\n", childpid);
sleep(1);
}else{
prctl(PR_SET_PDEATHSIG, SIGTERM); // send SIGTERM to child when parent dies
break; // go out to normal functional
}
}
/******************** child PID ********************/
// Open serial port
if(!open_serial(G->serialdev, G->baudrate)){
LOGERR("Can't open %s @%d", G->serialdev, G->baudrate);
ERRX("Can't open %s @%d", G->serialdev, G->baudrate);
}
isrunning = true;
while(isrunning){
bool trigger = false;
if(check_buttons()) trigger = true;
if(check_voltage()) trigger = true;
if(trigger){
LOGERR("Trigger condition met, executing poweroff");
DBG("poweroff");
/* int ret = system("poweroff");
if (ret == -1) {
LOGERR("Failed to execute poweroff: %s", strerror(errno));
}
break;
*/ }
usleep((useconds_t)(G->poll_interval * 1e6)); // seconds -> useconds
}
close_serial();
return 0;
}

View File

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

View File

@@ -0,0 +1,2 @@
// Add predefined macros for your project here. For example:
// #define THE_ANSWER 42

View File

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

View File

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

View File

@@ -0,0 +1,5 @@
cmdlnopts.c
cmdlnopts.h
main.c
serial.c
serial.h

View File

140
Poweroff_daemon/serial.c Normal file
View File

@@ -0,0 +1,140 @@
/*
* 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 <pthread.h>
#include <string.h>
#include <usefull_macros.h>
#include "serial.h"
static sl_tty_t *tty = NULL;
static pthread_mutex_t serial_mutex = PTHREAD_MUTEX_INITIALIZER;
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;
return true;
}
void close_serial(){
sl_tty_close(&tty);
tty = NULL;
}
/*
* Parse an integer value by key from a response buffer.
* Lines are separated by '\n'. No '\r' is expected.
* Returns true on success, false otherwise.
*/
static bool parse_int_from_response(const char *buf, const char *key, int *val) {
char *copy = strdup(buf);
if(!copy) return 0;
char *line = strtok(copy, "\n");
while(line){
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);
free(copy);
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);
free(copy);
return false;
}
static bool get_int(const char *cmdstring, const char *key, int *answer){
if(!tty || !cmdstring || !key) return false;
static int errcnt = 0;
DBG("Ask parameter '%s' from command %s", key, cmdstring);
pthread_mutex_lock(&serial_mutex);
if(sl_tty_write(tty->comfd, cmdstring, strlen(cmdstring))){
WARNX("Write error");
LOGERR("Serial writing error");
pthread_mutex_unlock(&serial_mutex);
if(++errcnt > MAX_WERR_CNT){
LOGERR("No connection -> go off");
ERRX("No connection -> go off");
}
return false;
}
int n = sl_tty_read(tty);
if(n <= 0){
char buf[BUFSIZ];
strncpy(buf, cmdstring, BUFSIZ-1);
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");
}
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;
DBG("Got int: %d", i);
if(answer) *answer = i;
return true;
}
/* Check buttons: returns true if BUTTON0 == 1 */
bool check_buttons(){
int b0 = 0;
if(!get_int(CMD_BTNCHECK, ANS_BTN0STATE, &b0)) return false;
if(b0){
LOGERR("BUTTON0 pressed (value=%d)", b0);
return true;
}
return false;
}
/* Check voltage: returns 1 if V12 < 9700 */
bool check_voltage(){
int voltage = 0;
if(!get_int(CMD_GETVOLTAGE, ANS_V12, &voltage)) return false;
if(voltage < LOWEST_V12){
LOGERR("V12 low: %d (%.2f V)", voltage, (double)voltage / 100.);
return true;
}
return false;
}
bool send_custom_command(const char *command, char *answer, size_t anslen){
if(!tty || !command) return false;
bool ret = false;
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;
}
pthread_mutex_unlock(&serial_mutex);
return ret;
}

36
Poweroff_daemon/serial.h Normal file
View File

@@ -0,0 +1,36 @@
/*
* 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
#define CMD_BTNCHECK "B\n"
#define ANS_BTN0STATE "BUTTON0"
#define CMD_GETVOLTAGE "V\n"
#define ANS_V12 "V12"
#define LOWEST_V12 970
#define MAX_WERR_CNT 5
#define MAX_RERR_CNT 15
bool open_serial(const char *path, int baudrate);
void close_serial();
bool check_buttons();
bool check_voltage();
bool send_custom_command(const char *command, char *answer, size_t anslen);