Server
-
class Server : public std::enable_shared_from_this<Server>
service model for IEC60870-5-104 communication as server
Public Functions
-
~Server()
Close and destroy server.
-
std::string getIP() const
Getter for ip of remote server
- Returns:
ip string
-
std::uint_fast16_t getPort() const
Getter for port of remote server
- Returns:
port number
-
void setMaxOpenConnections(std::uint_fast8_t max_open_connections)
Sets the maximum number of open connections the server can handle simultaneously.
This method updates the internal limit for the maximum number of concurrent open connections allowed on the server. When the limit changes, it updates the relevant subsystem responsible for enforcing this constraint.
- Parameters:
max_open_connections – The new maximum number of open connections the server should allow.
-
std::uint_fast8_t getMaxOpenConnections() const
Retrieves the maximum number of connections that can be simultaneously open on the server.
This method returns the predetermined upper limit for concurrent open connections allowed by the server. It helps manage server capacity and ensures that system resources are properly allocated and protected from exceeding this limit.
- Returns:
The maximum number of open connections allowed on the server.
-
void start()
start listening for client connections, send periodic broadcasts
- Throws:
std::runtime_error – if slave thread failed to start
-
void stop()
stop listening for client connections
-
bool isRunning()
test if server is currently active
- Returns:
information on active state of server
-
bool hasStations() const
Test if Stations exists at this NetworkStation.
- Returns:
information on availability of child Station objects
-
bool isExistingConnection(IMasterConnection connection)
Checks if a given master connection already exists in the server.
This method inspects the internal connection map to determine whether the provided master connection has already been registered with the server.
- Parameters:
connection – The master connection to verify its existence.
- Returns:
True if the connection exists, otherwise false.
-
bool hasOpenConnections() const
Test if Server has open connections to clients.
- Returns:
information if at least one connection exists
-
std::uint_fast8_t getOpenConnectionCount() const
get number of open connections to clients
- Returns:
open connection count
-
bool hasActiveConnections() const
Test if Server has active (open and not muted) connections to clients.
- Returns:
information if at least one connection is active
-
std::uint_fast8_t getActiveConnectionCount() const
get number of active (open and not muted) connections to clients
- Returns:
active connection count
-
Object::StationVector getStations() const
Get a list of all Stations.
- Returns:
vector with object stationer
-
std::shared_ptr<Object::Station> getStation(std::uint_fast16_t commonAddress) const
Get a Station that exists at this NetworkStation and is identified via information object address.
- Returns:
Stationer to Station or nullptr
-
bool hasStation(std::uint_fast16_t commonAddress) const
Test if Stations exists at this NetworkStation.
- Returns:
information on availability of child Station objects
-
std::shared_ptr<Object::Station> addStation(std::uint_fast16_t commonAddress)
Add a Station to this Station.
-
CS104_APCIParameters getParameters() const
Get a reference to the protocol parameters to be able to read and update these.
-
void setOnReceiveRawCallback(py::object &callable)
set python callback that will be executed on incoming message
- Throws:
std::invalid_argument – if callable signature does not match
-
void onReceiveRaw(unsigned char *msg, unsigned char msgSize)
Execute configured callback handlers on receiving raw messages.
- Parameters:
msg – Pointer to the raw message data received.
msgSize – Size of the raw message data received in bytes.
-
void setOnSendRawCallback(py::object &callable)
set python callback that will be executed on outgoing message
- Throws:
std::invalid_argument – if callable signature does not match
-
void onSendRaw(unsigned char *msg, unsigned char msgSize)
Execute configured callback handlers on sending raw messages.
- Parameters:
msg – Pointer to the raw message data received.
msgSize – Size of the raw message data received in bytes.
-
void setOnClockSyncCallback(py::object &callable)
set python callback that will be executed on incoming clock sync command
- Throws:
std::invalid_argument – if callable signature does not match
-
CommandResponseState onClockSync(std::string _ip, std::chrono::system_clock::time_point time)
Handles the clock synchronization request initiated from a specific client.
This method processes a clock synchronization request from a client, encapsulated with the client’s IP address and the target synchronization time. It facilitates actions such as invoking a Python callback, processing the time data into a structured format, and determining the appropriate response state.
- Parameters:
_ip – The IP address of the client requesting clock synchronization.
time – The target synchronization time represented as a std::chrono::system_clock::time_point object.
- Returns:
CommandResponseState indicating the result of the synchronization process. Possible values include:
RESPONSE_STATE_SUCCESS: The synchronization process was successful.
RESPONSE_STATE_FAILURE: The synchronization process failed.
RESPONSE_STATE_NONE: No specific response was generated.
-
void setOnUnexpectedMessageCallback(py::object &callable)
set python callback that will be executed on unexpected incoming messages
- Throws:
std::invalid_argument – if callable signature does not match
Execute configured callback handlers on receiving unexpected messages from a client.
- Parameters:
connection – The master connection from which the unexpected message was received.
message – A shared pointer to the incoming message that triggered the unexpected event.
cause – The reason why the message was classified as unexpected (e.g., unknown type ID or invalid cause-of-transmission).
-
void setOnConnectCallback(py::object &callable)
set python callback that will be executed on incoming connection requests
- Throws:
std::invalid_argument – if callable signature does not match
-
std::uint_fast16_t getTickRate_ms() const
getter for tickRate_ms
- Returns:
minimum interval between two periodic tasks
transmit a datapoint related message to a remote client
- Parameters:
point – datapoint that should be send via server
cause – reason for transmission
- Throws:
std::invalid_argument – if point type is not supported for this operation
- Returns:
information on operation success
send a message object to a remote client
- Parameters:
message – message that should be send via server
connection – send to a single client identified via internal connection object
- Returns:
information on operation success
Sends a batch of messages to connected clients.
This method is used to process and transmit a batch of data points encapsulated within a
Remote::Message::Batchobject. The method verifies various preconditions and constructs an ASDU (Application Service Data Unit) for transmission. The ASDU is populated with information derived from the batch and connection parameters, and is then sent to the master connection, either with high or low priority, based on the cause of the transmission. The method ensures that the ASDU and associated resources are managed appropriately during this process.- Parameters:
batch – A shared pointer to the
Remote::Message::Batchobject containing the data points to be transmitted. The batch must have valid data points.connection – The master connection (
IMasterConnection) through which the batch will be sent. If null, the batch is processed and sent in low-priority mode.
- Returns:
True if the batch is successfully processed and transmitted, otherwise false.
-
void sendActivationConfirmation(IMasterConnection connection, CS101_ASDU asdu, bool negative = false)
Sends an activation confirmation ASDU to the master connection.
This method is responsible for cloning incoming ASDUs into confirmation messages to the master connection. The message can either confirm or reject the activation request based on the specified parameters. If the ASDU is intended for a global common address, it is sent to all connected stations. Otherwise, it is sent directly to the requesting connection.
- Parameters:
connection – The master connection to which the activation confirmation will be sent.
asdu – The ASDU (Application Service Data Unit) to be modified and sent.
negative – A flag indicating whether the confirmation is negative (true) or positive (false).
-
void sendActivationTermination(IMasterConnection connection, CS101_ASDU asdu)
Sends an activation termination ASDU to the master connection.
This method clones and tansforms the incoming ASDU with the Cause of Transmission (COT) set to activation termination (CS101_COT_ACTIVATION_TERMINATION). It accounts for global or specific common addresses when sending the ASDU to the connected master station(s).
- Parameters:
connection – The master connection through which the ASDU will be sent.
asdu – The Application Service Data Unit (ASDU) to be sent, modified within the function.
-
void sendEndOfInitialization(std::uint_fast16_t commonAddress, CS101_CauseOfInitialization cause)
Sends an End of Initialization message (M_EI_NA_1) to the client.
This method sends an End of Initialization (M_EI_NA_1) message using the given common address and cause of initialization. This is typically used to signal the completion of a configuration and that some configurations got reset to initial values.
- Parameters:
commonAddress – The common address (source) where the message is sent. This is used to identify the originating system.
cause – The cause of initialization (
CS101_CauseOfInitialization) that specifies the reason for sending the initialization message.
-
void sendPeriodicInventory()
Send periodic measurement broadcasts.
-
void schedulePeriodicTask(const std::function<void()> &task, int interval)
Schedules a periodic task to be executed at a specified interval.
- Parameters:
task – A callable object representing the task to be executed periodically.
interval – The interval in milliseconds at which the task should be executed. Must be at least 1000ms. Throws std::out_of_range if the interval is less than 50ms.
-
void scheduleTask(const std::function<void()> &task, int delay = 0)
Schedules a task to be executed after a specified delay (or instant).
The order of execution will depend on the timestamp calculated from current time + delay. The delay may be negative for high priority tasks.
- Parameters:
task – The function to be executed.
delay – The delay in milliseconds before the task is executed. A negative delay executes the task immediately.
-
std::optional<uint8_t> getSelector(uint16_t ca, uint32_t ioa)
server thread function
-
std::shared_ptr<Remote::Message::IncomingMessage> getValidMessage(IMasterConnection connection, CS101_ASDU asdu)
validate incoming ASDU, send negative response if invalid receiver station or return ASDU wrapped in a IncomingMessage facade otherwise
- Parameters:
connection – reference to internal connection object
asdu – incoming ASDU packet
- Returns:
-
inline std::string toString() const
Generates a string representation of the server instance.
This method provides a detailed description of the server instance, including its IP address, port number, the number of connected clients, the number of associated stations, and the memory address of the server object.
- Returns:
A string containing the server’s state and attributes.
Public Static Functions
Factory method to create an instance of the Server class.
Provides a convenient way to instantiate a
Serverobject using shared pointers. The constructor ofServeris private, so this static method ensures proper allocation and initialization. The method allows customization of the bind IP address, TCP port, tick rate, selection timeout, the maximum number of open connections, and transport security.- Parameters:
bind_ip – The IP address on which the server will accept connections. Defaults to “0.0.0.0”.
tcp_port – The TCP port for the server. Defaults to IEC_60870_5_104_DEFAULT_PORT.
tick_rate_ms – The interval, in milliseconds, at which the server executes periodic tasks. Defaults to 100 ms.
select_timeout_ms – The timeout, in milliseconds, for select operations. Defaults to 100 ms.
max_open_connections – The maximum number of simultaneous open connections allowed. A value of 0 means no limit. Defaults to 0.
transport_security – A shared pointer to a TransportSecurity object to enable secure communication. Defaults to nullptr.
- Returns:
A
std::shared_ptrto the createdServerinstance.
-
static bool connectionRequestHandler(void *parameter, const char *ipAddress)
Callback to accept or decline incoming client connections.
- Parameters:
parameter – reference to custom bound connection data
ipAddress – ip address of client
- Returns:
-
static void connectionEventHandler(void *parameter, IMasterConnection connection, CS104_PeerConnectionEvent event)
Callback to handle connection state changes.
- Parameters:
parameter – reference to custom bound connection data
connection – reference to internal connection object
event – state change event (opened,closed,muted,unmuted identified via constants)
-
static void rawMessageHandler(void *parameter, IMasterConnection connection, uint_fast8_t *msg, int msgSize, bool sent)
Callback for logging incoming and outgoing byteStreams.
Warning
DEBUG FUNCTION, IN ORDER TO ACTIVE THIS CALLBACK REMOVE COMMENT WRAPPER IN CONSTRUCTOR
- Parameters:
parameter – reference to custom bound connection data
connection – reference to internal connection object
msg – pointer to first character of message
msgSize – character count of message
sent – direction of message
-
static bool interrogationHandler(void *parameter, IMasterConnection connection, CS101_ASDU asdu, QualifierOfInterrogation qoi)
Callback for reacting on incoming clock sync command and sending responses.
Callback for reacting on incoming interrogation command and sending responses
- Parameters:
parameter – reference to custom bound connection data
connection – reference to internal connection object
asdu – incoming ASDU packet
newtime – synchronized current timestamp formated as CP56Time2a
parameter – reference to custom bound connection data
connection – reference to internal connection object
asdu – incoming ASDU packet
qoi – which group of states and measurements are requested for interrogation (group 1-16 or general represented in constants)
- Returns:
if command was handled.. if not it will be passed to asduHandler
- Returns:
if command was handled.. if not it will be passed to asduHandler
-
static bool counterInterrogationHandler(void *parameter, IMasterConnection connection, CS101_ASDU asdu, QualifierOfCIC qcc)
Callback for reacting on incoming counter interrogation command and sending responses.
- Parameters:
parameter – reference to custom bound connection data
connection – reference to internal connection object
asdu – incoming ASDU packet
qcc – which group of counters are requested for interrogation (group 1-4 or general represented in constants)
- Returns:
if command was handled.. if not it will be passed to asduHandler
-
static bool readHandler(void *parameter, IMasterConnection connection, CS101_ASDU asdu, int ioAddress)
Callback for reacting on incoming read request command and sending responses.
- Parameters:
parameter – reference to custom bound connection data
connection – reference to internal connection object
asdu – incoming ASDU packet
ioAddress – unqiue identifier of information object whom’s state/value should be responded
- Returns:
if command was handled.. if not it will be passed to asduHandler
-
static bool asduHandler(void *parameter, IMasterConnection connection, CS101_ASDU asdu)
Callback for reacting on incoming commands.
- Parameters:
parameter – reference to custom bound connection data
connection – reference to internal connection object
asdu – incoming ASDU packet
- Returns:
if command was handled.. if not server responds negative confirmation to sender
-
~Server()