Files
STM32F4-Base/App/protocol/iec104/iec104_core.c
T
wandering1 2e9272cc8a feat(iec104): 在模拟器跑通共享协议核心与标准DTU点表
引入成熟 IEC 60870-5-104 子站的只读子集(App/protocol/iec60870,28 个源文件
按原字节复制,UPSTREAM.sha256 记录来源,兼容补丁保留全部断言与容量),在其上
装配单属主共享核心(Start/Poll/Stop/Get_Status),并把标准 DTU 演示点表全量
接入为唯一真源。

- iec104_core:threadless 推进,poll 零等待,通知/交互/COV 扫描全部有界;
  生命周期区分失败启动待重试、重复启动拒绝、断线保固化 RAM。
- iec104_dtu_table / iec104_source:标准 DTU 全点表注册,无数据源的点读 0,
  遥控只做模拟状态可读回,不触碰实际出口。
- iec104_sim:仅窗口与独立服务模式起真实 TCP,无头黄金模式保持确定性假统计。
- test/host/iec104_dtu:独立真实 TCP 11 项、传输层 10 项、生命周期与借用负例。

验证:lvgl_sim 真实 TCP 11/11、传输 10/10,UI 像素回归未回退;AC5 单 TU
编译 0 错误 0 诊断。板端尚未切换:完整库闭包 RAM 超 92% 门禁净增预算 25730B,
结论为停止转实施,记录在 IEC104_MCU最小可行性验证.md。旧实现与 board 服务
保持原样,未提交 MDK 工程改动,未烧板。
2026-11-17 20:48:00 +08:00

698 lines
34 KiB
C

