more fixes

This commit is contained in:
2026-11-18 17:50:39 +03:00
parent 54653dde4a
commit 9dcfafa5e4
15 changed files with 742 additions and 105 deletions

View File

@@ -2,7 +2,7 @@
CLIENT := dome_client
SERVER := dome_server
LDFLAGS += -fdata-sections -ffunction-sections -Wl,--gc-sections -Wl,--discard-all
LDFLAGS += -lusefull_macros -lssl -lcrypto
LDFLAGS += -pthread -lusefull_macros -lssl -lcrypto
DEFINES := $(DEF) -D_GNU_SOURCE -D_XOPEN_SOURCE=1111
SOBJDIR := mkserver
COBJDIR := mkclient
@@ -18,7 +18,7 @@ CC = gcc
TARGFILE := build.target
ifeq ($(shell test -e $(TARGFILE) && echo -n yes),yes)
ifeq ($(shell test -e $(TARGFILE) && printf yes),yes)
TARGET := $(file < $(TARGFILE))
else
TARGET := RELEASE
@@ -30,6 +30,7 @@ endif
release: CFLAGS += -flto
release: LDFLAGS += -flto
release: TARGET := RELEASE
release: $(TARGFILE) $(CLIENT) $(SERVER)
debug: CFLAGS += -DEBUG -Werror
@@ -41,16 +42,17 @@ $(TARGFILE):
@echo "$(TARGET)" > $(TARGFILE)
$(CLIENT) : DEFINES += -DCLIENT
$(CLIENT) : LDFLAGS += -lcrypt
$(CLIENT) : $(COBJDIR) $(COBJS)
@echo -e "\tLD $(CLIENT)"
$(CC) $(LDFLAGS) $(COBJS) -o $(CLIENT)
$(CC) $(COBJS) -o $(CLIENT) $(LDFLAGS)
$(SERVER) : DEFINES += -DSERVER
$(SERVER) : LDFLAGS += -lmodbus
$(SERVER) : $(SOBJDIR) $(SOBJS)
@echo -e "\tLD $(SERVER)"
$(CC) $(LDFLAGS) $(SOBJS) -o $(SERVER)
$(CC) $(SOBJS) -o $(SERVER) $(LDFLAGS)
$(SOBJDIR):
@mkdir $(SOBJDIR)
@@ -65,17 +67,17 @@ endif
$(COBJDIR)/%.o: %.c
@echo -e "\tCC $<"
$(CC) -MP -MMD -c $(LDFLAGS) $(CFLAGS) $(DEFINES) -o $@ $<
$(CC) -MP -MMD -c $(CFLAGS) $(DEFINES) -o $@ $<
$(SOBJDIR)/%.o: %.c
@echo -e "\t\tCC $<"
$(CC) -MP -MMD -c $(LDFLAGS) $(CFLAGS) $(DEFINES) -o $@ $<
$(CC) -MP -MMD -c $(CFLAGS) $(DEFINES) -o $@ $<
clean:
@echo -e "\t\tCLEAN"
@rm -rf $(SOBJDIR) $(COBJDIR) $(TARGFILE) 2>/dev/null || true
xclean: clean
@rm -f $(PROGRAM)
@rm -f $(CLIENT) $(SERVER)
.PHONY: clean xclean
.PHONY: clean xclean $(TARGFILE)

498
BTA_dome_modbus/Readme.md Normal file
View File

