外观
lib-mqtt 库参考
原文: https://finproducts.atlassian.net/wiki/spaces/JIDD3/pages/34793455872/FIN+5.3.1+lib-mqtt 中文整理基于 FIN 5.3.1
导读: 本页为
lib-mqtt的 API / 标签 / 函数参考文档。
以下为 API 参考,保留英文以便对照源码;目录已列出(英文标题便于检索);概述已尽量中译。
目录(导读)
- lib
- meta
- docs
- tags
- funcs
- Overview
- Broker Connectivity
- TCP/IP
- Optional Connect Configuration
- Web Sockets
- Authentication
- Publish
- Subscribe
- MQTT Points
- mqttPublish(conn, topic, payload, cfg: {})
概述(中译)
MQTT 连接器
API 正文(英文)
docs
Overview • Broker Connectivity • Publish • Subscribe • MQTT Points
tags
| mqttCertAlias | Used on an mqttConn to indicate which certificate and key pair to use for client authentication to the broker |
| mqttCleanSession | Whether to set the clean session flag on the connect request to the broker |
| mqttClientId | The client identifier to use when connecting to the broker |
| mqttConn | MQTT connector to an MQTT Broker |
| mqttConnRef | Used on a proxy point to reference its parent mqttConn |
| mqttMaxRetry | How many times to retry sending messages that require acknowlegment |
| mqttPoint | Point which synchronizes data via a MQTT connector |
| mqttQos | MQTT Quality of Service (QoS) - 0 - At most once (fire-and-forget) - 1 - At least once - 2 - Exactly once |
| mqttRetain | Set the retention flag on a published message |
| mqttRetryInterval | How long to wait between retries for messages that require acknowlegment |
| mqttVersion | MQTT protocol version |
| obsMqtt | Subscribe to MQTT connector published messages |
| obsMqttConnRef | Subscribe to the topic on this MQTT connector |
| obsMqttTopic | Receive published messages that match this filter |
funcs
| mqttPublish | Publish an MQTT message to the given topic on the broker |
lib mqtt
Overview
The MQTT library implements basic connector support to an MQTT broker. You can publish messages to a broker, and subscribe to messages from a broker by using the obsMqtt observable.
Broker Connectivity
The MQTT library supports connections to a broker using either the 3.1.1 or 5.0 version of the protocol. The protocol version to use can be configured on the connector rec using the mqttVersion tag.
You can specify the client identifier for the connector to use when connecting to the broker by setting the mqttClientId tag on the connector rec. If one is not specified, the connector will auto-generate one the first time it connects and save it on the rec.
TCP/IP
To connect to an MQTT broker over TCP/IP, use the mqtt scheme for a plaintext connection, or mqtts for a TLS connection to the broker. If you don't specify a port, then 1883 will be used for mqtt and 8883 will be used for mqtts.
dis: "MQTT Connector"
conn
mqttConn
uri: `mqtt://192.168.10.1/`
mqttVersion: "v3.1.1"
mqttClientId: "MqttTestClient"Optional Connect Configuration
By default, the connection to the broker is opened with cleanSession=false (3.1.1) and cleanStart=false (5.0). You can set the mqttCleanSession: true tag on the connector rec to force the connection to use cleanSession/cleanStart.
By default, the session expiry interval is configured for "on-close", meaning the broker will retain client session information until the network connection is closed. Use the mqttSessionExpiryInterval tag on the connector rec to specify the duration for the session to linger after the connection is closed. A value of -1sec indicates that the session should never expire.
Web Sockets
To connect to an MQTT broker using web sockets, use the ws scheme for plaintext connections, and wss for secure web sockets.
dis: "MQTT Connector"
conn
mqttConn
uri: `ws://192.168.10.2/`
mqttVersion: "v5"
mqttClientId: "MqttWebSocketTest"Authentication
By default, the connector will attempt to connect to the MQTT broker anonymously.
If the broker requires a username and password, set the username tag on the conn rec and then call passwordSet() with the conn rec's id to set the password:
passwordsSet(@mqttConnId, "password")Some MQTT brokers require client certificate authentication over TLS. To configure client certificate authentication, set the mqttCertAlias tag to the alias in the crypto manager that contains your client's private key and certificate. You can add your private key and certificates to the crypto store for SkySpark using the crypto tool or through the UI as described in the https section of the crypto docs.
Some brokers also allow you to connect to the broker over the HTTPS port using Application-Layer Protocol Negotiation (ALPN). If your broker requires this type of connectivity, you must set the application protocol on the conn rec using the mqttAppProtocols tag. For example. to connect to an AWS IoT broker on the HTTPS port using ALPN you might set up a connector like this
mqttConn
uri: `mqtts://foo-ats.iot.eu-west-1.amazonaws.com:443`
mqttVersion: "v3.1.1"
mqttCertAlias: "myMqttClient"
mqttClientId: "MyAwsThing"
mqttAppProtocols: "x-amzn-mqtt-ca"Publish
To publish a message to the broker use the mqttPublish() func.
read(@myMqttConn).mqttPublish("testTopic", "Hello, MQTT!", {mqttQos: 2})Subscribe
MQTT topic subscription is handled using the task framework. Create a task that subscribes to the obsMqtt observable. The obsMqtt observable fires an event whenever a message is received that matches configured topic filter.
MQTT observations include the following tags:
type: "obsMqtt"ts: DateTime when the observation was firedtopic: the name of the topic that the message was published to.payload: the payload of the published message. This will be a FantomBufobject. But you can use the variousiofunctions to read/parse the payload.userProps: the user properties of the published message. This will be aDictwhere the keys and values are bothStr. User properties are a feature of MQTT v5 only.
These are the config tags:
mqttQos: The maximum quality-of-service guarantee you are willing to accept for published messages.obsMqttConnRef: Which connector to subscribe to the topic onobsMqttTopic: the topic filter to subscribe with. This may be a specific topic, or a valid MQTT topic filter. If it is a filter, then your task will receive messages for potentially multiple topics.
obsMqtt
obsMqttConnRef: @myMqttConn
obsMqttTopic: "test/#"
mqttQos: 2
taskExpr:
(obs) => do
logInfo("mqttTask", ioReadStr(obs->payload))
endMQTT Points
Due to the open nature of MQTT payloads, the MQTT basic connector does not include direct support for points like there are for other connectors. In order to use values from an MQTT topic subscription, obsMqtt tasks can use different approaches based on the message format and requirements:
- Make transient commits to the
curValandcurStatustags of a point record and allow thehisCollectCovorhisCollectIntervalconfiguration to trend the data - Use
hisWrite()to directly write historical data to a point record
Since there is no standard format for an MQTT message payload the obsMqtt task must get the value(s) out of the message and determine what point record to commit/write the values to.
There could be several ways to determe the point record to write to. One way could simply be using the topic the message is published to and storing the topic on the point record.
For example, imagine each published message has this format:
{
"theValue": "79.6",
"sensor": "temperature",
"unit": "°F"
}Then one way to configure the task is shown below:
obsMqtt
obsMqttConnRef: @myMqttConn
obsMqttTopic: "#"
mqttQos: 2
taskExpr:
(obs) => do
msg: ioReadJson(obs->payload, {safeNames})
myPoint: read(myMqttTopic == obs->topic, false)
if (myPoint != null)
diff(myPoint, {curVal:parseNumber(msg->theValue).as(msg->unit), curStatus:"ok"}, {transient}).commit
enddef
func:mqttPublish
mqttPublish(conn, topic, payload, cfg: {})
Publish an MQTT message to the given topic on the broker. Currently, the payload of the message must be a Str.
The following configuration options are supported:
mqttQos: The quality-of-service to use for publishing the message. If not specified, then QoS0is used. SeemqttQos.mqttRetain: Should the message be retained on the broker (true|false). If not specified, thenfalseis used. SeemqttRetain.mqttExpiryInterval: Sets the expiry interval for the message as a Duration. This is only supported in MQTT 5.mqttUserProps: A Dict of user properties to include in the message. This is only supported in MQTT 5.
read(@mqttConn).mqttPublish("/test", "{a: a JSON object}", {mqttQos: 2, mqttExpiryInterval: 30min, mqttUserProps: {key: "value"}})meta
| admin | ✓ |
| def | func:mqttPublish |
| is | func |
| lib | lib:mqtt |
| name | mqttPublish |
supertypes
| feature | Feature namespace of definitions formatted as feature:name |
| func | Axon function |
def
mqttCertAlias
Used on an mqttConn to indicate which certificate and key pair to use for client authentication to the broker.
meta
| def | mqttCertAlias |
| is | str |
| lib | lib:mqtt |
| tagOn | mqttConn |
supertypes
| val | Data value type |
| scalar | Scalar is an atomic value kind |
| str | Unicode string of characters |
def
mqttCleanSession
Whether to set the clean session flag on the connect request to the broker.
meta
| def | mqttCleanSession |
| is | bool |
| lib | lib:mqtt |
| tagOn | mqttConn |
supertypes
| val | Data value type |
| scalar | Scalar is an atomic value kind |
| bool | Boolean value true or false |
def
mqttClientId
The client identifier to use when connecting to the broker
meta
| def | mqttClientId |
| is | str |
| lib | lib:mqtt |
| tagOn | mqttConn |
supertypes
| val | Data value type |
| scalar | Scalar is an atomic value kind |
| str | Unicode string of characters |
def
mqttConn
MQTT connector to an MQTT Broker.
meta
| connFeatures | {} |
| def | mqttConn |
| icon | mqtt |
| is | conn |
| lib | lib:mqtt |
usage
| mqttConn conn |
supertypes
| marker | Marker labels a dict with typing information |
| entity | Top-level dicts with a unique identifier |
| conn | Connector for communication to a remote system |
tags
| actorTimeout | Timeout for messages send to the connector's actor thread |
| connErr | Error message associated when connStatus indicates an error condition |
| connLinger | Linger timeout used to keep a connector open |
| connOpenRetryFreq | Duration used for connector open retries |
| connPingFreq | Duration used to configure the auto-ping feature on a given connector |
| connState | Current connection state of a connector as one of the predefined strings |
| connStatus | Current status of a connector as one of the predefined strings See Connectors |
| connTuningRef | Reference to a tuning configuration defined by a connTuning rec |
| dis | Display name for an entity |
| disabled | Indicates the entity is in a disabled state |
| id | Defines the unique identifier of an entity in system using a ref value type |
| mqttCertAlias | Used on an mqttConn to indicate which certificate and key pair to use for client authentication to the broker |
| mqttCleanSession | Whether to set the clean session flag on the connect request to the broker |
| mqttClientId | The client identifier to use when connecting to the broker |
| mqttMaxRetry | How many times to retry sending messages that require acknowlegment |
| mqttRetryInterval | How long to wait between retries for messages that require acknowlegment |
| mqttVersion | MQTT protocol version |
| password | Manages password which is hashed/stored to the password store |
| uri | Universal resource identifier |
| username | Username for an authentication account |
def
mqttConnRef
Used on a proxy point to reference its parent mqttConn
meta
| def | mqttConnRef |
| is | ref |
| lib | lib:mqtt |
| of | mqttConn |
| tagOn | mqttPoint |
supertypes
| val | Data value type |
| scalar | Scalar is an atomic value kind |
| ref | Reference to an entity |
def
mqttMaxRetry
How many times to retry sending messages that require acknowlegment
meta
| def | mqttMaxRetry |
| is | int |
| lib | lib:mqtt |
| tagOn | mqttConn |
supertypes
| val | Data value type |
| scalar | Scalar is an atomic value kind |
| number | Integer or floating point numbers annotated with an optional unit |
| int | Unitless integer number |
def
mqttPoint
Point which synchronizes data via a MQTT connector.
meta
| def | mqttPoint |
| is | connPoint |
| lib | lib:mqtt |
usage
| mqttPoint point |
supertypes
| marker | Marker labels a dict with typing information |
| entity | Top-level dicts with a unique identifier |
| point | Data point such as a sensor or actuator |
| connPoint | Point associated with a connector for data synchronization with a remote system |
tags
| connTuningRef | Reference to a tuning configuration defined by a connTuning rec |
| cur | Supports current value |
| curCalibration | Calibration value to apply to adjust the value read from the connector before updating curVal |
| curConvert | Conversion to apply when reading curVal from connector |
| dis | Display name for an entity |
| disMacro | Display name using macro syntax |
| disabled | Indicates the entity is in a disabled state |
| enum | Defines an eumeration of string key names |
| equipRef | Reference to equip which contains this entity |
| ghgFactorHis | Identifies point record with interval emission factor data that the Greenhouse Gas Emission Engine uses to calculate emissions |
| his | Supports historization of data |
| hisConvert | Conversion to apply when reading history data from connector |
| id | Defines the unique identifier of an entity in system using a ref value type |
| kind | Kind name used to identity a value data type |
| maxVal | Inclusive maximum for a numeric value |
| minVal | Inclusive minimum for a numeric value |
| mqttConnRef | Used on a proxy point to reference its parent mqttConn |
| navName | Navigation name commonly used with disMacro to create computed display strings |
| pointFunction | Classifies the point as a sensor, command, or setpoint |
| pointQuantity | Quantity the point senses or controls |
| pointSubject | What the point senses or controls |
| siteRef | Reference to site which contains the entity |
| spaceRef | Reference to space which contains this entity |
| systemRef | Reference to system |
| tz | Timezone identifier from standard timezone database |
| unit | Unit identifier from standard unit database |
| writable | Supports writing data |
| writeConvert | Conversion to apply when writing writeVal to the connector |
def
mqttQos
MQTT Quality of Service (QoS)
0- At most once (fire-and-forget)1- At least once2- Exactly once
meta
| def | mqttQos |
| is | number |
| lib | lib:mqtt |
| tagOn | obsMqtt |
supertypes
| val | Data value type |
| scalar | Scalar is an atomic value kind |
| number | Integer or floating point numbers annotated with an optional unit |
def
mqttRetain
Set the retention flag on a published message.
meta
| def | mqttRetain |
| is | bool |
| lib | lib:mqtt |
supertypes
| val | Data value type |
| scalar | Scalar is an atomic value kind |
| bool | Boolean value true or false |
def
mqttRetryInterval
How long to wait between retries for messages that require acknowlegment
meta
| def | mqttRetryInterval |
| is | duration |
| lib | lib:mqtt |
| tagOn | mqttConn |
supertypes
| val | Data value type |
| scalar | Scalar is an atomic value kind |
| number | Integer or floating point numbers annotated with an optional unit |
| duration | Number with a unit of time |
def
mqttVersion
MQTT protocol version
meta
| def | mqttVersion |
| enum | See below |
| is | str |
| lib | lib:mqtt |
| tagOn | mqttConn |
enum
| v3_1_1 | |
| v5 |
supertypes
| val | Data value type |
| scalar | Scalar is an atomic value kind |
| str | Unicode string of characters |
def
obsMqtt
Subscribe to MQTT connector published messages
meta
| def | obsMqtt |
| is | observable |
| lib | lib:mqtt |
supertypes
| marker | Marker labels a dict with typing information |
| observable | Observable subscription - see docs |
tags
| mqttQos | MQTT Quality of Service (QoS) - 0 - At most once (fire-and-forget) - 1 - At least once - 2 - Exactly once |
| obsMqttConnRef | Subscribe to the topic on this MQTT connector |
| obsMqttTopic | Receive published messages that match this filter |
def
obsMqttConnRef
Subscribe to the topic on this MQTT connector
meta
| def | obsMqttConnRef |
| is | ref |
| lib | lib:mqtt |
| of | mqttConn |
| tagOn | obsMqtt |
supertypes
| val | Data value type |
| scalar | Scalar is an atomic value kind |
| ref | Reference to an entity |
def
obsMqttTopic
Receive published messages that match this filter
meta
| def | obsMqttTopic |
| is | str |
| lib | lib:mqtt |
| tagOn | obsMqtt |
supertypes
| val | Data value type |
| scalar | Scalar is an atomic value kind |
| str | Unicode string of characters |