mirror of
https://github.com/eddyem/small_tel.git
synced 2026-03-20 00:31:00 +03:00
pre-alpha version of new dome daemon
This commit is contained in:
64
Daemons/domedaemon-astrosib/CMakeLists.txt
Normal file
64
Daemons/domedaemon-astrosib/CMakeLists.txt
Normal file
@@ -0,0 +1,64 @@
|
||||
cmake_minimum_required(VERSION 3.30)
|
||||
|
||||
set(PROJ domedaemon)
|
||||
project(${PROJ})
|
||||
|
||||
set(MINOR_VERSION "0")
|
||||
set(MID_VERSION "1")
|
||||
set(MAJOR_VERSION "0")
|
||||
set(VERSION "${MAJOR_VERSION}.${MID_VERSION}.${MINOR_VERSION}")
|
||||
|
||||
enable_language(C)
|
||||
message("VER: ${VERSION}")
|
||||
|
||||
# options
|
||||
option(DEBUG "Compile in debug mode" OFF)
|
||||
|
||||
# default flags
|
||||
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -W -Wextra -std=gnu99")
|
||||
if(DEBUG)
|
||||
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Og -g3 -ggdb -fno-builtin-strlen -Werror")
|
||||
add_definitions(-DEBUG)
|
||||
set(CMAKE_BUILD_TYPE DEBUG)
|
||||
set(CMAKE_VERBOSE_MAKEFILE "ON")
|
||||
else()
|
||||
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -O3 -march=native -fdata-sections -ffunction-sections")
|
||||
SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,--gc-sections")
|
||||
set(CMAKE_BUILD_TYPE RELEASE)
|
||||
endif()
|
||||
|
||||
message("Build type: ${CMAKE_BUILD_TYPE}")
|
||||
|
||||
set(CMAKE_COLOR_MAKEFILE ON)
|
||||
|
||||
# here is one of two variants: all .c in directory or .c files in list
|
||||
aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR} SOURCES)
|
||||
|
||||
###### pkgconfig ######
|
||||
find_package(PkgConfig REQUIRED)
|
||||
pkg_check_modules(MODULES REQUIRED usefull_macros>=0.3.2)
|
||||
|
||||
# change wrong behaviour with install prefix
|
||||
if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT AND CMAKE_INSTALL_PREFIX MATCHES "/usr/local")
|
||||
else()
|
||||
message("Change default install path to /usr/local")
|
||||
set(CMAKE_INSTALL_PREFIX "/usr/local")
|
||||
endif()
|
||||
message("Install dir prefix: ${CMAKE_INSTALL_PREFIX}")
|
||||
|
||||
# executable file
|
||||
add_executable(${PROJ} ${SOURCES})
|
||||
# -I
|
||||
target_include_directories(${PROJ} PUBLIC ${MODULES_INCLUDE_DIRS})
|
||||
# -L
|
||||
target_link_directories(${PROJ} PUBLIC ${MODULES_LIBRARY_DIRS})
|
||||
# -l
|
||||
target_link_libraries(${PROJ} ${MODULES_LIBRARIES})
|
||||
# -D
|
||||
add_definitions(
|
||||
-DPACKAGE_VERSION=\"${VERSION}\" -DMINOR_VERSION=\"${MINOR_VERSION}\"
|
||||
-DMID_VERSION=\"${MID_VERSION}\" -DMAJOR_VERSION=\"${MAJOR_VESION}\"
|
||||
)
|
||||
|
||||
# Installation of the program
|
||||
INSTALL(TARGETS ${PROJ} DESTINATION "bin")
|
||||
@@ -1,43 +0,0 @@
|
||||
# run `make DEF=...` to add extra defines
|
||||
PROGRAM := domedaemon
|
||||
LDFLAGS := -fdata-sections -ffunction-sections -Wl,--gc-sections -Wl,--discard-all -pthread
|
||||
SRCS := $(wildcard *.c)
|
||||
DEFINES := $(DEF) -D_GNU_SOURCE -D_XOPEN_SOURCE=1111
|
||||
#DEFINES += -DEBUG
|
||||
# baudrate for USB<->UART converter
|
||||
DEFINES += -DBAUD_RATE=B9600
|
||||
OBJDIR := mk
|
||||
CFLAGS += -O2 -Wall -Werror -Wextra -Wno-trampolines
|
||||
OBJS := $(addprefix $(OBJDIR)/, $(SRCS:%.c=%.o))
|
||||
DEPS := $(OBJS:.o=.d)
|
||||
CC = gcc
|
||||
|
||||
all : $(OBJDIR) $(PROGRAM)
|
||||
|
||||
$(PROGRAM) : $(OBJS)
|
||||
@echo -e "\t\tLD $(PROGRAM)"
|
||||
$(CC) $(LDFLAGS) $(OBJS) -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 -f $(OBJS) $(DEPS)
|
||||
@rmdir $(OBJDIR) 2>/dev/null || true
|
||||
|
||||
xclean: clean
|
||||
@rm -f $(PROGRAM)
|
||||
|
||||
gentags:
|
||||
CFLAGS="$(CFLAGS) $(DEFINES)" geany -g $(PROGRAM).c.tags *[hc] 2>/dev/null
|
||||
|
||||
.PHONY: gentags clean xclean
|
||||
@@ -1,12 +1,5 @@
|
||||
Astrosib all-sky dome control network daemon
|
||||
==================
|
||||
New version of "Astrosib" dome daemon.
|
||||
|
||||
Open a socket at given port (default: 55555), works with http & direct requests.
|
||||
Based on snippets_library ver. >= 0.3.2
|
||||
Allow more functionality than old one.
|
||||
|
||||
**Protocol**
|
||||
|
||||
Send requests over socket (by curl or something else) or http requests (in browser).
|
||||
|
||||
* *open* - open dome;
|
||||
* *close* - close dome;
|
||||
* *status* - dome state (return "opened", "closed" or "intermediate");
|
||||
|
||||
27
Daemons/domedaemon-astrosib/astrosib_proto.h
Normal file
27
Daemons/domedaemon-astrosib/astrosib_proto.h
Normal file
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
* This file is part of the domedaemon-astrosib project.
|
||||
* Copyright 2025 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 ASIB_CMD_STATUS "STATUS"
|
||||
#define ASIB_CMD_RELAY "SWITCHTOGGILE"
|
||||
#define ASIB_CMD_STOP "STOPDOME"
|
||||
#define ASIB_CMD_OPEN "OPENDOME"
|
||||
#define ASIB_CMD_CLOSE "CLOSEDOME"
|
||||
#define ASIB_CMD_MOVEONE "SHUTTERMOVEDEG"
|
||||
#define ASIB_CMD_RELAY "SWITCHTOGGILE"
|
||||
@@ -1,89 +0,0 @@
|
||||
/* geany_encoding=koi8-r
|
||||
* cmdlnopts.c - the only function that parse cmdln args and returns glob parameters
|
||||
*
|
||||
* Copyright 2018 Edward V. Emelianoff <eddy@sao.ru>
|
||||
*
|
||||
* 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 2 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, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
* MA 02110-1301, USA.
|
||||
*/
|
||||
#include <assert.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <strings.h>
|
||||
#include <math.h>
|
||||
#include "cmdlnopts.h"
|
||||
#include "usefull_macros.h"
|
||||
|
||||
/*
|
||||
* here are global parameters initialisation
|
||||
*/
|
||||
int help;
|
||||
static glob_pars G;
|
||||
|
||||
// default values for Gdefault & help
|
||||
#define DEFAULT_PORT "55555"
|
||||
|
||||
// DEFAULTS
|
||||
// default global parameters
|
||||
glob_pars const Gdefault = {
|
||||
.device = NULL,
|
||||
.port = DEFAULT_PORT,
|
||||
.terminal = 0,
|
||||
.echo = 0,
|
||||
.logfile = NULL,
|
||||
.rest_pars = NULL,
|
||||
.rest_pars_num = 0
|
||||
};
|
||||
|
||||
/*
|
||||
* Define command line options by filling structure:
|
||||
* name has_arg flag val type argptr help
|
||||
*/
|
||||
myoption cmdlnopts[] = {
|
||||
// common options
|
||||
{"help", NO_ARGS, NULL, 'h', arg_int, APTR(&help), _("show this help")},
|
||||
{"device", NEED_ARG, NULL, 'd', arg_string, APTR(&G.device), _("serial device name (default: none)")},
|
||||
{"port", NEED_ARG, NULL, 'p', arg_string, APTR(&G.port), _("network port to connect (default: " DEFAULT_PORT ")")},
|
||||
{"logfile", NEED_ARG, NULL, 'l', arg_string, APTR(&G.logfile), _("save logs to file (default: none)")},
|
||||
{"terminal",NO_ARGS, NULL, 't', arg_int, APTR(&G.terminal), _("run as terminal")},
|
||||
{"echo", NO_ARGS, NULL, 'e', arg_int, APTR(&G.echo), _("echo users commands back")},
|
||||
end_option
|
||||
};
|
||||
|
||||
/**
|
||||
* Parse command line options and return dynamically allocated structure
|
||||
* to global parameters
|
||||
* @param argc - copy of argc from main
|
||||
* @param argv - copy of argv from main
|
||||
* @return allocated structure with global parameters
|
||||
*/
|
||||
glob_pars *parse_args(int argc, char **argv){
|
||||
int i;
|
||||
void *ptr;
|
||||
ptr = memcpy(&G, &Gdefault, sizeof(G)); assert(ptr);
|
||||
// format of help: "Usage: progname [args]\n"
|
||||
change_helpstring("Usage: %s [args]\n\n\tWhere args are:\n");
|
||||
// parse arguments
|
||||
parseargs(&argc, &argv, cmdlnopts);
|
||||
if(help) showhelp(-1, cmdlnopts);
|
||||
if(argc > 0){
|
||||
G.rest_pars_num = argc;
|
||||
G.rest_pars = calloc(argc, sizeof(char*));
|
||||
for (i = 0; i < argc; i++)
|
||||
G.rest_pars[i] = strdup(argv[i]);
|
||||
}
|
||||
return &G;
|
||||
}
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
/* geany_encoding=koi8-r
|
||||
* cmdlnopts.h - comand line options for parceargs
|
||||
*
|
||||
* Copyright 2018 Edward V. Emelianoff <eddy@sao.ru>
|
||||
*
|
||||
* 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 2 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, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
* MA 02110-1301, USA.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
#ifndef __CMDLNOPTS_H__
|
||||
#define __CMDLNOPTS_H__
|
||||
|
||||
#include "parseargs.h"
|
||||
#include "term.h"
|
||||
|
||||
/*
|
||||
* here are some typedef's for global data
|
||||
*/
|
||||
typedef struct{
|
||||
char *device; // serial device name
|
||||
char *port; // port to connect
|
||||
char *logfile; // logfile name
|
||||
int terminal; // run as terminal
|
||||
int echo; // echo user commands back
|
||||
int rest_pars_num; // number of rest parameters
|
||||
char** rest_pars; // the rest parameters: array of char* (path to logfile and thrash)
|
||||
} glob_pars;
|
||||
|
||||
|
||||
glob_pars *parse_args(int argc, char **argv);
|
||||
#endif // __CMDLNOPTS_H__
|
||||
257
Daemons/domedaemon-astrosib/dome.c
Normal file
257
Daemons/domedaemon-astrosib/dome.c
Normal file
@@ -0,0 +1,257 @@
|
||||
/*
|
||||
* This file is part of the domedaemon-astrosib project.
|
||||
* Copyright 2025 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 <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "astrosib_proto.h"
|
||||
#include "dome.h"
|
||||
|
||||
// number of relay turning on/off motors power
|
||||
#define MOTRELAY_NO 1
|
||||
// state of relay to turn power on/off
|
||||
#define MOTRELAY_ON 1
|
||||
#define MOTRELAY_OFF 0
|
||||
|
||||
// time interval for requiring current dome status in idle state (e.g. trigger watchdog)
|
||||
#define STATUSREQ_IDLE 10.
|
||||
// update interval in moving state
|
||||
#define STATUSREQ_MOVE 0.5
|
||||
|
||||
// dome status by polling (each STATUSREQ_IDLE seconds)
|
||||
static dome_status_t dome_status = {0};
|
||||
// finite state machine state
|
||||
static dome_state_t state = DOME_S_IDLE;
|
||||
// last time dome_status was updated
|
||||
static double last_status_time = 0.;
|
||||
// current update interval
|
||||
static double status_req_interval = STATUSREQ_MOVE;
|
||||
// serial device
|
||||
static sl_tty_t *serialdev = NULL;
|
||||
static pthread_mutex_t serialmutex = PTHREAD_MUTEX_INITIALIZER;
|
||||
|
||||
void dome_serialdev(sl_tty_t *serial){
|
||||
serialdev = serial;
|
||||
}
|
||||
/**
|
||||
* @brief serial_write - write buffer without "\r" on end to port
|
||||
* @param cmd - data to send
|
||||
* @param answer - buffer for answer (or NULL if not need)
|
||||
* @param anslen - length of `answer`
|
||||
* @return error code
|
||||
*/
|
||||
static int serial_write(const char *cmd, char *answer, int anslen){
|
||||
if(!serialdev || !cmd || !answer || anslen < 2) return FALSE;
|
||||
static char *buf = NULL;
|
||||
static size_t buflen = 0;
|
||||
DBG("Write %s", cmd);
|
||||
size_t cmdlen = strlen(cmd);
|
||||
if(buflen < cmdlen + 2){
|
||||
buflen = (cmdlen + 4096) / 4096;
|
||||
buflen *= 4096;
|
||||
if(!(buf = realloc(buf, buflen))){
|
||||
LOGERR("serial_write(): realloc() failed!");
|
||||
ERRX("serial_write(): realloc() failed!");
|
||||
}
|
||||
}
|
||||
size_t _2write = snprintf(buf, buflen-1, "%s\r", cmd);
|
||||
DBG("try to send %zd bytes", _2write);
|
||||
if(sl_tty_write(serialdev->comfd, buf, _2write)) return FALSE;
|
||||
int got = 0, totlen = 0;
|
||||
--anslen; // for /0
|
||||
do{
|
||||
got = sl_tty_read(serialdev);
|
||||
if(got > 0){
|
||||
if(got > anslen) return FALSE; // buffer overflow
|
||||
memcpy(answer, serialdev->buf, got);
|
||||
totlen += got;
|
||||
answer += got;
|
||||
anslen -= got;
|
||||
answer[0] = 0;
|
||||
}
|
||||
DBG("got = %d", got);
|
||||
}while(got > 0 && anslen);
|
||||
if(got < 0){
|
||||
LOGERR("serial_write(): serial device disconnected!");
|
||||
ERRX("serial_write(): serial device disconnected!");
|
||||
}
|
||||
if(totlen < 1) return FALSE; // no answer received
|
||||
if(answer[-1] == '\r') answer[-1] = 0; // remove trailing trash
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
// return TRUE if can parse status
|
||||
static int parsestatus(const char *buf){
|
||||
if(!buf) return FALSE;
|
||||
DBG("buf=%s", buf);
|
||||
int n = sscanf(buf, ASIB_CMD_STATUS "%d,%d,%d,%d,%f,%f,%f,%f,%f,%f,%d,%d,%d,%d,%d",
|
||||
&dome_status.coverstate[0], &dome_status.coverstate[1],
|
||||
&dome_status.encoder[0], &dome_status.encoder[1],
|
||||
&dome_status.Tin, &dome_status.Tout,
|
||||
&dome_status.Imot[0], &dome_status.Imot[1], &dome_status.Imot[2], &dome_status.Imot[3],
|
||||
&dome_status.relay[0], &dome_status.relay[1], &dome_status.relay[2],
|
||||
&dome_status.rainArmed, &dome_status.israin);
|
||||
DBG("n=%d", n);
|
||||
if(n != 15){
|
||||
WARNX("Something wrong with STATUS answer");
|
||||
LOGWARN("Something wrong with STATUS answer");
|
||||
LOGWARNADD("%s", buf);
|
||||
return FALSE;
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
// check status; return FALSE if failed
|
||||
static int check_status(){
|
||||
char buf[BUFSIZ];
|
||||
// clear input buffers
|
||||
int got = sl_tty_read(serialdev);
|
||||
if(got > 0) printf("Got from serial %zd bytes of trash: `%s`\n", serialdev->buflen, serialdev->buf);
|
||||
else if(got < 0){
|
||||
LOGERR("Serial device disconnected?");
|
||||
ERRX("Serial device disconnected?");
|
||||
}
|
||||
DBG("Require status");
|
||||
if(!serial_write(ASIB_CMD_STATUS, buf, BUFSIZ)) return FALSE;
|
||||
int ret = FALSE;
|
||||
if(parsestatus(buf)){
|
||||
last_status_time = sl_dtime();
|
||||
ret = TRUE;
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
// run naked command or command with parameters
|
||||
static int runcmd(const char *cmd, const char *par){
|
||||
char buf[128];
|
||||
if(!cmd) return FALSE;
|
||||
DBG("Send command %s with par %s", cmd, par);
|
||||
if(!par) snprintf(buf, 127, "%s", cmd);
|
||||
else snprintf(buf, 127, "%s%s", cmd, par);
|
||||
if(!serial_write(buf, buf, 128)) return FALSE;
|
||||
if(strncmp(buf, "OK", 2)) return FALSE;
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
// check current state and turn on/off relay if need
|
||||
static void chkrelay(){
|
||||
if(state != DOME_S_MOVING) return;
|
||||
if(dome_status.coverstate[0] == COVER_INTERMEDIATE ||
|
||||
dome_status.coverstate[1] == COVER_INTERMEDIATE) return; // still moving
|
||||
// OK, we are on place - turn off motors' power
|
||||
char buf[128];
|
||||
snprintf(buf, 127, "%s%d,%d", ASIB_CMD_RELAY, MOTRELAY_NO, MOTRELAY_OFF);
|
||||
if(serial_write(buf, buf, 128) && check_status()){
|
||||
DBG("Check are motors really off");
|
||||
if(dome_status.relay[MOTRELAY_NO-1] == MOTRELAY_OFF){
|
||||
DBG("OK state->IDLE");
|
||||
state = DOME_S_IDLE;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// turn ON motors' relay
|
||||
static int motors_on(){
|
||||
char buf[128];
|
||||
snprintf(buf, 127, "%s%d,%d", ASIB_CMD_RELAY, MOTRELAY_NO, MOTRELAY_ON);
|
||||
if(serial_write(buf, buf, 128) && check_status()){
|
||||
DBG("Check are motors really on");
|
||||
if(dome_status.relay[MOTRELAY_NO-1] == MOTRELAY_ON){
|
||||
DBG("OK state->MOVING");
|
||||
state = DOME_S_MOVING;
|
||||
return TRUE;
|
||||
}
|
||||
}
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
// just get current status
|
||||
double get_dome_status(dome_status_t *s){
|
||||
if(s){
|
||||
pthread_mutex_lock(&serialmutex);
|
||||
*s = dome_status;
|
||||
pthread_mutex_unlock(&serialmutex);
|
||||
}
|
||||
return last_status_time;
|
||||
}
|
||||
|
||||
dome_state_t get_dome_state(){return state;}
|
||||
|
||||
dome_state_t dome_poll(dome_cmd_t cmd, int par){
|
||||
char buf[128];
|
||||
int st = DOME_S_ERROR;
|
||||
double curtime = sl_dtime();
|
||||
//DBG("curtime-lasttime=%g", curtime - last_status_time);
|
||||
// simple polling and there's a lot of time until next serial device poll
|
||||
if(cmd == DOME_POLL && curtime - last_status_time < status_req_interval)
|
||||
return state;
|
||||
pthread_mutex_lock(&serialmutex);
|
||||
// check if we need to turn ON motors' relay
|
||||
switch(cmd){
|
||||
case DOME_OPEN:
|
||||
case DOME_CLOSE:
|
||||
case DOME_OPEN_ONE:
|
||||
case DOME_CLOSE_ONE:
|
||||
if(!motors_on()) goto ret;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
switch(cmd){
|
||||
case DOME_STOP:
|
||||
if(!runcmd(ASIB_CMD_STOP, NULL)) goto ret;
|
||||
break;
|
||||
case DOME_OPEN:
|
||||
if(!runcmd(ASIB_CMD_OPEN, NULL)) goto ret;
|
||||
break;
|
||||
case DOME_CLOSE:
|
||||
if(!runcmd(ASIB_CMD_CLOSE, NULL)) goto ret;
|
||||
break;
|
||||
case DOME_OPEN_ONE:
|
||||
if(par < 1 || par > 2) goto ret;
|
||||
snprintf(buf, 127, "%d 90", par);
|
||||
if(!runcmd(ASIB_CMD_MOVEONE, buf)) goto ret;
|
||||
break;
|
||||
case DOME_CLOSE_ONE:
|
||||
if(par < 1 || par > 2) goto ret;
|
||||
snprintf(buf, 127, "%d 0", par);
|
||||
if(!runcmd(ASIB_CMD_MOVEONE, buf)) goto ret;
|
||||
break;
|
||||
case DOME_RELAY_ON:
|
||||
if(par < 1 || par > 3) goto ret;
|
||||
snprintf(buf, 127, "%d,1", par);
|
||||
if(!runcmd(ASIB_CMD_RELAY, buf)) goto ret;
|
||||
break;
|
||||
case DOME_RELAY_OFF:
|
||||
if(par < 1 || par > 3) goto ret;
|
||||
snprintf(buf, 127, "%d,0", par);
|
||||
if(!runcmd(ASIB_CMD_RELAY, buf)) goto ret;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
ret:
|
||||
if(check_status()){
|
||||
chkrelay();
|
||||
st = state;
|
||||
}
|
||||
if(state == DOME_S_IDLE) status_req_interval = STATUSREQ_IDLE;
|
||||
else status_req_interval = STATUSREQ_MOVE;
|
||||
pthread_mutex_unlock(&serialmutex);
|
||||
return st;
|
||||
}
|
||||
65
Daemons/domedaemon-astrosib/dome.h
Normal file
65
Daemons/domedaemon-astrosib/dome.h
Normal file
@@ -0,0 +1,65 @@
|
||||
/*
|
||||
* This file is part of the domedaemon-astrosib project.
|
||||
* Copyright 2025 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
|
||||
|
||||
#include <usefull_macros.h>
|
||||
|
||||
#define NRELAY_MIN 1
|
||||
#define NRELAY_MAX 3
|
||||
|
||||
// dome finite state machine state
|
||||
typedef enum{
|
||||
DOME_S_IDLE, // idle, motors disabled
|
||||
DOME_S_MOVING, // moving, motors enabled
|
||||
DOME_S_ERROR // some kind of error
|
||||
} dome_state_t;
|
||||
|
||||
// commands through dome_poll interface
|
||||
typedef enum{
|
||||
DOME_POLL, // just poll state maching
|
||||
DOME_STOP, // stop any moving
|
||||
DOME_OPEN, // fully open dome
|
||||
DOME_CLOSE, // fully close dome
|
||||
DOME_OPEN_ONE, // open only one part # `par` (1-2)
|
||||
DOME_CLOSE_ONE, // close only one part # `par`
|
||||
DOME_RELAY_ON, // turn on relay # `par` (1-3)
|
||||
DOME_RELAY_OFF, // turn off relay # `par`
|
||||
} dome_cmd_t;
|
||||
|
||||
// cover states
|
||||
enum{
|
||||
COVER_INTERMEDIATE = 1,
|
||||
COVER_OPENED = 2,
|
||||
COVER_CLOSED = 3
|
||||
};
|
||||
|
||||
typedef struct{
|
||||
int coverstate[2]; // north/south covers state (3 - closed, 2 - opened, 1 - intermediate)
|
||||
int encoder[2]; // encoders values
|
||||
float Tin; // temperatures (unavailable)
|
||||
float Tout;
|
||||
float Imot[4]; // motors' currents
|
||||
int relay[3]; // relays' state
|
||||
int rainArmed; // rain sensor closes the dome
|
||||
int israin; // arm sensor signal
|
||||
} dome_status_t;
|
||||
|
||||
double get_dome_status(dome_status_t *s);
|
||||
dome_state_t get_dome_state();
|
||||
dome_state_t dome_poll(dome_cmd_t cmd, int par);
|
||||
void dome_serialdev(sl_tty_t *serial);
|
||||
@@ -1,157 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE QtCreatorProject>
|
||||
<!-- Written by QtCreator 4.12.3, 2020-12-25T15:48:52. -->
|
||||
<qtcreator>
|
||||
<data>
|
||||
<variable>EnvironmentId</variable>
|
||||
<value type="QByteArray">{cf63021e-ef53-49b0-b03b-2f2570cdf3b6}</value>
|
||||
</data>
|
||||
<data>
|
||||
<variable>ProjectExplorer.Project.ActiveTarget</variable>
|
||||
<value type="int">0</value>
|
||||
</data>
|
||||
<data>
|
||||
<variable>ProjectExplorer.Project.EditorSettings</variable>
|
||||
<valuemap type="QVariantMap">
|
||||
<value type="bool" key="EditorConfiguration.AutoIndent">true</value>
|
||||
<value type="bool" key="EditorConfiguration.AutoSpacesForTabs">false</value>
|
||||
<value type="bool" key="EditorConfiguration.CamelCaseNavigation">true</value>
|
||||
<valuemap type="QVariantMap" key="EditorConfiguration.CodeStyle.0">
|
||||
<value type="QString" key="language">Cpp</value>
|
||||
<valuemap type="QVariantMap" key="value">
|
||||
<value type="QByteArray" key="CurrentPreferences">CppGlobal</value>
|
||||
</valuemap>
|
||||
</valuemap>
|
||||
<valuemap type="QVariantMap" key="EditorConfiguration.CodeStyle.1">
|
||||
<value type="QString" key="language">QmlJS</value>
|
||||
<valuemap type="QVariantMap" key="value">
|
||||
<value type="QByteArray" key="CurrentPreferences">QmlJSGlobal</value>
|
||||
</valuemap>
|
||||
</valuemap>
|
||||
<value type="int" key="EditorConfiguration.CodeStyle.Count">2</value>
|
||||
<value type="QByteArray" key="EditorConfiguration.Codec">KOI8-R</value>
|
||||
<value type="bool" key="EditorConfiguration.ConstrainTooltips">false</value>
|
||||
<value type="int" key="EditorConfiguration.IndentSize">4</value>
|
||||
<value type="bool" key="EditorConfiguration.KeyboardTooltips">false</value>
|
||||
<value type="int" key="EditorConfiguration.MarginColumn">80</value>
|
||||
<value type="bool" key="EditorConfiguration.MouseHiding">true</value>
|
||||
<value type="bool" key="EditorConfiguration.MouseNavigation">true</value>
|
||||
<value type="int" key="EditorConfiguration.PaddingMode">1</value>
|
||||
<value type="bool" key="EditorConfiguration.ScrollWheelZooming">false</value>
|
||||
<value type="bool" key="EditorConfiguration.ShowMargin">false</value>
|
||||
<value type="int" key="EditorConfiguration.SmartBackspaceBehavior">1</value>
|
||||
<value type="bool" key="EditorConfiguration.SmartSelectionChanging">true</value>
|
||||
<value type="bool" key="EditorConfiguration.SpacesForTabs">true</value>
|
||||
<value type="int" key="EditorConfiguration.TabKeyBehavior">0</value>
|
||||
<value type="int" key="EditorConfiguration.TabSize">8</value>
|
||||
<value type="bool" key="EditorConfiguration.UseGlobal">true</value>
|
||||
<value type="int" key="EditorConfiguration.Utf8BomBehavior">2</value>
|
||||
<value type="bool" key="EditorConfiguration.addFinalNewLine">true</value>
|
||||
<value type="bool" key="EditorConfiguration.cleanIndentation">true</value>
|
||||
<value type="bool" key="EditorConfiguration.cleanWhitespace">true</value>
|
||||
<value type="bool" key="EditorConfiguration.inEntireDocument">true</value>
|
||||
</valuemap>
|
||||
</data>
|
||||
<data>
|
||||
<variable>ProjectExplorer.Project.PluginSettings</variable>
|
||||
<valuemap type="QVariantMap"/>
|
||||
</data>
|
||||
<data>
|
||||
<variable>ProjectExplorer.Project.Target.0</variable>
|
||||
<valuemap type="QVariantMap">
|
||||
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Desktop</value>
|
||||
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName">Desktop</value>
|
||||
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">{91347f2c-5221-46a7-80b1-0a054ca02f79}</value>
|
||||
<value type="int" key="ProjectExplorer.Target.ActiveBuildConfiguration">0</value>
|
||||
<value type="int" key="ProjectExplorer.Target.ActiveDeployConfiguration">0</value>
|
||||
<value type="int" key="ProjectExplorer.Target.ActiveRunConfiguration">0</value>
|
||||
<valuemap type="QVariantMap" key="ProjectExplorer.Target.BuildConfiguration.0">
|
||||
<value type="QString" key="ProjectExplorer.BuildConfiguration.BuildDirectory">/home/eddy/Docs/SAO/10micron/C-sources/domedaemon-astrosib</value>
|
||||
<valuemap type="QVariantMap" key="ProjectExplorer.BuildConfiguration.BuildStepList.0">
|
||||
<valuemap type="QVariantMap" key="ProjectExplorer.BuildStepList.Step.0">
|
||||
<valuelist type="QVariantList" key="GenericProjectManager.GenericMakeStep.BuildTargets">
|
||||
<value type="QString">all</value>
|
||||
</valuelist>
|
||||
<value type="bool" key="GenericProjectManager.GenericMakeStep.Clean">false</value>
|
||||
<value type="QString" key="GenericProjectManager.GenericMakeStep.MakeArguments"></value>
|
||||
<value type="QString" key="GenericProjectManager.GenericMakeStep.MakeCommand"></value>
|
||||
<value type="bool" key="GenericProjectManager.GenericMakeStep.OverrideMakeflags">false</value>
|
||||
<value type="bool" key="ProjectExplorer.BuildStep.Enabled">true</value>
|
||||
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">GenericProjectManager.GenericMakeStep</value>
|
||||
</valuemap>
|
||||
<value type="int" key="ProjectExplorer.BuildStepList.StepsCount">1</value>
|
||||
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Сборка</value>
|
||||
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName">Сборка</value>
|
||||
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">ProjectExplorer.BuildSteps.Build</value>
|
||||
</valuemap>
|
||||
<valuemap type="QVariantMap" key="ProjectExplorer.BuildConfiguration.BuildStepList.1">
|
||||
<valuemap type="QVariantMap" key="ProjectExplorer.BuildStepList.Step.0">
|
||||
<valuelist type="QVariantList" key="GenericProjectManager.GenericMakeStep.BuildTargets">
|
||||
<value type="QString">clean</value>
|
||||
</valuelist>
|
||||
<value type="bool" key="GenericProjectManager.GenericMakeStep.Clean">true</value>
|
||||
<value type="QString" key="GenericProjectManager.GenericMakeStep.MakeArguments"></value>
|
||||
<value type="QString" key="GenericProjectManager.GenericMakeStep.MakeCommand"></value>
|
||||
<value type="bool" key="GenericProjectManager.GenericMakeStep.OverrideMakeflags">false</value>
|
||||
<value type="bool" key="ProjectExplorer.BuildStep.Enabled">true</value>
|
||||
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">GenericProjectManager.GenericMakeStep</value>
|
||||
</valuemap>
|
||||
<value type="int" key="ProjectExplorer.BuildStepList.StepsCount">1</value>
|
||||
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Очистка</value>
|
||||
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName">Очистка</value>
|
||||
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">ProjectExplorer.BuildSteps.Clean</value>
|
||||
</valuemap>
|
||||
<value type="int" key="ProjectExplorer.BuildConfiguration.BuildStepListCount">2</value>
|
||||
<value type="bool" key="ProjectExplorer.BuildConfiguration.ClearSystemEnvironment">false</value>
|
||||
<valuelist type="QVariantList" key="ProjectExplorer.BuildConfiguration.UserEnvironmentChanges"/>
|
||||
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName">По умолчанию</value>
|
||||
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">GenericProjectManager.GenericBuildConfiguration</value>
|
||||
</valuemap>
|
||||
<value type="int" key="ProjectExplorer.Target.BuildConfigurationCount">1</value>
|
||||
<valuemap type="QVariantMap" key="ProjectExplorer.Target.DeployConfiguration.0">
|
||||
<valuemap type="QVariantMap" key="ProjectExplorer.BuildConfiguration.BuildStepList.0">
|
||||
<value type="int" key="ProjectExplorer.BuildStepList.StepsCount">0</value>
|
||||
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Развёртывание</value>
|
||||
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName">Развёртывание</value>
|
||||
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">ProjectExplorer.BuildSteps.Deploy</value>
|
||||
</valuemap>
|
||||
<value type="int" key="ProjectExplorer.BuildConfiguration.BuildStepListCount">1</value>
|
||||
<valuemap type="QVariantMap" key="ProjectExplorer.DeployConfiguration.CustomData"/>
|
||||
<value type="bool" key="ProjectExplorer.DeployConfiguration.CustomDataEnabled">false</value>
|
||||
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">ProjectExplorer.DefaultDeployConfiguration</value>
|
||||
</valuemap>
|
||||
<value type="int" key="ProjectExplorer.Target.DeployConfigurationCount">1</value>
|
||||
<valuemap type="QVariantMap" key="ProjectExplorer.Target.PluginSettings"/>
|
||||
<valuemap type="QVariantMap" key="ProjectExplorer.Target.RunConfiguration.0">
|
||||
<value type="int" key="PE.EnvironmentAspect.Base">2</value>
|
||||
<valuelist type="QVariantList" key="PE.EnvironmentAspect.Changes"/>
|
||||
<value type="QString" key="ProjectExplorer.CustomExecutableRunConfiguration.Executable"></value>
|
||||
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">ProjectExplorer.CustomExecutableRunConfiguration</value>
|
||||
<value type="QString" key="ProjectExplorer.RunConfiguration.BuildKey"></value>
|
||||
<value type="QString" key="RunConfiguration.Arguments"></value>
|
||||
<value type="bool" key="RunConfiguration.Arguments.multi">false</value>
|
||||
<value type="QString" key="RunConfiguration.OverrideDebuggerStartup"></value>
|
||||
<value type="bool" key="RunConfiguration.UseCppDebugger">false</value>
|
||||
<value type="bool" key="RunConfiguration.UseCppDebuggerAuto">true</value>
|
||||
<value type="bool" key="RunConfiguration.UseMultiProcess">false</value>
|
||||
<value type="bool" key="RunConfiguration.UseQmlDebugger">false</value>
|
||||
<value type="bool" key="RunConfiguration.UseQmlDebuggerAuto">true</value>
|
||||
<value type="QString" key="RunConfiguration.WorkingDirectory"></value>
|
||||
<value type="QString" key="RunConfiguration.WorkingDirectory.default"></value>
|
||||
</valuemap>
|
||||
<value type="int" key="ProjectExplorer.Target.RunConfigurationCount">1</value>
|
||||
</valuemap>
|
||||
</data>
|
||||
<data>
|
||||
<variable>ProjectExplorer.Project.TargetCount</variable>
|
||||
<value type="int">1</value>
|
||||
</data>
|
||||
<data>
|
||||
<variable>ProjectExplorer.Project.Updater.FileVersion</variable>
|
||||
<value type="int">22</value>
|
||||
</data>
|
||||
<data>
|
||||
<variable>Version</variable>
|
||||
<value type="int">22</value>
|
||||
</data>
|
||||
</qtcreator>
|
||||
@@ -1,11 +0,0 @@
|
||||
cmdlnopts.c
|
||||
cmdlnopts.h
|
||||
main.c
|
||||
parseargs.c
|
||||
parseargs.h
|
||||
socket.c
|
||||
socket.h
|
||||
term.c
|
||||
term.h
|
||||
usefull_macros.c
|
||||
usefull_macros.h
|
||||
@@ -1 +0,0 @@
|
||||
.
|
||||
6
Daemons/domedaemon-astrosib/domedaemon-astrosib.files
Normal file
6
Daemons/domedaemon-astrosib/domedaemon-astrosib.files
Normal file
@@ -0,0 +1,6 @@
|
||||
astrosib_proto.h
|
||||
dome.c
|
||||
dome.h
|
||||
main.c
|
||||
server.c
|
||||
server.h
|
||||
@@ -1,11 +1,10 @@
|
||||
/* geany_encoding=koi8-r
|
||||
* main.c
|
||||
/*
|
||||
* This file is part of the Snippets project.
|
||||
* Copyright 2024 Edward V. Emelianov <edward.emelianoff@gmail.com>.
|
||||
*
|
||||
* Copyright 2018 Edward V. Emelianov <eddy@sao.ru, edward.emelianoff@gmail.com>
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify
|
||||
* 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 2 of the License, or
|
||||
* 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,
|
||||
@@ -14,60 +13,84 @@
|
||||
* 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, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
* MA 02110-1301, USA.
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
#include "usefull_macros.h"
|
||||
|
||||
#include <signal.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <sys/wait.h> // wait
|
||||
#include <sys/prctl.h> //prctl
|
||||
#include <time.h>
|
||||
#include "cmdlnopts.h"
|
||||
#include "socket.h"
|
||||
#include <usefull_macros.h>
|
||||
|
||||
// dome @ /dev/ttyS2
|
||||
#include "server.h"
|
||||
|
||||
glob_pars *GP;
|
||||
static pid_t childpid = 0;
|
||||
// TCP socket port
|
||||
#define DEFAULT_PORT "55555"
|
||||
// baudrate - 9600
|
||||
#define DEFAULT_SERSPEED 9600
|
||||
// serial polling timeout - 100ms
|
||||
#define DEFAULT_SERTMOUT 100000
|
||||
|
||||
void signals(int signo){
|
||||
if(childpid){ // parent process
|
||||
restore_tty();
|
||||
putlog("exit with status %d", signo);
|
||||
}
|
||||
exit(signo);
|
||||
typedef struct{
|
||||
char *device; // serial device name
|
||||
char *node; // port to connect or UNIX socket name
|
||||
char *logfile; // logfile name
|
||||
int isunix; // open UNIX-socket instead of TCP
|
||||
int verbose; // verbose level
|
||||
} parameters;
|
||||
|
||||
static parameters G = {
|
||||
.node = DEFAULT_PORT,
|
||||
};
|
||||
static int help;
|
||||
|
||||
static sl_option_t cmdlnopts[] = {
|
||||
{"help", NO_ARGS, NULL, 'h', arg_int, APTR(&help), "show this help"},
|
||||
{"device", NEED_ARG, NULL, 'd', arg_string, APTR(&G.device), "serial device name"},
|
||||
{"node", NEED_ARG, NULL, 'n', arg_string, APTR(&G.node), "UNIX socket name or network port to connect (default: " DEFAULT_PORT ")"},
|
||||
{"logfile", NEED_ARG, NULL, 'l', arg_string, APTR(&G.logfile), "save logs to file"},
|
||||
{"unix", NO_ARGS, NULL, 'u', arg_int, APTR(&G.isunix), "open UNIX-socket instead of TCP"},
|
||||
{"verbose", NO_ARGS, NULL, 'v', arg_none, APTR(&G.verbose), "logging verbose level (each -v adds one)"},
|
||||
end_option
|
||||
};
|
||||
|
||||
void signals(int sig){
|
||||
if(sig){
|
||||
signal(sig, SIG_IGN);
|
||||
DBG("Get signal %d, quit.\n", sig);
|
||||
LOGERR("Exit with status %d", sig);
|
||||
}else LOGERR("Exit");
|
||||
exit(sig);
|
||||
}
|
||||
|
||||
int main(int argc, char **argv){
|
||||
initial_setup();
|
||||
signal(SIGTERM, signals); // kill (-15) - quit
|
||||
signal(SIGHUP, SIG_IGN); // hup - ignore
|
||||
signal(SIGINT, signals); // ctrl+C - quit
|
||||
signal(SIGQUIT, signals); // ctrl+\ - quit
|
||||
signal(SIGTSTP, SIG_IGN); // ignore ctrl+Z
|
||||
GP = parse_args(argc, argv);
|
||||
if(GP->terminal){
|
||||
if(!GP->device) ERRX(_("Point serial device name"));
|
||||
try_connect(GP->device);
|
||||
run_terminal();
|
||||
signals(0); // never reached!
|
||||
}
|
||||
if(GP->logfile)
|
||||
openlogfile(GP->logfile);
|
||||
#ifndef EBUG
|
||||
if(daemon(1, 0)){
|
||||
ERR("daemon()");
|
||||
}
|
||||
sl_init();
|
||||
sl_parseargs(&argc, &argv, cmdlnopts);
|
||||
if(help) sl_showhelp(-1, cmdlnopts);
|
||||
if(!G.node) ERRX("Point node");
|
||||
if(!G.device) ERRX("Point path to serial device");
|
||||
sl_loglevel_e lvl = G.verbose + LOGLEVEL_ERR;
|
||||
if(lvl >= LOGLEVEL_AMOUNT) lvl = LOGLEVEL_AMOUNT - 1;
|
||||
if(G.logfile) OPENLOG(G.logfile, lvl, 1);
|
||||
LOGMSG("Started");
|
||||
signal(SIGTERM, signals);
|
||||
signal(SIGINT, signals);
|
||||
signal(SIGQUIT, signals);
|
||||
signal(SIGTSTP, SIG_IGN);
|
||||
signal(SIGHUP, signals);
|
||||
#ifndef EBUG
|
||||
time_t lastd = 0;
|
||||
while(1){ // guard for dead processes
|
||||
childpid = fork();
|
||||
pid_t childpid = fork();
|
||||
if(childpid){
|
||||
DBG("Created child with PID %d\n", childpid);
|
||||
LOGMSG("Created child with PID %d\n", childpid);
|
||||
wait(NULL);
|
||||
time_t t = time(NULL);
|
||||
if(t - lastd > 600) // at least 10 minutes of work
|
||||
putlog("child %d died\n", childpid);
|
||||
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);
|
||||
@@ -76,14 +99,16 @@ int main(int argc, char **argv){
|
||||
break; // go out to normal functional
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
if(GP->device) try_connect(GP->device);
|
||||
if(!poll_device()){
|
||||
ERRX(_("No answer from device"));
|
||||
#endif
|
||||
sl_socktype_e type = (G.isunix) ? SOCKT_UNIX : SOCKT_NETLOCAL;
|
||||
sl_tty_t *serial = sl_tty_new(G.device, DEFAULT_SERSPEED, 4096);
|
||||
if(serial) serial = sl_tty_open(serial, 1);
|
||||
if(!serial){
|
||||
LOGERR("Can't open serial device %s", G.device);
|
||||
ERRX("Can't open serial device %s", G.device);
|
||||
}
|
||||
putlog("Child %d connected to %s", getpid(), GP->device);
|
||||
daemonize(GP->port);
|
||||
signals(0); // newer reached
|
||||
sl_tty_tmout(DEFAULT_SERTMOUT);
|
||||
server_run(type, G.node, serial);
|
||||
LOGERR("Unreacheable code reached!");
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -1,497 +0,0 @@
|
||||
/* geany_encoding=koi8-r
|
||||
* parseargs.c - parsing command line arguments & print help
|
||||
*
|
||||
* Copyright 2013 Edward V. Emelianoff <eddy@sao.ru>
|
||||
*
|
||||
* 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 2 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, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
* MA 02110-1301, USA.
|
||||
*/
|
||||
|
||||
#include <stdio.h> // printf
|
||||
#include <getopt.h> // getopt_long
|
||||
#include <stdlib.h> // calloc, exit, strtoll
|
||||
#include <assert.h> // assert
|
||||
#include <string.h> // strdup, strchr, strlen
|
||||
#include <strings.h>// strcasecmp
|
||||
#include <limits.h> // INT_MAX & so on
|
||||
#include <libintl.h>// gettext
|
||||
#include <ctype.h> // isalpha
|
||||
#include "parseargs.h"
|
||||
#include "usefull_macros.h"
|
||||
|
||||
char *helpstring = "%s\n";
|
||||
|
||||
/**
|
||||
* Change standard help header
|
||||
* MAY consist ONE "%s" for progname
|
||||
* @param str (i) - new format
|
||||
*/
|
||||
void change_helpstring(char *s){
|
||||
int pcount = 0, scount = 0;
|
||||
char *str = s;
|
||||
// check `helpstring` and set it to default in case of error
|
||||
for(; pcount < 2; str += 2){
|
||||
if(!(str = strchr(str, '%'))) break;
|
||||
if(str[1] != '%') pcount++; // increment '%' counter if it isn't "%%"
|
||||
else{
|
||||
str += 2; // pass next '%'
|
||||
continue;
|
||||
}
|
||||
if(str[1] == 's') scount++; // increment "%s" counter
|
||||
};
|
||||
if(pcount > 1 || pcount != scount){ // amount of pcount and/or scount wrong
|
||||
/// "îÅÐÒÁ×ÉÌØÎÙÊ ÆÏÒÍÁÔ ÓÔÒÏËÉ ÐÏÍÏÝÉ"
|
||||
ERRX(_("Wrong helpstring!"));
|
||||
}
|
||||
helpstring = s;
|
||||
}
|
||||
|
||||
/**
|
||||
* Carefull atoll/atoi
|
||||
* @param num (o) - returning value (or NULL if you wish only check number) - allocated by user
|
||||
* @param str (i) - string with number must not be NULL
|
||||
* @param t (i) - T_INT for integer or T_LLONG for long long (if argtype would be wided, may add more)
|
||||
* @return TRUE if conversion sone without errors, FALSE otherwise
|
||||
*/
|
||||
static bool myatoll(void *num, char *str, argtype t){
|
||||
long long tmp, *llptr;
|
||||
int *iptr;
|
||||
char *endptr;
|
||||
assert(str);
|
||||
assert(num);
|
||||
tmp = strtoll(str, &endptr, 0);
|
||||
if(endptr == str || *str == '\0' || *endptr != '\0')
|
||||
return FALSE;
|
||||
switch(t){
|
||||
case arg_longlong:
|
||||
llptr = (long long*) num;
|
||||
*llptr = tmp;
|
||||
break;
|
||||
case arg_int:
|
||||
default:
|
||||
if(tmp < INT_MIN || tmp > INT_MAX){
|
||||
/// "ãÅÌÏÅ ×ÎÅ ÄÏÐÕÓÔÉÍÏÇÏ ÄÉÁÐÁÚÏÎÁ"
|
||||
WARNX(_("Integer out of range"));
|
||||
return FALSE;
|
||||
}
|
||||
iptr = (int*)num;
|
||||
*iptr = (int)tmp;
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
// the same as myatoll but for double
|
||||
// There's no NAN & INF checking here (what if they would be needed?)
|
||||
static bool myatod(void *num, const char *str, argtype t){
|
||||
double tmp, *dptr;
|
||||
float *fptr;
|
||||
char *endptr;
|
||||
assert(str);
|
||||
tmp = strtod(str, &endptr);
|
||||
if(endptr == str || *str == '\0' || *endptr != '\0')
|
||||
return FALSE;
|
||||
switch(t){
|
||||
case arg_double:
|
||||
dptr = (double *) num;
|
||||
*dptr = tmp;
|
||||
break;
|
||||
case arg_float:
|
||||
default:
|
||||
fptr = (float *) num;
|
||||
*fptr = (float)tmp;
|
||||
break;
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get index of current option in array options
|
||||
* @param opt (i) - returning val of getopt_long
|
||||
* @param options (i) - array of options
|
||||
* @return index in array
|
||||
*/
|
||||
static int get_optind(int opt, myoption *options){
|
||||
int oind;
|
||||
myoption *opts = options;
|
||||
assert(opts);
|
||||
for(oind = 0; opts->name && opts->val != opt; oind++, opts++);
|
||||
if(!opts->name || opts->val != opt) // no such parameter
|
||||
showhelp(-1, options);
|
||||
return oind;
|
||||
}
|
||||
|
||||
/**
|
||||
* reallocate new value in array of multiple repeating arguments
|
||||
* @arg paptr - address of pointer to array (**void)
|
||||
* @arg type - its type (for realloc)
|
||||
* @return pointer to new (next) value
|
||||
*/
|
||||
void *get_aptr(void *paptr, argtype type){
|
||||
int i = 1;
|
||||
void **aptr = *((void***)paptr);
|
||||
if(aptr){ // there's something in array
|
||||
void **p = aptr;
|
||||
while(*p++) ++i;
|
||||
}
|
||||
size_t sz = 0;
|
||||
switch(type){
|
||||
default:
|
||||
case arg_none:
|
||||
/// "îÅ ÍÏÇÕ ÉÓÐÏÌØÚÏ×ÁÔØ ÎÅÓËÏÌØËÏ ÐÁÒÁÍÅÔÒÏ× ÂÅÚ ÁÒÇÕÍÅÎÔÏ×!"
|
||||
ERRX("Can't use multiple args with arg_none!");
|
||||
break;
|
||||
case arg_int:
|
||||
sz = sizeof(int);
|
||||
break;
|
||||
case arg_longlong:
|
||||
sz = sizeof(long long);
|
||||
break;
|
||||
case arg_double:
|
||||
sz = sizeof(double);
|
||||
break;
|
||||
case arg_float:
|
||||
sz = sizeof(float);
|
||||
break;
|
||||
case arg_string:
|
||||
sz = 0;
|
||||
break;
|
||||
/* case arg_function:
|
||||
sz = sizeof(argfn *);
|
||||
break;*/
|
||||
}
|
||||
aptr = realloc(aptr, (i + 1) * sizeof(void*));
|
||||
*((void***)paptr) = aptr;
|
||||
aptr[i] = NULL;
|
||||
if(sz){
|
||||
aptr[i - 1] = malloc(sz);
|
||||
}else
|
||||
aptr[i - 1] = &aptr[i - 1];
|
||||
return aptr[i - 1];
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Parse command line arguments
|
||||
* ! If arg is string, then value will be strdup'ed!
|
||||
*
|
||||
* @param argc (io) - address of argc of main(), return value of argc stay after `getopt`
|
||||
* @param argv (io) - address of argv of main(), return pointer to argv stay after `getopt`
|
||||
* BE CAREFUL! if you wanna use full argc & argv, save their original values before
|
||||
* calling this function
|
||||
* @param options (i) - array of `myoption` for arguments parcing
|
||||
*
|
||||
* @exit: in case of error this function show help & make `exit(-1)`
|
||||
*/
|
||||
void parseargs(int *argc, char ***argv, myoption *options){
|
||||
char *short_options, *soptr;
|
||||
struct option *long_options, *loptr;
|
||||
size_t optsize, i;
|
||||
myoption *opts = options;
|
||||
// check whether there is at least one options
|
||||
assert(opts);
|
||||
assert(opts[0].name);
|
||||
// first we count how much values are in opts
|
||||
for(optsize = 0; opts->name; optsize++, opts++);
|
||||
// now we can allocate memory
|
||||
short_options = calloc(optsize * 3 + 1, 1); // multiply by three for '::' in case of args in opts
|
||||
long_options = calloc(optsize + 1, sizeof(struct option));
|
||||
opts = options; loptr = long_options; soptr = short_options;
|
||||
// in debug mode check the parameters are not repeated
|
||||
#ifdef EBUG
|
||||
char **longlist = MALLOC(char*, optsize);
|
||||
char *shortlist = MALLOC(char, optsize);
|
||||
#endif
|
||||
// fill short/long parameters and make a simple checking
|
||||
for(i = 0; i < optsize; i++, loptr++, opts++){
|
||||
// check
|
||||
assert(opts->name); // check name
|
||||
#ifdef EBUG
|
||||
longlist[i] = strdup(opts->name);
|
||||
#endif
|
||||
if(opts->has_arg){
|
||||
assert(opts->type != arg_none); // check error with arg type
|
||||
assert(opts->argptr); // check pointer
|
||||
}
|
||||
if(opts->type != arg_none) // if there is a flag without arg, check its pointer
|
||||
assert(opts->argptr);
|
||||
// fill long_options
|
||||
// don't do memcmp: what if there would be different alignment?
|
||||
loptr->name = opts->name;
|
||||
loptr->has_arg = (opts->has_arg < MULT_PAR) ? opts->has_arg : 1;
|
||||
loptr->flag = opts->flag;
|
||||
loptr->val = opts->val;
|
||||
// fill short options if they are:
|
||||
if(!opts->flag && opts->val){
|
||||
#ifdef EBUG
|
||||
shortlist[i] = (char) opts->val;
|
||||
#endif
|
||||
*soptr++ = opts->val;
|
||||
if(loptr->has_arg) // add ':' if option has required argument
|
||||
*soptr++ = ':';
|
||||
if(loptr->has_arg == 2) // add '::' if option has optional argument
|
||||
*soptr++ = ':';
|
||||
}
|
||||
}
|
||||
// sort all lists & check for repeating
|
||||
#ifdef EBUG
|
||||
int cmpstringp(const void *p1, const void *p2){
|
||||
return strcmp(* (char * const *) p1, * (char * const *) p2);
|
||||
}
|
||||
int cmpcharp(const void *p1, const void *p2){
|
||||
return (int)(*(char * const)p1 - *(char *const)p2);
|
||||
}
|
||||
qsort(longlist, optsize, sizeof(char *), cmpstringp);
|
||||
qsort(shortlist,optsize, sizeof(char), cmpcharp);
|
||||
char *prevl = longlist[0], prevshrt = shortlist[0];
|
||||
for(i = 1; i < optsize; ++i){
|
||||
if(longlist[i]){
|
||||
if(prevl){
|
||||
if(strcmp(prevl, longlist[i]) == 0) ERRX("double long arguments: --%s", prevl);
|
||||
}
|
||||
prevl = longlist[i];
|
||||
}
|
||||
if(shortlist[i]){
|
||||
if(prevshrt){
|
||||
if(prevshrt == shortlist[i]) ERRX("double short arguments: -%c", prevshrt);
|
||||
}
|
||||
prevshrt = shortlist[i];
|
||||
}
|
||||
}
|
||||
#endif
|
||||
// now we have both long_options & short_options and can parse `getopt_long`
|
||||
while(1){
|
||||
int opt;
|
||||
int oindex = 0, optind = 0; // oindex - number of option in argv, optind - number in options[]
|
||||
if((opt = getopt_long(*argc, *argv, short_options, long_options, &oindex)) == -1) break;
|
||||
if(opt == '?'){
|
||||
opt = optopt;
|
||||
optind = get_optind(opt, options);
|
||||
if(options[optind].has_arg == NEED_ARG || options[optind].has_arg == MULT_PAR)
|
||||
showhelp(optind, options); // need argument
|
||||
}
|
||||
else{
|
||||
if(opt == 0 || oindex > 0) optind = oindex;
|
||||
else optind = get_optind(opt, options);
|
||||
}
|
||||
opts = &options[optind];
|
||||
// if(opt == 0 && opts->has_arg == NO_ARGS) continue; // only long option changing integer flag
|
||||
// now check option
|
||||
if(opts->has_arg == NEED_ARG || opts->has_arg == MULT_PAR)
|
||||
if(!optarg) showhelp(optind, options); // need argument
|
||||
void *aptr;
|
||||
if(opts->has_arg == MULT_PAR){
|
||||
aptr = get_aptr(opts->argptr, opts->type);
|
||||
}else
|
||||
aptr = opts->argptr;
|
||||
bool result = TRUE;
|
||||
// even if there is no argument, but argptr != NULL, think that optarg = "1"
|
||||
if(!optarg) optarg = "1";
|
||||
switch(opts->type){
|
||||
default:
|
||||
case arg_none:
|
||||
if(opts->argptr) *((int*)aptr) += 1; // increment value
|
||||
break;
|
||||
case arg_int:
|
||||
result = myatoll(aptr, optarg, arg_int);
|
||||
break;
|
||||
case arg_longlong:
|
||||
result = myatoll(aptr, optarg, arg_longlong);
|
||||
break;
|
||||
case arg_double:
|
||||
result = myatod(aptr, optarg, arg_double);
|
||||
break;
|
||||
case arg_float:
|
||||
result = myatod(aptr, optarg, arg_float);
|
||||
break;
|
||||
case arg_string:
|
||||
result = (*((void**)aptr) = (void*)strdup(optarg));
|
||||
break;
|
||||
case arg_function:
|
||||
result = ((argfn)aptr)(optarg);
|
||||
break;
|
||||
}
|
||||
if(!result){
|
||||
showhelp(optind, options);
|
||||
}
|
||||
}
|
||||
*argc -= optind;
|
||||
*argv += optind;
|
||||
}
|
||||
|
||||
/**
|
||||
* compare function for qsort
|
||||
* first - sort by short options; second - sort arguments without sort opts (by long options)
|
||||
*/
|
||||
static int argsort(const void *a1, const void *a2){
|
||||
const myoption *o1 = (myoption*)a1, *o2 = (myoption*)a2;
|
||||
const char *l1 = o1->name, *l2 = o2->name;
|
||||
int s1 = o1->val, s2 = o2->val;
|
||||
int *f1 = o1->flag, *f2 = o2->flag;
|
||||
// check if both options has short arg
|
||||
if(f1 == NULL && f2 == NULL && s1 && s2){ // both have short arg
|
||||
return (s1 - s2);
|
||||
}else if((f1 != NULL || !s1) && (f2 != NULL || !s2)){ // both don't have short arg - sort by long
|
||||
return strcmp(l1, l2);
|
||||
}else{ // only one have short arg -- return it
|
||||
if(f2 || !s2) return -1; // a1 have short - it is 'lesser'
|
||||
else return 1;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Show help information based on myoption->help values
|
||||
* @param oindex (i) - if non-negative, show only help by myoption[oindex].help
|
||||
* @param options (i) - array of `myoption`
|
||||
*
|
||||
* @exit: run `exit(-1)` !!!
|
||||
*/
|
||||
void showhelp(int oindex, myoption *options){
|
||||
int max_opt_len = 0; // max len of options substring - for right indentation
|
||||
const int bufsz = 255;
|
||||
char buf[bufsz+1];
|
||||
myoption *opts = options;
|
||||
assert(opts);
|
||||
assert(opts[0].name); // check whether there is at least one options
|
||||
if(oindex > -1){ // print only one message
|
||||
opts = &options[oindex];
|
||||
printf(" ");
|
||||
if(!opts->flag && isalpha(opts->val)) printf("-%c, ", opts->val);
|
||||
printf("--%s", opts->name);
|
||||
if(opts->has_arg == 1) printf("=arg");
|
||||
else if(opts->has_arg == 2) printf("[=arg]");
|
||||
printf(" %s\n", _(opts->help));
|
||||
exit(-1);
|
||||
}
|
||||
// header, by default is just "progname\n"
|
||||
printf("\n");
|
||||
if(strstr(helpstring, "%s")) // print progname
|
||||
printf(helpstring, __progname);
|
||||
else // only text
|
||||
printf("%s", helpstring);
|
||||
printf("\n");
|
||||
// count max_opt_len
|
||||
do{
|
||||
int L = strlen(opts->name);
|
||||
if(max_opt_len < L) max_opt_len = L;
|
||||
}while((++opts)->name);
|
||||
max_opt_len += 14; // format: '-S , --long[=arg]' - get addition 13 symbols
|
||||
opts = options;
|
||||
// count amount of options
|
||||
int N; for(N = 0; opts->name; ++N, ++opts);
|
||||
if(N == 0) exit(-2);
|
||||
// Now print all help (sorted)
|
||||
opts = options;
|
||||
qsort(opts, N, sizeof(myoption), argsort);
|
||||
do{
|
||||
int p = sprintf(buf, " "); // a little indent
|
||||
if(!opts->flag && opts->val) // .val is short argument
|
||||
p += snprintf(buf+p, bufsz-p, "-%c, ", opts->val);
|
||||
p += snprintf(buf+p, bufsz-p, "--%s", opts->name);
|
||||
if(opts->has_arg == 1) // required argument
|
||||
p += snprintf(buf+p, bufsz-p, "=arg");
|
||||
else if(opts->has_arg == 2) // optional argument
|
||||
p += snprintf(buf+p, bufsz-p, "[=arg]");
|
||||
assert(p < max_opt_len); // there would be magic if p >= max_opt_len
|
||||
printf("%-*s%s\n", max_opt_len+1, buf, _(opts->help)); // write options & at least 2 spaces after
|
||||
++opts;
|
||||
}while(--N);
|
||||
printf("\n\n");
|
||||
exit(-1);
|
||||
}
|
||||
|
||||
/**
|
||||
* get suboptions from parameter string
|
||||
* @param str - parameter string
|
||||
* @param opt - pointer to suboptions structure
|
||||
* @return TRUE if all OK
|
||||
*/
|
||||
bool get_suboption(char *str, mysuboption *opt){
|
||||
int findsubopt(char *par, mysuboption *so){
|
||||
int idx = 0;
|
||||
if(!par) return -1;
|
||||
while(so[idx].name){
|
||||
if(strcasecmp(par, so[idx].name) == 0) return idx;
|
||||
++idx;
|
||||
}
|
||||
return -1; // badarg
|
||||
}
|
||||
bool opt_setarg(mysuboption *so, int idx, char *val){
|
||||
mysuboption *soptr = &so[idx];
|
||||
bool result = FALSE;
|
||||
void *aptr = soptr->argptr;
|
||||
switch(soptr->type){
|
||||
default:
|
||||
case arg_none:
|
||||
if(soptr->argptr) *((int*)aptr) += 1; // increment value
|
||||
result = TRUE;
|
||||
break;
|
||||
case arg_int:
|
||||
result = myatoll(aptr, val, arg_int);
|
||||
break;
|
||||
case arg_longlong:
|
||||
result = myatoll(aptr, val, arg_longlong);
|
||||
break;
|
||||
case arg_double:
|
||||
result = myatod(aptr, val, arg_double);
|
||||
break;
|
||||
case arg_float:
|
||||
result = myatod(aptr, val, arg_float);
|
||||
break;
|
||||
case arg_string:
|
||||
result = (*((void**)aptr) = (void*)strdup(val));
|
||||
break;
|
||||
case arg_function:
|
||||
result = ((argfn)aptr)(val);
|
||||
break;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
char *tok;
|
||||
bool ret = FALSE;
|
||||
char *tmpbuf;
|
||||
tok = strtok_r(str, ":,", &tmpbuf);
|
||||
do{
|
||||
char *val = strchr(tok, '=');
|
||||
int noarg = 0;
|
||||
if(val == NULL){ // no args
|
||||
val = "1";
|
||||
noarg = 1;
|
||||
}else{
|
||||
*val++ = '\0';
|
||||
if(!*val || *val == ':' || *val == ','){ // no argument - delimeter after =
|
||||
val = "1"; noarg = 1;
|
||||
}
|
||||
}
|
||||
int idx = findsubopt(tok, opt);
|
||||
if(idx < 0){
|
||||
/// "îÅÐÒÁ×ÉÌØÎÙÊ ÐÁÒÁÍÅÔÒ: %s"
|
||||
WARNX(_("Wrong parameter: %s"), tok);
|
||||
goto returning;
|
||||
}
|
||||
if(noarg && opt[idx].has_arg == NEED_ARG){
|
||||
/// "%s: ÎÅÏÂÈÏÄÉÍ ÁÒÇÕÍÅÎÔ!"
|
||||
WARNX(_("%s: argument needed!"), tok);
|
||||
goto returning;
|
||||
}
|
||||
if(!opt_setarg(opt, idx, val)){
|
||||
/// "îÅÐÒÁ×ÉÌØÎÙÊ ÁÒÇÕÍÅÎÔ \"%s\" ÐÁÒÁÍÅÔÒÁ \"%s\""
|
||||
WARNX(_("Wrong argument \"%s\" of parameter \"%s\""), val, tok);
|
||||
goto returning;
|
||||
}
|
||||
}while((tok = strtok_r(NULL, ":,", &tmpbuf)));
|
||||
ret = TRUE;
|
||||
returning:
|
||||
return ret;
|
||||
}
|
||||
@@ -1,124 +0,0 @@
|
||||
/* geany_encoding=koi8-r
|
||||
* parseargs.h - headers for parsing command line arguments
|
||||
*
|
||||
* Copyright 2013 Edward V. Emelianoff <eddy@sao.ru>
|
||||
*
|
||||
* 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 2 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, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
* MA 02110-1301, USA.
|
||||
*/
|
||||
#pragma once
|
||||
#ifndef __PARSEARGS_H__
|
||||
#define __PARSEARGS_H__
|
||||
|
||||
#include <stdbool.h>// bool
|
||||
#include <stdlib.h>
|
||||
|
||||
#ifndef TRUE
|
||||
#define TRUE true
|
||||
#endif
|
||||
|
||||
#ifndef FALSE
|
||||
#define FALSE false
|
||||
#endif
|
||||
|
||||
// macro for argptr
|
||||
#define APTR(x) ((void*)x)
|
||||
|
||||
// if argptr is a function:
|
||||
typedef bool(*argfn)(void *arg);
|
||||
|
||||
/*
|
||||
* type of getopt's argument
|
||||
* WARNING!
|
||||
* My function change value of flags by pointer, so if you want to use another type
|
||||
* make a latter conversion, example:
|
||||
* char charg;
|
||||
* int iarg;
|
||||
* myoption opts[] = {
|
||||
* {"value", 1, NULL, 'v', arg_int, &iarg, "char val"}, ..., end_option};
|
||||
* ..(parse args)..
|
||||
* charg = (char) iarg;
|
||||
*/
|
||||
typedef enum {
|
||||
arg_none = 0, // no arg
|
||||
arg_int, // integer
|
||||
arg_longlong, // long long
|
||||
arg_double, // double
|
||||
arg_float, // float
|
||||
arg_string, // char *
|
||||
arg_function // parse_args will run function `bool (*fn)(char *optarg, int N)`
|
||||
} argtype;
|
||||
|
||||
/*
|
||||
* Structure for getopt_long & help
|
||||
* BE CAREFUL: .argptr is pointer to data or pointer to function,
|
||||
* conversion depends on .type
|
||||
*
|
||||
* ATTENTION: string `help` prints through macro PRNT(), bu default it is gettext,
|
||||
* but you can redefine it before `#include "parseargs.h"`
|
||||
*
|
||||
* if arg is string, then value wil be strdup'ed like that:
|
||||
* char *str;
|
||||
* myoption opts[] = {{"string", 1, NULL, 's', arg_string, &str, "string val"}, ..., end_option};
|
||||
* *(opts[1].str) = strdup(optarg);
|
||||
* in other cases argptr should be address of some variable (or pointer to allocated memory)
|
||||
*
|
||||
* NON-NULL argptr should be written inside macro APTR(argptr) or directly: (void*)argptr
|
||||
*
|
||||
* !!!LAST VALUE OF ARRAY SHOULD BE `end_option` or ZEROS !!!
|
||||
*
|
||||
*/
|
||||
typedef enum{
|
||||
NO_ARGS = 0, // first three are the same as in getopt_long
|
||||
NEED_ARG = 1,
|
||||
OPT_ARG = 2,
|
||||
MULT_PAR
|
||||
} hasarg;
|
||||
|
||||
typedef struct{
|
||||
// these are from struct option:
|
||||
const char *name; // long option's name
|
||||
hasarg has_arg; // 0 - no args, 1 - nesessary arg, 2 - optionally arg, 4 - need arg & key can repeat (args are stored in null-terminated array)
|
||||
int *flag; // NULL to return val, pointer to int - to set its value of val (function returns 0)
|
||||
int val; // short opt name (if flag == NULL) or flag's value
|
||||
// and these are mine:
|
||||
argtype type; // type of argument
|
||||
void *argptr; // pointer to variable to assign optarg value or function `bool (*fn)(char *optarg, int N)`
|
||||
const char *help; // help string which would be shown in function `showhelp` or NULL
|
||||
} myoption;
|
||||
|
||||
/*
|
||||
* Suboptions structure, almost the same like myoption
|
||||
* used in parse_subopts()
|
||||
*/
|
||||
typedef struct{
|
||||
const char *name;
|
||||
hasarg has_arg;
|
||||
argtype type;
|
||||
void *argptr;
|
||||
} mysuboption;
|
||||
|
||||
// last string of array (all zeros)
|
||||
#define end_option {0,0,0,0,0,0,0}
|
||||
#define end_suboption {0,0,0,0}
|
||||
|
||||
extern const char *__progname;
|
||||
|
||||
void showhelp(int oindex, myoption *options);
|
||||
void parseargs(int *argc, char ***argv, myoption *options);
|
||||
void change_helpstring(char *s);
|
||||
bool get_suboption(char *str, mysuboption *opt);
|
||||
|
||||
#endif // __PARSEARGS_H__
|
||||
166
Daemons/domedaemon-astrosib/server.c
Normal file
166
Daemons/domedaemon-astrosib/server.c
Normal file
@@ -0,0 +1,166 @@
|
||||
/*
|
||||
* This file is part of the Snippets project.
|
||||
* Copyright 2024 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 <inttypes.h>
|
||||
#include <pthread.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <sys/socket.h>
|
||||
#include <usefull_macros.h>
|
||||
|
||||
#include "dome.h"
|
||||
|
||||
// max age time of last status - 30s
|
||||
#define STATUS_MAX_AGE (30.)
|
||||
|
||||
// commands
|
||||
#define CMD_UNIXT "unixt"
|
||||
#define CMD_STATUS "status"
|
||||
#define CMD_STATUST "statust"
|
||||
#define CMD_RELAY "relay"
|
||||
|
||||
// main socket
|
||||
static sl_sock_t *s = NULL;
|
||||
|
||||
/////// handlers
|
||||
// unixt - send to ALL clients
|
||||
static sl_sock_hresult_e dtimeh(sl_sock_t *c, _U_ sl_sock_hitem_t *item, _U_ const char *req){
|
||||
char buf[32];
|
||||
snprintf(buf, 31, "%s=%.2f\n", item->key, sl_dtime());
|
||||
sl_sock_sendstrmessage(c, buf);
|
||||
return RESULT_SILENCE;
|
||||
}
|
||||
// status - get current dome status in old format (first four numbers)
|
||||
static sl_sock_hresult_e statush(sl_sock_t *c, _U_ sl_sock_hitem_t *item, _U_ const char *req){
|
||||
char buf[128];
|
||||
dome_status_t dome_status;
|
||||
double lastt = get_dome_status(&dome_status);
|
||||
if(sl_dtime() - lastt > STATUS_MAX_AGE) return RESULT_FAIL;
|
||||
snprintf(buf, 127, "%s=%d,%d,%d,%d\n", item->key, dome_status.coverstate[0],
|
||||
dome_status.coverstate[1], dome_status.encoder[0], dome_status.encoder[1]);
|
||||
sl_sock_sendstrmessage(c, buf);
|
||||
return RESULT_SILENCE;
|
||||
}
|
||||
static const char *textst(int coverstate){
|
||||
switch(coverstate){
|
||||
case COVER_INTERMEDIATE: return "intermediate";
|
||||
case COVER_OPENED: return "opened";
|
||||
case COVER_CLOSED: return "closed";
|
||||
default: return "undefined";
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
// statust - text format status
|
||||
static sl_sock_hresult_e statusth(sl_sock_t *c, _U_ sl_sock_hitem_t *item, _U_ const char *req){
|
||||
char buf[BUFSIZ];
|
||||
dome_status_t dome_status;
|
||||
double lastt = get_dome_status(&dome_status);
|
||||
if(sl_dtime() - lastt > STATUS_MAX_AGE) return RESULT_FAIL;
|
||||
snprintf(buf, 127, "cover1=%s\ncover2=%s\nangle1=%d\nangle2=%d\nrelay1=%d\nrelay2=%d\nrelay3=%d\nreqtime=%.9f\n",
|
||||
textst(dome_status.coverstate[0]), textst(dome_status.coverstate[1]),
|
||||
dome_status.encoder[0], dome_status.encoder[1],
|
||||
dome_status.relay[0], dome_status.relay[1], dome_status.relay[2],
|
||||
lastt);
|
||||
sl_sock_sendstrmessage(c, buf);
|
||||
return RESULT_SILENCE;
|
||||
}
|
||||
// relay on/off
|
||||
static sl_sock_hresult_e relays(int Nrelay, int Stat){
|
||||
if(Nrelay < NRELAY_MIN|| Nrelay > NRELAY_MAX) return RESULT_BADKEY;
|
||||
dome_cmd_t cmd = Stat ? DOME_RELAY_ON : DOME_RELAY_OFF;
|
||||
if(DOME_S_ERROR == dome_poll(cmd, Nrelay)) return RESULT_FAIL;
|
||||
return RESULT_OK;
|
||||
}
|
||||
static sl_sock_hresult_e relay(sl_sock_t *c, sl_sock_hitem_t *item, const char *req){
|
||||
char buf[128];
|
||||
int N = item->key[sizeof(CMD_RELAY) - 1] - '0';
|
||||
if(!req || !*req){ // getter
|
||||
dome_status_t dome_status;
|
||||
double lastt = get_dome_status(&dome_status);
|
||||
if(sl_dtime() - lastt > STATUS_MAX_AGE) return RESULT_FAIL;
|
||||
snprintf(buf, 127, "%s=%d\n", item->key, dome_status.relay[N-1]);
|
||||
sl_sock_sendstrmessage(c, buf);
|
||||
return RESULT_SILENCE;
|
||||
}
|
||||
int Stat = *req - '0';
|
||||
return relays(N, Stat);
|
||||
}
|
||||
|
||||
// and all handlers collection
|
||||
static sl_sock_hitem_t handlers[] = {
|
||||
{dtimeh, CMD_UNIXT, "get server's UNIX time", NULL},
|
||||
{statush, CMD_STATUS, "get dome's status in old format", NULL},
|
||||
{statusth, CMD_STATUST, "get dome's status in full text format", NULL},
|
||||
{relay, CMD_RELAY "1", "turn on/off (=1/0) relay 1", NULL},
|
||||
{relay, CMD_RELAY "2", "turn on/off (=1/0) relay 2", NULL},
|
||||
{relay, CMD_RELAY "3", "turn on/off (=1/0) relay 3", NULL},
|
||||
{NULL, NULL, NULL, NULL}
|
||||
};
|
||||
|
||||
// Too much clients handler
|
||||
static void toomuch(int fd){
|
||||
const char m[] = "Try later: too much clients connected\n";
|
||||
send(fd, m, sizeof(m)-1, MSG_NOSIGNAL);
|
||||
shutdown(fd, SHUT_WR);
|
||||
DBG("shutdown, wait");
|
||||
double t0 = sl_dtime();
|
||||
uint8_t buf[8];
|
||||
while(sl_dtime() - t0 < 11.){
|
||||
if(sl_canread(fd)){
|
||||
ssize_t got = read(fd, buf, 8);
|
||||
DBG("Got=%zd", got);
|
||||
if(got < 1) break;
|
||||
}
|
||||
}
|
||||
DBG("Disc after %gs", sl_dtime() - t0);
|
||||
LOGWARN("Client fd=%d tried to connect after MAX reached", fd);
|
||||
}
|
||||
// new connections handler
|
||||
static void 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);
|
||||
}
|
||||
// disconnected handler
|
||||
static void disconnected(sl_sock_t *c){
|
||||
if(c->type == SOCKT_UNIX) LOGMSG("Disconnected client fd=%d", c->fd);
|
||||
else LOGMSG("Disconnected client fd=%d, IP=%s", c->fd, c->IP);
|
||||
}
|
||||
|
||||
void server_run(sl_socktype_e type, const char *node, sl_tty_t *serial){
|
||||
if(!node || !serial){
|
||||
LOGERR("server_run(): wrong parameters");
|
||||
ERRX("server_run(): wrong parameters");
|
||||
}
|
||||
dome_serialdev(serial);
|
||||
sl_sock_changemaxclients(5);
|
||||
sl_sock_maxclhandler(toomuch);
|
||||
sl_sock_connhandler(connected);
|
||||
sl_sock_dischandler(disconnected);
|
||||
s = sl_sock_run_server(type, node, -1, handlers);
|
||||
if(!s) ERRX("Can't create socket and/or run threads");
|
||||
while(s && s->connected){
|
||||
if(!s->rthread){
|
||||
LOGERR("Server handlers thread is dead");
|
||||
break;
|
||||
}
|
||||
// finite state machine polling
|
||||
dome_poll(DOME_POLL, 0);
|
||||
}
|
||||
sl_sock_delete(&s);
|
||||
ERRX("Server handlers thread is dead");
|
||||
}
|
||||
23
Daemons/domedaemon-astrosib/server.h
Normal file
23
Daemons/domedaemon-astrosib/server.h
Normal file
@@ -0,0 +1,23 @@
|
||||
/*
|
||||
* This file is part of the domedaemon-astrosib project.
|
||||
* Copyright 2025 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
|
||||
|
||||
#include <usefull_macros.h>
|
||||
|
||||
void server_run(sl_socktype_e type, const char *node, sl_tty_t *serial);
|
||||
@@ -1,336 +0,0 @@
|
||||
/*
|
||||
* geany_encoding=koi8-r
|
||||
* socket.c - socket IO
|
||||
*
|
||||
* Copyright 2018 Edward V. Emelianov <eddy@sao.ru, 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 2 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, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
* MA 02110-1301, USA.
|
||||
*
|
||||
*/
|
||||
#include "usefull_macros.h"
|
||||
#include "socket.h"
|
||||
#include "term.h"
|
||||
#include <netdb.h> // addrinfo
|
||||
#include <arpa/inet.h> // inet_ntop
|
||||
#include <pthread.h>
|
||||
#include <limits.h> // INT_xxx
|
||||
#include <signal.h> // pthread_kill
|
||||
#include <unistd.h> // daemon
|
||||
#include <sys/syscall.h> // syscall
|
||||
|
||||
#include "cmdlnopts.h" // glob_pars
|
||||
|
||||
#define BUFLEN (10240)
|
||||
// Max amount of connections
|
||||
#define BACKLOG (30)
|
||||
|
||||
extern glob_pars *GP;
|
||||
|
||||
static char *status; // global variable with device status
|
||||
|
||||
typedef enum{
|
||||
CMD_OPEN,
|
||||
CMD_CLOSE,
|
||||
CMD_STOP,
|
||||
CMD_NONE
|
||||
} commands;
|
||||
|
||||
static commands cmd = CMD_NONE;
|
||||
|
||||
/*
|
||||
* Define global data buffers here
|
||||
*/
|
||||
|
||||
/**************** COMMON FUNCTIONS ****************/
|
||||
/**
|
||||
* wait for answer from socket
|
||||
* @param sock - socket fd
|
||||
* @return 0 in case of error or timeout, 1 in case of socket ready
|
||||
*/
|
||||
static int waittoread(int sock){
|
||||
fd_set fds;
|
||||
struct timeval timeout;
|
||||
int rc;
|
||||
timeout.tv_sec = 1; // wait not more than 1 second
|
||||
timeout.tv_usec = 0;
|
||||
FD_ZERO(&fds);
|
||||
FD_SET(sock, &fds);
|
||||
do{
|
||||
rc = select(sock+1, &fds, NULL, NULL, &timeout);
|
||||
if(rc < 0){
|
||||
if(errno != EINTR){
|
||||
WARN("select()");
|
||||
return 0;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}while(1);
|
||||
if(FD_ISSET(sock, &fds)) return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**************** SERVER FUNCTIONS ****************/
|
||||
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
|
||||
/**
|
||||
* Send data over socket
|
||||
* @param sock - socket fd
|
||||
* @param webquery - ==1 if this is web query
|
||||
* @param textbuf - zero-trailing buffer with data to send
|
||||
* @return 1 if all OK
|
||||
*/
|
||||
static int send_data(int sock, int webquery, const char *textbuf){
|
||||
ssize_t L, Len;
|
||||
char tbuf[BUFLEN];
|
||||
Len = strlen(textbuf);
|
||||
// OK buffer ready, prepare to send it
|
||||
if(webquery){
|
||||
L = snprintf((char*)tbuf, BUFLEN,
|
||||
"HTTP/2.0 200 OK\r\n"
|
||||
"Access-Control-Allow-Origin: *\r\n"
|
||||
"Access-Control-Allow-Methods: GET, POST\r\n"
|
||||
"Access-Control-Allow-Credentials: true\r\n"
|
||||
"Content-type: text/plain\r\nContent-Length: %zd\r\n\r\n", Len);
|
||||
if(L < 0){
|
||||
WARN("sprintf()");
|
||||
return 0;
|
||||
}
|
||||
if(L != write(sock, tbuf, L)){
|
||||
WARN("write");
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
// send data
|
||||
//DBG("send %zd bytes\nBUF: %s", Len, buf);
|
||||
if(Len != write(sock, textbuf, Len)){
|
||||
WARN("write()");
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
// search a first word after needle without spaces
|
||||
static char* stringscan(char *str, char *needle){
|
||||
char *a, *e;
|
||||
char *end = str + strlen(str);
|
||||
a = strstr(str, needle);
|
||||
if(!a) return NULL;
|
||||
a += strlen(needle);
|
||||
while (a < end && (*a == ' ' || *a == '\r' || *a == '\t' || *a == '\r')) a++;
|
||||
if(a >= end) return NULL;
|
||||
e = strchr(a, ' ');
|
||||
if(e) *e = 0;
|
||||
return a;
|
||||
}
|
||||
|
||||
static void *handle_socket(void *asock){
|
||||
FNAME();
|
||||
int sock = *((int*)asock);
|
||||
int webquery = 0; // whether query is web or regular
|
||||
char buff[BUFLEN];
|
||||
ssize_t rd;
|
||||
double t0 = dtime();
|
||||
while(dtime() - t0 < SOCKET_TIMEOUT){
|
||||
if(!waittoread(sock)){ // no data incoming
|
||||
continue;
|
||||
}
|
||||
if(!(rd = read(sock, buff, BUFLEN-1))){
|
||||
break;
|
||||
}
|
||||
DBG("Got %zd bytes", rd);
|
||||
if(rd < 0){ // error
|
||||
DBG("Nothing to read from fd %d (ret: %zd)", sock, rd);
|
||||
break;
|
||||
}
|
||||
// add trailing zero to be on the safe side
|
||||
buff[rd] = 0;
|
||||
// now we should check what do user want
|
||||
char *got, *found = buff;
|
||||
if((got = stringscan(buff, "GET")) || (got = stringscan(buff, "POST"))){ // web query
|
||||
webquery = 1;
|
||||
char *slash = strchr(got, '/');
|
||||
if(slash) found = slash + 1;
|
||||
// web query have format GET /some.resource
|
||||
}
|
||||
// here we can process user data
|
||||
DBG("user send: %s\nfound=%s", buff, found);
|
||||
if(GP->echo){
|
||||
if(!send_data(sock, webquery, found)){
|
||||
putlog("can't send data, some error occured");
|
||||
}
|
||||
}
|
||||
pthread_mutex_lock(&mutex);
|
||||
const char *proto = "Commands: close, open, status, stop";
|
||||
if(0 == strcmp(found, "open")){
|
||||
DBG("User asks 2 open");
|
||||
putlog("User asks to open");
|
||||
cmd = CMD_OPEN;
|
||||
send_data(sock, webquery, "OK\n");
|
||||
}else if(0 == strcmp(found, "close")){
|
||||
DBG("User asks 2 close");
|
||||
putlog("User asks to close");
|
||||
cmd = CMD_CLOSE;
|
||||
send_data(sock, webquery, "OK\n");
|
||||
}else if(0 == strcmp(found, "status")){
|
||||
DBG("User asks 4 status");
|
||||
send_data(sock, webquery, status);
|
||||
}else if(0 == strcmp(found, "stop")){
|
||||
DBG("User asks 2 stop");
|
||||
putlog("User asks to stop");
|
||||
cmd = CMD_STOP;
|
||||
send_data(sock, webquery, "OK\n");
|
||||
}else send_data(sock, webquery, proto);
|
||||
pthread_mutex_unlock(&mutex);
|
||||
break;
|
||||
}
|
||||
close(sock);
|
||||
pthread_exit(NULL);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
// main socket server
|
||||
static void *server(void *asock){
|
||||
putlog("server(): getpid: %d, pthread_self: %lu, tid: %lu",getpid(), pthread_self(), syscall(SYS_gettid));
|
||||
int sock = *((int*)asock);
|
||||
if(listen(sock, BACKLOG) == -1){
|
||||
putlog("listen() failed");
|
||||
WARN("listen");
|
||||
return NULL;
|
||||
}
|
||||
while(1){
|
||||
socklen_t size = sizeof(struct sockaddr_in);
|
||||
struct sockaddr_in their_addr;
|
||||
int newsock;
|
||||
if(!waittoread(sock)) continue;
|
||||
newsock = accept(sock, (struct sockaddr*)&their_addr, &size);
|
||||
if(newsock <= 0){
|
||||
putlog("accept() failed");
|
||||
WARN("accept()");
|
||||
continue;
|
||||
}
|
||||
struct sockaddr_in* pV4Addr = (struct sockaddr_in*)&their_addr;
|
||||
struct in_addr ipAddr = pV4Addr->sin_addr;
|
||||
char str[INET_ADDRSTRLEN];
|
||||
inet_ntop(AF_INET, &ipAddr, str, INET_ADDRSTRLEN);
|
||||
putlog("Got connection from %s", str);
|
||||
DBG("Got connection from %s\n", str);
|
||||
pthread_t handler_thread;
|
||||
if(pthread_create(&handler_thread, NULL, handle_socket, (void*) &newsock)){
|
||||
putlog("server(): pthread_create() failed");
|
||||
WARN("pthread_create()");
|
||||
}else{
|
||||
DBG("Thread created, detouch");
|
||||
pthread_detach(handler_thread); // don't care about thread state
|
||||
}
|
||||
}
|
||||
putlog("server(): UNREACHABLE CODE REACHED!");
|
||||
}
|
||||
|
||||
// data gathering & socket management
|
||||
static void daemon_(int sock){
|
||||
if(sock < 0) return;
|
||||
pthread_t sock_thread;
|
||||
if(pthread_create(&sock_thread, NULL, server, (void*) &sock)){
|
||||
putlog("daemon_(): pthread_create() failed");
|
||||
ERR("pthread_create()");
|
||||
}
|
||||
double tgot = 0.;
|
||||
do{
|
||||
if(pthread_kill(sock_thread, 0) == ESRCH){ // died
|
||||
WARNX("Sockets thread died");
|
||||
putlog("Sockets thread died");
|
||||
pthread_join(sock_thread, NULL);
|
||||
if(pthread_create(&sock_thread, NULL, server, (void*) &sock)){
|
||||
putlog("daemon_(): new pthread_create() failed");
|
||||
ERR("pthread_create()");
|
||||
}
|
||||
}
|
||||
usleep(1000); // sleep a little or thread's won't be able to lock mutex
|
||||
if(dtime() - tgot < T_INTERVAL) continue;
|
||||
tgot = dtime();
|
||||
// copy temporary buffers to main
|
||||
pthread_mutex_lock(&mutex);
|
||||
char *pollans = poll_device();
|
||||
if(pollans) status = pollans;
|
||||
if(cmd != CMD_NONE){
|
||||
switch (cmd){
|
||||
case CMD_OPEN:
|
||||
DBG("received command: open");
|
||||
if(write_cmd("OPENDOME")) cmd = CMD_NONE;
|
||||
break;
|
||||
case CMD_CLOSE:
|
||||
DBG("received command: close");
|
||||
if(write_cmd("CLOSEDOME")) cmd = CMD_NONE;
|
||||
break;
|
||||
case CMD_STOP:
|
||||
DBG("received command: stop");
|
||||
if(write_cmd("STOPDOME")) cmd = CMD_NONE;
|
||||
break;
|
||||
default:
|
||||
DBG("WTF?");
|
||||
}
|
||||
}
|
||||
pthread_mutex_unlock(&mutex);
|
||||
}while(1);
|
||||
putlog("daemon_(): UNREACHABLE CODE REACHED!");
|
||||
}
|
||||
|
||||
/**
|
||||
* Run daemon service
|
||||
*/
|
||||
void daemonize(char *port){
|
||||
FNAME();
|
||||
int sock = -1;
|
||||
struct addrinfo hints, *res, *p;
|
||||
memset(&hints, 0, sizeof(hints));
|
||||
hints.ai_family = AF_INET;
|
||||
hints.ai_socktype = SOCK_STREAM;
|
||||
hints.ai_flags = AI_PASSIVE;
|
||||
if(getaddrinfo(NULL, port, &hints, &res) != 0){
|
||||
ERR("getaddrinfo");
|
||||
}
|
||||
struct sockaddr_in *ia = (struct sockaddr_in*)res->ai_addr;
|
||||
char str[INET_ADDRSTRLEN];
|
||||
inet_ntop(AF_INET, &(ia->sin_addr), str, INET_ADDRSTRLEN);
|
||||
// loop through all the results and bind to the first we can
|
||||
for(p = res; p != NULL; p = p->ai_next){
|
||||
if((sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1){
|
||||
WARN("socket");
|
||||
continue;
|
||||
}
|
||||
int reuseaddr = 1;
|
||||
if(setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, sizeof(int)) == -1){
|
||||
ERR("setsockopt");
|
||||
}
|
||||
if(bind(sock, p->ai_addr, p->ai_addrlen) == -1){
|
||||
close(sock);
|
||||
WARN("bind");
|
||||
continue;
|
||||
}
|
||||
break; // if we get here, we have a successfull connection
|
||||
}
|
||||
if(p == NULL){
|
||||
putlog("failed to bind socket, exit");
|
||||
// looped off the end of the list with no successful bind
|
||||
ERRX("failed to bind socket");
|
||||
}
|
||||
freeaddrinfo(res);
|
||||
daemon_(sock);
|
||||
close(sock);
|
||||
putlog("socket closed, exit");
|
||||
signals(0);
|
||||
}
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
/*
|
||||
* geany_encoding=koi8-r
|
||||
* socket.h
|
||||
*
|
||||
* Copyright 2017 Edward V. Emelianov <eddy@sao.ru, 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 2 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, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
* MA 02110-1301, USA.
|
||||
*
|
||||
*/
|
||||
#pragma once
|
||||
#ifndef __SOCKET_H__
|
||||
#define __SOCKET_H__
|
||||
|
||||
// timeout for socket closing
|
||||
#define SOCKET_TIMEOUT (5.0)
|
||||
// time interval for data polling (seconds)
|
||||
#define T_INTERVAL (2.)
|
||||
|
||||
void daemonize(char *port);
|
||||
|
||||
#endif // __SOCKET_H__
|
||||
@@ -1,172 +0,0 @@
|
||||
/* geany_encoding=koi8-r
|
||||
* client.c - terminal parser
|
||||
*
|
||||
* Copyright 2018 Edward V. Emelianoff <eddy@sao.ru>
|
||||
*
|
||||
* 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 2 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, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
* MA 02110-1301, USA.
|
||||
*/
|
||||
#include "usefull_macros.h"
|
||||
#include "term.h"
|
||||
#include <strings.h> // strncasecmp
|
||||
#include <time.h> // time(NULL)
|
||||
#include <limits.h> // INT_MAX, INT_MIN
|
||||
|
||||
#define BUFLEN 1024
|
||||
|
||||
static char buf[BUFLEN];
|
||||
|
||||
/**
|
||||
* read strings from terminal (ending with '\n') with timeout
|
||||
* @return NULL if nothing was read or pointer to static buffer
|
||||
*/
|
||||
static char *read_string(){
|
||||
//FNAME();
|
||||
size_t r = 0, l;
|
||||
int LL = BUFLEN - 1;
|
||||
char *ptr = NULL;
|
||||
static char *optr = NULL;
|
||||
if(optr && *optr){
|
||||
ptr = optr;
|
||||
optr = strchr(optr, '\n');
|
||||
if(optr) ++optr;
|
||||
//DBG("got data, roll to next; ptr=%s\noptr=%s",ptr,optr);
|
||||
return ptr;
|
||||
}
|
||||
ptr = buf;
|
||||
double d0 = dtime();
|
||||
do{
|
||||
if((l = read_tty(ptr, LL))){
|
||||
r += l; LL -= l; ptr += l;
|
||||
//DBG("got: %s", buf);
|
||||
if(ptr[-1] == '\n') break;
|
||||
d0 = dtime();
|
||||
}
|
||||
}while(dtime() - d0 < WAIT_TMOUT && LL);
|
||||
if(r){
|
||||
buf[r] = 0;
|
||||
//DBG("r=%zd, got string: %s", r, buf);
|
||||
optr = strchr(buf, '\n');
|
||||
if(optr) ++optr;
|
||||
return buf;
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/**
|
||||
* Try to connect to `device` at BAUD_RATE speed
|
||||
* @return connection speed if success or 0
|
||||
*/
|
||||
void try_connect(char *device){
|
||||
if(!device) return;
|
||||
char tmpbuf[4096];
|
||||
fflush(stdout);
|
||||
tty_init(device);
|
||||
read_tty(tmpbuf, 4096); // clear rbuf
|
||||
putlog("Connected to %s", device);
|
||||
DBG("connected");
|
||||
}
|
||||
|
||||
static void con_sig(int rb){
|
||||
static char buf[256];
|
||||
static int L = 0;
|
||||
if(rb < 1) return;
|
||||
if(rb != '\n'){
|
||||
if(rb == 127 && L > 0){
|
||||
printf("\b \b");
|
||||
fflush(stdout);
|
||||
--L;
|
||||
}else{
|
||||
if(1 != write(1, &rb, 1))
|
||||
printf("%c", (char)rb);
|
||||
buf[L++] = (char)rb;
|
||||
if(L >= 250){
|
||||
printf("\nbuffer overrun!\n");
|
||||
L = 0;
|
||||
}
|
||||
}
|
||||
}else{
|
||||
//buf[L++] = '\r';
|
||||
//buf[L++] = '\n';
|
||||
buf[L] = 0;
|
||||
printf("\n\t\tSend %s\n", buf);
|
||||
write_tty(buf, L);
|
||||
L = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* run terminal emulation: send user's commands and show answers
|
||||
*/
|
||||
void run_terminal(){
|
||||
green(_("Work in terminal mode without echo\n"));
|
||||
int rb;
|
||||
char buf[BUFLEN];
|
||||
size_t l;
|
||||
setup_con();
|
||||
while(1){
|
||||
if((l = read_tty(buf, BUFLEN - 1))){
|
||||
buf[l] = 0;
|
||||
printf("%s", buf);
|
||||
}
|
||||
if((rb = read_console())){
|
||||
con_sig(rb);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* write command
|
||||
* @return answer or NULL if error occured (or no answer)
|
||||
*/
|
||||
char *write_cmd(const char *cmd){
|
||||
DBG("Write %s", cmd);
|
||||
char buf[128];
|
||||
snprintf(buf, 128, "%s\r", cmd);
|
||||
if(write_tty(buf, strlen(buf))) return NULL;
|
||||
double t0 = dtime();
|
||||
static char *ans;
|
||||
while(dtime() - t0 < T_POLLING_TMOUT){ // read answer
|
||||
if((ans = read_string())){ // parse new data
|
||||
DBG("got answer: %s", ans);
|
||||
return ans;
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/**
|
||||
* Poll serial port for new dataportion
|
||||
* @return: NULL if no data received, pointer to string if valid data received
|
||||
*/
|
||||
char *poll_device(){
|
||||
char *ans;
|
||||
const char *cmdstat = "STATUS";
|
||||
#define statlen (6)
|
||||
static char pollbuf[256];
|
||||
while(read_string()); // clear receiving buffer
|
||||
if(!(ans = write_cmd(cmdstat))) return NULL; // error writing command
|
||||
if(strncmp(ans, cmdstat, statlen)) return NULL; // wrong answer
|
||||
ans += statlen;
|
||||
char *comma = ans;
|
||||
for(int i = 0; i < 4; ++i){
|
||||
char *nxtcomma = strchr(comma, ',');
|
||||
if(!nxtcomma) return NULL; // wrong answer
|
||||
comma = nxtcomma + 1;
|
||||
}
|
||||
comma[-1] = 0;
|
||||
strncpy(pollbuf, ans, 255);
|
||||
return pollbuf;
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
/* geany_encoding=koi8-r
|
||||
* term.h
|
||||
*
|
||||
* Copyright 2018 Edward V. Emelianov <eddy@sao.ru, 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 2 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, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
* MA 02110-1301, USA.
|
||||
*/
|
||||
#pragma once
|
||||
#ifndef __TERM_H__
|
||||
#define __TERM_H__
|
||||
|
||||
#define FRAME_MAX_LENGTH (300)
|
||||
#define MAX_MEMORY_DUMP_SIZE (0x800 * 4)
|
||||
// Terminal timeout (seconds)
|
||||
#define WAIT_TMOUT (0.5)
|
||||
// Terminal polling timeout - 1 second
|
||||
#define T_POLLING_TMOUT (1.0)
|
||||
|
||||
void run_terminal();
|
||||
void try_connect(char *device);
|
||||
char *poll_device();
|
||||
char *write_cmd(const char *cmd);
|
||||
|
||||
#endif // __TERM_H__
|
||||
@@ -1,427 +0,0 @@
|
||||
/*
|
||||
* usefull_macros.h - a set of usefull functions: memory, color etc
|
||||
*
|
||||
* Copyright 2013 Edward V. Emelianoff <eddy@sao.ru>
|
||||
*
|
||||
* 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 2 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, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
* MA 02110-1301, USA.
|
||||
*/
|
||||
|
||||
#include "usefull_macros.h"
|
||||
#include <time.h>
|
||||
#include <linux/limits.h> // PATH_MAX
|
||||
|
||||
/**
|
||||
* function for different purposes that need to know time intervals
|
||||
* @return double value: time in seconds
|
||||
*/
|
||||
double dtime(){
|
||||
double t;
|
||||
struct timeval tv;
|
||||
gettimeofday(&tv, NULL);
|
||||
t = tv.tv_sec + ((double)tv.tv_usec)/1e6;
|
||||
return t;
|
||||
}
|
||||
|
||||
/******************************************************************************\
|
||||
* Coloured terminal
|
||||
\******************************************************************************/
|
||||
int globErr = 0; // errno for WARN/ERR
|
||||
|
||||
// pointers to coloured output printf
|
||||
int (*red)(const char *fmt, ...);
|
||||
int (*green)(const char *fmt, ...);
|
||||
int (*_WARN)(const char *fmt, ...);
|
||||
|
||||
/*
|
||||
* format red / green messages
|
||||
* name: r_pr_, g_pr_
|
||||
* @param fmt ... - printf-like format
|
||||
* @return number of printed symbols
|
||||
*/
|
||||
int r_pr_(const char *fmt, ...){
|
||||
va_list ar; int i;
|
||||
printf(RED);
|
||||
va_start(ar, fmt);
|
||||
i = vprintf(fmt, ar);
|
||||
va_end(ar);
|
||||
printf(OLDCOLOR);
|
||||
return i;
|
||||
}
|
||||
int g_pr_(const char *fmt, ...){
|
||||
va_list ar; int i;
|
||||
printf(GREEN);
|
||||
va_start(ar, fmt);
|
||||
i = vprintf(fmt, ar);
|
||||
va_end(ar);
|
||||
printf(OLDCOLOR);
|
||||
return i;
|
||||
}
|
||||
/*
|
||||
* print red error/warning messages (if output is a tty)
|
||||
* @param fmt ... - printf-like format
|
||||
* @return number of printed symbols
|
||||
*/
|
||||
int r_WARN(const char *fmt, ...){
|
||||
va_list ar; int i = 1;
|
||||
fprintf(stderr, RED);
|
||||
va_start(ar, fmt);
|
||||
if(globErr){
|
||||
errno = globErr;
|
||||
vwarn(fmt, ar);
|
||||
errno = 0;
|
||||
}else
|
||||
i = vfprintf(stderr, fmt, ar);
|
||||
va_end(ar);
|
||||
i++;
|
||||
fprintf(stderr, OLDCOLOR "\n");
|
||||
return i;
|
||||
}
|
||||
|
||||
static const char stars[] = "****************************************";
|
||||
/*
|
||||
* notty variants of coloured printf
|
||||
* name: s_WARN, r_pr_notty
|
||||
* @param fmt ... - printf-like format
|
||||
* @return number of printed symbols
|
||||
*/
|
||||
int s_WARN(const char *fmt, ...){
|
||||
va_list ar; int i;
|
||||
i = fprintf(stderr, "\n%s\n", stars);
|
||||
va_start(ar, fmt);
|
||||
if(globErr){
|
||||
errno = globErr;
|
||||
vwarn(fmt, ar);
|
||||
errno = 0;
|
||||
}else
|
||||
i = +vfprintf(stderr, fmt, ar);
|
||||
va_end(ar);
|
||||
i += fprintf(stderr, "\n%s\n", stars);
|
||||
i += fprintf(stderr, "\n");
|
||||
return i;
|
||||
}
|
||||
int r_pr_notty(const char *fmt, ...){
|
||||
va_list ar; int i;
|
||||
i = printf("\n%s\n", stars);
|
||||
va_start(ar, fmt);
|
||||
i += vprintf(fmt, ar);
|
||||
va_end(ar);
|
||||
i += printf("\n%s\n", stars);
|
||||
return i;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run this function in the beginning of main() to setup locale & coloured output
|
||||
*/
|
||||
void initial_setup(){
|
||||
// setup coloured output
|
||||
if(isatty(STDOUT_FILENO)){ // make color output in tty
|
||||
red = r_pr_; green = g_pr_;
|
||||
}else{ // no colors in case of pipe
|
||||
red = r_pr_notty; green = printf;
|
||||
}
|
||||
if(isatty(STDERR_FILENO)) _WARN = r_WARN;
|
||||
else _WARN = s_WARN;
|
||||
// Setup locale
|
||||
setlocale(LC_ALL, "");
|
||||
setlocale(LC_NUMERIC, "C");
|
||||
#if defined GETTEXT_PACKAGE && defined LOCALEDIR
|
||||
bindtextdomain(GETTEXT_PACKAGE, LOCALEDIR);
|
||||
textdomain(GETTEXT_PACKAGE);
|
||||
#endif
|
||||
}
|
||||
|
||||
/******************************************************************************\
|
||||
* Memory
|
||||
\******************************************************************************/
|
||||
/*
|
||||
* safe memory allocation for macro ALLOC
|
||||
* @param N - number of elements to allocate
|
||||
* @param S - size of single element (typically sizeof)
|
||||
* @return pointer to allocated memory area
|
||||
*/
|
||||
void *my_alloc(size_t N, size_t S){
|
||||
void *p = calloc(N, S);
|
||||
if(!p) ERR("malloc");
|
||||
//assert(p);
|
||||
return p;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mmap file to a memory area
|
||||
*
|
||||
* @param filename (i) - name of file to mmap
|
||||
* @return stuct with mmap'ed file or die
|
||||
*/
|
||||
mmapbuf *My_mmap(char *filename){
|
||||
int fd;
|
||||
char *ptr;
|
||||
size_t Mlen;
|
||||
struct stat statbuf;
|
||||
/// "îÅ ÚÁÄÁÎÏ ÉÍÑ ÆÁÊÌÁ!"
|
||||
if(!filename){
|
||||
WARNX(_("No filename given!"));
|
||||
return NULL;
|
||||
}
|
||||
if((fd = open(filename, O_RDONLY)) < 0){
|
||||
/// "îÅ ÍÏÇÕ ÏÔËÒÙÔØ %s ÄÌÑ ÞÔÅÎÉÑ"
|
||||
WARN(_("Can't open %s for reading"), filename);
|
||||
return NULL;
|
||||
}
|
||||
if(fstat (fd, &statbuf) < 0){
|
||||
/// "îÅ ÍÏÇÕ ×ÙÐÏÌÎÉÔØ stat %s"
|
||||
WARN(_("Can't stat %s"), filename);
|
||||
close(fd);
|
||||
return NULL;
|
||||
}
|
||||
Mlen = statbuf.st_size;
|
||||
if((ptr = mmap (0, Mlen, PROT_READ, MAP_PRIVATE, fd, 0)) == MAP_FAILED){
|
||||
/// "ïÛÉÂËÁ mmap"
|
||||
WARN(_("Mmap error for input"));
|
||||
close(fd);
|
||||
return NULL;
|
||||
}
|
||||
/// "îÅ ÍÏÇÕ ÚÁËÒÙÔØ mmap'ÎÕÔÙÊ ÆÁÊÌ"
|
||||
if(close(fd)) WARN(_("Can't close mmap'ed file"));
|
||||
mmapbuf *ret = MALLOC(mmapbuf, 1);
|
||||
ret->data = ptr;
|
||||
ret->len = Mlen;
|
||||
return ret;
|
||||
}
|
||||
|
||||
void My_munmap(mmapbuf *b){
|
||||
if(munmap(b->data, b->len)){
|
||||
/// "îÅ ÍÏÇÕ munmap"
|
||||
ERR(_("Can't munmap"));
|
||||
}
|
||||
FREE(b);
|
||||
}
|
||||
|
||||
|
||||
/******************************************************************************\
|
||||
* Terminal in no-echo mode
|
||||
\******************************************************************************/
|
||||
static struct termios oldt, newt; // terminal flags
|
||||
static int console_changed = 0;
|
||||
// run on exit:
|
||||
void restore_console(){
|
||||
if(console_changed)
|
||||
tcsetattr(STDIN_FILENO, TCSANOW, &oldt); // return terminal to previous state
|
||||
console_changed = 0;
|
||||
}
|
||||
|
||||
// initial setup:
|
||||
void setup_con(){
|
||||
if(console_changed) return;
|
||||
tcgetattr(STDIN_FILENO, &oldt);
|
||||
newt = oldt;
|
||||
newt.c_lflag &= ~(ICANON | ECHO);
|
||||
if(tcsetattr(STDIN_FILENO, TCSANOW, &newt) < 0){
|
||||
/// "îÅ ÍÏÇÕ ÎÁÓÔÒÏÉÔØ ËÏÎÓÏÌØ"
|
||||
WARN(_("Can't setup console"));
|
||||
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
|
||||
signals(0); //quit?
|
||||
}
|
||||
console_changed = 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read character from console without echo
|
||||
* @return char readed
|
||||
*/
|
||||
int read_console(){
|
||||
int rb;
|
||||
struct timeval tv;
|
||||
int retval;
|
||||
fd_set rfds;
|
||||
FD_ZERO(&rfds);
|
||||
FD_SET(STDIN_FILENO, &rfds);
|
||||
tv.tv_sec = 0; tv.tv_usec = 10000;
|
||||
retval = select(1, &rfds, NULL, NULL, &tv);
|
||||
if(!retval) rb = 0;
|
||||
else {
|
||||
if(FD_ISSET(STDIN_FILENO, &rfds)) rb = getchar();
|
||||
else rb = 0;
|
||||
}
|
||||
return rb;
|
||||
}
|
||||
|
||||
/**
|
||||
* getchar() without echo
|
||||
* wait until at least one character pressed
|
||||
* @return character readed
|
||||
*/
|
||||
int mygetchar(){ // getchar() without need of pressing ENTER
|
||||
int ret;
|
||||
do ret = read_console();
|
||||
while(ret == 0);
|
||||
return ret;
|
||||
}
|
||||
|
||||
|
||||
/******************************************************************************\
|
||||
* TTY with select()
|
||||
\******************************************************************************/
|
||||
static struct termio oldtty, tty; // TTY flags
|
||||
static int comfd = -1; // TTY fd
|
||||
|
||||
// run on exit:
|
||||
void restore_tty(){
|
||||
if(comfd == -1) return;
|
||||
ioctl(comfd, TCSANOW, &oldtty ); // return TTY to previous state
|
||||
close(comfd);
|
||||
comfd = -1;
|
||||
}
|
||||
|
||||
#ifndef BAUD_RATE
|
||||
#define BAUD_RATE B4800
|
||||
#endif
|
||||
//#pragma message("Baudrate: " STR(BAUD_RATE) " (default: " STR(B4800) ")")
|
||||
// init:
|
||||
void tty_init(char *comdev){
|
||||
DBG("\nOpen port %s ...\n", comdev);
|
||||
do{
|
||||
comfd = open(comdev,O_RDWR|O_NOCTTY|O_NONBLOCK);
|
||||
}while (comfd == -1 && errno == EINTR);
|
||||
if(comfd < 0){
|
||||
WARN("Can't use port %s\n",comdev);
|
||||
signals(-1); // quit?
|
||||
}
|
||||
// make exclusive open
|
||||
if(ioctl(comfd, TIOCEXCL)){
|
||||
WARN(_("Can't do exclusive open"));
|
||||
close(comfd);
|
||||
signals(2);
|
||||
}
|
||||
DBG(" OK\nGet current settings... ");
|
||||
if(ioctl(comfd,TCGETA,&oldtty) < 0){ // Get settings
|
||||
/// "îÅ ÍÏÇÕ ÐÏÌÕÞÉÔØ ÎÁÓÔÒÏÊËÉ"
|
||||
WARN(_("Can't get settings"));
|
||||
signals(-1);
|
||||
}
|
||||
tty = oldtty;
|
||||
tty.c_lflag = 0;
|
||||
tty.c_oflag = 0;
|
||||
tty.c_cflag = BAUD_RATE|CS8|CREAD|CLOCAL; // 9.6k, 8N1, RW, ignore line ctrl
|
||||
tty.c_cc[VMIN] = 20;
|
||||
tty.c_cc[VTIME] = 5;
|
||||
if(ioctl(comfd,TCSETA,&tty) < 0){
|
||||
/// "îÅ ÍÏÇÕ ÕÓÔÁÎÏ×ÉÔØ ÎÁÓÔÒÏÊËÉ"
|
||||
WARN(_("Can't set settings"));
|
||||
signals(-1);
|
||||
}
|
||||
DBG(" OK\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* Read data from TTY
|
||||
* @param buff (o) - buffer for data read
|
||||
* @param length - buffer len
|
||||
* @return amount of bytes read
|
||||
*/
|
||||
size_t read_tty(char *buff, size_t length){
|
||||
ssize_t L = 0, l;
|
||||
char *ptr = buff;
|
||||
fd_set rfds;
|
||||
struct timeval tv;
|
||||
int retval;
|
||||
do{
|
||||
l = 0;
|
||||
FD_ZERO(&rfds);
|
||||
FD_SET(comfd, &rfds);
|
||||
// wait for 100ms
|
||||
tv.tv_sec = 0; tv.tv_usec = 10000;
|
||||
retval = select(comfd + 1, &rfds, NULL, NULL, &tv);
|
||||
if (!retval) break;
|
||||
if(FD_ISSET(comfd, &rfds)){
|
||||
//DBG("ISSET");
|
||||
if((l = read(comfd, ptr, length)) < 1){
|
||||
return 0;
|
||||
}
|
||||
//DBG("got %zd", l);
|
||||
ptr += l; L += l;
|
||||
length -= l;
|
||||
}
|
||||
}while(l);
|
||||
return (size_t)L;
|
||||
}
|
||||
|
||||
int write_tty(const char *buff, size_t length){
|
||||
ssize_t L = write(comfd, buff, length);
|
||||
if((size_t)L != length){
|
||||
/// "ïÛÉÂËÁ ÚÁÐÉÓÉ!"
|
||||
WARN("Write error");
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Safely convert data from string to double
|
||||
*
|
||||
* @param num (o) - double number read from string
|
||||
* @param str (i) - input string
|
||||
* @return 1 if success, 0 if fails
|
||||
*/
|
||||
int str2double(double *num, const char *str){
|
||||
double res;
|
||||
char *endptr;
|
||||
if(!str) return 0;
|
||||
res = strtod(str, &endptr);
|
||||
if(endptr == str || *str == '\0' || *endptr != '\0'){
|
||||
/// "îÅÐÒÁ×ÉÌØÎÙÊ ÆÏÒÍÁÔ ÞÉÓÌÁ double!"
|
||||
WARNX("Wrong double number format!");
|
||||
return FALSE;
|
||||
}
|
||||
if(num) *num = res; // you may run it like myatod(NULL, str) to test wether str is double number
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
static FILE *Flog = NULL; // log file descriptor
|
||||
static char *logname = NULL;
|
||||
|
||||
/**
|
||||
* Try to open log file
|
||||
* if failed show warning message
|
||||
*/
|
||||
void openlogfile(char *name){
|
||||
if(!name){
|
||||
WARNX(_("Need filename"));
|
||||
return;
|
||||
}
|
||||
green(_("Try to open log file %s in append mode\n"), name);
|
||||
if(!(Flog = fopen(name, "a"))){
|
||||
WARN(_("Can't open log file"));
|
||||
return;
|
||||
}
|
||||
logname = name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Save message to log file, rotate logs every 24 hours
|
||||
*/
|
||||
int putlog(const char *fmt, ...){
|
||||
if(!Flog) return 0;
|
||||
time_t t_now = time(NULL);
|
||||
int i = fprintf(Flog, "\n\t\t%s", ctime(&t_now));
|
||||
va_list ar;
|
||||
va_start(ar, fmt);
|
||||
i = vfprintf(Flog, fmt, ar);
|
||||
va_end(ar);
|
||||
fprintf(Flog, "\n");
|
||||
fflush(Flog);
|
||||
return i;
|
||||
}
|
||||
@@ -1,144 +0,0 @@
|
||||
/*
|
||||
* usefull_macros.h - a set of usefull macros: memory, color etc
|
||||
*
|
||||
* Copyright 2013 Edward V. Emelianoff <eddy@sao.ru>
|
||||
*
|
||||
* 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 2 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, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
* MA 02110-1301, USA.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
#ifndef __USEFULL_MACROS_H__
|
||||
#define __USEFULL_MACROS_H__
|
||||
|
||||
#include <sys/stat.h>
|
||||
#include <fcntl.h>
|
||||
#include <sys/mman.h>
|
||||
#include <unistd.h>
|
||||
#include <string.h>
|
||||
#include <stdio.h>
|
||||
#include <stdarg.h>
|
||||
#include <errno.h>
|
||||
#include <err.h>
|
||||
#include <locale.h>
|
||||
#if defined GETTEXT_PACKAGE && defined LOCALEDIR
|
||||
/*
|
||||
* GETTEXT
|
||||
*/
|
||||
#include <libintl.h>
|
||||
#define _(String) gettext(String)
|
||||
#define gettext_noop(String) String
|
||||
#define N_(String) gettext_noop(String)
|
||||
#else
|
||||
#define _(String) (String)
|
||||
#define N_(String) (String)
|
||||
#endif
|
||||
|
||||
#define STR_HELPER(s) #s
|
||||
#define STR(s) STR_HELPER(s)
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <termios.h>
|
||||
#include <termio.h>
|
||||
#include <sys/time.h>
|
||||
#include <sys/types.h>
|
||||
#include <stdint.h>
|
||||
|
||||
|
||||
// unused arguments with -Wall -Werror
|
||||
#define _U_ __attribute__((__unused__))
|
||||
|
||||
/*
|
||||
* Coloured messages output
|
||||
*/
|
||||
#define RED "\033[1;31;40m"
|
||||
#define GREEN "\033[1;32;40m"
|
||||
#define OLDCOLOR "\033[0;0;0m"
|
||||
|
||||
#ifndef FALSE
|
||||
#define FALSE (0)
|
||||
#endif
|
||||
|
||||
#ifndef TRUE
|
||||
#define TRUE (1)
|
||||
#endif
|
||||
|
||||
/*
|
||||
* ERROR/WARNING messages
|
||||
*/
|
||||
extern int globErr;
|
||||
extern void signals(int sig);
|
||||
#define ERR(...) do{globErr=errno; _WARN(__VA_ARGS__); signals(9);}while(0)
|
||||
#define ERRX(...) do{globErr=0; _WARN(__VA_ARGS__); signals(9);}while(0)
|
||||
#define WARN(...) do{globErr=errno; _WARN(__VA_ARGS__);}while(0)
|
||||
#define WARNX(...) do{globErr=0; _WARN(__VA_ARGS__);}while(0)
|
||||
|
||||
/*
|
||||
* print function name, debug messages
|
||||
* debug mode, -DEBUG
|
||||
*/
|
||||
#ifdef EBUG
|
||||
#define FNAME() fprintf(stderr, "\n%s (%s, line %d)\n", __func__, __FILE__, __LINE__)
|
||||
#define DBG(...) do{fprintf(stderr, "%s (%s, line %d): ", __func__, __FILE__, __LINE__); \
|
||||
fprintf(stderr, __VA_ARGS__); \
|
||||
fprintf(stderr, "\n");} while(0)
|
||||
#else
|
||||
#define FNAME() do{}while(0)
|
||||
#define DBG(...) do{}while(0)
|
||||
#endif //EBUG
|
||||
|
||||
/*
|
||||
* Memory allocation
|
||||
*/
|
||||
#define ALLOC(type, var, size) type * var = ((type *)my_alloc(size, sizeof(type)))
|
||||
#define MALLOC(type, size) ((type *)my_alloc(size, sizeof(type)))
|
||||
#define FREE(ptr) do{if(ptr){free(ptr); ptr = NULL;}}while(0)
|
||||
|
||||
#ifndef DBL_EPSILON
|
||||
#define DBL_EPSILON (2.2204460492503131e-16)
|
||||
#endif
|
||||
|
||||
double dtime();
|
||||
|
||||
// functions for color output in tty & no-color in pipes
|
||||
extern int (*red)(const char *fmt, ...);
|
||||
extern int (*_WARN)(const char *fmt, ...);
|
||||
extern int (*green)(const char *fmt, ...);
|
||||
void * my_alloc(size_t N, size_t S);
|
||||
void initial_setup();
|
||||
|
||||
// mmap file
|
||||
typedef struct{
|
||||
char *data;
|
||||
size_t len;
|
||||
} mmapbuf;
|
||||
mmapbuf *My_mmap(char *filename);
|
||||
void My_munmap(mmapbuf *b);
|
||||
|
||||
void restore_console();
|
||||
void setup_con();
|
||||
int read_console();
|
||||
int mygetchar();
|
||||
|
||||
void restore_tty();
|
||||
void tty_init(char *comdev);
|
||||
size_t read_tty(char *buff, size_t length);
|
||||
int write_tty(const char *buff, size_t length);
|
||||
|
||||
int str2double(double *num, const char *str);
|
||||
|
||||
void openlogfile(char *name);
|
||||
int putlog(const char *fmt, ...);
|
||||
#endif // __USEFULL_MACROS_H__
|
||||
Reference in New Issue
Block a user