2471 lines
131 KiB
C
2471 lines
131 KiB
C
/*
|
||
* 国网配电自动化文件服务(Type 210)。
|
||
* 模块管理报文、目录快照寿命和读写会话,不接触文件系统或硬件。
|
||
* 请求FIFO、写激活槽、写数据环各自有界;所有确认按形成序号交接。
|
||
* 写路径在BUSY期间仅操作应用暂存;COMMIT必须等Slave通知读空。
|
||
* 应用回调仅由Execute_Next同步交付,Handle_Event/Process不调用应用。
|
||
*
|
||
* 操作对:1/2目录,3/4读激活,5/6读数据及确认,7/8写激活,9/10写数据及确认。
|
||
* 三个入口分工:Handle_Event按通知顺序保存请求,Process检查期限并提交固定回复,
|
||
* Execute_Next交付一个应用步骤或组一帧数据。发送层接手不代表主站已收到。
|
||
*/
|
||
#include "IEC104_FileService.h"
|
||
#include "IEC104_Net.h"
|
||
#include "IEC104_TcpServer_Config.h"
|
||
#include <limits.h>
|
||
#include <string.h>
|
||
|
||
#ifndef IEC104_FILE_SERVICE_CAPACITY
|
||
#define IEC104_FILE_SERVICE_CAPACITY IEC104_TCP_SERVER_CAPACITY
|
||
#endif
|
||
#ifndef IEC104_FILE_SERVICE_TASK_CAPACITY
|
||
#define IEC104_FILE_SERVICE_TASK_CAPACITY 2U
|
||
#endif
|
||
#ifndef IEC104_FILE_SERVICE_SEGMENT_CAPACITY
|
||
#define IEC104_FILE_SERVICE_SEGMENT_CAPACITY 2U
|
||
#endif
|
||
#ifndef IEC104_FILE_SERVICE_CONFIRM_CAPACITY
|
||
#define IEC104_FILE_SERVICE_CONFIRM_CAPACITY 2U
|
||
#endif
|
||
typedef char FileService_Capacity_Check[(IEC104_FILE_SERVICE_CAPACITY > 0U &&
|
||
IEC104_FILE_SERVICE_CAPACITY <= UINT_MAX && IEC104_FILE_SERVICE_TASK_CAPACITY > 0U &&
|
||
IEC104_FILE_SERVICE_TASK_CAPACITY <= (UINT_MAX - 16U) / 4U &&
|
||
IEC104_FILE_SERVICE_SEGMENT_CAPACITY > 0U && IEC104_FILE_SERVICE_SEGMENT_CAPACITY <= UINT_MAX / 4U &&
|
||
IEC104_FILE_SERVICE_CONFIRM_CAPACITY >= 2U && IEC104_FILE_SERVICE_CONFIRM_CAPACITY <= UINT_MAX / 4U) ? 1 : -1];
|
||
|
||
/**
|
||
* 功能:外部边界替身只在专项构建中存在,生产对象不引用测试符号。
|
||
* 输入参数:self/identity——从站服务及请求身份;asdu——待提交的应答ASDU。
|
||
* 输出参数:self——本模块实例的更新结果。
|
||
* 返回值:OK已复制接手;WAIT未接手;ERROR为身份或ASDU非法;FATAL为连接故障。
|
||
* 说明:可直接交接或进入HIGH队列;本入口不返回票据,成功不表示对端已确认。
|
||
*/
|
||
#ifdef IEC104_FILE_SERVICE_TEST_HOOKS
|
||
extern IEC104_TcpSubmitResult_t IEC104_FileService_Test_Send_Response(IEC104_Slave_t *,
|
||
const IEC104_SlaveEventIdentity_t *, const IEC60870_Asdu_t *, uint64_t *);
|
||
/**
|
||
* 功能:使用默认业务等级查询该事件身份是否允许一次空闲业务发送。
|
||
* 输入参数:self/identity——从站服务及事件身份;reserve——提交后须保留的窗口和记录槽数量。
|
||
* 输出参数:无。
|
||
* 返回值:OK当前可发送;WAIT暂受通知、协议或资源限制;ERROR为身份、参数或状态非法。
|
||
* 说明:查询不接手ASDU或预留资源,实际Send_Idle仍重新核对通知和连接状态。
|
||
*/
|
||
extern IEC104_TcpSubmitResult_t IEC104_FileService_Test_Query_Idle_Send(const IEC104_Slave_t *,
|
||
const IEC104_SlaveEventIdentity_t *, uint16_t);
|
||
/**
|
||
* 功能:使用默认业务等级尝试直接发送一帧空闲业务ASDU。
|
||
* 输入参数:self/identity——从站服务及事件身份;asdu——待提交原文。
|
||
* reserve——提交后须保留的窗口和记录槽数量。
|
||
* 输出参数:self——本模块实例的更新结果。
|
||
* 返回值:OK已接手;WAIT尚未接手;ERROR非法;FATAL为连接故障。
|
||
* 说明:WAIT不把原文转入队列;待分派通知优先,实际发送仍遵循底层部分写入流程。
|
||
*/
|
||
extern IEC104_TcpSubmitResult_t IEC104_FileService_Test_Send_Idle(IEC104_Slave_t *,
|
||
const IEC104_SlaveEventIdentity_t *, const IEC60870_Asdu_t *, uint16_t);
|
||
/**
|
||
* 功能:统一判断业务是否应先处理通知、放弃失效请求,或继续当前会话的工作。
|
||
* 输入参数:identity为Get_Event_Identity的只读结果,允许零初始化表示尚未绑定会话。
|
||
* 输出参数:无。
|
||
* 返回值:ERROR为参数/查询失败;WAIT_EVENTS优先于会话判断;STALE为原身份不再可用;READY可继续。
|
||
* 说明:检查通知FIFO、服务实例、TCP代次和传输激活状态,不执行I/O或保留发送窗口。
|
||
* 先读空通知可避免同一代次STOP后又START时,仅凭最终激活状态误续旧业务。
|
||
*/
|
||
extern IEC104_SlaveRequestState_t IEC104_FileService_Test_Check_Request(const IEC104_Slave_t *,
|
||
const IEC104_SlaveEventIdentity_t *);
|
||
/**
|
||
* 功能:取得内部TCP服务、队列和最近会话的状态副本,不推进协议或消费队列。
|
||
* 输入参数:self——有效句柄;status——非NULL输出存储;error——可选诊断。
|
||
* 输出参数:status——状态快照的更新结果。
|
||
* error——错误诊断的更新结果。
|
||
* 返回值:OK写入status,失败保持输出;Create后、Init失败后和Close后均可查询。
|
||
* 说明:会话和队列各自有有效标志,connected与data_transfer_started含义不同。
|
||
*/
|
||
extern IEC104_TcpResult_t IEC104_FileService_Test_Get_Status(const IEC104_Slave_t *,
|
||
IEC104_TcpServerStatus_t *, IEC104_TcpError_t *);
|
||
/**
|
||
* 功能:能力属于已Init的服务,不依赖活动连接;
|
||
* 输入参数:self——本模块实例。
|
||
* capacity——存储容量。
|
||
* error——错误诊断。
|
||
* 输出参数:capacity——存储容量的更新结果。
|
||
* error——错误诊断的更新结果。
|
||
* 返回值:按处理分支返回Slave_Error(IEC104_TCP_INVALID_HANDLE, error)、IEC104_TcpServer_Get_Send_Capacity(self->server, capacity, error)。
|
||
* 说明:Close后历史ACTIVATED仍可能待分派,须保留INVALID_STATE。
|
||
*/
|
||
extern IEC104_TcpResult_t IEC104_FileService_Test_Get_Send_Capacity(const IEC104_Slave_t *,
|
||
IEC104_TcpSendCapacity_t *, IEC104_TcpError_t *);
|
||
/**
|
||
* 功能:按事件捕获的原连接身份主动断开主站,保留监听和服务级NORMAL。
|
||
* 输入参数:self——所属Slave;event——本服务事件或Copy_Event副本;error——可选诊断。
|
||
* 输出参数:self——本模块实例的更新结果。
|
||
* error——错误诊断的更新结果。
|
||
* 返回值:OK已断开;其他服务/已复用Slave的事件为INVALID_ARGUMENT;当前无连接为NOT_CONNECTED;
|
||
* 仍有连接但代次不同为STALE_GENERATION;底层服务异常通过原结果和error返回。
|
||
* 说明:来源serial先由本层检查,原generation再由TcpServer核对;不用当前代次代替旧身份。
|
||
* 不等待STOPDT或ACK,成功后继续读取收尾事件,再Prepare更新监听条件。
|
||
*/
|
||
extern IEC104_TcpResult_t IEC104_FileService_Test_Close_Connection(IEC104_Slave_t *,
|
||
const IEC104_SlaveEventIdentity_t *, IEC104_TcpError_t *);
|
||
/**
|
||
* 功能:读取系统启动以来的64位毫秒计数;供相对期限计算,不受用户修改日历时间影响。
|
||
* 输入参数:无。
|
||
* 输出参数:无。
|
||
* 返回值:64位单调毫秒计数,不是UTC时间戳,也不用于显示日期;0及连续读取相等值有效。
|
||
* 说明:不在此处换算为UTC或本地时间,避免将协议超时与日历时钟混用。
|
||
*/
|
||
extern uint64_t IEC104_FileService_Test_Now_Ms(void);
|
||
#define FS_SEND IEC104_FileService_Test_Send_Response
|
||
#define FS_IDLE_QUERY IEC104_FileService_Test_Query_Idle_Send
|
||
#define FS_IDLE_SEND IEC104_FileService_Test_Send_Idle
|
||
#define FS_CHECK IEC104_FileService_Test_Check_Request
|
||
#define FS_STATUS IEC104_FileService_Test_Get_Status
|
||
#define FS_CAPACITY IEC104_FileService_Test_Get_Send_Capacity
|
||
#define FS_CLOSE IEC104_FileService_Test_Close_Connection
|
||
#define FS_NOW IEC104_FileService_Test_Now_Ms
|
||
#else
|
||
/* 文件召唤/目录/固定确认归10,文件读取数据归11;控制提交并不等于已交接。 */
|
||
#define FS_SEND(s, i, a, t) IEC104_Slave_Send_Response_Tracked_Priority(s, i, a, t, IEC104_BUSINESS_PRIORITY_FILE_CALL)
|
||
#define FS_IDLE_QUERY(s, i, r) IEC104_Slave_Query_Idle_Send_Priority(s, i, r, IEC104_BUSINESS_PRIORITY_FILE_TRANSFER)
|
||
#define FS_IDLE_SEND(s, i, a, r) IEC104_Slave_Send_Idle_Priority(s, i, a, r, IEC104_BUSINESS_PRIORITY_FILE_TRANSFER)
|
||
#define FS_CHECK IEC104_Slave_Check_Request
|
||
#define FS_STATUS IEC104_Slave_Get_Status
|
||
#define FS_CAPACITY IEC104_Slave_Get_Send_Capacity
|
||
#define FS_CLOSE IEC104_Slave_Close_Connection_By_Identity
|
||
#define FS_NOW IEC104_Net_Now_Ms
|
||
#endif
|
||
|
||
/* 目录正常末帧交出后仍以DONE占住队首,等CLOSE_DIRECTORY交付才归还槽。
|
||
* FS_REPLY中的bytes已变成冻结回复,不能再按原请求偏移读取名称或时标。 */
|
||
enum { FS_EXECUTE = 1, FS_DIRECTORY = 2, FS_REPLY = 3, FS_DIRECTORY_DONE = 4 };
|
||
enum { FS_READ_OPEN = 1, FS_READ_DATA = 2 };
|
||
|
||
/* 持久记录的station非NULL表示拥有一个Acquire引用,转交时原记录必须置NULL。
|
||
* Source_Event构造的栈上来源暂借注册站,只有Queue_Task成功后才获得引用。
|
||
* 其他来源字段均按值保存,同CA重注册不会改写旧资源的station_id;
|
||
* 回复/近期记录只复制身份值,不因保留诊断字段而额外占有应用资源。 */
|
||
typedef struct {
|
||
IEC104_SlaveEventIdentity_t identity;
|
||
IEC104_Station_t *station;
|
||
uint64_t station_id, receive_serial, accepted_ms;
|
||
uint16_t ca;
|
||
uint8_t oa;
|
||
bool test;
|
||
} FileSource;
|
||
|
||
/* 目录扫描与固定回复/写激活不会同时使用这些字段,故复用阶段存储,不增加目录页缓冲。
|
||
* phase为0扫描、1前瞻、2重建待发页;task->cursor在页被接收前保持页首。
|
||
* page_end为候选页的尾后下标,next为前瞻位置;more记录是否发现下一匹配项。 */
|
||
typedef union {
|
||
struct { uint64_t sequence, formed_ms, write_serial; } reply;
|
||
struct { size_t page_end, next; uint8_t phase; bool more; } directory;
|
||
} FileTaskWork;
|
||
|
||
/* 请求槽同时用于FIFO和独立写激活:phase决定bytes是原文还是固定回复。
|
||
* cursor只在目录扫描时有效;work的两种解释由phase/operation区分。 */
|
||
typedef struct {
|
||
FileSource source;
|
||
FileTaskWork work;
|
||
size_t cursor;
|
||
uint8_t bytes[249];
|
||
uint16_t length;
|
||
uint8_t operation, phase;
|
||
bool occupied, waiting, failed;
|
||
} FileTask;
|
||
|
||
/* 数据段仅记录注册编号,不持站点引用;归属由执行时的打开会话证明。 */
|
||
typedef struct {
|
||
uint64_t write_serial, station_id, generation, receive_serial, accepted_ms;
|
||
uint32_t file_id, segment;
|
||
uint16_t ca, length;
|
||
uint8_t oa, data[IEC104_FILE_SERVICE_MAX_SEGMENT];
|
||
bool test, more, malformed, bad_sum;
|
||
} FileSegment;
|
||
|
||
/* reserved表示COMMIT尚未返回结果,仍实际占槽、参加排序和回复期限计算。
|
||
* terminal为最终结果,满队列时不能与非末段确认一起淘汰。 */
|
||
typedef struct {
|
||
FileSource source; /* 不拥有引用,资源引用由会话/收尾持有。 */
|
||
uint64_t sequence, formed_ms, write_serial;
|
||
uint8_t bytes[20];
|
||
bool occupied, reserved, terminal, waiting;
|
||
} FileConfirm;
|
||
|
||
/* 成功OPEN的资源只沿“打开 -> 收尾待交付 -> 释放”单向移动。
|
||
* COMMIT即最终收尾,不论结果如何都不会再补ABORT_WRITE。 */
|
||
typedef struct {
|
||
FileSource source;
|
||
uint64_t sequence, write_serial;
|
||
uintptr_t handle;
|
||
uint32_t size, transferred, file_id;
|
||
unsigned confirm_index;
|
||
IEC104_FileServiceCall_t call;
|
||
IEC104_FileServiceEndReason_t reason;
|
||
bool occupied;
|
||
} FileFinish;
|
||
|
||
/* task_alive和closed独立:先发末帧或先关快照都合法,两个条件完成才Release。
|
||
* task_index仅在task_alive时使用,避免任务取消/复用后误取另一目录原文。 */
|
||
typedef struct {
|
||
FileSource source;
|
||
uintptr_t handle;
|
||
uint64_t opened_ms, finish_sequence;
|
||
unsigned task_index;
|
||
IEC104_FileServiceEndReason_t reason;
|
||
bool occupied, task_alive, closing, closed;
|
||
} FileDirectory;
|
||
|
||
/* OPEN阶段只等待op4提交;DATA阶段启用段间隔期限,实际read还须通过op4票据的HANDED检查。
|
||
* aborting锁存读取失败:空中止末帧遇WAIT也不能重新调用read恢复传输。 */
|
||
typedef struct {
|
||
FileSource source;
|
||
uintptr_t handle;
|
||
uint32_t size, offset;
|
||
uint64_t progress_ms, confirmation_ticket; /* op4真实凭据;数据不得先于激活确认交给SendBuffer。 */
|
||
uint8_t phase;
|
||
bool occupied, waiting, aborting;
|
||
} FileRead;
|
||
|
||
/* serial是本实例每次受理写激活分配的序号,与线上file_id及Slave身份无关。
|
||
* op8_sent之前仅受激活回复期限约束;progress_ms只由成功的非空写入更新。 */
|
||
typedef struct {
|
||
FileSource source;
|
||
uintptr_t handle;
|
||
uint32_t size, received, file_id, segment;
|
||
uint64_t serial, op8_ms, progress_ms;
|
||
bool occupied, op8_sent, progress_valid;
|
||
} FileWrite;
|
||
|
||
/* 三种近期记录都只保存值,不保留站点指针或应用handle。
|
||
* recent_read用于末段后op6统计,silent_write用于健康Cancel后一次失败反馈;
|
||
* empty_write的ready表示COMMIT已有结果,pending表示对应终结确认尚未交出。 */
|
||
typedef struct {
|
||
FileSource source;
|
||
uint64_t serial;
|
||
uint32_t file_id;
|
||
uint8_t result;
|
||
bool valid, ready, pending;
|
||
} FileRecent;
|
||
|
||
struct IEC104_FileService {
|
||
IEC104_Slave_t *slave;
|
||
IEC104_FileServiceConfig_t config;
|
||
IEC104_FileServiceStatus_t status;
|
||
IEC104_SlaveEventIdentity_t session, fault_identity;
|
||
uint64_t instance_id, next_reply, next_write, next_finish; /* 实例身份、回复排序、写归属、收尾排序各自独立。 */
|
||
FileTask tasks[IEC104_FILE_SERVICE_TASK_CAPACITY], activation;
|
||
unsigned order[IEC104_FILE_SERVICE_TASK_CAPACITY], task_count; /* FIFO只移动槽下标,不搬动持有资源的记录。 */
|
||
FileSegment segments[IEC104_FILE_SERVICE_SEGMENT_CAPACITY];
|
||
unsigned segment_head, segment_count;
|
||
FileConfirm confirms[IEC104_FILE_SERVICE_CONFIRM_CAPACITY];
|
||
FileDirectory directory;
|
||
FileRead reader;
|
||
FileWrite writer;
|
||
FileFinish read_finish, write_finish[2]; /* 前次COMMIT暂缓时允许后一次写打开,故写收尾上界为2。 */
|
||
FileRecent recent_read, silent_write, empty_write;
|
||
uint8_t buffer[249]; /* 本次组帧/包装共用,正常目录和读帧WAIT后不保留其数据。 */
|
||
bool in_use, in_callback, close_attempted, fault_ended;
|
||
};
|
||
typedef char FileService_Storage_Check[(IEC104_FILE_SERVICE_CAPACITY <= SIZE_MAX / sizeof(IEC104_FileService_t) &&
|
||
IEC104_FILE_SERVICE_TASK_CAPACITY <= SIZE_MAX / sizeof(FileTask) &&
|
||
IEC104_FILE_SERVICE_SEGMENT_CAPACITY <= SIZE_MAX / sizeof(FileSegment) &&
|
||
IEC104_FILE_SERVICE_CONFIRM_CAPACITY <= SIZE_MAX / sizeof(FileConfirm)) ? 1 : -1];
|
||
static IEC104_FileService_t file_pool[IEC104_FILE_SERVICE_CAPACITY];
|
||
static uint64_t next_instance_id;
|
||
|
||
/**
|
||
* 功能:boundary=true表示已知传输边界改变,不再给旧会话保留一次性失败反馈。
|
||
* 输入参数:self——本模块实例。
|
||
* boundary——bool值。
|
||
* 输出参数:self——本模块实例的更新结果。
|
||
* 返回值:无。
|
||
* 说明:否则从打开/待COMMIT会话选最高写序号记录无声结束;已COMMIT或已欠ABORT
|
||
* 不参与。这里只登记收尾,绝不调用应用,也不回滚已经提交的文件。
|
||
*/
|
||
static void Cancel_All(IEC104_FileService_t *self, bool boundary);
|
||
/**
|
||
* 功能:先复制原身份:Cancel_All可能清掉identity所在任务。故障关闭至多一次,
|
||
* 输入参数:self——本模块实例。
|
||
* identity——原会话身份。
|
||
* attempted——bool值。
|
||
* 输出参数:self——本模块实例的更新结果。
|
||
* 返回值:无。
|
||
* 说明:attempted为回复超时已尝试关闭的情况;失败后保留清理责任而不自动重试。
|
||
*/
|
||
static void Fault(IEC104_FileService_t *self, const IEC104_SlaveEventIdentity_t *identity, bool attempted);
|
||
|
||
/**
|
||
* 功能:先按地址定位静态池,再读取in_use;
|
||
* 输入参数:self——本模块实例。
|
||
* 输出参数:无。
|
||
* 返回值:true表示句柄属于当前占用的静态实例槽;NULL、池外地址或未占用槽返回false。
|
||
* 说明:不解引用NULL或外来句柄。
|
||
*/
|
||
static bool Owned(const IEC104_FileService_t *self)
|
||
{
|
||
unsigned i;
|
||
for (i = 0U; i < IEC104_FILE_SERVICE_CAPACITY; ++i) {
|
||
if (self == &file_pool[i]) { return self->in_use; }
|
||
}
|
||
return false;
|
||
}
|
||
|
||
/**
|
||
* 功能:线格式一律小端;
|
||
* 输入参数:p——const uint8_t *所指数据。
|
||
* 输出参数:无。
|
||
* 返回值:返回(uint16_t)((uint16_t)p[0] | ((uint16_t)p[1] << 8))的结果。
|
||
* 说明:这些辅助函数不检查长度,调用者须先证明字段完整可读。
|
||
*/
|
||
static uint16_t Read16(const uint8_t *p)
|
||
{
|
||
return (uint16_t)((uint16_t)p[0] | ((uint16_t)p[1] << 8));
|
||
}
|
||
|
||
/**
|
||
* 功能:从已确认可读的4字节字段解析小端值,不要求地址对齐,也不自行检查报文剩余长度。
|
||
* 输入参数:p——const uint8_t *所指数据。
|
||
* 输出参数:无。
|
||
* 返回值:返回(uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24)的结果。
|
||
* 说明:直接处理传入的p,不经过其他函数调用。
|
||
*/
|
||
static uint32_t Read32(const uint8_t *p)
|
||
{
|
||
return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);
|
||
}
|
||
|
||
/**
|
||
* 功能:将32位值写为4字节小端字段;
|
||
* 输入参数:p——uint8_t *所指数据。
|
||
* value——业务值。
|
||
* 输出参数:p——uint8_t *所指数据的更新结果。
|
||
* 返回值:无。
|
||
* 说明:目标容量由组帧调用方保证。
|
||
*/
|
||
static void Write32(uint8_t *p, uint32_t value)
|
||
{
|
||
p[0] = (uint8_t)value; p[1] = (uint8_t)(value >> 8);
|
||
p[2] = (uint8_t)(value >> 16); p[3] = (uint8_t)(value >> 24);
|
||
}
|
||
|
||
/**
|
||
* 功能:比较Slave指针、实例编号及连接代次三项身份;
|
||
* 输入参数:a——const IEC104_SlaveEventIdentity_t *所指数据。
|
||
* b——const IEC104_SlaveEventIdentity_t *所指数据。
|
||
* 输出参数:无。
|
||
* 返回值:服务指针、实例编号和连接代次三者相同返回true,否则false。
|
||
* 说明:同一CA或重连后的同一指针不足以匹配。
|
||
*/
|
||
static bool Same_Identity(const IEC104_SlaveEventIdentity_t *a, const IEC104_SlaveEventIdentity_t *b)
|
||
{
|
||
return a->slave == b->slave && a->instance_id == b->instance_id && a->generation == b->generation;
|
||
}
|
||
|
||
/**
|
||
* 功能:OA仅用于回显/诊断,不作为授权凭证;
|
||
* 输入参数:a——const FileSource *所指数据。
|
||
* b——const FileSource *所指数据。
|
||
* 输出参数:无。
|
||
* 返回值:返回Same_Identity(&a->identity, &b->identity) && a->station_id == b->station_id && a->ca == b->ca && a->test == b->test的结果。
|
||
* 说明:station_id阻止同CA重注册继承旧会话。
|
||
*/
|
||
static bool Same_Source(const FileSource *a, const FileSource *b)
|
||
{
|
||
return Same_Identity(&a->identity, &b->identity) && a->station_id == b->station_id &&
|
||
a->ca == b->ca && a->test == b->test;
|
||
}
|
||
|
||
/**
|
||
* 功能:单调时钟回退与恰好到达期限均按到期处理;0禁用由Expired/Add_Timer过滤。
|
||
* 输入参数:now——当前时刻。
|
||
* start——uint64_t值。
|
||
* timeout——超时状态。
|
||
* 输出参数:无。
|
||
* 返回值:按处理分支返回0U、timeout - (uint32_t)(now - start)。
|
||
* 说明:先以64位判断差值,再转32位,避免长时间等待时截断成尚未到期。
|
||
*/
|
||
static uint32_t Remaining(uint64_t now, uint64_t start, uint32_t timeout)
|
||
{
|
||
if (now < start || now - start >= timeout) { return 0U; }
|
||
return timeout - (uint32_t)(now - start);
|
||
}
|
||
|
||
/**
|
||
* 功能:timeout=0禁用期限;
|
||
* 输入参数:now——当前时刻。
|
||
* start——uint64_t值。
|
||
* timeout——超时状态。
|
||
* 输出参数:无。
|
||
* 返回值:启用期限且已经到期或单调时钟回退时返回true;期限禁用或尚未到期时返回false。
|
||
* 说明:启用时恰到边界或单调时钟回退均返回到期。
|
||
*/
|
||
static bool Expired(uint64_t now, uint64_t start, uint32_t timeout)
|
||
{
|
||
return timeout != 0U && Remaining(now, start, timeout) == 0U;
|
||
}
|
||
|
||
/**
|
||
* 功能:归还source仍持有的站点引用并清指针,允许重复清理;
|
||
* 输入参数:self——本模块实例。
|
||
* source——源数据。
|
||
* 输出参数:source——源数据的更新结果。
|
||
* 返回值:无。
|
||
* 说明:不负责关闭应用文件句柄。
|
||
*/
|
||
static void Release_Source(IEC104_FileService_t *self, FileSource *source)
|
||
{
|
||
if (source->station != NULL) { (void)IEC104_Slave_Release_Station(self->slave, source->station); source->station = NULL; }
|
||
}
|
||
|
||
/**
|
||
* 功能:序号0留作未分配;
|
||
* 输入参数:self——本模块实例。
|
||
* counter——uint64_t *所指数据。
|
||
* value——业务值。
|
||
* identity——原会话身份。
|
||
* 输出参数:self——本模块实例的更新结果。
|
||
* counter、value——成功时递增并写回同一非零序号;耗尽时二者均不改。
|
||
* 返回值:成功递增计数器并写回新序号返回true;序号耗尽时登记故障并返回false,不回绕。
|
||
* 说明:耗尽不回绕,也不能为了拒绝再申请一个回复序号。
|
||
*/
|
||
static bool Next_Serial(IEC104_FileService_t *self, uint64_t *counter, uint64_t *value,
|
||
const IEC104_SlaveEventIdentity_t *identity)
|
||
{
|
||
if (*counter == UINT64_MAX) {
|
||
++self->status.serial_exhausted;
|
||
Fault(self, identity, false);
|
||
return false;
|
||
}
|
||
*value = ++*counter;
|
||
return true;
|
||
}
|
||
|
||
/**
|
||
* 功能:每次回调从零构造借用请求,操作专用字段随后填写;不能遗留上次name/handle。
|
||
* 输入参数:self——本模块实例。
|
||
* source——源数据。
|
||
* call——IEC104_FileServiceCall_t值。
|
||
* request——请求。
|
||
* 输出参数:request——请求的更新结果。
|
||
* 返回值:无。
|
||
* 说明:identity保持原Slave身份,instance_id则标识本模块实例,两者不得互换。
|
||
*/
|
||
static void Request_From(const IEC104_FileService_t *self, const FileSource *source,
|
||
IEC104_FileServiceCall_t call, IEC104_FileServiceRequest_t *request)
|
||
{
|
||
memset(request, 0, sizeof(*request));
|
||
request->identity = source->identity;
|
||
request->instance_id = self->instance_id;
|
||
request->receive_serial = source->receive_serial;
|
||
request->station_id = source->station_id;
|
||
request->common_address = source->ca;
|
||
request->originator_address = source->oa;
|
||
request->accepted_ms = source->accepted_ms;
|
||
request->test = source->test;
|
||
request->call = call;
|
||
}
|
||
|
||
/**
|
||
* 功能:新组帧采用固定104头,VSQ=1、IOA=0。只有COT7的失败结果置P/N;
|
||
* 输入参数:bytes——字节存储。
|
||
* source——源数据。
|
||
* operation——操作类型。
|
||
* cause——传送原因。
|
||
* result——处理结果。
|
||
* 输出参数:bytes——字节存储的更新结果。
|
||
* 返回值:无。
|
||
* 说明:COT5的数据/兼容确认保持P/N=0。镜像报文错误由Mirror_Error单独处理。
|
||
*/
|
||
static void Prefix(uint8_t *bytes, const FileSource *source, uint8_t operation, uint8_t cause, uint8_t result)
|
||
{
|
||
memset(bytes, 0, 11U);
|
||
bytes[0] = IEC104_FILE_SERVICE_TYPE_ID; bytes[1] = 1U;
|
||
bytes[2] = (uint8_t)(cause | (source->test ? 0x80U : 0U) | (cause == 7U && result != 0U ? 0x40U : 0U));
|
||
bytes[3] = source->oa; bytes[4] = (uint8_t)source->ca; bytes[5] = (uint8_t)(source->ca >> 8);
|
||
bytes[9] = IEC104_FILE_SERVICE_PACKAGE_FILE; bytes[10] = operation;
|
||
}
|
||
|
||
/**
|
||
* 功能:按配置决定回复文件ID:兼容回显模式保留请求值,默认模式统一输出0。
|
||
* 输入参数:self——本模块实例。
|
||
* requested——uint32_t值。
|
||
* 输出参数:无。
|
||
* 返回值:返回self->config.id_mode == IEC104_FILE_SERVICE_ID_ECHO ? requested : 0U的结果。
|
||
* 说明:直接处理传入的self、requested,不经过其他函数调用。
|
||
*/
|
||
static uint32_t Output_Id(const IEC104_FileService_t *self, uint32_t requested)
|
||
{
|
||
return self->config.id_mode == IEC104_FILE_SERVICE_ID_ECHO ? requested : 0U;
|
||
}
|
||
|
||
/**
|
||
* 功能:目录原站引用同时保护回复寿命与应用快照寿命,任一责任未完成都不能释放。
|
||
* 输入参数:self——本模块实例。
|
||
* 输出参数:self——本模块实例的更新结果。
|
||
* 返回值:无。
|
||
* 说明:内部调用:Release_Source、memset。
|
||
*/
|
||
static void Release_Directory(IEC104_FileService_t *self)
|
||
{
|
||
if (self->directory.occupied && !self->directory.task_alive && self->directory.closed) {
|
||
Release_Source(self, &self->directory.source);
|
||
memset(&self->directory, 0, sizeof(self->directory));
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 功能:删除协议任务不等于关闭应用资源;已转给会话/目录的station在此为NULL。
|
||
* 输入参数:self——本模块实例。
|
||
* task——业务任务。
|
||
* 输出参数:self——本模块实例的更新结果。
|
||
* task——业务任务的更新结果。
|
||
* 返回值:无。
|
||
* 说明:目录任务取消后独立清理记录继续保有handle,直到Execute交付关闭。
|
||
*/
|
||
static void Remove_Task(IEC104_FileService_t *self, FileTask *task)
|
||
{
|
||
unsigned i;
|
||
if (task == &self->activation) {
|
||
Release_Source(self, &task->source);
|
||
memset(task, 0, sizeof(*task));
|
||
return;
|
||
}
|
||
for (i = 0U; i < self->task_count; ++i) {
|
||
unsigned index = self->order[i];
|
||
if (task == &self->tasks[index]) {
|
||
if (self->directory.occupied && self->directory.task_alive && self->directory.task_index == index) {
|
||
self->directory.task_alive = false;
|
||
}
|
||
Release_Source(self, &task->source);
|
||
memset(task, 0, sizeof(*task));
|
||
--self->task_count;
|
||
memmove(self->order + i, self->order + i + 1U, (self->task_count - i) * sizeof(self->order[0]));
|
||
Release_Directory(self);
|
||
return;
|
||
}
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 功能:消费非空分段环的队首并清槽;
|
||
* 输入参数:self——本模块实例。
|
||
* 输出参数:self——本模块实例的更新结果。
|
||
* 返回值:无。
|
||
* 说明:调用方先处理其内容,本函数不发送确认或执行写回调。
|
||
*/
|
||
static void Pop_Segment(IEC104_FileService_t *self)
|
||
{
|
||
memset(&self->segments[self->segment_head], 0, sizeof(self->segments[0]));
|
||
self->segment_head = (self->segment_head + 1U) % IEC104_FILE_SERVICE_SEGMENT_CAPACITY;
|
||
--self->segment_count;
|
||
}
|
||
|
||
/**
|
||
* 功能:固定回复形成后直接冻结其完整字节,后续WAIT只重试同一份原文,不再借用回调输出。
|
||
* 输入参数:self——本模块实例。
|
||
* task——业务任务。
|
||
* length——字节长度。
|
||
* 输出参数:self——本模块实例的更新结果。
|
||
* task——业务任务的更新结果。
|
||
* 返回值:!Next_Serial(self, &self->next_reply, &sequence, &task->source.identity)时返回false;其余分支返回false、true。
|
||
* 说明:本槽执行阶段已结束,原请求名等仅在构造回复前使用。
|
||
*/
|
||
static bool Freeze_Task(IEC104_FileService_t *self, FileTask *task, uint16_t length)
|
||
{
|
||
uint64_t sequence;
|
||
if (!Next_Serial(self, &self->next_reply, &sequence, &task->source.identity)) { return false; }
|
||
memcpy(task->bytes, self->buffer, length);
|
||
task->length = length; task->phase = FS_REPLY; task->work.reply.sequence = sequence;
|
||
task->work.reply.formed_ms = FS_NOW(); task->waiting = false;
|
||
return true;
|
||
}
|
||
|
||
/**
|
||
* 功能:镜像完整请求形成否定回复,仅保留原T位并改写P/N及COT;
|
||
* 输入参数:self——本模块实例。
|
||
* task——业务任务。
|
||
* cause——传送原因。
|
||
* 输出参数:self——本模块实例的更新结果。
|
||
* task——业务任务的更新结果。
|
||
* 返回值:返回Freeze_Task(self, task, task->length)的结果。
|
||
* 说明:冻结失败由Freeze_Task报告。
|
||
*/
|
||
static bool Mirror_Error(IEC104_FileService_t *self, FileTask *task, uint8_t cause)
|
||
{
|
||
memcpy(self->buffer, task->bytes, task->length);
|
||
self->buffer[2] = (uint8_t)((self->buffer[2] & 0x80U) | 0x40U | cause);
|
||
return Freeze_Task(self, task, task->length);
|
||
}
|
||
|
||
/**
|
||
* 功能:格式错误仍只能回显完整可读的名称和字段;
|
||
* 输入参数:self——本模块实例。
|
||
* task——业务任务。
|
||
* result——处理结果。
|
||
* 输出参数:self——本模块实例的更新结果。
|
||
* task——业务任务的更新结果。
|
||
* 返回值:按处理分支返回Freeze_Task(self, task, 18U)、Freeze_Task(self, task, (uint16_t)(21U + name_length))。
|
||
* 说明:不能从截短原文臆造指针。
|
||
*/
|
||
static bool Operation_Error(IEC104_FileService_t *self, FileTask *task, uint8_t result)
|
||
{
|
||
uint8_t name_length = 0U, encoded_length = 0U;
|
||
uint32_t id = 0U, size = 0U;
|
||
unsigned position;
|
||
if (task->operation == 1U) {
|
||
uint8_t cause = (task->bytes[2] & 0x3FU) == 5U ? 5U : 7U;
|
||
if (task->length >= 15U) { id = Read32(task->bytes + 11U); }
|
||
Prefix(self->buffer, &task->source, 2U, cause, result);
|
||
self->buffer[11] = result; Write32(self->buffer + 12U, Output_Id(self, id));
|
||
self->buffer[16] = 0U; self->buffer[17] = 0U;
|
||
if (!task->failed) { ++self->status.directory_failures; task->failed = true; }
|
||
return Freeze_Task(self, task, 18U);
|
||
}
|
||
if (task->length >= 12U) {
|
||
encoded_length = task->bytes[11];
|
||
if (encoded_length > 0U && encoded_length <= IEC104_FILE_SERVICE_MAX_FILE_NAME &&
|
||
task->length >= 12U + encoded_length) { name_length = encoded_length; }
|
||
}
|
||
if (task->operation == 7U) {
|
||
position = 12U + encoded_length;
|
||
if (task->length >= position + 4U) { id = Read32(task->bytes + position); }
|
||
if (task->length >= position + 8U) { size = Read32(task->bytes + position + 4U); }
|
||
}
|
||
Prefix(self->buffer, &task->source, task->operation == 7U ? 8U : 4U, 7U, result);
|
||
self->buffer[11] = result; self->buffer[12] = name_length;
|
||
if (name_length != 0U) { memcpy(self->buffer + 13U, task->bytes + 12U, name_length); }
|
||
Write32(self->buffer + 13U + name_length, Output_Id(self, id));
|
||
Write32(self->buffer + 17U + name_length, size);
|
||
return Freeze_Task(self, task, (uint16_t)(21U + name_length));
|
||
}
|
||
|
||
/**
|
||
* 功能:登记目录关闭责任及先后序号,不在协议推进路径调用应用CLOSE_DIRECTORY。
|
||
* 输入参数:self——本模块实例。
|
||
* reason——原因。
|
||
* 输出参数:self——本模块实例的更新结果。
|
||
* 返回值:即使序号耗尽返回false,快照仍保留给后续Execute清理。
|
||
* 说明:重复关闭不改变第一次原因;即使序号耗尽返回false,快照仍保留给后续Execute清理。
|
||
*/
|
||
static bool Close_Directory(IEC104_FileService_t *self, IEC104_FileServiceEndReason_t reason)
|
||
{
|
||
FileDirectory *directory = &self->directory;
|
||
if (!directory->occupied || directory->closing || directory->closed) { return true; }
|
||
/* 先固定清理责任,编号耗尽触发的Fault也不能丢失成功OPEN的资源。 */
|
||
directory->closing = true; directory->reason = reason;
|
||
if (!Next_Serial(self, &self->next_finish, &directory->finish_sequence, &directory->source.identity)) {
|
||
directory->finish_sequence = UINT64_MAX;
|
||
return false;
|
||
}
|
||
return true;
|
||
}
|
||
|
||
/**
|
||
* 功能:把活动读的句柄、站点引用和已接手字节进度转交收尾槽,实际CLOSE_READ由Execute交付。
|
||
* 输入参数:self——本模块实例。
|
||
* reason——原因。
|
||
* 输出参数:self——本模块实例的更新结果。
|
||
* 返回值:!reader->occupied时返回true;其余分支返回true、false。
|
||
* 说明:清空活动读后仍保留不持有站点引用的最近来源,仅用于识别迟到op6,不允许它重新开启发送。
|
||
*/
|
||
static bool End_Read(IEC104_FileService_t *self, IEC104_FileServiceEndReason_t reason)
|
||
{
|
||
FileRead *reader = &self->reader;
|
||
FileFinish *finish = &self->read_finish;
|
||
if (!reader->occupied) { return true; }
|
||
if (finish->occupied) { Fault(self, &reader->source.identity, false); return false; }
|
||
memset(finish, 0, sizeof(*finish));
|
||
finish->occupied = true; finish->source = reader->source; reader->source.station = NULL;
|
||
finish->call = IEC104_FILE_SERVICE_CALL_CLOSE_READ; finish->reason = reason;
|
||
finish->handle = reader->handle; finish->size = reader->size; finish->transferred = reader->offset;
|
||
self->recent_read.source = finish->source; self->recent_read.source.station = NULL;
|
||
self->recent_read.valid = true;
|
||
if (reason != IEC104_FILE_SERVICE_END_COMPLETE) { ++self->status.reads_aborted; }
|
||
memset(reader, 0, sizeof(*reader));
|
||
if (!Next_Serial(self, &self->next_finish, &finish->sequence, &finish->source.identity)) {
|
||
finish->sequence = UINT64_MAX;
|
||
return false;
|
||
}
|
||
return true;
|
||
}
|
||
|
||
/**
|
||
* 功能:EACH可丢最旧非末段READY确认,COMMIT预留和终结结果始终受保护。
|
||
* 输入参数:self——本模块实例。
|
||
* source——源数据。
|
||
* serial——流水号。
|
||
* file_id——身份编号。
|
||
* segment——uint32_t值。
|
||
* result——处理结果。
|
||
* terminal——bool值。
|
||
* reserved——bool值。
|
||
* 输出参数:self——本模块实例的更新结果。
|
||
* 返回值: 此处即固定形成序号/时刻,COMMIT返回只填结果,不重新申请或延长期限。
|
||
* 说明:终结槽仍无法取得意味着容量不变量被破坏,必须faulted,不能丢最终结果。
|
||
* 此处即固定形成序号/时刻,COMMIT返回只填结果,不重新申请或延长期限。
|
||
*/
|
||
static FileConfirm *Reserve_Confirm(IEC104_FileService_t *self, const FileSource *source,
|
||
uint64_t serial, uint32_t file_id, uint32_t segment, uint8_t result, bool terminal, bool reserved)
|
||
{
|
||
FileConfirm *slot = NULL, *oldest = NULL;
|
||
unsigned i;
|
||
uint64_t sequence;
|
||
for (i = 0U; i < IEC104_FILE_SERVICE_CONFIRM_CAPACITY; ++i) {
|
||
FileConfirm *item = &self->confirms[i];
|
||
if (!item->occupied && slot == NULL) { slot = item; }
|
||
if (item->occupied && !item->terminal && !item->reserved &&
|
||
(oldest == NULL || item->sequence < oldest->sequence)) { oldest = item; }
|
||
}
|
||
if (slot == NULL) {
|
||
if (oldest != NULL) { slot = oldest; ++self->status.dropped_replies; }
|
||
else if (!terminal) { ++self->status.dropped_replies; return NULL; }
|
||
else { Fault(self, &source->identity, false); return NULL; }
|
||
}
|
||
if (!Next_Serial(self, &self->next_reply, &sequence, &source->identity)) { return NULL; }
|
||
memset(slot, 0, sizeof(*slot));
|
||
slot->occupied = true; slot->terminal = terminal; slot->reserved = reserved;
|
||
slot->source = *source; slot->source.station = NULL;
|
||
slot->write_serial = serial; slot->sequence = sequence; slot->formed_ms = FS_NOW();
|
||
Prefix(slot->bytes, source, 10U, self->config.write_confirm_cause, result);
|
||
Write32(slot->bytes + 11U, Output_Id(self, file_id));
|
||
Write32(slot->bytes + 15U, segment); slot->bytes[19] = result;
|
||
return slot;
|
||
}
|
||
|
||
/**
|
||
* 功能:转移引用和handle后立即清空writer,后续段不能再写已终结会话。
|
||
* 输入参数:self——本模块实例。
|
||
* call——IEC104_FileServiceCall_t值。
|
||
* reason——原因。
|
||
* 输出参数:self——本模块实例的更新结果。
|
||
* 返回值:按处理分支返回NULL、finish。
|
||
* 说明:先保留清理责任再分配排序号,序号耗尽也必须能交付ABORT。
|
||
*/
|
||
static FileFinish *Move_Write_To_Finish(IEC104_FileService_t *self,
|
||
IEC104_FileServiceCall_t call, IEC104_FileServiceEndReason_t reason)
|
||
{
|
||
FileWrite *writer = &self->writer;
|
||
FileFinish *finish = NULL;
|
||
unsigned i;
|
||
for (i = 0U; i < 2U; ++i) { if (!self->write_finish[i].occupied) { finish = &self->write_finish[i]; break; } }
|
||
if (finish == NULL) { Fault(self, &writer->source.identity, false); return NULL; }
|
||
memset(finish, 0, sizeof(*finish));
|
||
finish->occupied = true; finish->source = writer->source; writer->source.station = NULL;
|
||
finish->call = call; finish->reason = reason; finish->handle = writer->handle;
|
||
finish->size = writer->size; finish->transferred = writer->received;
|
||
finish->file_id = writer->file_id; finish->write_serial = writer->serial;
|
||
memset(writer, 0, sizeof(*writer));
|
||
if (!Next_Serial(self, &self->next_finish, &finish->sequence, &finish->source.identity)) {
|
||
finish->sequence = UINT64_MAX;
|
||
return NULL;
|
||
}
|
||
return finish;
|
||
}
|
||
|
||
/**
|
||
* 功能:错误/超时先冻结终结确认,随后只欠一次ABORT。
|
||
* 输入参数:self——本模块实例。
|
||
* result——处理结果。
|
||
* segment——uint32_t值。
|
||
* reason——原因。
|
||
* 输出参数:self——本模块实例的更新结果。
|
||
* 返回值:!writer->occupied时返回true;Reserve_Confirm(self, &writer->source, writer->serial, writer->file_id, segment, result, true, false) == NULL时返回false;Move_Write_To_Finish(self, IEC104_FILE_SERVICE_CALL_ABORT_WRITE, reason) == NULL时返回false;其余分支返回true、false。
|
||
* 说明:TEST直接结束协议会话。
|
||
*/
|
||
static bool Fail_Write(IEC104_FileService_t *self, uint8_t result,
|
||
uint32_t segment, IEC104_FileServiceEndReason_t reason)
|
||
{
|
||
FileWrite *writer = &self->writer;
|
||
if (!writer->occupied) { return true; }
|
||
if (Reserve_Confirm(self, &writer->source, writer->serial, writer->file_id, segment, result, true, false) == NULL) { return false; }
|
||
++self->status.writes_failed;
|
||
if (writer->source.test) { Release_Source(self, &writer->source); memset(writer, 0, sizeof(*writer)); }
|
||
else if (Move_Write_To_Finish(self, IEC104_FILE_SERVICE_CALL_ABORT_WRITE, reason) == NULL) { return false; }
|
||
return true;
|
||
}
|
||
|
||
/**
|
||
* 功能:保存最高序号的未提交写归属;
|
||
* 输入参数:self——本模块实例。
|
||
* source——源数据。
|
||
* serial——流水号。
|
||
* id——标识。
|
||
* 输出参数:self——本模块实例的更新结果。
|
||
* 返回值:无。
|
||
* 说明:重复Cancel不能用较旧清理覆盖这个标记。
|
||
*/
|
||
static void Remember_Silent(IEC104_FileService_t *self, const FileSource *source, uint64_t serial, uint32_t id)
|
||
{
|
||
if (!self->silent_write.valid || serial > self->silent_write.serial) {
|
||
memset(&self->silent_write, 0, sizeof(self->silent_write));
|
||
self->silent_write.valid = true; self->silent_write.source = *source;
|
||
self->silent_write.source.station = NULL; self->silent_write.serial = serial; self->silent_write.file_id = id;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 功能:boundary=true表示已知传输边界改变,不再给旧会话保留一次性失败反馈。
|
||
* 输入参数:self——本模块实例。
|
||
* boundary——bool值。
|
||
* 输出参数:self——本模块实例的更新结果。
|
||
* 返回值:无。
|
||
* 说明:否则从打开/待COMMIT会话选最高写序号记录无声结束;已COMMIT或已欠ABORT
|
||
* 不参与。这里只登记收尾,绝不调用应用,也不回滚已经提交的文件。
|
||
*/
|
||
static void Cancel_All(IEC104_FileService_t *self, bool boundary)
|
||
{
|
||
unsigned i;
|
||
if (self->directory.occupied) { (void)Close_Directory(self, IEC104_FILE_SERVICE_END_CANCELLED); }
|
||
if (self->reader.occupied) { (void)End_Read(self, IEC104_FILE_SERVICE_END_CANCELLED); }
|
||
if (self->writer.occupied) {
|
||
if (!boundary) { Remember_Silent(self, &self->writer.source, self->writer.serial, self->writer.file_id); }
|
||
if (self->writer.source.test) { Release_Source(self, &self->writer.source); memset(&self->writer, 0, sizeof(self->writer)); }
|
||
else { (void)Move_Write_To_Finish(self, IEC104_FILE_SERVICE_CALL_ABORT_WRITE, IEC104_FILE_SERVICE_END_CANCELLED); }
|
||
}
|
||
for (i = 0U; i < 2U; ++i) {
|
||
FileFinish *finish = &self->write_finish[i];
|
||
if (finish->occupied && finish->call == IEC104_FILE_SERVICE_CALL_COMMIT) {
|
||
if (!boundary) { Remember_Silent(self, &finish->source, finish->write_serial, finish->file_id); }
|
||
finish->call = IEC104_FILE_SERVICE_CALL_ABORT_WRITE;
|
||
finish->reason = IEC104_FILE_SERVICE_END_CANCELLED; ++self->status.commits_cancelled;
|
||
}
|
||
}
|
||
while (self->task_count != 0U) { ++self->status.cancelled; Remove_Task(self, &self->tasks[self->order[0]]); }
|
||
if (self->activation.occupied) { ++self->status.cancelled; Remove_Task(self, &self->activation); }
|
||
while (self->segment_count != 0U) { ++self->status.cancelled; Pop_Segment(self); }
|
||
memset(self->confirms, 0, sizeof(self->confirms));
|
||
memset(&self->recent_read, 0, sizeof(self->recent_read));
|
||
memset(&self->empty_write, 0, sizeof(self->empty_write));
|
||
if (boundary) { memset(&self->silent_write, 0, sizeof(self->silent_write)); }
|
||
}
|
||
|
||
/**
|
||
* 功能:原连接已关闭、已断开或代次过期都表示关闭义务结束;
|
||
* 输入参数:result——处理结果。
|
||
* 输出参数:无。
|
||
* 返回值:返回result == IEC104_TCP_OK || result == IEC104_TCP_NOT_CONNECTED || result == IEC104_TCP_STALE_GENERATION的结果。
|
||
* 说明:其他结果仍按关闭错误处理。
|
||
*/
|
||
static bool Closed_Result(IEC104_TcpResult_t result)
|
||
{
|
||
return result == IEC104_TCP_OK || result == IEC104_TCP_NOT_CONNECTED || result == IEC104_TCP_STALE_GENERATION;
|
||
}
|
||
|
||
/**
|
||
* 功能:先复制原身份:Cancel_All可能清掉identity所在任务。故障关闭至多一次,
|
||
* 输入参数:self——本模块实例。
|
||
* identity——原会话身份。
|
||
* attempted——bool值。
|
||
* 输出参数:self——本模块实例的更新结果。
|
||
* 返回值:无。
|
||
* 说明:attempted为回复超时已尝试关闭的情况;失败后保留清理责任而不自动重试。
|
||
*/
|
||
static void Fault(IEC104_FileService_t *self, const IEC104_SlaveEventIdentity_t *identity, bool attempted)
|
||
{
|
||
IEC104_SlaveEventIdentity_t original = *identity;
|
||
/* 已置faulted时只保留最初故障,避免清理中的内部错误递归重进取消/关闭。 */
|
||
if (self->status.faulted) { return; }
|
||
self->status.faulted = true; self->fault_identity = original; self->close_attempted = attempted;
|
||
Cancel_All(self, false);
|
||
if (!self->close_attempted) {
|
||
IEC104_TcpResult_t result;
|
||
self->close_attempted = true;
|
||
result = FS_CLOSE(self->slave, &self->fault_identity, NULL);
|
||
if (Closed_Result(result)) { self->fault_ended = true; }
|
||
else { ++self->status.close_errors; }
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 功能:查询原请求身份并同步通知等待状态;WAIT_EVENTS只暂停业务,不丢请求也不刷新期限。
|
||
* 输入参数:self——本模块实例。
|
||
* identity——原会话身份。
|
||
* 输出参数:self——本模块实例的更新结果。
|
||
* 返回值:两种路径都可能清空identity所在任务,返回后须先按状态分支。
|
||
* 说明:ERROR转故障收尾,STALE取消旧会话;两种路径都可能清空identity所在任务,返回后须先按状态分支。
|
||
*/
|
||
static IEC104_SlaveRequestState_t Check(IEC104_FileService_t *self, const IEC104_SlaveEventIdentity_t *identity)
|
||
{
|
||
IEC104_SlaveRequestState_t state = FS_CHECK(self->slave, identity);
|
||
self->status.events_pending = state == IEC104_SLAVE_REQUEST_WAIT_EVENTS;
|
||
if (state == IEC104_SLAVE_REQUEST_ERROR) { Fault(self, identity, false); }
|
||
else if (state == IEC104_SLAVE_REQUEST_STALE) { Cancel_All(self, true); self->status.active = false; }
|
||
return state;
|
||
}
|
||
|
||
/**
|
||
* 功能:只用于HIGH提交ERROR:完整原身份、健康连接及已停传输且有未读通知须同时成立。
|
||
* 输入参数:self——本模块实例。
|
||
* identity——原会话身份。
|
||
* 输出参数:无。
|
||
* 返回值:仅原会话仍健康、传输已停止且存在待消费通知时返回true;其他情况返回false。
|
||
* 说明:FATAL和IDLE故障不适用;仅有未读通知不能证明错误来自尚未分派的STOP。
|
||
*/
|
||
static bool Defer_For_Stop(IEC104_FileService_t *self, const IEC104_SlaveEventIdentity_t *identity)
|
||
{
|
||
IEC104_TcpServerStatus_t status;
|
||
return Same_Identity(identity, &self->session) && identity->slave == self->slave &&
|
||
FS_STATUS(self->slave, &status, NULL) == IEC104_TCP_OK && status.generation == identity->generation &&
|
||
status.connected && status.connection_status_valid && status.asdu_queue_status_valid &&
|
||
status.connection.phase == IEC104_TCP_SESSION_ACTIVE && status.connection.fault == IEC104_TCP_FAULT_NONE &&
|
||
!status.connection.data_transfer_started && status.pending_event_count != 0U;
|
||
}
|
||
|
||
/**
|
||
* 功能:1已接手,0等待,-1故障。
|
||
* 输入参数:self——本模块实例。
|
||
* source——源数据。
|
||
* bytes——字节存储。
|
||
* length——字节长度。
|
||
* negative——否定确认标志。
|
||
* idle——bool值。
|
||
* ticket——应答交接票据。
|
||
* 输出参数:self——本模块实例的更新结果。
|
||
* 返回值:按处理分支返回-1、1、0。
|
||
* 说明:故障后可能清空调用者的任务,不能再解引用它。
|
||
*/
|
||
static int Send(IEC104_FileService_t *self, const FileSource *source, const uint8_t *bytes,
|
||
uint16_t length, bool negative, bool idle, uint64_t *ticket)
|
||
{
|
||
IEC60870_Asdu_t asdu;
|
||
IEC104_TcpSubmitResult_t result;
|
||
IEC104_SlaveEventIdentity_t identity = source->identity;
|
||
if (bytes != self->buffer) { memcpy(self->buffer, bytes, length); }
|
||
if (IEC60870_Asdu_Create_From_Buffer(&asdu, IEC104_Slave_Get_Application_Layer_Parameters(self->slave),
|
||
self->buffer, length) != IEC60870_ASDU_OK) { Fault(self, &identity, false); return -1; }
|
||
result = idle ? FS_IDLE_SEND(self->slave, &identity, &asdu, self->config.window_reserve) :
|
||
FS_SEND(self->slave, &identity, &asdu, ticket);
|
||
if (result == IEC104_TCP_SUBMIT_OK) {
|
||
++self->status.submitted; if (negative) { ++self->status.negative_submitted; }
|
||
return 1;
|
||
}
|
||
if (result == IEC104_TCP_SUBMIT_WAIT) {
|
||
if (idle) { ++self->status.idle_waits; } else { ++self->status.waits; }
|
||
return 0;
|
||
}
|
||
++self->status.send_errors;
|
||
if (!idle && result == IEC104_TCP_SUBMIT_ERROR && Defer_For_Stop(self, &identity)) {
|
||
self->status.events_pending = true; return 0;
|
||
}
|
||
Fault(self, &identity, false);
|
||
return -1;
|
||
}
|
||
|
||
/**
|
||
* 功能:固定回复跨三条存储路径按形成序号排序。RESERVED_COMMIT占实际槽,
|
||
* 输入参数:self——本模块实例。
|
||
* task——业务任务。
|
||
* confirm——const FileConfirm **所指数据。
|
||
* 输出参数:task、confirm——分别指向最早回复的任务或确认槽,另一项置NULL;无回复时均置NULL。
|
||
* 返回值:最早待交接回复的形成序号;没有已分配序号的回复时返回0。
|
||
* 说明:因而会挡住下一写激活确认;不能越过它提交任何较晚确认。
|
||
*/
|
||
static uint64_t Oldest_Reply(const IEC104_FileService_t *self, const FileTask **task, const FileConfirm **confirm)
|
||
{
|
||
uint64_t sequence = 0U;
|
||
unsigned i;
|
||
*task = NULL; *confirm = NULL;
|
||
for (i = 0U; i < self->task_count; ++i) {
|
||
const FileTask *item = &self->tasks[self->order[i]];
|
||
if (item->phase == FS_REPLY && (sequence == 0U || item->work.reply.sequence < sequence)) {
|
||
sequence = item->work.reply.sequence; *task = item;
|
||
}
|
||
}
|
||
if (self->activation.occupied && self->activation.phase == FS_REPLY &&
|
||
(sequence == 0U || self->activation.work.reply.sequence < sequence)) {
|
||
sequence = self->activation.work.reply.sequence; *task = &self->activation;
|
||
}
|
||
for (i = 0U; i < IEC104_FILE_SERVICE_CONFIRM_CAPACITY; ++i) {
|
||
const FileConfirm *item = &self->confirms[i];
|
||
if (item->occupied && (sequence == 0U || item->sequence < sequence)) {
|
||
sequence = item->sequence; *task = NULL; *confirm = item;
|
||
}
|
||
}
|
||
return sequence;
|
||
}
|
||
|
||
/**
|
||
* 功能:查询所有回复路径是否存在已分配序号,含预留COMMIT确认;
|
||
* 输入参数:self——本模块实例。
|
||
* 输出参数:无。
|
||
* 返回值:返回Oldest_Reply(self, &task, &confirm) != 0U的结果。
|
||
* 说明:有回复不代表立即可提交。
|
||
*/
|
||
static bool Has_Reply(const IEC104_FileService_t *self)
|
||
{
|
||
const FileTask *task;
|
||
const FileConfirm *confirm;
|
||
return Oldest_Reply(self, &task, &confirm) != 0U;
|
||
}
|
||
|
||
/**
|
||
* 功能:op4/op8提交OK(入HIGH或直接交接)才启动读间隔/写进度计时,不等待链路ACK。
|
||
* 输入参数:self——本模块实例。
|
||
* task——业务任务。
|
||
* ticket——应答交接票据。
|
||
* 输出参数:self——本模块实例的更新结果。
|
||
* task——业务任务的更新结果。
|
||
* 返回值:无。
|
||
* 说明:op4的PENDING等待计入该读期限;较低等级暂未获发送机会不能暂停计时或重置progress_ms。
|
||
* op8对应会话可能已经写完并转入COMMIT,此时无需再启动活动写计时器。
|
||
*/
|
||
static void Task_Sent(IEC104_FileService_t *self, FileTask *task, uint64_t ticket)
|
||
{
|
||
if (task == &self->activation) {
|
||
if (self->writer.occupied && self->writer.serial == task->work.reply.write_serial) {
|
||
self->writer.op8_sent = true; self->writer.op8_ms = FS_NOW();
|
||
}
|
||
} else if (task->operation == 3U && task->length >= 12U && task->bytes[11] == 0U &&
|
||
self->reader.occupied && self->reader.phase == FS_READ_OPEN &&
|
||
self->reader.source.receive_serial == task->source.receive_serial &&
|
||
Same_Source(&self->reader.source, &task->source)) {
|
||
self->reader.phase = FS_READ_DATA; self->reader.progress_ms = FS_NOW();
|
||
self->reader.confirmation_ticket = ticket;
|
||
}
|
||
if (self->directory.occupied && self->directory.task_alive &&
|
||
task == &self->tasks[self->directory.task_index]) {
|
||
++self->status.directory_frames; ++self->status.directories;
|
||
if (!self->directory.closed) { task->phase = FS_DIRECTORY_DONE; return; }
|
||
} else if (task->operation == 1U && task->length >= 18U && task->bytes[10] == 2U) {
|
||
++self->status.directory_frames; ++self->status.directories;
|
||
}
|
||
Remove_Task(self, task);
|
||
}
|
||
|
||
/**
|
||
* 功能:提交循环只发送固定字节,不执行应用;每次成功移除一条待发回复,
|
||
* 输入参数:self——本模块实例。
|
||
* 输出参数:self——本模块实例的更新结果。
|
||
* 返回值:按处理分支返回1、0、-1、self->status.faulted ? -1 : 1。
|
||
* 说明:但目录任务槽可能仍须等关闭回调。循环预算覆盖本轮全部固定回复位置。
|
||
* 请求FIFO中的应用动作仍严格只执行队首,错误回复则服从统一形成序号。
|
||
*/
|
||
static int Flush_Replies(IEC104_FileService_t *self)
|
||
{
|
||
unsigned budget = IEC104_FILE_SERVICE_TASK_CAPACITY + IEC104_FILE_SERVICE_CONFIRM_CAPACITY + 2U;
|
||
while (budget-- != 0U && !self->status.faulted) {
|
||
const FileTask *found_task;
|
||
const FileConfirm *found_confirm;
|
||
FileTask *task;
|
||
FileConfirm *confirm;
|
||
const FileSource *source;
|
||
IEC104_SlaveRequestState_t state;
|
||
uint64_t ticket = 0U;
|
||
int sent;
|
||
if (Oldest_Reply(self, &found_task, &found_confirm) == 0U) { return 1; }
|
||
if (found_confirm != NULL && found_confirm->reserved) { return 0; }
|
||
task = (FileTask *)found_task; confirm = (FileConfirm *)found_confirm;
|
||
source = task != NULL ? &task->source : &confirm->source;
|
||
state = Check(self, &source->identity);
|
||
if (state == IEC104_SLAVE_REQUEST_ERROR) { return -1; }
|
||
if (state != IEC104_SLAVE_REQUEST_READY) { return 0; }
|
||
if (task != NULL) {
|
||
bool negative = (task->bytes[2] & 0x40U) != 0U ||
|
||
(task->length >= 12U && task->bytes[10] == 2U && task->bytes[11] != 0U);
|
||
sent = Send(self, &task->source, task->bytes, task->length, negative, false, &ticket);
|
||
if (sent < 0) { return -1; }
|
||
task->waiting = sent == 0;
|
||
if (sent == 0) { return 0; }
|
||
Task_Sent(self, task, ticket);
|
||
} else {
|
||
sent = Send(self, &confirm->source, confirm->bytes, 20U, confirm->bytes[19] != 0U, false, NULL);
|
||
if (sent < 0) { return -1; }
|
||
confirm->waiting = sent == 0;
|
||
if (sent == 0) { return 0; }
|
||
if (self->empty_write.valid && self->empty_write.serial == confirm->write_serial) { self->empty_write.pending = false; }
|
||
memset(confirm, 0, sizeof(*confirm));
|
||
}
|
||
}
|
||
return self->status.faulted ? -1 : 1;
|
||
}
|
||
|
||
/**
|
||
* 功能:从扫描转入固定错误末帧,同时登记关闭快照;之后只重试冻结回复,不再list。
|
||
* 输入参数:self——本模块实例。
|
||
* reason——原因。
|
||
* 输出参数:self——本模块实例的更新结果。
|
||
* 返回值:!directory->occupied || !directory->task_alive时返回true;task->phase != FS_DIRECTORY时返回true;!Operation_Error(self, task, 1U)时返回false;其余分支返回true、false、Close_Directory(self, reason)。
|
||
* 说明:错误帧不含本轮尚未交出的条目,回复期限从冻结时重新独立起算。
|
||
*/
|
||
static bool Directory_Failed(IEC104_FileService_t *self, IEC104_FileServiceEndReason_t reason)
|
||
{
|
||
FileDirectory *directory = &self->directory;
|
||
FileTask *task;
|
||
if (!directory->occupied || !directory->task_alive) { return true; }
|
||
task = &self->tasks[directory->task_index];
|
||
if (task->phase != FS_DIRECTORY) { return true; }
|
||
if (!Operation_Error(self, task, 1U)) { return false; }
|
||
return Close_Directory(self, reason);
|
||
}
|
||
|
||
/**
|
||
* 功能:BUSY允许在op8交出前先写暂存,所以取确认接手与成功非空写入中较晚的时刻。
|
||
* 输入参数:writer——日志写入回调。
|
||
* 输出参数:无。
|
||
* 返回值:返回writer->progress_valid && writer->progress_ms > writer->op8_ms ? writer->progress_ms : writer->op8_ms的结果。
|
||
* 说明:新段入环、零长度段和不匹配归属均不能刷新这个起点。
|
||
*/
|
||
static uint64_t Write_Progress(const FileWrite *writer)
|
||
{
|
||
return writer->progress_valid && writer->progress_ms > writer->op8_ms ? writer->progress_ms : writer->op8_ms;
|
||
}
|
||
|
||
/**
|
||
* 功能:回复期限从形成时起算,包括未到队首及尚未执行COMMIT的预留槽。
|
||
* 输入参数:self——本模块实例。
|
||
* source——源数据。
|
||
* reserved_serial——顺序编号。
|
||
* 输出参数:self——本模块实例的更新结果。
|
||
* 返回值:原连接关闭义务已结束并完成取消返回true;关闭失败时登记故障并返回false。
|
||
* 说明:关闭前把预留COMMIT改为TIMEOUT收尾,随后取消不得改写这个首个原因。
|
||
*/
|
||
static bool Reply_Timeout(IEC104_FileService_t *self, const FileSource *source, uint64_t reserved_serial)
|
||
{
|
||
IEC104_SlaveEventIdentity_t identity = source->identity;
|
||
IEC104_TcpResult_t result;
|
||
unsigned i;
|
||
++self->status.reply_timeouts;
|
||
if (reserved_serial != 0U) {
|
||
for (i = 0U; i < 2U; ++i) {
|
||
FileFinish *finish = &self->write_finish[i];
|
||
if (finish->occupied && finish->write_serial == reserved_serial && finish->call == IEC104_FILE_SERVICE_CALL_COMMIT) {
|
||
finish->call = IEC104_FILE_SERVICE_CALL_ABORT_WRITE;
|
||
finish->reason = IEC104_FILE_SERVICE_END_TIMEOUT; ++self->status.commits_cancelled;
|
||
}
|
||
}
|
||
}
|
||
result = FS_CLOSE(self->slave, &identity, NULL);
|
||
if (!Closed_Result(result)) {
|
||
++self->status.close_errors; Fault(self, &identity, true); return false;
|
||
}
|
||
Cancel_All(self, true); self->status.active = false;
|
||
return true;
|
||
}
|
||
|
||
/**
|
||
* 功能:-1新故障,0无变化,1发生确定的本地推进。Execute不能把纯超时清理报成EMPTY,
|
||
* 输入参数:self——本模块实例。
|
||
* 输出参数:self——本模块实例的更新结果。
|
||
* 返回值:按处理分支返回0、Reply_Timeout(self, &task->source, 0U) ? 1 : -1、Reply_Timeout(self, &self->activation.source, 0U) ? 1 : -1、Reply_Timeout(self, &confirm->source, confirm->reserved ? confirm->write_serial : 0U) ? 1 : -1、-1、changed。
|
||
* 说明:否则保留事件的BUSY循环会把已腾出槽误认为没有进展。
|
||
*/
|
||
static int Expire(IEC104_FileService_t *self)
|
||
{
|
||
uint64_t now = FS_NOW();
|
||
unsigned i;
|
||
int changed = 0;
|
||
if (self->status.faulted) { return 0; }
|
||
/* 回复从形成就计时,检查全部固定回复及预留槽;不能仅检查最早一条。 */
|
||
for (i = 0U; i < self->task_count; ++i) {
|
||
FileTask *task = &self->tasks[self->order[i]];
|
||
if (task->phase == FS_REPLY && Expired(now, task->work.reply.formed_ms, self->config.reply_timeout_ms)) {
|
||
return Reply_Timeout(self, &task->source, 0U) ? 1 : -1;
|
||
}
|
||
}
|
||
if (self->activation.occupied && self->activation.phase == FS_REPLY &&
|
||
Expired(now, self->activation.work.reply.formed_ms, self->config.reply_timeout_ms)) {
|
||
return Reply_Timeout(self, &self->activation.source, 0U) ? 1 : -1;
|
||
}
|
||
for (i = 0U; i < IEC104_FILE_SERVICE_CONFIRM_CAPACITY; ++i) {
|
||
FileConfirm *confirm = &self->confirms[i];
|
||
if (confirm->occupied && Expired(now, confirm->formed_ms, self->config.reply_timeout_ms)) {
|
||
return Reply_Timeout(self, &confirm->source, confirm->reserved ? confirm->write_serial : 0U) ? 1 : -1;
|
||
}
|
||
}
|
||
if (self->directory.occupied && self->directory.task_alive && !self->directory.closing && !self->directory.closed &&
|
||
Expired(now, self->directory.opened_ms, self->config.directory_timeout_ms)) {
|
||
++self->status.directory_timeouts;
|
||
if (!Directory_Failed(self, IEC104_FILE_SERVICE_END_TIMEOUT)) { return -1; }
|
||
changed = 1;
|
||
}
|
||
if (self->reader.occupied && self->reader.phase == FS_READ_DATA &&
|
||
Expired(now, self->reader.progress_ms, self->config.read_idle_timeout_ms)) {
|
||
++self->status.read_timeouts;
|
||
if (!End_Read(self, IEC104_FILE_SERVICE_END_TIMEOUT)) { return -1; }
|
||
changed = 1;
|
||
}
|
||
if (self->writer.occupied && self->writer.op8_sent &&
|
||
Expired(now, Write_Progress(&self->writer), self->config.write_idle_timeout_ms)) {
|
||
++self->status.write_timeouts;
|
||
if (!Fail_Write(self, 1U, self->writer.segment, IEC104_FILE_SERVICE_END_TIMEOUT)) { return -1; }
|
||
changed = 1;
|
||
}
|
||
if (self->activation.occupied && self->activation.phase == FS_EXECUTE &&
|
||
Expired(now, self->activation.source.accepted_ms, self->config.execute_timeout_ms)) {
|
||
++self->status.timeouts;
|
||
if (!Operation_Error(self, &self->activation, 1U)) { return -1; }
|
||
changed = 1;
|
||
}
|
||
/* 读请求的执行期限只处理FIFO队首,后方超时不提前越序形成回复。 */
|
||
if (self->task_count != 0U) {
|
||
FileTask *task = &self->tasks[self->order[0]];
|
||
if (task->phase == FS_EXECUTE && Expired(now, task->source.accepted_ms, self->config.execute_timeout_ms)) {
|
||
++self->status.timeouts;
|
||
if (!Operation_Error(self, task, 1U)) { return -1; }
|
||
changed = 1;
|
||
}
|
||
}
|
||
return changed;
|
||
}
|
||
|
||
/**
|
||
* 功能:只按日历分量比较,忽略星期/SU;
|
||
* 输入参数:a——const IEC60870_CP56Time2a_t *所指数据。
|
||
* b——const IEC60870_CP56Time2a_t *所指数据。
|
||
* 输出参数:无。
|
||
* 返回值:按处理分支返回a->time.field < b->time.field ? -1 : 1、0。
|
||
* 说明:查询和条目的CP56合法性在调用前检查。
|
||
*/
|
||
static int Time_Compare(const IEC60870_CP56Time2a_t *a, const IEC60870_CP56Time2a_t *b)
|
||
{
|
||
#define FS_TIME_COMPARE(field) if (a->time.field != b->time.field) { return a->time.field < b->time.field ? -1 : 1; }
|
||
FS_TIME_COMPARE(year)
|
||
FS_TIME_COMPARE(month)
|
||
FS_TIME_COMPARE(day)
|
||
FS_TIME_COMPARE(hour)
|
||
FS_TIME_COMPARE(minute)
|
||
FS_TIME_COMPARE(second)
|
||
FS_TIME_COMPARE(ms)
|
||
#undef FS_TIME_COMPARE
|
||
return 0;
|
||
}
|
||
|
||
/**
|
||
* 功能:校验目录名称、过滤标志及两份CP56字段的长度/有效性,不比较起止顺序。
|
||
* 输入参数:self——本模块实例。
|
||
* data——数据存储。
|
||
* length——字节长度。
|
||
* 输出参数:无。
|
||
* 返回值:目录名、过滤标志和适用的时标字段符合本服务配置返回true,否则false。
|
||
* 说明:未启用过滤时忽略时标内容;仅显式兼容配置允许同时省略两份时标。
|
||
*/
|
||
static bool Directory_Request_Valid(const IEC104_FileService_t *self, const uint8_t *data, uint16_t length)
|
||
{
|
||
unsigned name_length, position;
|
||
IEC60870_CP56Time2a_t first, last;
|
||
if (length < 16U) { return false; }
|
||
name_length = data[15]; position = 16U + name_length;
|
||
if (name_length > IEC104_FILE_SERVICE_MAX_DIRECTORY_NAME || length <= position || data[position] > 1U) { return false; }
|
||
if (data[position] == 0U) {
|
||
/* 不过滤时仍默认要求完整14字节时标,但忽略内容;兼容项仅放行全部省略。 */
|
||
return length == position + 15U || (self->config.allow_short_directory_request && length == position + 1U);
|
||
}
|
||
return length == position + 15U &&
|
||
IEC60870_Time_From_CP56(data + position + 1U, 7U, &first) != 0 && first.is_invalid == 0U &&
|
||
IEC60870_Time_From_CP56(data + position + 8U, 7U, &last) != 0 && last.is_invalid == 0U;
|
||
}
|
||
|
||
/**
|
||
* 功能:仅返回结构错误对应的结果码;op9的模和、文件ID、偏移及剩余长度按环序执行。
|
||
* 输入参数:self——本模块实例。
|
||
* data——数据存储。
|
||
* length——字节长度。
|
||
* operation——操作类型。
|
||
* 输出参数:无。
|
||
* 返回值:仅返回结构错误对应的结果码;
|
||
* 说明:已确认前缀与操作合法后才进入这里,避免先读变长字段再补长度检查。
|
||
*/
|
||
static uint8_t Check_Structure(const IEC104_FileService_t *self, const uint8_t *data, uint16_t length, uint8_t operation)
|
||
{
|
||
unsigned size;
|
||
if (operation == 1U) { return Directory_Request_Valid(self, data, length) ? 0U : 1U; }
|
||
if (operation == 6U) { return length == 20U ? 0U : 1U; }
|
||
if (operation == 9U) { return length >= 21U && data[19] <= 1U ? 0U : 1U; }
|
||
if (length < 12U) { return 1U; }
|
||
size = data[11];
|
||
if (size == 0U || size > IEC104_FILE_SERVICE_MAX_FILE_NAME) { return operation == 7U ? 2U : 1U; }
|
||
return length == (operation == 7U ? 20U : 12U) + size ? 0U : 1U;
|
||
}
|
||
|
||
/**
|
||
* 功能:记录原I帧来源,不从当前连接重建身份。
|
||
* 输入参数:source——源数据。
|
||
* identity——原会话身份。
|
||
* event——事件。
|
||
* data——数据存储。
|
||
* station——逻辑站点。
|
||
* 输出参数:source——源数据的更新结果。
|
||
* 返回值:无。
|
||
* 说明:此处station仅借用,尚未Acquire。
|
||
*/
|
||
static void Source_Event(FileSource *source, const IEC104_SlaveEventIdentity_t *identity,
|
||
const IEC104_SlaveEvent_t *event, const uint8_t *data, IEC104_Station_t *station)
|
||
{
|
||
memset(source, 0, sizeof(*source));
|
||
source->identity = *identity; source->station = station;
|
||
source->station_id = IEC104_Station_Get_Id(station);
|
||
source->receive_serial = event->transport.data.i_frame.receive_serial;
|
||
source->accepted_ms = FS_NOW(); source->ca = Read16(data + 4U); source->oa = data[3];
|
||
source->test = (data[2] & 0x80U) != 0U;
|
||
}
|
||
|
||
/**
|
||
* 功能:先找空槽再Acquire,成功后才发布occupied/FIFO顺序;满槽丢新不取代旧会话。
|
||
* 输入参数:self——本模块实例。
|
||
* source——源数据。
|
||
* bytes——字节存储。
|
||
* length——字节长度。
|
||
* operation——操作类型。
|
||
* activation——活动轮次。
|
||
* 输出参数:self——本模块实例的更新结果。
|
||
* 返回值:按处理分支返回NULL、task。
|
||
* 说明:后续OPEN将此引用转给资源,失败请求则持有到确认交出或任务取消。
|
||
*/
|
||
static FileTask *Queue_Task(IEC104_FileService_t *self, const FileSource *source,
|
||
const uint8_t *bytes, uint16_t length, uint8_t operation, bool activation)
|
||
{
|
||
FileTask *task = NULL;
|
||
unsigned i;
|
||
if (activation) { if (!self->activation.occupied) { task = &self->activation; } }
|
||
else if (self->task_count < IEC104_FILE_SERVICE_TASK_CAPACITY) {
|
||
for (i = 0U; i < IEC104_FILE_SERVICE_TASK_CAPACITY; ++i) {
|
||
if (!self->tasks[i].occupied) { task = &self->tasks[i]; self->order[self->task_count] = i; break; }
|
||
}
|
||
}
|
||
if (task == NULL) { ++self->status.dropped_requests; return NULL; }
|
||
if (source->station != NULL && IEC104_Slave_Acquire_Station(self->slave, source->station) != IEC104_STATION_OK) { return NULL; }
|
||
memset(task, 0, sizeof(*task)); task->occupied = true; task->source = *source;
|
||
memcpy(task->bytes, bytes, length); task->length = length; task->operation = operation; task->phase = FS_EXECUTE;
|
||
if (!activation) { ++self->task_count; }
|
||
return task;
|
||
}
|
||
|
||
/**
|
||
* 功能:仅在新激活实际入槽后调用。旧待执行激活改否定,已打开读资源立即停发;
|
||
* 输入参数:self——本模块实例。
|
||
* new_task——const FileTask *所指数据。
|
||
* 输出参数:self——本模块实例的更新结果。
|
||
* 返回值:!Operation_Error(self, task, 1U)时返回false;!End_Read(self, IEC104_FILE_SERVICE_END_SUPERSEDED)时返回false;其余分支返回false、true。
|
||
* 说明:不区分CA/T,已安排的旧CLOSE由独立收尾记录保留,不会再安排第二次。
|
||
*/
|
||
static bool Supersede_Read(IEC104_FileService_t *self, const FileTask *new_task)
|
||
{
|
||
unsigned i;
|
||
for (i = 0U; i < self->task_count; ++i) {
|
||
FileTask *task = &self->tasks[self->order[i]];
|
||
if (task == new_task || task->operation != 3U) { continue; }
|
||
if (task->phase == FS_EXECUTE) { if (!Operation_Error(self, task, 1U)) { return false; } }
|
||
else if (task->phase == FS_REPLY && task->length >= 21U && task->bytes[10] == 4U && task->bytes[11] == 0U) {
|
||
/* 原回复已经有形成序号,取代只改结果/大小,不重启回复期限。 */
|
||
task->bytes[2] |= 0x40U; task->bytes[11] = 1U;
|
||
Write32(task->bytes + 17U + task->bytes[12], 0U);
|
||
}
|
||
}
|
||
if (!End_Read(self, IEC104_FILE_SERVICE_END_SUPERSEDED)) { return false; }
|
||
memset(&self->recent_read, 0, sizeof(self->recent_read));
|
||
return true;
|
||
}
|
||
|
||
/**
|
||
* 功能:只终结仍打开的writer,不改已经安排的COMMIT/ABORT;
|
||
* 输入参数:self——本模块实例。
|
||
* 输出参数:self——本模块实例的更新结果。
|
||
* 返回值:Move_Write_To_Finish(self, IEC104_FILE_SERVICE_CALL_ABORT_WRITE, IEC104_FILE_SERVICE_END_SUPERSEDED) == NULL时返回false;其余分支返回false、true。
|
||
* 说明:新激活是近期记录边界。
|
||
*/
|
||
static bool Supersede_Write(IEC104_FileService_t *self)
|
||
{
|
||
if (self->writer.occupied) {
|
||
if (self->writer.source.test) { Release_Source(self, &self->writer.source); memset(&self->writer, 0, sizeof(self->writer)); }
|
||
else if (Move_Write_To_Finish(self, IEC104_FILE_SERVICE_CALL_ABORT_WRITE, IEC104_FILE_SERVICE_END_SUPERSEDED) == NULL) { return false; }
|
||
}
|
||
memset(&self->silent_write, 0, sizeof(self->silent_write));
|
||
memset(&self->empty_write, 0, sizeof(self->empty_write));
|
||
return true;
|
||
}
|
||
|
||
/**
|
||
* 功能:op6不入队、不回复:最近结束的读归属仍可统计迟到确认,但只有DATA会话可停发。
|
||
* 输入参数:self——本模块实例。
|
||
* source——源数据。
|
||
* result——处理结果。
|
||
* 输出参数:self——本模块实例的更新结果。
|
||
* 返回值:无。
|
||
* 说明:非零结果仅作诊断;是否据此中止由显式模式决定,不推断规范的失败含义。
|
||
*/
|
||
static void Receive_Read_Confirm(IEC104_FileService_t *self, const FileSource *source, uint8_t result)
|
||
{
|
||
bool active = self->reader.occupied && self->reader.phase == FS_READ_DATA && Same_Source(source, &self->reader.source);
|
||
bool match = active || (self->read_finish.occupied && Same_Source(source, &self->read_finish.source)) ||
|
||
(self->recent_read.valid && Same_Source(source, &self->recent_read.source));
|
||
if (!match) { ++self->status.rejected; return; }
|
||
++self->status.read_confirms; if (result != 0U) { ++self->status.read_confirm_nonzero; }
|
||
if (active && (self->config.read_confirm_mode == IEC104_FILE_SERVICE_READ_CONFIRM_STOP_ANY ||
|
||
(self->config.read_confirm_mode == IEC104_FILE_SERVICE_READ_CONFIRM_STOP_NONZERO && result != 0U))) {
|
||
(void)End_Read(self, IEC104_FILE_SERVICE_END_MASTER);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 功能:填入全功能、偏移校验及末段确认等默认策略和期限;
|
||
* 输入参数:config——配置。
|
||
* 输出参数:config——配置的更新结果。
|
||
* 返回值:无。
|
||
* 说明:NULL无操作,不绑定Slave或打开文件。
|
||
*/
|
||
void IEC104_FileService_Config_Default(IEC104_FileServiceConfig_t *config)
|
||
{
|
||
if (config == NULL) { return; }
|
||
memset(config, 0, sizeof(*config));
|
||
config->features = IEC104_FILE_SERVICE_FEATURE_ALL;
|
||
config->segment_mode = IEC104_FILE_SERVICE_SEGMENT_OFFSET;
|
||
config->write_confirm_mode = IEC104_FILE_SERVICE_WRITE_CONFIRM_FINAL;
|
||
config->read_confirm_mode = IEC104_FILE_SERVICE_READ_CONFIRM_COUNT;
|
||
config->id_mode = IEC104_FILE_SERVICE_ID_ZERO; config->write_confirm_cause = 7U;
|
||
config->read_segment_bytes = IEC104_FILE_SERVICE_MAX_SEGMENT; config->window_reserve = 2U;
|
||
config->list_scan_budget = 64U; config->directory_timeout_ms = 60000U;
|
||
config->reply_timeout_ms = 15000U; config->execute_timeout_ms = 15000U;
|
||
config->read_idle_timeout_ms = 60000U; config->write_idle_timeout_ms = 60000U;
|
||
}
|
||
|
||
/**
|
||
* 功能:固定偏移依赖104的2/2/3字段宽度;全部配置/重复绑定检查通过后才占静态池槽。
|
||
* 输入参数:slave——所属从站服务。
|
||
* config——配置。
|
||
* 输出参数:无。
|
||
* 返回值:按处理分支返回NULL、slot。
|
||
* 说明:window_reserve与实际k/记录容量的关系推迟到ACTIVATED检查,允许Init前创建。
|
||
*/
|
||
IEC104_FileService_t *IEC104_FileService_Create(IEC104_Slave_t *slave, const IEC104_FileServiceConfig_t *config)
|
||
{
|
||
const IEC60870_AppLayerParameters_t *parameters = IEC104_Slave_Get_Application_Layer_Parameters(slave);
|
||
IEC104_FileService_t *slot = NULL;
|
||
unsigned i;
|
||
if (parameters == NULL || config == NULL || parameters->sizeOfCOT != 2 || parameters->sizeOfCA != 2 || parameters->sizeOfIOA != 3 ||
|
||
config->features == 0U || (config->features & ~IEC104_FILE_SERVICE_FEATURE_ALL) != 0U ||
|
||
(config->segment_mode != IEC104_FILE_SERVICE_SEGMENT_OFFSET && config->segment_mode != IEC104_FILE_SERVICE_SEGMENT_UNCHECKED) ||
|
||
(config->write_confirm_mode != IEC104_FILE_SERVICE_WRITE_CONFIRM_FINAL && config->write_confirm_mode != IEC104_FILE_SERVICE_WRITE_CONFIRM_EACH) ||
|
||
(config->read_confirm_mode != IEC104_FILE_SERVICE_READ_CONFIRM_COUNT && config->read_confirm_mode != IEC104_FILE_SERVICE_READ_CONFIRM_STOP_NONZERO &&
|
||
config->read_confirm_mode != IEC104_FILE_SERVICE_READ_CONFIRM_STOP_ANY) ||
|
||
(config->id_mode != IEC104_FILE_SERVICE_ID_ZERO && config->id_mode != IEC104_FILE_SERVICE_ID_ECHO) ||
|
||
(config->write_confirm_cause != 5U && config->write_confirm_cause != 7U) || config->read_segment_bytes == 0U ||
|
||
config->read_segment_bytes > IEC104_FILE_SERVICE_MAX_SEGMENT || config->window_reserve == 0U ||
|
||
config->list_scan_budget == 0U || config->reply_timeout_ms == 0U || next_instance_id == UINT64_MAX) { return NULL; }
|
||
for (i = 0U; i < IEC104_FILE_SERVICE_CAPACITY; ++i) {
|
||
if (file_pool[i].in_use && file_pool[i].slave == slave) { return NULL; }
|
||
if (!file_pool[i].in_use && slot == NULL) { slot = &file_pool[i]; }
|
||
}
|
||
if (slot == NULL) { return NULL; }
|
||
memset(slot, 0, sizeof(*slot)); slot->slave = slave; slot->config = *config;
|
||
slot->instance_id = ++next_instance_id; slot->in_use = true;
|
||
return slot;
|
||
}
|
||
|
||
/**
|
||
* 功能:Destroy不隐式Cancel,也不交付回调。faulted即使已无任务仍须证明原连接结束,
|
||
* 输入参数:self——本模块实例。
|
||
* 输出参数:self——本模块实例的更新结果。
|
||
* 返回值:self->write_finish[i].occupied时返回false;self->confirms[i].occupied时返回false;!self->fault_ended时返回false;其余分支返回false、true。
|
||
* 说明:防止在同一健康TCP代次上通过Destroy/Create跳过故障隔离。
|
||
*/
|
||
bool IEC104_FileService_Destroy(IEC104_FileService_t *self)
|
||
{
|
||
IEC104_TcpServerStatus_t status;
|
||
unsigned i;
|
||
if (!Owned(self) || self->in_callback || self->task_count != 0U || self->activation.occupied ||
|
||
self->segment_count != 0U || self->directory.occupied || self->reader.occupied || self->writer.occupied || self->read_finish.occupied) { return false; }
|
||
for (i = 0U; i < 2U; ++i) { if (self->write_finish[i].occupied) { return false; } }
|
||
for (i = 0U; i < IEC104_FILE_SERVICE_CONFIRM_CAPACITY; ++i) { if (self->confirms[i].occupied) { return false; } }
|
||
if (self->status.faulted && !self->fault_ended) {
|
||
if (FS_STATUS(self->slave, &status, NULL) == IEC104_TCP_OK &&
|
||
(!status.connected || status.generation != self->fault_identity.generation)) { self->fault_ended = true; }
|
||
if (!self->fault_ended) { return false; }
|
||
}
|
||
memset(self, 0, sizeof(*self)); return true;
|
||
}
|
||
|
||
/**
|
||
* 功能:取消协议任务并保留外部资源的收尾责任;不在本入口执行应用回调。
|
||
* 输入参数:self——本模块实例。
|
||
* 输出参数:self——本模块实例的更新结果。
|
||
* 返回值:无。
|
||
* 说明:调用方仍须提供原handlers/context推进Execute,直至关闭/中止完成后才能Destroy。
|
||
*/
|
||
void IEC104_FileService_Cancel(IEC104_FileService_t *self)
|
||
{
|
||
if (!Owned(self) || self->in_callback) { return; }
|
||
Cancel_All(self, false);
|
||
}
|
||
|
||
/**
|
||
* 功能:生命周期先处理,再按无状态校验顺序分流I帧。本入口只登记/取代协议状态,
|
||
* 输入参数:self——本模块实例。
|
||
* event——事件。
|
||
* 输出参数:self——本模块实例的更新结果。
|
||
* 返回值:返回IEC104_FileServiceEventResult_t结果;本函数显式处理IEC104_FILE_SERVICE_EVENT_ERROR、IEC104_FILE_SERVICE_EVENT_IGNORED、IEC104_FILE_SERVICE_EVENT_HANDLED、IEC104_FILE_SERVICE_TASK_CAPACITY、IEC104_FILE_SERVICE_EVENT_BUSY,其余结果由下层调用传回。
|
||
* 说明:不执行存储回调;BUSY时未消费事件,应用必须保留原事件并在本地推进后重试。
|
||
*/
|
||
IEC104_FileServiceEventResult_t IEC104_FileService_Handle_Event(IEC104_FileService_t *self, const IEC104_SlaveEvent_t *event)
|
||
{
|
||
IEC104_SlaveEventIdentity_t identity;
|
||
IEC104_Station_t *station;
|
||
FileSource source;
|
||
FileTask *task;
|
||
const uint8_t *data;
|
||
uint16_t length;
|
||
uint8_t cause, operation = 0U, error = 0U, feature = 0U, mirror = 0U;
|
||
bool drop = false, rejected = false, malformed = false;
|
||
if (!Owned(self) || self->in_callback || !IEC104_Slave_Get_Event_Identity(self->slave, event, &identity) ||
|
||
(self->session.instance_id != 0U && self->session.instance_id != identity.instance_id)) { return IEC104_FILE_SERVICE_EVENT_ERROR; }
|
||
if (event->transport.type == IEC104_TCP_EVENT_CONNECTED) {
|
||
if (self->session.generation != 0U && identity.generation < self->session.generation) { return IEC104_FILE_SERVICE_EVENT_IGNORED; }
|
||
Cancel_All(self, true);
|
||
if (self->status.faulted && !Same_Identity(&identity, &self->fault_identity)) { self->fault_ended = true; }
|
||
self->session = identity; self->status.active = false; self->status.reserve_invalid = false;
|
||
return IEC104_FILE_SERVICE_EVENT_HANDLED;
|
||
}
|
||
if (event->transport.type == IEC104_TCP_EVENT_DISCONNECTED && self->status.faulted && Same_Identity(&identity, &self->fault_identity)) { self->fault_ended = true; }
|
||
if (!Same_Identity(&identity, &self->session)) { return IEC104_FILE_SERVICE_EVENT_IGNORED; }
|
||
switch (event->transport.type) {
|
||
case IEC104_TCP_EVENT_ACTIVATED:
|
||
if (!self->status.faulted) {
|
||
IEC104_TcpSendCapacity_t capacity;
|
||
IEC104_TcpResult_t result = FS_CAPACITY(self->slave, &capacity, NULL);
|
||
/* Close后读出的历史ACTIVATED只消费,不重新激活或误报reserve非法。 */
|
||
if (result == IEC104_TCP_INVALID_STATE) { return IEC104_FILE_SERVICE_EVENT_HANDLED; }
|
||
if (result != IEC104_TCP_OK) { return IEC104_FILE_SERVICE_EVENT_ERROR; }
|
||
self->status.reserve_invalid = self->config.window_reserve >= capacity.window_k || self->config.window_reserve >= capacity.record_capacity;
|
||
self->status.active = true;
|
||
}
|
||
return IEC104_FILE_SERVICE_EVENT_HANDLED;
|
||
case IEC104_TCP_EVENT_DEACTIVATED:
|
||
case IEC104_TCP_EVENT_DISCONNECTED:
|
||
Cancel_All(self, true); self->status.active = false;
|
||
if (event->transport.type == IEC104_TCP_EVENT_DISCONNECTED) { self->status.reserve_invalid = false; }
|
||
return IEC104_FILE_SERVICE_EVENT_HANDLED;
|
||
case IEC104_TCP_EVENT_I_FRAME: break;
|
||
default: return IEC104_FILE_SERVICE_EVENT_IGNORED;
|
||
}
|
||
if (event->asdu_result != IEC60870_ASDU_OK || IEC60870_Asdu_Get_Data(&event->asdu, &data, &length) != IEC60870_ASDU_OK ||
|
||
length < 6U || length > 249U || data[0] != IEC104_FILE_SERVICE_TYPE_ID) { return IEC104_FILE_SERVICE_EVENT_IGNORED; }
|
||
/* faulted只吞本模块Type210,防止应用继续44兜底;其他业务类型仍可分派。 */
|
||
if (self->status.faulted) { ++self->status.faulted_dropped; return IEC104_FILE_SERVICE_EVENT_HANDLED; }
|
||
if (!self->status.active) { return IEC104_FILE_SERVICE_EVENT_IGNORED; }
|
||
cause = data[2] & 0x3FU;
|
||
station = Read16(data + 4U) == 65535U ? NULL : IEC104_Slave_Get_Station(self->slave, Read16(data + 4U));
|
||
Source_Event(&source, &identity, event, data, station);
|
||
/* 优先级:COT -> CA -> 可读IOA -> 前缀 -> 操作COT -> 功能 -> 结构。 */
|
||
if (cause != 5U && cause != 6U) { mirror = 45U; }
|
||
else if (station == NULL) { mirror = 46U; }
|
||
else if (length >= 9U && (data[6] != 0U || data[7] != 0U || data[8] != 0U)) { mirror = 47U; }
|
||
else if (length < 11U || data[9] != IEC104_FILE_SERVICE_PACKAGE_FILE || (data[2] & 0x40U) != 0U ||
|
||
(data[10] != 1U && data[10] != 3U && data[10] != 6U && data[10] != 7U && data[10] != 9U)) {
|
||
if (cause == 6U) { mirror = 7U; } else { drop = true; rejected = true; }
|
||
} else {
|
||
operation = data[10];
|
||
if (((operation == 3U || operation == 7U) && cause != 6U) ||
|
||
((operation == 6U || operation == 9U) && cause != 5U)) { mirror = 45U; }
|
||
else {
|
||
feature = operation == 1U ? IEC104_FILE_SERVICE_FEATURE_DIRECTORY :
|
||
((operation == 3U || operation == 6U) ? IEC104_FILE_SERVICE_FEATURE_READ : IEC104_FILE_SERVICE_FEATURE_WRITE);
|
||
if ((self->config.features & feature) == 0U) {
|
||
if (operation == 9U) { ++self->status.stray_segments; drop = true; }
|
||
else if (operation == 6U) { drop = true; rejected = true; }
|
||
else { error = 1U; }
|
||
} else {
|
||
error = Check_Structure(self, data, length, operation);
|
||
if (operation == 9U) { malformed = error != 0U; error = 0U; }
|
||
else if (operation == 6U && error != 0U) { error = 0U; drop = true; rejected = true; }
|
||
}
|
||
}
|
||
}
|
||
if (mirror != 0U || error != 0U || rejected) { ++self->status.rejected; }
|
||
if (drop) { return IEC104_FILE_SERVICE_EVENT_HANDLED; }
|
||
if (mirror != 0U || error != 0U) {
|
||
unsigned before = self->task_count;
|
||
task = Queue_Task(self, &source, data, length, operation, false);
|
||
if (task == NULL) { return before == IEC104_FILE_SERVICE_TASK_CAPACITY ? IEC104_FILE_SERVICE_EVENT_HANDLED : IEC104_FILE_SERVICE_EVENT_ERROR; }
|
||
if (!(mirror != 0U ? Mirror_Error(self, task, mirror) : Operation_Error(self, task, error))) { return IEC104_FILE_SERVICE_EVENT_HANDLED; }
|
||
return IEC104_FILE_SERVICE_EVENT_HANDLED;
|
||
}
|
||
if (operation == 6U) { Receive_Read_Confirm(self, &source, data[19]); return IEC104_FILE_SERVICE_EVENT_HANDLED; }
|
||
if (operation == 9U) {
|
||
FileSegment *segment;
|
||
unsigned index, i;
|
||
uint8_t checksum = 0U;
|
||
/* 格式/模和错误也须按环序处理,不能越过前面的合法段提前终结会话。
|
||
* 满环时不复制、不Acquire、不增加accepted,重试仍使用同一原事件。 */
|
||
if (self->segment_count == IEC104_FILE_SERVICE_SEGMENT_CAPACITY) { ++self->status.busy_returns; return IEC104_FILE_SERVICE_EVENT_BUSY; }
|
||
index = (self->segment_head + self->segment_count) % IEC104_FILE_SERVICE_SEGMENT_CAPACITY;
|
||
segment = &self->segments[index]; memset(segment, 0, sizeof(*segment));
|
||
segment->write_serial = self->next_write; segment->station_id = source.station_id;
|
||
segment->generation = identity.generation; segment->ca = source.ca; segment->oa = source.oa; segment->test = source.test;
|
||
segment->receive_serial = source.receive_serial; segment->accepted_ms = source.accepted_ms; segment->malformed = malformed;
|
||
if (length >= 15U) { segment->file_id = Read32(data + 11U); }
|
||
if (length >= 19U) { segment->segment = Read32(data + 15U); }
|
||
if (length >= 20U) { segment->more = data[19] != 0U; }
|
||
if (length >= 21U) {
|
||
segment->length = (uint16_t)(length - 21U);
|
||
memcpy(segment->data, data + 20U, segment->length);
|
||
for (i = 0U; i < segment->length; ++i) { checksum = (uint8_t)(checksum + segment->data[i]); }
|
||
segment->bad_sum = checksum != data[length - 1U];
|
||
}
|
||
++self->segment_count; ++self->status.accepted;
|
||
return IEC104_FILE_SERVICE_EVENT_HANDLED;
|
||
}
|
||
/* TEST写不能抢占真实打开会话;拒绝走普通错误FIFO,不改变写序号。 */
|
||
if (operation == 7U && source.test && self->writer.occupied && !self->writer.source.test) {
|
||
unsigned before = self->task_count;
|
||
++self->status.rejected;
|
||
task = Queue_Task(self, &source, data, length, operation, false);
|
||
if (task == NULL) { return before == IEC104_FILE_SERVICE_TASK_CAPACITY ? IEC104_FILE_SERVICE_EVENT_HANDLED : IEC104_FILE_SERVICE_EVENT_ERROR; }
|
||
(void)Operation_Error(self, task, 1U); return IEC104_FILE_SERVICE_EVENT_HANDLED;
|
||
}
|
||
{
|
||
bool full = operation == 7U ? self->activation.occupied : self->task_count == IEC104_FILE_SERVICE_TASK_CAPACITY;
|
||
task = Queue_Task(self, &source, data, length, operation, operation == 7U);
|
||
if (task == NULL) { return full ? IEC104_FILE_SERVICE_EVENT_HANDLED : IEC104_FILE_SERVICE_EVENT_ERROR; }
|
||
}
|
||
++self->status.accepted;
|
||
/* 直到入槽成功才产生取代副作用;写序号把之后到达的数据段绑定到这次激活。 */
|
||
if (operation == 3U) { (void)Supersede_Read(self, task); }
|
||
else if (operation == 7U) {
|
||
if (!Next_Serial(self, &self->next_write, &task->work.reply.write_serial, &source.identity)) { return IEC104_FILE_SERVICE_EVENT_HANDLED; }
|
||
(void)Supersede_Write(self);
|
||
}
|
||
return IEC104_FILE_SERVICE_EVENT_HANDLED;
|
||
}
|
||
|
||
/**
|
||
* 功能:每轮即使need_process=false也可调用以重试WAIT。先检查期限,再验证会话并提交;
|
||
* 输入参数:self——本模块实例。
|
||
* 输出参数:self——本模块实例的更新结果。
|
||
* 返回值:每轮即使need_process=false也可调用以重试WAIT。
|
||
* true表示本轮正常结束,不表示队列已空。
|
||
* 说明:true表示本轮正常结束,不表示队列已空。故障时清理仍由Execute_Next交付。
|
||
*/
|
||
bool IEC104_FileService_Process(IEC104_FileService_t *self)
|
||
{
|
||
IEC104_SlaveRequestState_t state;
|
||
if (!Owned(self) || self->in_callback) { return false; }
|
||
if (self->status.faulted) { return false; }
|
||
if (Expire(self) < 0) { return false; }
|
||
if (self->session.instance_id == 0U || !self->status.active) { return true; }
|
||
state = Check(self, &self->session);
|
||
if (state == IEC104_SLAVE_REQUEST_ERROR) { return false; }
|
||
if (state != IEC104_SLAVE_REQUEST_READY) { return true; }
|
||
return Flush_Replies(self) >= 0;
|
||
}
|
||
|
||
/**
|
||
* 功能:检查是否为协议可表达的四种应用结果;
|
||
* 输入参数:result——处理结果。
|
||
* 输出参数:无。
|
||
* 返回值:其他枚举值返回false,交由调用方计数和归一化。
|
||
* 说明:其他枚举值返回false,交由调用方计数和归一化。
|
||
*/
|
||
static bool Valid_Result(IEC104_FileServiceResult_t result)
|
||
{
|
||
return result == IEC104_FILE_SERVICE_RESULT_OK || result == IEC104_FILE_SERVICE_RESULT_FAILED ||
|
||
result == IEC104_FILE_SERVICE_RESULT_NAME_UNSUPPORTED || result == IEC104_FILE_SERVICE_RESULT_SIZE_OUT_OF_RANGE;
|
||
}
|
||
|
||
/**
|
||
* 功能:同步借用期间阻止修改入口重入;
|
||
* 输入参数:self——本模块实例。
|
||
* handlers——回调集合。
|
||
* context——调用方上下文。
|
||
* request——请求。
|
||
* open——IEC104_FileServiceOpen_t *所指数据。
|
||
* 输出参数:self——本模块实例的更新结果。
|
||
* 返回值:返回result的结果。
|
||
* 说明:此保护不保存handlers/context,也不替代串行调用约束。
|
||
*/
|
||
static IEC104_FileServiceResult_t Action(IEC104_FileService_t *self,
|
||
const IEC104_FileServiceHandlers_t *handlers, void *context,
|
||
const IEC104_FileServiceRequest_t *request, IEC104_FileServiceOpen_t *open)
|
||
{
|
||
IEC104_FileServiceResult_t result;
|
||
self->in_callback = true;
|
||
result = handlers->action(context, request, open);
|
||
self->in_callback = false;
|
||
return result;
|
||
}
|
||
|
||
/**
|
||
* 功能:所有应用借用都现用现建;
|
||
* 输入参数:self——本模块实例。
|
||
* task——业务任务。
|
||
* call——IEC104_FileServiceCall_t值。
|
||
* request——请求。
|
||
* 输出参数:request——请求的更新结果。
|
||
* 返回值:无。
|
||
* 说明:目录名保留在尚未冻结回复的任务原文中。
|
||
*/
|
||
static void Directory_Request(const IEC104_FileService_t *self, const FileTask *task,
|
||
IEC104_FileServiceCall_t call, IEC104_FileServiceRequest_t *request)
|
||
{
|
||
unsigned position = 16U + task->bytes[15];
|
||
Request_From(self, &task->source, call, request);
|
||
request->name_length = task->bytes[15];
|
||
request->name = request->name_length != 0U ? task->bytes + 16U : NULL;
|
||
request->time_filter = task->bytes[position] != 0U;
|
||
if (request->time_filter) {
|
||
(void)IEC60870_Time_From_CP56(task->bytes + position + 1U, 7U, &request->start_time);
|
||
(void)IEC60870_Time_From_CP56(task->bytes + position + 8U, 7U, &request->stop_time);
|
||
}
|
||
if (call == IEC104_FILE_SERVICE_CALL_NONE) { request->handle = self->directory.handle; }
|
||
}
|
||
|
||
/**
|
||
* 功能:打开成功只建立快照和总期限,本次不继续list;原站引用从任务转入目录资源。
|
||
* 输入参数:self——本模块实例。
|
||
* task——业务任务。
|
||
* handlers——回调集合。
|
||
* context——调用方上下文。
|
||
* 输出参数:self——本模块实例的更新结果。
|
||
* task——业务任务的更新结果。
|
||
* 返回值:按处理分支返回IEC104_FILE_SERVICE_EXECUTE_EMPTY、IEC104_FILE_SERVICE_EXECUTE_OK。
|
||
* 说明:打开失败没有CLOSE,应用必须已自行释放临时资源。
|
||
*/
|
||
static IEC104_FileServiceExecuteResult_t Open_Directory(IEC104_FileService_t *self, FileTask *task,
|
||
const IEC104_FileServiceHandlers_t *handlers, void *context)
|
||
{
|
||
IEC104_FileServiceRequest_t request;
|
||
IEC104_FileServiceOpen_t open;
|
||
IEC104_FileServiceResult_t result;
|
||
if (self->directory.occupied) { return IEC104_FILE_SERVICE_EXECUTE_EMPTY; }
|
||
Directory_Request(self, task, IEC104_FILE_SERVICE_CALL_OPEN_DIRECTORY, &request);
|
||
memset(&open, 0, sizeof(open));
|
||
result = Action(self, handlers, context, &request, &open);
|
||
if (!Valid_Result(result)) { ++self->status.invalid_callbacks; }
|
||
if (result != IEC104_FILE_SERVICE_RESULT_OK) {
|
||
if (Operation_Error(self, task, 1U)) { (void)Flush_Replies(self); }
|
||
return IEC104_FILE_SERVICE_EXECUTE_OK;
|
||
}
|
||
memset(&self->directory, 0, sizeof(self->directory));
|
||
self->directory.occupied = true; self->directory.task_alive = true;
|
||
self->directory.source = task->source; task->source.station = NULL;
|
||
self->directory.task_index = (unsigned)(task - self->tasks);
|
||
self->directory.handle = open.handle; self->directory.opened_ms = FS_NOW();
|
||
memset(&task->work, 0, sizeof(task->work));
|
||
task->phase = FS_DIRECTORY; task->cursor = 0U; task->waiting = false;
|
||
return IEC104_FILE_SERVICE_EXECUTE_OK;
|
||
}
|
||
|
||
/**
|
||
* 功能:预算耗尽时暂不发送含条目的候选页,跨轮前瞻到下一匹配项或END再重建。
|
||
* 输入参数:self——本模块实例。
|
||
* task——业务任务。
|
||
* handlers——回调集合。
|
||
* context——调用方上下文。
|
||
* 输出参数:self——本模块实例的更新结果。
|
||
* task——业务任务的更新结果。
|
||
* 返回值:按处理分支返回IEC104_FILE_SERVICE_EXECUTE_EMPTY、IEC104_FILE_SERVICE_EXECUTE_OK、called ? IEC104_FILE_SERVICE_EXECUTE_OK : IEC104_FILE_SERVICE_EXECUTE_ERROR、IEC104_FILE_SERVICE_EXECUTE_WAIT、expired < 0 && !called ? IEC104_FILE_SERVICE_EXECUTE_ERROR : IEC104_FILE_SERVICE_EXECUTE_OK。
|
||
* 说明:非空结果的末页因此始终含真实条目;真空目录/错误仍使用规范的零项末帧。
|
||
* 这样避免非空目录额外以零项帧收尾,兼容不接受纯头部目录确认帧的接收端。
|
||
* 扫描、前瞻、重建各轮均受list_scan_budget限制;WAIT从固定页首重建。
|
||
* 原请求始终保留,重建只使用现有工作缓冲,目录快照必须保持不变。
|
||
*/
|
||
static IEC104_FileServiceExecuteResult_t Scan_Directory(IEC104_FileService_t *self, FileTask *task,
|
||
const IEC104_FileServiceHandlers_t *handlers, void *context)
|
||
{
|
||
IEC104_FileServiceRequest_t request;
|
||
IEC104_SlaveRequestState_t state;
|
||
bool lookahead = task->work.directory.phase == 1U;
|
||
bool rebuild = task->work.directory.phase == 2U;
|
||
size_t cursor = lookahead ? task->work.directory.next : task->cursor;
|
||
uint16_t length = 18U;
|
||
uint8_t count = 0U, cause = (task->bytes[2] & 0x3FU) == 5U ? 5U : 7U;
|
||
unsigned scanned = 0U;
|
||
bool last = false, called = false, more = false;
|
||
uint64_t sequence;
|
||
int sent, expired;
|
||
if (Has_Reply(self)) { return IEC104_FILE_SERVICE_EXECUTE_EMPTY; }
|
||
Directory_Request(self, task, IEC104_FILE_SERVICE_CALL_NONE, &request);
|
||
Prefix(self->buffer, &task->source, 2U, cause, 0U);
|
||
self->buffer[11] = 0U; Write32(self->buffer + 12U, Output_Id(self, Read32(task->bytes + 11U)));
|
||
if (request.time_filter && Time_Compare(&request.start_time, &request.stop_time) > 0) { last = true; }
|
||
while (!last && scanned < self->config.list_scan_budget &&
|
||
(!rebuild || cursor < task->work.directory.page_end)) {
|
||
IEC104_FileServiceEntry_t entry;
|
||
IEC104_FileServiceListResult_t result;
|
||
uint8_t time_bytes[7];
|
||
unsigned item_length;
|
||
bool selected;
|
||
memset(&entry, 0, sizeof(entry));
|
||
self->in_callback = true;
|
||
result = handlers->list(context, &request, cursor, &entry);
|
||
self->in_callback = false; called = true; ++scanned;
|
||
if (result == IEC104_FILE_SERVICE_LIST_END) { last = true; break; }
|
||
if (result == IEC104_FILE_SERVICE_LIST_NO_DIRECTORY && cursor == 0U) {
|
||
(void)Directory_Failed(self, IEC104_FILE_SERVICE_END_ERROR);
|
||
(void)Flush_Replies(self); return IEC104_FILE_SERVICE_EXECUTE_OK;
|
||
}
|
||
if (result != IEC104_FILE_SERVICE_LIST_ENTRY) {
|
||
if (result != IEC104_FILE_SERVICE_LIST_ERROR) { ++self->status.invalid_callbacks; }
|
||
(void)Directory_Failed(self, IEC104_FILE_SERVICE_END_ERROR);
|
||
(void)Flush_Replies(self); return IEC104_FILE_SERVICE_EXECUTE_OK;
|
||
}
|
||
/* 即使条目稍后会被过滤,也须先检查输出;SIZE_MAX可END但不能再ENTRY递增。 */
|
||
if (entry.name == NULL || entry.name_length == 0U || entry.name_length > IEC104_FILE_SERVICE_MAX_DIRECTORY_NAME ||
|
||
IEC60870_Time_To_CP56(&entry.time, time_bytes, sizeof(time_bytes)) == 0 || cursor == SIZE_MAX) {
|
||
++self->status.invalid_callbacks;
|
||
(void)Directory_Failed(self, IEC104_FILE_SERVICE_END_ERROR);
|
||
(void)Flush_Replies(self); return IEC104_FILE_SERVICE_EXECUTE_OK;
|
||
}
|
||
selected = !request.time_filter || (entry.time.is_invalid == 0U &&
|
||
Time_Compare(&entry.time, &request.start_time) >= 0 && Time_Compare(&entry.time, &request.stop_time) <= 0);
|
||
if (!selected) { ++cursor; continue; }
|
||
if (lookahead) { more = true; break; }
|
||
item_length = 13U + entry.name_length;
|
||
if (item_length > 249U - length) {
|
||
if (count == 0U) {
|
||
++self->status.invalid_callbacks;
|
||
(void)Directory_Failed(self, IEC104_FILE_SERVICE_END_ERROR);
|
||
(void)Flush_Replies(self); return IEC104_FILE_SERVICE_EXECUTE_OK;
|
||
}
|
||
more = true; break;
|
||
}
|
||
self->buffer[length] = entry.name_length;
|
||
memcpy(self->buffer + length + 1U, entry.name, entry.name_length);
|
||
self->buffer[length + 1U + entry.name_length] = entry.attribute;
|
||
Write32(self->buffer + length + 2U + entry.name_length, entry.size);
|
||
memcpy(self->buffer + length + 6U + entry.name_length, time_bytes, sizeof(time_bytes));
|
||
length = (uint16_t)(length + item_length); ++count; ++cursor;
|
||
}
|
||
/* list已经调用过也不能直接发送:再次确认原会话和总期限,失败丢弃本轮条目。 */
|
||
state = Check(self, &task->source.identity);
|
||
if (state == IEC104_SLAVE_REQUEST_ERROR) { return called ? IEC104_FILE_SERVICE_EXECUTE_OK : IEC104_FILE_SERVICE_EXECUTE_ERROR; }
|
||
if (state == IEC104_SLAVE_REQUEST_STALE) { return IEC104_FILE_SERVICE_EXECUTE_OK; }
|
||
if (state == IEC104_SLAVE_REQUEST_WAIT_EVENTS) { return IEC104_FILE_SERVICE_EXECUTE_WAIT; }
|
||
expired = Expire(self);
|
||
if (expired != 0) { return expired < 0 && !called ? IEC104_FILE_SERVICE_EXECUTE_ERROR : IEC104_FILE_SERVICE_EXECUTE_OK; }
|
||
if (lookahead) {
|
||
/* 找到的匹配项尚未消费,next仍指向它;重建并发出本页后,它将作为下一页首项。 */
|
||
task->work.directory.next = cursor;
|
||
if (last || more) { task->work.directory.phase = 2U; task->work.directory.more = more; }
|
||
task->waiting = false;
|
||
return IEC104_FILE_SERVICE_EXECUTE_OK;
|
||
}
|
||
if (rebuild) { last = !task->work.directory.more; }
|
||
else if (count != 0U && !last && !more) {
|
||
/* 恰好耗尽本轮预算,尚不能确定CONT;仅保存边界,下一轮先找后续项。 */
|
||
task->work.directory.page_end = cursor; task->work.directory.next = cursor;
|
||
task->work.directory.phase = 1U; task->waiting = false;
|
||
return IEC104_FILE_SERVICE_EXECUTE_OK;
|
||
}
|
||
if (count == 0U && !last) {
|
||
/* 只有已确定不匹配且无需发出的条目可独立提交游标,不发送空CONT=1。 */
|
||
task->cursor = cursor; task->waiting = false;
|
||
return IEC104_FILE_SERVICE_EXECUTE_OK;
|
||
}
|
||
self->buffer[16] = last ? 0U : 1U; self->buffer[17] = count;
|
||
if (!Next_Serial(self, &self->next_reply, &sequence, &task->source.identity)) {
|
||
return called ? IEC104_FILE_SERVICE_EXECUTE_OK : IEC104_FILE_SERVICE_EXECUTE_ERROR;
|
||
}
|
||
(void)sequence; /* 现组帧没有跨WAIT槽;下一次重取重新参加形成次序。 */
|
||
sent = Send(self, &task->source, self->buffer, length, false, false, NULL);
|
||
if (sent < 0) { return called ? IEC104_FILE_SERVICE_EXECUTE_OK : IEC104_FILE_SERVICE_EXECUTE_ERROR; }
|
||
task->waiting = sent == 0;
|
||
if (sent == 0) { return IEC104_FILE_SERVICE_EXECUTE_WAIT; }
|
||
/* 只有Send接收整页后才推进游标;WAIT期间保留页首及前瞻结论,便于原样重建。 */
|
||
task->cursor = rebuild ? task->work.directory.next : cursor;
|
||
task->work.directory.phase = 0U; ++self->status.directory_frames;
|
||
if (last) {
|
||
++self->status.directories; task->phase = FS_DIRECTORY_DONE;
|
||
(void)Close_Directory(self, IEC104_FILE_SERVICE_END_COMPLETE);
|
||
}
|
||
return IEC104_FILE_SERVICE_EXECUTE_OK;
|
||
}
|
||
|
||
/**
|
||
* 功能:先接管成功OPEN的handle,再复核回显名;输出非法仍须恰一次CLOSE,不能泄漏资源。
|
||
* 输入参数:self——本模块实例。
|
||
* task——业务任务。
|
||
* handlers——回调集合。
|
||
* context——调用方上下文。
|
||
* 输出参数:self——本模块实例的更新结果。
|
||
* task——业务任务的更新结果。
|
||
* 返回值:按处理分支返回IEC104_FILE_SERVICE_EXECUTE_ERROR、IEC104_FILE_SERVICE_EXECUTE_OK。
|
||
* 说明:固定op4交给HIGH之前维持OPEN阶段,数据读取由Task_Sent切入DATA。
|
||
*/
|
||
static IEC104_FileServiceExecuteResult_t Open_Read(IEC104_FileService_t *self, FileTask *task,
|
||
const IEC104_FileServiceHandlers_t *handlers, void *context)
|
||
{
|
||
IEC104_FileServiceRequest_t request;
|
||
IEC104_FileServiceOpen_t open;
|
||
IEC104_FileServiceResult_t result;
|
||
const uint8_t *name;
|
||
uint8_t name_length;
|
||
if (self->status.reserve_invalid) {
|
||
if (!Operation_Error(self, task, 1U) || Flush_Replies(self) < 0) { return IEC104_FILE_SERVICE_EXECUTE_ERROR; }
|
||
return IEC104_FILE_SERVICE_EXECUTE_OK;
|
||
}
|
||
Request_From(self, &task->source, IEC104_FILE_SERVICE_CALL_OPEN_READ, &request);
|
||
request.name = task->bytes + 12U; request.name_length = task->bytes[11];
|
||
memset(&open, 0, sizeof(open)); result = Action(self, handlers, context, &request, &open);
|
||
if (!Valid_Result(result)) { ++self->status.invalid_callbacks; }
|
||
if (result != IEC104_FILE_SERVICE_RESULT_OK) {
|
||
if (Operation_Error(self, task, 1U)) { (void)Flush_Replies(self); }
|
||
return IEC104_FILE_SERVICE_EXECUTE_OK;
|
||
}
|
||
++self->status.reads_opened;
|
||
memset(&self->reader, 0, sizeof(self->reader)); self->reader.occupied = true;
|
||
self->reader.source = task->source; task->source.station = NULL;
|
||
self->reader.handle = open.handle; self->reader.size = open.size; self->reader.phase = FS_READ_OPEN;
|
||
name = open.name == NULL ? request.name : open.name;
|
||
name_length = open.name == NULL ? request.name_length : open.name_length;
|
||
if (name_length == 0U || name_length > IEC104_FILE_SERVICE_MAX_FILE_NAME) {
|
||
++self->status.invalid_callbacks;
|
||
if (Operation_Error(self, task, 1U)) { (void)End_Read(self, IEC104_FILE_SERVICE_END_ERROR); (void)Flush_Replies(self); }
|
||
return IEC104_FILE_SERVICE_EXECUTE_OK;
|
||
}
|
||
Prefix(self->buffer, &task->source, 4U, 7U, 0U);
|
||
self->buffer[11] = 0U; self->buffer[12] = name_length; memcpy(self->buffer + 13U, name, name_length);
|
||
Write32(self->buffer + 13U + name_length, 0U); Write32(self->buffer + 17U + name_length, open.size);
|
||
if (Freeze_Task(self, task, (uint16_t)(21U + name_length))) { (void)Flush_Replies(self); }
|
||
return IEC104_FILE_SERVICE_EXECUTE_OK;
|
||
}
|
||
|
||
/**
|
||
* 功能:IDLE准入先于read,拥塞时不取数;提交WAIT后偏移不动,下轮重取同一快照内容。
|
||
* 输入参数:self——本模块实例。
|
||
* handlers——回调集合。
|
||
* context——调用方上下文。
|
||
* 输出参数:self——本模块实例的更新结果。
|
||
* 返回值:返回IEC104_FileServiceExecuteResult_t结果;本函数显式处理IEC104_FILE_SERVICE_EXECUTE_EMPTY、IEC104_FILE_SERVICE_EXECUTE_ERROR、IEC104_FILE_SERVICE_EXECUTE_OK、IEC104_FILE_SERVICE_EXECUTE_WAIT,其余结果由下层调用传回。
|
||
* 说明:read失败锁存为空末段,不伪造P/N失败字段,主站须按激活大小发现截短。
|
||
*/
|
||
static IEC104_FileServiceExecuteResult_t Read_Data(IEC104_FileService_t *self,
|
||
const IEC104_FileServiceHandlers_t *handlers, void *context)
|
||
{
|
||
FileRead *reader = &self->reader;
|
||
IEC104_FileServiceRequest_t request;
|
||
IEC104_SlaveRequestState_t state;
|
||
IEC104_TcpSubmitResult_t query;
|
||
uint16_t length;
|
||
uint8_t checksum = 0U;
|
||
unsigned i;
|
||
bool last, called = false;
|
||
int sent, expired;
|
||
if (Has_Reply(self)) { return IEC104_FILE_SERVICE_EXECUTE_EMPTY; }
|
||
state = Check(self, &reader->source.identity);
|
||
if (state == IEC104_SLAVE_REQUEST_ERROR) { return IEC104_FILE_SERVICE_EXECUTE_ERROR; }
|
||
if (state == IEC104_SLAVE_REQUEST_STALE) { return IEC104_FILE_SERVICE_EXECUTE_OK; }
|
||
if (state == IEC104_SLAVE_REQUEST_WAIT_EVENTS) { return IEC104_FILE_SERVICE_EXECUTE_WAIT; }
|
||
/* 级10的op4虽已提交,仍可能排在统一队列中;级11的数据是nocache直交路径,
|
||
* 因此须以真实票据建立依赖,不能只依靠READ_DATA阶段或先前调用顺序。
|
||
* 0仅在op4提交OK后存入,代表直接交接;不等待主站ACK。
|
||
* PENDING在调用read之前返回WAIT,既不预读数据,也不刷新读期限;CANCELLED/ERROR不放行数据。 */
|
||
if (reader->confirmation_ticket != 0U) {
|
||
IEC104_ResponseState_t handed = IEC104_Slave_Get_Response_State(self->slave, reader->confirmation_ticket);
|
||
if (handed == IEC104_RESPONSE_PENDING) {
|
||
reader->waiting = true; ++self->status.idle_waits; return IEC104_FILE_SERVICE_EXECUTE_WAIT;
|
||
}
|
||
if (handed != IEC104_RESPONSE_HANDED) {
|
||
++self->status.send_errors; Fault(self, &reader->source.identity, false);
|
||
return IEC104_FILE_SERVICE_EXECUTE_ERROR;
|
||
}
|
||
}
|
||
query = FS_IDLE_QUERY(self->slave, &reader->source.identity, self->config.window_reserve);
|
||
if (query == IEC104_TCP_SUBMIT_WAIT) { reader->waiting = true; ++self->status.idle_waits; return IEC104_FILE_SERVICE_EXECUTE_WAIT; }
|
||
if (query != IEC104_TCP_SUBMIT_OK) {
|
||
++self->status.send_errors; Fault(self, &reader->source.identity, false); return IEC104_FILE_SERVICE_EXECUTE_ERROR;
|
||
}
|
||
if (reader->offset > reader->size) { Fault(self, &reader->source.identity, false); return IEC104_FILE_SERVICE_EXECUTE_ERROR; }
|
||
length = (uint16_t)((reader->size - reader->offset) < self->config.read_segment_bytes ?
|
||
(reader->size - reader->offset) : self->config.read_segment_bytes);
|
||
if (!reader->aborting) {
|
||
bool success;
|
||
Request_From(self, &reader->source, IEC104_FILE_SERVICE_CALL_NONE, &request);
|
||
request.handle = reader->handle; request.file_size = reader->size;
|
||
self->in_callback = true;
|
||
success = handlers->read(context, &request, reader->offset, self->buffer + 20U, length);
|
||
self->in_callback = false; called = true;
|
||
if (!success) { reader->aborting = true; }
|
||
}
|
||
if (reader->aborting) { length = 0U; }
|
||
last = reader->aborting || length == reader->size - reader->offset;
|
||
Prefix(self->buffer, &reader->source, 5U, 5U, 0U);
|
||
Write32(self->buffer + 11U, 0U); Write32(self->buffer + 15U, reader->offset); self->buffer[19] = last ? 0U : 1U;
|
||
for (i = 0U; i < length; ++i) { checksum = (uint8_t)(checksum + self->buffer[20U + i]); }
|
||
self->buffer[20U + length] = checksum;
|
||
/* read返回后再次确认会话和期限;回调已发生的故障返回OK,避免调用方误重做。 */
|
||
state = Check(self, &reader->source.identity);
|
||
if (state == IEC104_SLAVE_REQUEST_ERROR) { return called ? IEC104_FILE_SERVICE_EXECUTE_OK : IEC104_FILE_SERVICE_EXECUTE_ERROR; }
|
||
if (state == IEC104_SLAVE_REQUEST_STALE) { return IEC104_FILE_SERVICE_EXECUTE_OK; }
|
||
if (state == IEC104_SLAVE_REQUEST_WAIT_EVENTS) { return IEC104_FILE_SERVICE_EXECUTE_WAIT; }
|
||
expired = Expire(self);
|
||
if (expired != 0) { return expired < 0 && !called ? IEC104_FILE_SERVICE_EXECUTE_ERROR : IEC104_FILE_SERVICE_EXECUTE_OK; }
|
||
sent = Send(self, &reader->source, self->buffer, (uint16_t)(21U + length), false, true, NULL);
|
||
if (sent < 0) { return called ? IEC104_FILE_SERVICE_EXECUTE_OK : IEC104_FILE_SERVICE_EXECUTE_ERROR; }
|
||
reader->waiting = sent == 0;
|
||
if (sent == 0) { return IEC104_FILE_SERVICE_EXECUTE_WAIT; }
|
||
reader->offset += length; reader->progress_ms = FS_NOW(); ++self->status.read_frames;
|
||
if (last) {
|
||
if (!reader->aborting) { ++self->status.reads_completed; }
|
||
(void)End_Read(self, reader->aborting ? IEC104_FILE_SERVICE_END_ERROR : IEC104_FILE_SERVICE_END_COMPLETE);
|
||
}
|
||
return IEC104_FILE_SERVICE_EXECUTE_OK;
|
||
}
|
||
|
||
/**
|
||
* 功能:保存空文件的重复末段识别信息,不新增站点引用;资源归属仍由原写会话/COMMIT收尾槽负责。
|
||
* 输入参数:self——本模块实例。
|
||
* writer——日志写入回调。
|
||
* ready——就绪信息。
|
||
* 输出参数:self——本模块实例的更新结果。
|
||
* 返回值:无。
|
||
* 说明:ready为true才允许重复确认,真实写必须等COMMIT完成;不能因声明大小为0就提前报告持久化成功。
|
||
*/
|
||
static void Empty_Record(IEC104_FileService_t *self, const FileWrite *writer, bool ready)
|
||
{
|
||
memset(&self->empty_write, 0, sizeof(self->empty_write));
|
||
self->empty_write.valid = true; self->empty_write.ready = ready; self->empty_write.pending = true;
|
||
self->empty_write.source = writer->source; self->empty_write.source.station = NULL;
|
||
self->empty_write.serial = writer->serial; self->empty_write.file_id = writer->file_id;
|
||
}
|
||
|
||
/**
|
||
* 功能:末段完成时先实际占终结确认槽,再转为待COMMIT资源;预留挡住较晚op8。
|
||
* 输入参数:self——本模块实例。
|
||
* 输出参数:self——本模块实例的更新结果。
|
||
* 返回值:confirm == NULL时返回false;finish == NULL时返回false;其余分支返回false、true。
|
||
* 说明:TEST没有外部资源,确认立即就绪;真实空文件也必须等COMMIT结果才能重确认。
|
||
*/
|
||
static bool Schedule_Commit(IEC104_FileService_t *self)
|
||
{
|
||
FileWrite *writer = &self->writer;
|
||
FileConfirm *confirm;
|
||
FileFinish *finish;
|
||
bool test = writer->source.test;
|
||
confirm = Reserve_Confirm(self, &writer->source, writer->serial, writer->file_id, writer->segment, 0U, true, !test);
|
||
if (confirm == NULL) { return false; }
|
||
if (writer->size == 0U) { Empty_Record(self, writer, test); }
|
||
if (test) { Release_Source(self, &writer->source); memset(writer, 0, sizeof(*writer)); return true; }
|
||
finish = Move_Write_To_Finish(self, IEC104_FILE_SERVICE_CALL_COMMIT, IEC104_FILE_SERVICE_END_NONE);
|
||
if (finish == NULL) { return false; }
|
||
finish->confirm_index = (unsigned)(confirm - self->confirms);
|
||
return true;
|
||
}
|
||
|
||
/**
|
||
* 功能:本地暂存步骤不等通知读空:BUSY保留事件时仍能执行,应用不得在OPEN发布文件。
|
||
* 输入参数:self——本模块实例。
|
||
* handlers——回调集合。
|
||
* context——调用方上下文。
|
||
* 输出参数:self——本模块实例的更新结果。
|
||
* 返回值:返回IEC104_FILE_SERVICE_EXECUTE_OK的结果。
|
||
* 说明:op8先形成,再为空文件预留op10,保证即使主站不等确认就发数据也不颠倒回复。
|
||
*/
|
||
static IEC104_FileServiceExecuteResult_t Open_Write(IEC104_FileService_t *self,
|
||
const IEC104_FileServiceHandlers_t *handlers, void *context)
|
||
{
|
||
FileTask *task = &self->activation;
|
||
IEC104_FileServiceRequest_t request;
|
||
IEC104_FileServiceOpen_t open;
|
||
IEC104_FileServiceResult_t result;
|
||
unsigned position = 12U + task->bytes[11];
|
||
Request_From(self, &task->source, IEC104_FILE_SERVICE_CALL_OPEN_WRITE, &request);
|
||
request.name = task->bytes + 12U; request.name_length = task->bytes[11];
|
||
request.file_id = Read32(task->bytes + position); request.file_size = Read32(task->bytes + position + 4U);
|
||
memset(&open, 0, sizeof(open));
|
||
result = request.test ? IEC104_FILE_SERVICE_RESULT_OK : Action(self, handlers, context, &request, &open);
|
||
if (!Valid_Result(result)) { ++self->status.invalid_callbacks; result = IEC104_FILE_SERVICE_RESULT_FAILED; }
|
||
if (result == IEC104_FILE_SERVICE_RESULT_OK) {
|
||
memset(&self->writer, 0, sizeof(self->writer)); self->writer.occupied = true;
|
||
self->writer.source = task->source; task->source.station = NULL;
|
||
self->writer.handle = open.handle; self->writer.file_id = request.file_id;
|
||
self->writer.size = request.file_size; self->writer.serial = task->work.reply.write_serial;
|
||
if (!request.test) { ++self->status.writes_opened; }
|
||
}
|
||
if (Operation_Error(self, task, (uint8_t)result)) {
|
||
if (result == IEC104_FILE_SERVICE_RESULT_OK && request.file_size == 0U) { (void)Schedule_Commit(self); }
|
||
(void)Flush_Replies(self);
|
||
}
|
||
return IEC104_FILE_SERVICE_EXECUTE_OK;
|
||
}
|
||
|
||
/**
|
||
* 功能:数据环只属于本实例,因此保存代次+写序号即可定位其传输批次;另核对原站和T。
|
||
* 输入参数:segment——const FileSegment *所指数据。
|
||
* source——源数据。
|
||
* serial——流水号。
|
||
* 输出参数:无。
|
||
* 返回值: file_id在归属成立后独立检查,以便正确返回结果4,而非误当游离段丢弃。
|
||
* 说明:file_id在归属成立后独立检查,以便正确返回结果4,而非误当游离段丢弃。
|
||
*/
|
||
static bool Segment_Matches(const FileSegment *segment, const FileSource *source, uint64_t serial)
|
||
{
|
||
return segment->write_serial == serial && segment->generation == source->identity.generation &&
|
||
segment->station_id == source->station_id && segment->ca == source->ca && segment->test == source->test;
|
||
}
|
||
|
||
/**
|
||
* 功能:正常处理无论写入、拒绝还是丢弃都会消费环头,保证BUSY能在有限步骤内解除。
|
||
* 输入参数:self——本模块实例。
|
||
* handlers——回调集合。
|
||
* context——调用方上下文。
|
||
* 输出参数:self——本模块实例的更新结果。
|
||
* 返回值: 本地消费即使没有回调也返回OK;
|
||
* 说明:本地消费即使没有回调也返回OK;新查询/发送故障仍按本轮是否已调用应用区分。
|
||
*/
|
||
static IEC104_FileServiceExecuteResult_t Write_Segment(IEC104_FileService_t *self,
|
||
const IEC104_FileServiceHandlers_t *handlers, void *context)
|
||
{
|
||
FileSegment *segment = &self->segments[self->segment_head];
|
||
FileWrite *writer = &self->writer;
|
||
uint32_t number = segment->segment;
|
||
uint16_t length = segment->length;
|
||
uint8_t result = 0U;
|
||
bool last = !segment->more, called = false, success;
|
||
if (!writer->occupied || !Segment_Matches(segment, &writer->source, writer->serial)) {
|
||
FileRecent *empty = &self->empty_write, *silent = &self->silent_write;
|
||
/* 已终结空文件只复述既有结果;确认仍待交出时合并重复空末段,
|
||
* 不占第二槽、不重置原形成序号/期限,也不再次执行COMMIT。 */
|
||
if (empty->valid && Segment_Matches(segment, &empty->source, empty->serial) &&
|
||
!segment->malformed && !segment->bad_sum && segment->file_id == empty->file_id && length == 0U && last &&
|
||
(self->config.segment_mode == IEC104_FILE_SERVICE_SEGMENT_UNCHECKED || number == 0U)) {
|
||
Pop_Segment(self);
|
||
if (!empty->pending && empty->ready) {
|
||
if (Reserve_Confirm(self, &empty->source, empty->serial, empty->file_id, number, empty->result, true, false) == NULL) {
|
||
return IEC104_FILE_SERVICE_EXECUTE_ERROR;
|
||
}
|
||
empty->pending = true;
|
||
}
|
||
} else if (silent->valid && Segment_Matches(segment, &silent->source, silent->serial)) {
|
||
/* 健康Cancel的反馈只消耗一次;faulted已在Execute入口阻止业务发送。 */
|
||
Pop_Segment(self);
|
||
if (Reserve_Confirm(self, &silent->source, silent->serial, silent->file_id, number, 1U, true, false) == NULL) {
|
||
return IEC104_FILE_SERVICE_EXECUTE_ERROR;
|
||
}
|
||
memset(silent, 0, sizeof(*silent));
|
||
} else { ++self->status.stray_segments; Pop_Segment(self); }
|
||
if (Flush_Replies(self) < 0) { return IEC104_FILE_SERVICE_EXECUTE_ERROR; }
|
||
return IEC104_FILE_SERVICE_EXECUTE_OK;
|
||
}
|
||
/* 先检查旧进度期限,再处理已入环的段;受理时间不能复活过期的暂存会话。 */
|
||
if (writer->op8_sent && Expired(FS_NOW(), Write_Progress(writer), self->config.write_idle_timeout_ms)) {
|
||
++self->status.write_timeouts;
|
||
Pop_Segment(self);
|
||
if (!Fail_Write(self, 1U, writer->segment, IEC104_FILE_SERVICE_END_TIMEOUT) || Flush_Replies(self) < 0) { return IEC104_FILE_SERVICE_EXECUTE_ERROR; }
|
||
return IEC104_FILE_SERVICE_EXECUTE_OK;
|
||
}
|
||
/* 错误优先级固定:结构、模和、ID、偏移、剩余长度,最后才触及应用暂存。
|
||
* 长度使用size-received验证,避免uint32加法回绕;空非末段不能续命。 */
|
||
if (segment->malformed) { result = 1U; }
|
||
else if (segment->bad_sum) { result = 2U; }
|
||
else if (segment->file_id != writer->file_id) { result = 4U; }
|
||
else if (self->config.segment_mode == IEC104_FILE_SERVICE_SEGMENT_OFFSET && number != writer->received) { result = 3U; }
|
||
else if (writer->received > writer->size) { Fault(self, &writer->source.identity, false); return IEC104_FILE_SERVICE_EXECUTE_ERROR; }
|
||
else if (length > writer->size - writer->received || (last && length != writer->size - writer->received) || (length == 0U && !last)) { result = 3U; }
|
||
if (result != 0U) {
|
||
Pop_Segment(self);
|
||
if (!Fail_Write(self, result, number, IEC104_FILE_SERVICE_END_ERROR) || Flush_Replies(self) < 0) { return IEC104_FILE_SERVICE_EXECUTE_ERROR; }
|
||
return IEC104_FILE_SERVICE_EXECUTE_OK;
|
||
}
|
||
success = true;
|
||
if (!writer->source.test) {
|
||
IEC104_FileServiceRequest_t request;
|
||
Request_From(self, &writer->source, IEC104_FILE_SERVICE_CALL_NONE, &request);
|
||
request.handle = writer->handle; request.file_id = writer->file_id; request.file_size = writer->size;
|
||
self->in_callback = true;
|
||
success = handlers->write(context, &request, writer->received, segment->data, length, last);
|
||
self->in_callback = false; called = true;
|
||
} else { called = true; /* TEST模拟本段同样属于确定的本地推进。 */ }
|
||
/* write/TEST只执行一次,先消费本段;后续确认WAIT不能重做外部写入。 */
|
||
Pop_Segment(self);
|
||
if (!success) {
|
||
(void)Fail_Write(self, 1U, number, IEC104_FILE_SERVICE_END_ERROR);
|
||
} else {
|
||
writer->received += length; writer->segment = number;
|
||
if (length != 0U) { writer->progress_ms = FS_NOW(); writer->progress_valid = true; }
|
||
if (!writer->source.test) { ++self->status.segments_written; }
|
||
if (last) { (void)Schedule_Commit(self); }
|
||
else if (self->config.write_confirm_mode == IEC104_FILE_SERVICE_WRITE_CONFIRM_EACH) {
|
||
(void)Reserve_Confirm(self, &writer->source, writer->serial, writer->file_id, number, 0U, false, false);
|
||
}
|
||
}
|
||
if (!self->status.faulted) { (void)Flush_Replies(self); }
|
||
return called ? IEC104_FILE_SERVICE_EXECUTE_OK : IEC104_FILE_SERVICE_EXECUTE_ERROR;
|
||
}
|
||
|
||
/**
|
||
* 功能:不检查连接是否仍有效,清理必须在STOP/faulted后仍可交付。
|
||
* 输入参数:self——本模块实例。
|
||
* handlers——回调集合。
|
||
* context——调用方上下文。
|
||
* 输出参数:self——本模块实例的更新结果。
|
||
* 返回值:无。
|
||
* 说明:关闭完成不一定立即释放目录:固定错误末帧可能仍在等待HIGH容量。
|
||
*/
|
||
static void Deliver_Directory(IEC104_FileService_t *self, const IEC104_FileServiceHandlers_t *handlers, void *context)
|
||
{
|
||
IEC104_FileServiceRequest_t request;
|
||
FileDirectory *directory = &self->directory;
|
||
Request_From(self, &directory->source, IEC104_FILE_SERVICE_CALL_CLOSE_DIRECTORY, &request);
|
||
request.reason = directory->reason; request.handle = directory->handle;
|
||
(void)Action(self, handlers, context, &request, NULL);
|
||
++self->status.finishes; directory->closing = false; directory->closed = true;
|
||
if (directory->task_alive && self->tasks[directory->task_index].phase == FS_DIRECTORY_DONE) {
|
||
Remove_Task(self, &self->tasks[directory->task_index]);
|
||
}
|
||
Release_Directory(self);
|
||
}
|
||
|
||
/**
|
||
* 功能:COMMIT仅由Execute在READY后选中;交付前核对其真实预留槽仍属于本写会话。
|
||
* 输入参数:self——本模块实例。
|
||
* finish——FileFinish *所指数据。
|
||
* handlers——回调集合。
|
||
* context——调用方上下文。
|
||
* 输出参数:self——本模块实例的更新结果。
|
||
* finish——FileFinish *所指数据的更新结果。
|
||
* 返回值:按处理分支返回IEC104_FILE_SERVICE_EXECUTE_ERROR、IEC104_FILE_SERVICE_EXECUTE_OK。
|
||
* 说明:COMMIT不论成败均是最终资源回调,应用须自行释放handle;CLOSE/ABORT结果忽略。
|
||
*/
|
||
static IEC104_FileServiceExecuteResult_t Deliver_Finish(IEC104_FileService_t *self, FileFinish *finish,
|
||
const IEC104_FileServiceHandlers_t *handlers, void *context)
|
||
{
|
||
IEC104_FileServiceRequest_t request;
|
||
IEC104_FileServiceResult_t result;
|
||
FileConfirm *confirm = NULL;
|
||
bool commit = finish->call == IEC104_FILE_SERVICE_CALL_COMMIT;
|
||
uint64_t serial = finish->write_serial;
|
||
if (commit) {
|
||
if (finish->confirm_index >= IEC104_FILE_SERVICE_CONFIRM_CAPACITY) {
|
||
Fault(self, &finish->source.identity, false); return IEC104_FILE_SERVICE_EXECUTE_ERROR;
|
||
}
|
||
confirm = &self->confirms[finish->confirm_index];
|
||
if (!confirm->occupied || !confirm->reserved || confirm->write_serial != serial) {
|
||
Fault(self, &finish->source.identity, false); return IEC104_FILE_SERVICE_EXECUTE_ERROR;
|
||
}
|
||
}
|
||
Request_From(self, &finish->source, finish->call, &request);
|
||
request.reason = finish->reason; request.handle = finish->handle; request.file_size = finish->size;
|
||
request.file_id = finish->file_id; request.transferred = finish->transferred;
|
||
result = Action(self, handlers, context, &request, NULL);
|
||
++self->status.finishes;
|
||
if (commit) {
|
||
uint8_t wire_result = result == IEC104_FILE_SERVICE_RESULT_OK ? 0U : 1U;
|
||
if (!Valid_Result(result)) { ++self->status.invalid_callbacks; }
|
||
if (wire_result == 0U) { ++self->status.writes_committed; } else { ++self->status.writes_failed; }
|
||
confirm->bytes[19] = wire_result;
|
||
confirm->bytes[2] = (uint8_t)(self->config.write_confirm_cause | (confirm->source.test ? 0x80U : 0U) |
|
||
(self->config.write_confirm_cause == 7U && wire_result != 0U ? 0x40U : 0U));
|
||
confirm->reserved = false; /* 原序号、预留时刻、槽位置都不变。 */
|
||
if (self->empty_write.valid && self->empty_write.serial == serial) {
|
||
self->empty_write.ready = true; self->empty_write.result = wire_result;
|
||
}
|
||
}
|
||
/* 已交付COMMIT不论成败都在查询/发送之前移出清理集合,不再补ABORT。
|
||
* 尤其成功提交的事实不能因随后STOP或回复丢失而反转成失败。 */
|
||
Release_Source(self, &finish->source); memset(finish, 0, sizeof(*finish));
|
||
if (commit) { (void)Flush_Replies(self); }
|
||
return IEC104_FILE_SERVICE_EXECUTE_OK;
|
||
}
|
||
|
||
/**
|
||
* 功能:每次只推进一个收尾/本地步骤/请求帧:清理优先,然后写激活、数据环、读FIFO、读数据。
|
||
* 输入参数:self——本模块实例。
|
||
* handlers——回调集合。
|
||
* context——调用方上下文。
|
||
* mode——处理模式。
|
||
* 输出参数:self——本模块实例的更新结果。
|
||
* 返回值:未调用回调的超时推进也返回OK。
|
||
* 说明:先检查旧期限再触及应用,避免迟到段复活会话;未调用回调的超时推进也返回OK。
|
||
* CONTROL/ALL中的清理不受faulted或未读通知阻挡,只有对外发布的COMMIT必须满足READY。
|
||
* CONTROL可先OPEN而尚无应答原文,应用须继续有界推进,不能把这次OK当作级10候选已收集完成。
|
||
*/
|
||
IEC104_FileServiceExecuteResult_t IEC104_FileService_Execute_Next_Mode(IEC104_FileService_t *self,
|
||
const IEC104_FileServiceHandlers_t *handlers, void *context, IEC104_FileServiceExecuteMode_t mode)
|
||
{
|
||
bool tried[4] = { false, false, false, false }; /* 目录、读、两个写收尾;暂缓项每轮只检查一次。 */
|
||
unsigned attempt;
|
||
int expired;
|
||
if (!Owned(self) || self->in_callback || handlers == NULL || handlers->action == NULL ||
|
||
(mode != IEC104_FILE_SERVICE_EXECUTE_ALL && mode != IEC104_FILE_SERVICE_EXECUTE_CONTROL &&
|
||
mode != IEC104_FILE_SERVICE_EXECUTE_DATA) ||
|
||
((self->config.features & IEC104_FILE_SERVICE_FEATURE_DIRECTORY) != 0U && handlers->list == NULL) ||
|
||
((self->config.features & IEC104_FILE_SERVICE_FEATURE_READ) != 0U && handlers->read == NULL) ||
|
||
((self->config.features & IEC104_FILE_SERVICE_FEATURE_WRITE) != 0U && handlers->write == NULL)) { return IEC104_FILE_SERVICE_EXECUTE_ERROR; }
|
||
expired = Expire(self);
|
||
if (expired < 0) { return IEC104_FILE_SERVICE_EXECUTE_ERROR; }
|
||
if (expired != 0) { return IEC104_FILE_SERVICE_EXECUTE_OK; }
|
||
/* DATA阶段不执行新控制动作;清理仍由CONTROL/ALL推进,不能为低级数据跳过高层资源收尾。
|
||
* 两种模式都已执行Expire;拆分只限定本轮动作类别,不给读会话另起期限或绕过确认依赖。 */
|
||
if (mode == IEC104_FILE_SERVICE_EXECUTE_DATA) {
|
||
return !self->status.faulted && self->reader.occupied && self->reader.phase == FS_READ_DATA ?
|
||
Read_Data(self, handlers, context) : IEC104_FILE_SERVICE_EXECUTE_EMPTY;
|
||
}
|
||
/* 排序只决定可交付收尾的次序。WAIT_EVENTS的COMMIT让出,后面的ABORT/本地写不能被它堵住。 */
|
||
for (attempt = 0U; attempt < 4U; ++attempt) {
|
||
uint64_t sequence = 0U;
|
||
int selected = -1;
|
||
FileFinish *finish = NULL;
|
||
unsigned i;
|
||
if (!tried[0] && self->directory.occupied && self->directory.closing) { selected = 0; sequence = self->directory.finish_sequence; }
|
||
if (!tried[1] && self->read_finish.occupied && (selected < 0 || self->read_finish.sequence < sequence)) { selected = 1; sequence = self->read_finish.sequence; }
|
||
for (i = 0U; i < 2U; ++i) {
|
||
if (!tried[i + 2U] && self->write_finish[i].occupied && (selected < 0 || self->write_finish[i].sequence < sequence)) {
|
||
selected = (int)i + 2; sequence = self->write_finish[i].sequence;
|
||
}
|
||
}
|
||
if (selected < 0) { break; }
|
||
tried[selected] = true;
|
||
if (selected == 0) { Deliver_Directory(self, handlers, context); return IEC104_FILE_SERVICE_EXECUTE_OK; }
|
||
finish = selected == 1 ? &self->read_finish : &self->write_finish[(unsigned)selected - 2U];
|
||
if (finish->call == IEC104_FILE_SERVICE_CALL_COMMIT) {
|
||
IEC104_SlaveRequestState_t state;
|
||
if (self->status.faulted) { finish->call = IEC104_FILE_SERVICE_CALL_ABORT_WRITE; finish->reason = IEC104_FILE_SERVICE_END_CANCELLED; ++self->status.commits_cancelled; }
|
||
else {
|
||
state = Check(self, &finish->source.identity);
|
||
if (state == IEC104_SLAVE_REQUEST_ERROR) { return IEC104_FILE_SERVICE_EXECUTE_ERROR; }
|
||
if (state == IEC104_SLAVE_REQUEST_STALE) { return IEC104_FILE_SERVICE_EXECUTE_OK; }
|
||
if (state == IEC104_SLAVE_REQUEST_WAIT_EVENTS) { continue; }
|
||
}
|
||
}
|
||
return Deliver_Finish(self, finish, handlers, context);
|
||
}
|
||
if (self->status.faulted) { return IEC104_FILE_SERVICE_EXECUTE_EMPTY; }
|
||
/* 以下两个本地步骤刻意不查WAIT_EVENTS,否则保留op9的BUSY循环会自锁。
|
||
* 仍只允许写暂存,真正发布已经移到上方COMMIT屏障。 */
|
||
if (self->activation.occupied && self->activation.phase == FS_EXECUTE) { return Open_Write(self, handlers, context); }
|
||
if (self->segment_count != 0U) { return Write_Segment(self, handlers, context); }
|
||
if (self->task_count != 0U) {
|
||
FileTask *task = &self->tasks[self->order[0]];
|
||
if (task->phase == FS_EXECUTE || task->phase == FS_DIRECTORY) {
|
||
IEC104_SlaveRequestState_t state = Check(self, &task->source.identity);
|
||
if (state == IEC104_SLAVE_REQUEST_ERROR) { return IEC104_FILE_SERVICE_EXECUTE_ERROR; }
|
||
if (state == IEC104_SLAVE_REQUEST_STALE) { return IEC104_FILE_SERVICE_EXECUTE_OK; }
|
||
if (state == IEC104_SLAVE_REQUEST_WAIT_EVENTS) { return IEC104_FILE_SERVICE_EXECUTE_WAIT; }
|
||
if (task->phase == FS_DIRECTORY) { return Scan_Directory(self, task, handlers, context); }
|
||
if (task->operation == 1U) { return Open_Directory(self, task, handlers, context); }
|
||
return Open_Read(self, task, handlers, context);
|
||
}
|
||
}
|
||
if (mode == IEC104_FILE_SERVICE_EXECUTE_ALL && self->reader.occupied && self->reader.phase == FS_READ_DATA) {
|
||
return Read_Data(self, handlers, context);
|
||
}
|
||
return IEC104_FILE_SERVICE_EXECUTE_EMPTY;
|
||
}
|
||
|
||
/**
|
||
* 功能:以ALL模式推进一次应用工作,包含清理、执行及读数据;
|
||
* 输入参数:self——本模块实例。
|
||
* handlers——回调集合。
|
||
* context——调用方上下文。
|
||
* 输出参数:self——本模块实例的更新结果。
|
||
* 返回值:回调借用及返回语义沿用模式入口。
|
||
* 说明:回调借用及返回语义沿用模式入口。
|
||
*/
|
||
IEC104_FileServiceExecuteResult_t IEC104_FileService_Execute_Next(IEC104_FileService_t *self,
|
||
const IEC104_FileServiceHandlers_t *handlers, void *context)
|
||
{
|
||
return IEC104_FileService_Execute_Next_Mode(self, handlers, context, IEC104_FILE_SERVICE_EXECUTE_ALL);
|
||
}
|
||
|
||
/**
|
||
* 功能:合并可处理期限:timer_active区分“没有定时器”和“已有定时器恰好到期为0”。
|
||
* 输入参数:status——状态快照。
|
||
* now——当前时刻。
|
||
* start——uint64_t值。
|
||
* timeout——超时状态。
|
||
* 输出参数:status——状态快照的更新结果。
|
||
* 返回值:无。
|
||
* 说明:内部调用:Remaining。
|
||
*/
|
||
static void Add_Timer(IEC104_FileServiceStatus_t *status, uint64_t now, uint64_t start, uint32_t timeout)
|
||
{
|
||
uint32_t remaining;
|
||
if (timeout == 0U) { return; }
|
||
remaining = Remaining(now, start, timeout);
|
||
if (!status->timer_active || remaining < status->timeout_remaining_ms) { status->timeout_remaining_ms = remaining; }
|
||
status->timer_active = true;
|
||
}
|
||
|
||
/**
|
||
* 功能:在局部副本合成快照,查询失败不改调用者输出,也不在只读接口里执行取消/关闭。
|
||
* 输入参数:self——本模块实例。
|
||
* status——状态快照。
|
||
* 输出参数:status——全部查询成功后写回快照,失败保持原值。
|
||
* 返回值:!Owned(self) || status == NULL || FS_STATUS(self->slave, &transport, NULL) != IEC104_TCP_OK时返回false;其余分支返回false、true。
|
||
* 说明:pending只说明工作存在;ready/need_process才决定零等待,背压不能导致空转。
|
||
*/
|
||
bool IEC104_FileService_Get_Status(const IEC104_FileService_t *self, IEC104_FileServiceStatus_t *status)
|
||
{
|
||
IEC104_FileServiceStatus_t value;
|
||
IEC104_TcpServerStatus_t transport;
|
||
const FileTask *oldest_task;
|
||
const FileConfirm *oldest_confirm;
|
||
bool reply, cleanup = false, commit = false, local = false;
|
||
uint64_t now;
|
||
unsigned i;
|
||
if (!Owned(self) || status == NULL || FS_STATUS(self->slave, &transport, NULL) != IEC104_TCP_OK) { return false; }
|
||
value = self->status; now = FS_NOW();
|
||
value.generation = self->session.generation; value.events_pending = transport.pending_event_count != 0U;
|
||
value.pending_requests = self->task_count + (self->activation.occupied ? 1U : 0U);
|
||
value.pending_segments = self->segment_count; value.pending_replies = 0U;
|
||
value.segments_full = self->segment_count == IEC104_FILE_SERVICE_SEGMENT_CAPACITY;
|
||
value.directory_active = self->directory.occupied && !self->directory.closed;
|
||
value.read_active = self->reader.occupied; value.write_active = self->writer.occupied;
|
||
value.write_test = self->writer.occupied && self->writer.source.test;
|
||
value.read_offset = self->reader.offset; value.read_size = self->reader.size;
|
||
value.write_received = self->writer.received; value.write_size = self->writer.size;
|
||
value.idle_waiting = self->reader.occupied && self->reader.waiting;
|
||
value.execute_pending = false; value.execute_ready = false; value.need_process = false;
|
||
value.timer_active = false; value.timeout_remaining_ms = 0U;
|
||
cleanup = (self->directory.occupied && self->directory.closing) || self->read_finish.occupied;
|
||
for (i = 0U; i < 2U; ++i) {
|
||
if (self->write_finish[i].occupied) {
|
||
if (self->write_finish[i].call == IEC104_FILE_SERVICE_CALL_COMMIT) { commit = true; }
|
||
else { cleanup = true; }
|
||
}
|
||
}
|
||
value.finish_pending = cleanup || commit; value.commit_waiting = commit && value.events_pending;
|
||
reply = Oldest_Reply(self, &oldest_task, &oldest_confirm) != 0U;
|
||
/* 固定回复无论是否队首都计期限,RESERVED_COMMIT同样计pending_replies。
|
||
* 未执行读请求则仅由下面的FIFO队首参加执行计时。 */
|
||
for (i = 0U; i < self->task_count; ++i) {
|
||
const FileTask *task = &self->tasks[self->order[i]];
|
||
if (task->phase == FS_REPLY) {
|
||
++value.pending_replies;
|
||
if (!value.faulted) { Add_Timer(&value, now, task->work.reply.formed_ms, self->config.reply_timeout_ms); }
|
||
} else if (task->phase == FS_EXECUTE || task->phase == FS_DIRECTORY) { value.execute_pending = true; }
|
||
}
|
||
if (self->activation.occupied) {
|
||
if (self->activation.phase == FS_REPLY) {
|
||
++value.pending_replies;
|
||
if (!value.faulted) { Add_Timer(&value, now, self->activation.work.reply.formed_ms, self->config.reply_timeout_ms); }
|
||
} else {
|
||
local = true;
|
||
if (!value.faulted) { Add_Timer(&value, now, self->activation.source.accepted_ms, self->config.execute_timeout_ms); }
|
||
}
|
||
}
|
||
for (i = 0U; i < IEC104_FILE_SERVICE_CONFIRM_CAPACITY; ++i) {
|
||
if (self->confirms[i].occupied) {
|
||
++value.pending_replies;
|
||
if (!value.faulted) { Add_Timer(&value, now, self->confirms[i].formed_ms, self->config.reply_timeout_ms); }
|
||
}
|
||
}
|
||
local = local || self->segment_count != 0U;
|
||
if (!value.faulted) {
|
||
if (self->task_count != 0U) {
|
||
const FileTask *head = &self->tasks[self->order[0]];
|
||
if (head->phase == FS_EXECUTE) { Add_Timer(&value, now, head->source.accepted_ms, self->config.execute_timeout_ms); }
|
||
if ((head->phase == FS_EXECUTE || head->phase == FS_DIRECTORY) && !value.events_pending && !head->waiting &&
|
||
(head->phase != FS_DIRECTORY || !reply)) { value.execute_ready = true; }
|
||
}
|
||
if (self->directory.occupied && self->directory.task_alive && !self->directory.closing && !self->directory.closed) {
|
||
Add_Timer(&value, now, self->directory.opened_ms, self->config.directory_timeout_ms);
|
||
}
|
||
if (self->reader.occupied && self->reader.phase == FS_READ_DATA) {
|
||
value.execute_pending = true;
|
||
Add_Timer(&value, now, self->reader.progress_ms, self->config.read_idle_timeout_ms);
|
||
if (!value.events_pending && !reply && !self->reader.waiting) { value.execute_ready = true; }
|
||
}
|
||
if (self->writer.occupied && self->writer.op8_sent) { Add_Timer(&value, now, Write_Progress(&self->writer), self->config.write_idle_timeout_ms); }
|
||
if (reply && !value.events_pending) {
|
||
value.need_process = oldest_task != NULL ? !oldest_task->waiting : (!oldest_confirm->reserved && !oldest_confirm->waiting);
|
||
}
|
||
if (value.timer_active && value.timeout_remaining_ms == 0U) { value.need_process = true; }
|
||
if ((self->reader.occupied || self->writer.occupied || self->directory.occupied || value.pending_requests != 0U || value.finish_pending) &&
|
||
(!transport.connected || transport.generation != self->session.generation)) { value.need_process = true; }
|
||
value.execute_pending = value.execute_pending || local || cleanup || commit;
|
||
value.execute_ready = value.execute_ready || local || cleanup || (commit && !value.events_pending);
|
||
} else { value.execute_pending = cleanup; value.execute_ready = cleanup; }
|
||
/* 回调内允许观察事实和计数,但压住递归推进提示;这不是重入许可。 */
|
||
if (self->in_callback) { value.execute_ready = false; value.need_process = false; value.timer_active = false; value.timeout_remaining_ms = 0U; }
|
||
*status = value; return true;
|
||
}
|