/* 模块名称:共享 IEC104 产品业务装配。
* Product assembly of the imported IEC60870-Slave state machines.
* No protocol parser, socket implementation or example main is duplicated here.
*/
#include "iec104_core.h"
#include "iec104_source.h"
#include "IEC104_Startup.h"
#include "IEC104_GeneralInterrogation.h"
#include "IEC104_CounterInterrogation.h"
#include "IEC104_Read.h"
#include "IEC104_PeriodicScan.h"
#include "IEC104_Net.h"
#include <string.h>
#define CORE_EVENT_BUDGET 16U
#define CORE_DATA_BUDGET 20U
#define CORE_WORK_BUDGET 4U
#define CORE_FEEDBACK_CAPACITY 8U
#define CORE_SCAN_CAPACITY 30U
#define CORE_MONITOR_CAPACITY 105U
typedef struct {
uint32_t value;
uint8_t quality;
bool initialized;
} core_previous_t;
typedef struct {
IEC104_Interrogation_t *module;
IEC104_InterrogationEvent_t event;
size_t cursor;
uint64_t request_id;
bool pending;
bool counter;
} core_interrogation_t;
typedef union {
IEC60870_SinglePointWithCP56Time2a_t single;
IEC60870_DoublePointWithCP56Time2a_t double_point;
} core_timestamped_t;
typedef struct {
IEC104_Slave_t *slave;
IEC104_Station_t station;
IEC104_Startup_t startup;
IEC104_SystemCommand_t *system;
IEC104_Command_t *command;
IEC104_ClockSynchronization_t *clock;
IEC104_RemoteParameter_t *remote;
IEC104_Parameter_t *parameter;
IEC104_Read_t *read;
IEC104_PeriodicScan_t *scan;
IEC104_Spontaneous_t *spontaneous;
IEC104_SpontaneousChange_t change;
IEC104_SpontaneousPublishInfo_t publication;
core_previous_t previous[CORE_MONITOR_CAPACITY];
size_t sample_cursor;
iec104_source_stats_t source_stats;
IEC60870_CP56Time2a_t sample_time;
core_timestamped_t timestamped;
core_interrogation_t gi, ci;
IEC104_SlaveEvent_t event;
IEC104_CommandEvent_t command_event, next_command;
IEC104_CommandActionResult_t action_result;
IEC104_SystemCommandStatus_t system_status;
IEC104_TcpServerStatus_t transport_status;
IEC104_TcpError_t error;
IEC60870_Asdu_t batch;
uint8_t bytes[IEC104_MAX_ASDU_LEN];
iec104_source_object_t object;
IEC104_PeriodicScanPoint_t scan_points[CORE_SCAN_CAPACITY];
uint32_t feedback[CORE_FEEDBACK_CAPACITY];
size_t feedback_count, feedback_index;
uint16_t ca;
uint8_t command_step;
bool command_pending, reject_pending, closing;
iec104_core_status_t status;
} core_t;
static core_t s_core;
/* Init configuration storage is static: never put these on a 640-word task stack. */
static IEC104_SlaveConfig_t s_transport_config;
static IEC104_SystemCommandConfig_t s_system_config;
static IEC104_InterrogationConfig_t s_gi_config, s_ci_config;
static IEC104_CommandConfig_t s_command_config;
static IEC104_ClockSynchronizationConfig_t s_clock_config;
static IEC104_RemoteParameterConfig_t s_remote_config;
static IEC104_ParameterConfig_t s_parameter_config;
static IEC104_ReadConfig_t s_read_config;
static IEC104_PeriodicScanConfig_t s_scan_config;
static IEC104_PeriodicScanGroupConfig_t s_scan_group;
static IEC104_SpontaneousConfig_t s_spontaneous_config;
/* 函数功能:将累计观测计数饱和递增一次。 */
static void increment(uint32_t *value)
{
if (*value != UINT32_MAX) { ++*value; }
}
/* 函数功能:保存最近一次服务失败诊断。 */
static int fail(void)
{
s_core.status.last_error = s_core.error.result != IEC104_TCP_OK ?
(int)s_core.error.result : (int)IEC104_TCP_INTERNAL_ERROR;
s_core.status.last_stage = (int)s_core.error.stage;
s_core.status.native_error = s_core.error.socket_error;
return -1;
}
/* 函数功能:以本站及请求身份建立零对象肯定数据帧。 */
static bool new_batch(uint8_t cause, uint8_t oa, bool test)
{
IEC60870_AsduHeader_t header;
memset(&header, 0, sizeof(header));
header.common_address = s_core.ca;
header.cause_of_transmission = cause;
header.originator_address = oa;
header.is_test = test ? 1U : 0U;
/* P/N stays zero: success data is never encoded as a negative confirm. */
return IEC60870_Asdu_Create(&s_core.batch,
IEC104_Slave_Get_Application_Layer_Parameters(s_core.slave),
s_core.bytes, sizeof(s_core.bytes), &header, 0) == IEC60870_ASDU_OK;
}
static IEC104_ReadLookupResult_t read_point(void *context,
const IEC104_ReadRequest_t *request, IEC60870_Asdu_t *response)
{
(void)context;
if (!iec104_source_find(request->ioa, &s_core.object)) { return IEC104_READ_LOOKUP_UNKNOWN; }
/* Counters and parameter objects are not in Type102's monitor whitelist. */
if (s_core.object.object.type_id == 15U || s_core.object.object.type_id == 37U ||
s_core.object.object.type_id >= 100U) { return IEC104_READ_LOOKUP_UNKNOWN; }
if (s_core.object.object.type_id == 1U || s_core.object.object.type_id == 3U) {
uint64_t utc_ms = iec104_source_clock_ms(request->base_ms);
uint64_t utc_seconds = utc_ms / 1000U;
iec104_source_stats(&s_core.source_stats);
memset(&s_core.sample_time, 0, sizeof(s_core.sample_time));
if (utc_seconds > IEC60870_TIME_MAX_SECONDS ||
!IEC60870_Time_Seconds_To_Local((uint32_t)utc_seconds,
(uint16_t)(utc_ms % 1000U), &s_core.sample_time.time)) { return IEC104_READ_LOOKUP_ERROR; }
s_core.sample_time.has_weekday = 1U;
s_core.sample_time.is_invalid = s_core.source_stats.synchronized ? 0U : 1U;
if (s_core.object.object.type_id == 1U) {
if (IEC60870_SinglePointWithCP56Time2a_Create(&s_core.timestamped.single,
request->ioa, s_core.object.single.value, s_core.object.single.quality,
&s_core.sample_time) != IEC60870_ASDU_OK) { return IEC104_READ_LOOKUP_ERROR; }
return IEC60870_Asdu_Add_InformationObject(response, &s_core.timestamped.single.base.object) ==
IEC60870_ASDU_OK ? IEC104_READ_LOOKUP_FOUND : IEC104_READ_LOOKUP_ERROR;
}
if (IEC60870_DoublePointWithCP56Time2a_Create(&s_core.timestamped.double_point,
request->ioa, s_core.object.double_point.value, s_core.object.double_point.quality,
&s_core.sample_time) != IEC60870_ASDU_OK) { return IEC104_READ_LOOKUP_ERROR; }
return IEC60870_Asdu_Add_InformationObject(response, &s_core.timestamped.double_point.base.object) ==
IEC60870_ASDU_OK ? IEC104_READ_LOOKUP_FOUND : IEC104_READ_LOOKUP_ERROR;
}
return IEC60870_Asdu_Add_InformationObject(response, &s_core.object.object) == IEC60870_ASDU_OK ?
IEC104_READ_LOOKUP_FOUND : IEC104_READ_LOOKUP_ERROR;
}
static IEC104_PeriodicScanLookupResult_t scan_point(void *context,
const IEC104_PeriodicScanRequest_t *request, IEC60870_Asdu_t *response)
{
(void)context;
if (!iec104_source_find(request->ioa, &s_core.object)) { return IEC104_PERIODIC_SCAN_LOOKUP_ERROR; }
return IEC60870_Asdu_Add_InformationObject(response, &s_core.object.object) == IEC60870_ASDU_OK ?
IEC104_PERIODIC_SCAN_LOOKUP_ADDED : IEC104_PERIODIC_SCAN_LOOKUP_ERROR;
}
/* Lifecycle events go to EVERY module, even if another module handled them. */
/* 函数功能:分派原连接事件并对未支持请求执行有界否定回显。 */
static bool dispatch(const IEC104_SlaveEvent_t *event)
{
bool reset_data = false;
int handled;
bool information = event->transport.type == IEC104_TCP_EVENT_I_FRAME;
if (s_core.closing && information) { return true; }
if (!s_core.closing &&
!IEC104_Startup_Handle_Event(&s_core.startup, s_core.slave, event, &reset_data)) { return false; }
if (reset_data) {
s_core.gi.cursor = s_core.ci.cursor = 0U;
s_core.gi.request_id = s_core.ci.request_id = 0U;
}
#define CORE_DISPATCH(module, function) \
do { \
if ((module) != NULL) { \
handled = (int)function((module), event); \
if (handled < 0) { return false; } \
if (information && handled > 0) { return true; } \
} \
} while (0)
CORE_DISPATCH(s_core.gi.module, IEC104_Interrogation_Handle_Event);
CORE_DISPATCH(s_core.ci.module, IEC104_Interrogation_Handle_Event);
CORE_DISPATCH(s_core.command, IEC104_Command_Handle_Event);
CORE_DISPATCH(s_core.clock, IEC104_ClockSynchronization_Handle_Event);
CORE_DISPATCH(s_core.remote, IEC104_RemoteParameter_Handle_Event);
CORE_DISPATCH(s_core.parameter, IEC104_Parameter_Handle_Event);
CORE_DISPATCH(s_core.read, IEC104_Read_Handle_Event);
CORE_DISPATCH(s_core.system, IEC104_SystemCommand_Handle_Event);
CORE_DISPATCH(s_core.scan, IEC104_PeriodicScan_Handle_Event);
#undef CORE_DISPATCH
if (information && event->asdu_result == IEC60870_ASDU_OK && !s_core.closing) {
IEC104_TcpSubmitResult_t result = IEC104_Slave_Reject_Request(s_core.slave, event,
IEC60870_ASDU_COT_UNKNOWN_TYPE);
if (result == IEC104_TCP_SUBMIT_WAIT) { s_core.reject_pending = true; }
else if (result != IEC104_TCP_SUBMIT_OK && result != IEC104_TCP_SUBMIT_ERROR) { return false; }
}
return true;
}
/* 函数功能:按预算消费传输通知,保留背压请求的稳定存储。 */
static bool drain_events(unsigned budget)
{
unsigned count;
if (s_core.reject_pending && !s_core.closing) {
IEC104_TcpSubmitResult_t reply = IEC104_Slave_Reject_Request(s_core.slave, &s_core.event,
IEC60870_ASDU_COT_UNKNOWN_TYPE);
if (reply == IEC104_TCP_SUBMIT_WAIT) { return true; }
s_core.reject_pending = false;
if (reply == IEC104_TCP_SUBMIT_FATAL) { return false; }
}
for (count = 0U; count < budget; ++count) {
IEC104_TcpEventResult_t next = IEC104_Slave_NextEvent(s_core.slave, &s_core.event);
const IEC104_TcpEvent_t *transport = &s_core.event.transport;
if (next == IEC104_TCP_EVENT_EMPTY) { return true; }
if (next != IEC104_TCP_EVENT_READY) { return false; }
if (transport->type == IEC104_TCP_EVENT_CONNECTED) { increment(&s_core.status.connections); }
if (transport->type == IEC104_TCP_EVENT_I_FRAME) { increment(&s_core.status.received_i_frames); }
if (transport->type == IEC104_TCP_EVENT_RECORD) {
if (transport->data.record.value.local_send_completed != 0U) {
increment(&s_core.status.written_i_frames);
}
if (transport->data.record.value.peer_acknowledged != 0U) {
increment(&s_core.status.acknowledged_i_frames);
}
}
if (!dispatch(&s_core.event)) { return false; }
if (s_core.reject_pending) { return true; }
}
return true;
}
/* 函数功能:按召唤分组限定本次取点范围。 */
static bool group_member(const core_interrogation_t *work, uint8_t type)
{
if (work->counter || work->event.request.qualifier == 20U) { return true; }
if (work->event.request.qualifier == 21U) { return type == 1U || type == 3U; }
return type == 9U || type == 11U || type == 13U;
}
/* 函数功能:有界推进召唤业务,仅在发送接手后提交取点游标。 */
static bool interrogation_step(core_interrogation_t *work)
{
unsigned round;
for (round = 0U; round < CORE_WORK_BUDGET; ++round) {
IEC104_InterrogationReplyResult_t reply = IEC104_INTERROGATION_REPLY_OK;
IEC104_InterrogationEvent_t *event = &work->event;
if (!IEC104_Interrogation_Process(work->module)) { return false; }
if (!work->counter && !IEC104_Startup_Can_Consume_General(&s_core.startup)) { return true; }
if (!work->pending) {
IEC104_InterrogationNextResult_t next = IEC104_Interrogation_NextEvent(work->module, event);
if (next == IEC104_INTERROGATION_NEXT_EMPTY) { return true; }
if (next != IEC104_INTERROGATION_NEXT_READY) { return false; }
work->pending = true;
}
if (event->type == IEC104_INTERROGATION_BEGIN) {
bool accept = work->counter ?
(event->request.qualifier == 5U && event->request.freeze == 0U) :
(event->request.qualifier >= 20U && event->request.qualifier <= 22U);
if (!work->counter && accept) {
IEC104_TcpSubmitResult_t observed = IEC104_Startup_Observe_General(
&s_core.startup, s_core.slave, event, true);
if (observed == IEC104_TCP_SUBMIT_WAIT) { return true; }
if (observed != IEC104_TCP_SUBMIT_OK) { return false; }
}
reply = IEC104_Interrogation_Reply_Begin(work->module, event, accept);
} else if (event->type == IEC104_INTERROGATION_NEED_DATA) {
size_t cursor, count = 0U, inspected = 0U;
size_t total = work->counter ? 8U : iec104_source_count();
if (work->request_id != event->request_id) {
work->request_id = event->request_id;
work->cursor = 0U;
}
cursor = work->cursor;
if (!new_batch(event->request.data_cause, event->request.originator_address,
event->request.is_test)) { return false; }
while (cursor < total && inspected < CORE_DATA_BUDGET) {
bool read_ok = work->counter ? iec104_source_counter(cursor, &s_core.object) :
iec104_source_point(cursor, &s_core.object);
IEC60870_AsduResult_t added;
++inspected;
if (!read_ok) { return false; }
if (!group_member(work, s_core.object.object.type_id)) { ++cursor; continue; }
if (count != 0U && s_core.batch.type_id != s_core.object.object.type_id) { break; }
added = IEC60870_Asdu_Add_InformationObject(&s_core.batch, &s_core.object.object);
if (added == IEC60870_ASDU_FULL) { break; }
if (added != IEC60870_ASDU_OK) { return false; }
++cursor;
++count;
}
if (count != 0U) {
reply = IEC104_Interrogation_Submit_Batch(work->module, event, &s_core.batch);
if (reply == IEC104_INTERROGATION_REPLY_OK) { work->cursor = cursor; }
} else if (cursor == total) {
reply = IEC104_Interrogation_Complete_Data(work->module, event);
} else {
/* Filtering consumed a bounded number of rows but produced no ASDU. */
work->cursor = cursor;
return true;
}
} else if (event->type == IEC104_INTERROGATION_FINISHED) {
if (!work->counter && event->reason == IEC104_INTERROGATION_FINISH_COMPLETED) {
IEC104_TcpSubmitResult_t observed = IEC104_Startup_Observe_General(
&s_core.startup, s_core.slave, event, false);
if (observed == IEC104_TCP_SUBMIT_WAIT) { return true; }
if (observed == IEC104_TCP_SUBMIT_FATAL) { return false; }
increment(&s_core.status.gi_completed);
}
if (work->request_id == event->request_id) { work->request_id = 0U; work->cursor = 0U; }
} else { return false; }
if (reply == IEC104_INTERROGATION_REPLY_WAIT) { return true; }
if (reply != IEC104_INTERROGATION_REPLY_OK && reply != IEC104_INTERROGATION_REPLY_STALE) { return false; }
work->pending = false;
}
return true;
}
/* 函数功能:执行一次数据源模拟动作并保存启动结果。 */
static IEC104_CommandActionResult_t command_action(void *context, const IEC104_CommandRequest_t *request)
{
s_core.action_result = iec104_source_command(context, request);
return s_core.action_result;
}
/* 函数功能:推进遥控动作结果、反馈及终止;背压不重复动作。 */
static bool command_step(void)
{
unsigned step;
IEC104_CommandReplyResult_t reply;
for (step = 0U; step < CORE_WORK_BUDGET; ++step) {
IEC104_CommandNextResult_t next = IEC104_Command_NextEvent(s_core.command, &s_core.next_command);
if (next == IEC104_COMMAND_NEXT_EMPTY) { break; }
if (next != IEC104_COMMAND_NEXT_READY) { return false; }
if (s_core.next_command.type == IEC104_COMMAND_FINISHED) {
if (s_core.next_command.reason == IEC104_COMMAND_FINISH_COMPLETED) {
increment(&s_core.status.commands_completed);
}
if (s_core.command_event.transaction_id == s_core.next_command.transaction_id) {
s_core.command_pending = false;
s_core.command_step = 0U;
}
} else {
s_core.command_event = s_core.next_command;
s_core.command_pending = true;
s_core.command_step = 0U;
}
}
if (!s_core.command_pending) { return true; }
reply = IEC104_COMMAND_REPLY_OK;
if (s_core.command_step == 0U) {
s_core.action_result = IEC104_COMMAND_ACTION_NOT_STARTED;
reply = IEC104_Command_Accept(s_core.command, &s_core.command_event, command_action, NULL);
if (reply == IEC104_COMMAND_REPLY_OK) {
if (s_core.command_event.type == IEC104_COMMAND_SELECT ||
s_core.action_result != IEC104_COMMAND_ACTION_STARTED) {
s_core.command_pending = false;
return true;
}
s_core.feedback_count = iec104_source_command_feedback(s_core.command_event.request.ioa,
s_core.feedback, CORE_FEEDBACK_CAPACITY);
if (s_core.feedback_count > CORE_FEEDBACK_CAPACITY) { return false; }
s_core.feedback_index = 0U;
s_core.command_step = 1U;
}
}
if (reply == IEC104_COMMAND_REPLY_OK && s_core.command_step == 1U) {
reply = IEC104_Command_Report_Result(s_core.command, &s_core.command_event, IEC104_COMMAND_RESULT_SUCCEEDED);
if (reply == IEC104_COMMAND_REPLY_OK) { s_core.command_step = 2U; }
}
if (reply == IEC104_COMMAND_REPLY_OK && s_core.command_step == 2U) {
if (s_core.feedback_index < s_core.feedback_count) {
if (!new_batch(IEC60870_ASDU_COT_RETURN_INFO_REMOTE,
s_core.command_event.request.originator_address, false) ||
!iec104_source_find(s_core.feedback[s_core.feedback_index], &s_core.object) ||
IEC60870_Asdu_Add_InformationObject(&s_core.batch, &s_core.object.object) != IEC60870_ASDU_OK) {
return false;
}
reply = IEC104_Command_Submit_Return_Info(s_core.command, &s_core.command_event, &s_core.batch);
if (reply == IEC104_COMMAND_REPLY_OK) { ++s_core.feedback_index; }
}
if (s_core.feedback_index == s_core.feedback_count) { s_core.command_step = 3U; }
}
if (reply == IEC104_COMMAND_REPLY_OK && s_core.command_step == 3U) {
reply = IEC104_Command_Complete(s_core.command, &s_core.command_event);
if (reply == IEC104_COMMAND_REPLY_OK) { s_core.command_pending = false; }
}
if (reply == IEC104_COMMAND_REPLY_STALE) { s_core.command_pending = false; return true; }
return reply != IEC104_COMMAND_REPLY_ERROR;
}
/* 函数功能:等待初始化和真实全站总召交接后开放上送门禁。 */
static bool startup_step(void)
{
return IEC104_Startup_Process(&s_core.startup, s_core.slave, s_core.system, &s_core.system_status);
}
/* Re-read current snapshots after backpressure; never consume source events. */
/* 函数功能:有界读取当前快照并将变化交给成熟突发引擎。 */
static bool collect_changes(void)
{
unsigned row;
uint64_t now = IEC104_Net_Now_Ms();
iec104_source_stats(&s_core.source_stats);
if (!IEC104_Spontaneous_Set_Time_Base(s_core.spontaneous,
iec104_source_clock_ms(now), now, s_core.source_stats.synchronized)) { return false; }
for (row = 0U; row < CORE_DATA_BUDGET; ++row) {
uint32_t value = 0U;
uint8_t quality;
core_previous_t *previous = &s_core.previous[s_core.sample_cursor];
if (!iec104_source_point(s_core.sample_cursor, &s_core.object)) { return false; }
memset(&s_core.change, 0, sizeof(s_core.change));
s_core.change.common_address = s_core.ca;
s_core.change.ioa = s_core.object.object.ioa;
s_core.change.time_kind = IEC104_SPONTANEOUS_TIME_MONOTONIC;
s_core.change.time_ms = now;
switch (s_core.object.object.type_id) {
case 1U:
value = s_core.object.single.value;
quality = s_core.object.single.quality;
s_core.change.kind = IEC104_SPONTANEOUS_SINGLE;
s_core.change.value.single = (uint8_t)value;
break;
case 3U:
value = s_core.object.double_point.value;
quality = s_core.object.double_point.quality;
s_core.change.kind = IEC104_SPONTANEOUS_DOUBLE;
s_core.change.value.double_point = (uint8_t)value;
break;
case 13U:
memcpy(&value, &s_core.object.measurement.value, sizeof(value));
quality = s_core.object.measurement.quality;
s_core.change.kind = IEC104_SPONTANEOUS_FLOAT;
s_core.change.value.short_float = s_core.object.measurement.value;
break;
default: return false;
}
s_core.change.quality = quality;
if (previous->initialized && (previous->value != value || previous->quality != quality)) {
IEC104_SpontaneousPublishResult_t result = IEC104_Spontaneous_Publish(s_core.spontaneous,
&s_core.change, 1U, &s_core.publication);
if (result == IEC104_SPONTANEOUS_PUBLISH_WAIT) { return true; }
if (result != IEC104_SPONTANEOUS_PUBLISH_OK) { return false; }
}
previous->value = value;
previous->quality = quality;
previous->initialized = true;
++s_core.sample_cursor;
if (s_core.sample_cursor == CORE_MONITOR_CAPACITY) { s_core.sample_cursor = 0U; }
}
return true;
}
static IEC104_ParameterActionResult_t parameter_action(void *context,
const IEC104_ParameterRequest_t *request)
{
IEC104_ParameterActionResult_t result = iec104_source_parameter_action(context, request);
if (result == IEC104_PARAMETER_ACTION_APPLIED && request->type_id == 113U &&
request->qpa == IEC60870_ASDU_QPA_CYCLIC_TRANSMISSION && !request->test &&
request->phase == IEC104_PARAMETER_PHASE_EXECUTE) {
uint32_t period = request->operation == IEC104_PARAMETER_OP_ACTIVATE ? 10000U : 0U;
if (!IEC104_PeriodicScan_Set_Group_Period(s_core.scan, 0U, period)) {
return IEC104_PARAMETER_ACTION_REJECTED;
}
}
return result;
}
/* 函数功能:按严格业务优先级逐轮调度已装配模块。 */
static bool business_step(void)
{
unsigned priority;
uint64_t now = IEC104_Net_Now_Ms();
if (!IEC104_Command_Set_Time_Base(s_core.command, iec104_source_clock_ms(now), now) ||
!collect_changes()) { return false; }
for (priority = IEC104_BUSINESS_PRIORITY_INITIALIZATION; priority < IEC104_BUSINESS_PRIORITY_COUNT; ++priority) {
if (IEC104_Slave_Set_Business_Priority(s_core.slave, (IEC104_BusinessPriority_t)priority) != IEC104_TCP_SUBMIT_OK) {
return false;
}
switch ((IEC104_BusinessPriority_t)priority) {
case IEC104_BUSINESS_PRIORITY_INITIALIZATION:
if (!IEC104_SystemCommand_Process(s_core.system) || !startup_step()) { return false; }
break;
case IEC104_BUSINESS_PRIORITY_INITIAL_INTERROGATION:
case IEC104_BUSINESS_PRIORITY_INTERROGATION:
if (!interrogation_step(&s_core.gi) || !startup_step()) { return false; }
if (priority == IEC104_BUSINESS_PRIORITY_INTERROGATION &&
(!IEC104_Read_Process(s_core.read) || IEC104_Read_Execute_Next(s_core.read, read_point, NULL) ==
IEC104_READ_EXECUTE_ERROR)) { return false; }
break;
case IEC104_BUSINESS_PRIORITY_COMMAND:
if (!IEC104_Command_Process(s_core.command) || !command_step() ||
!IEC104_Command_Process(s_core.command) || !IEC104_Parameter_Process(s_core.parameter) ||
IEC104_Parameter_Execute_Next(s_core.parameter, parameter_action, NULL) ==
IEC104_PARAMETER_EXECUTE_ERROR || !IEC104_RemoteParameter_Process(s_core.remote) ||
IEC104_RemoteParameter_Execute_Next(s_core.remote, &iec104_source_remote_handlers, NULL) ==
IEC104_REMOTE_PARAMETER_EXECUTE_ERROR) { return false; }
break;
case IEC104_BUSINESS_PRIORITY_CLOCK:
if (!IEC104_ClockSynchronization_Process(s_core.clock) ||
IEC104_ClockSynchronization_Execute_Next_With_Read(s_core.clock,
iec104_source_clock_set, iec104_source_clock_read, NULL) == IEC104_CLOCK_SYNCHRONIZATION_EXECUTE_ERROR ||
!IEC104_ClockSynchronization_Process(s_core.clock)) { return false; }
break;
case IEC104_BUSINESS_PRIORITY_MEASUREMENT:
if (IEC104_PeriodicScan_Step(s_core.scan, scan_point, NULL) == IEC104_PERIODIC_SCAN_STEP_ERROR) { return false; }
break;
case IEC104_BUSINESS_PRIORITY_COUNTER_INTERROGATION:
if (!interrogation_step(&s_core.ci)) { return false; }
break;
default: break;
}
}
return true;
}
/* 函数功能:更新同所有者线程读取的传输观测镜像。 */
static bool refresh_status(void)
{
if (IEC104_Slave_Get_Status(s_core.slave, &s_core.transport_status, &s_core.error) != IEC104_TCP_OK) { return false; }
s_core.status.bound_port = s_core.transport_status.bound_port;
s_core.status.connected = s_core.transport_status.connected;
s_core.status.active = (uint8_t)(s_core.transport_status.connected != 0U &&
s_core.transport_status.connection_status_valid != 0U &&
s_core.transport_status.connection.data_transfer_started != 0U);
return true;
}
/* 函数功能:执行一次零等待网络推进及有界业务调度。 */
int iec104_core_poll(void)
{
bool ok;
if (s_core.slave == NULL || s_core.status.running == 0U || s_core.closing) { return -1; }
if (IEC104_Slave_Poll(s_core.slave, 0U, &s_core.error) != IEC104_TCP_OK ||
!drain_events(CORE_EVENT_BUDGET) || !refresh_status()) { return fail(); }
if (s_core.transport_status.pending_event_count != 0U || s_core.reject_pending) { return 0; }
if (IEC104_Slave_Begin_Business_Cycle(s_core.slave) != IEC104_TCP_SUBMIT_OK) { return fail(); }
ok = business_step();
if (IEC104_Slave_End_Business_Cycle(s_core.slave) != IEC104_TCP_SUBMIT_OK) { ok = false; }
return ok ? 0 : fail();
}
/* 函数功能:分步取得静态模块及监听资源,失败由外层统一清理。 */
static int initialize_core(const iec104_core_config_t *config)
{
size_t i, scan_count = 0U;
if (s_core.slave != NULL || config == NULL || config->bind_address == NULL ||
strlen(config->bind_address) >= sizeof(s_transport_config.bind_address) ||
config->common_address == 0U || config->common_address == UINT16_MAX) { return -1; }
memset(&s_core, 0, sizeof(s_core));
s_core.ca = config->common_address;
iec104_source_init();
s_core.slave = IEC104_Slave_Create();
if (s_core.slave == NULL) { return fail(); }
s_core.status.owns_resources = 1U;
IEC104_Startup_Init(&s_core.startup);
IEC104_Startup_Config_Default(&s_transport_config, &s_system_config, &s_gi_config, &s_ci_config, &s_spontaneous_config);
memcpy(s_transport_config.bind_address, config->bind_address, strlen(config->bind_address) + 1U);
s_transport_config.port = config->port;
/* Only initialization and protocol tests are enabled: no MCU reset side effects. */
s_system_config.features = IEC104_SYSTEM_COMMAND_FEATURE_INIT_END | IEC104_SYSTEM_COMMAND_FEATURE_TEST_COMMAND;
if (IEC104_Slave_Add_Station(s_core.slave, &s_core.station, s_core.ca, NULL) != IEC104_STATION_OK) { return fail(); }
s_core.system = IEC104_SystemCommand_Create(s_core.slave, &s_system_config);
s_core.gi.module = IEC104_Interrogation_Create(s_core.slave, &s_gi_config);
s_core.ci.module = IEC104_CounterInterrogation_Create(s_core.slave, &s_ci_config);
s_core.ci.counter = true;
IEC104_Command_Config_Default(&s_command_config);
s_command_config.points = iec104_source_commands(s_core.ca, &s_command_config.point_count);
s_core.command = IEC104_Command_Create(s_core.slave, &s_command_config);
IEC104_ClockSynchronization_Config_Default(&s_clock_config);
s_core.clock = IEC104_ClockSynchronization_Create(s_core.slave, &s_clock_config);
IEC104_RemoteParameter_Config_Default(&s_remote_config);
s_core.remote = IEC104_RemoteParameter_Create(s_core.slave, &s_remote_config);
iec104_source_parameter_config(s_core.ca, &s_parameter_config);
s_core.parameter = IEC104_Parameter_Create(s_core.slave, &s_parameter_config);
IEC104_Read_Config_Default(&s_read_config);
s_core.read = IEC104_Read_Create(s_core.slave, &s_read_config);
for (i = 0U; i < iec104_source_count(); ++i) {
if (!iec104_source_point(i, &s_core.object)) { return fail(); }
if (s_core.object.object.type_id == 13U) {
if (scan_count == CORE_SCAN_CAPACITY) { return fail(); }
s_core.scan_points[scan_count].common_address = s_core.ca;
s_core.scan_points[scan_count].type_id = 13U;
s_core.scan_points[scan_count].groups = 1U;
s_core.scan_points[scan_count].ioa = s_core.object.object.ioa;
++scan_count;
}
}
IEC104_PeriodicScan_Config_Default(&s_scan_config);
memset(&s_scan_group, 0, sizeof(s_scan_group));
s_scan_group.period_ms = 10000U;
s_scan_group.first_delay_ms = 10000U;
s_scan_group.cause = IEC60870_ASDU_COT_PERIODIC;
s_scan_config.points = s_core.scan_points;
s_scan_config.point_count = scan_count;
s_scan_config.groups = &s_scan_group;
s_scan_config.group_count = 1U;
s_scan_config.max_objects_per_asdu = CORE_DATA_BUDGET;
s_scan_config.max_asdus_per_step = 1U;
s_core.scan = IEC104_PeriodicScan_Create(s_core.slave, &s_scan_config);
s_core.spontaneous = IEC104_Spontaneous_Create(s_core.slave, &s_spontaneous_config);
if (s_core.system == NULL || s_core.gi.module == NULL || s_core.ci.module == NULL ||
s_core.command == NULL || s_core.clock == NULL || s_core.remote == NULL ||
s_core.parameter == NULL || s_core.read == NULL || s_core.scan == NULL || s_core.spontaneous == NULL ||
!IEC104_SystemCommand_Set_Initialization(s_core.system, 0U) ||
IEC104_Slave_Init(s_core.slave, &s_transport_config, &s_core.error) != IEC104_TCP_OK) { return fail(); }
s_core.status.running = 1U;
if (!refresh_status()) { return fail(); }
return 0;
}
/* 函数功能:启动单实例服务,失败时保留错误并有界回收已取得资源。 */
int iec104_core_start(const iec104_core_config_t *config)
{
int result;
/* An existing instance must never be torn down by a rejected double start. */
if (s_core.slave != NULL) { return -1; }
result = initialize_core(config);
if (result != 0 && s_core.slave != NULL) {
int original_error = s_core.status.last_error;
int original_stage = s_core.status.last_stage;
int original_native = s_core.status.native_error;
(void)iec104_core_stop();
s_core.status.last_error = original_error;
s_core.status.last_stage = original_stage;
s_core.status.native_error = original_native;
}
return result;
}
/* 函数功能:取消业务、排空有限通知并按依赖顺序释放模块。 */
int iec104_core_stop(void)
{
unsigned n;
bool ok = true;
if (s_core.slave == NULL) { return 0; }
s_core.closing = true;
s_core.status.running = 0U;
if (!IEC104_Startup_Reset(&s_core.startup, s_core.slave)) { return fail(); }
IEC104_Interrogation_Cancel(s_core.gi.module);
IEC104_Interrogation_Cancel(s_core.ci.module);
IEC104_Command_Cancel(s_core.command);
IEC104_ClockSynchronization_Cancel(s_core.clock);
IEC104_RemoteParameter_Cancel(s_core.remote);
IEC104_Parameter_Cancel(s_core.parameter);
IEC104_Read_Cancel(s_core.read);
IEC104_PeriodicScan_Cancel(s_core.scan);
IEC104_SystemCommand_Cancel(s_core.system);
if (IEC104_Slave_Close(s_core.slave, &s_core.error) != IEC104_TCP_OK) { return fail(); }
s_core.reject_pending = false;
if (!drain_events(256U)) { return fail(); }
for (n = 0U; n < 8U; ++n) {
if (s_core.gi.module != NULL) { (void)IEC104_Interrogation_NextEvent(s_core.gi.module, &s_core.gi.event); }
if (s_core.ci.module != NULL) { (void)IEC104_Interrogation_NextEvent(s_core.ci.module, &s_core.ci.event); }
if (s_core.command != NULL) { (void)IEC104_Command_NextEvent(s_core.command, &s_core.next_command); }
if (s_core.remote != NULL) {
(void)IEC104_RemoteParameter_Execute_Next(s_core.remote, &iec104_source_remote_handlers, NULL);
}
}
#define CORE_DESTROY(member, function) \
do { if ((member) != NULL) { if (function(member)) { (member) = NULL; } else { ok = false; } } } while (0)
CORE_DESTROY(s_core.gi.module, IEC104_Interrogation_Destroy);
CORE_DESTROY(s_core.ci.module, IEC104_Interrogation_Destroy);
CORE_DESTROY(s_core.command, IEC104_Command_Destroy);
CORE_DESTROY(s_core.clock, IEC104_ClockSynchronization_Destroy);
CORE_DESTROY(s_core.remote, IEC104_RemoteParameter_Destroy);
CORE_DESTROY(s_core.parameter, IEC104_Parameter_Destroy);
CORE_DESTROY(s_core.read, IEC104_Read_Destroy);
CORE_DESTROY(s_core.scan, IEC104_PeriodicScan_Destroy);
CORE_DESTROY(s_core.system, IEC104_SystemCommand_Destroy);
CORE_DESTROY(s_core.spontaneous, IEC104_Spontaneous_Destroy);
#undef CORE_DESTROY
if (!ok) { return fail(); }
if (IEC104_Station_Is_Registered(&s_core.station) &&
IEC104_Slave_Remove_Station(s_core.slave, &s_core.station) != IEC104_STATION_OK) { return fail(); }
if (IEC104_Slave_Destroy(s_core.slave, &s_core.error) != IEC104_TCP_OK) { return fail(); }
s_core.slave = NULL;
s_core.status.owns_resources = 0U;
s_core.status.connected = s_core.status.active = 0U;
s_core.status.bound_port = 0U;
s_core.closing = false;
return 0;
}
/* 函数功能:同所有者只读复制状态,空指针无操作。 */
void iec104_core_get_status(iec104_core_status_t *status)
{
if (status != NULL) { *status = s_core.status; }
}