Skip to content

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 ​

mqttCertAliasUsed on an mqttConn to indicate which certificate and key pair to use for client authentication to the broker
mqttCleanSessionWhether to set the clean session flag on the connect request to the broker
mqttClientIdThe client identifier to use when connecting to the broker
mqttConnMQTT connector to an MQTT Broker
mqttConnRefUsed on a proxy point to reference its parent mqttConn
mqttMaxRetryHow many times to retry sending messages that require acknowlegment
mqttPointPoint which synchronizes data via a MQTT connector
mqttQosMQTT Quality of Service (QoS) - 0 - At most once (fire-and-forget) - 1 - At least once - 2 - Exactly once
mqttRetainSet the retention flag on a published message
mqttRetryIntervalHow long to wait between retries for messages that require acknowlegment
mqttVersionMQTT protocol version
obsMqttSubscribe to MQTT connector published messages
obsMqttConnRefSubscribe to the topic on this MQTT connector
obsMqttTopicReceive published messages that match this filter

funcs ​

mqttPublishPublish 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 fired
  • topic: the name of the topic that the message was published to.
  • payload: the payload of the published message. This will be a Fantom Buf object. But you can use the various io functions to read/parse the payload.
  • userProps: the user properties of the published message. This will be a Dict where the keys and values are both Str. 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 on
  • obsMqttTopic: 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))
end

MQTT 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:

  1. Make transient commits to the curVal and curStatus tags of a point record and allow the hisCollectCov or hisCollectInterval configuration to trend the data
  2. 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
end


def ​

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 QoS 0 is used. See mqttQos.
  • mqttRetain: Should the message be retained on the broker (true | false). If not specified, then false is used. See mqttRetain.
  • 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✓
deffunc:mqttPublish
isfunc
liblib:mqtt
namemqttPublish

supertypes ​

featureFeature namespace of definitions formatted as feature:name
funcAxon function


def ​

mqttCertAlias ​

Used on an mqttConn to indicate which certificate and key pair to use for client authentication to the broker.


meta ​

defmqttCertAlias
isstr
liblib:mqtt
tagOnmqttConn

supertypes ​

valData value type
scalarScalar is an atomic value kind
strUnicode string of characters


def ​

mqttCleanSession ​

Whether to set the clean session flag on the connect request to the broker.


meta ​

defmqttCleanSession
isbool
liblib:mqtt
tagOnmqttConn

supertypes ​

valData value type
scalarScalar is an atomic value kind
boolBoolean value true or false


def ​

mqttClientId ​

The client identifier to use when connecting to the broker


meta ​

defmqttClientId
isstr
liblib:mqtt
tagOnmqttConn

supertypes ​

valData value type
scalarScalar is an atomic value kind
strUnicode string of characters


def ​

mqttConn ​

MQTT connector to an MQTT Broker.


meta ​

connFeatures{}
defmqttConn
iconmqtt
isconn
liblib:mqtt

usage ​

mqttConn  conn

supertypes ​

markerMarker labels a dict with typing information
entityTop-level dicts with a unique identifier
connConnector for communication to a remote system

tags ​

actorTimeoutTimeout for messages send to the connector's actor thread
connErrError message associated when connStatus indicates an error condition
connLingerLinger timeout used to keep a connector open
connOpenRetryFreqDuration used for connector open retries
connPingFreqDuration used to configure the auto-ping feature on a given connector
connStateCurrent connection state of a connector as one of the predefined strings
connStatusCurrent status of a connector as one of the predefined strings See Connectors
connTuningRefReference to a tuning configuration defined by a connTuning rec
disDisplay name for an entity
disabledIndicates the entity is in a disabled state
idDefines the unique identifier of an entity in system using a ref value type
mqttCertAliasUsed on an mqttConn to indicate which certificate and key pair to use for client authentication to the broker
mqttCleanSessionWhether to set the clean session flag on the connect request to the broker
mqttClientIdThe client identifier to use when connecting to the broker
mqttMaxRetryHow many times to retry sending messages that require acknowlegment
mqttRetryIntervalHow long to wait between retries for messages that require acknowlegment
mqttVersionMQTT protocol version
passwordManages password which is hashed/stored to the password store
uriUniversal resource identifier
usernameUsername for an authentication account


def ​

mqttConnRef ​

Used on a proxy point to reference its parent mqttConn


meta ​

