mirror of
https://github.com/eddyem/small_tel.git
synced 2026-03-24 10:40:56 +03:00
new baader daemon
This commit is contained in:
43
Daemons/deprecated/domedaemon-astrosib.deprecated/Makefile
Normal file
43
Daemons/deprecated/domedaemon-astrosib.deprecated/Makefile
Normal file
@@ -0,0 +1,43 @@
|
||||
# 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
|
||||
12
Daemons/deprecated/domedaemon-astrosib.deprecated/Readme.md
Normal file
12
Daemons/deprecated/domedaemon-astrosib.deprecated/Readme.md
Normal file
@@ -0,0 +1,12 @@
|
||||
Astrosib all-sky dome control network daemon
|
||||
==================
|
||||
|
||||
Open a socket at given port (default: 55555), works with http & direct requests.
|
||||
|
||||
**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");
|
||||
@@ -0,0 +1,89 @@
|
||||
/* 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;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
/* 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__
|
||||
@@ -0,0 +1 @@
|
||||
-std=c17
|
||||
@@ -0,0 +1,2 @@
|
||||
// Add predefined macros for your project here. For example:
|
||||
// #define THE_ANSWER 42
|
||||
@@ -0,0 +1 @@
|
||||
[General]
|
||||
@@ -0,0 +1,157 @@
|
||||
<?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>
|
||||
@@ -0,0 +1 @@
|
||||
-std=c++17
|
||||
@@ -0,0 +1,11 @@
|
||||
cmdlnopts.c
|
||||
cmdlnopts.h
|
||||
main.c
|
||||
parseargs.c
|
||||
parseargs.h
|
||||
socket.c
|
||||
socket.h
|
||||
term.c
|
||||
term.h
|
||||
usefull_macros.c
|
||||
usefull_macros.h
|
||||
@@ -0,0 +1 @@
|
||||
.
|
||||
89
Daemons/deprecated/domedaemon-astrosib.deprecated/main.c
Normal file
89
Daemons/deprecated/domedaemon-astrosib.deprecated/main.c
Normal file
@@ -0,0 +1,89 @@
|
||||
/* geany_encoding=koi8-r
|
||||
* main.c
|
||||
*
|
||||
* 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 <signal.h>
|
||||
#include <sys/wait.h> // wait
|
||||
#include <sys/prctl.h> //prctl
|
||||
#include <time.h>
|
||||
#include "cmdlnopts.h"
|
||||
#include "socket.h"
|
||||
|
||||
// dome @ /dev/ttyS2
|
||||
|
||||
glob_pars *GP;
|
||||
static pid_t childpid = 0;
|
||||
|
||||
void signals(int signo){
|
||||
if(childpid){ // parent process
|
||||
restore_tty();
|
||||
putlog("exit with status %d", signo);
|
||||
}
|
||||
exit(signo);
|
||||
}
|
||||
|
||||
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()");
|
||||
}
|
||||
time_t lastd = 0;
|
||||
while(1){ // guard for dead processes
|
||||
childpid = fork();
|
||||
if(childpid){
|
||||
DBG("Created child with PID %d\n", childpid);
|
||||
wait(NULL);
|
||||
time_t t = time(NULL);
|
||||
if(t - lastd > 600) // at least 10 minutes of work
|
||||
putlog("child %d died\n", childpid);
|
||||
lastd = t;
|
||||
WARNX("Child %d died\n", childpid);
|
||||
sleep(1);
|
||||
}else{
|
||||
prctl(PR_SET_PDEATHSIG, SIGTERM); // send SIGTERM to child when parent dies
|
||||
break; // go out to normal functional
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
if(GP->device) try_connect(GP->device);
|
||||
if(!poll_device()){
|
||||
ERRX(_("No answer from device"));
|
||||
}
|
||||
putlog("Child %d connected to %s", getpid(), GP->device);
|
||||
daemonize(GP->port);
|
||||
signals(0); // newer reached
|
||||
return 0;
|
||||
}
|
||||
497
Daemons/deprecated/domedaemon-astrosib.deprecated/parseargs.c
Normal file
497
Daemons/deprecated/domedaemon-astrosib.deprecated/parseargs.c
Normal file
@@ -0,0 +1,497 @@
|
||||
/* 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;
|
||||
}
|
||||
124
Daemons/deprecated/domedaemon-astrosib.deprecated/parseargs.h
Normal file
124
Daemons/deprecated/domedaemon-astrosib.deprecated/parseargs.h
Normal file
@@ -0,0 +1,124 @@
|
||||
/* 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__
|
||||
336
Daemons/deprecated/domedaemon-astrosib.deprecated/socket.c
Normal file
336
Daemons/deprecated/domedaemon-astrosib.deprecated/socket.c
Normal file
@@ -0,0 +1,336 @@
|
||||
/*
|
||||
* 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);
|
||||
}
|
||||
|
||||
34
Daemons/deprecated/domedaemon-astrosib.deprecated/socket.h
Normal file
34
Daemons/deprecated/domedaemon-astrosib.deprecated/socket.h
Normal file
@@ -0,0 +1,34 @@
|
||||
/*
|
||||
* 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__
|
||||
172
Daemons/deprecated/domedaemon-astrosib.deprecated/term.c
Normal file
172
Daemons/deprecated/domedaemon-astrosib.deprecated/term.c
Normal file
@@ -0,0 +1,172 @@
|
||||
/* 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;
|
||||
}
|
||||
37
Daemons/deprecated/domedaemon-astrosib.deprecated/term.h
Normal file
37
Daemons/deprecated/domedaemon-astrosib.deprecated/term.h
Normal file
@@ -0,0 +1,37 @@
|
||||
/* 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__
|
||||
@@ -0,0 +1,427 @@
|
||||
/*
|
||||
* 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;
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
/*
|
||||
* 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__
|
||||
43
Daemons/deprecated/domedaemon/Makefile
Normal file
43
Daemons/deprecated/domedaemon/Makefile
Normal file
@@ -0,0 +1,43 @@
|
||||
# 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
|
||||
13
Daemons/deprecated/domedaemon/Readme.md
Normal file
13
Daemons/deprecated/domedaemon/Readme.md
Normal file
@@ -0,0 +1,13 @@
|
||||
Baader all-sky dome control network daemon
|
||||
==================
|
||||
|
||||
Open a socket at given port (default: 55555), works with http & direct requests.
|
||||
|
||||
**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");
|
||||
* *weather* - weather status (good weather or rain/clouds).
|
||||
89
Daemons/deprecated/domedaemon/cmdlnopts.c
Normal file
89
Daemons/deprecated/domedaemon/cmdlnopts.c
Normal file
@@ -0,0 +1,89 @@
|
||||
/* 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;
|
||||
}
|
||||
|
||||
44
Daemons/deprecated/domedaemon/cmdlnopts.h
Normal file
44
Daemons/deprecated/domedaemon/cmdlnopts.h
Normal file
@@ -0,0 +1,44 @@
|
||||
/* 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__
|
||||
15
Daemons/deprecated/domedaemon/dome_readme.koi8-r
Normal file
15
Daemons/deprecated/domedaemon/dome_readme.koi8-r
Normal file
@@ -0,0 +1,15 @@
|
||||
Протокол управления куполом
|
||||
|
||||
в случае ошибки коммуникации ответ - d#comerro -> повторить запрос
|
||||
в случае ошибки купола ответ - d#domerro
|
||||
|
||||
d#opendom - открыть
|
||||
d#closdom - закрыть
|
||||
d#get_dom - текущее положение
|
||||
ответ: d#posXXXX, X=0 - движение или промежуточное положение, 1 - сегмент полностью открыт, 2 - сегмент полностью закрыт
|
||||
d#warning - состояние ошибок
|
||||
ответ: d#erro123, позиции: 1 - дождь, 2 - таймаут, 3 - отключение питания (висит на упсе)
|
||||
значение: 0 - все в порядке, 1 - тревога (купол закрывается)
|
||||
d#ask_wea - погодный датчик
|
||||
ответ: d#weaX000, X==1 - дождь или облака
|
||||
|
||||
89
Daemons/deprecated/domedaemon/main.c
Normal file
89
Daemons/deprecated/domedaemon/main.c
Normal file
@@ -0,0 +1,89 @@
|
||||
/* geany_encoding=koi8-r
|
||||
* main.c
|
||||
*
|
||||
* 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 <signal.h>
|
||||
#include <sys/wait.h> // wait
|
||||
#include <sys/prctl.h> //prctl
|
||||
#include <time.h>
|
||||
#include "cmdlnopts.h"
|
||||
#include "socket.h"
|
||||
|
||||
// dome @ /dev/ttyS2
|
||||
|
||||
glob_pars *GP;
|
||||
static pid_t childpid = 0;
|
||||
|
||||
void signals(int signo){
|
||||
if(childpid){ // parent process
|
||||
restore_tty();
|
||||
putlog("exit with status %d", signo);
|
||||
}
|
||||
exit(signo);
|
||||
}
|
||||
|
||||
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()");
|
||||
}
|
||||
time_t lastd = 0;
|
||||
while(1){ // guard for dead processes
|
||||
childpid = fork();
|
||||
if(childpid){
|
||||
DBG("Created child with PID %d\n", childpid);
|
||||
wait(NULL);
|
||||
time_t t = time(NULL);
|
||||
if(t - lastd > 600) // at least 10 minutes of work
|
||||
putlog("child %d died\n", childpid);
|
||||
lastd = t;
|
||||
WARNX("Child %d died\n", childpid);
|
||||
sleep(1);
|
||||
}else{
|
||||
prctl(PR_SET_PDEATHSIG, SIGTERM); // send SIGTERM to child when parent dies
|
||||
break; // go out to normal functional
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
if(GP->device) try_connect(GP->device);
|
||||
if(ping()){
|
||||
ERRX(_("Can't write command PING"));
|
||||
}
|
||||
putlog("Child %d connected to %s", getpid(), GP->device);
|
||||
daemonize(GP->port);
|
||||
signals(0); // newer reached
|
||||
return 0;
|
||||
}
|
||||
497
Daemons/deprecated/domedaemon/parseargs.c
Normal file
497
Daemons/deprecated/domedaemon/parseargs.c
Normal file
@@ -0,0 +1,497 @@
|
||||
/* 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;
|
||||
}
|
||||
124
Daemons/deprecated/domedaemon/parseargs.h
Normal file
124
Daemons/deprecated/domedaemon/parseargs.h
Normal file
@@ -0,0 +1,124 @@
|
||||
/* 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__
|
||||
330
Daemons/deprecated/domedaemon/socket.c
Normal file
330
Daemons/deprecated/domedaemon/socket.c
Normal file
@@ -0,0 +1,330 @@
|
||||
/*
|
||||
* 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
|
||||
static char weather[32];
|
||||
|
||||
typedef enum{
|
||||
CMD_OPEN,
|
||||
CMD_CLOSE,
|
||||
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: open, close, status";
|
||||
if(strstr(found, "open")){
|
||||
DBG("User asks 2 open");
|
||||
putlog("User asks to open");
|
||||
cmd = CMD_OPEN;
|
||||
send_data(sock, webquery, "OK\n");
|
||||
}else if(strstr(found, "close")){
|
||||
DBG("User asks 2 close");
|
||||
putlog("User asks to close");
|
||||
cmd = CMD_CLOSE;
|
||||
send_data(sock, webquery, "OK\n");
|
||||
}else if(strstr(found, "weather")){
|
||||
send_data(sock, webquery, weather);
|
||||
}else if(strstr(found, "status")){
|
||||
DBG("User asks 4 status");
|
||||
send_data(sock, webquery, status);
|
||||
}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.;
|
||||
sprintf(weather, "unknown");
|
||||
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(weather);
|
||||
if(pollans) status = pollans;
|
||||
if(cmd != CMD_NONE){
|
||||
switch (cmd){
|
||||
case CMD_OPEN:
|
||||
DBG("received command: open");
|
||||
if(write_cmd("d#opendom")) cmd = CMD_NONE;
|
||||
break;
|
||||
case CMD_CLOSE:
|
||||
DBG("received command: close");
|
||||
if(write_cmd("d#closdom")) 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);
|
||||
}
|
||||
|
||||
34
Daemons/deprecated/domedaemon/socket.h
Normal file
34
Daemons/deprecated/domedaemon/socket.h
Normal file
@@ -0,0 +1,34 @@
|
||||
/*
|
||||
* 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__
|
||||
203
Daemons/deprecated/domedaemon/term.c
Normal file
203
Daemons/deprecated/domedaemon/term.c
Normal file
@@ -0,0 +1,203 @@
|
||||
/* 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);
|
||||
if(write_tty(cmd, strlen(cmd))) 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 *wea){
|
||||
char *ans;
|
||||
static char pollbuf[32];
|
||||
const char *cmdstat = "d#get_dom";
|
||||
const char *cmdweat = "d#ask_wea";
|
||||
const char *getweat = "d#wea";
|
||||
const char *cmdget = "d#pos";
|
||||
#define CMDGETLEN (5)
|
||||
#define CMDWEALEN (5)
|
||||
while(read_string()); // clear receiving buffer
|
||||
if(!(ans = write_cmd(cmdstat))) return NULL; // error writing command
|
||||
if(strstr(ans, cmdget) == NULL){
|
||||
DBG("no %s found in %s", cmdstat, ans);
|
||||
return NULL; // ?
|
||||
}
|
||||
ans += CMDGETLEN;
|
||||
if(strstr(ans, "1111")){
|
||||
sprintf(pollbuf, "opened\n");
|
||||
DBG("dome opened");
|
||||
}else if(strstr(ans, "2222")){
|
||||
sprintf(pollbuf, "closed\n");
|
||||
DBG("dome closed");
|
||||
}else sprintf(pollbuf, "intermediate\n");
|
||||
if(!wea || !(ans = write_cmd(cmdweat))) return pollbuf;
|
||||
DBG("poll weather answer");
|
||||
if(strstr(ans, getweat) == NULL){
|
||||
DBG("no %s found in %s", getweat, ans);
|
||||
return pollbuf; // ?
|
||||
}
|
||||
ans += CMDWEALEN;
|
||||
if(*ans == '0'){
|
||||
sprintf(wea, "good weather\n");
|
||||
DBG("good weather");
|
||||
}else if(*ans == '1'){
|
||||
sprintf(wea, "rain or clouds\n");
|
||||
DBG("bad weather");
|
||||
}else sprintf(wea, "unknown\n");
|
||||
return pollbuf;
|
||||
}
|
||||
|
||||
/**
|
||||
* ping device
|
||||
* @return 0 if all OK
|
||||
*/
|
||||
int ping(){
|
||||
FNAME();
|
||||
while(read_string()); // clear receiving buffer
|
||||
char *ans = write_cmd("d#get_dom");
|
||||
if(!ans) return 1;
|
||||
if(strstr(ans, "d#pos")) return 0;
|
||||
return 1;
|
||||
}
|
||||
38
Daemons/deprecated/domedaemon/term.h
Normal file
38
Daemons/deprecated/domedaemon/term.h
Normal file
@@ -0,0 +1,38 @@
|
||||
/* 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 *wea);
|
||||
int ping();
|
||||
char *write_cmd(const char *cmd);
|
||||
|
||||
#endif // __TERM_H__
|
||||
427
Daemons/deprecated/domedaemon/usefull_macros.c
Normal file
427
Daemons/deprecated/domedaemon/usefull_macros.c
Normal file
@@ -0,0 +1,427 @@
|
||||
/*
|
||||
* 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;
|
||||
}
|
||||
144
Daemons/deprecated/domedaemon/usefull_macros.h
Normal file
144
Daemons/deprecated/domedaemon/usefull_macros.h
Normal file
@@ -0,0 +1,144 @@
|
||||
/*
|
||||
* 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__
|
||||
43
Daemons/deprecated/netdaemon.deprecated/Makefile
Normal file
43
Daemons/deprecated/netdaemon.deprecated/Makefile
Normal file
@@ -0,0 +1,43 @@
|
||||
# run `make DEF=...` to add extra defines
|
||||
PROGRAM := netdaemon
|
||||
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=B115200
|
||||
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
|
||||
9
Daemons/deprecated/netdaemon.deprecated/Readme.md
Normal file
9
Daemons/deprecated/netdaemon.deprecated/Readme.md
Normal file
@@ -0,0 +1,9 @@
|
||||
Network daemon snippet
|
||||
==================
|
||||
|
||||
This isn't an end-product, but just a template for different net-daemons.
|
||||
|
||||
Open a socket at given port (default: 4444), works with http & direct requests.
|
||||
Can read and send commands over serial interface.
|
||||
|
||||
Pieces with user code marked as 'INSERT CODE HERE'.
|
||||
89
Daemons/deprecated/netdaemon.deprecated/cmdlnopts.c
Normal file
89
Daemons/deprecated/netdaemon.deprecated/cmdlnopts.c
Normal file
@@ -0,0 +1,89 @@
|
||||
/* 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 "4444"
|
||||
|
||||
// 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, 'i', 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;
|
||||
}
|
||||
|
||||
44
Daemons/deprecated/netdaemon.deprecated/cmdlnopts.h
Normal file
44
Daemons/deprecated/netdaemon.deprecated/cmdlnopts.h
Normal file
@@ -0,0 +1,44 @@
|
||||
/* 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__
|
||||
79
Daemons/deprecated/netdaemon.deprecated/main.c
Normal file
79
Daemons/deprecated/netdaemon.deprecated/main.c
Normal file
@@ -0,0 +1,79 @@
|
||||
/* geany_encoding=koi8-r
|
||||
* main.c
|
||||
*
|
||||
* 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 <signal.h>
|
||||
#include <sys/wait.h> // wait
|
||||
#include <sys/prctl.h> //prctl
|
||||
#include "cmdlnopts.h"
|
||||
#include "socket.h"
|
||||
|
||||
glob_pars *GP;
|
||||
|
||||
void signals(int signo){
|
||||
restore_console();
|
||||
restore_tty();
|
||||
LOG("exit with status %d", signo);
|
||||
exit(signo);
|
||||
}
|
||||
|
||||
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)
|
||||
Cl_createlog(GP->logfile);
|
||||
#ifndef EBUG
|
||||
if(daemon(1, 0)){
|
||||
ERR("daemon()");
|
||||
}
|
||||
while(1){ // guard for dead processes
|
||||
pid_t childpid = fork();
|
||||
if(childpid){
|
||||
LOG("create child with PID %d\n", childpid);
|
||||
DBG("Created child with PID %d\n", childpid);
|
||||
wait(NULL);
|
||||
WARNX("Child %d died\n", childpid);
|
||||
sleep(1);
|
||||
}else{
|
||||
prctl(PR_SET_PDEATHSIG, SIGTERM); // send SIGTERM to child when parent dies
|
||||
break; // go out to normal functional
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
if(GP->device) try_connect(GP->device);
|
||||
/*
|
||||
* INSERT CODE HERE
|
||||
* connection check & device validation
|
||||
*/
|
||||
daemonize(GP->port);
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
#define EBUG 1
|
||||
# baudrate for USB<->UART converter
|
||||
#define BAUD_RATE B115200
|
||||
@@ -0,0 +1 @@
|
||||
[General]
|
||||
@@ -0,0 +1,11 @@
|
||||
cmdlnopts.c
|
||||
cmdlnopts.h
|
||||
main.c
|
||||
parseargs.c
|
||||
parseargs.h
|
||||
socket.c
|
||||
socket.h
|
||||
term.c
|
||||
term.h
|
||||
usefull_macros.c
|
||||
usefull_macros.h
|
||||
@@ -0,0 +1 @@
|
||||
.
|
||||
497
Daemons/deprecated/netdaemon.deprecated/parseargs.c
Normal file
497
Daemons/deprecated/netdaemon.deprecated/parseargs.c
Normal file
@@ -0,0 +1,497 @@
|
||||
/* 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;
|
||||
}
|
||||
124
Daemons/deprecated/netdaemon.deprecated/parseargs.h
Normal file
124
Daemons/deprecated/netdaemon.deprecated/parseargs.h
Normal file
@@ -0,0 +1,124 @@
|
||||
/* 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__
|
||||
307
Daemons/deprecated/netdaemon.deprecated/socket.c
Normal file
307
Daemons/deprecated/netdaemon.deprecated/socket.c
Normal file
@@ -0,0 +1,307 @@
|
||||
/*
|
||||
* 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 <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;
|
||||
|
||||
/*
|
||||
* 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 ****************/
|
||||
static 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, 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){
|
||||
//LOG("handle_socket(): getpid: %d, pthread_self: %lu, tid: %lu",getpid(), pthread_self(), syscall(SYS_gettid));
|
||||
FNAME();
|
||||
int sock = *((int*)asock);
|
||||
int webquery = 0; // whether query is web or regular
|
||||
char buff[BUFLEN];
|
||||
ssize_t rd;
|
||||
double t0 = dtime();
|
||||
/*
|
||||
* INSERT CODE HERE
|
||||
* change to while(1) if socket shouldn't be closed after data transmission
|
||||
*/
|
||||
while(dtime() - t0 < SOCKET_TIMEOUT){
|
||||
if(!waittoread(sock)){ // no data incoming
|
||||
continue;
|
||||
}
|
||||
if(!(rd = read(sock, buff, BUFLEN-1))){
|
||||
//LOG("socket closed. Exit");
|
||||
break;
|
||||
}
|
||||
//LOG("client send %zd bytes", rd);
|
||||
DBG("Got %zd bytes", rd);
|
||||
if(rd < 0){ // error
|
||||
//LOG("some error occured");
|
||||
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)){
|
||||
LOG("can't send data, some error occured");
|
||||
}
|
||||
}
|
||||
pthread_mutex_lock(&mutex);
|
||||
/*
|
||||
* INSERT CODE HERE
|
||||
* Process user commands here & send him an answer
|
||||
* remove trailing break if socket shouldn't be closed after server sent data
|
||||
*/
|
||||
pthread_mutex_unlock(&mutex);
|
||||
break;
|
||||
}
|
||||
close(sock);
|
||||
//DBG("closed");
|
||||
//LOG("socket closed, exit");
|
||||
pthread_exit(NULL);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
// main socket server
|
||||
static void *server(void *asock){
|
||||
LOG("server(): getpid: %d, pthread_self: %lu, tid: %lu",getpid(), pthread_self(), syscall(SYS_gettid));
|
||||
int sock = *((int*)asock);
|
||||
if(listen(sock, BACKLOG) == -1){
|
||||
LOG("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){
|
||||
LOG("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);
|
||||
//LOG("get 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)){
|
||||
LOG("server(): pthread_create() failed");
|
||||
WARN("pthread_create()");
|
||||
}else{
|
||||
DBG("Thread created, detouch");
|
||||
pthread_detach(handler_thread); // don't care about thread state
|
||||
}
|
||||
}
|
||||
LOG("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)){
|
||||
LOG("daemon_(): pthread_create() failed");
|
||||
ERR("pthread_create()");
|
||||
}
|
||||
double tgot = 0.;
|
||||
do{
|
||||
if(pthread_kill(sock_thread, 0) == ESRCH){ // died
|
||||
WARNX("Sockets thread died");
|
||||
LOG("Sockets thread died");
|
||||
pthread_join(sock_thread, NULL);
|
||||
if(pthread_create(&sock_thread, NULL, server, (void*) &sock)){
|
||||
LOG("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();
|
||||
/*
|
||||
* INSERT CODE HERE
|
||||
* Gather data (poll_device)
|
||||
*/
|
||||
// copy temporary buffers to main
|
||||
pthread_mutex_lock(&mutex);
|
||||
/*
|
||||
* INSERT CODE HERE
|
||||
* fill global data buffers
|
||||
*/
|
||||
pthread_mutex_unlock(&mutex);
|
||||
}while(1);
|
||||
LOG("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){
|
||||
LOG("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);
|
||||
LOG("socket closed, exit");
|
||||
signals(0);
|
||||
}
|
||||
|
||||
34
Daemons/deprecated/netdaemon.deprecated/socket.h
Normal file
34
Daemons/deprecated/netdaemon.deprecated/socket.h
Normal file
@@ -0,0 +1,34 @@
|
||||
/*
|
||||
* 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 (10.)
|
||||
|
||||
void daemonize(char *port);
|
||||
|
||||
#endif // __SOCKET_H__
|
||||
118
Daemons/deprecated/netdaemon.deprecated/term.c
Normal file
118
Daemons/deprecated/netdaemon.deprecated/term.c
Normal file
@@ -0,0 +1,118 @@
|
||||
/* 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(){
|
||||
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;
|
||||
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);
|
||||
while(read_tty(tmpbuf, 4096)); // clear rbuf
|
||||
LOG("Connected to %s", device);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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())){
|
||||
buf[0] = (char) rb;
|
||||
write_tty(buf, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Poll serial port for new dataportion
|
||||
* @return: NULL if no data received, pointer to string if valid data received
|
||||
*/
|
||||
char *poll_device(){
|
||||
char *ans;
|
||||
double t0 = dtime();
|
||||
while(dtime() - t0 < T_POLLING_TMOUT){
|
||||
if((ans = read_string())){ // parse new data
|
||||
DBG("got %s", ans);
|
||||
/*
|
||||
* INSERT CODE HERE
|
||||
* (data validation)
|
||||
*/
|
||||
return ans;
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
36
Daemons/deprecated/netdaemon.deprecated/term.h
Normal file
36
Daemons/deprecated/netdaemon.deprecated/term.h
Normal file
@@ -0,0 +1,36 @@
|
||||
/* 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();
|
||||
|
||||
#endif // __TERM_H__
|
||||
448
Daemons/deprecated/netdaemon.deprecated/usefull_macros.c
Normal file
448
Daemons/deprecated/netdaemon.deprecated/usefull_macros.c
Normal file
@@ -0,0 +1,448 @@
|
||||
/*
|
||||
* 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
|
||||
// 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; // ~(ICANON | ECHO | ECHOE | ISIG)
|
||||
tty.c_oflag = 0;
|
||||
tty.c_cflag = BAUD_RATE|CS8|CREAD|CLOCAL; // 9.6k, 8N1, RW, ignore line ctrl
|
||||
tty.c_cc[VMIN] = 0; // non-canonical mode
|
||||
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 = 100000;
|
||||
retval = select(comfd + 1, &rfds, NULL, NULL, &tv);
|
||||
if (!retval) break;
|
||||
if(FD_ISSET(comfd, &rfds)){
|
||||
if((l = read(comfd, ptr, length)) < 1){
|
||||
return 0;
|
||||
}
|
||||
ptr += l; L += l;
|
||||
length -= l;
|
||||
}
|
||||
}while(l);
|
||||
return (size_t)L;
|
||||
}
|
||||
|
||||
int write_tty(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;
|
||||
}
|
||||
|
||||
//////////// logging
|
||||
|
||||
static Cl_log log = {0};
|
||||
/**
|
||||
* @brief Cl_createlog - create log file: init mutex, test file open ability
|
||||
* @param log - log structure
|
||||
* @return 0 if all OK
|
||||
*/
|
||||
int Cl_createlog(char *logname){
|
||||
if(log.logpath){
|
||||
FREE(log.logpath);
|
||||
pthread_mutex_destroy(&log.mutex);
|
||||
}
|
||||
FILE *logfd = fopen(logname, "a");
|
||||
if(!logfd){
|
||||
WARN("Can't open log file");
|
||||
return 2;
|
||||
}
|
||||
log.logpath = strdup(logname);
|
||||
fclose(logfd);
|
||||
if(pthread_mutex_init(&log.mutex, NULL)){
|
||||
WARN("Can't init log mutes");
|
||||
return 3;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Cl_putlog - put message to log file with/without timestamp
|
||||
* @param timest - ==1 to put timestamp
|
||||
* @param log - pointer to log structure
|
||||
* @param lvl - message loglevel (if lvl > loglevel, message won't be printed)
|
||||
* @param fmt - format and the rest part of message
|
||||
* @return amount of symbols saved in file
|
||||
*/
|
||||
int Cl_putlogt(const char *fmt, ...){
|
||||
if(pthread_mutex_lock(&log.mutex)){
|
||||
WARN("Can't lock log mutex");
|
||||
return 0;
|
||||
}
|
||||
int i = 0;
|
||||
FILE *logfd = fopen(log.logpath, "a");
|
||||
if(!logfd) goto rtn;
|
||||
char strtm[128];
|
||||
time_t t = time(NULL);
|
||||
struct tm *curtm = localtime(&t);
|
||||
strftime(strtm, 128, "%Y/%m/%d-%H:%M:%S", curtm);
|
||||
i = fprintf(logfd, "%s\t", strtm);
|
||||
va_list ar;
|
||||
va_start(ar, fmt);
|
||||
i += vfprintf(logfd, fmt, ar);
|
||||
va_end(ar);
|
||||
i += fprintf(logfd, "\n");
|
||||
fclose(logfd);
|
||||
rtn:
|
||||
pthread_mutex_unlock(&log.mutex);
|
||||
return i;
|
||||
}
|
||||
|
||||
148
Daemons/deprecated/netdaemon.deprecated/usefull_macros.h
Normal file
148
Daemons/deprecated/netdaemon.deprecated/usefull_macros.h
Normal file
@@ -0,0 +1,148 @@
|
||||
/*
|
||||
* 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
|
||||
#include <pthread.h>
|
||||
#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; Cl_putlogt(__VA_ARGS__); _WARN(__VA_ARGS__); signals(9);}while(0)
|
||||
#define ERRX(...) do{globErr=0; Cl_putlogt(__VA_ARGS__); _WARN(__VA_ARGS__); signals(9);}while(0)
|
||||
#define WARN(...) do{globErr=errno; Cl_putlogt(__VA_ARGS__); _WARN(__VA_ARGS__);}while(0)
|
||||
#define WARNX(...) do{globErr=0; Cl_putlogt(__VA_ARGS__); _WARN(__VA_ARGS__);}while(0)
|
||||
#define LOG(...) do{Cl_putlogt(__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(char *buff, size_t length);
|
||||
|
||||
int str2double(double *num, const char *str);
|
||||
|
||||
typedef struct{
|
||||
char *logpath; // full path to logfile
|
||||
pthread_mutex_t mutex; // log mutex
|
||||
} Cl_log;
|
||||
|
||||
int Cl_createlog(char *logname);
|
||||
int Cl_putlogt(const char *fmt, ...);
|
||||
|
||||
#endif // __USEFULL_MACROS_H__
|
||||
43
Daemons/deprecated/weatherdaemon.deprecated/Makefile
Normal file
43
Daemons/deprecated/weatherdaemon.deprecated/Makefile
Normal file
@@ -0,0 +1,43 @@
|
||||
# run `make DEF=...` to add extra defines
|
||||
PROGRAM := weatherdaemon
|
||||
LDFLAGS := -fdata-sections -ffunction-sections -Wl,--gc-sections -Wl,--discard-all -pthread
|
||||
LDFLAGS += -lusefull_macros
|
||||
SRCS := $(wildcard *.c)
|
||||
DEFINES := $(DEF) -D_GNU_SOURCE -D_XOPEN_SOURCE=1111
|
||||
#DEFINES += -DEBUG
|
||||
# baudrate for USB<->UART converter
|
||||
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
|
||||
20
Daemons/deprecated/weatherdaemon.deprecated/Readme.md
Normal file
20
Daemons/deprecated/weatherdaemon.deprecated/Readme.md
Normal file
@@ -0,0 +1,20 @@
|
||||
Weather daemon
|
||||
==================
|
||||
|
||||
Open a socket at given port (default: 4444)
|
||||
Parse weather data and send it to client
|
||||
|
||||
```
|
||||
Usage: weatherdaemon [args]
|
||||
|
||||
Where args are:
|
||||
|
||||
-P, --pidfile=arg pidfile name (default: /tmp/weatherdaemon.pid)
|
||||
-b, --baudrate=arg serial terminal baudrate (default: 9600)
|
||||
-d, --device=arg serial device name (default: none)
|
||||
-e, --emulation emulate serial device
|
||||
-h, --help show this help
|
||||
-l, --logfile=arg save logs to file (default: none)
|
||||
-p, --port=arg network port to connect (default: 12345)
|
||||
-v, --verb logfile verbocity level (each -v increase it)
|
||||
```
|
||||
348
Daemons/deprecated/weatherdaemon.deprecated/bta_shdata.c
Normal file
348
Daemons/deprecated/weatherdaemon.deprecated/bta_shdata.c
Normal file
@@ -0,0 +1,348 @@
|
||||
// Copyright: V.S. Shergin, vsher@sao.ru
|
||||
// fixed for x86_64 E.V. Emelianov, edward.emelianoff@gmail.com
|
||||
#include "bta_shdata.h"
|
||||
#include <usefull_macros.h>
|
||||
|
||||
#include <crypt.h>
|
||||
|
||||
#pragma pack(push, 4)
|
||||
// Main command channel (level 5)
|
||||
struct CMD_Queue mcmd = {{"Mcmd"}, 0200,0,-1,0};
|
||||
// Operator command channel (level 4)
|
||||
struct CMD_Queue ocmd = {{"Ocmd"}, 0200,0,-1,0};
|
||||
// User command channel (level 2/3)
|
||||
struct CMD_Queue ucmd = {{"Ucmd"}, 0200,0,-1,0};
|
||||
|
||||
#define MSGLEN (80)
|
||||
static char msg[MSGLEN];
|
||||
#define PERR(...) do{snprintf(msg, MSGLEN, __VA_ARGS__); perror(msg);} while(0)
|
||||
|
||||
#ifndef BTA_MODULE
|
||||
volatile struct BTA_Data *sdt;
|
||||
volatile struct BTA_Local *sdtl;
|
||||
|
||||
volatile struct SHM_Block sdat = {
|
||||
{"Sdat"},
|
||||
sizeof(struct BTA_Data),
|
||||
2048,0444,
|
||||
SHM_RDONLY,
|
||||
bta_data_init,
|
||||
bta_data_check,
|
||||
bta_data_close,
|
||||
ClientSide,-1,NULL
|
||||
};
|
||||
|
||||
int snd_id = -1; // client sender ID
|
||||
int cmd_src_pid = 0; // next command source PID
|
||||
uint32_t cmd_src_ip = 0;// next command source IP
|
||||
|
||||
/**
|
||||
* Init data
|
||||
*/
|
||||
void bta_data_init() {
|
||||
sdt = (struct BTA_Data *)sdat.addr;
|
||||
sdtl = (struct BTA_Local *)(sdat.addr+sizeof(struct BTA_Data));
|
||||
if(sdat.side == ClientSide) {
|
||||
if(sdt->magic != sdat.key.code) {
|
||||
WARN("Wrong shared data (maybe server turned off)");
|
||||
}
|
||||
if(sdt->version == 0) {
|
||||
WARN("Null shared data version (maybe server turned off)");
|
||||
}
|
||||
else if(sdt->version != BTA_Data_Ver) {
|
||||
WARN("Wrong shared data version: I'am - %d, but server - %d ...",
|
||||
BTA_Data_Ver, sdt->version );
|
||||
}
|
||||
if(sdt->size != sdat.size) {
|
||||
if(sdt->size > sdat.size) {
|
||||
WARN("Wrong shared area size: I needs - %d, but server - %d ...",
|
||||
sdat.size, sdt->size );
|
||||
} else {
|
||||
WARN("Attention! Too little shared data structure!");
|
||||
WARN("I needs - %d, but server gives only %d ...",
|
||||
sdat.size, sdt->size );
|
||||
WARN("May be server's version too old!?");
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
/* ServerSide */
|
||||
if(sdt->magic == sdat.key.code &&
|
||||
sdt->version == BTA_Data_Ver &&
|
||||
sdt->size == sdat.size)
|
||||
return;
|
||||
memset(sdat.addr, 0, sdat.maxsize);
|
||||
sdt->magic = sdat.key.code;
|
||||
sdt->version = BTA_Data_Ver;
|
||||
sdt->size = sdat.size;
|
||||
Tel_Hardware = Hard_On;
|
||||
Pos_Corr = PC_On;
|
||||
TrkOk_Mode = UseDiffVel | UseDiffAZ ;
|
||||
inp_B = 591.;
|
||||
Pressure = 595.;
|
||||
PEP_code_A = 0x002aaa;
|
||||
PEP_code_Z = 0x002aaa;
|
||||
PEP_code_P = 0x002aaa;
|
||||
PEP_code_F = 0x002aaa;
|
||||
PEP_code_D = 0x002aaa;
|
||||
DomeSEW_N = 1;
|
||||
}
|
||||
|
||||
int bta_data_check() {
|
||||
return( (sdt->magic == sdat.key.code) && (sdt->version == BTA_Data_Ver) );
|
||||
}
|
||||
|
||||
void bta_data_close() {
|
||||
if(sdat.side == ServerSide) {
|
||||
sdt->magic = 0;
|
||||
sdt->version = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Allocate shared memory segment
|
||||
*/
|
||||
int get_shm_block(volatile struct SHM_Block *sb, int server) {
|
||||
int getsize = (server)? sb->maxsize : sb->size;
|
||||
// first try to find existing one
|
||||
sb->id = shmget(sb->key.code, getsize, sb->mode);
|
||||
if(sb->id < 0 && errno == ENOENT && server){
|
||||
// if no - try to create a new one
|
||||
int cresize = sb->maxsize;
|
||||
if(sb->size > cresize){
|
||||
WARN("Wrong shm maxsize(%d) < realsize(%d)",sb->maxsize,sb->size);
|
||||
cresize = sb->size;
|
||||
}
|
||||
sb->id = shmget(sb->key.code, cresize, IPC_CREAT|IPC_EXCL|sb->mode);
|
||||
}
|
||||
if(sb->id < 0){
|
||||
if(server)
|
||||
PERR("Can't create shared memory segment '%s'",sb->key.name);
|
||||
else
|
||||
PERR("Can't find shared segment '%s' (maybe no server process) ",sb->key.name);
|
||||
return 0;
|
||||
}
|
||||
// attach it to our memory space
|
||||
sb->addr = (unsigned char *) shmat(sb->id, NULL, sb->atflag);
|
||||
if((long)sb->addr == -1){
|
||||
PERR("Can't attach shared memory segment '%s'",sb->key.name);
|
||||
return 0;
|
||||
}
|
||||
if(server && (shmctl(sb->id, SHM_LOCK, NULL) < 0)){
|
||||
PERR("Can't prevents swapping of shared memory segment '%s'",sb->key.name);
|
||||
return 0;
|
||||
}
|
||||
DBG("Create & attach shared memory segment '%s' %dbytes", sb->key.name, sb->size);
|
||||
sb->side = server;
|
||||
if(sb->init != NULL)
|
||||
sb->init();
|
||||
return 1;
|
||||
}
|
||||
|
||||
int close_shm_block(volatile struct SHM_Block *sb){
|
||||
int ret;
|
||||
if(sb->close != NULL)
|
||||
sb->close();
|
||||
if(sb->side == ServerSide) {
|
||||
// ret = shmctl(sb->id, SHM_UNLOCK, NULL);
|
||||
ret = shmctl(sb->id, IPC_RMID, NULL);
|
||||
}
|
||||
ret = shmdt (sb->addr);
|
||||
return(ret);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create|Find command queue
|
||||
*/
|
||||
void get_cmd_queue(struct CMD_Queue *cq, int server){
|
||||
if (!server && cq->id >= 0) { //if already in use set current
|
||||
snd_id = cq->id;
|
||||
return;
|
||||
}
|
||||
// first try to find existing one
|
||||
cq->id = msgget(cq->key.code, cq->mode);
|
||||
// if no - try to create a new one
|
||||
if(cq->id<0 && errno == ENOENT && server)
|
||||
cq->id = msgget(cq->key.code, IPC_CREAT|IPC_EXCL|cq->mode);
|
||||
if(cq->id<0){
|
||||
if(server)
|
||||
PERR("Can't create comand queue '%s'",cq->key.name);
|
||||
else
|
||||
PERR("Can't find comand queue '%s' (maybe no server process) ",cq->key.name);
|
||||
return;
|
||||
}
|
||||
cq->side = server;
|
||||
if(server){
|
||||
char buf[120]; /* выбросить все команды из очереди */
|
||||
while(msgrcv(cq->id, (struct msgbuf *)buf, 112, 0, IPC_NOWAIT) > 0);
|
||||
}else
|
||||
snd_id = cq->id;
|
||||
cq->acckey = 0;
|
||||
}
|
||||
|
||||
#endif // BTA_MODULE
|
||||
|
||||
|
||||
int check_shm_block(volatile struct SHM_Block *sb) {
|
||||
if(sb->check)
|
||||
return(sb->check());
|
||||
else return(0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set access key in current channel
|
||||
*/
|
||||
void set_acckey(uint32_t newkey){
|
||||
if(snd_id < 0) return;
|
||||
if(ucmd.id == snd_id) ucmd.acckey = newkey;
|
||||
else if(ocmd.id == snd_id) ocmd.acckey = newkey;
|
||||
else if(mcmd.id == snd_id) mcmd.acckey = newkey;
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup source data for one following command if default values
|
||||
* (IP == 0 - local, PID = current) not suits
|
||||
*/
|
||||
void set_cmd_src(uint32_t ip, int pid) {
|
||||
cmd_src_pid = pid;
|
||||
cmd_src_ip = ip;
|
||||
}
|
||||
|
||||
#pragma pack(push, 4)
|
||||
/**
|
||||
* Send client commands to server
|
||||
*/
|
||||
void send_cmd(int cmd_code, char *buf, int size) {
|
||||
struct my_msgbuf mbuf;
|
||||
if(snd_id < 0) return;
|
||||
if(size > 100) size = 100;
|
||||
if(cmd_code > 0)
|
||||
mbuf.mtype = cmd_code;
|
||||
else
|
||||
return;
|
||||
if(ucmd.id == snd_id) mbuf.acckey = ucmd.acckey;
|
||||
else if(ocmd.id == snd_id) mbuf.acckey = ocmd.acckey;
|
||||
else if(mcmd.id == snd_id) mbuf.acckey = mcmd.acckey;
|
||||
|
||||
mbuf.src_pid = cmd_src_pid ? cmd_src_pid : getpid();
|
||||
mbuf.src_ip = cmd_src_ip;
|
||||
cmd_src_pid = cmd_src_ip = 0;
|
||||
|
||||
if(size > 0)
|
||||
memcpy(mbuf.mtext, buf, size);
|
||||
else {
|
||||
mbuf.mtext[0] = 0;
|
||||
size = 1;
|
||||
}
|
||||
msgsnd(snd_id, (struct msgbuf *)&mbuf, size+12, IPC_NOWAIT);
|
||||
}
|
||||
|
||||
void send_cmd_noarg(int cmd_code) {
|
||||
send_cmd(cmd_code, NULL, 0);
|
||||
}
|
||||
void send_cmd_str(int cmd_code, char *arg) {
|
||||
send_cmd(cmd_code, arg, strlen(arg)+1);
|
||||
}
|
||||
void send_cmd_i1(int cmd_code, int32_t arg1) {
|
||||
send_cmd(cmd_code, (char *)&arg1, sizeof(int32_t));
|
||||
}
|
||||
void send_cmd_i2(int cmd_code, int32_t arg1, int32_t arg2) {
|
||||
int32_t ibuf[2];
|
||||
ibuf[0] = arg1;
|
||||
ibuf[1] = arg2;
|
||||
send_cmd(cmd_code, (char *)ibuf, 2*sizeof(int32_t));
|
||||
}
|
||||
void send_cmd_i3(int cmd_code, int32_t arg1, int32_t arg2, int32_t arg3) {
|
||||
int32_t ibuf[3];
|
||||
ibuf[0] = arg1;
|
||||
ibuf[1] = arg2;
|
||||
ibuf[2] = arg3;
|
||||
send_cmd(cmd_code, (char *)ibuf, 3*sizeof(int32_t));
|
||||
}
|
||||
void send_cmd_i4(int cmd_code, int32_t arg1, int32_t arg2, int32_t arg3, int32_t arg4) {
|
||||
int32_t ibuf[4];
|
||||
ibuf[0] = arg1;
|
||||
ibuf[1] = arg2;
|
||||
ibuf[2] = arg3;
|
||||
ibuf[3] = arg4;
|
||||
send_cmd(cmd_code, (char *)ibuf, 4*sizeof(int32_t));
|
||||
}
|
||||
void send_cmd_d1(int32_t cmd_code, double arg1) {
|
||||
send_cmd(cmd_code, (char *)&arg1, sizeof(double));
|
||||
}
|
||||
void send_cmd_d2(int cmd_code, double arg1, double arg2) {
|
||||
double dbuf[2];
|
||||
dbuf[0] = arg1;
|
||||
dbuf[1] = arg2;
|
||||
send_cmd(cmd_code, (char *)dbuf, 2*sizeof(double));
|
||||
}
|
||||
void send_cmd_i1d1(int cmd_code, int32_t arg1, double arg2) {
|
||||
struct {
|
||||
int32_t ival;
|
||||
double dval;
|
||||
} buf;
|
||||
buf.ival = arg1;
|
||||
buf.dval = arg2;
|
||||
send_cmd(cmd_code, (char *)&buf, sizeof(buf));
|
||||
}
|
||||
void send_cmd_i2d1(int cmd_code, int32_t arg1, int32_t arg2, double arg3) {
|
||||
struct {
|
||||
int32_t ival[2];
|
||||
double dval;
|
||||
} buf;
|
||||
buf.ival[0] = arg1;
|
||||
buf.ival[1] = arg2;
|
||||
buf.dval = arg3;
|
||||
send_cmd(cmd_code, (char *)&buf, sizeof(buf));
|
||||
}
|
||||
void send_cmd_i3d1(int cmd_code, int32_t arg1, int32_t arg2, int32_t arg3, double arg4) {
|
||||
struct {
|
||||
int32_t ival[3];
|
||||
double dval;
|
||||
} buf;
|
||||
buf.ival[0] = arg1;
|
||||
buf.ival[1] = arg2;
|
||||
buf.ival[2] = arg3;
|
||||
buf.dval = arg4;
|
||||
send_cmd(cmd_code, (char *)&buf, sizeof(buf));
|
||||
}
|
||||
|
||||
void encode_lev_passwd(char *passwd, int nlev, uint32_t *keylev, uint32_t *codlev){
|
||||
char salt[4];
|
||||
char *encr;
|
||||
union {
|
||||
uint32_t ui;
|
||||
char c[4];
|
||||
} key, cod;
|
||||
sprintf(salt,"L%1d",nlev);
|
||||
encr = (char *)crypt(passwd, salt);
|
||||
cod.c[0] = encr[2];
|
||||
key.c[0] = encr[3];
|
||||
cod.c[1] = encr[4];
|
||||
key.c[1] = encr[5];
|
||||
cod.c[2] = encr[6];
|
||||
key.c[2] = encr[7];
|
||||
cod.c[3] = encr[8];
|
||||
key.c[3] = encr[9];
|
||||
*keylev = key.ui;
|
||||
*codlev = cod.ui;
|
||||
}
|
||||
|
||||
int find_lev_passwd(char *passwd, uint32_t *keylev, uint32_t *codlev){
|
||||
int nlev;
|
||||
for(nlev = 5; nlev > 0; --nlev){
|
||||
encode_lev_passwd(passwd, nlev, keylev, codlev);
|
||||
if(*codlev == code_Lev(nlev)) break;
|
||||
}
|
||||
return(nlev);
|
||||
}
|
||||
|
||||
int check_lev_passwd(char *passwd){
|
||||
uint32_t keylev,codlev;
|
||||
int nlev;
|
||||
nlev = find_lev_passwd(passwd, &keylev, &codlev);
|
||||
if(nlev > 0) set_acckey(keylev);
|
||||
return(nlev);
|
||||
}
|
||||
|
||||
#pragma pack(pop)
|
||||
853
Daemons/deprecated/weatherdaemon.deprecated/bta_shdata.h
Normal file
853
Daemons/deprecated/weatherdaemon.deprecated/bta_shdata.h
Normal file
@@ -0,0 +1,853 @@
|
||||
// Copyright: V.S. Shergin, vsher@sao.ru
|
||||
// fixed for x86_64 E.V. Emelianov, edward.emelianoff@gmail.com
|
||||
#pragma once
|
||||
#ifndef __BTA_SHDATA_H__
|
||||
#define __BTA_SHDATA_H__
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <unistd.h>
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
#include <sys/ipc.h>
|
||||
#include <sys/shm.h>
|
||||
#include <sys/msg.h>
|
||||
#include <errno.h>
|
||||
|
||||
#pragma pack(push, 4)
|
||||
/*
|
||||
* Shared memory block
|
||||
*/
|
||||
struct SHM_Block {
|
||||
union {
|
||||
char name[5]; // memory segment identificator
|
||||
key_t code;
|
||||
} key;
|
||||
int32_t size; // size of memory used
|
||||
int32_t maxsize; // size when created
|
||||
int32_t mode; // access mode (rwxrwxrwx)
|
||||
int32_t atflag; // connection mode (SHM_RDONLY or 0)
|
||||
void (*init)(); // init function
|
||||
int32_t (*check)(); // test function
|
||||
void (*close)(); // deinit function
|
||||
int32_t side; // connection type: client/server
|
||||
int32_t id; // connection identificator
|
||||
uint8_t *addr; // connection address
|
||||
};
|
||||
|
||||
extern volatile struct SHM_Block sdat;
|
||||
|
||||
/*
|
||||
* Command queue descriptor
|
||||
*/
|
||||
struct CMD_Queue {
|
||||
union {
|
||||
char name[5]; // queue key
|
||||
key_t code;
|
||||
} key;
|
||||
int32_t mode; // access mode (rwxrwxrwx)
|
||||
int32_t side; // connection type (Sender/Receiver - server/client)
|
||||
int32_t id; // connection identificator
|
||||
uint32_t acckey; // access key (for transmission from client to server)
|
||||
};
|
||||
|
||||
extern struct CMD_Queue mcmd;
|
||||
extern struct CMD_Queue ocmd;
|
||||
extern struct CMD_Queue ucmd;
|
||||
|
||||
void send_cmd_noarg(int);
|
||||
void send_cmd_str(int, char *);
|
||||
void send_cmd_i1(int, int32_t);
|
||||
void send_cmd_i2(int, int32_t, int32_t);
|
||||
void send_cmd_i3(int, int32_t, int32_t, int32_t);
|
||||
void send_cmd_i4(int, int32_t, int32_t, int32_t, int32_t);
|
||||
void send_cmd_d1(int, double);
|
||||
void send_cmd_d2(int, double, double);
|
||||
void send_cmd_i1d1(int, int32_t, double);
|
||||
void send_cmd_i2d1(int, int32_t, int32_t, double);
|
||||
void send_cmd_i3d1(int, int32_t, int32_t, int32_t, double);
|
||||
|
||||
/*******************************************************************************
|
||||
* Command list *
|
||||
*******************************************************************************/
|
||||
/* name code args type */
|
||||
// Stop telescope
|
||||
#define StopTel 1
|
||||
#define StopTeleskope() send_cmd_noarg( 1 )
|
||||
// High/low speed
|
||||
#define StartHS 2
|
||||
#define StartHighSpeed() send_cmd_noarg( 2 )
|
||||
#define StartLS 3
|
||||
#define StartLowSpeed() send_cmd_noarg( 3 )
|
||||
// Timer setup (Ch7_15 or SysTimer)
|
||||
#define SetTmr 4
|
||||
#define SetTimerMode(T) send_cmd_i1 ( 4, (int)(T))
|
||||
// Simulation (modeling) mode
|
||||
#define SetModMod 5
|
||||
#define SetModelMode(M) send_cmd_i1 ( 5, (int)(M))
|
||||
// Azimuth speed code
|
||||
#define SetCodA 6
|
||||
#define SetPKN_A(iA,sA) send_cmd_i2 ( 6, (int)(iA),(int)(sA))
|
||||
// Zenith speed code
|
||||
#define SetCodZ 7
|
||||
#define SetPKN_Z(iZ) send_cmd_i1 ( 7, (int)(iZ))
|
||||
// Parangle speed code
|
||||
#define SetCodP 8
|
||||
#define SetPKN_P(iP) send_cmd_i1 ( 8, (int)(iP))
|
||||
// Set Az velocity
|
||||
#define SetVA 9
|
||||
#define SetSpeedA(vA) send_cmd_d1 ( 9, (double)(vA))
|
||||
// Set Z velocity
|
||||
#define SetVZ 10
|
||||
#define SetSpeedZ(vZ) send_cmd_d1 (10, (double)(vZ))
|
||||
// Set P velocity
|
||||
#define SetVP 11
|
||||
#define SetSpeedP(vP) send_cmd_d1 (11, (double)(vP))
|
||||
// Set new polar coordinates
|
||||
#define SetAD 12
|
||||
#define SetRADec(Alp,Del) send_cmd_d2 (12, (double)(Alp),(double)(Del))
|
||||
// Set new azimutal coordinates
|
||||
#define SetAZ 13
|
||||
#define SetAzimZ(A,Z) send_cmd_d2 (13, (double)(A),(double)(Z))
|
||||
// Goto new object by polar coords
|
||||
#define GoToAD 14
|
||||
#define GoToObject() send_cmd_noarg(14 )
|
||||
// Start steering to object by polar coords
|
||||
#define MoveToAD 15
|
||||
#define MoveToObject() send_cmd_noarg(15 )
|
||||
// Go to object by azimutal coords
|
||||
#define GoToAZ 16
|
||||
#define GoToAzimZ() send_cmd_noarg(16 )
|
||||
// Set A&Z for simulation
|
||||
#define WriteAZ 17
|
||||
#define WriteModelAZ() send_cmd_noarg(17 )
|
||||
// Set P2 mode
|
||||
#define SetModP 18
|
||||
#define SetPMode(pmod) send_cmd_i1 (18, (int)(pmod))
|
||||
// Move(+-1)/Stop(0) P2
|
||||
#define P2Move 19
|
||||
#define MoveP2(dir) send_cmd_i1 (19, (int)(dir))
|
||||
// Move(+-2,+-1)/Stop(0) focus
|
||||
#define FocMove 20
|
||||
#define MoveFocus(speed,time) send_cmd_i1d1(20,(int)(speed),(double)(time))
|
||||
// Use/don't use pointing correction system
|
||||
#define UsePCorr 21
|
||||
#define SwitchPosCorr(pc_flag) send_cmd_i1 (21, (int)(pc_flag))
|
||||
// Tracking flags
|
||||
#define SetTrkFlags 22
|
||||
#define SetTrkOkMode(trk_flags) send_cmd_i1 (22, (int)(trk_flags))
|
||||
// Set focus (0 - primary, 1 - N1, 2 - N2)
|
||||
#define SetTFoc 23
|
||||
#define SetTelFocus(N) send_cmd_i1 ( 23, (int)(N))
|
||||
// Set intrinsic move parameters by RA/Decl
|
||||
#define SetVAD 24
|
||||
#define SetVelAD(VAlp,VDel) send_cmd_d2 (24, (double)(VAlp),(double)(VDel))
|
||||
// Reverse Azimuth direction when pointing
|
||||
#define SetRevA 25
|
||||
#define SetAzRevers(amod) send_cmd_i1 (25, (int)(amod))
|
||||
// Set P2 velocity
|
||||
#define SetVP2 26
|
||||
#define SetVelP2(vP2) send_cmd_d1 (26, (double)(vP2))
|
||||
// Set pointing target
|
||||
#define SetTarg 27
|
||||
#define SetSysTarg(Targ) send_cmd_i1 (27, (int)(Targ))
|
||||
// Send message to all clients (+write into protocol)
|
||||
#define SendMsg 28
|
||||
#define SendMessage(Mesg) send_cmd_str (28, (char *)(Mesg))
|
||||
// RA/Decl user correction
|
||||
#define CorrAD 29
|
||||
#define DoADcorr(dAlp,dDel) send_cmd_d2 (29, (double)(dAlp),(double)(dDel))
|
||||
// A/Z user correction
|
||||
#define CorrAZ 30
|
||||
#define DoAZcorr(dA,dZ) send_cmd_d2 (30, (double)(dA),(double)(dZ))
|
||||
// sec A/Z user correction speed
|
||||
#define SetVCAZ 31
|
||||
#define SetVCorr(vA,vZ) send_cmd_d2 (31, (double)(vA),(double)(vZ))
|
||||
// move P2 with given velocity for a given time
|
||||
#define P2MoveTo 32
|
||||
#define MoveP2To(vP2,time) send_cmd_d2 (32, (double)(vP2),(double)(time))
|
||||
// Go to t/Decl position
|
||||
#define GoToTD 33
|
||||
#define GoToSat() send_cmd_noarg (33 )
|
||||
// Move to t/Decl
|
||||
#define MoveToTD 34
|
||||
#define MoveToSat() send_cmd_noarg (34 )
|
||||
// Empty command for synchronisation
|
||||
#define NullCom 35
|
||||
#define SyncCom() send_cmd_noarg (35 )
|
||||
// Button "Start"
|
||||
#define StartTel 36
|
||||
#define StartTeleskope() send_cmd_noarg(36 )
|
||||
// Set telescope mode
|
||||
#define SetTMod 37
|
||||
#define SetTelMode(M) send_cmd_i1 ( 37, (int)(M))
|
||||
// Turn telescope on (oil etc)
|
||||
#define TelOn 38
|
||||
#define TeleskopeOn() send_cmd_noarg(38 )
|
||||
// Dome mode
|
||||
#define SetModD 39
|
||||
#define SetDomeMode(dmod) send_cmd_i1 (39, (int)(dmod))
|
||||
// Move(+-3,+-2,+-1)/Stop(0) dome
|
||||
#define DomeMove 40
|
||||
#define MoveDome(speed,time) send_cmd_i1d1(40,(int)(speed),(double)(time))
|
||||
// Set account password
|
||||
#define SetPass 41
|
||||
#define SetPasswd(LPass) send_cmd_str (41, (char *)(LPass))
|
||||
// Set code of access level
|
||||
#define SetLevC 42
|
||||
#define SetLevCode(Nlev,Cod) send_cmd_i2(42, (int)(Nlev),(int)(Cod))
|
||||
// Set key for access level
|
||||
#define SetLevK 43
|
||||
#define SetLevKey(Nlev,Key) send_cmd_i2(43, (int)(Nlev),(int)(Key))
|
||||
// Setup network
|
||||
#define SetNet 44
|
||||
#define SetNetAcc(Mask,Addr) send_cmd_i2(44, (int)(Mask),(int)(Addr))
|
||||
// Input meteo data
|
||||
#define SetMet 45
|
||||
#define SetMeteo(m_id,m_val) send_cmd_i1d1(45,(int)(m_id),(double)(m_val))
|
||||
// Cancel meteo data
|
||||
#define TurnMetOff 46
|
||||
#define TurnMeteoOff(m_id) send_cmd_i1 (46, (int)(m_id))
|
||||
// Set time correction (IERS DUT1=UT1-UTC)
|
||||
#define SetDUT1 47
|
||||
#define SetDtime(dT) send_cmd_d1 (47, (double)(dT))
|
||||
// Set polar motion (IERS polar motion)
|
||||
#define SetPM 48
|
||||
#define SetPolMot(Xp,Yp) send_cmd_d2 (48, (double)(Xp),(double)(Yp))
|
||||
// Get SEW parameter
|
||||
#define GetSEW 49
|
||||
#define GetSEWparam(Ndrv,Indx,Cnt) send_cmd_i3(49,(int)(Ndrv),(int)(Indx),(int)(Cnt))
|
||||
// Set SEW parameter
|
||||
#define PutSEW 50
|
||||
#define PutSEWparam(Ndrv,Indx,Key,Val) send_cmd_i4(50,(int)(Ndrv),(int)(Indx),(int)(Key),(int)(Val))
|
||||
// Set lock flags
|
||||
#define SetLocks 51
|
||||
#define SetLockFlags(f) send_cmd_i1 (SetLocks, (int)(f))
|
||||
// Clear lock flags
|
||||
#define ClearLocks 52
|
||||
#define ClearLockFlags(f) send_cmd_i1 (ClearLocks, (int)(f))
|
||||
// Set PEP-RK bits
|
||||
#define SetRKbits 53
|
||||
#define AddRKbits(f) send_cmd_i1 (SetRKbits, (int)(f))
|
||||
// Clear PEP-RK bits
|
||||
#define ClrRKbits 54
|
||||
#define ClearRKbits(f) send_cmd_i1 (ClrRKbits, (int)(f))
|
||||
// Set SEW dome motor number (for indication)
|
||||
#define SetSEWnd 55
|
||||
#define SetDomeDrive(ND) send_cmd_i1 (SetSEWnd, (int)(ND))
|
||||
// Turn SEW controllers of dome on/off
|
||||
#define SEWsDome 56
|
||||
#define DomeSEW(OnOff) send_cmd_i1 (SEWsDome, (int)(OnOff))
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
* BTA data structure definitions *
|
||||
*******************************************************************************/
|
||||
|
||||
#define ServPID (sdt->pid) // PID of main program
|
||||
// model
|
||||
#define UseModel (sdt->model) // model variants
|
||||
enum{
|
||||
NoModel = 0 // OFF
|
||||
,CheckModel // control motors by model
|
||||
,DriveModel // "blind" management without real sensors
|
||||
,FullModel // full model without telescope
|
||||
};
|
||||
// timer
|
||||
#define ClockType (sdt->timer) // which timer to use
|
||||
enum{
|
||||
Ch7_15 = 0 // Inner timer with synchronisation by CH7_15
|
||||
,SysTimer // System timer (synchronisation unknown)
|
||||
,ExtSynchro // External synchronisation (bta_time or xntpd)
|
||||
};
|
||||
// system
|
||||
#define Sys_Mode (sdt->system) // main system mode
|
||||
enum{
|
||||
SysStop = 0 // Stop
|
||||
,SysWait // Wait for start (pointing)
|
||||
,SysPointAZ // Pointing by A/Z
|
||||
,SysPointAD // Pointing by RA/Decl
|
||||
,SysTrkStop // Tracking stop
|
||||
,SysTrkStart // Start tracking (acceleration to nominal velocity)
|
||||
,SysTrkMove // Tracking move to object
|
||||
,SysTrkSeek // Tracking in seeking mode
|
||||
,SysTrkOk // Tracking OK
|
||||
,SysTrkCorr // Correction of tracking position
|
||||
,SysTest // Test
|
||||
};
|
||||
// sys_target
|
||||
#define Sys_Target (sdt->sys_target) // system pointing target
|
||||
enum{
|
||||
TagPosition = 0 // point by A/Z
|
||||
,TagObject // point by RA/Decl
|
||||
,TagNest // point to "nest"
|
||||
,TagZenith // point to zenith
|
||||
,TagHorizon // point to horizon
|
||||
,TagStatObj // point to statinary object (t/Decl)
|
||||
};
|
||||
// tel_focus
|
||||
#define Tel_Focus (sdt->tel_focus) // telescope focus type
|
||||
enum{
|
||||
Prime = 0
|
||||
,Nasmyth1
|
||||
,Nasmyth2
|
||||
};
|
||||
// PCS
|
||||
#define PosCor_Coeff (sdt->pc_coeff) // pointing correction system coefficients
|
||||
// tel_state
|
||||
#define Tel_State (sdt->tel_state) // telescope state
|
||||
#define Req_State (sdt->req_state) // required state
|
||||
enum{
|
||||
Stopping = 0
|
||||
,Pointing
|
||||
,Tracking
|
||||
};
|
||||
// tel_hard_state
|
||||
#define Tel_Hardware (sdt->tel_hard_state) // Power state
|
||||
enum{
|
||||
Hard_Off = 0
|
||||
,Hard_On
|
||||
};
|
||||
// tel_mode
|
||||
#define Tel_Mode (sdt->tel_mode) // telescope mode
|
||||
enum{
|
||||
Automatic = 0 // Automatic (normal) mode
|
||||
,Manual = 1 // manual mode
|
||||
,ZenHor = 2 // work when Z<5 || Z>80
|
||||
,A_Move = 4 // hand move by A
|
||||
,Z_Move = 8 // hand move by Z
|
||||
,Balance =0x10// balancing
|
||||
};
|
||||
// az_mode
|
||||
#define Az_Mode (sdt->az_mode) // azimuth reverce
|
||||
enum{
|
||||
Rev_Off = 0 // move by nearest way
|
||||
,Rev_On // move by longest way
|
||||
};
|
||||
// p2_state
|
||||
#define P2_State (sdt->p2_state) // P2 motor state
|
||||
#define P2_Mode (sdt->p2_req_mode)
|
||||
enum{
|
||||
P2_Off = 0 // Stop
|
||||
,P2_On // Guiding
|
||||
,P2_Plus // Move to +
|
||||
,P2_Minus = -2 // Move to -
|
||||
};
|
||||
// focus_state
|
||||
#define Foc_State (sdt->focus_state) // focus motor state
|
||||
enum{
|
||||
Foc_Hminus = -2// fast "-" move
|
||||
,Foc_Lminus // slow "-" move
|
||||
,Foc_Off // Off
|
||||
,Foc_Lplus // slow "+" move
|
||||
,Foc_Hplus // fast "+" move
|
||||
};
|
||||
// dome_state
|
||||
#define Dome_State (sdt->dome_state) // dome motors state
|
||||
enum{
|
||||
D_Hminus = -3 // speeds: low, medium, high
|
||||
,D_Mminus
|
||||
,D_Lminus
|
||||
,D_Off // off
|
||||
,D_Lplus
|
||||
,D_Mplus
|
||||
,D_Hplus
|
||||
,D_On = 7 // auto
|
||||
};
|
||||
// pcor_mode
|
||||
#define Pos_Corr (sdt->pcor_mode) // pointing correction mode
|
||||
enum{
|
||||
PC_Off = 0
|
||||
,PC_On
|
||||
};
|
||||
// trkok_mode
|
||||
#define TrkOk_Mode (sdt->trkok_mode) // tracking mode
|
||||
enum{
|
||||
UseDiffVel = 1 // Isodrome (correction by real motors speed)
|
||||
,UseDiffAZ = 2 // Tracking by coordinate difference
|
||||
,UseDFlt = 4 // Turn on digital filter
|
||||
};
|
||||
// input RA/Decl values
|
||||
#define InpAlpha (sdt->i_alpha)
|
||||
#define InpDelta (sdt->i_delta)
|
||||
// current source RA/Decl values
|
||||
#define SrcAlpha (sdt->s_alpha)
|
||||
#define SrcDelta (sdt->s_delta)
|
||||
// intrinsic object velocity
|
||||
#define VelAlpha (sdt->v_alpha)
|
||||
#define VelDelta (sdt->v_delta)
|
||||
// input A/Z values
|
||||
#define InpAzim (sdt->i_azim)
|
||||
#define InpZdist (sdt->i_zdist)
|
||||
// calculated values
|
||||
#define CurAlpha (sdt->c_alpha)
|
||||
#define CurDelta (sdt->c_delta)
|
||||
// current values (from sensors)
|
||||
#define tag_A (sdt->tag_a)
|
||||
#define tag_Z (sdt->tag_z)
|
||||
#define tag_P (sdt->tag_p)
|
||||
// calculated corrections
|
||||
#define pos_cor_A (sdt->pcor_a)
|
||||
#define pos_cor_Z (sdt->pcor_z)
|
||||
#define refract_Z (sdt->refr_z)
|
||||
// reverse calculation corr.
|
||||
#define tel_cor_A (sdt->tcor_a)
|
||||
#define tel_cor_Z (sdt->tcor_z)
|
||||
#define tel_ref_Z (sdt->tref_z)
|
||||
// coords difference
|
||||
#define Diff_A (sdt->diff_a)
|
||||
#define Diff_Z (sdt->diff_z)
|
||||
#define Diff_P (sdt->diff_p)
|
||||
// base object velocity
|
||||
#define vel_objA (sdt->vbasea)
|
||||
#define vel_objZ (sdt->vbasez)
|
||||
#define vel_objP (sdt->vbasep)
|
||||
// correction by real speed
|
||||
#define diff_vA (sdt->diffva)
|
||||
#define diff_vZ (sdt->diffvz)
|
||||
#define diff_vP (sdt->diffvp)
|
||||
// motor speed
|
||||
#define speedA (sdt->speeda)
|
||||
#define speedZ (sdt->speedz)
|
||||
#define speedP (sdt->speedp)
|
||||
// last precipitation time
|
||||
#define Precip_time (sdt->m_time_precip)
|
||||
// reserved
|
||||
#define Reserve (sdt->reserve)
|
||||
// real motor speed (''/sec)
|
||||
#define req_speedA (sdt->rspeeda)
|
||||
#define req_speedZ (sdt->rspeedz)
|
||||
#define req_speedP (sdt->rspeedp)
|
||||
// model speed
|
||||
#define mod_vel_A (sdt->simvela)
|
||||
#define mod_vel_Z (sdt->simvelz)
|
||||
#define mod_vel_P (sdt->simvelp)
|
||||
#define mod_vel_F (sdt->simvelf)
|
||||
#define mod_vel_D (sdt->simvelf)
|
||||
// telescope & hand correction state
|
||||
/*
|
||||
* 0x8000 - ÁÚÉÍÕÔ ÐÏÌÏÖÉÔÅÌØÎÙÊ
|
||||
* 0x4000 - ÏÔÒÁÂÏÔËÁ ×ËÌ.
|
||||
* 0x2000 - ÒÅÖÉÍ ×ÅÄÅÎÉÑ
|
||||
* 0x1000 - ÏÔÒÁÂÏÔËÁ P2 ×ËÌ.
|
||||
* 0x01F0 - ÓË.ËÏÒÒ. 0.2 0.4 1.0 2.0 5.0("/ÓÅË)
|
||||
* 0x000F - ÎÁÐÒ.ËÏÒÒ. +Z -Z +A -A
|
||||
*/
|
||||
#define code_KOST (sdt->kost)
|
||||
// different time (UTC, stellar, local)
|
||||
#define M_time (sdt->m_time)
|
||||
#define S_time (sdt->s_time)
|
||||
#define L_time (sdt->l_time)
|
||||
// PPNDD sensor (rough) code
|
||||
#define ppndd_A (sdt->ppndd_a)
|
||||
#define ppndd_Z (sdt->ppndd_z)
|
||||
#define ppndd_P (sdt->ppndd_p)
|
||||
#define ppndd_B (sdt->ppndd_b) // atm. pressure
|
||||
// DUP sensor (precise) code (Gray code)
|
||||
#define dup_A (sdt->dup_a)
|
||||
#define dup_Z (sdt->dup_z)
|
||||
#define dup_P (sdt->dup_p)
|
||||
#define dup_F (sdt->dup_f)
|
||||
#define dup_D (sdt->dup_d)
|
||||
// binary 14-digit precise code
|
||||
#define low_A (sdt->low_a)
|
||||
#define low_Z (sdt->low_z)
|
||||
#define low_P (sdt->low_p)
|
||||
#define low_F (sdt->low_f)
|
||||
#define low_D (sdt->low_d)
|
||||
// binary 23-digit rough code
|
||||
#define code_A (sdt->code_a)
|
||||
#define code_Z (sdt->code_z)
|
||||
#define code_P (sdt->code_p)
|
||||
#define code_B (sdt->code_b)
|
||||
#define code_F (sdt->code_f)
|
||||
#define code_D (sdt->code_d)
|
||||
// ADC PCL818 (8-channel) codes
|
||||
#define ADC(N) (sdt->adc[(N)])
|
||||
#define code_T1 ADC(0) // External temperature code
|
||||
#define code_T2 ADC(1) // In-dome temperature code
|
||||
#define code_T3 ADC(2) // Mirror temperature code
|
||||
#define code_Wnd ADC(3) // Wind speed code
|
||||
// calculated values
|
||||
#define val_A (sdt->val_a) // A, ''
|
||||
#define val_Z (sdt->val_z) // Z, ''
|
||||
#define val_P (sdt->val_p) // P, ''
|
||||
#define val_B (sdt->val_b) // atm. pressure, mm.hg.
|
||||
#define val_F (sdt->val_f) // focus, mm
|
||||
#define val_D (sdt->val_d) // Dome Az, ''
|
||||
#define val_T1 (sdt->val_t1) // ext. T, degrC
|
||||
#define val_T2 (sdt->val_t2) // in-dome T, degrC
|
||||
#define val_T3 (sdt->val_t3) // mirror T, degrC
|
||||
#define val_Wnd (sdt->val_wnd) // wind speed, m/s
|
||||
// RA/Decl calculated by A/Z
|
||||
#define val_Alp (sdt->val_alp)
|
||||
#define val_Del (sdt->val_del)
|
||||
// measured speed
|
||||
#define vel_A (sdt->vel_a)
|
||||
#define vel_Z (sdt->vel_z)
|
||||
#define vel_P (sdt->vel_p)
|
||||
#define vel_F (sdt->vel_f)
|
||||
#define vel_D (sdt->vel_d)
|
||||
// system messages queue
|
||||
#define MesgNum 3
|
||||
#define MesgLen 39
|
||||
// message type
|
||||
enum{
|
||||
MesgEmpty = 0
|
||||
,MesgInfor
|
||||
,MesgWarn
|
||||
,MesgFault
|
||||
,MesgLog
|
||||
};
|
||||
#define Sys_Mesg(N) (sdt->sys_msg_buf[N])
|
||||
// access levels
|
||||
#define code_Lev1 (sdt->code_lev[0]) // remote observer - only information
|
||||
#define code_Lev2 (sdt->code_lev[1]) // local observer - input coordinates
|
||||
#define code_Lev3 (sdt->code_lev[2]) // main observer - correction by A/Z, P2/F management
|
||||
#define code_Lev4 (sdt->code_lev[3]) // operator - start/stop telescope, testing
|
||||
#define code_Lev5 (sdt->code_lev[4]) // main operator - full access
|
||||
#define code_Lev(x) (sdt->code_lev[(x-1)])
|
||||
// network settings
|
||||
#define NetMask (sdt->netmask) // subnet mask (usually 255.255.255.0)
|
||||
#define NetWork (sdt->netaddr) // subnet address (for ex.: 192.168.3.0)
|
||||
#define ACSMask (sdt->acsmask) // ACS network mask (for ex.: 255.255.255.0)
|
||||
#define ACSNet (sdt->acsaddr) // ACS subnet address (for ex.: 192.168.13.0)
|
||||
// meteo data
|
||||
#define MeteoMode (sdt->meteo_stat)
|
||||
enum{
|
||||
INPUT_B = 1 // pressure
|
||||
,INPUT_T1 = 2 // external T
|
||||
,INPUT_T2 = 4 // in-dome T
|
||||
,INPUT_T3 = 8 // mirror T
|
||||
,INPUT_WND = 0x10 // wind speed
|
||||
,INPUT_HMD = 0x20 // humidity
|
||||
};
|
||||
#define SENSOR_B (INPUT_B <<8) // external data flags
|
||||
#define SENSOR_T1 (INPUT_T1 <<8)
|
||||
#define SENSOR_T2 (INPUT_T2 <<8)
|
||||
#define SENSOR_T3 (INPUT_T3 <<8)
|
||||
#define SENSOR_WND (INPUT_WND<<8)
|
||||
#define SENSOR_HMD (INPUT_HMD<<8)
|
||||
#define ADC_B (INPUT_B <<16) // reading from ADC flags
|
||||
#define ADC_T1 (INPUT_T1 <<16)
|
||||
#define ADC_T2 (INPUT_T2 <<16)
|
||||
#define ADC_T3 (INPUT_T3 <<16)
|
||||
#define ADC_WND (INPUT_WND<<16)
|
||||
#define ADC_HMD (INPUT_HMD<<16)
|
||||
#define NET_B (INPUT_B <<24) // got by network flags
|
||||
#define NET_T1 (INPUT_T1 <<24)
|
||||
#define NET_T3 (INPUT_T3 <<24)
|
||||
#define NET_WND (INPUT_WND<<24)
|
||||
#define NET_HMD (INPUT_HMD<<24)
|
||||
// input meteo values
|
||||
#define inp_B (sdt->inp_b) // atm.pressure (mm.hg)
|
||||
#define inp_T1 (sdt->inp_t1) // ext T
|
||||
#define inp_T2 (sdt->inp_t2) // in-dome T
|
||||
#define inp_T3 (sdt->inp_t3) // mirror T
|
||||
#define inp_Wnd (sdt->inp_wnd) // wind
|
||||
// values used for refraction calculation
|
||||
#define Temper (sdt->temper)
|
||||
#define Pressure (sdt->press)
|
||||
// last wind gust time
|
||||
#define Wnd10_time (sdt->m_time10)
|
||||
#define Wnd15_time (sdt->m_time15)
|
||||
// IERS DUT1
|
||||
#define DUT1 (sdt->dut1)
|
||||
// sensors reading time
|
||||
#define A_time (sdt->a_time)
|
||||
#define Z_time (sdt->z_time)
|
||||
#define P_time (sdt->p_time)
|
||||
// input speeds
|
||||
#define speedAin (sdt->speedain)
|
||||
#define speedZin (sdt->speedzin)
|
||||
#define speedPin (sdt->speedpin)
|
||||
// acceleration (''/sec^2)
|
||||
#define acc_A (sdt->acc_a)
|
||||
#define acc_Z (sdt->acc_z)
|
||||
#define acc_P (sdt->acc_p)
|
||||
#define acc_F (sdt->acc_f)
|
||||
#define acc_D (sdt->acc_d)
|
||||
// SEW code
|
||||
#define code_SEW (sdt->code_sew)
|
||||
// sew data
|
||||
#define statusSEW(Drv) (sdt->sewdrv[(Drv)-1].status)
|
||||
#define statusSEW1 (sdt->sewdrv[0].status)
|
||||
#define statusSEW2 (sdt->sewdrv[1].status)
|
||||
#define statusSEW3 (sdt->sewdrv[2].status)
|
||||
#define speedSEW(Drv) (sdt->sewdrv[(Drv)-1].set_speed)
|
||||
#define speedSEW1 (sdt->sewdrv[0].set_speed)
|
||||
#define speedSEW2 (sdt->sewdrv[1].set_speed)
|
||||
#define speedSEW3 (sdt->sewdrv[2].set_speed)
|
||||
#define vel_SEW(Drv) (sdt->sewdrv[(Drv)-1].mes_speed)
|
||||
#define vel_SEW1 (sdt->sewdrv[0].mes_speed)
|
||||
#define vel_SEW2 (sdt->sewdrv[1].mes_speed)
|
||||
#define vel_SEW3 (sdt->sewdrv[2].mes_speed)
|
||||
#define currentSEW(Drv) (sdt->sewdrv[(Drv)-1].current)
|
||||
#define currentSEW1 (sdt->sewdrv[0].current)
|
||||
#define currentSEW2 (sdt->sewdrv[1].current)
|
||||
#define currentSEW3 (sdt->sewdrv[2].current)
|
||||
#define indexSEW(Drv) (sdt->sewdrv[(Drv)-1].index)
|
||||
#define indexSEW1 (sdt->sewdrv[0].index)
|
||||
#define indexSEW2 (sdt->sewdrv[1].index)
|
||||
#define indexSEW3 (sdt->sewdrv[2].index)
|
||||
#define valueSEW(Drv) (sdt->sewdrv[(Drv)-1].value.l)
|
||||
#define valueSEW1 (sdt->sewdrv[0].value.l)
|
||||
#define valueSEW2 (sdt->sewdrv[1].value.l)
|
||||
#define valueSEW3 (sdt->sewdrv[2].value.l)
|
||||
#define bvalSEW(Drv,Nb) (sdt->sewdrv[(Drv)-1].value.b[Nb])
|
||||
// 23-digit PEP-controllers code
|
||||
#define PEP_code_A (sdt->pep_code_a)
|
||||
#define PEP_code_Z (sdt->pep_code_z)
|
||||
#define PEP_code_P (sdt->pep_code_p)
|
||||
// PEP end-switches code
|
||||
#define switch_A (sdt->pep_sw_a)
|
||||
enum{
|
||||
Sw_minus_A = 1 // negative A value
|
||||
,Sw_plus240_A = 2 // end switch +240degr
|
||||
,Sw_minus240_A = 4 // end switch -240degr
|
||||
,Sw_minus45_A = 8 // "horizon" end switch
|
||||
};
|
||||
#define switch_Z (sdt->pep_sw_z)
|
||||
enum{
|
||||
Sw_0_Z = 1
|
||||
,Sw_5_Z = 2
|
||||
,Sw_20_Z = 4
|
||||
,Sw_60_Z = 8
|
||||
,Sw_80_Z = 0x10
|
||||
,Sw_90_Z = 0x20
|
||||
};
|
||||
#define switch_P (sdt->pep_sw_p)
|
||||
enum{
|
||||
Sw_No_P = 0 // no switches
|
||||
,Sw_22_P = 1 // 22degr
|
||||
,Sw_89_P = 2 // 89degr
|
||||
,Sw_Sm_P = 0x80 // Primary focus smoke sensor
|
||||
};
|
||||
// PEP codes
|
||||
#define PEP_code_F (sdt->pep_code_f)
|
||||
#define PEP_code_D (sdt->pep_code_d)
|
||||
#define PEP_code_Rin (sdt->pep_code_ri)
|
||||
#define PEP_code_Rout (sdt->pep_code_ro)
|
||||
// PEP flags
|
||||
#define PEP_A_On (sdt->pep_on[0])
|
||||
#define PEP_A_Off (PEP_A_On==0)
|
||||
#define PEP_Z_On (sdt->pep_on[1])
|
||||
#define PEP_Z_Off (PEP_Z_On==0)
|
||||
#define PEP_P_On (sdt->pep_on[2])
|
||||
#define PEP_P_Off (PEP_P_On==0)
|
||||
#define PEP_F_On (sdt->pep_on[3])
|
||||
#define PEP_F_Off (PEP_F_On==0)
|
||||
#define PEP_D_On (sdt->pep_on[4])
|
||||
#define PEP_D_Off (PEP_D_On==0)
|
||||
#define PEP_R_On (sdt->pep_on[5])
|
||||
#define PEP_R_Off ((PEP_R_On&1)==0)
|
||||
#define PEP_R_Inp ((PEP_R_On&2)!=0)
|
||||
#define PEP_K_On (sdt->pep_on[6])
|
||||
#define PEP_K_Off ((PEP_K_On&1)==0)
|
||||
#define PEP_K_Inp ((PEP_K_On&2)!=0)
|
||||
// IERS polar motion
|
||||
#define polarX (sdt->xpol)
|
||||
#define polarY (sdt->ypol)
|
||||
// current Julian date, sidereal time correction by "Equation of the Equinoxes"
|
||||
#define JDate (sdt->jdate)
|
||||
#define EE_time (sdt->eetime)
|
||||
// humidity value (%%) & hand input
|
||||
#define val_Hmd (sdt->val_hmd)
|
||||
#define inp_Hmd (sdt->val_hmd)
|
||||
// worm position, mkm
|
||||
#define worm_A (sdt->worm_a)
|
||||
#define worm_Z (sdt->worm_z)
|
||||
// locking flags
|
||||
#define LockFlags (sdt->lock_flags)
|
||||
enum{
|
||||
Lock_A = 1
|
||||
,Lock_Z = 2
|
||||
,Lock_P = 4
|
||||
,Lock_F = 8
|
||||
,Lock_D = 0x10
|
||||
};
|
||||
#define A_Locked (LockFlags&Lock_A)
|
||||
#define Z_Locked (LockFlags&Lock_Z)
|
||||
#define P_Locked (LockFlags&Lock_P)
|
||||
#define F_Locked (LockFlags&Lock_F)
|
||||
#define D_Locked (LockFlags&Lock_D)
|
||||
// SEW dome divers speed
|
||||
#define Dome_Speed (sdt->sew_dome_speed)
|
||||
// SEW dome drive number (for indication)
|
||||
#define DomeSEW_N (sdt->sew_dome_num)
|
||||
// SEW dome driver parameters
|
||||
#define statusSEWD (sdt->sewdomedrv.status) // controller status
|
||||
#define speedSEWD (sdt->sewdomedrv.set_speed) // speed, rpm
|
||||
#define vel_SEWD (sdt->sewdomedrv.mes_speed) /*ÉÚÍÅÒÅÎÎÁÑ ÓËÏÒÏÓÔØ ÏÂ/ÍÉÎ (rpm)*/
|
||||
#define currentSEWD (sdt->sewdomedrv.current) // current, A
|
||||
#define indexSEWD (sdt->sewdomedrv.index) // parameter index
|
||||
#define valueSEWD (sdt->sewdomedrv.value.l) // parameter value
|
||||
// dome PEP codes
|
||||
#define PEP_code_Din (sdt->pep_code_di) // data in
|
||||
#define PEP_Dome_SEW_Ok 0x200
|
||||
#define PEP_Dome_Cable_Ok 0x100
|
||||
#define PEP_code_Dout (sdt->pep_code_do) // data out
|
||||
#define PEP_Dome_SEW_On 0x10
|
||||
#define PEP_Dome_SEW_Off 0x20
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
* BTA data structure *
|
||||
*******************************************************************************/
|
||||
|
||||
#define BTA_Data_Ver 2
|
||||
struct BTA_Data {
|
||||
int32_t magic; // magic value
|
||||
int32_t version; // BTA_Data_Ver
|
||||
int32_t size; // sizeof(struct BTA_Data)
|
||||
int32_t pid; // main process PID
|
||||
int32_t model; // model modes
|
||||
int32_t timer; // timer selected
|
||||
int32_t system; // main system mode
|
||||
int32_t sys_target; // system pointing target
|
||||
int32_t tel_focus; // telescope focus type
|
||||
double pc_coeff[8]; // pointing correction system coefficients
|
||||
int32_t tel_state; // telescope state
|
||||
int32_t req_state; // new (required) state
|
||||
int32_t tel_hard_state; // Power state
|
||||
int32_t tel_mode; // telescope mode
|
||||
int32_t az_mode; // azimuth reverce
|
||||
int32_t p2_state; // P2 motor state
|
||||
int32_t p2_req_mode; // P2 required state
|
||||
int32_t focus_state; // focus motor state
|
||||
int32_t dome_state; // dome motors state
|
||||
int32_t pcor_mode; // pointing correction mode
|
||||
int32_t trkok_mode; // tracking mode
|
||||
double i_alpha, i_delta; // input values
|
||||
double s_alpha, s_delta; // source
|
||||
double v_alpha, v_delta; // intrinsic vel.
|
||||
double i_azim, i_zdist; // input A/Z
|
||||
double c_alpha, c_delta; // calculated values
|
||||
double tag_a, tag_z, tag_p; // current values (from sensors)
|
||||
double pcor_a, pcor_z, refr_z; // calculated corrections
|
||||
double tcor_a, tcor_z, tref_z; // reverse calculation corr.
|
||||
double diff_a, diff_z, diff_p; // coords difference
|
||||
double vbasea,vbasez,vbasep; // base object velocity
|
||||
double diffva,diffvz,diffvp; // correction by real speed
|
||||
double speeda,speedz,speedp; // motor speed
|
||||
double m_time_precip; // last precipitation time
|
||||
uint8_t reserve[16]; // reserved
|
||||
double rspeeda, rspeedz, rspeedp; // real motor speed (''/sec)
|
||||
double simvela, simvelz, simvelp, simvelf, simveld; // model speed
|
||||
uint32_t kost; // telescope & hand correction state
|
||||
double m_time, s_time, l_time; // different time (UTC, stellar, local)
|
||||
uint32_t ppndd_a, ppndd_z, ppndd_p, ppndd_b; // PPNDD sensor (rough) code
|
||||
uint32_t dup_a, dup_z, dup_p, dup_f, dup_d; // DUP sensor (precise) code (Gray code)
|
||||
uint32_t low_a, low_z, low_p, low_f, low_d; // binary 14-digit precise code
|
||||
uint32_t code_a, code_z, code_p, code_b, code_f, code_d; // binary 23-digit rough code
|
||||
uint32_t adc[8]; // ADC PCL818 (8-channel) codes
|
||||
double val_a, val_z, val_p, val_b, val_f, val_d;
|
||||
double val_t1, val_t2, val_t3, val_wnd; // calculated values
|
||||
double val_alp, val_del; // RA/Decl calculated by A/Z
|
||||
double vel_a, vel_z, vel_p, vel_f, vel_d; // measured speed
|
||||
// system messages queue
|
||||
struct SysMesg {
|
||||
int32_t seq_num;
|
||||
char type; // message type
|
||||
char text[MesgLen]; // message itself
|
||||
} sys_msg_buf[MesgNum];
|
||||
// access levels
|
||||
uint32_t code_lev[5];
|
||||
// network settings
|
||||
uint32_t netmask, netaddr, acsmask, acsaddr;
|
||||
int32_t meteo_stat; // meteo data
|
||||
double inp_b, inp_t1, inp_t2, inp_t3, inp_wnd; // input meteo values
|
||||
double temper, press; // values used for refraction calculation
|
||||
double m_time10, m_time15; // last wind gust time
|
||||
double dut1; // IERS DUT1 (src: ftp://maia.usno.navy.mil/ser7/ser7.dat), DUT1 = UT1-UTC
|
||||
double a_time, z_time, p_time; // sensors reading time
|
||||
double speedain, speedzin, speedpin; // input speeds
|
||||
double acc_a, acc_z, acc_p, acc_f, acc_d; // acceleration (''/sec^2)
|
||||
uint32_t code_sew; // SEW code
|
||||
struct SEWdata { // sew data
|
||||
int32_t status;
|
||||
double set_speed; // target speed, rpm
|
||||
double mes_speed; // measured speed, rpm
|
||||
double current; // measured current, A
|
||||
int32_t index; // parameter number
|
||||
union{ // parameter code
|
||||
uint8_t b[4];
|
||||
uint32_t l;
|
||||
} value;
|
||||
} sewdrv[3];
|
||||
uint32_t pep_code_a, pep_code_z, pep_code_p; // 23-digit PEP-controllers code
|
||||
uint32_t pep_sw_a, pep_sw_z, pep_sw_p; // PEP end-switches code
|
||||
uint32_t pep_code_f, pep_code_d, pep_code_ri, pep_code_ro; // PEP codes
|
||||
uint8_t pep_on[10]; // PEP flags
|
||||
double xpol, ypol; // IERS polar motion (src: ftp://maia.usno.navy.mil/ser7/ser7.dat)
|
||||
double jdate, eetime; // current Julian date, sidereal time correction by "Equation of the Equinoxes"
|
||||
double val_hmd, inp_hmd; // humidity value (%%) & hand input
|
||||
double worm_a, worm_z; // worm position, mkm
|
||||
/* ÆÌÁÇÉ ÂÌÏËÉÒÏ×ËÉ ÕÐÒÁ×ÌÅÎÉÑ ÕÚÌÁÍÉ */
|
||||
uint32_t lock_flags; // locking flags
|
||||
int32_t sew_dome_speed; // SEW dome divers speed: D_Lplus, D_Hminus etc
|
||||
int32_t sew_dome_num; // SEW dome drive number (for indication)
|
||||
struct SEWdata sewdomedrv; // SEW dome driver parameters
|
||||
uint32_t pep_code_di, pep_code_do; // dome PEP codes
|
||||
};
|
||||
|
||||
extern volatile struct BTA_Data *sdt;
|
||||
|
||||
/*******************************************************************************
|
||||
* Local data structure *
|
||||
*******************************************************************************/
|
||||
// Oil pressure, MPa
|
||||
#define PressOilA (sdtl->pr_oil_a)
|
||||
#define PressOilZ (sdtl->pr_oil_z)
|
||||
#define PressOilTank (sdtl->pr_oil_t)
|
||||
// Oil themperature, degrC
|
||||
#define OilTemper1 (sdtl->t_oil_1) // oil
|
||||
#define OilTemper2 (sdtl->t_oil_2) // water
|
||||
|
||||
// Local data structure
|
||||
struct BTA_Local {
|
||||
uint8_t reserve[120]; // reserved data
|
||||
double pr_oil_a,pr_oil_z,pr_oil_t; // Oil pressure
|
||||
double t_oil_1,t_oil_2; // Oil themperature
|
||||
};
|
||||
|
||||
/**
|
||||
* Message buffer structure
|
||||
*/
|
||||
struct my_msgbuf {
|
||||
int32_t mtype; // message type
|
||||
uint32_t acckey; // client access key
|
||||
uint32_t src_pid; // source PID
|
||||
uint32_t src_ip; // IP of command source or 0 for local
|
||||
char mtext[100]; // message itself
|
||||
};
|
||||
|
||||
extern volatile struct BTA_Local *sdtl;
|
||||
extern int snd_id;
|
||||
extern int cmd_src_pid;
|
||||
extern uint32_t cmd_src_ip;
|
||||
|
||||
#define ClientSide 0
|
||||
#define ServerSide 1
|
||||
|
||||
#ifndef BTA_MODULE
|
||||
void bta_data_init();
|
||||
int bta_data_check();
|
||||
void bta_data_close();
|
||||
int get_shm_block(volatile struct SHM_Block *sb, int server);
|
||||
int close_shm_block(volatile struct SHM_Block *sb);
|
||||
void get_cmd_queue(struct CMD_Queue *cq, int server);
|
||||
#endif
|
||||
|
||||
int check_shm_block(volatile struct SHM_Block *sb);
|
||||
|
||||
void encode_lev_passwd(char *passwd, int nlev, uint32_t *keylev, uint32_t *codlev);
|
||||
int find_lev_passwd(char *passwd, uint32_t *keylev, uint32_t *codlev);
|
||||
int check_lev_passwd(char *passwd);
|
||||
void set_acckey(uint32_t newkey);
|
||||
|
||||
// restore packing
|
||||
#pragma pack(pop)
|
||||
//#pragma GCC diagnostic pop
|
||||
|
||||
#endif // __BTA_SHDATA_H__
|
||||
24
Daemons/deprecated/weatherdaemon.deprecated/chkweather
Normal file
24
Daemons/deprecated/weatherdaemon.deprecated/chkweather
Normal file
@@ -0,0 +1,24 @@
|
||||
#!/bin/bash
|
||||
|
||||
badsky=1700
|
||||
[ $# = 1 ] && badsky=$1
|
||||
|
||||
export http_proxy=""
|
||||
|
||||
Q="192.168.70.33:12345"
|
||||
ANS=$(curl $Q 2>/dev/null)
|
||||
retval=$?
|
||||
[ $retval -ne "0" ] && exit $retval
|
||||
[ "$ANS" = "No data" ] && exit 2
|
||||
Rain=1
|
||||
Clouds=0
|
||||
Wind=100
|
||||
eval $ANS
|
||||
retval=0
|
||||
clouds=$(echo "$Clouds" | sed 's/\..*//g')
|
||||
wind=$(echo "$Wind" | sed 's/\..*//g')
|
||||
[ $Rain -ne "0" ] && retval=1
|
||||
[ $clouds -lt "$badsky" ] && retval=1
|
||||
[ $wind -gt "15" ] && retval=1
|
||||
echo "$ANS"
|
||||
exit $retval
|
||||
93
Daemons/deprecated/weatherdaemon.deprecated/cmdlnopts.c
Normal file
93
Daemons/deprecated/weatherdaemon.deprecated/cmdlnopts.c
Normal file
@@ -0,0 +1,93 @@
|
||||
/*
|
||||
* This file is part of the weatherdaemon project.
|
||||
* Copyright 2021 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 <assert.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <strings.h>
|
||||
#include <math.h>
|
||||
#include <usefull_macros.h>
|
||||
#include "cmdlnopts.h"
|
||||
#include "term.h"
|
||||
|
||||
/*
|
||||
* here are global parameters initialisation
|
||||
*/
|
||||
int help;
|
||||
static glob_pars G;
|
||||
|
||||
// default values for Gdefault & help
|
||||
#define DEFAULT_PORT "12345"
|
||||
#define DEFAULT_PID "/tmp/weatherdaemon.pid"
|
||||
|
||||
// DEFAULTS
|
||||
// default global parameters
|
||||
glob_pars const Gdefault = {
|
||||
.device = NULL,
|
||||
.port = DEFAULT_PORT,
|
||||
.logfile = NULL,
|
||||
.verb = 0,
|
||||
.tty_speed = 9600,
|
||||
.rest_pars = NULL,
|
||||
.rest_pars_num = 0,
|
||||
.emul = 0,
|
||||
.pidfile = DEFAULT_PID
|
||||
};
|
||||
|
||||
/*
|
||||
* 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)")},
|
||||
{"verb", NO_ARGS, NULL, 'v', arg_none, APTR(&G.verb), _("logfile verbocity level (each -v increase it)")},
|
||||
{"baudrate",NEED_ARG, NULL, 'b', arg_int, APTR(&G.tty_speed), _("serial terminal baudrate (default: 9600)")},
|
||||
{"emulation",NO_ARGS, NULL, 'e', arg_int, APTR(&G.emul), _("emulate serial device")},
|
||||
{"pidfile", NEED_ARG, NULL, 'P', arg_string, APTR(&G.pidfile), _("pidfile name (default: " DEFAULT_PID ")")},
|
||||
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;
|
||||
}
|
||||
|
||||
44
Daemons/deprecated/weatherdaemon.deprecated/cmdlnopts.h
Normal file
44
Daemons/deprecated/weatherdaemon.deprecated/cmdlnopts.h
Normal file
@@ -0,0 +1,44 @@
|
||||
/*
|
||||
* This file is part of the weatherdaemon project.
|
||||
* Copyright 2021 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
|
||||
#ifndef __CMDLNOPTS_H__
|
||||
#define __CMDLNOPTS_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 verb; // verbocity level
|
||||
int tty_speed; // serial terminal baudrate
|
||||
int emul; // emulation of serial device
|
||||
char *pidfile; // pidfile name
|
||||
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__
|
||||
90
Daemons/deprecated/weatherdaemon.deprecated/main.c
Normal file
90
Daemons/deprecated/weatherdaemon.deprecated/main.c
Normal file
@@ -0,0 +1,90 @@
|
||||
/*
|
||||
* This file is part of the weatherdaemon project.
|
||||
* Copyright 2021 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 <signal.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <sys/wait.h> // wait
|
||||
#include <sys/prctl.h> //prctl
|
||||
#include <usefull_macros.h>
|
||||
|
||||
#include "bta_shdata.h"
|
||||
#include "cmdlnopts.h"
|
||||
#include "socket.h"
|
||||
#include "term.h"
|
||||
|
||||
glob_pars *GP;
|
||||
|
||||
void signals(int signo){
|
||||
restore_console();
|
||||
if(ttydescr) close_tty(&ttydescr);
|
||||
LOGERR("exit with status %d", signo);
|
||||
exit(signo);
|
||||
}
|
||||
|
||||
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
|
||||
#ifndef EBUG
|
||||
char *self = strdup(argv[0]);
|
||||
#endif
|
||||
GP = parse_args(argc, argv);
|
||||
if(GP->logfile){
|
||||
sl_loglevel lvl = LOGLEVEL_ERR;
|
||||
for(; GP->verb && lvl < LOGLEVEL_ANY; --GP->verb) ++lvl;
|
||||
DBG("Loglevel: %d", lvl);
|
||||
if(!OPENLOG(GP->logfile, lvl, 1)) ERRX("Can't open log file");
|
||||
LOGERR("Started");
|
||||
}
|
||||
#ifndef EBUG
|
||||
if(daemon(1, 0)){
|
||||
ERR("daemon()");
|
||||
}
|
||||
check4running(self, GP->pidfile);
|
||||
while(1){ // guard for dead processes
|
||||
pid_t childpid = fork();
|
||||
if(childpid){
|
||||
LOGDBG("create child with PID %d\n", childpid);
|
||||
DBG("Created child with PID %d\n", childpid);
|
||||
wait(NULL);
|
||||
WARNX("Child %d died\n", childpid);
|
||||
LOGWARN("Child %d died\n", childpid);
|
||||
sleep(1);
|
||||
}else{
|
||||
prctl(PR_SET_PDEATHSIG, SIGTERM); // send SIGTERM to child when parent dies
|
||||
break; // go out to normal functional
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
if(!get_shm_block( &sdat, ClientSide)) WARNX("Can't get BTA shared memory block");
|
||||
if(GP->device) if(!try_connect(GP->device, GP->tty_speed)){
|
||||
LOGERR("Can't connect to device");
|
||||
ERRX("Can't connect to device");
|
||||
}
|
||||
if(!GP->device && !GP->emul){
|
||||
LOGERR("Need serial device name or emulation flag");
|
||||
ERRX("Need serial device name or emulation flag");
|
||||
}
|
||||
daemonize(GP->port);
|
||||
return 0;
|
||||
}
|
||||
347
Daemons/deprecated/weatherdaemon.deprecated/socket.c
Normal file
347
Daemons/deprecated/weatherdaemon.deprecated/socket.c
Normal file
@@ -0,0 +1,347 @@
|
||||
/*
|
||||
* This file is part of the weatherdaemon project.
|
||||
* Copyright 2021 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 <netdb.h> // addrinfo
|
||||
#include <arpa/inet.h> // inet_ntop
|
||||
#include <limits.h> // INT_xxx
|
||||
#include <poll.h> // poll
|
||||
#include <pthread.h>
|
||||
#include <signal.h> // pthread_kill
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <sys/syscall.h> // syscall
|
||||
#include <unistd.h> // daemon
|
||||
#include <usefull_macros.h>
|
||||
|
||||
#include "cmdlnopts.h" // glob_pars
|
||||
#include "socket.h"
|
||||
#include "term.h"
|
||||
|
||||
// temporary buffers
|
||||
#define BUFLEN (1024)
|
||||
// Max amount of connections
|
||||
#define BACKLOG (30)
|
||||
|
||||
extern glob_pars *GP;
|
||||
|
||||
static char *answer = NULL;
|
||||
static int freshdata = 0;
|
||||
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
|
||||
|
||||
/**************** SERVER FUNCTIONS ****************/
|
||||
/**
|
||||
* 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, 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()");
|
||||
LOGWARN("sprintf()");
|
||||
return 0;
|
||||
}
|
||||
if(L != write(sock, tbuf, L)){
|
||||
LOGWARN("Can't write header");
|
||||
WARN("write");
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
// send data
|
||||
//DBG("send %zd bytes\nBUF: %s", Len, buf);
|
||||
if(Len != write(sock, textbuf, Len)){
|
||||
WARN("write()");
|
||||
LOGERR("send_data(): write() failed");
|
||||
return 0;
|
||||
}
|
||||
//LOGDBG("fd %d, write %s", sock, textbuf);
|
||||
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;
|
||||
return a;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief handle_socket - read information from socket
|
||||
* @param sock - socket fd
|
||||
* @param chkheader - ==1 on first run
|
||||
* @return 1 if socket closed
|
||||
*/
|
||||
static int handle_socket(int sock, int notchkhdr){
|
||||
FNAME();
|
||||
int webquery = 0; // whether query is web or regular
|
||||
char buff[BUFLEN];
|
||||
ssize_t rd;
|
||||
if(!(rd = read(sock, buff, BUFLEN-1))){
|
||||
//LOGMSG("Client %d closed", sock);
|
||||
return 1;
|
||||
}
|
||||
//LOG("client send %zd bytes", rd);
|
||||
DBG("Got %zd bytes", rd);
|
||||
if(rd < 0){ // error
|
||||
LOGWARN("Client %d close socket on error", sock);
|
||||
DBG("Nothing to read from fd %d (ret: %zd)", sock, rd);
|
||||
return 1;
|
||||
}
|
||||
// add trailing zero to be on the safe side
|
||||
buff[rd] = 0;
|
||||
// now we should check what do user want
|
||||
char *found = buff;
|
||||
DBG("user send: %s", buff);
|
||||
if(!notchkhdr){
|
||||
if(0 == strncmp(buff, "GET", 3)){
|
||||
DBG("GET");
|
||||
// GET web query have format GET /some.resource
|
||||
webquery = 1;
|
||||
char *slash = strchr(buff, '/');
|
||||
if(slash){
|
||||
found = slash + 1;
|
||||
char *eol = strstr(found, "HTTP");
|
||||
if(eol) *eol = 0;
|
||||
}
|
||||
}else if(0 == strncmp(buff, "POST", 4)){
|
||||
DBG("POST");
|
||||
webquery = 1;
|
||||
// search content length of POST query
|
||||
char *cl = stringscan(buff, "Content-Length:");
|
||||
if(cl){
|
||||
int contlen = atoi(cl);
|
||||
int l = strlen(buff);
|
||||
if(contlen && l > contlen) found = &buff[l - contlen];
|
||||
}
|
||||
}
|
||||
}
|
||||
// here we can process user data
|
||||
DBG("found=%s", found);
|
||||
LOGDBG("sockfd=%d, got %s", sock, buff);
|
||||
if(GP->echo){
|
||||
if(!send_data(sock, webquery, found)){
|
||||
LOGWARN("Can't send data, some error occured");
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
if(answer) send_data(sock, webquery, answer);
|
||||
else send_data(sock, webquery, "No data\n");
|
||||
if(webquery) return 1; // close web query after message processing
|
||||
return 0;
|
||||
}
|
||||
|
||||
// main socket server
|
||||
static void *server(void *asock){
|
||||
LOGMSG("server()");
|
||||
int sock = *((int*)asock);
|
||||
if(listen(sock, BACKLOG) == -1){
|
||||
LOGERR("listen() failed");
|
||||
WARN("listen");
|
||||
return NULL;
|
||||
}
|
||||
int nfd = 1; // current fd amount in poll_set
|
||||
struct pollfd poll_set[MAX_FDS];
|
||||
int notchkhdr[MAX_FDS];
|
||||
memset(poll_set, 0, sizeof(poll_set));
|
||||
memset(notchkhdr, 0, sizeof(notchkhdr));
|
||||
poll_set[0].fd = sock;
|
||||
poll_set[0].events = POLLIN;
|
||||
double lastdatat = dtime();
|
||||
while(1){
|
||||
poll(poll_set, nfd, 1); // poll for 1ms
|
||||
for(int fdidx = 0; fdidx < nfd; ++fdidx){ // poll opened FDs
|
||||
if((poll_set[fdidx].revents & POLLIN) == 0) continue;
|
||||
poll_set[fdidx].revents = 0;
|
||||
if(fdidx){ // client
|
||||
int fd = poll_set[fdidx].fd;
|
||||
if(handle_socket(fd, notchkhdr[fdidx])){ // socket closed - remove it from list
|
||||
close(fd);
|
||||
DBG("Client with fd %d closed", fd);
|
||||
LOGMSG("Client %d disconnected", fd);
|
||||
// move last to free space
|
||||
poll_set[fdidx] = poll_set[nfd - 1];
|
||||
notchkhdr[fdidx] = notchkhdr[nfd - 1];
|
||||
--nfd;
|
||||
}else notchkhdr[fdidx] = 1;
|
||||
}else{ // server
|
||||
socklen_t size = sizeof(struct sockaddr_in);
|
||||
struct sockaddr_in their_addr;
|
||||
int newsock = accept(sock, (struct sockaddr*)&their_addr, &size);
|
||||
if(newsock <= 0){
|
||||
LOGERR("server(): accept() failed");
|
||||
WARN("accept()");
|
||||
continue;
|
||||
}
|
||||
struct in_addr ipAddr = their_addr.sin_addr;
|
||||
char str[INET_ADDRSTRLEN];
|
||||
inet_ntop(AF_INET, &ipAddr, str, INET_ADDRSTRLEN);
|
||||
DBG("Connection from %s, give fd=%d", str, newsock);
|
||||
LOGMSG("Got connection from %s, fd=%d", str, newsock);
|
||||
if(nfd == MAX_FDS){
|
||||
LOGWARN("Max amount of connections: disconnect %s (%d)", str, newsock);
|
||||
send_data(newsock, 0, "Max amount of connections reached!\n");
|
||||
WARNX("Limit of connections reached");
|
||||
close(newsock);
|
||||
}else{
|
||||
memset(&poll_set[nfd], 0, sizeof(struct pollfd));
|
||||
poll_set[nfd].fd = newsock;
|
||||
poll_set[nfd].events = POLLIN;
|
||||
notchkhdr[nfd] = 0;
|
||||
++nfd;
|
||||
}
|
||||
}
|
||||
} // endfor
|
||||
if(freshdata && answer){ // send new data to all
|
||||
freshdata = 0;
|
||||
lastdatat = dtime();
|
||||
for(int fdidx = 1; fdidx < nfd; ++fdidx){
|
||||
if(notchkhdr[fdidx])
|
||||
send_data(poll_set[fdidx].fd, 0, answer);
|
||||
}
|
||||
}
|
||||
if(dtime() - lastdatat > NODATA_TMOUT){
|
||||
LOGERR("No data timeout");
|
||||
ERRX("No data timeout");
|
||||
}
|
||||
}
|
||||
LOGERR("server(): UNREACHABLE CODE REACHED!");
|
||||
}
|
||||
|
||||
static void *ttyparser(_U_ void *notused){
|
||||
double tlast = 0;
|
||||
while(1){
|
||||
if(dtime() - tlast > T_INTERVAL){
|
||||
char *got = poll_device();
|
||||
if(got){
|
||||
if (0 == pthread_mutex_lock(&mutex)){
|
||||
FREE(answer);
|
||||
answer = strdup(got);
|
||||
freshdata = 1;
|
||||
pthread_mutex_unlock(&mutex);
|
||||
}
|
||||
tlast = dtime();
|
||||
}
|
||||
}
|
||||
sleep(1);
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
// data gathering & socket management
|
||||
static void daemon_(int sock){
|
||||
if(sock < 0) return;
|
||||
pthread_t sock_thread, parser_thread;
|
||||
if(pthread_create(&sock_thread, NULL, server, (void*) &sock)){
|
||||
LOGERR("daemon_(): pthread_create(sock_thread) failed");
|
||||
ERR("pthread_create()");
|
||||
}
|
||||
if(pthread_create(&parser_thread, NULL, ttyparser, NULL)){
|
||||
LOGERR("daemon_(): pthread_create(parser_thread) failed");
|
||||
ERR("pthread_create()");
|
||||
}
|
||||
do{
|
||||
if(pthread_kill(sock_thread, 0) == ESRCH){ // died
|
||||
WARNX("Sockets thread died");
|
||||
LOGWARN("Sockets thread died");
|
||||
pthread_join(sock_thread, NULL);
|
||||
if(pthread_create(&sock_thread, NULL, server, (void*) &sock)){
|
||||
LOGERR("daemon_(): new pthread_create() failed");
|
||||
ERR("pthread_create()");
|
||||
}
|
||||
}
|
||||
if(pthread_kill(parser_thread, 0) == ESRCH){ // died
|
||||
WARNX("TTY thread died");
|
||||
LOGWARN("TTY thread died");
|
||||
pthread_join(parser_thread, NULL);
|
||||
if(pthread_create(&parser_thread, NULL, ttyparser, NULL)){
|
||||
LOGERR("daemon_(): new pthread_create(parser_thread) failed");
|
||||
ERR("pthread_create()");
|
||||
}
|
||||
}
|
||||
usleep(1000); // sleep a little
|
||||
}while(1);
|
||||
LOGERR("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;
|
||||
// To accept only local sockets replace NULL with "127.0.0.1" and remove AI_PASSIVE
|
||||
if(getaddrinfo(NULL, port, &hints, &res) != 0){
|
||||
LOGERR("getaddrinfo");
|
||||
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){
|
||||
LOGERR("setsockopt() error");
|
||||
ERR("setsockopt");
|
||||
}
|
||||
if(bind(sock, p->ai_addr, p->ai_addrlen) == -1){
|
||||
close(sock);
|
||||
WARN("bind");
|
||||
LOGWARN("bind() error");
|
||||
continue;
|
||||
}
|
||||
break; // if we get here, we have a successfull connection
|
||||
}
|
||||
if(p == NULL){
|
||||
LOGERR("daemonize(): 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);
|
||||
LOGERR("daemonize(): UNREACHABLE CODE REACHED!");
|
||||
signals(0);
|
||||
}
|
||||
|
||||
32
Daemons/deprecated/weatherdaemon.deprecated/socket.h
Normal file
32
Daemons/deprecated/weatherdaemon.deprecated/socket.h
Normal file
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
* This file is part of the weatherdaemon project.
|
||||
* Copyright 2021 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
|
||||
#ifndef __SOCKET_H__
|
||||
#define __SOCKET_H__
|
||||
|
||||
// time interval for data polling (seconds)
|
||||
#define T_INTERVAL (10.)
|
||||
// max amount of opened fd (+1 for server socket)
|
||||
#define MAX_FDS (11)
|
||||
// no data timeout
|
||||
#define NODATA_TMOUT (90.)
|
||||
|
||||
void daemonize(char *port);
|
||||
|
||||
#endif // __SOCKET_H__
|
||||
159
Daemons/deprecated/weatherdaemon.deprecated/term.c
Normal file
159
Daemons/deprecated/weatherdaemon.deprecated/term.c
Normal file
@@ -0,0 +1,159 @@
|
||||
/*
|
||||
* This file is part of the weatherdaemon project.
|
||||
* Copyright 2021 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 <ctype.h> // isspace
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <strings.h> // strncasecmp
|
||||
#include <time.h> // time(NULL)
|
||||
#include <limits.h> // INT_MAX, INT_MIN
|
||||
|
||||
#include "bta_shdata.h"
|
||||
#include "cmdlnopts.h"
|
||||
#include "term.h"
|
||||
|
||||
#define BUFLEN (4096)
|
||||
|
||||
TTY_descr *ttydescr = NULL;
|
||||
extern glob_pars *GP;
|
||||
|
||||
static char buf[BUFLEN];
|
||||
static const char *emultemplate = "<?U> 06:50:36, 20.01.00, TE-2.20, DR1405.50, WU2057.68, RT0.00, WK1.00, WR177.80, WT-2.20, FE0.69, RE0.00, WG7.36, WV260.03, TI0.00, FI0.00,";
|
||||
|
||||
/**
|
||||
* read strings from terminal (ending with '\n') with timeout
|
||||
* @return NULL if nothing was read or pointer to static buffer
|
||||
*/
|
||||
static char *read_string(){
|
||||
//static int done = 0;
|
||||
if(GP->emul){
|
||||
//if(done) return NULL;
|
||||
strncpy(buf, emultemplate, BUFLEN);
|
||||
//done = 1;
|
||||
return buf;
|
||||
}
|
||||
if(!ttydescr) ERRX("Serial device not initialized");
|
||||
size_t r = 0, l;
|
||||
int LL = BUFLEN - 1;
|
||||
char *ptr = buf;
|
||||
double d0 = dtime();
|
||||
do{
|
||||
if((l = read_tty(ttydescr))){
|
||||
strncpy(ptr, ttydescr->buf, LL);
|
||||
r += l; LL -= l; ptr += l;
|
||||
DBG("l=%zd, r=%zd, LL=%d", l, r, LL);
|
||||
d0 = dtime();
|
||||
}
|
||||
}while(dtime() - d0 < WAIT_TMOUT && LL);
|
||||
if(r){
|
||||
//buf[r] = 0;
|
||||
DBG("buf: %s", buf);
|
||||
return buf;
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/**
|
||||
* Try to connect to `device` at baudrate speed
|
||||
* @return 1 if OK
|
||||
*/
|
||||
int try_connect(char *device, int baudrate){
|
||||
if(!device) return 0;
|
||||
fflush(stdout);
|
||||
ttydescr = new_tty(device, baudrate, 1024);
|
||||
if(ttydescr) ttydescr = tty_open(ttydescr, 1); // exclusive open
|
||||
if(!ttydescr) return 0;
|
||||
while(read_tty(ttydescr)); // clear rbuf
|
||||
LOGMSG("Connected to %s", device);
|
||||
return 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief getpar - get parameter value
|
||||
* @param string (i) - string where to search
|
||||
* @param Val (o) - value found
|
||||
* @param Name - parameter name
|
||||
* @return TRUE if found
|
||||
*/
|
||||
static int getpar(char *string, double *Val, char *Name){
|
||||
if(!string || !Val || !Name) return FALSE;
|
||||
char *p = strstr(string, Name);
|
||||
if(!p) return FALSE;
|
||||
p += strlen(Name);
|
||||
DBG("search %s", Name);
|
||||
char *endptr;
|
||||
*Val = strtod(p, &endptr);
|
||||
DBG("eptr=%s, val=%g", endptr, *Val);
|
||||
if(endptr == string){
|
||||
WARNX("Double value not found");
|
||||
return FALSE;
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Poll serial port for new dataportion
|
||||
* @return: NULL if no data received, pointer to string if valid data received
|
||||
*/
|
||||
char *poll_device(){
|
||||
FNAME();
|
||||
static char ans[BUFLEN];
|
||||
char *ptr = ans, *r = NULL;
|
||||
if(!GP->emul){
|
||||
if(write_tty(ttydescr->comfd, "?U\r\n", 4))
|
||||
return NULL;
|
||||
}
|
||||
double t0 = dtime();
|
||||
while(dtime() - t0 < T_POLLING_TMOUT){
|
||||
if((r = read_string())){ // parse new data
|
||||
DBG("got %s", r);
|
||||
if(strncmp(r, "<?U>", 4)){
|
||||
WARNX("Wrong answer");
|
||||
LOGWARN("poll_device() get wrong answer: %s", r);
|
||||
return NULL;
|
||||
}
|
||||
r += 4;
|
||||
DBG("R=%s", r);
|
||||
while(*r){if(isspace(*r)) ++r; else break;}
|
||||
DBG("R=%s", r);
|
||||
char *eol = strchr(r, '\n');
|
||||
if(eol) *eol = 0;
|
||||
double d;
|
||||
size_t L = BUFLEN, l;
|
||||
#define PRINT(...) do{l = snprintf(ptr, L, __VA_ARGS__); if(l > 0){ L -= l; ptr += l;}}while(0)
|
||||
if(getpar(r, &d, "RT")) PRINT("Rain=%g\n", d);
|
||||
if(getpar(r, &d, "WU")) PRINT("Clouds=%.1f\n", d);
|
||||
if(getpar(r, &d, "TE")) PRINT("Exttemp=%.1f\n", d);
|
||||
if(getpar(r, &d, "WG")) PRINT("Wind=%.1f\n", d/3.6);
|
||||
// now get BTA parameters
|
||||
if(check_shm_block(&sdat)){
|
||||
PRINT("BTAExttemp=%.1f\n", val_T1);
|
||||
PRINT("BTAPres=%.1f\n", val_B);
|
||||
PRINT("BTAWind=%.1f\n", val_Wnd);
|
||||
PRINT("BTAHumid=%.1f\n", val_Hmd);
|
||||
}
|
||||
#undef PRINT
|
||||
snprintf(ptr, L, "Time=%lld\n", (long long)time(NULL));
|
||||
DBG("Buffer: %s", ans);
|
||||
return ans;
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
37
Daemons/deprecated/weatherdaemon.deprecated/term.h
Normal file
37
Daemons/deprecated/weatherdaemon.deprecated/term.h
Normal file
@@ -0,0 +1,37 @@
|
||||
/*
|
||||
* This file is part of the weatherdaemon project.
|
||||
* Copyright 2021 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
|
||||
#ifndef __TERM_H__
|
||||
#define __TERM_H__
|
||||
|
||||
#include <usefull_macros.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)
|
||||
|
||||
extern TTY_descr *ttydescr;
|
||||
void run_terminal();
|
||||
int try_connect(char *device, int baudrate);
|
||||
char *poll_device();
|
||||
|
||||
#endif // __TERM_H__
|
||||
@@ -0,0 +1 @@
|
||||
-std=c17
|
||||
@@ -0,0 +1 @@
|
||||
#define EBUG 1
|
||||
@@ -0,0 +1 @@
|
||||
[General]
|
||||
@@ -0,0 +1,157 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE QtCreatorProject>
|
||||
<!-- Written by QtCreator 4.12.3, 2021-06-09T21:11:29. -->
|
||||
<qtcreator>
|
||||
<data>
|
||||
<variable>EnvironmentId</variable>
|
||||
<value type="QByteArray">{7bd84e39-ca37-46d3-be9d-99ebea85bc0d}</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">true</value>
|
||||
<value type="bool" key="EditorConfiguration.ShowMargin">false</value>
|
||||
<value type="int" key="EditorConfiguration.SmartBackspaceBehavior">0</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">1</value>
|
||||
<value type="bool" key="EditorConfiguration.addFinalNewLine">true</value>
|
||||
<value type="bool" key="EditorConfiguration.cleanIndentation">false</value>
|
||||
<value type="bool" key="EditorConfiguration.cleanWhitespace">true</value>
|
||||
<value type="bool" key="EditorConfiguration.inEntireDocument">false</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">{65a14f9e-e008-4c1b-89df-4eaa4774b6e3}</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">/Big/Data/00__Small_tel/C-sources/netdaemon</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">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.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>
|
||||
@@ -0,0 +1,167 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE QtCreatorProject>
|
||||
<!-- Written by QtCreator 4.8.2, 2020-08-27T15:02:35. -->
|
||||
<qtcreator>
|
||||
<data>
|
||||
<variable>EnvironmentId</variable>
|
||||
<value type="QByteArray">{7bd84e39-ca37-46d3-be9d-99ebea85bc0d}</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">true</value>
|
||||
<value type="bool" key="EditorConfiguration.ShowMargin">false</value>
|
||||
<value type="int" key="EditorConfiguration.SmartBackspaceBehavior">0</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">1</value>
|
||||
<value type="bool" key="EditorConfiguration.addFinalNewLine">true</value>
|
||||
<value type="bool" key="EditorConfiguration.cleanIndentation">false</value>
|
||||
<value type="bool" key="EditorConfiguration.cleanWhitespace">true</value>
|
||||
<value type="bool" key="EditorConfiguration.inEntireDocument">false</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">{65a14f9e-e008-4c1b-89df-4eaa4774b6e3}</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">/Big/Data/00__Small_tel/C-sources/netdaemon</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.DefaultDisplayName">Сборка</value>
|
||||
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></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">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.DefaultDisplayName">Сборка</value>
|
||||
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></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.DefaultDisplayName">По умолчанию</value>
|
||||
<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>
|
||||
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Конфигурация установки</value>
|
||||
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></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="bool" key="Analyzer.QmlProfiler.AggregateTraces">false</value>
|
||||
<value type="bool" key="Analyzer.QmlProfiler.FlushEnabled">false</value>
|
||||
<value type="uint" key="Analyzer.QmlProfiler.FlushInterval">1000</value>
|
||||
<value type="QString" key="Analyzer.QmlProfiler.LastTraceFile"></value>
|
||||
<value type="bool" key="Analyzer.QmlProfiler.Settings.UseGlobalSettings">true</value>
|
||||
<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.DefaultDisplayName">Особая программа</value>
|
||||
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value>
|
||||
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">ProjectExplorer.CustomExecutableRunConfiguration</value>
|
||||
<value type="QString" key="RunConfiguration.Arguments"></value>
|
||||
<value type="uint" key="RunConfiguration.QmlDebugServerPort">3768</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">20</value>
|
||||
</data>
|
||||
<data>
|
||||
<variable>Version</variable>
|
||||
<value type="int">20</value>
|
||||
</data>
|
||||
</qtcreator>
|
||||
@@ -0,0 +1 @@
|
||||
-std=c++17
|
||||
@@ -0,0 +1,9 @@
|
||||
bta_shdata.c
|
||||
bta_shdata.h
|
||||
cmdlnopts.c
|
||||
cmdlnopts.h
|
||||
main.c
|
||||
socket.c
|
||||
socket.h
|
||||
term.c
|
||||
term.h
|
||||
@@ -0,0 +1 @@
|
||||
.
|
||||
@@ -0,0 +1,42 @@
|
||||
# run `make DEF=...` to add extra defines
|
||||
PROGRAM := weatherdaemon
|
||||
LDFLAGS := -fdata-sections -ffunction-sections -Wl,--gc-sections -Wl,--discard-all -pthread
|
||||
LDFLAGS += -flto `pkg-config --libs usefull_macros` -lm
|
||||
SRCS := $(wildcard *.c)
|
||||
DEFINES := $(DEF) -D_GNU_SOURCE -D_XOPEN_SOURCE=1111
|
||||
#DEFINES += -DEBUG
|
||||
OBJDIR := mk
|
||||
CFLAGS += `pkg-config --cflags usefull_macros` -O3 -Wall -Werror -Wextra -Wno-trampolines -flto
|
||||
OBJS := $(addprefix $(OBJDIR)/, $(SRCS:%.c=%.o))
|
||||
DEPS := $(OBJS:.o=.d)
|
||||
CC = gcc
|
||||
|
||||
all : $(OBJDIR) $(PROGRAM)
|
||||
|
||||
$(PROGRAM) : $(OBJS)
|
||||
@echo -e "\t\tLD $(PROGRAM)"
|
||||
$(CC) $(OBJS) $(LDFLAGS) -o $(PROGRAM)
|
||||
|
||||
$(OBJDIR):
|
||||
mkdir $(OBJDIR)
|
||||
|
||||
ifneq ($(MAKECMDGOALS),clean)
|
||||
-include $(DEPS)
|
||||
endif
|
||||
|
||||
$(OBJDIR)/%.o: %.c
|
||||
@echo -e "\t\tCC $<"
|
||||
$(CC) -MD -c $(LDFLAGS) $(CFLAGS) $(DEFINES) -o $@ $<
|
||||
|
||||
clean:
|
||||
@echo -e "\t\tCLEAN"
|
||||
@rm -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
|
||||
@@ -0,0 +1,22 @@
|
||||
Weather daemon
|
||||
==================
|
||||
|
||||
Weather daemon for new meteostation.
|
||||
|
||||
Open a socket at given port (default: 12345)
|
||||
Parse weather data and send it to client
|
||||
|
||||
```
|
||||
Usage: weatherdaemon [args]
|
||||
|
||||
Where args are:
|
||||
|
||||
-P, --pidfile=arg pidfile name (default: /tmp/weatherdaemon.pid)
|
||||
-b, --baudrate=arg serial terminal baudrate (default: 9600)
|
||||
-d, --device=arg serial device name (default: none)
|
||||
-e, --emulation emulate serial device
|
||||
-h, --help show this help
|
||||
-l, --logfile=arg save logs to file (default: none)
|
||||
-p, --port=arg network port to connect (default: 12345)
|
||||
-v, --verb logfile verbocity level (each -v increase it)
|
||||
```
|
||||
@@ -0,0 +1,92 @@
|
||||
/*
|
||||
* This file is part of the weatherdaemon project.
|
||||
* Copyright 2021 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 <assert.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <strings.h>
|
||||
#include <math.h>
|
||||
#include <usefull_macros.h>
|
||||
#include "cmdlnopts.h"
|
||||
|
||||
/*
|
||||
* here are global parameters initialisation
|
||||
*/
|
||||
int help;
|
||||
static glob_pars G;
|
||||
|
||||
// default values for Gdefault & help
|
||||
#define DEFAULT_PORT "12345"
|
||||
#define DEFAULT_PID "/tmp/weatherdaemon.pid"
|
||||
|
||||
// DEFAULTS
|
||||
// default global parameters
|
||||
glob_pars const Gdefault = {
|
||||
.device = NULL,
|
||||
.port = DEFAULT_PORT,
|
||||
.logfile = NULL,
|
||||
.verb = 0,
|
||||
.tty_speed = 9600,
|
||||
.rest_pars = NULL,
|
||||
.rest_pars_num = 0,
|
||||
.emul = 0,
|
||||
.pidfile = DEFAULT_PID
|
||||
};
|
||||
|
||||
/*
|
||||
* 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)")},
|
||||
{"verb", NO_ARGS, NULL, 'v', arg_none, APTR(&G.verb), _("logfile verbocity level (each -v increase it)")},
|
||||
{"baudrate",NEED_ARG, NULL, 'b', arg_int, APTR(&G.tty_speed), _("serial terminal baudrate (default: 9600)")},
|
||||
{"emulation",NO_ARGS, NULL, 'e', arg_int, APTR(&G.emul), _("emulate serial device")},
|
||||
{"pidfile", NEED_ARG, NULL, 'P', arg_string, APTR(&G.pidfile), _("pidfile name (default: " DEFAULT_PID ")")},
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
/*
|
||||
* This file is part of the weatherdaemon project.
|
||||
* Copyright 2021 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
|
||||
#ifndef __CMDLNOPTS_H__
|
||||
#define __CMDLNOPTS_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 verb; // verbocity level
|
||||
int tty_speed; // serial terminal baudrate
|
||||
int emul; // emulation of serial device
|
||||
char *pidfile; // pidfile name
|
||||
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__
|
||||
88
Daemons/deprecated/weatherdaemon_newmeteo.deprecated/main.c
Normal file
88
Daemons/deprecated/weatherdaemon_newmeteo.deprecated/main.c
Normal file
@@ -0,0 +1,88 @@
|
||||
/*
|
||||
* This file is part of the weatherdaemon project.
|
||||
* Copyright 2021 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 <signal.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <sys/wait.h> // wait
|
||||
#include <sys/prctl.h> //prctl
|
||||
#include <usefull_macros.h>
|
||||
|
||||
#include "cmdlnopts.h"
|
||||
#include "socket.h"
|
||||
#include "term.h"
|
||||
|
||||
glob_pars *GP;
|
||||
|
||||
void signals(int signo){
|
||||
restore_console();
|
||||
stop_tty();
|
||||
LOGERR("exit with status %d", signo);
|
||||
exit(signo);
|
||||
}
|
||||
|
||||
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
|
||||
#ifndef EBUG
|
||||
char *self = strdup(argv[0]);
|
||||
#endif
|
||||
GP = parse_args(argc, argv);
|
||||
if(GP->logfile){
|
||||
sl_loglevel lvl = LOGLEVEL_ERR;
|
||||
for(; GP->verb && lvl < LOGLEVEL_ANY; --GP->verb) ++lvl;
|
||||
DBG("Loglevel: %d", lvl);
|
||||
if(!OPENLOG(GP->logfile, lvl, 1)) ERRX("Can't open log file");
|
||||
LOGERR("Started");
|
||||
}
|
||||
#ifndef EBUG
|
||||
if(daemon(1, 0)){
|
||||
ERR("daemon()");
|
||||
}
|
||||
check4running(self, GP->pidfile);
|
||||
while(1){ // guard for dead processes
|
||||
pid_t childpid = fork();
|
||||
if(childpid){
|
||||
LOGDBG("create child with PID %d\n", childpid);
|
||||
DBG("Created child with PID %d\n", childpid);
|
||||
wait(NULL);
|
||||
WARNX("Child %d died\n", childpid);
|
||||
LOGWARN("Child %d died\n", childpid);
|
||||
sleep(1);
|
||||
}else{
|
||||
prctl(PR_SET_PDEATHSIG, SIGTERM); // send SIGTERM to child when parent dies
|
||||
break; // go out to normal functional
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
if(GP->device) if(!try_connect(GP->device, GP->tty_speed)){
|
||||
LOGERR("Can't connect to device");
|
||||
ERRX("Can't connect to device");
|
||||
}
|
||||
if(!GP->device && !GP->emul){
|
||||
LOGERR("Need serial device name or emulation flag");
|
||||
ERRX("Need serial device name or emulation flag");
|
||||
}
|
||||
daemonize(GP->port);
|
||||
return 0;
|
||||
}
|
||||
407
Daemons/deprecated/weatherdaemon_newmeteo.deprecated/socket.c
Normal file
407
Daemons/deprecated/weatherdaemon_newmeteo.deprecated/socket.c
Normal file
@@ -0,0 +1,407 @@
|
||||
/*
|
||||
* This file is part of the weatherdaemon project.
|
||||
* Copyright 2021 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 <netdb.h> // addrinfo
|
||||
#include <arpa/inet.h> // inet_ntop
|
||||
#include <limits.h> // INT_xxx
|
||||
#include <poll.h> // poll
|
||||
#include <pthread.h>
|
||||
#include <signal.h> // pthread_kill
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <sys/syscall.h> // syscall
|
||||
#include <unistd.h> // daemon
|
||||
#include <usefull_macros.h>
|
||||
|
||||
#include "cmdlnopts.h" // glob_pars
|
||||
#include "socket.h"
|
||||
#include "stat.h"
|
||||
#include "term.h"
|
||||
|
||||
// temporary buffers
|
||||
#define BUFLEN (1024)
|
||||
// Max amount of connections
|
||||
#define BACKLOG (30)
|
||||
|
||||
extern glob_pars *GP;
|
||||
|
||||
static weather_t lastweather = {0};
|
||||
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
|
||||
static weatherstat_t wstat;
|
||||
|
||||
typedef enum{
|
||||
FORMAT_ERROR, // send user an error message
|
||||
FORMAT_CURDFULL, // param=value for current data
|
||||
FORMAT_CURDSHORT, // comma-separated current data
|
||||
FORMAT_STATFULL, // param=value for stat
|
||||
FORMAT_STATSHORT // comma-separated stat
|
||||
} format_t;
|
||||
|
||||
|
||||
|
||||
/**************** SERVER FUNCTIONS ****************/
|
||||
/**
|
||||
* Send data over socket
|
||||
* @param sock - socket fd
|
||||
* @param webquery - ==1 if this is web query
|
||||
* @param format - data format
|
||||
* @return 1 if all OK
|
||||
*/
|
||||
static int send_data(int sock, int webquery, format_t format){
|
||||
char tbuf[BUFSIZ]; // buffer to send
|
||||
char databuf[BUFSIZ]; // buffer with data
|
||||
ssize_t Len = 0;
|
||||
const char *eol = webquery ? "\r\n" : "\n";
|
||||
// fill buffer with data
|
||||
pthread_mutex_lock(&mutex);
|
||||
if(format == FORMAT_CURDFULL){ // full format
|
||||
Len = snprintf(databuf, BUFSIZ,
|
||||
"Wind=%.1f%sDir=%.1f%sPressure=%.1f%sTemperature=%.1f%sHumidity=%.1f%s"
|
||||
"Rain=%.1f%sTime=%.3f%s",
|
||||
lastweather.windspeed, eol, lastweather.winddir, eol, lastweather.pressure, eol,
|
||||
lastweather.temperature, eol, lastweather.humidity, eol, lastweather.rainfall, eol,
|
||||
lastweather.tmeasure, eol
|
||||
);
|
||||
}else if(format == FORMAT_CURDSHORT){ // short format
|
||||
Len = snprintf(databuf, BUFSIZ,
|
||||
"%.3f,%.1f,%.1f,%.1f,%.1f,%.1f,%.1f%s",
|
||||
lastweather.tmeasure, lastweather.windspeed, lastweather.winddir,
|
||||
lastweather.pressure, lastweather.temperature, lastweather.humidity,
|
||||
lastweather.rainfall, eol
|
||||
);
|
||||
}else if(format == FORMAT_STATFULL){
|
||||
char *ptr = databuf;
|
||||
int l = BUFSIZ;
|
||||
#define PRSTAT(field, nm) do{register int lc = snprintf(ptr, l, \
|
||||
nm "max=%.1f%s" nm "min=%.1f%s" nm "mean=%.1f%s" nm "rms=%.1f%s", \
|
||||
wstat.field.max, eol, wstat.field.min, eol, wstat.field.mean, eol, wstat.field.rms, eol); \
|
||||
Len += lc; l -= lc; ptr += lc;}while(0)
|
||||
PRSTAT(windspeed, "Wind");
|
||||
PRSTAT(winddir, "Dir");
|
||||
PRSTAT(pressure, "Pressure");
|
||||
PRSTAT(temperature, "Temperature");
|
||||
PRSTAT(humidity, "Humidity");
|
||||
PRSTAT(rainfall, "Rain");
|
||||
PRSTAT(tmeasure, "Time");
|
||||
#undef PRSTAT
|
||||
}else if(format == FORMAT_STATSHORT){
|
||||
char *ptr = databuf;
|
||||
int l = BUFSIZ;
|
||||
register int lc;
|
||||
#define PRSTAT(field, nm) do{lc = snprintf(ptr, l, \
|
||||
"%.1f,%.1f,%.1f,%.1f", \
|
||||
wstat.field.max, wstat.field.min, wstat.field.mean, wstat.field.rms); \
|
||||
Len += lc; l -= lc; ptr += lc;}while(0)
|
||||
#define COMMA() do{lc = snprintf(ptr, l, ","); Len += lc; l -= lc; ptr += lc;}while(0)
|
||||
PRSTAT(windspeed, "Wind"); COMMA();
|
||||
PRSTAT(winddir, "Dir"); COMMA();
|
||||
PRSTAT(pressure, "Pressure"); COMMA();
|
||||
PRSTAT(temperature, "Temperature"); COMMA();
|
||||
PRSTAT(humidity, "Humidity"); COMMA();
|
||||
PRSTAT(rainfall, "Rain"); COMMA();
|
||||
PRSTAT(tmeasure, "Time");
|
||||
Len += snprintf(ptr, l, "%s", eol);
|
||||
#undef PRSTAT
|
||||
}else{
|
||||
Len = snprintf(databuf, BUFSIZ, "Error!");
|
||||
}
|
||||
pthread_mutex_unlock(&mutex);
|
||||
// OK buffer ready, prepare to send it
|
||||
if(webquery){
|
||||
ssize_t L = snprintf(tbuf, BUFSIZ,
|
||||
"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()");
|
||||
LOGWARN("sprintf()");
|
||||
return FALSE;
|
||||
}
|
||||
if(L != write(sock, tbuf, L)){
|
||||
LOGWARN("Can't write header");
|
||||
WARN("write");
|
||||
return FALSE;
|
||||
}
|
||||
}
|
||||
if(Len != write(sock, databuf, Len)){
|
||||
WARN("write()");
|
||||
LOGERR("send_data(): write() failed");
|
||||
return FALSE;
|
||||
}
|
||||
//LOGDBG("fd %d, write %s", sock, textbuf);
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
// 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;
|
||||
return a;
|
||||
}
|
||||
|
||||
static double getpar(const char *s){
|
||||
double x = -1.;
|
||||
char *eptr = NULL;
|
||||
while(*s && *s <= ' ') ++s;
|
||||
x = strtod(s, &eptr);
|
||||
if(eptr == s) x = -1.;
|
||||
return x;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief handle_socket - read information from socket
|
||||
* @param sock - socket fd
|
||||
* @param chkheader - ==1 on first run
|
||||
* @return 1 if socket closed
|
||||
*/
|
||||
static int handle_socket(int sock){
|
||||
FNAME();
|
||||
int webquery = 0; // whether query is web or regular
|
||||
char buff[BUFLEN];
|
||||
ssize_t rd;
|
||||
if(!(rd = read(sock, buff, BUFLEN-1))){
|
||||
//LOGMSG("Client %d closed", sock);
|
||||
return 1;
|
||||
}
|
||||
//LOG("client send %zd bytes", rd);
|
||||
DBG("Got %zd bytes", rd);
|
||||
if(rd <= 0){ // error
|
||||
LOGWARN("Client %d close socket on error", sock);
|
||||
DBG("Nothing to read from fd %d (ret: %zd)", sock, rd);
|
||||
return 1;
|
||||
}
|
||||
// add trailing zero to be on the safe side
|
||||
buff[rd] = 0;
|
||||
// now we should check what do user want
|
||||
char *found = buff;
|
||||
DBG("user send: %s", buff);
|
||||
format_t format = FORMAT_CURDFULL; // text format - default for web-queries
|
||||
|
||||
if(0 == strncmp(buff, "GET", 3)){
|
||||
DBG("GET, buff=%s", buff);
|
||||
// GET web query have format GET /some.resource
|
||||
webquery = 1;
|
||||
char *slash = strchr(buff, '/');
|
||||
if(slash){
|
||||
found = slash + 1;
|
||||
if(strncmp(found, "stat", 4) == 0){
|
||||
format = FORMAT_STATFULL;
|
||||
double dt = getpar(found + 4);
|
||||
if(dt < 1.) dt = 900.;
|
||||
if(stat_for(dt, &wstat) < 1.) format = FORMAT_ERROR;
|
||||
}
|
||||
char *eol = strstr(found, "HTTP");
|
||||
if(eol) *eol = 0;
|
||||
}
|
||||
}else if(0 == strncmp(buff, "POST", 4)){
|
||||
DBG("POST");
|
||||
webquery = 1;
|
||||
// search content length of POST query
|
||||
char *cl = stringscan(buff, "Content-Length:");
|
||||
if(cl){
|
||||
int contlen = atoi(cl);
|
||||
int l = strlen(buff);
|
||||
if(contlen && l > contlen) found = &buff[l - contlen];
|
||||
}
|
||||
}else if(0 == strncmp(buff, "simple", 6)) format = FORMAT_CURDSHORT; // simple format
|
||||
else if(0 == strncmp(buff, "stat", 4)){ // show stat
|
||||
double dt = -1.; int l = 4;
|
||||
if(0 == strncmp(buff, "statsimple", 10)){
|
||||
l = 10; format = FORMAT_STATSHORT;
|
||||
}else format = FORMAT_STATFULL;
|
||||
dt = getpar(buff + l);
|
||||
if(dt < 1.) dt = 900.; // 15 minutes - default
|
||||
if(stat_for(dt, &wstat) < 1.) format = FORMAT_ERROR;
|
||||
}
|
||||
|
||||
// here we can process user data
|
||||
DBG("found=%s", found);
|
||||
LOGDBG("sockfd=%d, got %s", sock, buff);
|
||||
DBG("format=%d", format);
|
||||
send_data(sock, webquery, format);
|
||||
if(webquery) return 1; // close web query after message processing
|
||||
return 0;
|
||||
}
|
||||
|
||||
// main socket server
|
||||
static void *server(void *asock){
|
||||
LOGMSG("server()");
|
||||
int sock = *((int*)asock);
|
||||
if(listen(sock, BACKLOG) == -1){
|
||||
LOGERR("listen() failed");
|
||||
WARN("listen");
|
||||
return NULL;
|
||||
}
|
||||
int nfd = 1; // current fd amount in poll_set
|
||||
struct pollfd poll_set[MAX_FDS];
|
||||
memset(poll_set, 0, sizeof(poll_set));
|
||||
poll_set[0].fd = sock;
|
||||
poll_set[0].events = POLLIN;
|
||||
while(1){
|
||||
poll(poll_set, nfd, 1); // poll for 1ms
|
||||
for(int fdidx = 0; fdidx < nfd; ++fdidx){ // poll opened FDs
|
||||
if((poll_set[fdidx].revents & POLLIN) == 0) continue;
|
||||
poll_set[fdidx].revents = 0;
|
||||
if(fdidx){ // client
|
||||
int fd = poll_set[fdidx].fd;
|
||||
if(handle_socket(fd)){ // socket closed - remove it from list
|
||||
close(fd);
|
||||
DBG("Client with fd %d closed", fd);
|
||||
LOGMSG("Client %d disconnected", fd);
|
||||
// move last to free space
|
||||
poll_set[fdidx] = poll_set[nfd - 1];
|
||||
--nfd;
|
||||
}
|
||||
}else{ // server
|
||||
socklen_t size = sizeof(struct sockaddr_in);
|
||||
struct sockaddr_in their_addr;
|
||||
int newsock = accept(sock, (struct sockaddr*)&their_addr, &size);
|
||||
if(newsock <= 0){
|
||||
LOGERR("server(): accept() failed");
|
||||
WARN("accept()");
|
||||
continue;
|
||||
}
|
||||
struct in_addr ipAddr = their_addr.sin_addr;
|
||||
char str[INET_ADDRSTRLEN];
|
||||
inet_ntop(AF_INET, &ipAddr, str, INET_ADDRSTRLEN);
|
||||
DBG("Connection from %s, give fd=%d", str, newsock);
|
||||
LOGMSG("Got connection from %s, fd=%d", str, newsock);
|
||||
if(nfd == MAX_FDS){
|
||||
LOGWARN("Max amount of connections: disconnect %s (%d)", str, newsock);
|
||||
int _U_ x = write(newsock, "Max amount of connections reached!\n", 35);
|
||||
WARNX("Limit of connections reached");
|
||||
close(newsock);
|
||||
}else{
|
||||
memset(&poll_set[nfd], 0, sizeof(struct pollfd));
|
||||
poll_set[nfd].fd = newsock;
|
||||
poll_set[nfd].events = POLLIN;
|
||||
++nfd;
|
||||
}
|
||||
}
|
||||
} // endfor
|
||||
} // endwhile(1)
|
||||
LOGERR("server(): UNREACHABLE CODE REACHED!");
|
||||
}
|
||||
|
||||
// poll last weather data
|
||||
static void *weatherpolling(_U_ void *notused){
|
||||
while(1){
|
||||
weather_t w;
|
||||
if(getlastweather(&w) && 0 == pthread_mutex_lock(&mutex)){
|
||||
memcpy(&lastweather, &w, sizeof(weather_t));
|
||||
addtobuf(&w);
|
||||
pthread_mutex_unlock(&mutex);
|
||||
}
|
||||
usleep(100000); // not more than 10 messages per second
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
// data gathering & socket management
|
||||
static void daemon_(int sock){
|
||||
if(sock < 0) return;
|
||||
pthread_t sock_thread, parser_thread;
|
||||
if(pthread_create(&sock_thread, NULL, server, (void*) &sock)){
|
||||
LOGERR("daemon_(): pthread_create(sock_thread) failed");
|
||||
ERR("pthread_create()");
|
||||
}
|
||||
if(pthread_create(&parser_thread, NULL, weatherpolling, NULL)){
|
||||
LOGERR("daemon_(): pthread_create(parser_thread) failed");
|
||||
ERR("pthread_create()");
|
||||
}
|
||||
do{
|
||||
if(pthread_kill(sock_thread, 0) == ESRCH){ // died
|
||||
WARNX("Sockets thread died");
|
||||
LOGWARN("Sockets thread died");
|
||||
pthread_join(sock_thread, NULL);
|
||||
if(pthread_create(&sock_thread, NULL, server, (void*) &sock)){
|
||||
LOGERR("daemon_(): new pthread_create() failed");
|
||||
ERR("pthread_create()");
|
||||
}
|
||||
}
|
||||
if(pthread_kill(parser_thread, 0) == ESRCH){ // died
|
||||
WARNX("TTY thread died");
|
||||
LOGWARN("TTY thread died");
|
||||
pthread_join(parser_thread, NULL);
|
||||
if(pthread_create(&parser_thread, NULL, weatherpolling, NULL)){
|
||||
LOGERR("daemon_(): new pthread_create(parser_thread) failed");
|
||||
ERR("pthread_create()");
|
||||
}
|
||||
}
|
||||
usleep(1000); // sleep a little
|
||||
}while(1);
|
||||
LOGERR("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;
|
||||
// To accept only local sockets replace NULL with "127.0.0.1" and remove AI_PASSIVE
|
||||
if(getaddrinfo(NULL, port, &hints, &res) != 0){
|
||||
LOGERR("getaddrinfo");
|
||||
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){
|
||||
LOGERR("setsockopt() error");
|
||||
ERR("setsockopt");
|
||||
}
|
||||
if(bind(sock, p->ai_addr, p->ai_addrlen) == -1){
|
||||
close(sock);
|
||||
WARN("bind");
|
||||
LOGWARN("bind() error");
|
||||
continue;
|
||||
}
|
||||
break; // if we get here, we have a successfull connection
|
||||
}
|
||||
if(p == NULL){
|
||||
LOGERR("daemonize(): 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);
|
||||
LOGERR("daemonize(): UNREACHABLE CODE REACHED!");
|
||||
signals(0);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
* This file is part of the weatherdaemon project.
|
||||
* Copyright 2021 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
|
||||
#ifndef __SOCKET_H__
|
||||
#define __SOCKET_H__
|
||||
|
||||
// time interval for data polling (seconds)
|
||||
#define T_INTERVAL (10.)
|
||||
// max amount of opened fd (+1 for server socket)
|
||||
#define MAX_FDS (11)
|
||||
// no data timeout
|
||||
#define NODATA_TMOUT (90.)
|
||||
|
||||
void daemonize(char *port);
|
||||
|
||||
#endif // __SOCKET_H__
|
||||
153
Daemons/deprecated/weatherdaemon_newmeteo.deprecated/stat.c
Normal file
153
Daemons/deprecated/weatherdaemon_newmeteo.deprecated/stat.c
Normal file
@@ -0,0 +1,153 @@
|
||||
/*
|
||||
* This file is part of the weatherdaemon project.
|
||||
* Copyright 2023 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 <math.h>
|
||||
#include <pthread.h>
|
||||
#include <string.h>
|
||||
#include <stdio.h>
|
||||
#include <usefull_macros.h>
|
||||
|
||||
#include "stat.h"
|
||||
|
||||
// add BUFSZ_INCR records to buffer each time when no free space left
|
||||
#define BUFSZ_INCR (2048)
|
||||
static weather_t *buf = NULL;
|
||||
// current size of `buf`
|
||||
static size_t buflen = 0;
|
||||
// indexes of first and last element in buffer
|
||||
static size_t firstidx = 0, lastidx = 0;
|
||||
// maximal current time delta between last and first items of `buf`
|
||||
static double tdiffmax = 0.;
|
||||
|
||||
// mutex for working with buffer
|
||||
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
|
||||
|
||||
double get_tmax(){
|
||||
return tdiffmax;
|
||||
}
|
||||
|
||||
// add new record to buffer
|
||||
void addtobuf(weather_t *record){
|
||||
if(!record) return;
|
||||
pthread_mutex_lock(&mutex);
|
||||
if(!buf){ // first run
|
||||
buf = MALLOC(weather_t, BUFSZ_INCR);
|
||||
buflen = BUFSZ_INCR;
|
||||
memcpy(&buf[0], record, sizeof(weather_t));
|
||||
//DBG("init buff to %zd", buflen);
|
||||
pthread_mutex_unlock(&mutex);
|
||||
return;
|
||||
}
|
||||
if(++lastidx == buflen){ // end of buffer reached: decide wether to increase buffer or not
|
||||
if(tdiffmax < STATMAXT){
|
||||
buflen += BUFSZ_INCR;
|
||||
buf = realloc(buf, sizeof(weather_t)*buflen);
|
||||
DBG("realloc buf to %zd", buflen);
|
||||
}else lastidx = 0;
|
||||
}
|
||||
if(lastidx == firstidx){
|
||||
if(++firstidx == buflen) firstidx = 0;
|
||||
}
|
||||
memcpy(&buf[lastidx], record, sizeof(weather_t));
|
||||
tdiffmax = buf[lastidx].tmeasure - buf[firstidx].tmeasure;
|
||||
//DBG("add record, last=%zd, first=%zd, dT=%.3f", lastidx, firstidx, tdiffmax);
|
||||
pthread_mutex_unlock(&mutex);
|
||||
}
|
||||
|
||||
|
||||
|
||||
// get statistics for last `Tsec` seconds; @return real dT for given interval
|
||||
double stat_for(double Tsec, weatherstat_t *wstat){
|
||||
if(!wstat || Tsec < 1.) return 0.;
|
||||
double dt = 0., tlast = buf[lastidx].tmeasure;
|
||||
size_t startfrom = lastidx;
|
||||
pthread_mutex_lock(&mutex);
|
||||
if(tdiffmax <= Tsec){ // use all data
|
||||
startfrom = firstidx;
|
||||
dt = tdiffmax;
|
||||
}else while(dt < Tsec && startfrom != firstidx){ // search from which index we should start
|
||||
if(startfrom == 0) startfrom = buflen - 1;
|
||||
else --startfrom;
|
||||
dt = tlast - buf[startfrom].tmeasure;
|
||||
}
|
||||
DBG("got indexes: start=%zd, end=%zd, dt=%.2f (dtiffmax=%.1f)", startfrom, lastidx, dt, tdiffmax);
|
||||
weather_t min, max, sum = {0}, sum2 = {0};
|
||||
size_t amount = 0;
|
||||
memcpy(&min, &buf[lastidx], sizeof(weather_t));
|
||||
memcpy(&max, &buf[lastidx], sizeof(weather_t));
|
||||
min.tmeasure = buf[startfrom].tmeasure;
|
||||
max.tmeasure = buf[lastidx].tmeasure;
|
||||
double tmean = (max.tmeasure+min.tmeasure)/2.;
|
||||
// DBG("tmean=%.1f, min=%.1f, max=%.1f", tmean, min.tmeasure, max.tmeasure);
|
||||
size_t st = startfrom;
|
||||
// calculate amount of north and south winds
|
||||
size_t north = 0, south = 0;
|
||||
while(st != lastidx){
|
||||
double w = buf[st].winddir;
|
||||
if(w < 90. || w > 270.) ++north;
|
||||
else ++south;
|
||||
if(++st == buflen) st = 0;
|
||||
}
|
||||
int minus = 0;
|
||||
if(north > 2*south) minus = 1;
|
||||
while(startfrom != lastidx){
|
||||
weather_t *curw = &buf[startfrom];
|
||||
#define CHK(field) do{register double d = curw->field; if(d > max.field) max.field = d; if(d < min.field) min.field = d; \
|
||||
sum.field += d; sum2.field += d*d;}while(0)
|
||||
CHK(windspeed);
|
||||
register double dir = curw->winddir, s = curw->windspeed;
|
||||
if(minus && dir > 180.) dir -= 360.;
|
||||
register double sd = dir * s; // weighted sum
|
||||
if(dir > max.winddir) max.winddir = dir;
|
||||
if(dir < min.winddir) min.winddir = dir;
|
||||
sum.winddir += sd;
|
||||
sum2.winddir += sd * dir; // v * dir^2
|
||||
CHK(pressure);
|
||||
CHK(temperature);
|
||||
CHK(humidity);
|
||||
CHK(rainfall);
|
||||
s = curw->tmeasure;
|
||||
sum.tmeasure += s; s -= tmean;
|
||||
sum2.tmeasure += s * s; // correct tmeasure by mean time to exclude cumulative error of double
|
||||
#undef CHK
|
||||
++amount;
|
||||
if(++startfrom == buflen) startfrom = 0;
|
||||
}
|
||||
// DBG("Got %zd records; tsum/sum2: %g/%g", amount, sum.tmeasure, sum2.tmeasure);
|
||||
wstat->winddir.max = max.winddir;
|
||||
wstat->winddir.min = min.winddir;
|
||||
register double s2 = sum2.winddir / sum.windspeed, s = sum.winddir / sum.windspeed;
|
||||
wstat->winddir.mean = s;
|
||||
wstat->winddir.rms = sqrt(s2 - s*s);
|
||||
// correct RMS by float epsilon to exclude negative values when near zero
|
||||
#define STAT(field) do{ register double ms = sum.field/amount, ms2 = sum2.field/amount; \
|
||||
wstat->field.min = min.field; wstat->field.max = max.field; wstat->field.mean = ms; \
|
||||
wstat->field.rms = sqrt(ms2 - ms*ms + __FLT_EPSILON__); }while(0)
|
||||
STAT(windspeed);
|
||||
STAT(pressure);
|
||||
STAT(temperature);
|
||||
STAT(humidity);
|
||||
STAT(rainfall);
|
||||
wstat->tmeasure.max = max.tmeasure;
|
||||
wstat->tmeasure.min = min.tmeasure;
|
||||
wstat->tmeasure.mean = sum.tmeasure/amount;
|
||||
wstat->tmeasure.rms = sqrt(sum2.tmeasure/amount); // sum2.tmeasure is already corrected by mean
|
||||
// DBG("tmean=%.1f, min=%.1f, max=%.1f", wstat->tmeasure.mean, wstat->tmeasure.min, wstat->tmeasure.max);
|
||||
pthread_mutex_unlock(&mutex);
|
||||
return dt;
|
||||
}
|
||||
46
Daemons/deprecated/weatherdaemon_newmeteo.deprecated/stat.h
Normal file
46
Daemons/deprecated/weatherdaemon_newmeteo.deprecated/stat.h
Normal file
@@ -0,0 +1,46 @@
|
||||
/*
|
||||
* This file is part of the weatherdaemon project.
|
||||
* Copyright 2023 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 "term.h"
|
||||
|
||||
// maximal time difference for records in statbuf - one hour
|
||||
#define STATMAXT (3600.)
|
||||
|
||||
// main statistical data
|
||||
typedef struct{
|
||||
double min;
|
||||
double max;
|
||||
double mean;
|
||||
double rms;
|
||||
} stat_t;
|
||||
|
||||
typedef struct{
|
||||
stat_t windspeed;
|
||||
stat_t winddir;
|
||||
stat_t pressure;
|
||||
stat_t temperature;
|
||||
stat_t humidity;
|
||||
stat_t rainfall;
|
||||
stat_t tmeasure;
|
||||
} weatherstat_t;
|
||||
|
||||
double stat_for(double Tsec, weatherstat_t *wstat);
|
||||
void addtobuf(weather_t *record);
|
||||
double get_tmax();
|
||||
156
Daemons/deprecated/weatherdaemon_newmeteo.deprecated/term.c
Normal file
156
Daemons/deprecated/weatherdaemon_newmeteo.deprecated/term.c
Normal file
@@ -0,0 +1,156 @@
|
||||
/*
|
||||
* This file is part of the weatherdaemon project.
|
||||
* Copyright 2021 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 <ctype.h> // isspace
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <strings.h> // strncasecmp
|
||||
#include <time.h> // time(NULL)
|
||||
#include <limits.h> // INT_MAX, INT_MIN
|
||||
#include <pthread.h>
|
||||
|
||||
#include "cmdlnopts.h"
|
||||
#include "term.h"
|
||||
|
||||
#define BUFLEN (4096)
|
||||
|
||||
static TTY_descr *ttydescr = NULL;
|
||||
extern glob_pars *GP;
|
||||
|
||||
static char buf[BUFLEN];
|
||||
static const char *emultemplate = "0R0,S=1.9,D=217.2,P=787.7,T=10.8,H=69.0,R=31.0,Ri=0.0,Rs=Y";
|
||||
|
||||
/**
|
||||
* read strings from terminal (ending with '\n') with timeout
|
||||
* @return NULL if nothing was read or pointer to static buffer
|
||||
*/
|
||||
static char *read_string(){
|
||||
//static int done = 0;
|
||||
if(GP->emul){
|
||||
strncpy(buf, emultemplate, BUFLEN);
|
||||
return buf;
|
||||
}
|
||||
if(!ttydescr) ERRX("Serial device not initialized");
|
||||
size_t r = 0, l;
|
||||
int LL = BUFLEN - 1;
|
||||
char *ptr = buf;
|
||||
double d0 = dtime();
|
||||
do{
|
||||
if((l = read_tty(ttydescr))){
|
||||
strncpy(ptr, ttydescr->buf, LL);
|
||||
r += l; LL -= l; ptr += l;
|
||||
//DBG("l=%zd, r=%zd, LL=%d", l, r, LL);
|
||||
d0 = dtime();
|
||||
if(r > 2 && ptr[-1] == '\n') break;
|
||||
}
|
||||
}while(dtime() - d0 < WAIT_TMOUT && LL);
|
||||
if(r){
|
||||
//buf[r] = 0;
|
||||
//DBG("buf: %s", buf);
|
||||
return buf;
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/**
|
||||
* Try to connect to `device` at baudrate speed
|
||||
* @return 1 if OK
|
||||
*/
|
||||
int try_connect(char *device, int baudrate){
|
||||
if(!device) return 0;
|
||||
fflush(stdout);
|
||||
ttydescr = new_tty(device, baudrate, 1024);
|
||||
if(ttydescr) ttydescr = tty_open(ttydescr, 1); // exclusive open
|
||||
if(!ttydescr) return 0;
|
||||
while(read_tty(ttydescr)); // clear rbuf
|
||||
LOGMSG("Connected to %s", device);
|
||||
return 1;
|
||||
}
|
||||
|
||||
// stop polling thread and close tty
|
||||
void stop_tty(){
|
||||
if(ttydescr) close_tty(&ttydescr);
|
||||
}
|
||||
|
||||
static weather_t lastweather;
|
||||
typedef struct{
|
||||
const char *parname;
|
||||
int parlen;
|
||||
double *weatherpar;
|
||||
} wpair_t;
|
||||
|
||||
static const wpair_t wpairs[] = {
|
||||
{"S=", 2, &lastweather.windspeed},
|
||||
{"D=", 2, &lastweather.winddir},
|
||||
{"P=", 2, &lastweather.pressure},
|
||||
{"T=", 2, &lastweather.temperature},
|
||||
{"H=", 2, &lastweather.humidity},
|
||||
{"R=", 2, &lastweather.rainfall},
|
||||
{NULL, 0, NULL}
|
||||
};
|
||||
|
||||
static int parseans(char *str, weather_t *w){
|
||||
if(strncmp(str, "0R0,", 4)){
|
||||
WARNX("Wrong answer");
|
||||
LOGWARN("poll_device() get wrong answer: %s", str);
|
||||
return FALSE;
|
||||
}
|
||||
str += 3;
|
||||
do{
|
||||
++str;
|
||||
//DBG("start=%s", str);
|
||||
const wpair_t *el = wpairs;
|
||||
while(el->parname){
|
||||
if(strncmp(str, el->parname, el->parlen) == 0){ // found next parameter
|
||||
str += el->parlen;
|
||||
char *endptr;
|
||||
*el->weatherpar = strtod(str, &endptr);
|
||||
DBG("found par: %s, val=%g", el->parname, *el->weatherpar);
|
||||
if(endptr == str){
|
||||
DBG("Wrong double value");
|
||||
*el->weatherpar = 0.;
|
||||
//return FALSE;
|
||||
}
|
||||
break;
|
||||
}
|
||||
++el;
|
||||
}
|
||||
str = strchr(str, ',');
|
||||
//DBG("next=%s", str);
|
||||
}while(str && *str);
|
||||
lastweather.tmeasure = dtime();
|
||||
if(w) memcpy(w, &lastweather, sizeof(weather_t));
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
// get weather measurements; return FALSE if something failed
|
||||
int getlastweather(weather_t *w){
|
||||
if(!GP->emul){
|
||||
if(write_tty(ttydescr->comfd, "!0R0\r\n", 6))
|
||||
return FALSE;
|
||||
}
|
||||
double t0 = dtime();
|
||||
while(dtime() - t0 < T_POLLING_TMOUT){
|
||||
char *r = NULL;
|
||||
if((r = read_string())){ // parse new data
|
||||
//DBG("got %s", r);
|
||||
if(parseans(r, w)) return TRUE;
|
||||
}
|
||||
}
|
||||
return FALSE;
|
||||
}
|
||||
46
Daemons/deprecated/weatherdaemon_newmeteo.deprecated/term.h
Normal file
46
Daemons/deprecated/weatherdaemon_newmeteo.deprecated/term.h
Normal file
@@ -0,0 +1,46 @@
|
||||
/*
|
||||
* This file is part of the weatherdaemon project.
|
||||
* Copyright 2021 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
|
||||
#ifndef __TERM_H__
|
||||
#define __TERM_H__
|
||||
|
||||
#include <usefull_macros.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)
|
||||
|
||||
typedef struct{
|
||||
double windspeed; // speed in m/s
|
||||
double winddir; // direction from north
|
||||
double pressure; // pressure in hPa
|
||||
double temperature; // outern temperature in degC
|
||||
double humidity; // humidity in percents
|
||||
double rainfall; // cumulative rain level (mm)
|
||||
double tmeasure; // UNIX-time of last measure
|
||||
} weather_t;
|
||||
|
||||
int try_connect(char *device, int baudrate);
|
||||
int getlastweather(weather_t *w);
|
||||
void stop_tty();
|
||||
|
||||
#endif // __TERM_H__
|
||||
@@ -0,0 +1 @@
|
||||
-std=c17
|
||||
@@ -0,0 +1,4 @@
|
||||
#define EBUG 1
|
||||
#define _GNU_SOURCE
|
||||
#define _XOPEN_SOURCE 1111
|
||||
#define _POSIX_C_SOURCE 200000
|
||||
@@ -0,0 +1 @@
|
||||
[General]
|
||||
@@ -0,0 +1,160 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE QtCreatorProject>
|
||||
<!-- Written by QtCreator 8.0.2, 2023-05-23T16:02:23. -->
|
||||
<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.PreferSingleLineComments">false</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="bool" key="EditorConfiguration.UseIndenter">false</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="QString" key="EditorConfiguration.ignoreFileTypes">*.md, *.MD, Makefile</value>
|
||||
<value type="bool" key="EditorConfiguration.inEntireDocument">true</value>
|
||||
<value type="bool" key="EditorConfiguration.skipTrailingWhitespace">true</value>
|
||||
</valuemap>
|
||||
</data>
|
||||
<data>
|
||||
<variable>ProjectExplorer.Project.PluginSettings</variable>
|
||||
<valuemap type="QVariantMap">
|
||||
<valuemap type="QVariantMap" key="ClangTools">
|
||||
<value type="bool" key="ClangTools.AnalyzeOpenFiles">true</value>
|
||||
<value type="bool" key="ClangTools.BuildBeforeAnalysis">true</value>
|
||||
<value type="QString" key="ClangTools.DiagnosticConfig">Builtin.DefaultTidyAndClazy</value>
|
||||
<value type="int" key="ClangTools.ParallelJobs">4</value>
|
||||
<valuelist type="QVariantList" key="ClangTools.SelectedDirs"/>
|
||||
<valuelist type="QVariantList" key="ClangTools.SelectedFiles"/>
|
||||
<valuelist type="QVariantList" key="ClangTools.SuppressedDiagnostics"/>
|
||||
<value type="bool" key="ClangTools.UseGlobalSettings">true</value>
|
||||
</valuemap>
|
||||
</valuemap>
|
||||
</data>
|
||||
<data>
|
||||
<variable>ProjectExplorer.Project.Target.0</variable>
|
||||
<valuemap type="QVariantMap">
|
||||
<value type="QString" key="DeviceType">Desktop</value>
|
||||
<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/weatherdaemon_newmeteo</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="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="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.CustomParsers"/>
|
||||
<value type="bool" key="ProjectExplorer.BuildConfiguration.ParseStandardOutput">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.RunConfiguration.0">
|
||||
<valuelist type="QVariantList" key="CustomOutputParsers"/>
|
||||
<value type="int" key="PE.EnvironmentAspect.Base">2</value>
|
||||
<valuelist type="QVariantList" key="PE.EnvironmentAspect.Changes"/>
|
||||
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">ProjectExplorer.CustomExecutableRunConfiguration</value>
|
||||
<value type="QString" key="ProjectExplorer.RunConfiguration.BuildKey"></value>
|
||||
<value type="bool" key="RunConfiguration.UseCppDebugger">false</value>
|
||||
<value type="bool" key="RunConfiguration.UseCppDebuggerAuto">true</value>
|
||||
<value type="bool" key="RunConfiguration.UseQmlDebugger">false</value>
|
||||
<value type="bool" key="RunConfiguration.UseQmlDebuggerAuto">true</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>
|
||||
@@ -0,0 +1,167 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE QtCreatorProject>
|
||||
<!-- Written by QtCreator 4.8.2, 2020-08-27T15:02:35. -->
|
||||
<qtcreator>
|
||||
<data>
|
||||
<variable>EnvironmentId</variable>
|
||||
<value type="QByteArray">{7bd84e39-ca37-46d3-be9d-99ebea85bc0d}</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">true</value>
|
||||
<value type="bool" key="EditorConfiguration.ShowMargin">false</value>
|
||||
<value type="int" key="EditorConfiguration.SmartBackspaceBehavior">0</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">1</value>
|
||||
<value type="bool" key="EditorConfiguration.addFinalNewLine">true</value>
|
||||
<value type="bool" key="EditorConfiguration.cleanIndentation">false</value>
|
||||
<value type="bool" key="EditorConfiguration.cleanWhitespace">true</value>
|
||||
<value type="bool" key="EditorConfiguration.inEntireDocument">false</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">{65a14f9e-e008-4c1b-89df-4eaa4774b6e3}</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">/Big/Data/00__Small_tel/C-sources/netdaemon</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.DefaultDisplayName">Сборка</value>
|
||||
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></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">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.DefaultDisplayName">Сборка</value>
|
||||
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></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.DefaultDisplayName">По умолчанию</value>
|
||||
<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>
|
||||
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Конфигурация установки</value>
|
||||
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></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="bool" key="Analyzer.QmlProfiler.AggregateTraces">false</value>
|
||||
<value type="bool" key="Analyzer.QmlProfiler.FlushEnabled">false</value>
|
||||
<value type="uint" key="Analyzer.QmlProfiler.FlushInterval">1000</value>
|
||||
<value type="QString" key="Analyzer.QmlProfiler.LastTraceFile"></value>
|
||||
<value type="bool" key="Analyzer.QmlProfiler.Settings.UseGlobalSettings">true</value>
|
||||
<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.DefaultDisplayName">Особая программа</value>
|
||||
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value>
|
||||
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">ProjectExplorer.CustomExecutableRunConfiguration</value>
|
||||
<value type="QString" key="RunConfiguration.Arguments"></value>
|
||||
<value type="uint" key="RunConfiguration.QmlDebugServerPort">3768</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">20</value>
|
||||
</data>
|
||||
<data>
|
||||
<variable>Version</variable>
|
||||
<value type="int">20</value>
|
||||
</data>
|
||||
</qtcreator>
|
||||
@@ -0,0 +1,157 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE QtCreatorProject>
|
||||
<!-- Written by QtCreator 4.12.3, 2021-06-09T21:11:29. -->
|
||||
<qtcreator>
|
||||
<data>
|
||||
<variable>EnvironmentId</variable>
|
||||
<value type="QByteArray">{7bd84e39-ca37-46d3-be9d-99ebea85bc0d}</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">true</value>
|
||||
<value type="bool" key="EditorConfiguration.ShowMargin">false</value>
|
||||
<value type="int" key="EditorConfiguration.SmartBackspaceBehavior">0</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">1</value>
|
||||
<value type="bool" key="EditorConfiguration.addFinalNewLine">true</value>
|
||||
<value type="bool" key="EditorConfiguration.cleanIndentation">false</value>
|
||||
<value type="bool" key="EditorConfiguration.cleanWhitespace">true</value>
|
||||
<value type="bool" key="EditorConfiguration.inEntireDocument">false</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">{65a14f9e-e008-4c1b-89df-4eaa4774b6e3}</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">/Big/Data/00__Small_tel/C-sources/netdaemon</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">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.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>
|
||||
@@ -0,0 +1 @@
|
||||
-std=c++17
|
||||
@@ -0,0 +1,9 @@
|
||||
cmdlnopts.c
|
||||
cmdlnopts.h
|
||||
main.c
|
||||
socket.c
|
||||
socket.h
|
||||
stat.c
|
||||
stat.h
|
||||
term.c
|
||||
term.h
|
||||
@@ -0,0 +1 @@
|
||||
.
|
||||
Reference in New Issue
Block a user