Compare commits

..

1 Commits

Author SHA1 Message Date
c8ee17854d a lot of fixes 2026-11-17 09:21:59 +03:00
15 changed files with 316 additions and 173 deletions

2
.gitignore vendored
View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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