Initial commit: C++20 SECS-II / HSMS / GEM client + server
A fully containerised SECS/GEM toolchain. Single docker compose project,
no host build tools. 63 unit-test cases / 278 assertions, two demo
executables, end-to-end two-container demo exercising every implemented
capability.
Architecture (bottom-up):
secs2/ E5 SECS-II codec
Item variant over L/A/B/BOOLEAN/I1-8/U1-8/F4/F8
encode/decode big-endian, 1/2/3-byte length encoding
Message SxFy + W-bit + optional root item
to_sml human-readable text rendering
hsms/ E37 HSMS transport (TCP)
Header 10-byte header + SType enum (Data/Select/Deselect/
Linktest/Reject/Separate)
Frame 4-byte length prefix + payload encode/decode
Connection async Asio TCP, NOT-SELECTED -> SELECTED state machine,
T3/T5/T6/T7/T8 timers, system-bytes reply correlation,
graceful close-after-flush separation
endpoint active Client (connect with T5 retry) and passive Server
(accept loop) wrappers over Connection
gem/ E30 GEM logic
ControlStateMachine 5-state E30 control model with operator
actions, host requests, SEMI-mandated ack
codes (OnlineAck, OfflineAck, CommAck), and
a state-change handler
EquipmentDataModel in-memory dictionary: SVIDs, DVIDs, ECIDs
(with EAC), CEIDs, report defs, CEID->report
links, enabled-events set, alarm table
(ALCD, enabled, active), process programs,
host command registry, clock (16-char
YYYYMMDDhhmmsscc with offset)
messages.hpp builders + parsers for every SxFy below
GEM message coverage (full list):
S1F1/F2 Are You There / On Line Data
S1F3/F4 Selected Equipment Status Request / Data
S1F11/F12 Status Variable Namelist Request / Data
S1F13/F14 Establish Communications (+ CommAck)
S1F15/F16 Request OFFLINE (+ OfflineAck)
S1F17/F18 Request ONLINE (+ OnlineAck)
S2F13/F14 Equipment Constant Request / Data
S2F15/F16 EC Send + EquipmentAck (Accept/UnknownEcid/Busy/OutOfRange)
S2F17/F18 Date and Time Request / Data
S2F29/F30 Equipment Constant Namelist Request / Data
S2F31/F32 Date and Time Set Request / TimeAck
S2F33/F34 Define Report + DefineReportAck (5 enum values)
S2F35/F36 Link Event Report + LinkEventAck
S2F37/F38 Enable / Disable Event Report + EnableEventAck
S2F41/F42 Host Command + HostCmdAck (7 values) + per-param CPACKs
S5F1/F2 Alarm Report Send + AlarmAck (ALCD bit-7 set/cleared
+ lower-7 category)
S5F3/F4 Enable/Disable Alarm Send + AlarmAck
S5F5/F6 List Alarms Request / Data (active alarms tagged in ALCD)
S6F11/F12 Event Report Send (equipment-initiated CEID emission
with full report data) + EventReportAck
S7F3/F4 Process Program Send + ProcessProgramAck (7 values)
S7F5/F6 Process Program Request / Data
S7F19/F20 Current EPPD List Request / Data
S10F1/F2 Terminal Display Single (host->equipment) + TerminalAck
S10F3/F4 Terminal Display Single (equipment->host)
Demo apps:
apps/secs_server.cpp passive equipment. Populates the data model
with 3 SVIDs (ControlState, Clock,
EventsEnabled), 2 ECIDs, 3 CEIDs
(ControlStateChanged, AlarmSetEvent,
ProcessStarted), 2 alarms (Chiller Temp High
cat 4, Door Open cat 1), 2 recipes
(RECIPE-A, RECIPE-B), and 4 host commands
(START, STOP, PAUSE, FAULT). Emits S6F11 on
every control state transition + on START;
emits S5F1 + the AlarmSetEvent CEID on FAULT.
Pushes an S10F3 welcome message when the host
comes online.
apps/secs_client.cpp active host. Walks 17 steps: Establish ->
Online -> S1F11 SVID namelist -> S1F3 read ->
S2F29 EC namelist -> S2F13 read ->
S2F17 clock -> S2F33/S2F35/S2F37 dynamic
event subscription -> S2F41 START
(-> receives S6F11) -> S5F5 alarm list ->
S5F3 enable alarm 1 -> S2F41 FAULT
(-> receives S5F1 + S6F11) -> S7F19/S7F5
recipe list + body -> S10F1 terminal ->
S1F15 Offline -> Separate. Handles inbound
S6F11, S5F1, S10F3 primaries.
Testing:
tests/test_secs2.cpp codec round-trip for every format,
byte-layout assertions for known values,
truncation/trailing-byte rejection,
nested list round-trip, SML rendering
tests/test_hsms.cpp header byte layout, data + control
header round-trip, full frame round-
trip with length prefix, short-payload
rejection
tests/test_control_state.cpp every (state, event) pair in the E30
control state machine, including
AlreadyOnline / NotAccept rejections
and idempotent offline-while-offline
tests/test_data_model.cpp SVID/ECID/Alarm/Recipe CRUD, clock
format + parse, host command registry,
full event-report pipeline (define ->
link -> enable -> compose) with
every error path (InvalidVid,
UnknownCeid, UnknownRptid), alarm
set/clear with ALCD bit-7 semantics
tests/test_messages.cpp round-trip + byte-layout for every
builder/parser pair, including S6F11
event reports with mixed item types
Toolchain:
Dockerfile Ubuntu 24.04, g++-13, CMake, Ninja, libasio-dev
docker-compose.yml builder / tests / server / client services,
source bind-mounted, build artifacts in a
named volume so the host tree stays clean
CMakeLists.txt C++20, -Wall -Wextra -Wpedantic, standalone
Asio (ASIO_STANDALONE), doctest via FetchContent
Documentation:
README.md architecture, quick start, demo log
COMPLIANCE.md honest per-capability E5/E30/E37 audit with
spec section refs. Calls out what's implemented,
what's partial (Reject.req, Alarms missing F7/F8,
EC range validation, PP without verify, terminal
single-line only), and what's intentionally not
yet implemented (spooling, S9 error stream,
Documentation S1F19/F20+F21/F22, limits monitoring,
trace data collection, multi-block, material
movement). Does NOT claim "100% GEM-compliant" and
lists the work required to honestly make that claim.
This is Layer 0 + the start of Layer 1 from implementation_plan.md.
The transition-table-driven "spec-as-data" architecture (Layer 1
proper) is not yet implemented; the current code uses imperative
state machines that are structurally ready to be refactored onto
tables.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,396 @@
|
||||
#include "secsgem/hsms/connection.hpp"
|
||||
|
||||
#include <exception>
|
||||
|
||||
namespace secsgem::hsms {
|
||||
namespace {
|
||||
|
||||
class HsmsCategory : public std::error_category {
|
||||
public:
|
||||
const char* name() const noexcept override { return "hsms"; }
|
||||
std::string message(int ev) const override {
|
||||
switch (static_cast<Error>(ev)) {
|
||||
case Error::Timeout: return "HSMS transaction timeout";
|
||||
case Error::Closed: return "HSMS connection closed";
|
||||
}
|
||||
return "unknown HSMS error";
|
||||
}
|
||||
};
|
||||
|
||||
const HsmsCategory g_category;
|
||||
|
||||
constexpr std::size_t kMaxFrameLength = 16 * 1024 * 1024;
|
||||
|
||||
} // namespace
|
||||
|
||||
std::error_code make_error(Error e) {
|
||||
return {static_cast<int>(e), g_category};
|
||||
}
|
||||
|
||||
Connection::Connection(asio::ip::tcp::socket socket, Mode mode, uint16_t device_id,
|
||||
Timers timers)
|
||||
: socket_(std::move(socket)),
|
||||
t6_timer_(socket_.get_executor()),
|
||||
t7_timer_(socket_.get_executor()),
|
||||
t8_timer_(socket_.get_executor()),
|
||||
linktest_timer_(socket_.get_executor()),
|
||||
mode_(mode),
|
||||
device_id_(device_id),
|
||||
timers_(timers) {}
|
||||
|
||||
void Connection::start() {
|
||||
read_length();
|
||||
if (mode_ == Mode::Active) {
|
||||
send_select_req();
|
||||
} else {
|
||||
arm_t7();
|
||||
}
|
||||
}
|
||||
|
||||
// --- read path ------------------------------------------------------------
|
||||
|
||||
void Connection::read_length() {
|
||||
if (closed_) return;
|
||||
auto self = shared_from_this();
|
||||
asio::async_read(socket_, asio::buffer(len_buf_),
|
||||
[this, self](std::error_code ec, std::size_t n) { on_length(ec, n); });
|
||||
}
|
||||
|
||||
void Connection::on_length(std::error_code ec, std::size_t) {
|
||||
if (closed_) return;
|
||||
if (ec) {
|
||||
close("read length: " + ec.message());
|
||||
return;
|
||||
}
|
||||
const uint32_t len = (static_cast<uint32_t>(len_buf_[0]) << 24) |
|
||||
(static_cast<uint32_t>(len_buf_[1]) << 16) |
|
||||
(static_cast<uint32_t>(len_buf_[2]) << 8) |
|
||||
static_cast<uint32_t>(len_buf_[3]);
|
||||
if (len < kHeaderSize) {
|
||||
close("invalid frame length " + std::to_string(len));
|
||||
return;
|
||||
}
|
||||
if (len > kMaxFrameLength) {
|
||||
close("frame too large: " + std::to_string(len));
|
||||
return;
|
||||
}
|
||||
|
||||
payload_.resize(len);
|
||||
|
||||
t8_timer_.expires_after(timers_.t8);
|
||||
auto self = shared_from_this();
|
||||
t8_timer_.async_wait([this, self](std::error_code tec) {
|
||||
if (!tec && !closed_) close("T8 intercharacter timeout");
|
||||
});
|
||||
asio::async_read(socket_, asio::buffer(payload_),
|
||||
[this, self](std::error_code rec, std::size_t n) { on_payload(rec, n); });
|
||||
}
|
||||
|
||||
void Connection::on_payload(std::error_code ec, std::size_t) {
|
||||
if (closed_) return;
|
||||
t8_timer_.cancel();
|
||||
if (ec) {
|
||||
close("read payload: " + ec.message());
|
||||
return;
|
||||
}
|
||||
try {
|
||||
handle_frame(Frame::decode(payload_.data(), payload_.size()));
|
||||
} catch (const std::exception& e) {
|
||||
close(std::string("decode: ") + e.what());
|
||||
return;
|
||||
}
|
||||
read_length();
|
||||
}
|
||||
|
||||
void Connection::handle_frame(Frame frame) {
|
||||
if (frame.header.stype == SType::Data) {
|
||||
handle_data(frame);
|
||||
} else {
|
||||
handle_control(frame);
|
||||
}
|
||||
}
|
||||
|
||||
void Connection::handle_data(const Frame& frame) {
|
||||
const Header& h = frame.header;
|
||||
|
||||
// Reply correlation: an even function with matching system bytes completes an
|
||||
// outstanding request.
|
||||
auto it = pending_requests_.find(h.system_bytes);
|
||||
if ((h.function() % 2 == 0) && it != pending_requests_.end()) {
|
||||
secs2::Message reply;
|
||||
try {
|
||||
reply = secs2::Message::from_body(h.stream(), h.function(), h.w_bit(), frame.body);
|
||||
} catch (const std::exception& e) {
|
||||
close(std::string("reply body decode: ") + e.what());
|
||||
return;
|
||||
}
|
||||
auto cb = std::move(it->second.cb);
|
||||
it->second.t3->cancel();
|
||||
pending_requests_.erase(it);
|
||||
log("<- " + h.describe());
|
||||
cb({}, reply);
|
||||
return;
|
||||
}
|
||||
|
||||
// Primary message; only valid while SELECTED.
|
||||
if (state_ != State::Selected) {
|
||||
send_frame(Frame(Header::control(SType::RejectReq, h.system_bytes, kControlSessionId,
|
||||
static_cast<uint8_t>(SType::Data),
|
||||
static_cast<uint8_t>(RejectReason::EntityNotSelected))));
|
||||
return;
|
||||
}
|
||||
|
||||
secs2::Message msg;
|
||||
try {
|
||||
msg = secs2::Message::from_body(h.stream(), h.function(), h.w_bit(), frame.body);
|
||||
} catch (const std::exception& e) {
|
||||
close(std::string("message body decode: ") + e.what());
|
||||
return;
|
||||
}
|
||||
|
||||
log("<- " + h.describe());
|
||||
if (!on_message_) return;
|
||||
|
||||
auto reply = on_message_(msg);
|
||||
if (reply) {
|
||||
Frame out(Header::data_message(device_id_, reply->stream, reply->function,
|
||||
reply->reply_expected, h.system_bytes),
|
||||
reply->encode_body());
|
||||
log("-> " + out.header.describe());
|
||||
send_frame(std::move(out));
|
||||
}
|
||||
}
|
||||
|
||||
void Connection::handle_control(const Frame& frame) {
|
||||
const Header& h = frame.header;
|
||||
switch (h.stype) {
|
||||
case SType::SelectReq: {
|
||||
log("<- Select.req");
|
||||
send_frame(Frame(Header::control(SType::SelectRsp, h.system_bytes, h.session_id, 0,
|
||||
static_cast<uint8_t>(SelectStatus::Ok))));
|
||||
log("-> Select.rsp (Ok)");
|
||||
enter_selected();
|
||||
break;
|
||||
}
|
||||
case SType::SelectRsp: {
|
||||
if (pending_control_ && pending_control_->expected_response == SType::SelectRsp &&
|
||||
pending_control_->system_bytes == h.system_bytes) {
|
||||
clear_control_transaction();
|
||||
if (h.byte3 == static_cast<uint8_t>(SelectStatus::Ok)) {
|
||||
log("<- Select.rsp (Ok)");
|
||||
enter_selected();
|
||||
} else {
|
||||
close("Select rejected, status=" + std::to_string(h.byte3));
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case SType::DeselectReq: {
|
||||
log("<- Deselect.req");
|
||||
send_frame(Frame(Header::control(SType::DeselectRsp, h.system_bytes, h.session_id, 0,
|
||||
static_cast<uint8_t>(DeselectStatus::Ok))));
|
||||
state_ = State::NotSelected;
|
||||
arm_t7();
|
||||
break;
|
||||
}
|
||||
case SType::DeselectRsp: {
|
||||
if (pending_control_ && pending_control_->expected_response == SType::DeselectRsp &&
|
||||
pending_control_->system_bytes == h.system_bytes) {
|
||||
clear_control_transaction();
|
||||
state_ = State::NotSelected;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case SType::LinktestReq: {
|
||||
send_frame(Frame(Header::control(SType::LinktestRsp, h.system_bytes)));
|
||||
break;
|
||||
}
|
||||
case SType::LinktestRsp: {
|
||||
if (pending_control_ && pending_control_->expected_response == SType::LinktestRsp &&
|
||||
pending_control_->system_bytes == h.system_bytes) {
|
||||
clear_control_transaction();
|
||||
arm_linktest();
|
||||
}
|
||||
break;
|
||||
}
|
||||
case SType::SeparateReq: {
|
||||
log("<- Separate.req");
|
||||
close("peer separated");
|
||||
break;
|
||||
}
|
||||
case SType::RejectReq: {
|
||||
log("<- Reject.req reason=" + std::to_string(h.byte3));
|
||||
break;
|
||||
}
|
||||
case SType::Data:
|
||||
break; // unreachable
|
||||
}
|
||||
}
|
||||
|
||||
// --- write path -----------------------------------------------------------
|
||||
|
||||
void Connection::send_frame(Frame frame) {
|
||||
if (closed_) return;
|
||||
write_queue_.push_back(frame.encode());
|
||||
if (!writing_) write_next();
|
||||
}
|
||||
|
||||
void Connection::write_next() {
|
||||
if (write_queue_.empty()) {
|
||||
writing_ = false;
|
||||
if (close_after_flush_) close(close_reason_);
|
||||
return;
|
||||
}
|
||||
writing_ = true;
|
||||
auto self = shared_from_this();
|
||||
asio::async_write(socket_, asio::buffer(write_queue_.front()),
|
||||
[this, self](std::error_code ec, std::size_t) {
|
||||
write_queue_.pop_front();
|
||||
if (ec) {
|
||||
close("write: " + ec.message());
|
||||
return;
|
||||
}
|
||||
write_next();
|
||||
});
|
||||
}
|
||||
|
||||
// --- public send API ------------------------------------------------------
|
||||
|
||||
void Connection::send_request(secs2::Message msg, ReplyHandler cb) {
|
||||
if (closed_) {
|
||||
cb(make_error(Error::Closed), {});
|
||||
return;
|
||||
}
|
||||
const uint32_t sys = next_system_bytes();
|
||||
Frame f(Header::data_message(device_id_, msg.stream, msg.function, true, sys),
|
||||
msg.encode_body());
|
||||
|
||||
auto t3 = std::make_shared<asio::steady_timer>(socket_.get_executor());
|
||||
t3->expires_after(timers_.t3);
|
||||
pending_requests_.emplace(sys, PendingRequest{std::move(cb), t3});
|
||||
|
||||
auto self = shared_from_this();
|
||||
t3->async_wait([this, self, sys](std::error_code ec) {
|
||||
if (ec) return;
|
||||
auto it = pending_requests_.find(sys);
|
||||
if (it == pending_requests_.end()) return;
|
||||
auto cb2 = std::move(it->second.cb);
|
||||
pending_requests_.erase(it);
|
||||
cb2(make_error(Error::Timeout), {});
|
||||
});
|
||||
|
||||
log("-> " + f.header.describe());
|
||||
send_frame(std::move(f));
|
||||
}
|
||||
|
||||
void Connection::send_data(secs2::Message msg) {
|
||||
if (closed_) return;
|
||||
const uint32_t sys = next_system_bytes();
|
||||
Frame f(Header::data_message(device_id_, msg.stream, msg.function, msg.reply_expected, sys),
|
||||
msg.encode_body());
|
||||
log("-> " + f.header.describe());
|
||||
send_frame(std::move(f));
|
||||
}
|
||||
|
||||
void Connection::separate() {
|
||||
if (closed_) return;
|
||||
Frame f(Header::control(SType::SeparateReq, next_system_bytes(), device_id_));
|
||||
log("-> Separate.req");
|
||||
close_after_flush_ = true;
|
||||
close_reason_ = "separated";
|
||||
send_frame(std::move(f));
|
||||
}
|
||||
|
||||
void Connection::close(const std::string& reason) {
|
||||
if (closed_) return;
|
||||
closed_ = true;
|
||||
|
||||
std::error_code ignore;
|
||||
t6_timer_.cancel();
|
||||
t7_timer_.cancel();
|
||||
t8_timer_.cancel();
|
||||
linktest_timer_.cancel();
|
||||
socket_.shutdown(asio::ip::tcp::socket::shutdown_both, ignore);
|
||||
socket_.close(ignore);
|
||||
|
||||
for (auto& [sys, pr] : pending_requests_) {
|
||||
pr.t3->cancel();
|
||||
pr.cb(make_error(Error::Closed), {});
|
||||
}
|
||||
pending_requests_.clear();
|
||||
|
||||
log("xx CLOSED: " + reason);
|
||||
if (on_closed_) on_closed_(reason);
|
||||
}
|
||||
|
||||
// --- handshakes & timers --------------------------------------------------
|
||||
|
||||
void Connection::send_select_req() {
|
||||
const uint32_t sys = next_system_bytes();
|
||||
log("-> Select.req");
|
||||
send_frame(Frame(Header::control(SType::SelectReq, sys)));
|
||||
start_control_transaction(SType::SelectRsp, sys, "Select");
|
||||
}
|
||||
|
||||
void Connection::send_linktest_req() {
|
||||
const uint32_t sys = next_system_bytes();
|
||||
send_frame(Frame(Header::control(SType::LinktestReq, sys)));
|
||||
start_control_transaction(SType::LinktestRsp, sys, "Linktest");
|
||||
}
|
||||
|
||||
void Connection::enter_selected() {
|
||||
if (state_ == State::Selected) return;
|
||||
state_ = State::Selected;
|
||||
t7_timer_.cancel();
|
||||
log("== SELECTED ==");
|
||||
arm_linktest();
|
||||
if (on_selected_) on_selected_();
|
||||
}
|
||||
|
||||
void Connection::arm_t7() {
|
||||
if (mode_ != Mode::Passive) return;
|
||||
if (timers_.t7.count() <= 0) return;
|
||||
t7_timer_.expires_after(timers_.t7);
|
||||
auto self = shared_from_this();
|
||||
t7_timer_.async_wait([this, self](std::error_code ec) {
|
||||
if (!ec && !closed_ && state_ == State::NotSelected) close("T7 not-selected timeout");
|
||||
});
|
||||
}
|
||||
|
||||
void Connection::arm_linktest() {
|
||||
if (timers_.linktest.count() <= 0) return;
|
||||
if (state_ != State::Selected) return;
|
||||
linktest_timer_.expires_after(timers_.linktest);
|
||||
auto self = shared_from_this();
|
||||
linktest_timer_.async_wait([this, self](std::error_code ec) {
|
||||
if (!ec && !closed_ && state_ == State::Selected) send_linktest_req();
|
||||
});
|
||||
}
|
||||
|
||||
void Connection::start_control_transaction(SType expected_response, uint32_t system_bytes,
|
||||
const char* what) {
|
||||
pending_control_ = PendingControl{expected_response, system_bytes};
|
||||
t6_timer_.expires_after(timers_.t6);
|
||||
auto self = shared_from_this();
|
||||
std::string what_str = what;
|
||||
t6_timer_.async_wait([this, self, what_str](std::error_code ec) {
|
||||
if (!ec && !closed_ && pending_control_) close("T6 timeout on " + what_str);
|
||||
});
|
||||
}
|
||||
|
||||
void Connection::clear_control_transaction() {
|
||||
pending_control_.reset();
|
||||
t6_timer_.cancel();
|
||||
}
|
||||
|
||||
uint32_t Connection::next_system_bytes() {
|
||||
uint32_t s = next_system_bytes_++;
|
||||
if (next_system_bytes_ == 0) next_system_bytes_ = 1;
|
||||
return s;
|
||||
}
|
||||
|
||||
void Connection::log(const std::string& msg) {
|
||||
if (on_log_) on_log_(msg);
|
||||
}
|
||||
|
||||
} // namespace secsgem::hsms
|
||||
Reference in New Issue
Block a user