本项目提供了一个 Swift 类包装器,用于 mosquitto
客户端库,该库实现了 MQTT 协议版本 3.1 和 3.1.1。
这个包使用 Swift Package Manager 构建,并且是 Perfect 项目的一部分,但是,它可以作为一个独立的服务器端 Swift 组件工作。
请确保您已安装并激活最新的 Swift 工具链。
本项目依赖于 mosquitto 库。要在 macOS 上安装,请尝试命令 brew
$ brew install mosquitto
注意
$ cd /usr/local/include && ln -s ../Cellar/mosquitto/1.6.3/include/mosquitto.h
pkgconfig
路径添加到环境变量中export PKG_CONFIG_PATH="/usr/local/Cellar/mosquitto/1.6.3/share/pkgconfig"
本项目依赖于 Ubuntu 16.04 库 libmosquitto-dev
$ sudo apt-get install -y libmosquitto-dev
在使用 Perfect Mosquitto 的任何功能之前,请通过调用 Mosquitto.OpenLibrary()
初始化函数集。此外,强烈建议在程序退出后调用 Mosquitto.CloseLibrary()
。
注意 这两个操作都不是线程安全的,因此请在任何线程之前执行操作。
Mosquitto 实例可以通过带或不带任何参数的方式构造。最简单的形式可以是
let m = Mosquitto()
这意味着为这个新实例分配一个随机客户端 ID,而所有消息和订阅将在断开连接后被清除。
但是,您也可以使用自定义的客户端 ID 进行分配,并指示保留所有消息和订阅,使用这个特定的名称。这对于在连接丢失的情况下恢复工作非常有用。
let mosquitto = Mosquitto(id: "myInstanceId", cleanSession: false)
消息代理是一个实现了 MQTT 协议的服务器,它在消息传递方面为所有客户端提供服务 - 从生产者接收消息并将消息分发给消息订阅者。
虽然连接到消息代理可以是异步的,保持活动状态或绑定到特定的网络地址,但 api connect()` 可以像下面的演示一样简洁 - 只需要主机名和端口(通常是 1883)
try moosquitto.connect(host: "mybroker.com", port: 1883)
尽管实例在不再使用对象时可以自动从代理 disconnect()
,但为了更好的实践,建议显式调用此函数。此外,同一个实例还提供 reconnect()` 函数。
Perfect Mosquitto 在处理线程方面非常灵活。客户端可以调用 start()` 在后台运行 mosquitto 线程,这将自动执行消息发布/接收,而无需在主线程中进行任何额外操作,即,线程将在调用
publish()` 后执行实际发送,并激活传入消息的回调。如果不再运行,您也可以随时通过调用
stop()
停止服务线程
// start the messaging thread as a background service, it will not block the main thread and will return immediately.
try mosquitto.start()
// do your other work in the main thread, such as publishing etc., and the messages received will go to the callbacks
// stop the background messaging service if no longer need.
try mosquitto.stop()
或者,作为替代方案,您可以在主线程中处理事件,通过以消息轮询的方式频繁调用 wait()
方法
// wait a minimal while for events.
// In this specific moment, mosquitto will perform actual message sending,
// and pull messages from broker / run call backs.
try mosquitto.wait(0)
wait()
的唯一参数是消息轮询的超时值,以毫秒为单位。零表示系统等待的最小周期,负值将被视为与 1000(1 秒)相同。
start()
/stop()
与 wait()
混用
一旦连接到代理,您可以随时发送消息
var msg = Mosquitto.Message()
msg.id = 100 // input your message id here
msg.topic = "publish/test"
msg.string = "publication test 🇨🇳🇨🇦"
let mid = try mosquitto.publish(message: msg)
如以上演示所示,首先设置一个空消息结构,然后分配一个消息 ID(整数)、此消息的主题和消息内容;然后调用 publish()
方法将其发送到代理,并返回消息 ID。
注意 消息内容也可以是二进制缓冲区,例如
// send a [Int8] array
msg.payload = [40, 41, 42, 43, 44, 45]
发布后,调用 start()
或 wait()
来执行实际的消息发送,如线程模型中所述。
在 Perfect Mosquitto 中接收 MQTT 消息的唯一方法是消息回调
mosquitto.OnMessage = { msg in
// print out message id
print(msg.id)
// print out message topic
print(msg.topic)
// print out message content
print(msg.string)
// print out message body, in a binary array form
print(msg.payload)
}//end on Message
设置回调后,您可以调用 subscribe()
在客户端完成消息订阅
try mosquitto.subscribe(topic: "publish/test")
订阅后,调用 start()
或 wait()
来执行实际的接收过程,如线程模型中所述。
除了上述功能外,Perfect Mosquitto 还提供了丰富的功能集,请查看项目参考以获取详细信息。
如果需要,请为您的 mosquitto 对象设置以下事件回调
API | 参数 | 描述 |
---|---|---|
OnConnect { status in } |
连接状态 |
连接时触发 |
OnDisconnected { status in } |
连接状态 |
断开连接时触发 |
OnPublish { msg in } |
消息 |
消息发送时触发 |
OnMessage { msg in } |
消息 |
消息到达时触发 |
OnSubscribe { id, qos in } |
(Int32, [Int32]) |
订阅时触发 |
OnUnsubscribe { id in } |
Int32 (消息 ID) |
取消订阅时触发 |
OnLog { level, content in } |
(LogLevel, String) |
日志输出时触发 |
设置 TLS 证书文件:func setTLS(caFile: String?, caPath: String?, certFile: String? = nil, keyFile: String? = nil, keyPass: String? = nil) throws
设置 TLS 验证方法:func setTLS(verify: SSLVerify = .PEER, version: String? = nil, ciphers: String? = nil) throws
设置预共享密钥:func setTLS(psk: String, identity: String, ciphers: String? = nil) throws
为 mosquitto 实例配置遗嘱信息:func setConfigWill(message: Message?) throws
为 mosquitto 实例配置用户名和密码:func login(username: String? = nil, password: String? = nil) throws
设置重试消息前等待的秒数:func setMessageRetry(max: UInt32 = 20)
设置一次可以“在途”的 QoS 1 和 2 消息的数量:func setInflightMessages(max: UInt32 = 20) throws
控制客户端意外断开连接时的行为:func reconnectSetDelay(delay: UInt32 = 2, delayMax: UInt32 = 10, backOff: Bool = false) throws
在连接丢失后重新连接到代理:func reconnect(_ asynchronous: Bool = true) throws
重用现有的 mosquitto 实例:func reset(id: String? = nil, cleanSession: Bool = true) throws
设置 MQTT 版本:func setClientOption(_ version: MQTTVersion = .V31, value: UnsafeMutableRawPointer) throws
解释异常(英文):static func Explain(_ fault: Exception) -> String
有关 Perfect 项目的更多信息,请访问 perfect.org。