@@ -0,0 +1,498 @@
# Dome Control System over SSL-sockets
## 1. Overview
The product is a two‑part system for controlling BTA dome driven by a set of AC motors with
**ESQ‑770** frequency converters and a **Modbus I/O board** (relays, discrete inputs, ADC):
* **`dome_server`** — runs on the machine connected to the RS‑485 bus. It talks Modbus RTU to the
frequency converters and the I/O board, and serves an SSL/TLS socket with a simple ASCII line
protocol.
* **`dome_client`** — connects to the server, keeps the dome shared‑memory block (`bta_shdata`) up
to date, drives the motors according to commands from the higher‑level control system, and can also
be used interactively in *terminal mode*.
Both binaries share the same argument parser, daemonization code, and SSL socket layer. The client
and server are mutually exclusive builds of the same sources (`-DCLIENT` / `-DSERVER`).
Key properties:
| Property | Value |
|---|---|
| Transport | TCP + TLS (min. TLS 1.2), mutual authentication |
| Default port | 4444 |
| Protocol | newline‑terminated ASCII, `key` (getter) or `key=value` (setter) |
| Motor bus | Modbus RTU over RS‑485, 10 drives, IDs 1…10 |
| Max SSL clients | 10 (`BACKLOG`) |
| Network timeout | 1 s (configurable) |
## 2. Repository layout
| File | Purpose |
|---|---|
| `main.c` | Entry point: init, parse args, start daemon |
| `cmdlnopts.c/.h` | Command line / config file parsing, global `G` structure |
| `daemon.c/.h` | Daemonization, PID file, signal handling, child supervision |
| `sslsock.c/.h` | SSL context creation, socket open/connect, `read_string()` |
| `client.c/.h` | Client main loop, terminal mode, motor polling, speed control |
| `server.c/.h` | Server poll loop, connection handling, command dispatch, handlers |
| `motors.c/.h` | Modbus motor control, state cache, emulation, logging |
| `io.c/.h` | Modbus I/O board: relays, inputs, ADC, safety interlock logic |
| `esq770.h` | ESQ‑770 register map, command/status codes, unit conversions |
| `handlers_list.h` | X‑macro list of protocol commands (must stay sorted!) |
| `Makefile` | Build rules for `dome_client` / `dome_server` |
| `bta_shdata.c/.h` | shared memory with the dome control subsystem |
## 3. Building
```sh
make # release build (adds -flto); the default target
make debug # debug build (-Werror, -DEBUG)
make clean # remove object dirs and build.target
make xclean # clean + remove binaries
```
Dependencies:
* [`libusefull_macros`](https://github.com/eddyem/snippets_library) (logging, CLI parsing, config files, time helpers)
* OpenSSL (`libssl`, `libcrypto`)
* [`libmodbus`](https://github.com/stephane/libmodbus) (server only)
* `libcrypt` (client only)
Build details:
* The selected target is stored in `build.target`; if it contains `DEBUG`, a plain `make` also
builds the debug variant. Use `make DEF=...` to append extra defines.
* Binaries are `dome_server` and `dome_client`; objects go to `mkserver/` and `mkclient/`
respectively.
* The debug build passes `-DEBUG`, which GCC interprets as `-D EBUG`, i.e. it defines the `EBUG`
macro used throughout the code for verbose diagnostic printing.
## 4. Architecture
```
higher-level control (GUI / SHM) operator (terminal mode)
| |
bta_shdata <--- dome_client ---TLS---> dome_server
|
Modbus RTU (RS-485)
/ \
ESQ-770 drives 1..10 I/O board
(motors) (relays/inputs/ADC)
```
* The **client** reads the shared memory block `sdat` (dome speed command, lock flags, telescope
position, server PID, etc.), polls motor state from the server in a round‑robin fashion, writes
averaged state and SEW data back into SHM, and sends status messages to the GUI via
`SendMessage()`.
* The **server** is a poll‑driven event loop: every iteration it advances the motor state machine,
processes the I/O board, and serves any pending SSL traffic.
* Both sides are non‑blocking; the server uses `poll()` with an 1 ms timeout, the client sleeps ~100
ms per cycle.
## 5. SSL layer (`sslsock.c`)
`open_socket()`:
1. Initializes the OpenSSL library and creates a context (`TLS_server_method()` /
`TLS_client_method()`).
2. Requires TLS ≥ 1.2.
3. Loads the CA file (`-a`, default `ca_cert.pem`); on the server side the CA list is also loaded
so the client certificate can be requested.
4. Loads the certificate (`-c`) and private key (`-k`), checks key/cert match.
5. Verification:
* **Server**: `SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT` — a valid client certificate
signed by the CA is mandatory.
* **Client**: `SSL_VERIFY_PEER`.
* Verification depth is limited to 1 (only certificates signed directly by the CA are accepted).
6. Opens the socket:
* **Server**: `bind()` to `INADDR_ANY:<port>` with `SO_REUSEADDR`, then `listen(BACKLOG)`.
* **Client**: resolves `--server` via `gethostbyname()` and `connect()`s.
`read_string(ssl, buf, l)` reads one `\n`‑terminated line:
* Uses `SSL_peek()` to locate the newline without consuming data.
* If the buffer fills up before a newline, the pending data is discarded (`SSL_read` of `l` bytes)
and `0` is returned.
* Returns the number of bytes read (the trailing `\n` is replaced by `\0`), `0` if nothing is
available or the line is incomplete, and `-1` on disconnect/error. `SSL_ERROR_WANT_READ/WRITE` are
treated as “nothing yet”.
## 6. Protocol
Text, one message per line, `\n` terminator.
### 6.1 Message forms
| Form | Meaning | Reply |
|---|---|---|
| `name` | getter | `name=value` |
| `name=value` | setter | `OK`, `BADVAL`, `BADKEY` or `FAIL` |
| `help` | list commands | one `command: description` line per command |
| empty line / comment | ignored | (no reply) |
The client side (`send_motor_command()`) distinguishes getters from setters by the presence of `=`,
and treats the four uppercase tokens above as setter results. In practice only `motnum`,
`motstatus`, `motspeed`, `motcurrent`, `speed`, `stop`, `nmotors`, `forbidden` are used by the
client.
### 6.2 Result codes
| Token | Enum | Meaning |
|---|---|---|
| `OK` | `RESULT_OK` | setter executed |
| `BADVAL` | `RESULT_BADVAL` | malformed or out‑of‑range argument |
| `BADKEY` | `RESULT_BADKEY` | unknown command |
| `FAIL` | `RESULT_FAIL` | command failed (e.g. motors not running) |
| *(no token)* | `RESULT_SILENCE` | internal: getter answer is sent as `key=value` or no answer at all |
## 7. Command reference
All commands are defined once in `handlers_list.h` and expanded into the server’s dispatch table.
**The list must be kept in alphabetical order** — the server looks commands up with a binary search
(`search_handler()`).
| Command | Access | Argument / answer | Description |
|---|---|---|---|
| `adc=N` | get | `N` → `value` | Read ADC channel `N` (0…7) |
| `forbidden` | get/set | `0`/`1` | Setter: `1` forbids dome operations (blocks motors), `0` permits. Getter: state of the `RELAY_BLOCK_MOTORS` relay (`1` = forbidden) |
| `inputs` | get | decimal mask | State of the 16 discrete inputs |
| `logprefix` | get/set | string ≤ 31 chars | Prefix of motor log files (`<prefix>_NN.log`) |
| `motcurrent` | get | amps | Current of the active motor |
| `motnum` | get/set | `0`…`9` | Number of the motor used by status/current/speed getters |
| `motspeed` | get | rev/min | Speed of the active motor |
| `motstatus` | get | `0`…`3` | Status of the active motor (see below) |
| `nmotors` | get | count | Number of motors whose status is not `OFF` |
| `relayon` | get/set | `N` / mask | Setter: turn relay `N` on. Getter: full relay state mask |
| `relayoff` | get/set | `N` / mask | Setter: turn relay `N` off. Getter: full relay state mask |
| `relayset` | get/set | mask | Setter: set/reset all relays at once by bit mask. Getter: state mask |
| `speed` | get/set | rev/min | Setter: speed setpoint, sign selects direction, `0` stops. Getter: current setpoint |
| `startlog` | action | — | Open per‑motor log files |
| `stop` | action | — | Stop all motors |
| `stoplog` | action | — | Close log files |
### Motor status values (`motors.h`)
| Value | Name | Meaning |
|---|---|---|
| 0 | `MOT_OFF` | no answer / disabled |
| 1 | `MOT_SLEEP` | stopped but ready |
| 2 | `MOT_RUN` | rotating |
| 3 | `MOT_ERROR` | drive fault |
`nmotors` counts all motors whose status differs from `MOT_OFF`.
### Relay / input bit masks (`io.h`)
Inputs (16 bits):
| Bit | Macro | Meaning |
|---|---|---|
| 0 | `INP_FLOOR1` | man on floor 1 |
| 1 | `INP_FLOOR2` | man on floor 2 |
| 2 | `INP_DOOR_OPENED` | door is open |
| 3 | `INP_OPEN_DOOR` | “open door” request |
| 4 | `INP_TEL_AT_NEST` | telescope is at the “nest” |
Relays (16 bits, only some are populated):
| Number | Macro | Meaning |
|---|---|---|
| 1 | `RELAY_OPEN_DOOR` | open the door |
| 2 | `RELAY_BLOCK_DOOR` | block the door |
| 3 | `RELAY_LIGHT` | turn on light |
| 4 | `RELAY_POWER` | turn on power socket |
| 5 | `RELAY_BLOCK_MOTORS` | block (inhibit) the motors |
| 10 | `RELAY_DOOR_UNLOCKED` | door is unlocked (turn on light) |
## 8. Server
### 8.1 Startup
`main()` → `sl_init()` → `parse_args()` → `start_daemon()` → `open_socket()` → `serverproc()`.
`start_daemon()` (in `daemon.c`) validates the port (1024…65535) and that certificate/key files can
be opened; optionally opens the log file; installs signal handlers; checks for an already‑running
instance via the PID file; then daemonizes and runs the supervision loop:
* The **master** forks a child, waits for it, logs the child’s lifetime, and respawns after 5 s.
Logging is throttled if children die faster than 30 s.
* The **child** sets `PR_SET_PDEATHSIG = SIGTERM` (it is killed when the master dies), sets
`isrunning = TRUE` and runs the main loop.
Signals: `SIGTERM`, `SIGINT`, `SIGQUIT` set `isrunning = FALSE` and exit (after removing the PID
file); `SIGTSTP` and `SIGHUP` are ignored.
### 8.2 Main loop (`serverproc()`)
1. `motors_process()` — advance the motor state machine (one motor per call plus queued commands).
2. `io_process()` — read inputs/relays/ADC from the I/O board and apply the safety logic.
3. `poll(..., 1 ms)`.
4. On the listening socket: `accept4(..., SOCK_NONBLOCK)`, then `SSL_new()` + timeout‑protected
`SSL_accept()` (bounded by `--timeout`). On failure the client is sent an error and disconnected.
Up to `BACKLOG` (10) clients are served.
5. For each readable client: `handle_connection()` — read one line, parse `key[=value]`, dispatch
to the handler, write the reply. On disconnect the last poll entry is moved into the freed slot.
On exit the server stops all motors and closes the Modbus connection.
### 8.3 Motor control (`motors.c`)
* One Modbus RTU context for the whole process, shared with `io.c` via `io_set_ctx()`.
* **Shared‑memory‑like state** in the server: `motstates[10]`, `n_working_motors`, speed/current
setpoints, and a bit‑flag word (`stop`, `change_speed`, `change_current`), all protected by
`statemutex`.
* **Setter path** (`motors_set_speedsetpoint()`, `motors_set_curntsetpoint()`, `motors_stop()`)
only sets flags; the actual bus traffic happens in `motors_process_m()`:
* Commands are sent to the **broadcast** slave address 0 (`modbus_set_slave(ctx, 0)`) without
checking the return code (what's impossible in broadcast mode).
* `stop` → `CMD_STOP` on `REG_CMD`, setpoint zeroed.
* Speed change: if `|speed| < SPEED_TOLERANCE` → `CMD_STOP`; otherwise write
`CMD_FORWARD`/`CMD_REVERSE` to `REG_CMD` and `REVMIN2FREQ(|speed|)` to `REG_FREQ_SET`.
* Setting a speed requires `n_working_motors ≥ MIN_WORKING_MOTORS` (1); otherwise `RESULT_FAIL`.
* `|speed| > MAX_SPEED` (655 rev/min) → `RESULT_BADVAL`.
* Changing the current setpoint is currently a stub (`change_current` is cleared without bus
traffic).
* **Polling path**: each call selects one slave `MOTOR_ID(curN) = curN+1` and reads
`REG_STATUS_MAIN`, `REG_STATUS_EXT`, `REG_OUTPUT_FREQ`, `REG_OUTPUT_CURRENT`; converts to rev/min
and amperes; maps statuses:
* `STATUS_CW`, `STATUS_CCW` → `MOT_RUN`
* `STATUS_STOP` → `MOT_SLEEP`
* anything else → `MOT_ERROR`
* `STATUS_READY_MASK` absent in the extended status → forced `MOT_ERROR`; an attempt is made to
reset the fault with `CMD_RESET_FAULT`.
* After `MAX_ERRORS` (5) consecutive bus errors the motor is marked `MOT_OFF`.
* `count_motors()` recomputes `n_working_motors` after each full sweep.
### 8.4 Motor logging
`start_log()` opens `<mldir>/<prefix>_NN.log` (append mode) for each motor (default prefix `motor`,
default directory `/tmp`). Each poll writes `time<TAB>speed<TAB>current`, but only while the motor
is `MOT_RUN`. `stop_log()` closes them. Prefixes are validated (`set_logfile_prefix()` rejects `/`,
`%`, control characters and non‑ASCII, and limits length to 31).
### 8.5 Emulation mode
With `--emulation` the server skips the serial port and uses `motors_open_e()` /
`motors_process_e()`:
* All motors start in `MOT_SLEEP`; `n_working_motors = 10`.
* Speed ramps linearly toward the setpoint with `EMUL_ACCEL` (10000 min⁻²); current equals the
current setpoint while accelerating and 0.6 × setpoint when at speed.
### 8.6 I/O board (`io.c`)
* The board is addressed by `G.io_ID`; if it is < 1 or the Modbus context is missing,
`io_process()` does nothing.
* Each pass reads 16 inputs, 16 relay outputs and 8 ADC registers, updates the cached state under a
mutex, then runs the interlock logic.
* **Inputs → relays** (`chk_inputs()`):
* Any of `FLOOR1`, `FLOOR2`, `DOOR_OPENED` → door unblocked and unlocked, motors blocked, light on.
* `TEL_AT_NEST` → door unblocked/unlocked, and if `OPEN_DOOR` is asserted the door is opened and
the motors blocked.
* Otherwise the door is blocked and locked; if somebody is on the nest without the telescope, the
open‑door request is honoured.
* **Relays → relays** (`chk_relays()`): motors blocked ⇒ light on, otherwise off. Pending user
requests (`OnFlags`/`OffFlags`) are applied and cleared.
* Public API: `io_read_inputs()`, `io_read_relays()`, `io_read_adc()`, `io_relay_on()`,
`io_relay_off()`, `io_set_relays()`.
* At server start, `io_set_relays(0)` turns everything off and then `RELAY_BLOCK_MOTORS` is
switched on (inhibit by default).
## 9. Client
### 9.1 Connection setup
`clientproc()` / `terminal()` create an SSL connection (`openConn()`), make the socket
non‑blocking, attach the shared memory block (`get_shm_block(&sdat, ClientSide)` — may fail if the
SHM block is not created by the higher‑level system), the command queues (`mcmd`, `ocmd`, `ucmd`),
and publish `DomeSEW_N = MOTORS_AMOUNT`.
### 9.2 Background (daemon) mode — `clientproc()`
Every ~100 ms:
1. `process_system(ssl)`:
* **SHM watchdog**: if `M_time` lags more than `T_sync_lost` behind wall time, or
`check_shm_block()` fails, the client tolerates 9 failures and exits on the 10th.
* **Model mode**: if the SHM reports `UseModel == FullModel`, the client logs a warning once, sends
an emergency stop, and suspends control until the model mode ends.
* **Server liveness** (unless `--emulation`): `kill(ServPID, 0)`; two consecutive failures
terminate the client.
* **Motor polling**: round‑robin over 10 motors with 4 commands each — `motnum=N`, `motstatus`,
`motspeed`, `motcurrent`. The active‑motor data feed the `SEWD` variables (`statusSEWD`,
`vel_SEWD`, `currentSEWD`) for `indexSEWD`.
* After the full sweep, the **common state** is computed: status = maximum over motors,
speed/current = mean over `MOT_RUN` motors. Transitions between “all off” and “any running”
generate `MesgFault`/`MesgInfor` messages to the GUI; an unresponsive motor in error state
generates `MesgWarn`.
* `chk_dome_speed()`: translates the SHM `Dome_Speed` state (`D_Off`, `D_Lplus/Lminus`,
`D_Mplus/Mminus`, `D_Hplus/Hminus`) into ±`LSpeed`/`MSpeed`/`HSpeed` (±71/350/610 rev/min). The
command is (re)sent every `speedchk_interval` seconds until the measured speed is within
`SPEED_TOLERANCE` of the setpoint. `D_Locked` forces a stop.
2. Drain and log any unsolicited data from the server.
On exit: `stop_all()` sends `stop` up to 5 times (100 ms apart); if all attempts fail, an error is
logged; otherwise `Dome_Speed` is reset.
### 9.3 Terminal mode — `terminal()`
Enabled by `-T`. Before daemonizing (so it works without detaching), the client offers a raw line
pipe:
* `> ` prompt; each line read from stdin is written to the SSL connection.
* Every reply line is printed as `< reply`.
* `Ctrl‑D` or a write error ends the session.
The shared memory block and automatic motor polling are **not** used in this mode.
## 10. ESQ‑770 frequency converter interface (`esq770.h`)
| Register | Address | Access | Contents |
|---|---|---|---|
| `REG_CMD` | 0x2000 | RW | Command |
| `REG_FREQ_SET` | 0x3000 | RW | Frequency setpoint (0.01 Hz) |
| `REG_TORQUE_LIMIT` | 0x3006 | RW | Torque limit |
| `REG_BRAKE_TORQUE_LIMIT` | 0x3007 | RW | Brake torque limit |
| `REG_STATUS_MAIN` | 0x6000 | R | Main status |
| `REG_STATUS_EXT` | 0x6001 | R | Extended status |
| `REG_OUTPUT_FREQ` | 0xA201 | R | Output frequency × 100 |
| `REG_OUTPUT_CURRENT` | 0xA204 | R | Output current × 10 |
| `REG_MOTOR_SPEED` | 0xA205 | R | Speed (depends on settings) |
Commands (`REG_CMD`): `CMD_FORWARD` = 1, `CMD_REVERSE` = 2, `CMD_STOP` = 5, `CMD_FAST_STOP` = 6,
`CMD_RESET_FAULT` = 7.
Main status (`REG_STATUS_MAIN`): `STATUS_CW` = 1, `STATUS_CCW` = 2, `STATUS_STOP` = 3, `STATUS_ERR`
= 4, `STATUS_LOW_V` = 5. Extended status bit `STATUS_READY_MASK` = 0x01.
Conversions (4‑pole motor, 100× scale):
```c
REVMIN2FREQ(r) = (uint16_t)(100. * r / 15.) /* rev/min → register */
FREQ2REVMIN(f) = (f * 15.) / 100. /* register → rev/min */
current[A] = register / CURRENT_SCALE /* CURRENT_SCALE = 10 */
```
Because the frequency register is 16‑bit, the maximum representable speed is 655.35 rev/min
(`MAX_SPEED = 655`).
## 11. Command line options
Defined in `cmdlnopts.c`; configuration files (`-C`) use the same names and take precedence over
the command line. `-v`, `-v2`, `-v3` raise the log level to MSG, DBG and ANY respectively (default
WARN).
### Common
| Option | Argument | Default | Description |
|---|---|---|---|
| `-h`, `--help` | — | — | show help |
| `-l`, `--logfile` | file | — | write logs to this file |
| `-P`, `--pidfile` | file | `/tmp/domeserver.pid` / `/tmp/domeclt.pid` | PID file |
| `-c`, `--certificate` | file | `server_cert.pem` / `client_cert.pem` | SSL certificate |
| `-k`, `--key` | file | `server_key.pem` / `client_key.pem` | SSL private key |
| `-p`, `--port` | string | `4444` | TCP port |
| `-v`, `--verbose` | int (optional) | 0 | verbosity level |
| `-a`, `--ca` | file | `ca_cert.pem` | CA certificate |
| `-t`, `--timeout` | double | 1 s | network timeout (accept, command reply) |
| `-C`, `--conffile` | file | — | configuration file |
The certificate and private key files must have absolute path as are opened after daemonisation
and `chroot('/')`.
### Server only
| Option | Argument | Default | Description |
|---|---|---|---|
| `-e`, `--emulation` | — | off | emulation mode (no hardware) |
| `-d`, `--serialdev` | file | — | RS‑485 device path (absolute) |
| `-s`, `--serialspeed` | int | — | serial port speed |
| `-D`, `--mldir` | dir | `/tmp` | directory for motor log files (absolute) |
| `-i`, `--ioid` | int | −1 | Modbus ID of the I/O board (disabled if < 1) |
### Client only
| Option | Argument | Default | Description |
|---|---|---|---|
| `-M`, `--mottmout` | double | 10 s | interval for re‑sending the speed command until it is reached |
| `-s`, `--server` | host | — (required) | server name or IP |
| `-L`, `--lostsync` | double | 5 s | shared‑memory “lost synchronization” timeout |
| `-e`, `--emulation` | — | off | run even if the SHM reports emulation mode |
| `-T`, `--terminal` | — | off | interactive terminal mode |
Note that `-s` has different meanings in the server (`serialspeed`) and client (`server`) builds —
the option tables are compiled conditionally.
## 12. Tuning constants
`motors.h` / `esq770.h`:
| Constant | Value | Meaning |
|---|---|---|
| `MOTORS_AMOUNT` | 10 | number of drives |
| `START_ID` / `MOTOR_ID(n)` | 1 / `n+1` | Modbus slave addresses |
| `MIN_WORKING_MOTORS` | 1 | minimum motors to allow a speed setpoint |
| `MAX_ERRORS` | 5 | consecutive bus errors before a motor is `MOT_OFF` |
| `MAX_SPEED` | 655 | rev/min |
| `SPEED_TOLERANCE` | 0.01 | rev/min |
| `MAX_CURRENT` / `DEFAULT_CURRENT` | 15 / 10 | A |
| `LSpeed` / `MSpeed` / `HSpeed` | 71 / 350 / 610 | rev/min presets |
| `MODBUS_RESPONCE_TIMEOUT` | 100000 | µs |
| `EMUL_ACCEL` | 10000 | min⁻² |
| `BACKLOG` | 10 | max simultaneous SSL clients |
| `IOBUF_LEN` / `SL_VAL_LEN` / `SL_KEY_LEN` | 256 / (external) | protocol buffer sizes |
## 13. Client ↔ shared memory integration
The client depends on the `bta_shdata.[ch]` module that provides:
* `sdat` — the shared `struct` (mode, `atflag`, `Dome_Speed`, `D_Locked`, `DomeSEW_N`, `indexSEWD`,
`statusSEWD`, `vel_SEWD`, `currentSEWD`, `speedSEWD`, `M_time`, `UseModel`, `ServPID`, …);
* command queues `mcmd`, `ocmd`, `ucmd` (motor / observer / user commands);
* helpers `get_shm_block()`, `check_shm_block()`, `get_cmd_queue()`;
* `SendMessage()` with `MesgWarn`, `MesgFault`, `MesgInfor` message classes for the GUI.
The client writes the shared block (`mode |= 0200`, i.e. write access, `atflag = 0`) and publishes
`DomeSEW_N`. If the block cannot be attached, the client logs the error and aborts.
## 14. Notes and caveats
* **Command order is significant.** `handlers_list.h` must remain alphabetically sorted; the server
uses binary search over the expanded table.
* **The `EBUG` macro** is produced by the Makefile’s `-DEBUG` flag (GCC parses it as `-D EBUG`).
Debug builds therefore enable extra `printf` traces in `io.c`, `motors.c`, etc., and disable
daemonization (`#ifndef EBUG` around `sl_daemonize()`), which is handy for running under a
debugger.
* **Setters vs. getters** are distinguished purely by the presence of `=`. `startlog`, `stop`,
`stoplog` are actions; any `=value` they receive is ignored.
* The relay getters of `relayon`, `relayoff`, `relayset` are identical (they all return the full
relay mask); the setter forms differ.
* The server **broadcasts** motion commands (slave 0) and therefore does not verify their
execution; confirmation happens only indirectly through the client’s periodic speed polling and
re‑sending.
* Motor speed commands are accepted only when at least `MIN_WORKING_MOTORS` drives are alive;
otherwise `RESULT_FAIL` is returned.
* `read_string()` silently drops a line that does not fit into the buffer; keep `IOBUF_LEN` in mind
for custom clients.
* The I/O board’s safety logic runs before the relay state is refreshed, so user relay requests
issued in the same iteration may be overwritten by the interlock rules on the next pass.
## 15. License
This repository is provided under the GNU General Public License v3 or later. Full text of the
GPLv3 is available at https://www.gnu.org/licenses/gpl-3.0.html.

View File

@@ -216,16 +216,18 @@ void set_cmd_src(uint32_t ip, int 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(size > 100){
size = 100;
buf[99] = 0;
}
if(cmd_code > 0)
mbuf.mtype = cmd_code;
mbuf.mtype = (int32_t)cmd_code;
else
return;
if(ucmd.id == snd_id) mbuf.acckey = ucmd.acckey;
@@ -242,6 +244,7 @@ void send_cmd(int cmd_code, char *buf, int size) {
mbuf.mtext[0] = 0;
size = 1;
}
// in case of error the message would be lost!
msgsnd(snd_id, (struct msgbuf *)&mbuf, size+12, IPC_NOWAIT);
}
@@ -317,21 +320,22 @@ void send_cmd_i3d1(int cmd_code, int32_t arg1, int32_t arg2, int32_t arg3, doubl
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;
struct crypt_data data[1] = {0};
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];
// normally we must check what crypt_r returns!
crypt_r(passwd, salt, data);
cod.c[0] = data->output[2];
key.c[0] = data->output[3];
cod.c[1] = data->output[4];
key.c[1] = data->output[5];
cod.c[2] = data->output[6];
key.c[2] = data->output[7];
cod.c[3] = data->output[8];
key.c[3] = data->output[9];
*keylev = key.ui;
*codlev = cod.ui;
}

View File

@@ -55,12 +55,12 @@ typedef struct{
arg_type_t type;
} value_t;
// setter: when setspeed command sent successfully
static double set_speed = 0.;
// common state - by last motor polled
static motor_state_t CommonState = {0};
// state of each motor
static motor_state_t MotorState[MOTORS_AMOUNT] = {0};
// new speed setter
static double set_speed = 0.;
static int SSL_nbread(SSL *ssl, char *buf, int bufsz){
struct pollfd fds = {0};
@@ -72,7 +72,8 @@ static int SSL_nbread(SSL *ssl, char *buf, int bufsz){
WARNX("poll()");
return 0;
}
if(fds.revents == POLLIN){
if(fds.revents & POLLHUP) return -1; // closed
if(fds.revents & POLLIN){
// DBG("Got info in fd #%d", fd);
int l = read_string(ssl, buf, bufsz);
// DBG("read %d bytes", l);
@@ -101,9 +102,10 @@ static sl_sock_hresult_e send_motor_command(SSL *ssl, const char *cmd, value_t *
l = snprintf(buf, IOBUF_LEN-1, "%s=%g\n", cmd, setter->d);
}
}else l = snprintf(buf, IOBUF_LEN-1, "%s\n", cmd);
if(l < 0 || l >= IOBUF_LEN) return RESULT_FAIL; // snprintf error or overflow
buf[l] = 0;
//DBG("Send to server: %s", buf);
SSL_write(ssl, buf, l);
if(!write_string(ssl, buf)) return RESULT_FAIL;
double t0 = sl_dtime();
while(sl_dtime() - t0 < G.acc_timeout){
l = SSL_nbread(ssl, buf, IOBUF_LEN-1);
@@ -170,6 +172,25 @@ static void stop_all(SSL *ssl){
++ntries;
usleep(100000);
}
if(ntries >= 5){
LOGERR("Can't run emergency motor's stopping!");
}else{
Dome_Speed = D_Off;
set_speed = 0.;
}
}
static int chkm(SSL *ssl, int motno){
value_t Ival = {.type = ARG_TYPE_INT, .i = motno};
value_t Dval = {.type = ARG_TYPE_DOUBLE};
if(RESULT_OK != send_motor_command(ssl, cmd_motnum, &Ival, NULL)) return -1;
if(RESULT_OK != send_motor_command(ssl, cmd_motstatus, NULL, &Ival)) return -1;
MotorState[motno].status = (int) Ival.i;
if(RESULT_OK != send_motor_command(ssl, cmd_motspeed, NULL, &Dval)) return 0;
MotorState[motno].speed = Dval.d;
if(RESULT_OK != send_motor_command(ssl, cmd_motcurrent, NULL, &Dval)) return 0;
MotorState[motno].current = Dval.d;
return 1;
}
/**
@@ -181,17 +202,13 @@ static void stop_all(SSL *ssl){
static int check_motor(SSL *ssl, int motno){
char msg[128];
if(!ssl || motno < 0 || motno >= MOTORS_AMOUNT) return FALSE;
value_t Ival = {.type = ARG_TYPE_INT, .i = motno};
value_t Dval = {.type = ARG_TYPE_DOUBLE};
if(RESULT_OK != send_motor_command(ssl, cmd_motnum, &Ival, NULL)) return FALSE;
if(RESULT_OK != send_motor_command(ssl, cmd_motstatus, NULL, &Ival)) return FALSE;
MotorState[motno].status = (int) Ival.i;
if(RESULT_OK != send_motor_command(ssl, cmd_motspeed, NULL, &Dval)) return FALSE;
MotorState[motno].speed = Dval.d;
if(RESULT_OK != send_motor_command(ssl, cmd_motcurrent, NULL, &Dval)) return FALSE;
MotorState[motno].current = Dval.d;
int ret = chkm(ssl, motno);
if(ret < 0){
ret = FALSE;
MotorState[motno].status = MOT_ERROR; // no answer -> error
}
// now set common state as mean of all
if(motno != MOTORS_AMOUNT - 1) return TRUE;
if(motno != MOTORS_AMOUNT - 1) return ret;
int status = 0, N = 0; // mean status is largest
double speed = 0., current = 0.;
for(int i = 0; i < MOTORS_AMOUNT; ++i){
@@ -199,12 +216,12 @@ static int check_motor(SSL *ssl, int motno){
if(s == MOT_OFF) continue;
if(s == MOT_ERROR){
*msg = MesgWarn;
printf(msg+1, "Dome: Error in motor %d!\n", i+1);
sprintf(msg+1, "Dome: Error in motor %d!\n", i+1);
SendMessage(msg);
MotorState[i].status = MOT_OFF;
s = MotorState[i].status = MOT_OFF;
}
if(status < s) status = s;
if(status == MOT_RUN){
if(s == MOT_RUN){
speed += MotorState[i].speed;
current += MotorState[i].current;
++N;
@@ -227,7 +244,7 @@ static int check_motor(SSL *ssl, int motno){
CommonState.status = status;
CommonState.speed = speed;
CommonState.current = current;
return TRUE;
return ret;
}
// check for speed change and send given command to server
@@ -242,8 +259,8 @@ static void chk_dome_speed(SSL *ssl){
if(new_state == old_state){
if(sl_dtime() - tlast < G.speedchk_interval) return;
DBG("Time - tlast = %g", sl_dtime() - tlast);
if(CommonState.speed == set_speed){
tlast = sl_dtime();
tlast = sl_dtime();
if(fabs(CommonState.speed - fabs(set_speed)) < SPEED_TOLERANCE){
return;
}
DBG("Speed set command still not sent");
@@ -275,7 +292,8 @@ static void chk_dome_speed(SSL *ssl){
value_t Dval = {.type = ARG_TYPE_DOUBLE, .d = new_speed};
if(RESULT_OK == send_motor_command(ssl, cmd_speed, &Dval, NULL)){
DBG("New speed %g sent", new_speed);
if(RESULT_OK == send_motor_command(ssl, cmd_speed, NULL, &Dval) && fabs(Dval.d - new_speed) <= FLT_EPSILON){
// check that server receives right new speed
if(RESULT_OK == send_motor_command(ssl, cmd_speed, NULL, &Dval) && fabs(Dval.d - new_speed) <= SPEED_TOLERANCE){
DBG("Got answer with speed set: %g", Dval.d);
old_state = new_state; // all OK, command in work
set_speed = new_speed;
@@ -287,27 +305,22 @@ static void chk_dome_speed(SSL *ssl){
// SHM parser; return FALSE if SHM is in erroreous state
static int process_system(SSL *ssl){
static double t0 = 0., last_mtime = 0.;
static int curMotNo = 0; // current motor number (we'll scan all 10 motors by one)
double curtime = sl_dtime();
if(t0 < 1.){ // first run
t0 = curtime;
last_mtime = M_time;
return TRUE;
}
// check time sync
static int brokenshmctr = 0;
if(M_time - last_mtime > curtime - t0 + G.T_sync_lost || !check_shm_block(&sdat)){ // broken SHM
if(curtime - M_time > G.T_sync_lost || !check_shm_block(&sdat)){ // broken SHM
if(brokenshmctr == 0){
LOGERR("Stalled or broken SHM block");
}
WARNX("Stalled or broken SHM block; %g -- %g", M_time - last_mtime + G.T_sync_lost, curtime - t0);
WARNX("Stalled or broken SHM block; (M_time - curtime) = %g", M_time - curtime);
if(++brokenshmctr < 10) return TRUE;
return FALSE;
}else brokenshmctr = 0;
#if 0
// set/reset PEP_K_On by information from server!
value_t Ival = {.type = ARG_TYPE_INT, .i = 0};
if(RESULT_OK != send_motor_command(ssl, cmd_forbidden, &Ival, NULL)) return FALSE;
if(RESULT_OK != send_motor_command(ssl, cmd_forbidden, NULL, &Ival)) return FALSE;
#ifdef EBUG
//if(PEP_K_On != Ival.i) DBG("Set PEP_K_On to %d", !Ival.i);
#endif
@@ -315,6 +328,7 @@ static int process_system(SSL *ssl){
if(Ival.i) PEP_K_On = 0;
else PEP_K_On = 1;
*/
#endif
static int modelused = FALSE;
if(!G.emulmode){
if(UseModel == FullModel){ // model
@@ -326,6 +340,8 @@ static int process_system(SSL *ssl){
return TRUE;
}else modelused = FALSE;
static int serverisdead = FALSE;
// !!! carefully: when running not by root, kill can return -1 wiwth EPERM !!!
// (in this case this is normal: only root can run client)
if(ServPID <= 0 || kill(ServPID, 0) < 0){ // dead server
WARNX("Main server is dead");
if(!serverisdead){
@@ -344,8 +360,8 @@ static int process_system(SSL *ssl){
vel_SEWD = st->speed;
currentSEWD = st->current;
}
if(++curMotNo >= MOTORS_AMOUNT) curMotNo = 0;
}
if(++curMotNo >= MOTORS_AMOUNT) curMotNo = 0;
chk_dome_speed(ssl);
return TRUE;
}
@@ -370,7 +386,7 @@ static SSL *openConn(SSL_CTX *ctx, int fd){
SSL *ssl = SSL_new(ctx);
SSL_set_fd(ssl, fd);
int c = SSL_connect(ssl);
if(c < 0){
if(c != 1){
LOGERR("SSL_connect()");
ERRX("SSL_connect() error: %d", SSL_get_error(ssl, c));
}
@@ -394,6 +410,9 @@ void clientproc(SSL_CTX *ctx, int fd){
LOGERR("Can't get SHM block");
ERRX("Can't get SHM block");
}
get_cmd_queue(&mcmd, ClientSide);
get_cmd_queue(&ocmd, ClientSide);
get_cmd_queue(&ucmd, ClientSide);
// set amount of working motors
DomeSEW_N = MOTORS_AMOUNT;
DBG("set DomeSEW_N = %d", DomeSEW_N);
@@ -401,21 +420,19 @@ void clientproc(SSL_CTX *ctx, int fd){
if(!process_system(ssl)){
LOGERR("Motors error");
WARNX("ERROR!");
stop_all(ssl);
sleep(5);
break;
}
// clear receiving buffer (TODO: parse it?)
int bytes = SSL_nbread(ssl, buf, sizeof(buf)-1);
if(bytes > 0){
buf[bytes] = 0;
fprintf(stderr, "Received: \"%s\"\n", buf);
LOGDBG("Received: \"%s\"", buf);
}else if(bytes < 0){
LOGWARN("Server disconnected or other error");
ERRX("Disconnected");
LOGERR("Server disconnected or other error");
}
usleep(100000);
}
if(ssl) stop_all(ssl);
DBG("Exit; isrunning=%d", isrunning);
SSL_free(ssl);
}
@@ -436,9 +453,10 @@ void terminal(SSL_CTX *ctx, int fd){
}
if(sl_canread(0)){
ssize_t L = getline(&lptr, &N, stdin);
if(L < 0) break; // ctrl + D
if(L > (ssize_t)(sizeof(buf)-1)) WARNX("String too long!");
else if(L > 0){
SSL_write(ssl, lptr, L);
if(!write_string(ssl, lptr)) break; // error
}
}
int bytes = 0;
@@ -454,5 +472,6 @@ void terminal(SSL_CTX *ctx, int fd){
printed = FALSE;
}
}
FREE(lptr);
SSL_free(ssl);
}

View File

@@ -98,9 +98,8 @@ static sl_option_t cmdlnopts[] = {
*/
void parse_args(int argc, char **argv){
int i;
size_t hlen = 1024;
char helpstring[1024], *hptr = helpstring;
snprintf(hptr, hlen, "Usage: %%s [args]\n\n\tWhere args are:\n");
char helpstring[1024];
snprintf(helpstring, 1023, "Usage: %%s [args]\n\n\tWhere args are:\n");
// format of help: "Usage: progname [args]\n"
sl_helpstring(helpstring);
// parse arguments

View File

@@ -83,7 +83,7 @@ int start_daemon(){
OPENLOG(G.logfile, lvl, 1);
}
signal(SIGTERM, signals); // kill (-15) - quit
//signal(SIGHUP, SIG_IGN); // hup - ignore (used in sl_daemonize())
signal(SIGPIPE, SIG_IGN); // don't fall on SSL_write() error
signal(SIGINT, signals); // ctrl+C - quit
signal(SIGQUIT, signals); // ctrl+\ - quit
signal(SIGTSTP, SIG_IGN); // ignore ctrl+Z
@@ -95,6 +95,12 @@ int start_daemon(){
tstart = sl_dtime();
while(1){
childpid = fork();
if(childpid == -1){
WARN("fork()");
LOGERR("daemon(): fork() error");
sleep(5);
continue;
}
if(childpid){ // master
if(savelogs) LOGMSG("Created child with pid %d", childpid);
wait(NULL);

View File

@@ -35,14 +35,14 @@
#define REG_OUTPUT_CURRENT 0xA204 // 41476 (current * 10)
#define REG_MOTOR_SPEED 0xA205 // 41477 (speed, depends on settings)
// REG_CMD bits
// REG_CMD codes
#define CMD_FORWARD 1
#define CMD_REVERSE 2
#define CMD_STOP 5
#define CMD_FAST_STOP 6
#define CMD_RESET_FAULT 7
// REG_STATUS_MAIN bits
// REG_STATUS_MAIN codes
#define STATUS_CW 1
#define STATUS_CCW 2
#define STATUS_STOP 3
@@ -54,7 +54,7 @@
// convert rev/min to frequency register value and back
// 100 * revmin / 60 * 4; 100 - scale, 60 - min2sec, 4 - pole amount
#define REVMIN2FREQ(r) (uint16_t)((100. * (r)) / 15.)
#define REVMIN2FREQ(r) (uint16_t)((100. * (fabs(r))) / 15.)
#define FREQ2REVMIN(f) ((((double)(f)) * 15.) / 100.)
#define CURRENT_SCALE 10.

View File

@@ -25,11 +25,11 @@
// Handlers in this list MUST be in sortered order (by name)!!!
#define HANDLERS_LIST() \
NEW_HANDLER(adc, "read nth ADC channel") \
NEW_HANDLER(adc, "read nth ADC channel (adc=n)") \
NEW_HANDLER(forbidden, "forbid (1) or permit (0) dome operations") \
NEW_HANDLER(inputs, "read PLC discrete inputs") \
NEW_HANDLER(logprefix, "prefix of log file for nth motor (prefix_%d.log), max 31 chars") \
NEW_HANDLER(motcurrent, "maximal motor current") \
NEW_HANDLER(motcurrent, "maximal motor current (only stub, do nothing)") \
NEW_HANDLER(motnum, "active motor number for status requests") \
NEW_HANDLER(motspeed, "motor speed") \
NEW_HANDLER(motstatus, "motor status") \

View File

@@ -19,6 +19,8 @@
#include <modbus/modbus.h>
#include <pthread.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <usefull_macros.h>
@@ -74,10 +76,10 @@ static int change_relay(int N, int state){
return ret;
}
//#define RON(relayNo) do{if((RelaysState & (1<<relayNo)) == 0) change_relay(relayNo, 1);}while(0)
//#define ROFF(relayNo) do{if((RelaysState & (1<<relayNo))) change_relay(relayNo, 0);}while(0)
#define RON(relayNo) do{change_relay(relayNo, 1);}while(0)
#define ROFF(relayNo) do{change_relay(relayNo, 0);}while(0)
#define RON(relayNo) do{if((RelaysState & (1<<relayNo)) == 0) change_relay(relayNo, 1);}while(0)
#define ROFF(relayNo) do{if((RelaysState & (1<<relayNo))) change_relay(relayNo, 0);}while(0)
//#define RON(relayNo) do{change_relay(relayNo, 1);}while(0)
//#define ROFF(relayNo) do{change_relay(relayNo, 0);}while(0)
// check inputs and set/reset relays according to them
static void chk_inputs(){
@@ -146,6 +148,9 @@ static void chk_relays(){
pthread_mutex_unlock(&sync_mutex);
}
#undef RON
#undef ROFF
// process reading relays & inputs state
void io_process(){
uint8_t buf[NRELAYS + NINPUTS];

View File

@@ -16,8 +16,10 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <limits.h>
#include <math.h>
#include <modbus/modbus.h>
#include <pthread.h>
#include <stdio.h>
#include <string.h>
@@ -50,6 +52,9 @@ static motor_state_t motstates[MOTORS_AMOUNT] = {0};
// amount of working motors
static int n_working_motors = 0;
// mutex for flags, currentSet, speedSet, n_working_motors and motstates
static pthread_mutex_t statemutex = PTHREAD_MUTEX_INITIALIZER;
// set points
static double currentSet = DEFAULT_CURRENT, speedSet = 0.;
// flags for main routine
@@ -110,15 +115,19 @@ static int motors_open_m(const char *path, int speed){
return TRUE;
}
static int motors_open_e(const char _U_ *path, int _U_ speed){ // stub for emulation mode
pthread_mutex_lock(&statemutex);
for(int i = 0; i < MOTORS_AMOUNT; ++i) motstates[i].status = MOT_SLEEP;
n_working_motors = MOTORS_AMOUNT;
pthread_mutex_unlock(&statemutex);
return TRUE;
}
// stop all
void motors_stop(){
pthread_mutex_lock(&statemutex);
flags.stop = 1;
pthread_mutex_unlock(&statemutex);
}
// current setpoint getter
@@ -129,8 +138,10 @@ double motors_get_curntsetpoint(){
int motors_set_curntsetpoint(double val){
if(val < 0. || val > MAX_CURRENT) return FALSE;
DBG("Change max current to %g", val);
pthread_mutex_lock(&statemutex);
currentSet = val;
flags.change_current = 1;
pthread_mutex_unlock(&statemutex);
return TRUE;
}
@@ -145,13 +156,16 @@ sl_sock_hresult_e motors_set_speedsetpoint(double val){
DBG("Speed to large");
return RESULT_BADVAL;
}
pthread_mutex_lock(&statemutex);
if(n_working_motors < MIN_WORKING_MOTORS){
DBG("n_working_motors = %d", n_working_motors);
pthread_mutex_unlock(&statemutex);
return RESULT_FAIL;
}
DBG("Change speed setpoint to %g", val);
speedSet = val;
flags.change_speed = 1;
pthread_mutex_unlock(&statemutex);
return RESULT_OK;
}
@@ -167,23 +181,35 @@ int motors_set_activenum(int N){
// get current value for active motor
int motors_get_actcurrent(double *val){
if(val) *val = motstates[motindex].current;
if(val){
pthread_mutex_lock(&statemutex);
*val = motstates[motindex].current;
pthread_mutex_unlock(&statemutex);
}
return TRUE;
}
// get speed for active motor
int motors_get_actspeed(double *val){
if(val) *val = motstates[motindex].speed;
if(val){
pthread_mutex_lock(&statemutex);
*val = motstates[motindex].speed;
pthread_mutex_unlock(&statemutex);
}
return TRUE;
}
// get status for active motor
int motors_get_actstatus(int *val){
if(val) *val = motstates[motindex].status;
if(val){
pthread_mutex_lock(&statemutex);
*val = motstates[motindex].status;
pthread_mutex_unlock(&statemutex);
}
return TRUE;
}
// count amount of actual motors
// count amount of actual motors; called under locked statemutex
static void count_motors(){
n_working_motors = 0;
for(int i = 0; i < MOTORS_AMOUNT; ++i){
@@ -191,11 +217,13 @@ static void count_motors(){
}
}
// should be run under locked statemutex
static void log_data(int motno){
if(!logF[motno] || motstates[motno].status != MOT_RUN) return;
pthread_mutex_lock(&logmutex);
if(!logF[motno] || motstates[motno].status != MOT_RUN) goto retn;
fprintf(logF[motno], "%.3f\t%.2f\t%.2f\n",
sl_dtime() - Tstart, motstates[motno].speed, motstates[motno].current);
retn:
pthread_mutex_unlock(&logmutex);
}
@@ -207,6 +235,7 @@ static void motors_process_m(){
LOGERR("Modbus not inited or other error! Error counter = %d", errctr);
ERRX("Modbus not inited or other error!");
}
pthread_mutex_lock(&statemutex);
if(flags.all){
if(-1 == modbus_set_slave(modbus_ctx, 0)){
WARN("Can't set broadcast slave");
@@ -215,7 +244,7 @@ static void motors_process_m(){
if(flags.stop){
DBG("User asks to stop");
speedSet = 0.;
// send command stop (don't check return code for broadcast messages!
// send command stop (don't check return code for broadcast messages!)
modbus_write_register(modbus_ctx, REG_CMD, CMD_STOP);
flags.stop = 0;
}
@@ -226,11 +255,14 @@ static void motors_process_m(){
}
if(flags.change_speed){
DBG("User asks to change speed to %g", speedSet);
// send command "set speed"
uint16_t dir = (speedSet > 0.) ? CMD_FORWARD : CMD_REVERSE;
uint16_t freq = REVMIN2FREQ(fabs(speedSet));
modbus_write_register(modbus_ctx, REG_CMD, dir);
modbus_write_register(modbus_ctx, REG_FREQ_SET, freq);
if(fabs(speedSet) < SPEED_TOLERANCE){ // stop motor
modbus_write_register(modbus_ctx, REG_CMD, CMD_STOP);
}else{ // send command "set speed"
uint16_t dir = (speedSet > 0.) ? CMD_FORWARD : CMD_REVERSE;
uint16_t freq = REVMIN2FREQ(fabs(speedSet));
modbus_write_register(modbus_ctx, REG_CMD, dir);
modbus_write_register(modbus_ctx, REG_FREQ_SET, freq);
}
flags.change_speed = 0;
}
}
@@ -256,6 +288,7 @@ static void motors_process_m(){
curN = 0;
count_motors();
}
pthread_mutex_unlock(&statemutex);
return;
}
DBG("motor %d; status: %x, extstatus: %x", curN, regs[0], regs[1]);
@@ -293,13 +326,18 @@ static void motors_process_m(){
count_motors();
}
errctr = 0;
pthread_mutex_unlock(&statemutex);
return;
reg_error:
pthread_mutex_unlock(&statemutex);
++errctr;
}
static void motors_process_e(){
static double t0 = -1., curspeed = 0.;
double curt = sl_dtime(), dt = curt - t0, curcurrent = 0.;
double curt = sl_dtime();
if(t0 < 0.) t0 = curt;
double dt = curt - t0, curcurrent = 0.;
pthread_mutex_lock(&statemutex);
int curstatus = motstates[0].status;
if(flags.all){
if(flags.stop){
@@ -331,17 +369,21 @@ static void motors_process_e(){
motstates[i].current = curcurrent;
motstates[i].speed = curspeed;
}
pthread_mutex_unlock(&statemutex);
}
int (*motors_open)(const char *, int) = motors_open_m;
void (*motors_close)() = motors_close_m;
void (*motors_process)() = motors_process_m;
// Run only @ start of main()
void set_emulation_mode(){
LOGMSG("Set emulation mode");
pthread_mutex_lock(&statemutex);
motors_open = motors_open_e;
motors_close = motors_close_e;
motors_process = motors_process_e;
pthread_mutex_unlock(&statemutex);
}
int motors_get_working_amount(){ return n_working_motors; }

View File

@@ -29,6 +29,7 @@
// freq_scale == 100, so for UINT16_t we can't make speed more than 655.35
#define MAX_SPEED 655.
#define SPEED_TOLERANCE 0.01
// emulation acceleration, min^-2
#define EMUL_ACCEL 10000.
#define MAX_CURRENT 15.

View File

@@ -16,6 +16,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <inttypes.h>
#include <usefull_macros.h>
#include "cmdlnopts.h"
@@ -35,8 +36,8 @@ typedef struct{
const char *helpstring;
} command_t;
static const char *maxcl = "Max client number reached, connect later\n";
static const char *sslerr = "SSL error occured\n";
static const char maxcl[] = "Max client number reached, connect later\n";
static const char sslerr[] = "SSL error occured\n";
// declaration of handlers
#define NEW_HANDLER(name, unused) \
@@ -70,9 +71,8 @@ static int handle_connection(SSL *ssl){
char buf[IOBUF_LEN], key[SL_KEY_LEN], val[SL_VAL_LEN];
int r = read_string(ssl, buf, IOBUF_LEN);
if(r < 0) return 0;
int sd = SSL_get_fd(ssl);
//DBG("Client %d msg: \"%s\"\n", sd, buf);
LOGDBG("fd=%d, message=%s", sd, buf);
else if(r == 0) return 1; // nothing to read or buffer overflow
LOGDBG("fd=%d, message=%s", SSL_get_fd(ssl), buf);
int got = sl_get_keyval(buf, key, val);
if(got == 0){
DBG("Comment or empty string");
@@ -93,7 +93,7 @@ static int handle_connection(SSL *ssl){
if(0 == strcmp(key, "help")){
for(size_t i = 0; i < HANDLERS_AMOUNT; ++i){
snprintf(buf, IOBUF_LEN-1, "%s: %s\n", command_list[i].command, command_list[i].helpstring);
SSL_write(ssl, buf, strlen(buf));
write_string(ssl, buf);
}
return 1;
}
@@ -101,7 +101,7 @@ static int handle_connection(SSL *ssl){
// now `val` is an answer or error code
if(result != RESULT_SILENCE) snprintf(buf, IOBUF_LEN-1, "%s\n", sl_sock_hresult2str(result));
else snprintf(buf, IOBUF_LEN-1, "%s=%s\n", key, val);
SSL_write(ssl, buf, strlen(buf));
write_string(ssl, buf);
return 1;
}
@@ -120,8 +120,9 @@ static int timeouted_sslaccept(SSL *ssl){
SSL_ERROR_WANT_WRITE == sslerr) continue;
DBG("SSL error %d", sslerr);
return FALSE;
}
else return TRUE;
}else if(x == 1) return TRUE;
// x == 0 -> unclosed connection
usleep(10000);
}
DBG("Timeout");
return FALSE;
@@ -152,7 +153,7 @@ void serverproc(SSL_CTX *ctx, int fd){
int l = strlen(buf);
for(int i = nfd-1; i > 0; --i){
//DBG("To fd[%d]=%d", i, poll_set[i].fd);
SSL_write(ssls[i], buf, l);
write_string(ssls[i], buf);
}
t0 = tnow;
}*/
@@ -162,6 +163,7 @@ void serverproc(SSL_CTX *ctx, int fd){
struct sockaddr_in addr;
socklen_t len = sizeof(addr);
int client = accept4(fd, (struct sockaddr*)&addr, &len, SOCK_NONBLOCK); // non-blocking for timeout of SSL_accept
if(client < 0) continue; // accept4() error
DBG("Connection: %s @ %d (fd=%d)\n", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port), client);
LOGMSG("Client %s connected to port %d (fd=%d)", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port), client);
if(nfd == BACKLOG + 1){
@@ -186,6 +188,7 @@ void serverproc(SSL_CTX *ctx, int fd){
}else{
LOGERR("SSL_accept()");
WARNX("SSL_accept()");
SSL_shutdown(ssl);
SSL_free(ssl);
send(client, sslerr, sizeof(sslerr)-1, MSG_NOSIGNAL);
shutdown(client, SHUT_WR);
@@ -199,7 +202,9 @@ void serverproc(SSL_CTX *ctx, int fd){
if((poll_set[fdidx].revents & POLLIN) == 0) continue;
int fd = poll_set[fdidx].fd;
if(!handle_connection(ssls[fdidx])){ // socket closed
SSL_shutdown(ssls[fdidx]);
SSL_free(ssls[fdidx]);
ERR_clear_error();
DBG("Client fd=%d disconnected", fd);
LOGMSG("Client fd=%d disconnected", fd);
close(fd);
@@ -210,7 +215,10 @@ void serverproc(SSL_CTX *ctx, int fd){
}
}
}
for(int i = 0; i < nfd; ++i) SSL_free(ssls[i]);
for(int i = 1; i < nfd; ++i){
SSL_shutdown(ssls[i]);
SSL_free(ssls[i]);
}
motors_stop();
motors_close();
}
@@ -218,6 +226,7 @@ void serverproc(SSL_CTX *ctx, int fd){
/****************** Protocol handlers (return 0 in case of success or error code >0 if failed) ******************/
static sl_sock_hresult_e adc_handler(int _U_ index, char value[SL_VAL_LEN]){
int I; uint16_t val;
// have setter format: adc=x for reading x channel
if(!ISSETTER(value) || !sl_str2i(&I, value)) return RESULT_BADVAL;
if(!io_read_adc(I, &val)) return RESULT_BADVAL;
snprintf(value, SL_VAL_LEN-1, "%d", val);
@@ -347,11 +356,13 @@ static sl_sock_hresult_e speed_handler(int _U_ index, char _U_ value[SL_VAL_LEN]
}
static sl_sock_hresult_e stop_handler(int _U_ index, char _U_ value[SL_VAL_LEN]){
if(ISSETTER(value)) return RESULT_BADVAL; // not setter
motors_stop();
return RESULT_OK;
}
static sl_sock_hresult_e nmotors_handler(int _U_ index, char _U_ value[SL_VAL_LEN]){
static sl_sock_hresult_e nmotors_handler(int _U_ index, char value[SL_VAL_LEN]){
if(ISSETTER(value)) return RESULT_BADVAL; // only getter
snprintf(value, SL_VAL_LEN-1, "%d", motors_get_working_amount());
return RESULT_SILENCE;
}
@@ -366,11 +377,13 @@ static sl_sock_hresult_e logprefix_handler(int _U_ index, char _U_ value[SL_VAL_
}
static sl_sock_hresult_e startlog_handler(int _U_ index, char _U_ value[SL_VAL_LEN]){
if(ISSETTER(value)) return RESULT_BADVAL; // not setter
if(start_log()) return RESULT_OK;
return RESULT_FAIL;
}
static sl_sock_hresult_e stoplog_handler(int _U_ index, char _U_ value[SL_VAL_LEN]){
if(ISSETTER(value)) return RESULT_BADVAL; // not setter
stop_log();
return RESULT_OK;
}
@@ -379,10 +392,14 @@ static sl_sock_hresult_e stoplog_handler(int _U_ index, char _U_ value[SL_VAL_LE
static int search_handler(const char *name){
int low = 0;
int high = HANDLERS_AMOUNT - 1;
#ifdef EBUG
int iter = 0;
#endif
while(low <= high){
#ifdef EBUG
++iter;
#endif
int mid = low + (high - low) / 2;
// Compare the target string with the struct's string field
int res = strcmp(name, command_list[mid].command);

View File

@@ -21,6 +21,7 @@
#include <signal.h> // pthread_kill
#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <usefull_macros.h>
#include "cmdlnopts.h"
@@ -75,7 +76,8 @@ static int OpenConn(int port){
bzero(&addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = *(long*)(host->h_addr);
//addr.sin_addr.s_addr = *(long*)(host->h_addr);
memcpy(&addr.sin_addr, host->h_addr, host->h_length);
if(connect(sd, (struct sockaddr*)&addr, sizeof(addr))){
close(sd);
LOGWARN("Can't connect to %s", G.serverhost);
@@ -88,8 +90,8 @@ static int OpenConn(int port){
static SSL_CTX* InitCTX(void){
const SSL_METHOD *method;
SSL_CTX *ctx;
OpenSSL_add_all_algorithms();
SSL_load_error_strings();
//OpenSSL_add_all_algorithms();
//SSL_load_error_strings();
method =
#ifdef CLIENT
TLS_client_method();
@@ -101,27 +103,39 @@ static SSL_CTX* InitCTX(void){
LOGWARN("Can't create SSL context");
ERRX("SSL_CTX_new()");
}
if(!SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION)){
LOGWARN("Can't set minimum TLS protocol version");
ERRX("SSL_CTX_set_min_proto_version()");
}
if(SSL_CTX_load_verify_locations(ctx, G.ca, NULL) != 1){
LOGWARN("Could not set the CA file location\n");
ERRX("Could not set the CA file location\n");
}
#ifdef SERVER
SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(G.ca));
STACK_OF(X509_NAME) *cert_names = SSL_load_client_CA_file(G.ca);
if(!cert_names){
LOGWARN("Could not load client CA file %s", G.ca);
ERRX("SSL_load_client_CA_file()");
}
SSL_CTX_set_client_CA_list(ctx, cert_names);
#endif
if(SSL_CTX_use_certificate_file(ctx, G.cert, SSL_FILETYPE_PEM) <= 0){
ERR_print_errors_fp(stderr);
LOGWARN("Can't use SSL certificate %s", G.cert);
ERRX("Can't use SSL certificate %s", G.cert);
}
if(SSL_CTX_use_PrivateKey_file(ctx, G.key, SSL_FILETYPE_PEM) <= 0){
ERR_print_errors_fp(stderr);
LOGWARN("Can't use SSL key %s", G.key);
ERRX("Can't use SSL key %s", G.key);
}
if(!SSL_CTX_check_private_key(ctx)){
ERR_print_errors_fp(stderr);
LOGWARN("Private key does not match the public certificate\n");
ERRX("Private key does not match the public certificate\n");
}
SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY);
// don't need as socket would be non-blocking
// SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY);
#ifdef SERVER
SSL_CTX_set_verify(ctx, // Specify that we need to verify the client as well
SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
@@ -129,7 +143,7 @@ static SSL_CTX* InitCTX(void){
#else
SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
#endif
SSL_CTX_set_verify_depth(ctx, 1); // We accept only certificates signed only by the CA himself
SSL_CTX_set_verify_depth(ctx, 1); // We accept only certificates signed by the CA himself
return ctx;
}
@@ -143,6 +157,8 @@ int open_socket(){
if(!motors_open(G.serialpath, G.serialspeed)){
LOGERR("Can't open %s @%d", G.serialpath, G.serialspeed);
WARNX("Can't open %s @%d", G.serialpath, G.serialspeed);
close(fd);
SSL_CTX_free(ctx);
return 1;
}
DBG("Motors opened: Stop them");
@@ -155,7 +171,6 @@ int open_socket(){
if(G.terminal) terminal(ctx, fd);
else clientproc(ctx, fd);
#endif
// newer reached
close(fd);
SSL_CTX_free(ctx);
return 0;
@@ -186,7 +201,7 @@ int read_string(SSL *ssl, char *buf, int l){
if(bytes < 1){ // nothing to read or error
return geterrcode(ssl, bytes);
}
char *eol = strchr(buf, '\n');
char *eol = memchr(buf, '\n', bytes);
if(!eol){ // not found: overflow or no enough symbols
if(bytes == l){ // oops: overflow, thow it out
SSL_read(ssl, buf, l);
@@ -202,3 +217,29 @@ int read_string(SSL *ssl, char *buf, int l){
buf[bytes-1] = 0; // replace '\n' with 0
return bytes;
}
/**
* @brief write_string - write '\n'-terminated string
* @param ssl - SSL
* @param buf - zero-terminated buffer with text (last symbol should be '\n')
* @return FALSE in case of fail or timeout (1s)
*/
int write_string(SSL *ssl, char *buf){
double t0 = sl_dtime();
int l = strlen(buf);
while(sl_dtime() - t0 < 1. && l > 0){
int written = SSL_write(ssl, buf, l);
if(written <= 0){
int err = SSL_get_error(ssl, written);
if(err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE){ // try next time
continue;
}
return FALSE; // error
}
buf += written;
l -= written;
if(l) usleep(10000);
}
if(l > 0) return FALSE;
return TRUE;
}

View File

@@ -42,3 +42,4 @@
int open_socket();
int read_string(SSL *ssl, char *buf, int l);
int write_string(SSL *ssl, char *buf);

View File

@@ -1,3 +1,5 @@
Makefile
Readme.md
bta_shdata.c
bta_shdata.h
client.c