Compare commits
2 Commits
6dcb11ae0c
...
95fd88e93e
| Author | SHA1 | Date |
|---|---|---|
|
|
95fd88e93e | |
|
|
21797d8507 |
|
|
@ -11,6 +11,8 @@
|
||||||
#include <zephyr/modbus/modbus.h>
|
#include <zephyr/modbus/modbus.h>
|
||||||
#include <zephyr/usb/usb_device.h>
|
#include <zephyr/usb/usb_device.h>
|
||||||
#include <zephyr/settings/settings.h>
|
#include <zephyr/settings/settings.h>
|
||||||
|
#include <zephyr/sys/crc.h>
|
||||||
|
#include <zephyr/sys/byteorder.h>
|
||||||
|
|
||||||
#include <zephyr/logging/log.h>
|
#include <zephyr/logging/log.h>
|
||||||
#include "modbus_bridge.h"
|
#include "modbus_bridge.h"
|
||||||
|
|
@ -21,54 +23,72 @@ LOG_MODULE_REGISTER(mbs_sample, LOG_LEVEL_INF);
|
||||||
#define APP_VERSION_MINOR 0
|
#define APP_VERSION_MINOR 0
|
||||||
#define APP_VERSION_PATCH 0
|
#define APP_VERSION_PATCH 0
|
||||||
|
|
||||||
|
/* Register Definitions from Documentation */
|
||||||
enum {
|
enum {
|
||||||
|
/* Valve Control & Status */
|
||||||
REG_INPUT_VALVE_STATE_MOVEMENT = 0x0000,
|
REG_INPUT_VALVE_STATE_MOVEMENT = 0x0000,
|
||||||
REG_INPUT_MOTOR_CURRENT_MA = 0x0001,
|
REG_INPUT_MOTOR_CURRENT_MA = 0x0001,
|
||||||
|
/* Digital Inputs */
|
||||||
|
REG_INPUT_DIGITAL_INPUTS_STATE = 0x0020,
|
||||||
|
REG_INPUT_BUTTON_EVENTS = 0x0021,
|
||||||
|
/* System Config & Status */
|
||||||
REG_INPUT_FIRMWARE_VERSION_MAJOR_MINOR = 0x00F0,
|
REG_INPUT_FIRMWARE_VERSION_MAJOR_MINOR = 0x00F0,
|
||||||
REG_INPUT_FIRMWARE_VERSION_PATCH = 0x00F1,
|
REG_INPUT_FIRMWARE_VERSION_PATCH = 0x00F1,
|
||||||
REG_INPUT_DEVICE_STATUS = 0x00F2,
|
REG_INPUT_DEVICE_STATUS = 0x00F2,
|
||||||
REG_INPUT_UPTIME_SECONDS_LOW = 0x00F3,
|
REG_INPUT_UPTIME_SECONDS_LOW = 0x00F3,
|
||||||
REG_INPUT_UPTIME_SECONDS_HIGH = 0x00F4,
|
REG_INPUT_UPTIME_SECONDS_HIGH = 0x00F4,
|
||||||
|
/* Firmware Update */
|
||||||
|
REG_INPUT_FWU_LAST_CHUNK_CRC = 0x0100,
|
||||||
};
|
};
|
||||||
|
|
||||||
enum {
|
enum {
|
||||||
|
/* Valve Control */
|
||||||
REG_HOLDING_VALVE_COMMAND = 0x0000,
|
REG_HOLDING_VALVE_COMMAND = 0x0000,
|
||||||
REG_HOLDING_MAX_OPENING_TIME_S = 0x0001,
|
REG_HOLDING_MAX_OPENING_TIME_S = 0x0001,
|
||||||
REG_HOLDING_MAX_CLOSING_TIME_S = 0x0002,
|
REG_HOLDING_MAX_CLOSING_TIME_S = 0x0002,
|
||||||
|
/* Digital Outputs */
|
||||||
|
REG_HOLDING_DIGITAL_OUTPUTS_STATE = 0x0010,
|
||||||
|
/* System Config */
|
||||||
REG_HOLDING_WATCHDOG_TIMEOUT_S = 0x00F0,
|
REG_HOLDING_WATCHDOG_TIMEOUT_S = 0x00F0,
|
||||||
|
/* Firmware Update */
|
||||||
|
REG_HOLDING_FWU_COMMAND = 0x0100,
|
||||||
|
REG_HOLDING_FWU_CHUNK_OFFSET_LOW = 0x0101,
|
||||||
|
REG_HOLDING_FWU_CHUNK_OFFSET_HIGH = 0x0102,
|
||||||
|
REG_HOLDING_FWU_CHUNK_SIZE = 0x0103,
|
||||||
|
REG_HOLDING_FWU_DATA_BUFFER = 0x0180,
|
||||||
};
|
};
|
||||||
|
|
||||||
enum valve_state {
|
/* Valve Simulation */
|
||||||
VALVE_STATE_CLOSED,
|
enum valve_state { VALVE_STATE_CLOSED, VALVE_STATE_OPEN };
|
||||||
VALVE_STATE_OPEN,
|
enum valve_movement { VALVE_MOVEMENT_IDLE, VALVE_MOVEMENT_OPENING, VALVE_MOVEMENT_CLOSING, VALVE_MOVEMENT_ERROR };
|
||||||
};
|
|
||||||
|
|
||||||
enum valve_movement {
|
|
||||||
VALVE_MOVEMENT_IDLE,
|
|
||||||
VALVE_MOVEMENT_OPENING,
|
|
||||||
VALVE_MOVEMENT_CLOSING,
|
|
||||||
VALVE_MOVEMENT_ERROR,
|
|
||||||
};
|
|
||||||
|
|
||||||
static enum valve_state current_state = VALVE_STATE_CLOSED;
|
static enum valve_state current_state = VALVE_STATE_CLOSED;
|
||||||
static enum valve_movement current_movement = VALVE_MOVEMENT_IDLE;
|
static enum valve_movement current_movement = VALVE_MOVEMENT_IDLE;
|
||||||
static uint16_t max_opening_time_s = 60;
|
static uint16_t max_opening_time_s = 60;
|
||||||
static uint16_t max_closing_time_s = 60;
|
static uint16_t max_closing_time_s = 60;
|
||||||
static uint16_t watchdog_timeout_s;
|
|
||||||
static int modbus_iface;
|
|
||||||
|
|
||||||
static struct k_work_delayable valve_work;
|
static struct k_work_delayable valve_work;
|
||||||
|
|
||||||
|
/* Digital I/O State */
|
||||||
|
static uint16_t digital_outputs_state = 0;
|
||||||
|
static uint16_t digital_inputs_state = 0; // Will be controlled by real hardware
|
||||||
|
static uint16_t button_events = 0; // Clear-on-read
|
||||||
|
|
||||||
|
/* System State */
|
||||||
|
static uint16_t device_status = 0; // 0 = OK
|
||||||
|
static uint16_t watchdog_timeout_s = 0;
|
||||||
|
|
||||||
|
/* Firmware Update State */
|
||||||
|
#define FWU_BUFFER_SIZE 256
|
||||||
|
static uint8_t fwu_buffer[FWU_BUFFER_SIZE];
|
||||||
|
static uint32_t fwu_chunk_offset = 0;
|
||||||
|
static uint16_t fwu_chunk_size = 0;
|
||||||
|
static uint16_t fwu_last_chunk_crc = 0;
|
||||||
|
|
||||||
|
/* Modbus Configuration */
|
||||||
|
static int modbus_iface;
|
||||||
static struct modbus_iface_param server_param = {
|
static struct modbus_iface_param server_param = {
|
||||||
.mode = MODBUS_MODE_RTU,
|
.mode = MODBUS_MODE_RTU,
|
||||||
.server = {
|
.server = { .user_cb = NULL, .unit_id = 1 },
|
||||||
.user_cb = NULL, // Will be set later
|
.serial = { .baud = 19200, .parity = UART_CFG_PARITY_NONE },
|
||||||
.unit_id = 1,
|
|
||||||
},
|
|
||||||
.serial = {
|
|
||||||
.baud = 19200,
|
|
||||||
.parity = UART_CFG_PARITY_NONE,
|
|
||||||
},
|
|
||||||
};
|
};
|
||||||
|
|
||||||
static void valve_work_handler(struct k_work *work)
|
static void valve_work_handler(struct k_work *work)
|
||||||
|
|
@ -82,38 +102,15 @@ static void valve_work_handler(struct k_work *work)
|
||||||
current_movement = VALVE_MOVEMENT_IDLE;
|
current_movement = VALVE_MOVEMENT_IDLE;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
static int coil_rd(uint16_t addr, bool *state)
|
|
||||||
{
|
|
||||||
*state = true;
|
|
||||||
LOG_INF("Coil read, addr %u, %d", addr, (int)*state);
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
static int coil_wr(uint16_t addr, bool state)
|
|
||||||
{
|
|
||||||
LOG_INF("Coil write, addr %u, %d", addr, (int)state);
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
static int holding_reg_rd(uint16_t addr, uint16_t *reg)
|
static int holding_reg_rd(uint16_t addr, uint16_t *reg)
|
||||||
{
|
{
|
||||||
switch (addr) {
|
switch (addr) {
|
||||||
case REG_HOLDING_MAX_OPENING_TIME_S:
|
case REG_HOLDING_MAX_OPENING_TIME_S: *reg = max_opening_time_s; break;
|
||||||
*reg = max_opening_time_s;
|
case REG_HOLDING_MAX_CLOSING_TIME_S: *reg = max_closing_time_s; break;
|
||||||
break;
|
case REG_HOLDING_DIGITAL_OUTPUTS_STATE: *reg = digital_outputs_state; break;
|
||||||
case REG_HOLDING_MAX_CLOSING_TIME_S:
|
case REG_HOLDING_WATCHDOG_TIMEOUT_S: *reg = watchdog_timeout_s; break;
|
||||||
*reg = max_closing_time_s;
|
default: *reg = 0; break;
|
||||||
break;
|
|
||||||
case REG_HOLDING_WATCHDOG_TIMEOUT_S:
|
|
||||||
*reg = watchdog_timeout_s;
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
*reg = 0;
|
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
LOG_INF("Holding register read, addr %u, value %u", addr, *reg);
|
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -125,19 +122,16 @@ static int holding_reg_wr(uint16_t addr, uint16_t reg)
|
||||||
if (current_state == VALVE_STATE_CLOSED) {
|
if (current_state == VALVE_STATE_CLOSED) {
|
||||||
current_state = VALVE_STATE_OPEN;
|
current_state = VALVE_STATE_OPEN;
|
||||||
current_movement = VALVE_MOVEMENT_OPENING;
|
current_movement = VALVE_MOVEMENT_OPENING;
|
||||||
LOG_INF("Virtual valve opening...");
|
k_work_schedule(&valve_work, K_SECONDS(max_opening_time_s));
|
||||||
k_work_schedule(&valve_work, K_MSEC(max_opening_time_s * 1000 * 0.9));
|
|
||||||
}
|
}
|
||||||
} else if (reg == 2) { /* Close */
|
} else if (reg == 2) { /* Close */
|
||||||
if (current_state == VALVE_STATE_OPEN) {
|
if (current_state == VALVE_STATE_OPEN) {
|
||||||
current_movement = VALVE_MOVEMENT_CLOSING;
|
current_movement = VALVE_MOVEMENT_CLOSING;
|
||||||
LOG_INF("Virtual valve closing...");
|
k_work_schedule(&valve_work, K_SECONDS(max_closing_time_s));
|
||||||
k_work_schedule(&valve_work, K_MSEC(max_closing_time_s * 1000 * 0.9));
|
|
||||||
}
|
}
|
||||||
} else if (reg == 0) { /* Stop */
|
} else if (reg == 0) { /* Stop */
|
||||||
k_work_cancel_delayable(&valve_work);
|
k_work_cancel_delayable(&valve_work);
|
||||||
current_movement = VALVE_MOVEMENT_IDLE;
|
current_movement = VALVE_MOVEMENT_IDLE;
|
||||||
LOG_INF("Virtual valve movement stopped");
|
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case REG_HOLDING_MAX_OPENING_TIME_S:
|
case REG_HOLDING_MAX_OPENING_TIME_S:
|
||||||
|
|
@ -148,14 +142,43 @@ static int holding_reg_wr(uint16_t addr, uint16_t reg)
|
||||||
max_closing_time_s = reg;
|
max_closing_time_s = reg;
|
||||||
settings_save_one("valve/max_close_time", &max_closing_time_s, sizeof(max_closing_time_s));
|
settings_save_one("valve/max_close_time", &max_closing_time_s, sizeof(max_closing_time_s));
|
||||||
break;
|
break;
|
||||||
|
case REG_HOLDING_DIGITAL_OUTPUTS_STATE:
|
||||||
|
digital_outputs_state = reg;
|
||||||
|
LOG_INF("Digital outputs set to 0x%04X", digital_outputs_state);
|
||||||
|
// Here you would typically write to GPIOs
|
||||||
|
break;
|
||||||
case REG_HOLDING_WATCHDOG_TIMEOUT_S:
|
case REG_HOLDING_WATCHDOG_TIMEOUT_S:
|
||||||
watchdog_timeout_s = reg;
|
watchdog_timeout_s = reg;
|
||||||
|
LOG_INF("Watchdog timeout set to %u s", watchdog_timeout_s);
|
||||||
|
break;
|
||||||
|
case REG_HOLDING_FWU_COMMAND:
|
||||||
|
if (reg == 1) { // Verify Chunk
|
||||||
|
LOG_INF("FWU: Chunk at offset %u (size %u) verified by client, writing to flash (simulated).", fwu_chunk_offset, fwu_chunk_size);
|
||||||
|
} else if (reg == 2) { // Finalize Update
|
||||||
|
LOG_INF("FWU: Finalize command received. Rebooting (simulated).");
|
||||||
|
// In a real scenario: sys_reboot(SYS_REBOOT_WARM);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case REG_HOLDING_FWU_CHUNK_OFFSET_LOW: fwu_chunk_offset = (fwu_chunk_offset & 0xFFFF0000) | reg; break;
|
||||||
|
case REG_HOLDING_FWU_CHUNK_OFFSET_HIGH: fwu_chunk_offset = (fwu_chunk_offset & 0x0000FFFF) | ((uint32_t)reg << 16); break;
|
||||||
|
case REG_HOLDING_FWU_CHUNK_SIZE:
|
||||||
|
fwu_chunk_size = (reg > FWU_BUFFER_SIZE) ? FWU_BUFFER_SIZE : reg;
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
|
// Handle FWU_DATA_BUFFER writes
|
||||||
|
if (addr >= REG_HOLDING_FWU_DATA_BUFFER && addr < (REG_HOLDING_FWU_DATA_BUFFER + (FWU_BUFFER_SIZE / 2))) {
|
||||||
|
uint16_t index = (addr - REG_HOLDING_FWU_DATA_BUFFER) * 2;
|
||||||
|
if (index < sizeof(fwu_buffer)) {
|
||||||
|
sys_put_be16(reg, &fwu_buffer[index]);
|
||||||
|
// After the last register of a chunk is written, calculate CRC
|
||||||
|
if (index + 2 >= fwu_chunk_size) {
|
||||||
|
fwu_last_chunk_crc = crc16_ccitt(0xffff, fwu_buffer, fwu_chunk_size);
|
||||||
|
LOG_INF("FWU: Chunk received, CRC is 0x%04X", fwu_last_chunk_crc);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
LOG_INF("Holding register write, addr %u, value %u", addr, reg);
|
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -164,39 +187,25 @@ static int input_reg_rd(uint16_t addr, uint16_t *reg)
|
||||||
uint32_t uptime_s = k_uptime_get_32() / 1000;
|
uint32_t uptime_s = k_uptime_get_32() / 1000;
|
||||||
|
|
||||||
switch (addr) {
|
switch (addr) {
|
||||||
case REG_INPUT_VALVE_STATE_MOVEMENT:
|
case REG_INPUT_VALVE_STATE_MOVEMENT: *reg = (current_movement << 8) | (current_state & 0xFF); break;
|
||||||
*reg = (current_movement << 8) | (current_state & 0xFF);
|
case REG_INPUT_MOTOR_CURRENT_MA: *reg = (current_movement != VALVE_MOVEMENT_IDLE) ? 150 : 10; break; // Simulated
|
||||||
break;
|
case REG_INPUT_DIGITAL_INPUTS_STATE: *reg = digital_inputs_state; break;
|
||||||
case REG_INPUT_MOTOR_CURRENT_MA:
|
case REG_INPUT_BUTTON_EVENTS:
|
||||||
*reg = 50; /* Dummy value */
|
*reg = button_events;
|
||||||
break;
|
button_events = 0; // Clear-on-read
|
||||||
case REG_INPUT_FIRMWARE_VERSION_MAJOR_MINOR:
|
|
||||||
*reg = (APP_VERSION_MAJOR << 8) | (APP_VERSION_MINOR & 0xFF);
|
|
||||||
break;
|
|
||||||
case REG_INPUT_FIRMWARE_VERSION_PATCH:
|
|
||||||
*reg = APP_VERSION_PATCH;
|
|
||||||
break;
|
|
||||||
case REG_INPUT_DEVICE_STATUS:
|
|
||||||
*reg = 0; /* 0 = OK */
|
|
||||||
break;
|
|
||||||
case REG_INPUT_UPTIME_SECONDS_LOW:
|
|
||||||
*reg = (uint16_t)(uptime_s & 0xFFFF);
|
|
||||||
break;
|
|
||||||
case REG_INPUT_UPTIME_SECONDS_HIGH:
|
|
||||||
*reg = (uint16_t)(uptime_s >> 16);
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
*reg = 0;
|
|
||||||
break;
|
break;
|
||||||
|
case REG_INPUT_FIRMWARE_VERSION_MAJOR_MINOR: *reg = (APP_VERSION_MAJOR << 8) | (APP_VERSION_MINOR & 0xFF); break;
|
||||||
|
case REG_INPUT_FIRMWARE_VERSION_PATCH: *reg = APP_VERSION_PATCH; break;
|
||||||
|
case REG_INPUT_DEVICE_STATUS: *reg = device_status; break;
|
||||||
|
case REG_INPUT_UPTIME_SECONDS_LOW: *reg = (uint16_t)(uptime_s & 0xFFFF); break;
|
||||||
|
case REG_INPUT_UPTIME_SECONDS_HIGH: *reg = (uint16_t)(uptime_s >> 16); break;
|
||||||
|
case REG_INPUT_FWU_LAST_CHUNK_CRC: *reg = fwu_last_chunk_crc; break;
|
||||||
|
default: *reg = 0; break;
|
||||||
}
|
}
|
||||||
|
|
||||||
LOG_INF("Input register read, addr %u, value %u", addr, *reg);
|
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
static struct modbus_user_callbacks mbs_cbs = {
|
static struct modbus_user_callbacks mbs_cbs = {
|
||||||
.coil_rd = coil_rd,
|
|
||||||
.coil_wr = coil_wr,
|
|
||||||
.holding_reg_rd = holding_reg_rd,
|
.holding_reg_rd = holding_reg_rd,
|
||||||
.holding_reg_wr = holding_reg_wr,
|
.holding_reg_wr = holding_reg_wr,
|
||||||
.input_reg_rd = input_reg_rd,
|
.input_reg_rd = input_reg_rd,
|
||||||
|
|
@ -207,146 +216,71 @@ static struct modbus_user_callbacks mbs_cbs = {
|
||||||
int modbus_reconfigure(uint32_t baudrate, uint8_t unit_id)
|
int modbus_reconfigure(uint32_t baudrate, uint8_t unit_id)
|
||||||
{
|
{
|
||||||
int err;
|
int err;
|
||||||
|
|
||||||
LOG_INF("Reconfiguring Modbus: baudrate=%u, id=%u", baudrate, unit_id);
|
|
||||||
|
|
||||||
err = modbus_disable(modbus_iface);
|
err = modbus_disable(modbus_iface);
|
||||||
if (err) {
|
if (err) { return err; }
|
||||||
LOG_ERR("Failed to disable Modbus: %d", err);
|
|
||||||
return err;
|
|
||||||
}
|
|
||||||
|
|
||||||
server_param.serial.baud = baudrate;
|
server_param.serial.baud = baudrate;
|
||||||
server_param.server.unit_id = unit_id;
|
server_param.server.unit_id = unit_id;
|
||||||
|
|
||||||
err = modbus_init_server(modbus_iface, server_param);
|
err = modbus_init_server(modbus_iface, server_param);
|
||||||
if (err) {
|
return err;
|
||||||
LOG_ERR("Failed to re-init Modbus server: %d", err);
|
|
||||||
return err;
|
|
||||||
}
|
|
||||||
|
|
||||||
return 0;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
uint32_t modbus_get_baudrate(void)
|
uint32_t modbus_get_baudrate(void) { return server_param.serial.baud; }
|
||||||
{
|
uint8_t modbus_get_unit_id(void) { return server_param.server.unit_id; }
|
||||||
return server_param.serial.baud;
|
void valve_set_max_open_time(uint16_t seconds) { max_opening_time_s = seconds; settings_save_one("valve/max_open_time", &max_opening_time_s, sizeof(max_opening_time_s)); }
|
||||||
}
|
void valve_set_max_close_time(uint16_t seconds) { max_closing_time_s = seconds; settings_save_one("valve/max_close_time", &max_closing_time_s, sizeof(max_closing_time_s)); }
|
||||||
|
uint16_t valve_get_max_open_time(void) { return max_opening_time_s; }
|
||||||
|
uint16_t valve_get_max_close_time(void) { return max_closing_time_s; }
|
||||||
|
|
||||||
uint8_t modbus_get_unit_id(void)
|
static int settings_load_cb(const char *name, size_t len, settings_read_cb read_cb, void *cb_arg)
|
||||||
{
|
|
||||||
return server_param.server.unit_id;
|
|
||||||
}
|
|
||||||
|
|
||||||
void valve_set_max_open_time(uint16_t seconds)
|
|
||||||
{
|
|
||||||
max_opening_time_s = seconds;
|
|
||||||
settings_save_one("valve/max_open_time", &max_opening_time_s, sizeof(max_opening_time_s));
|
|
||||||
}
|
|
||||||
|
|
||||||
void valve_set_max_close_time(uint16_t seconds)
|
|
||||||
{
|
|
||||||
max_closing_time_s = seconds;
|
|
||||||
settings_save_one("valve/max_close_time", &max_closing_time_s, sizeof(max_closing_time_s));
|
|
||||||
}
|
|
||||||
|
|
||||||
uint16_t valve_get_max_open_time(void)
|
|
||||||
{
|
|
||||||
return max_opening_time_s;
|
|
||||||
}
|
|
||||||
|
|
||||||
uint16_t valve_get_max_close_time(void)
|
|
||||||
{
|
|
||||||
return max_closing_time_s;
|
|
||||||
}
|
|
||||||
|
|
||||||
static int settings_load_cb(const char *name, size_t len,
|
|
||||||
settings_read_cb read_cb, void *cb_arg)
|
|
||||||
{
|
{
|
||||||
const char *next;
|
const char *next;
|
||||||
int rc;
|
int rc;
|
||||||
|
|
||||||
if (settings_name_steq(name, "baudrate", &next) && !next) {
|
if (settings_name_steq(name, "baudrate", &next) && !next) {
|
||||||
rc = read_cb(cb_arg, &server_param.serial.baud, sizeof(server_param.serial.baud));
|
rc = read_cb(cb_arg, &server_param.serial.baud, sizeof(server_param.serial.baud));
|
||||||
if (rc < 0) {
|
return (rc < 0) ? rc : 0;
|
||||||
return rc;
|
|
||||||
}
|
|
||||||
LOG_INF("Loaded modbus/baudrate: %u", server_param.serial.baud);
|
|
||||||
return 0;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (settings_name_steq(name, "unit_id", &next) && !next) {
|
if (settings_name_steq(name, "unit_id", &next) && !next) {
|
||||||
rc = read_cb(cb_arg, &server_param.server.unit_id, sizeof(server_param.server.unit_id));
|
rc = read_cb(cb_arg, &server_param.server.unit_id, sizeof(server_param.server.unit_id));
|
||||||
if (rc < 0) {
|
return (rc < 0) ? rc : 0;
|
||||||
return rc;
|
|
||||||
}
|
|
||||||
LOG_INF("Loaded modbus/unit_id: %u", server_param.server.unit_id);
|
|
||||||
return 0;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (settings_name_steq(name, "max_open_time", &next) && !next) {
|
if (settings_name_steq(name, "max_open_time", &next) && !next) {
|
||||||
rc = read_cb(cb_arg, &max_opening_time_s, sizeof(max_opening_time_s));
|
rc = read_cb(cb_arg, &max_opening_time_s, sizeof(max_opening_time_s));
|
||||||
if (rc < 0) {
|
return (rc < 0) ? rc : 0;
|
||||||
return rc;
|
|
||||||
}
|
|
||||||
LOG_INF("Loaded valve/max_open_time: %u", max_opening_time_s);
|
|
||||||
return 0;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (settings_name_steq(name, "max_close_time", &next) && !next) {
|
if (settings_name_steq(name, "max_close_time", &next) && !next) {
|
||||||
rc = read_cb(cb_arg, &max_closing_time_s, sizeof(max_closing_time_s));
|
rc = read_cb(cb_arg, &max_closing_time_s, sizeof(max_closing_time_s));
|
||||||
if (rc < 0) {
|
return (rc < 0) ? rc : 0;
|
||||||
return rc;
|
|
||||||
}
|
|
||||||
LOG_INF("Loaded valve/max_close_time: %u", max_closing_time_s);
|
|
||||||
return 0;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return -ENOENT;
|
return -ENOENT;
|
||||||
}
|
}
|
||||||
|
|
||||||
SETTINGS_STATIC_HANDLER_DEFINE(modbus, "modbus", NULL, settings_load_cb, NULL, NULL);
|
SETTINGS_STATIC_HANDLER_DEFINE(modbus, "modbus", NULL, settings_load_cb, NULL, NULL);
|
||||||
SETTINGS_STATIC_HANDLER_DEFINE(valve, "valve", NULL, settings_load_cb, NULL, NULL);
|
SETTINGS_STATIC_HANDLER_DEFINE(valve, "valve", NULL, settings_load_cb, NULL, NULL);
|
||||||
|
|
||||||
|
|
||||||
static int init_modbus_server(void)
|
static int init_modbus_server(void)
|
||||||
{
|
{
|
||||||
const char iface_name[] = {DEVICE_DT_NAME(MODBUS_NODE)};
|
const char iface_name[] = {DEVICE_DT_NAME(MODBUS_NODE)};
|
||||||
|
|
||||||
modbus_iface = modbus_iface_get_by_name(iface_name);
|
modbus_iface = modbus_iface_get_by_name(iface_name);
|
||||||
if (modbus_iface < 0) {
|
if (modbus_iface < 0) { return modbus_iface; }
|
||||||
LOG_ERR("Failed to get iface index for %s", iface_name);
|
|
||||||
return modbus_iface;
|
|
||||||
}
|
|
||||||
|
|
||||||
server_param.server.user_cb = &mbs_cbs;
|
server_param.server.user_cb = &mbs_cbs;
|
||||||
|
|
||||||
return modbus_init_server(modbus_iface, server_param);
|
return modbus_init_server(modbus_iface, server_param);
|
||||||
}
|
}
|
||||||
|
|
||||||
int main(void)
|
int main(void)
|
||||||
{
|
{
|
||||||
LOG_INF("Starting APP");
|
LOG_INF("Starting Irrigation System Slave Node");
|
||||||
|
|
||||||
k_work_init_delayable(&valve_work, valve_work_handler);
|
k_work_init_delayable(&valve_work, valve_work_handler);
|
||||||
|
|
||||||
if (settings_subsys_init()) {
|
if (settings_subsys_init() || settings_load()) {
|
||||||
LOG_ERR("Failed to initialize settings subsystem");
|
LOG_ERR("Settings initialization or loading failed");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (settings_load()) {
|
|
||||||
LOG_ERR("Failed to load settings");
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
if (init_modbus_server()) {
|
if (init_modbus_server()) {
|
||||||
LOG_ERR("Modbus RTU server initialization failed");
|
LOG_ERR("Modbus RTU server initialization failed");
|
||||||
}
|
return 0;
|
||||||
LOG_INF("APP started");
|
|
||||||
|
|
||||||
while (1) {
|
|
||||||
k_sleep(K_MSEC(1000));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
LOG_INF("Irrigation System Slave Node started successfully");
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
@ -6,19 +6,34 @@ import sys
|
||||||
import curses
|
import curses
|
||||||
from pymodbus.client import ModbusSerialClient
|
from pymodbus.client import ModbusSerialClient
|
||||||
from pymodbus.exceptions import ModbusException
|
from pymodbus.exceptions import ModbusException
|
||||||
|
import os
|
||||||
|
|
||||||
# Register Definitions
|
# --- Register Definitions ---
|
||||||
|
# Input Registers
|
||||||
REG_INPUT_VALVE_STATE_MOVEMENT = 0x0000
|
REG_INPUT_VALVE_STATE_MOVEMENT = 0x0000
|
||||||
REG_INPUT_MOTOR_CURRENT_MA = 0x0001
|
REG_INPUT_MOTOR_CURRENT_MA = 0x0001
|
||||||
|
REG_INPUT_DIGITAL_INPUTS_STATE = 0x0020
|
||||||
|
REG_INPUT_BUTTON_EVENTS = 0x0021
|
||||||
REG_INPUT_FIRMWARE_VERSION_MAJOR_MINOR = 0x00F0
|
REG_INPUT_FIRMWARE_VERSION_MAJOR_MINOR = 0x00F0
|
||||||
REG_INPUT_FIRMWARE_VERSION_PATCH = 0x00F1
|
REG_INPUT_FIRMWARE_VERSION_PATCH = 0x00F1
|
||||||
|
REG_INPUT_DEVICE_STATUS = 0x00F2
|
||||||
REG_INPUT_UPTIME_SECONDS_LOW = 0x00F3
|
REG_INPUT_UPTIME_SECONDS_LOW = 0x00F3
|
||||||
REG_INPUT_UPTIME_SECONDS_HIGH = 0x00F4
|
REG_INPUT_UPTIME_SECONDS_HIGH = 0x00F4
|
||||||
|
REG_INPUT_FWU_LAST_CHUNK_CRC = 0x0100
|
||||||
|
|
||||||
|
# Holding Registers
|
||||||
REG_HOLDING_VALVE_COMMAND = 0x0000
|
REG_HOLDING_VALVE_COMMAND = 0x0000
|
||||||
REG_HOLDING_MAX_OPENING_TIME_S = 0x0001
|
REG_HOLDING_MAX_OPENING_TIME_S = 0x0001
|
||||||
REG_HOLDING_MAX_CLOSING_TIME_S = 0x0002
|
REG_HOLDING_MAX_CLOSING_TIME_S = 0x0002
|
||||||
|
REG_HOLDING_DIGITAL_OUTPUTS_STATE = 0x0010
|
||||||
|
REG_HOLDING_WATCHDOG_TIMEOUT_S = 0x00F0
|
||||||
|
REG_HOLDING_FWU_COMMAND = 0x0100
|
||||||
|
REG_HOLDING_FWU_CHUNK_OFFSET_LOW = 0x0101
|
||||||
|
REG_HOLDING_FWU_CHUNK_OFFSET_HIGH = 0x0102
|
||||||
|
REG_HOLDING_FWU_CHUNK_SIZE = 0x0103
|
||||||
|
REG_HOLDING_FWU_DATA_BUFFER = 0x0180
|
||||||
|
|
||||||
# Global state
|
# --- Global State ---
|
||||||
stop_event = threading.Event()
|
stop_event = threading.Event()
|
||||||
client = None
|
client = None
|
||||||
status_data = {}
|
status_data = {}
|
||||||
|
|
@ -26,26 +41,16 @@ status_lock = threading.Lock()
|
||||||
|
|
||||||
def format_uptime(seconds):
|
def format_uptime(seconds):
|
||||||
"""Formats seconds into a human-readable d/h/m/s string."""
|
"""Formats seconds into a human-readable d/h/m/s string."""
|
||||||
if not isinstance(seconds, (int, float)) or seconds < 0:
|
if not isinstance(seconds, (int, float)) or seconds < 0: return "N/A"
|
||||||
return "N/A"
|
if seconds == 0: return "0s"
|
||||||
if seconds == 0:
|
days, rem = divmod(seconds, 86400)
|
||||||
return "0s"
|
hours, rem = divmod(rem, 3600)
|
||||||
|
minutes, secs = divmod(rem, 60)
|
||||||
days, remainder = divmod(seconds, 86400)
|
|
||||||
hours, remainder = divmod(remainder, 3600)
|
|
||||||
minutes, secs = divmod(remainder, 60)
|
|
||||||
|
|
||||||
parts = []
|
parts = []
|
||||||
if days > 0:
|
if days > 0: parts.append(f"{int(days)}d")
|
||||||
parts.append(f"{int(days)}d")
|
if hours > 0: parts.append(f"{int(hours)}h")
|
||||||
if hours > 0:
|
if minutes > 0: parts.append(f"{int(minutes)}m")
|
||||||
parts.append(f"{int(hours)}h")
|
if secs > 0 or not parts: parts.append(f"{int(secs)}s")
|
||||||
if minutes > 0:
|
|
||||||
parts.append(f"{int(minutes)}m")
|
|
||||||
# Always show seconds if it's the only unit or if other units are present
|
|
||||||
if secs > 0 or not parts:
|
|
||||||
parts.append(f"{int(secs)}s")
|
|
||||||
|
|
||||||
return " ".join(parts)
|
return " ".join(parts)
|
||||||
|
|
||||||
def poll_status(slave_id, interval):
|
def poll_status(slave_id, interval):
|
||||||
|
|
@ -54,32 +59,42 @@ def poll_status(slave_id, interval):
|
||||||
while not stop_event.is_set():
|
while not stop_event.is_set():
|
||||||
new_data = {"error": None}
|
new_data = {"error": None}
|
||||||
try:
|
try:
|
||||||
# Read all registers in a few calls
|
# Grouped reads for efficiency
|
||||||
rr = client.read_input_registers(REG_INPUT_VALVE_STATE_MOVEMENT, count=2, slave=slave_id)
|
ir_valve = client.read_input_registers(REG_INPUT_VALVE_STATE_MOVEMENT, count=2, slave=slave_id)
|
||||||
hr = client.read_holding_registers(REG_HOLDING_MAX_OPENING_TIME_S, count=2, slave=slave_id)
|
ir_dig = client.read_input_registers(REG_INPUT_DIGITAL_INPUTS_STATE, count=2, slave=slave_id)
|
||||||
rr_sys = client.read_input_registers(REG_INPUT_FIRMWARE_VERSION_MAJOR_MINOR, count=5, slave=slave_id)
|
ir_sys = client.read_input_registers(REG_INPUT_FIRMWARE_VERSION_MAJOR_MINOR, count=5, slave=slave_id)
|
||||||
|
hr_valve = client.read_holding_registers(REG_HOLDING_MAX_OPENING_TIME_S, count=2, slave=slave_id)
|
||||||
|
hr_dig = client.read_holding_registers(REG_HOLDING_DIGITAL_OUTPUTS_STATE, count=1, slave=slave_id)
|
||||||
|
hr_sys = client.read_holding_registers(REG_HOLDING_WATCHDOG_TIMEOUT_S, count=1, slave=slave_id)
|
||||||
|
|
||||||
if rr.isError(): raise ModbusException(f"reading valve status: {rr}")
|
# Check for errors
|
||||||
if hr.isError(): raise ModbusException(f"reading holding registers: {hr}")
|
for res in [ir_valve, ir_dig, ir_sys, hr_valve, hr_dig, hr_sys]:
|
||||||
if rr_sys.isError(): raise ModbusException(f"reading system status: {rr_sys}")
|
if res.isError(): raise ModbusException(str(res))
|
||||||
|
|
||||||
valve_state_raw = rr.registers[0]
|
# --- Process Valve & Motor Data ---
|
||||||
|
valve_state_raw = ir_valve.registers[0]
|
||||||
movement_map = {0: "Idle", 1: "Opening", 2: "Closing", 3: "Error"}
|
movement_map = {0: "Idle", 1: "Opening", 2: "Closing", 3: "Error"}
|
||||||
state_map = {0: "Closed", 1: "Open"}
|
state_map = {0: "Closed", 1: "Open"}
|
||||||
new_data["movement"] = movement_map.get(valve_state_raw >> 8, 'Unknown')
|
new_data["movement"] = movement_map.get(valve_state_raw >> 8, 'Unknown')
|
||||||
new_data["state"] = state_map.get(valve_state_raw & 0xFF, 'Unknown')
|
new_data["state"] = state_map.get(valve_state_raw & 0xFF, 'Unknown')
|
||||||
new_data["motor_current"] = f"{rr.registers[1]} mA"
|
new_data["motor_current"] = f"{ir_valve.registers[1]} mA"
|
||||||
new_data["open_time"] = f"{hr.registers[0]}s"
|
new_data["open_time"] = f"{hr_valve.registers[0]}s"
|
||||||
new_data["close_time"] = f"{hr.registers[1]}s"
|
new_data["close_time"] = f"{hr_valve.registers[1]}s"
|
||||||
|
|
||||||
fw_major = rr_sys.registers[0] >> 8
|
# --- Process Digital I/O ---
|
||||||
fw_minor = rr_sys.registers[0] & 0xFF
|
new_data["digital_inputs"] = f"0x{ir_dig.registers[0]:04X}"
|
||||||
fw_patch = rr_sys.registers[1]
|
new_data["button_events"] = f"0x{ir_dig.registers[1]:04X}"
|
||||||
uptime_low = rr_sys.registers[3]
|
new_data["digital_outputs"] = f"0x{hr_dig.registers[0]:04X}"
|
||||||
uptime_high = rr_sys.registers[4]
|
|
||||||
uptime_seconds = (uptime_high << 16) | uptime_low
|
# --- Process System Data ---
|
||||||
|
fw_major = ir_sys.registers[0] >> 8
|
||||||
|
fw_minor = ir_sys.registers[0] & 0xFF
|
||||||
|
fw_patch = ir_sys.registers[1]
|
||||||
|
uptime_seconds = (ir_sys.registers[4] << 16) | ir_sys.registers[3]
|
||||||
new_data["firmware"] = f"v{fw_major}.{fw_minor}.{fw_patch}"
|
new_data["firmware"] = f"v{fw_major}.{fw_minor}.{fw_patch}"
|
||||||
|
new_data["device_status"] = "OK" if ir_sys.registers[2] == 0 else "ERROR"
|
||||||
new_data["uptime"] = format_uptime(uptime_seconds)
|
new_data["uptime"] = format_uptime(uptime_seconds)
|
||||||
|
new_data["watchdog"] = f"{hr_sys.registers[0]}s"
|
||||||
|
|
||||||
except ModbusException as e:
|
except ModbusException as e:
|
||||||
new_data["error"] = f"Modbus Error: {e}"
|
new_data["error"] = f"Modbus Error: {e}"
|
||||||
|
|
@ -94,7 +109,6 @@ def draw_button(stdscr, y, x, text, selected=False):
|
||||||
"""Draws a button with a border, handling selection highlight."""
|
"""Draws a button with a border, handling selection highlight."""
|
||||||
button_width = len(text) + 4
|
button_width = len(text) + 4
|
||||||
color = curses.color_pair(2) if selected else curses.color_pair(1)
|
color = curses.color_pair(2) if selected else curses.color_pair(1)
|
||||||
|
|
||||||
stdscr.addstr(y, x, " " * button_width, color)
|
stdscr.addstr(y, x, " " * button_width, color)
|
||||||
stdscr.addstr(y, x + 2, text, color)
|
stdscr.addstr(y, x + 2, text, color)
|
||||||
stdscr.addstr(y - 1, x, "┌" + "─" * (button_width - 2) + "┐", color)
|
stdscr.addstr(y - 1, x, "┌" + "─" * (button_width - 2) + "┐", color)
|
||||||
|
|
@ -109,105 +123,90 @@ def main_menu(stdscr, slave_id):
|
||||||
stdscr.nodelay(1)
|
stdscr.nodelay(1)
|
||||||
stdscr.timeout(100)
|
stdscr.timeout(100)
|
||||||
|
|
||||||
# --- Color Pairs ---
|
|
||||||
curses.start_color()
|
curses.start_color()
|
||||||
curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLUE) # Main: white on blue
|
curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLUE)
|
||||||
curses.init_pair(2, curses.COLOR_BLUE, curses.COLOR_WHITE) # Selected: blue on white
|
curses.init_pair(2, curses.COLOR_BLUE, curses.COLOR_WHITE)
|
||||||
curses.init_pair(3, curses.COLOR_RED, curses.COLOR_BLUE) # Error: red on blue
|
curses.init_pair(3, curses.COLOR_RED, curses.COLOR_BLUE)
|
||||||
stdscr.bkgd(' ', curses.color_pair(1))
|
stdscr.bkgd(' ', curses.color_pair(1))
|
||||||
|
|
||||||
# --- UI State ---
|
menu = ["Open Valve", "Close Valve", "Stop Valve", "Toggle Output 1", "Toggle Output 2", "Set Watchdog", "Firmware Update", "Exit"]
|
||||||
menu = ["Open Valve", "Close Valve", "Stop Valve", "Set Max Opening Time", "Set Max Closing Time", "Exit"]
|
|
||||||
current_row_idx = 0
|
current_row_idx = 0
|
||||||
|
message, message_time = "", 0
|
||||||
# State for transient messages
|
input_mode, input_prompt, input_str, input_target_reg = False, "", "", 0
|
||||||
message = ""
|
|
||||||
message_time = 0
|
|
||||||
|
|
||||||
# State for user input
|
|
||||||
input_mode = False
|
|
||||||
input_prompt = ""
|
|
||||||
input_str = ""
|
|
||||||
input_target_reg = 0
|
|
||||||
|
|
||||||
while not stop_event.is_set():
|
while not stop_event.is_set():
|
||||||
h, w = stdscr.getmaxyx()
|
h, w = stdscr.getmaxyx()
|
||||||
|
|
||||||
# --- Handle Input and State Changes ---
|
|
||||||
key = stdscr.getch()
|
key = stdscr.getch()
|
||||||
|
|
||||||
if input_mode:
|
if input_mode:
|
||||||
if key in [10, 13]: # Enter
|
if key in [10, 13]: # Enter
|
||||||
try:
|
try:
|
||||||
seconds = int(input_str)
|
value = int(input_str)
|
||||||
client.write_register(input_target_reg, seconds, slave=slave_id)
|
client.write_register(input_target_reg, value, slave=slave_id)
|
||||||
message = f"-> Set time to {seconds}s"
|
message = f"-> Set register 0x{input_target_reg:04X} to {value}"
|
||||||
except ValueError:
|
|
||||||
message = "-> Invalid input. Please enter a number."
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
message = f"-> Error: {e}"
|
message = f"-> Error: {e}"
|
||||||
message_time = time.time()
|
message_time, input_mode, input_str = time.time(), False, ""
|
||||||
input_mode = False
|
|
||||||
input_str = ""
|
|
||||||
elif key == curses.KEY_BACKSPACE or key == 127:
|
elif key == curses.KEY_BACKSPACE or key == 127:
|
||||||
input_str = input_str[:-1]
|
input_str = input_str[:-1]
|
||||||
elif key != -1 and chr(key).isprintable():
|
elif key != -1 and chr(key).isprintable():
|
||||||
input_str += chr(key)
|
input_str += chr(key)
|
||||||
else: # Navigation mode
|
else: # Navigation mode
|
||||||
if key == curses.KEY_UP and current_row_idx > 0:
|
if key == curses.KEY_UP: current_row_idx = (current_row_idx - 1) % len(menu)
|
||||||
current_row_idx -= 1
|
elif key == curses.KEY_DOWN: current_row_idx = (current_row_idx + 1) % len(menu)
|
||||||
elif key == curses.KEY_DOWN and current_row_idx < len(menu) - 1:
|
|
||||||
current_row_idx += 1
|
|
||||||
elif key == curses.KEY_ENTER or key in [10, 13]:
|
elif key == curses.KEY_ENTER or key in [10, 13]:
|
||||||
selected_option = menu[current_row_idx]
|
selected_option = menu[current_row_idx]
|
||||||
message_time = time.time() # Set time for all actions
|
message_time = time.time()
|
||||||
|
|
||||||
if selected_option == "Exit":
|
if selected_option == "Exit": stop_event.set(); continue
|
||||||
stop_event.set()
|
elif selected_option == "Open Valve": client.write_register(REG_HOLDING_VALVE_COMMAND, 1, slave=slave_id); message = "-> Sent OPEN command"
|
||||||
continue
|
elif selected_option == "Close Valve": client.write_register(REG_HOLDING_VALVE_COMMAND, 2, slave=slave_id); message = "-> Sent CLOSE command"
|
||||||
elif selected_option == "Open Valve":
|
elif selected_option == "Stop Valve": client.write_register(REG_HOLDING_VALVE_COMMAND, 0, slave=slave_id); message = "-> Sent STOP command"
|
||||||
client.write_register(REG_HOLDING_VALVE_COMMAND, 1, slave=slave_id)
|
elif "Toggle Output" in selected_option:
|
||||||
message = "-> Sent OPEN command"
|
bit = 0 if "1" in selected_option else 1
|
||||||
elif selected_option == "Close Valve":
|
try:
|
||||||
client.write_register(REG_HOLDING_VALVE_COMMAND, 2, slave=slave_id)
|
current_val = client.read_holding_registers(REG_HOLDING_DIGITAL_OUTPUTS_STATE, count=1, slave=slave_id).registers[0]
|
||||||
message = "-> Sent CLOSE command"
|
new_val = current_val ^ (1 << bit)
|
||||||
elif selected_option == "Stop Valve":
|
client.write_register(REG_HOLDING_DIGITAL_OUTPUTS_STATE, new_val, slave=slave_id)
|
||||||
client.write_register(REG_HOLDING_VALVE_COMMAND, 0, slave=slave_id)
|
message = f"-> Toggled Output {bit+1}"
|
||||||
message = "-> Sent STOP command"
|
except Exception as e: message = f"-> Error: {e}"
|
||||||
elif "Set Max" in selected_option:
|
elif selected_option == "Set Watchdog":
|
||||||
input_mode = True
|
input_mode, input_prompt, input_target_reg = True, "Enter Watchdog Timeout (s): ", REG_HOLDING_WATCHDOG_TIMEOUT_S
|
||||||
input_prompt = f"Enter new value for '{selected_option}' (seconds): "
|
elif selected_option == "Firmware Update":
|
||||||
input_target_reg = REG_HOLDING_MAX_OPENING_TIME_S if "Opening" in selected_option else REG_HOLDING_MAX_CLOSING_TIME_S
|
message = "-> Firmware update process not yet implemented."
|
||||||
|
|
||||||
# --- Drawing Logic (Single Source of Truth) ---
|
|
||||||
stdscr.clear()
|
stdscr.clear()
|
||||||
|
with status_lock: current_data = status_data.copy()
|
||||||
# 1. Draw Status Area
|
|
||||||
with status_lock:
|
|
||||||
current_data = status_data.copy()
|
|
||||||
|
|
||||||
if current_data.get("error"):
|
if current_data.get("error"):
|
||||||
stdscr.addstr(0, 0, current_data["error"], curses.color_pair(3) | curses.A_BOLD)
|
stdscr.addstr(0, 0, current_data["error"], curses.color_pair(3) | curses.A_BOLD)
|
||||||
else:
|
else:
|
||||||
bold = curses.color_pair(1) | curses.A_BOLD
|
bold, normal = curses.color_pair(1) | curses.A_BOLD, curses.color_pair(1)
|
||||||
normal = curses.color_pair(1)
|
# Status Area
|
||||||
col1_x, col2_x, col3_x = 2, 35, 70
|
col1, col2, col3, col4 = 2, 30, 58, 88
|
||||||
stdscr.addstr(1, col1_x, "Valve State:", bold); stdscr.addstr(1, col1_x + 14, str(current_data.get('state', 'N/A')), normal)
|
stdscr.addstr(1, col1, "State:", bold); stdscr.addstr(1, col1 + 18, str(current_data.get('state', 'N/A')), normal)
|
||||||
stdscr.addstr(2, col1_x, "Movement:", bold); stdscr.addstr(2, col1_x + 14, str(current_data.get('movement', 'N/A')), normal)
|
stdscr.addstr(2, col1, "Movement:", bold); stdscr.addstr(2, col1 + 18, str(current_data.get('movement', 'N/A')), normal)
|
||||||
stdscr.addstr(3, col1_x, "Motor Current:", bold); stdscr.addstr(3, col1_x + 14, str(current_data.get('motor_current', 'N/A')), normal)
|
stdscr.addstr(3, col1, "Motor Current:", bold); stdscr.addstr(3, col1 + 18, str(current_data.get('motor_current', 'N/A')), normal)
|
||||||
stdscr.addstr(1, col2_x, "Max Open Time:", bold); stdscr.addstr(1, col2_x + 16, str(current_data.get('open_time', 'N/A')), normal)
|
|
||||||
stdscr.addstr(2, col2_x, "Max Close Time:", bold); stdscr.addstr(2, col2_x + 16, str(current_data.get('close_time', 'N/A')), normal)
|
stdscr.addstr(1, col2, "Digital Inputs:", bold); stdscr.addstr(1, col2 + 18, str(current_data.get('digital_inputs', 'N/A')), normal)
|
||||||
stdscr.addstr(1, col3_x, "Firmware:", bold); stdscr.addstr(1, col3_x + 11, str(current_data.get('firmware', 'N/A')), normal)
|
stdscr.addstr(2, col2, "Digital Outputs:", bold); stdscr.addstr(2, col2 + 18, str(current_data.get('digital_outputs', 'N/A')), normal)
|
||||||
stdscr.addstr(2, col3_x, "Uptime:", bold); stdscr.addstr(2, col3_x + 11, str(current_data.get('uptime', 'N/A')), normal)
|
stdscr.addstr(3, col2, "Button Events:", bold); stdscr.addstr(3, col2 + 18, str(current_data.get('button_events', 'N/A')), normal)
|
||||||
|
|
||||||
|
stdscr.addstr(1, col3, "Max Open Time:", bold); stdscr.addstr(1, col3 + 16, str(current_data.get('open_time', 'N/A')), normal)
|
||||||
|
stdscr.addstr(2, col3, "Max Close Time:", bold); stdscr.addstr(2, col3 + 16, str(current_data.get('close_time', 'N/A')), normal)
|
||||||
|
stdscr.addstr(3, col3, "Watchdog:", bold); stdscr.addstr(3, col3 + 16, str(current_data.get('watchdog', 'N/A')), normal)
|
||||||
|
|
||||||
|
stdscr.addstr(1, col4, "Firmware:", bold); stdscr.addstr(1, col4 + 12, str(current_data.get('firmware', 'N/A')), normal)
|
||||||
|
stdscr.addstr(2, col4, "Uptime:", bold); stdscr.addstr(2, col4 + 12, str(current_data.get('uptime', 'N/A')), normal)
|
||||||
|
stdscr.addstr(3, col4, "Device Status:", bold); stdscr.addstr(3, col4 + 12, str(current_data.get('device_status', 'N/A')), normal)
|
||||||
|
|
||||||
stdscr.addstr(5, 0, "─" * (w - 1), normal)
|
stdscr.addstr(5, 0, "─" * (w - 1), normal)
|
||||||
|
|
||||||
# 2. Draw Menu Buttons
|
|
||||||
for idx, row in enumerate(menu):
|
for idx, row in enumerate(menu):
|
||||||
x = w // 2 - (len(row) + 4) // 2
|
x = w // 2 - (len(row) + 4) // 2
|
||||||
y = h // 2 - len(menu) + (idx * 3)
|
y = h // 2 - len(menu) + (idx * 3)
|
||||||
draw_button(stdscr, y, x, row, idx == current_row_idx)
|
draw_button(stdscr, y, x, row, idx == current_row_idx)
|
||||||
|
|
||||||
# 3. Draw Transient Message or Input Prompt
|
|
||||||
if time.time() - message_time < 2.0:
|
if time.time() - message_time < 2.0:
|
||||||
stdscr.addstr(h - 2, 0, message.ljust(w - 1), curses.color_pair(1) | curses.A_BOLD)
|
stdscr.addstr(h - 2, 0, message.ljust(w - 1), curses.color_pair(1) | curses.A_BOLD)
|
||||||
|
|
||||||
|
|
@ -231,14 +230,10 @@ def main():
|
||||||
|
|
||||||
client = ModbusSerialClient(port=args.port, baudrate=args.baud, stopbits=1, bytesize=8, parity="N", timeout=1)
|
client = ModbusSerialClient(port=args.port, baudrate=args.baud, stopbits=1, bytesize=8, parity="N", timeout=1)
|
||||||
if not client.connect():
|
if not client.connect():
|
||||||
print(f"Error: Failed to connect to serial port {args.port}")
|
print(f"Error: Failed to connect to serial port {args.port}"); sys.exit(1)
|
||||||
sys.exit(1)
|
|
||||||
|
|
||||||
print(f"Successfully connected to {args.port}. Starting UI...")
|
print("Successfully connected. Starting UI..."); time.sleep(0.5)
|
||||||
time.sleep(0.5)
|
poll_thread = threading.Thread(target=poll_status, args=(args.slave_id, args.interval), daemon=True)
|
||||||
|
|
||||||
poll_thread = threading.Thread(target=poll_status, args=(args.slave_id, args.interval))
|
|
||||||
poll_thread.daemon = True
|
|
||||||
poll_thread.start()
|
poll_thread.start()
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
|
@ -246,8 +241,7 @@ def main():
|
||||||
finally:
|
finally:
|
||||||
stop_event.set()
|
stop_event.set()
|
||||||
print("\nExiting...")
|
print("\nExiting...")
|
||||||
if client.is_socket_open():
|
if client.is_socket_open(): client.close()
|
||||||
client.close()
|
|
||||||
poll_thread.join(timeout=2)
|
poll_thread.join(timeout=2)
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue