Skip to main content

Reverse RPC Details

This document is intended for novice readers, introducing the concept, working principle, and configuration usage of Reverse RPC in ThingsGatewayRuntime.

What is Reverse RPC?

Basic Concept

RPC (Remote Procedure Call) is a communication method that allows one computer to call a program on another computer.

Reverse RPC is the "reverse" application of traditional RPC:

ModeDescriptionAnalogy
Traditional RPCClient actively calls server methodsA customer actively goes to a restaurant to order food
Reverse RPCServer passively accepts write requests from external systemsA restaurant prepares dishes and waits for customers to pick them up

Communication Model

Reverse RPC Communication Model

Applicable Scenarios

ScenarioDescriptionTypical Application
Remote ControlUpper computer remotely controls field devicesStart/stop devices, adjust parameters
Data DistributionConfiguration parameters distributed to devicesSet thresholds, recipe distribution
Command ExecutionExecute specific device operationsDevice reset, calibration operations

ThingsGatewayRuntime Reverse RPC Architecture

Architecture Layers

Reverse RPC Architecture

Invocation Flow

  1. External system initiates a write request
  2. Protocol adaptation layer receives the request
  3. Permission check (variable RPC enable, device write permission)
  4. Execute variable write
  5. Return execution result

Protocol Configuration Details

1. OPC UA Reverse RPC

Protocol Features

FeatureDescription
High SecuritySupports certificate authentication and encrypted communication
Cross-platformPlatform-independent communication protocol
Industrial StandardWidely used in industrial automation

Configuration Steps

Step 1: Create an OPC UA Server device

  1. Create a new channel in the gateway configuration
  2. Select the OPC UA Server driver
  3. Configure server parameters

Step 2: Configure server properties

ParameterDescriptionDefault Value
OpcUaStringUrlOPC UA service address (semicolon-separated, multiple URLs can be set)opc.tcp://127.0.0.1:49321
BigTextApplicationNameApplication name identifierThingsGateway OPC UA Server
SecurityPolicyWhether to enable security policyfalse
UserNameUsername (allows anonymous access when empty)Empty
PasswordPasswordEmpty
ServerCertificateNameServer certificate nameEmpty
IsAllVariableWhether to enable all variablesfalse

Step 3: Configure variable properties

PropertyDescriptionValue
DataTypeVariable data typeSelect based on actual needs, default Object

Usage Method

After an external OPC UA client connects to the gateway, it can directly write to the corresponding nodes, and the gateway will automatically write the data to the corresponding variables. The OPC UA Server automatically creates the node structure based on the device name and variable name.

Common Issues

IssueCauseSolution
Connection refusedCertificate not trustedImport the certificate to the trusted list or set SecurityPolicy to false
Authentication failedIncorrect username or passwordCheck UserName and Password configuration
Node does not existVariable not correctly configuredConfirm the variable has been added to the device

2. Modbus Slave Reverse RPC

Protocol Features

FeatureDescription
Simple and ReliableSimple protocol, easy to implement
Widely SupportedAlmost all industrial devices support it
Master-Slave ArchitectureMaster initiates requests, slave responds

Working Principle

The gateway acts as a Modbus slave, waiting for write requests from external masters:

External Master ────Write Command (Function Code 06/16)────▶ Gateway (Slave) ────▶ Variable Write
◀───────Response Result────────

Register Mapping

Register TypeFunction CodeAddress RangePurpose
Coil01 Read/05 Write00001-09999Digital output
Holding Register03 Read/06 Write/16 Write40001-49999Analog output

Configuration Steps

Step 1: Create a Modbus Slave device

  1. Add a new channel (TCP Service or serial port)
  2. Select the Modbus Slave driver
  3. Configure slave parameters

Step 2: Configure slave properties

ParameterDescriptionExample Value
StationDefault station number1
ModbusTypeModbus typeTcp
DeviceRpcEnableAllow RPC writetrue

Step 3: Configure variable mapping

Variable PropertyDescriptionExample
ServiceAddressSlave variable address"40001"
VariableRpcEnableAllow RPC writetrue
DataTypeData typeInt16/Float

Usage Method

The external Modbus master writes to the corresponding register address, and the gateway automatically writes the data to the mapped variable.

Test Verification

Using Modbus debug tools (such as Modbus Poll):

  1. Configure connection parameters (IP, port, slave address)
  2. Execute write operations
  3. Observe gateway logs and variable value changes

3. Web API Reverse RPC

Protocol Features

FeatureDescription
Easy to UseBased on HTTP protocol, easy to integrate
Cross-platformAny platform supporting HTTP can use it
RESTfulStandard REST API design

Interface Description

InterfaceMethodDescription
/api/GatewayWriteVariableController/SetVariableValuePOSTWrite variable value
/api/GatewayAuthController/LoginPOSTLogin to get Token
/api/GatewayDataController/GetVariableStatusPageListPOSTRead variable value

Configuration Steps

Step 1: Enable Web API service

The Web API service runs automatically when the gateway starts, on port 6100.

Step 2: Configure variable RPC properties

Enable RPC write permission in the variable properties.

Step 3: Get authentication Token

After login, get the Token. Subsequent requests need to carry the Token.

Usage Method

Request Example:

POST /api/GatewayWriteVariableController/SetVariableValue
Header: Authorization: Bearer {"{token}"}
Body: {
"Device1": {
"temperature_setpoint": 28.5
}
}

Response Example:

{
"code": 200,
"msg": "success",
"data": {
"Device1": {
"temperature_setpoint": {
"IsSuccess": true,
"OperCode": 0,
"ErrorMessage": ""
}
}
}
}

Authentication Description

ItemDescription
Authentication MethodJWT Token
Token Validity PeriodDefault 15 days (configurable via JWTOptions.ExpiredTime, in minutes)
Default Accountadmin / 111111

4. MQTT Reverse RPC

Protocol Features

FeatureDescription
LightweightSmall protocol overhead, suitable for low-bandwidth environments
Publish/SubscribeDecoupled message delivery pattern
IoT FriendlyWidely used in IoT scenarios

Topic Design

TopicDescriptionExample
Write RequestReceive write requestsgateway/rpc/write
Write ResponseReturn execution resultgateway/rpc/write/Response
Data RequestTrigger data pushgateway/rpc/quest

Message Format

Write Request Message:

{
"Device1": {
"temperature_setpoint": 28.5
}
}

Response Message:

{
"Device1": {
"temperature_setpoint": {
"IsSuccess": true,
"OperCode": 0,
"ErrorMessage": ""
}
}
}

Error Response Example:

{
"Device1": {
"temperature_setpoint": {
"IsSuccess": false,
"OperCode": 500,
"ErrorMessage": "The variable does not exist"
}
}
}

Configuration Steps

Step 1: Configure MQTT connection

ParameterDescriptionExample Value
IPIP addresslocalhost
PortPort1883
ClientIdClient IDgateway_client

Step 2: Configure RPC topics

ParameterDescriptionExample Value
RPC Write TopicRPC write topic prefixgateway/rpc/write
Data Request TopicTopic that triggers a full data uploadgateway/rpc/quest
QoS LevelQoS levelAtMostOnce

Step 3: Configure variable RPC properties

Variable PropertyDescriptionValue
Allow RPC WriteAllow this variable to be written through RPCtrue

QoS Level Description

LevelDescriptionApplicable Scenario
0At most once, may be lostNon-critical data
1At least once, may be duplicatedGeneral scenarios
2Exactly onceCritical data

Common Issues

Q1: RPC write failed, prompt "Insufficient permissions"

Solution:

  1. Check if VariableRpcEnable is true in the variable properties (Modbus Slave / MQTT)
  2. Check if DeviceRpcEnable is true in the device properties (Modbus Slave / MQTT)
  3. Check if the user role has the corresponding permission

Q2: OPC UA connection refused

Solution:

  1. Import the client certificate into the server's trusted list
  2. Ensure the client and server security policies are consistent (SecurityPolicy configuration)
  3. Check firewall rules
  4. If security policy is not needed, set SecurityPolicy to false

Q3: MQTT message lost

Solution:

  1. Increase the QoS level to at least 1
  2. Check if the topic configuration is correct
  3. Enable client auto-reconnect

Q4: Web API Token expired

Solution:

  1. The Token validity period is 15 days by default (configurable via JWTOptions.ExpiredTime), re-login is required after expiration
  2. Call the refresh interface when the Token is about to expire

Appendix

Glossary

TermExplanation
RPCRemote Procedure Call, a computer communication protocol
Reverse RPCAn RPC mode where the server passively accepts external calls
OPC UAOpen Platform Communications Unified Architecture, an industrial communication standard
ModbusA communication protocol widely used in the industrial field
MQTTMessage Queue Telemetry Transport, a lightweight IoT protocol
QoSQuality of Service level

Tip

This document is continuously updated. If you have any questions, please provide feedback in the community or check the latest online documentation.