defmqttConnRef
isref
liblib:mqtt
ofmqttConn
tagOnmqttPoint

supertypes ​

valData value type
scalarScalar is an atomic value kind
refReference to an entity


def ​

mqttMaxRetry ​

How many times to retry sending messages that require acknowlegment


meta ​

defmqttMaxRetry
isint
liblib:mqtt
tagOnmqttConn

supertypes ​

valData value type
scalarScalar is an atomic value kind
numberInteger or floating point numbers annotated with an optional unit
intUnitless integer number


def ​

mqttPoint ​

Point which synchronizes data via a MQTT connector.


meta ​

defmqttPoint
isconnPoint
liblib:mqtt

usage ​

mqttPoint  point

supertypes ​

markerMarker labels a dict with typing information
entityTop-level dicts with a unique identifier
pointData point such as a sensor or actuator
connPointPoint associated with a connector for data synchronization with a remote system

tags ​

connTuningRefReference to a tuning configuration defined by a connTuning rec
curSupports current value
curCalibrationCalibration value to apply to adjust the value read from the connector before updating curVal
curConvertConversion to apply when reading curVal from connector
disDisplay name for an entity
disMacroDisplay name using macro syntax
disabledIndicates the entity is in a disabled state
enumDefines an eumeration of string key names
equipRefReference to equip which contains this entity
ghgFactorHisIdentifies point record with interval emission factor data that the Greenhouse Gas Emission Engine uses to calculate emissions
hisSupports historization of data
hisConvertConversion to apply when reading history data from connector
idDefines the unique identifier of an entity in system using a ref value type
kindKind name used to identity a value data type
maxValInclusive maximum for a numeric value
minValInclusive minimum for a numeric value
mqttConnRefUsed on a proxy point to reference its parent mqttConn
navNameNavigation name commonly used with disMacro to create computed display strings
pointFunctionClassifies the point as a sensor, command, or setpoint
pointQuantityQuantity the point senses or controls
pointSubjectWhat the point senses or controls
siteRefReference to site which contains the entity
spaceRefReference to space which contains this entity
systemRefReference to system
tzTimezone identifier from standard timezone database
unitUnit identifier from standard unit database
writableSupports writing data
writeConvertConversion 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 once
  • 2 - Exactly once

meta ​

defmqttQos
isnumber
liblib:mqtt
tagOnobsMqtt

supertypes ​

valData value type
scalarScalar is an atomic value kind
numberInteger or floating point numbers annotated with an optional unit


def ​

mqttRetain ​

Set the retention flag on a published message.


meta ​

defmqttRetain
isbool
liblib:mqtt

supertypes ​

valData value type
scalarScalar is an atomic value kind
boolBoolean value true or false


def ​

mqttRetryInterval ​

How long to wait between retries for messages that require acknowlegment


meta ​

defmqttRetryInterval
isduration
liblib:mqtt
tagOnmqttConn

supertypes ​

valData value type
scalarScalar is an atomic value kind
numberInteger or floating point numbers annotated with an optional unit
durationNumber with a unit of time


def ​

mqttVersion ​

MQTT protocol version


meta ​

defmqttVersion
enumSee below
isstr
liblib:mqtt
tagOnmqttConn

enum ​

v3_1_1
v5

supertypes ​

valData value type
scalarScalar is an atomic value kind
strUnicode string of characters


def ​

obsMqtt ​

Subscribe to MQTT connector published messages


meta ​

defobsMqtt
isobservable
liblib:mqtt

supertypes ​

markerMarker labels a dict with typing information
observableObservable subscription - see docs

tags ​

mqttQosMQTT Quality of Service (QoS) - 0 - At most once (fire-and-forget) - 1 - At least once - 2 - Exactly once
obsMqttConnRefSubscribe to the topic on this MQTT connector
obsMqttTopicReceive published messages that match this filter


def ​

obsMqttConnRef ​

Subscribe to the topic on this MQTT connector


meta ​

defobsMqttConnRef
isref
liblib:mqtt
ofmqttConn
tagOnobsMqtt

supertypes ​

valData value type
scalarScalar is an atomic value kind
refReference to an entity


def ​

obsMqttTopic ​

Receive published messages that match this filter


meta ​

defobsMqttTopic
isstr
liblib:mqtt
tagOnobsMqtt

supertypes ​

valData value type
scalarScalar is an atomic value kind
strUnicode string of characters