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,97 @@
|
||||
#include "secsgem/endpoint.hpp"
|
||||
|
||||
namespace secsgem {
|
||||
|
||||
using asio::ip::tcp;
|
||||
|
||||
// --- Server ---------------------------------------------------------------
|
||||
|
||||
Server::Server(asio::io_context& io, Config cfg)
|
||||
: io_(io),
|
||||
acceptor_(io, tcp::endpoint(tcp::v4(), cfg.port)),
|
||||
cfg_(std::move(cfg)) {}
|
||||
|
||||
void Server::start() {
|
||||
log("listening on port " + std::to_string(cfg_.port) +
|
||||
" (device " + std::to_string(cfg_.device_id) + ")");
|
||||
do_accept();
|
||||
}
|
||||
|
||||
void Server::do_accept() {
|
||||
acceptor_.async_accept([this](std::error_code ec, tcp::socket socket) {
|
||||
if (ec) {
|
||||
log("accept error: " + ec.message());
|
||||
return;
|
||||
}
|
||||
std::error_code rec;
|
||||
auto remote = socket.remote_endpoint(rec);
|
||||
log("accepted connection from " +
|
||||
(rec ? std::string("?") : remote.address().to_string() + ":" +
|
||||
std::to_string(remote.port())));
|
||||
|
||||
auto conn = std::make_shared<Connection>(std::move(socket), Connection::Mode::Passive,
|
||||
cfg_.device_id, cfg_.timers);
|
||||
if (on_log_) conn->set_log_handler(on_log_);
|
||||
if (on_connection_) on_connection_(conn);
|
||||
conn->start();
|
||||
|
||||
do_accept();
|
||||
});
|
||||
}
|
||||
|
||||
void Server::log(const std::string& msg) {
|
||||
if (on_log_) on_log_(msg);
|
||||
}
|
||||
|
||||
// --- Client ---------------------------------------------------------------
|
||||
|
||||
Client::Client(asio::io_context& io, Config cfg)
|
||||
: io_(io), resolver_(io), retry_timer_(io), cfg_(std::move(cfg)) {}
|
||||
|
||||
void Client::start() {
|
||||
do_connect();
|
||||
}
|
||||
|
||||
void Client::do_connect() {
|
||||
log("connecting to " + cfg_.host + ":" + std::to_string(cfg_.port));
|
||||
resolver_.async_resolve(
|
||||
cfg_.host, std::to_string(cfg_.port),
|
||||
[this](std::error_code ec, tcp::resolver::results_type results) {
|
||||
if (ec) {
|
||||
log("resolve failed: " + ec.message());
|
||||
schedule_retry();
|
||||
return;
|
||||
}
|
||||
auto socket = std::make_shared<tcp::socket>(io_);
|
||||
asio::async_connect(
|
||||
*socket, results,
|
||||
[this, socket](std::error_code cec, const tcp::endpoint& ep) {
|
||||
if (cec) {
|
||||
log("connect failed: " + cec.message());
|
||||
schedule_retry();
|
||||
return;
|
||||
}
|
||||
log("connected to " + ep.address().to_string() + ":" +
|
||||
std::to_string(ep.port()));
|
||||
auto conn = std::make_shared<Connection>(
|
||||
std::move(*socket), Connection::Mode::Active, cfg_.device_id, cfg_.timers);
|
||||
if (on_log_) conn->set_log_handler(on_log_);
|
||||
if (on_connection_) on_connection_(conn);
|
||||
conn->start();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
void Client::schedule_retry() {
|
||||
log("retrying in " + std::to_string(cfg_.timers.t5.count()) + " ms (T5)");
|
||||
retry_timer_.expires_after(cfg_.timers.t5);
|
||||
retry_timer_.async_wait([this](std::error_code ec) {
|
||||
if (!ec) do_connect();
|
||||
});
|
||||
}
|
||||
|
||||
void Client::log(const std::string& msg) {
|
||||
if (on_log_) on_log_(msg);
|
||||
}
|
||||
|
||||
} // namespace secsgem
|
||||
@@ -0,0 +1,126 @@
|
||||
#include "secsgem/gem/control_state.hpp"
|
||||
|
||||
namespace secsgem::gem {
|
||||
|
||||
const char* control_state_name(ControlState s) {
|
||||
switch (s) {
|
||||
case ControlState::EquipmentOffline: return "EquipmentOffline";
|
||||
case ControlState::AttemptOnline: return "AttemptOnline";
|
||||
case ControlState::HostOffline: return "HostOffline";
|
||||
case ControlState::OnlineLocal: return "OnlineLocal";
|
||||
case ControlState::OnlineRemote: return "OnlineRemote";
|
||||
}
|
||||
return "?";
|
||||
}
|
||||
|
||||
bool is_online(ControlState s) {
|
||||
return s == ControlState::OnlineLocal || s == ControlState::OnlineRemote;
|
||||
}
|
||||
|
||||
const char* control_event_name(ControlEvent e) {
|
||||
switch (e) {
|
||||
case ControlEvent::OperatorSwitchOnline: return "OperatorSwitchOnline";
|
||||
case ControlEvent::OperatorSwitchOffline: return "OperatorSwitchOffline";
|
||||
case ControlEvent::OperatorSwitchLocal: return "OperatorSwitchLocal";
|
||||
case ControlEvent::OperatorSwitchRemote: return "OperatorSwitchRemote";
|
||||
case ControlEvent::AttemptComplete: return "AttemptComplete";
|
||||
case ControlEvent::AttemptFailed: return "AttemptFailed";
|
||||
case ControlEvent::HostRequestOnline: return "HostRequestOnline";
|
||||
case ControlEvent::HostRequestOffline: return "HostRequestOffline";
|
||||
}
|
||||
return "?";
|
||||
}
|
||||
|
||||
ControlStateMachine::ControlStateMachine() : ControlStateMachine(Config{}) {}
|
||||
|
||||
ControlStateMachine::ControlStateMachine(Config cfg)
|
||||
: cfg_(cfg), state_(cfg.initial) {}
|
||||
|
||||
void ControlStateMachine::transition(ControlState next, ControlEvent trigger) {
|
||||
if (state_ == next) return;
|
||||
const ControlState prev = state_;
|
||||
state_ = next;
|
||||
if (on_change_) on_change_(prev, next, trigger);
|
||||
}
|
||||
|
||||
bool ControlStateMachine::operator_online() {
|
||||
switch (state_) {
|
||||
case ControlState::EquipmentOffline:
|
||||
case ControlState::HostOffline:
|
||||
transition(ControlState::AttemptOnline, ControlEvent::OperatorSwitchOnline);
|
||||
transition(cfg_.operator_default_remote ? ControlState::OnlineRemote
|
||||
: ControlState::OnlineLocal,
|
||||
ControlEvent::AttemptComplete);
|
||||
return true;
|
||||
case ControlState::AttemptOnline:
|
||||
case ControlState::OnlineLocal:
|
||||
case ControlState::OnlineRemote:
|
||||
return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool ControlStateMachine::operator_offline() {
|
||||
switch (state_) {
|
||||
case ControlState::OnlineLocal:
|
||||
case ControlState::OnlineRemote:
|
||||
case ControlState::AttemptOnline:
|
||||
transition(ControlState::HostOffline, ControlEvent::OperatorSwitchOffline);
|
||||
return true;
|
||||
case ControlState::EquipmentOffline:
|
||||
case ControlState::HostOffline:
|
||||
return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool ControlStateMachine::operator_local() {
|
||||
if (state_ == ControlState::OnlineRemote) {
|
||||
transition(ControlState::OnlineLocal, ControlEvent::OperatorSwitchLocal);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool ControlStateMachine::operator_remote() {
|
||||
if (state_ == ControlState::OnlineLocal) {
|
||||
transition(ControlState::OnlineRemote, ControlEvent::OperatorSwitchRemote);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
OnlineAck ControlStateMachine::on_host_request_online() {
|
||||
switch (state_) {
|
||||
case ControlState::HostOffline:
|
||||
transition(ControlState::AttemptOnline, ControlEvent::HostRequestOnline);
|
||||
transition(cfg_.host_request_grants_remote ? ControlState::OnlineRemote
|
||||
: ControlState::OnlineLocal,
|
||||
ControlEvent::AttemptComplete);
|
||||
return OnlineAck::Accept;
|
||||
case ControlState::OnlineLocal:
|
||||
case ControlState::OnlineRemote:
|
||||
return OnlineAck::AlreadyOnline;
|
||||
case ControlState::EquipmentOffline:
|
||||
case ControlState::AttemptOnline:
|
||||
return OnlineAck::NotAccept;
|
||||
}
|
||||
return OnlineAck::NotAccept;
|
||||
}
|
||||
|
||||
OfflineAck ControlStateMachine::on_host_request_offline() {
|
||||
switch (state_) {
|
||||
case ControlState::OnlineLocal:
|
||||
case ControlState::OnlineRemote:
|
||||
transition(ControlState::HostOffline, ControlEvent::HostRequestOffline);
|
||||
return OfflineAck::Accept;
|
||||
case ControlState::EquipmentOffline:
|
||||
case ControlState::AttemptOnline:
|
||||
case ControlState::HostOffline:
|
||||
// Idempotent: already offline from host's point of view.
|
||||
return OfflineAck::Accept;
|
||||
}
|
||||
return OfflineAck::Accept;
|
||||
}
|
||||
|
||||
} // namespace secsgem::gem
|
||||
@@ -0,0 +1,339 @@
|
||||
#include "secsgem/gem/data_model.hpp"
|
||||
|
||||
#include <array>
|
||||
#include <chrono>
|
||||
#include <cstdio>
|
||||
#include <ctime>
|
||||
|
||||
namespace secsgem::gem {
|
||||
|
||||
// ---- SVIDs ---------------------------------------------------------------
|
||||
|
||||
void EquipmentDataModel::add_status_variable(StatusVariable sv) {
|
||||
const uint32_t id = sv.id;
|
||||
svids_.insert_or_assign(id, std::move(sv));
|
||||
}
|
||||
std::optional<StatusVariable> EquipmentDataModel::status_variable(uint32_t id) const {
|
||||
auto it = svids_.find(id);
|
||||
if (it == svids_.end()) return std::nullopt;
|
||||
return it->second;
|
||||
}
|
||||
std::vector<StatusVariable> EquipmentDataModel::all_status_variables() const {
|
||||
std::vector<StatusVariable> out;
|
||||
out.reserve(svids_.size());
|
||||
for (const auto& [_, sv] : svids_) out.push_back(sv);
|
||||
return out;
|
||||
}
|
||||
void EquipmentDataModel::set_status_value(uint32_t id, s2::Item value) {
|
||||
auto it = svids_.find(id);
|
||||
if (it != svids_.end()) it->second.value = std::move(value);
|
||||
}
|
||||
|
||||
// ---- DVIDs ---------------------------------------------------------------
|
||||
|
||||
void EquipmentDataModel::add_data_variable(DataVariable dv) {
|
||||
const uint32_t id = dv.id;
|
||||
dvids_.insert_or_assign(id, std::move(dv));
|
||||
}
|
||||
std::optional<DataVariable> EquipmentDataModel::data_variable(uint32_t id) const {
|
||||
auto it = dvids_.find(id);
|
||||
if (it == dvids_.end()) return std::nullopt;
|
||||
return it->second;
|
||||
}
|
||||
std::vector<DataVariable> EquipmentDataModel::all_data_variables() const {
|
||||
std::vector<DataVariable> out;
|
||||
out.reserve(dvids_.size());
|
||||
for (const auto& [_, dv] : dvids_) out.push_back(dv);
|
||||
return out;
|
||||
}
|
||||
void EquipmentDataModel::set_data_value(uint32_t id, s2::Item value) {
|
||||
auto it = dvids_.find(id);
|
||||
if (it != dvids_.end()) it->second.value = std::move(value);
|
||||
}
|
||||
|
||||
std::optional<s2::Item> EquipmentDataModel::vid_value(uint32_t vid) const {
|
||||
if (auto it = svids_.find(vid); it != svids_.end()) return it->second.value;
|
||||
if (auto it = dvids_.find(vid); it != dvids_.end()) return it->second.value;
|
||||
return std::nullopt;
|
||||
}
|
||||
bool EquipmentDataModel::vid_exists(uint32_t vid) const {
|
||||
return svids_.count(vid) || dvids_.count(vid);
|
||||
}
|
||||
|
||||
// ---- ECIDs ---------------------------------------------------------------
|
||||
|
||||
void EquipmentDataModel::add_equipment_constant(EquipmentConstant ec) {
|
||||
const uint32_t id = ec.id;
|
||||
ecids_.insert_or_assign(id, std::move(ec));
|
||||
}
|
||||
std::optional<EquipmentConstant> EquipmentDataModel::equipment_constant(uint32_t id) const {
|
||||
auto it = ecids_.find(id);
|
||||
if (it == ecids_.end()) return std::nullopt;
|
||||
return it->second;
|
||||
}
|
||||
std::vector<EquipmentConstant> EquipmentDataModel::all_equipment_constants() const {
|
||||
std::vector<EquipmentConstant> out;
|
||||
out.reserve(ecids_.size());
|
||||
for (const auto& [_, ec] : ecids_) out.push_back(ec);
|
||||
return out;
|
||||
}
|
||||
EquipmentAck EquipmentDataModel::set_equipment_constant_value(uint32_t id, s2::Item value) {
|
||||
auto it = ecids_.find(id);
|
||||
if (it == ecids_.end()) return EquipmentAck::Denied_UnknownEcid;
|
||||
it->second.value = std::move(value);
|
||||
return EquipmentAck::Accept;
|
||||
}
|
||||
|
||||
// ---- Clock ---------------------------------------------------------------
|
||||
|
||||
std::string EquipmentDataModel::current_time_string() const {
|
||||
using namespace std::chrono;
|
||||
const auto now = system_clock::now() + seconds(time_offset_seconds_);
|
||||
const auto t = system_clock::to_time_t(now);
|
||||
const auto ms = duration_cast<milliseconds>(now.time_since_epoch()) % 1000;
|
||||
|
||||
std::tm tm{};
|
||||
gmtime_r(&t, &tm);
|
||||
|
||||
std::array<char, 64> buf{};
|
||||
std::snprintf(buf.data(), buf.size(), "%04d%02d%02d%02d%02d%02d%02d",
|
||||
tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
|
||||
tm.tm_hour, tm.tm_min, tm.tm_sec,
|
||||
static_cast<int>(ms.count() / 10));
|
||||
return std::string(buf.data());
|
||||
}
|
||||
|
||||
namespace {
|
||||
bool parse_uint(const char* p, std::size_t n, int& out) {
|
||||
int v = 0;
|
||||
for (std::size_t i = 0; i < n; ++i) {
|
||||
if (p[i] < '0' || p[i] > '9') return false;
|
||||
v = v * 10 + (p[i] - '0');
|
||||
}
|
||||
out = v;
|
||||
return true;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
TimeAck EquipmentDataModel::set_time_string(const std::string& s) {
|
||||
if (s.size() != 14 && s.size() != 16) return TimeAck::Error;
|
||||
int y, mo, d, h, mi, se;
|
||||
if (!parse_uint(s.data() + 0, 4, y) ||
|
||||
!parse_uint(s.data() + 4, 2, mo) ||
|
||||
!parse_uint(s.data() + 6, 2, d) ||
|
||||
!parse_uint(s.data() + 8, 2, h) ||
|
||||
!parse_uint(s.data() + 10, 2, mi) ||
|
||||
!parse_uint(s.data() + 12, 2, se)) {
|
||||
return TimeAck::Error;
|
||||
}
|
||||
std::tm tm{};
|
||||
tm.tm_year = y - 1900;
|
||||
tm.tm_mon = mo - 1;
|
||||
tm.tm_mday = d;
|
||||
tm.tm_hour = h;
|
||||
tm.tm_min = mi;
|
||||
tm.tm_sec = se;
|
||||
const std::time_t target = timegm(&tm);
|
||||
if (target == static_cast<std::time_t>(-1)) return TimeAck::Error;
|
||||
const std::time_t now = std::time(nullptr);
|
||||
time_offset_seconds_ = static_cast<std::int64_t>(target - now);
|
||||
return TimeAck::Accept;
|
||||
}
|
||||
|
||||
// ---- Host commands -------------------------------------------------------
|
||||
|
||||
void EquipmentDataModel::register_command(const std::string& rcmd, HostCommandHandler handler) {
|
||||
commands_.insert_or_assign(rcmd, std::move(handler));
|
||||
}
|
||||
bool EquipmentDataModel::has_command(const std::string& rcmd) const {
|
||||
return commands_.find(rcmd) != commands_.end();
|
||||
}
|
||||
HostCmdAck EquipmentDataModel::dispatch_command(
|
||||
const std::string& rcmd, const std::vector<CommandParam>& params) const {
|
||||
auto it = commands_.find(rcmd);
|
||||
if (it == commands_.end()) return HostCmdAck::InvalidCommand;
|
||||
return it->second(params);
|
||||
}
|
||||
|
||||
// ---- Collection events ---------------------------------------------------
|
||||
|
||||
void EquipmentDataModel::register_event(CollectionEvent ce) {
|
||||
const uint32_t id = ce.id;
|
||||
ceids_.insert_or_assign(id, std::move(ce));
|
||||
}
|
||||
|
||||
bool EquipmentDataModel::has_event(uint32_t ceid) const { return ceids_.count(ceid); }
|
||||
|
||||
std::vector<CollectionEvent> EquipmentDataModel::all_events() const {
|
||||
std::vector<CollectionEvent> out;
|
||||
out.reserve(ceids_.size());
|
||||
for (const auto& [_, e] : ceids_) out.push_back(e);
|
||||
return out;
|
||||
}
|
||||
|
||||
DefineReportAck EquipmentDataModel::define_reports(
|
||||
const std::vector<std::pair<uint32_t, std::vector<uint32_t>>>& reports) {
|
||||
// Empty outer list deletes all reports (and links).
|
||||
if (reports.empty()) {
|
||||
reports_.clear();
|
||||
ce_links_.clear();
|
||||
return DefineReportAck::Accept;
|
||||
}
|
||||
|
||||
// Validate first; commit only on full success.
|
||||
for (const auto& [rptid, vids] : reports) {
|
||||
if (vids.empty()) continue; // delete-report row is always valid
|
||||
for (auto v : vids)
|
||||
if (!vid_exists(v)) return DefineReportAck::InvalidVid;
|
||||
}
|
||||
|
||||
for (const auto& [rptid, vids] : reports) {
|
||||
if (vids.empty()) {
|
||||
reports_.erase(rptid);
|
||||
// Drop the RPTID from any links.
|
||||
for (auto& [ceid, rpts] : ce_links_) {
|
||||
rpts.erase(std::remove(rpts.begin(), rpts.end(), rptid), rpts.end());
|
||||
}
|
||||
} else {
|
||||
reports_.insert_or_assign(rptid, Report{rptid, vids});
|
||||
}
|
||||
}
|
||||
return DefineReportAck::Accept;
|
||||
}
|
||||
|
||||
LinkEventAck EquipmentDataModel::link_event_reports(
|
||||
const std::vector<std::pair<uint32_t, std::vector<uint32_t>>>& links) {
|
||||
if (links.empty()) {
|
||||
ce_links_.clear();
|
||||
return LinkEventAck::Accept;
|
||||
}
|
||||
|
||||
for (const auto& [ceid, rpts] : links) {
|
||||
if (!has_event(ceid)) return LinkEventAck::UnknownCeid;
|
||||
for (auto r : rpts)
|
||||
if (!reports_.count(r)) return LinkEventAck::UnknownRptid;
|
||||
}
|
||||
|
||||
for (const auto& [ceid, rpts] : links) {
|
||||
if (rpts.empty()) {
|
||||
ce_links_.erase(ceid);
|
||||
} else {
|
||||
ce_links_[ceid] = rpts;
|
||||
}
|
||||
}
|
||||
return LinkEventAck::Accept;
|
||||
}
|
||||
|
||||
EnableEventAck EquipmentDataModel::enable_events(bool enable,
|
||||
const std::vector<uint32_t>& ceids) {
|
||||
if (ceids.empty()) {
|
||||
if (enable) {
|
||||
for (const auto& [id, _] : ceids_) events_enabled_.insert(id);
|
||||
} else {
|
||||
events_enabled_.clear();
|
||||
}
|
||||
return EnableEventAck::Accept;
|
||||
}
|
||||
for (auto id : ceids)
|
||||
if (!has_event(id)) return EnableEventAck::UnknownCeid;
|
||||
for (auto id : ceids) {
|
||||
if (enable) events_enabled_.insert(id);
|
||||
else events_enabled_.erase(id);
|
||||
}
|
||||
return EnableEventAck::Accept;
|
||||
}
|
||||
|
||||
bool EquipmentDataModel::is_event_enabled(uint32_t ceid) const {
|
||||
return events_enabled_.count(ceid) > 0;
|
||||
}
|
||||
|
||||
std::vector<ReportData> EquipmentDataModel::compose_reports_for(uint32_t ceid) const {
|
||||
std::vector<ReportData> out;
|
||||
auto it = ce_links_.find(ceid);
|
||||
if (it == ce_links_.end()) return out;
|
||||
for (auto rptid : it->second) {
|
||||
auto rit = reports_.find(rptid);
|
||||
if (rit == reports_.end()) continue;
|
||||
ReportData rd{rptid, {}};
|
||||
for (auto vid : rit->second.vids) {
|
||||
auto v = vid_value(vid);
|
||||
rd.values.push_back(v ? *v : s2::Item::list({}));
|
||||
}
|
||||
out.push_back(std::move(rd));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
std::vector<Report> EquipmentDataModel::all_reports() const {
|
||||
std::vector<Report> out;
|
||||
out.reserve(reports_.size());
|
||||
for (const auto& [_, r] : reports_) out.push_back(r);
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---- Alarms --------------------------------------------------------------
|
||||
|
||||
void EquipmentDataModel::add_alarm(Alarm a) {
|
||||
const uint32_t id = a.id;
|
||||
alarms_.insert_or_assign(id, std::move(a));
|
||||
}
|
||||
std::optional<Alarm> EquipmentDataModel::alarm(uint32_t alid) const {
|
||||
auto it = alarms_.find(alid);
|
||||
if (it == alarms_.end()) return std::nullopt;
|
||||
return it->second;
|
||||
}
|
||||
std::vector<Alarm> EquipmentDataModel::all_alarms() const {
|
||||
std::vector<Alarm> out;
|
||||
out.reserve(alarms_.size());
|
||||
for (const auto& [_, a] : alarms_) out.push_back(a);
|
||||
return out;
|
||||
}
|
||||
AlarmAck EquipmentDataModel::set_alarm_enabled(uint32_t alid, bool enable) {
|
||||
if (!alarms_.count(alid)) return AlarmAck::Error;
|
||||
if (enable) alarms_enabled_.insert(alid);
|
||||
else alarms_enabled_.erase(alid);
|
||||
return AlarmAck::Accept;
|
||||
}
|
||||
bool EquipmentDataModel::alarm_enabled(uint32_t alid) const {
|
||||
return alarms_enabled_.count(alid) > 0;
|
||||
}
|
||||
|
||||
std::optional<uint8_t> EquipmentDataModel::alarm_set(uint32_t alid) {
|
||||
auto it = alarms_.find(alid);
|
||||
if (it == alarms_.end()) return std::nullopt;
|
||||
alarms_active_.insert(alid);
|
||||
return static_cast<uint8_t>((it->second.severity_category & 0x7F) | 0x80);
|
||||
}
|
||||
std::optional<uint8_t> EquipmentDataModel::alarm_clear(uint32_t alid) {
|
||||
auto it = alarms_.find(alid);
|
||||
if (it == alarms_.end()) return std::nullopt;
|
||||
alarms_active_.erase(alid);
|
||||
return static_cast<uint8_t>(it->second.severity_category & 0x7F);
|
||||
}
|
||||
bool EquipmentDataModel::alarm_active(uint32_t alid) const {
|
||||
return alarms_active_.count(alid) > 0;
|
||||
}
|
||||
|
||||
// ---- Process programs ----------------------------------------------------
|
||||
|
||||
void EquipmentDataModel::add_process_program(std::string ppid, std::string ppbody) {
|
||||
process_programs_.insert_or_assign(std::move(ppid), std::move(ppbody));
|
||||
}
|
||||
std::optional<std::string> EquipmentDataModel::process_program(const std::string& ppid) const {
|
||||
auto it = process_programs_.find(ppid);
|
||||
if (it == process_programs_.end()) return std::nullopt;
|
||||
return it->second;
|
||||
}
|
||||
std::vector<std::string> EquipmentDataModel::process_program_list() const {
|
||||
std::vector<std::string> out;
|
||||
out.reserve(process_programs_.size());
|
||||
for (const auto& [k, _] : process_programs_) out.push_back(k);
|
||||
return out;
|
||||
}
|
||||
ProcessProgramAck EquipmentDataModel::delete_process_program(const std::string& ppid) {
|
||||
if (!process_programs_.count(ppid)) return ProcessProgramAck::PpidNotFound;
|
||||
process_programs_.erase(ppid);
|
||||
return ProcessProgramAck::Accept;
|
||||
}
|
||||
|
||||
} // namespace secsgem::gem
|
||||
@@ -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
|
||||
@@ -0,0 +1,32 @@
|
||||
#include "secsgem/hsms/frame.hpp"
|
||||
|
||||
namespace secsgem::hsms {
|
||||
|
||||
std::vector<uint8_t> Frame::encode() const {
|
||||
const std::size_t payload_len = kHeaderSize + body.size();
|
||||
|
||||
std::vector<uint8_t> out;
|
||||
out.reserve(kLengthPrefixSize + payload_len);
|
||||
|
||||
out.push_back(static_cast<uint8_t>(payload_len >> 24));
|
||||
out.push_back(static_cast<uint8_t>(payload_len >> 16));
|
||||
out.push_back(static_cast<uint8_t>(payload_len >> 8));
|
||||
out.push_back(static_cast<uint8_t>(payload_len & 0xFF));
|
||||
|
||||
const auto hdr = header.encode();
|
||||
out.insert(out.end(), hdr.begin(), hdr.end());
|
||||
out.insert(out.end(), body.begin(), body.end());
|
||||
return out;
|
||||
}
|
||||
|
||||
Frame Frame::decode(const uint8_t* payload, std::size_t len) {
|
||||
if (len < kHeaderSize)
|
||||
throw FrameError("HSMS payload shorter than the 10-byte header");
|
||||
|
||||
Frame f;
|
||||
f.header = Header::decode(payload);
|
||||
f.body.assign(payload + kHeaderSize, payload + len);
|
||||
return f;
|
||||
}
|
||||
|
||||
} // namespace secsgem::hsms
|
||||
@@ -0,0 +1,59 @@
|
||||
#include "secsgem/hsms/header.hpp"
|
||||
|
||||
namespace secsgem::hsms {
|
||||
|
||||
const char* stype_name(SType s) {
|
||||
switch (s) {
|
||||
case SType::Data: return "Data";
|
||||
case SType::SelectReq: return "Select.req";
|
||||
case SType::SelectRsp: return "Select.rsp";
|
||||
case SType::DeselectReq: return "Deselect.req";
|
||||
case SType::DeselectRsp: return "Deselect.rsp";
|
||||
case SType::LinktestReq: return "Linktest.req";
|
||||
case SType::LinktestRsp: return "Linktest.rsp";
|
||||
case SType::RejectReq: return "Reject.req";
|
||||
case SType::SeparateReq: return "Separate.req";
|
||||
}
|
||||
return "?";
|
||||
}
|
||||
|
||||
std::array<uint8_t, 10> Header::encode() const {
|
||||
std::array<uint8_t, 10> b{};
|
||||
b[0] = static_cast<uint8_t>(session_id >> 8);
|
||||
b[1] = static_cast<uint8_t>(session_id & 0xFF);
|
||||
b[2] = byte2;
|
||||
b[3] = byte3;
|
||||
b[4] = ptype;
|
||||
b[5] = static_cast<uint8_t>(stype);
|
||||
b[6] = static_cast<uint8_t>(system_bytes >> 24);
|
||||
b[7] = static_cast<uint8_t>(system_bytes >> 16);
|
||||
b[8] = static_cast<uint8_t>(system_bytes >> 8);
|
||||
b[9] = static_cast<uint8_t>(system_bytes & 0xFF);
|
||||
return b;
|
||||
}
|
||||
|
||||
Header Header::decode(const uint8_t* d) {
|
||||
Header h;
|
||||
h.session_id = static_cast<uint16_t>((d[0] << 8) | d[1]);
|
||||
h.byte2 = d[2];
|
||||
h.byte3 = d[3];
|
||||
h.ptype = d[4];
|
||||
h.stype = static_cast<SType>(d[5]);
|
||||
h.system_bytes = (static_cast<uint32_t>(d[6]) << 24) |
|
||||
(static_cast<uint32_t>(d[7]) << 16) |
|
||||
(static_cast<uint32_t>(d[8]) << 8) |
|
||||
static_cast<uint32_t>(d[9]);
|
||||
return h;
|
||||
}
|
||||
|
||||
std::string Header::describe() const {
|
||||
std::string out = stype_name(stype);
|
||||
if (stype == SType::Data) {
|
||||
out = "S" + std::to_string(stream()) + "F" + std::to_string(function());
|
||||
if (w_bit()) out += " W";
|
||||
}
|
||||
out += " (sys=" + std::to_string(system_bytes) + ")";
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace secsgem::hsms
|
||||
@@ -0,0 +1,225 @@
|
||||
#include "secsgem/secs2/codec.hpp"
|
||||
|
||||
#include <bit>
|
||||
#include <cstdio>
|
||||
#include <type_traits>
|
||||
|
||||
namespace secsgem::secs2 {
|
||||
namespace {
|
||||
|
||||
template <typename T>
|
||||
void put_scalar_be(std::vector<uint8_t>& out, T value) {
|
||||
if constexpr (std::is_same_v<T, float>) {
|
||||
uint32_t bits = std::bit_cast<uint32_t>(value);
|
||||
for (int i = 3; i >= 0; --i) out.push_back(static_cast<uint8_t>(bits >> (8 * i)));
|
||||
} else if constexpr (std::is_same_v<T, double>) {
|
||||
uint64_t bits = std::bit_cast<uint64_t>(value);
|
||||
for (int i = 7; i >= 0; --i) out.push_back(static_cast<uint8_t>(bits >> (8 * i)));
|
||||
} else {
|
||||
using U = std::make_unsigned_t<T>;
|
||||
U u = static_cast<U>(value);
|
||||
for (int i = static_cast<int>(sizeof(T)) - 1; i >= 0; --i)
|
||||
out.push_back(static_cast<uint8_t>(u >> (8 * i)));
|
||||
}
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
T get_scalar_be(const uint8_t* p) {
|
||||
if constexpr (std::is_same_v<T, float>) {
|
||||
uint32_t bits = 0;
|
||||
for (int i = 0; i < 4; ++i) bits = (bits << 8) | p[i];
|
||||
return std::bit_cast<float>(bits);
|
||||
} else if constexpr (std::is_same_v<T, double>) {
|
||||
uint64_t bits = 0;
|
||||
for (int i = 0; i < 8; ++i) bits = (bits << 8) | p[i];
|
||||
return std::bit_cast<double>(bits);
|
||||
} else {
|
||||
using U = std::make_unsigned_t<T>;
|
||||
U u = 0;
|
||||
for (std::size_t i = 0; i < sizeof(T); ++i) u = static_cast<U>((u << 8) | p[i]);
|
||||
return static_cast<T>(u);
|
||||
}
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
std::vector<T> read_array(const uint8_t* p, std::size_t bytes) {
|
||||
if (bytes % sizeof(T) != 0)
|
||||
throw CodecError("item byte length is not a multiple of the element size");
|
||||
const std::size_t n = bytes / sizeof(T);
|
||||
std::vector<T> out;
|
||||
out.reserve(n);
|
||||
for (std::size_t i = 0; i < n; ++i) out.push_back(get_scalar_be<T>(p + i * sizeof(T)));
|
||||
return out;
|
||||
}
|
||||
|
||||
void write_header(std::vector<uint8_t>& out, Format fmt, std::size_t length) {
|
||||
std::size_t nlen;
|
||||
if (length <= 0xFF) nlen = 1;
|
||||
else if (length <= 0xFFFF) nlen = 2;
|
||||
else if (length <= 0xFFFFFF) nlen = 3;
|
||||
else throw CodecError("item length exceeds 3-byte maximum");
|
||||
|
||||
out.push_back(static_cast<uint8_t>((static_cast<uint8_t>(fmt) << 2) | nlen));
|
||||
for (std::size_t i = 0; i < nlen; ++i) {
|
||||
const std::size_t shift = 8 * (nlen - 1 - i);
|
||||
out.push_back(static_cast<uint8_t>((length >> shift) & 0xFF));
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void encode_into(const Item& item, std::vector<uint8_t>& out) {
|
||||
const Format fmt = item.format();
|
||||
|
||||
if (fmt == Format::List) {
|
||||
const auto& children = item.as_list();
|
||||
write_header(out, fmt, children.size());
|
||||
for (const auto& child : children) encode_into(child, out);
|
||||
return;
|
||||
}
|
||||
|
||||
std::visit(
|
||||
[&](const auto& v) {
|
||||
using V = std::decay_t<decltype(v)>;
|
||||
if constexpr (std::is_same_v<V, Item::List>) {
|
||||
// unreachable: lists handled above
|
||||
} else if constexpr (std::is_same_v<V, std::string>) {
|
||||
write_header(out, fmt, v.size());
|
||||
out.insert(out.end(), v.begin(), v.end());
|
||||
} else {
|
||||
using Elem = typename V::value_type;
|
||||
write_header(out, fmt, v.size() * sizeof(Elem));
|
||||
for (auto e : v) put_scalar_be(out, e);
|
||||
}
|
||||
},
|
||||
item.storage());
|
||||
}
|
||||
|
||||
std::vector<uint8_t> encode(const Item& item) {
|
||||
std::vector<uint8_t> out;
|
||||
encode_into(item, out);
|
||||
return out;
|
||||
}
|
||||
|
||||
Item decode_at(const uint8_t* data, std::size_t len, std::size_t& pos) {
|
||||
if (pos >= len) throw CodecError("unexpected end of input reading format byte");
|
||||
|
||||
const uint8_t format_byte = data[pos++];
|
||||
const uint8_t nlen = format_byte & 0x03;
|
||||
const Format fmt = static_cast<Format>((format_byte >> 2) & 0x3F);
|
||||
|
||||
if (nlen == 0) throw CodecError("invalid item: zero length bytes");
|
||||
if (pos + nlen > len) throw CodecError("unexpected end of input reading length bytes");
|
||||
|
||||
std::size_t length = 0;
|
||||
for (uint8_t i = 0; i < nlen; ++i) length = (length << 8) | data[pos++];
|
||||
|
||||
if (fmt == Format::List) {
|
||||
Item::List items;
|
||||
items.reserve(length);
|
||||
for (std::size_t i = 0; i < length; ++i) items.push_back(decode_at(data, len, pos));
|
||||
return Item::list(std::move(items));
|
||||
}
|
||||
|
||||
if (pos + length > len) throw CodecError("unexpected end of input reading item data");
|
||||
const uint8_t* p = data + pos;
|
||||
pos += length;
|
||||
|
||||
switch (fmt) {
|
||||
case Format::ASCII:
|
||||
return Item::ascii(std::string(reinterpret_cast<const char*>(p), length));
|
||||
case Format::Binary:
|
||||
return Item::binary(std::vector<uint8_t>(p, p + length));
|
||||
case Format::Boolean:
|
||||
return Item::boolean(std::vector<uint8_t>(p, p + length));
|
||||
case Format::U1:
|
||||
return Item::u1(std::vector<uint8_t>(p, p + length));
|
||||
case Format::I1:
|
||||
return Item::i1(read_array<int8_t>(p, length));
|
||||
case Format::U2:
|
||||
return Item::u2(read_array<uint16_t>(p, length));
|
||||
case Format::I2:
|
||||
return Item::i2(read_array<int16_t>(p, length));
|
||||
case Format::U4:
|
||||
return Item::u4(read_array<uint32_t>(p, length));
|
||||
case Format::I4:
|
||||
return Item::i4(read_array<int32_t>(p, length));
|
||||
case Format::F4:
|
||||
return Item::f4(read_array<float>(p, length));
|
||||
case Format::U8:
|
||||
return Item::u8(read_array<uint64_t>(p, length));
|
||||
case Format::I8:
|
||||
return Item::i8(read_array<int64_t>(p, length));
|
||||
case Format::F8:
|
||||
return Item::f8(read_array<double>(p, length));
|
||||
case Format::List:
|
||||
break; // handled above
|
||||
}
|
||||
throw CodecError("unknown SECS-II format code");
|
||||
}
|
||||
|
||||
Item decode(const std::vector<uint8_t>& bytes) {
|
||||
std::size_t pos = 0;
|
||||
Item item = decode_at(bytes.data(), bytes.size(), pos);
|
||||
if (pos != bytes.size()) throw CodecError("trailing bytes after decoded item");
|
||||
return item;
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
void sml_into(const Item& item, std::string& out) {
|
||||
const Format fmt = item.format();
|
||||
out += '<';
|
||||
out += format_name(fmt);
|
||||
|
||||
if (fmt == Format::List) {
|
||||
out += " [" + std::to_string(item.size()) + "]";
|
||||
for (const auto& child : item.as_list()) {
|
||||
out += ' ';
|
||||
sml_into(child, out);
|
||||
}
|
||||
out += " >";
|
||||
return;
|
||||
}
|
||||
|
||||
std::visit(
|
||||
[&](const auto& v) {
|
||||
using V = std::decay_t<decltype(v)>;
|
||||
if constexpr (std::is_same_v<V, Item::List>) {
|
||||
// unreachable
|
||||
} else if constexpr (std::is_same_v<V, std::string>) {
|
||||
out += " \"" + v + "\"";
|
||||
} else {
|
||||
using Elem = typename V::value_type;
|
||||
for (auto e : v) {
|
||||
out += ' ';
|
||||
if constexpr (std::is_same_v<Elem, uint8_t>) {
|
||||
if (fmt == Format::Boolean) {
|
||||
out += (e ? "T" : "F");
|
||||
} else {
|
||||
char buf[5];
|
||||
std::snprintf(buf, sizeof(buf), "0x%02X", e);
|
||||
out += buf;
|
||||
}
|
||||
} else if constexpr (std::is_floating_point_v<Elem>) {
|
||||
out += std::to_string(e);
|
||||
} else {
|
||||
out += std::to_string(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
item.storage());
|
||||
|
||||
out += " >";
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
std::string to_sml(const Item& item) {
|
||||
std::string out;
|
||||
sml_into(item, out);
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace secsgem::secs2
|
||||
@@ -0,0 +1,49 @@
|
||||
#include "secsgem/secs2/item.hpp"
|
||||
|
||||
namespace secsgem::secs2 {
|
||||
|
||||
const char* format_name(Format f) {
|
||||
switch (f) {
|
||||
case Format::List: return "L";
|
||||
case Format::Binary: return "B";
|
||||
case Format::Boolean: return "BOOLEAN";
|
||||
case Format::ASCII: return "A";
|
||||
case Format::I8: return "I8";
|
||||
case Format::I1: return "I1";
|
||||
case Format::I2: return "I2";
|
||||
case Format::I4: return "I4";
|
||||
case Format::F8: return "F8";
|
||||
case Format::F4: return "F4";
|
||||
case Format::U8: return "U8";
|
||||
case Format::U1: return "U1";
|
||||
case Format::U2: return "U2";
|
||||
case Format::U4: return "U4";
|
||||
}
|
||||
return "?";
|
||||
}
|
||||
|
||||
std::size_t element_size(Format f) {
|
||||
switch (f) {
|
||||
case Format::List: return 0;
|
||||
case Format::ASCII:
|
||||
case Format::Binary:
|
||||
case Format::Boolean:
|
||||
case Format::U1:
|
||||
case Format::I1: return 1;
|
||||
case Format::U2:
|
||||
case Format::I2: return 2;
|
||||
case Format::U4:
|
||||
case Format::I4:
|
||||
case Format::F4: return 4;
|
||||
case Format::U8:
|
||||
case Format::I8:
|
||||
case Format::F8: return 8;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
std::size_t Item::size() const {
|
||||
return std::visit([](const auto& v) { return v.size(); }, data_);
|
||||
}
|
||||
|
||||
} // namespace secsgem::secs2
|
||||
@@ -0,0 +1,30 @@
|
||||
#include "secsgem/secs2/message.hpp"
|
||||
|
||||
#include "secsgem/secs2/codec.hpp"
|
||||
|
||||
namespace secsgem::secs2 {
|
||||
|
||||
std::vector<uint8_t> Message::encode_body() const {
|
||||
if (!body) return {};
|
||||
return encode(*body);
|
||||
}
|
||||
|
||||
Message Message::from_body(uint8_t stream, uint8_t function, bool reply_expected,
|
||||
const std::vector<uint8_t>& body_bytes) {
|
||||
Message m(stream, function, reply_expected);
|
||||
if (!body_bytes.empty()) m.body = decode(body_bytes);
|
||||
return m;
|
||||
}
|
||||
|
||||
std::string Message::sml() const {
|
||||
std::string out = "S" + std::to_string(stream) + "F" + std::to_string(function);
|
||||
if (reply_expected) out += " W";
|
||||
if (body) {
|
||||
out += "\n ";
|
||||
out += to_sml(*body);
|
||||
}
|
||||
out += " .";
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace secsgem::secs2
|
||||
Reference in New Issue
Block a user