Paho-MQTT C 库使用

1、MQTTAsync_connectOptions

typedef struct
{
	/** The eyecatcher for this structure.  must be MQTC. */
	char struct_id[4];
	/** The version number of this structure.  Must be 0, 1, 2, 3 4 5 6, 7 or 8.
	  * 0 signifies no SSL options and no serverURIs
	  * 1 signifies no serverURIs
      * 2 signifies no MQTTVersion
      * 3 signifies no automatic reconnect options
      * 4 signifies no binary password option (just string)
      * 5 signifies no MQTTV5 properties
      * 6 signifies no HTTP headers option
      * 7 signifies no HTTP proxy and HTTPS proxy options
	  */
	int struct_version;
	/** The "keep alive" interval, measured in seconds, defines the maximum time
      * that should pass without communication between the client and the server
      * The client will ensure that at least one message travels across the
      * network within each keep alive period.  In the absence of a data-related
	  * message during the time period, the client sends a very small MQTT
      * "ping" message, which the server will acknowledge. The keep alive
      * interval enables the client to detect when the server is no longer
	  * available without having to wait for the long TCP/IP timeout.
	  * Set to 0 if you do not want any keep alive processing.
	  */
	int keepAliveInterval;
	/**
      * This is a boolean value. The cleansession setting controls the behaviour
      * of both the client and the server at connection and disconnection time.
      * The client and server both maintain session state information. This
      * information is used to ensure "at least once" and "exactly once"
      * delivery, and "exactly once" receipt of messages. Session state also
      * includes subscriptions created by an MQTT client. You can choose to
      * maintain or discard state information between sessions.
      *
      * When cleansession is true, the state information is discarded at
      * connect and disconnect. Setting cleansession to false keeps the state
      * information. When you connect an MQTT client application with
      * MQTTAsync_connect(), the client identifies the connection using the
      * client identifier and the address of the server. The server checks
      * whether session information for this client
      * has been saved from a previous connection to the server. If a previous
      * session still exists, and cleansession=true, then the previous session
      * information at the client and server is cleared. If cleansession=false,
      * the previous session is resumed. If no previous session exists, a new
      * session is started.
	  */
	int cleansession;
	/**
      * This controls how many messages can be in-flight simultaneously.
	  */
	int maxInflight;
	/**
      * This is a pointer to an MQTTAsync_willOptions structure. If your
      * application does not make use of the Last Will and Testament feature,
      * set this pointer to NULL.
      */
	MQTTAsync_willOptions* will;
	/**
      * MQTT servers that support the MQTT v3.1 protocol provide authentication
      * and authorisation by user name and password. This is the user name
      * parameter.
      */
	const char* username;
	/**
      * MQTT servers that support the MQTT v3.1 protocol provide authentication
      * and authorisation by user name and password. This is the password
      * parameter.
      */
	const char* password;
	/**
      * The time interval in seconds to allow a connect to complete.
      */
	int connectTimeout;
	/**
	 * The time interval in seconds after which unacknowledged publish requests are
	 * retried during a TCP session.  With MQTT 3.1.1 and later, retries are
	 * not required except on reconnect.  0 turns off in-session retries, and is the
	 * recommended setting.  Adding retries to an already overloaded network only
	 * exacerbates the problem.
	 */
	int retryInterval;
	/**
      * This is a pointer to an MQTTAsync_SSLOptions structure. If your
      * application does not make use of SSL, set this pointer to NULL.
      */
	MQTTAsync_SSLOptions* ssl;
	/**
      * A pointer to a callback function to be called if the connect successfully
      * completes.  Can be set to NULL, in which case no indication of successful
      * completion will be received.
      */
	MQTTAsync_onSuccess* onSuccess;
	/**
      * A pointer to a callback function to be called if the connect fails.
      * Can be set to NULL, in which case no indication of unsuccessful
      * completion will be received.
      */
	MQTTAsync_onFailure* onFailure;
	/**
	  * A pointer to any application-specific context. The
      * the <i>context</i> pointer is passed to success or failure callback functions to
      * provide access to the context information in the callback.
      */
	void* context;
	/**
	  * The number of entries in the serverURIs array.
	  */
	int serverURIcount;
	/**
	  * An array of null-terminated strings specifying the servers to
      * which the client will connect. Each string takes the form <i>protocol://host:port</i>.
      * <i>protocol</i> must be <i>tcp</i>, <i>ssl</i>, <i>ws</i> or <i>wss</i>.
      * The TLS enabled prefixes (ssl, wss) are only valid if a TLS version of the library
      * is linked with.
      * For <i>host</i>, you can
      * specify either an IP address or a domain name. For instance, to connect to
      * a server running on the local machines with the default MQTT port, specify
      * <i>tcp://localhost:1883</i>.
      */
	char* const* serverURIs;
	/**
      * Sets the version of MQTT to be used on the connect.
      * MQTTVERSION_DEFAULT (0) = default: start with 3.1.1, and if that fails, fall back to 3.1
      * MQTTVERSION_3_1 (3) = only try version 3.1
      * MQTTVERSION_3_1_1 (4) = only try version 3.1.1
	  */
	int MQTTVersion;
	/**
	  * Reconnect automatically in the case of a connection being lost?
	  */
	int automaticReconnect;
	/**
	  * Minimum retry interval in seconds.  Doubled on each failed retry.
	  */
	int minRetryInterval;
	/**
	  * Maximum retry interval in seconds.  The doubling stops here on failed retries.
	  */
	int maxRetryInterval;
	/**
	 * Optional binary password.  Only checked and used if the password option is NULL
	 */
	struct {
		int len;            /**< binary password length */
		const void* data;  /**< binary password data */
	} binarypwd;
	/*
	 * MQTT V5 clean start flag.  Only clears state at the beginning of the session.
	 */
	int cleanstart;
	/**
	 * MQTT V5 properties for connect
	 */
	MQTTProperties *connectProperties;
	/**
	 * MQTT V5 properties for the will message in the connect
	 */
	MQTTProperties *willProperties;
	/**
      * A pointer to a callback function to be called if the connect successfully
      * completes.  Can be set to NULL, in which case no indication of successful
      * completion will be received.
      */
	MQTTAsync_onSuccess5* onSuccess5;
	/**
      * A pointer to a callback function to be called if the connect fails.
      * Can be set to NULL, in which case no indication of unsuccessful
      * completion will be received.
      */
	MQTTAsync_onFailure5* onFailure5;
	/**
	 * HTTP headers for websockets
	 */
	const MQTTAsync_nameValue* httpHeaders;
	/**
	 * HTTP proxy
	 */
	const char* httpProxy;
	/**
	 * HTTPS proxy
	 */
	const char* httpsProxy;
} MQTTAsync_connectOptions;

keepAliveInterval

LinkedIn Login, Sign in | LinkedIn

MQTT 协议 Keep Alive 详解 | EMQ

并且由于我们的broker在internet上,broker和客户端的通讯必须要加密。所以这篇文章介绍的Mosquitto安装会包含使用用户名/密码的身份验证和SSL数据传输加密机制。对于SSL所需要的证书的申请和配置,本文介绍了两种方法。一种通过Let’s Encrypt申请免费证书。一种是采用自签名的证书。如果客户端不需要采用证书认证的方式,就推荐用Let’s Encrypt去生成服务器证书,因为Let’s Encrypt是一个被广泛认可的trusted CA,其发布的证书安全性更高。

虽然使用了用户名加密码的方式可以用来验证发布或订阅消息客户端的合法性,但用户名和密码在internet上是明文传输的,属于裸奔行为,非常容易被第三方截取。下面我们将使用SSL的方式对通讯进行加密。

/etc/mosquitto/certs/ca.crt:服务器自签名CA证书
/etc/mosquitto/certs/client.crt:客户端证书
/etc/mosquitto/certs/client.key:客户端密钥文件

#define BRIXBOT_ADDRESS     "ssl://www.domain.com:8883"	// You have to change it to your broker


#define BRIXBOT_USER        "bot"       // You have to change it to a valid user name of your broker
#define BRIXBOT_PASSWORD    "password"	// You have to change it to the user's password

#define BRIXBOT_SERVER_CA_FILE	"../../ssl/ca.crt"
#define BRIXBOT_CLIENT_CRT_FILE	"../../ssl/client.crt"
#define BRIXBOT_CLIENT_KEY_FILE	"../../ssl/client.key"



MQTTAsync_SSLOptions sslOpts = MQTTAsync_SSLOptions_initializer;
sslOpts.trustStore = BRIXBOT_SERVER_CA_FILE;
sslOpts.keyStore = BRIXBOT_CLIENT_CRT_FILE;
sslOpts.privateKey = BRIXBOT_CLIENT_KEY_FILE;
sslOpts.verify = 1;
 
...
 
connOpts.ssl = &sslOpts;
  • BRIXBOT_ADDRESS:前面的ssl表明我要用SSL加密去和broker通讯。后面是broker的域名和SSL通讯端口
  • BRIXBOT_USERBRIXBOT_PASSWORD:是用来以用户名密码的方式进行身份验证。其值要和broker创建的用户一致。请参考《MQTT什么鬼?第二讲:安装MQTT服务器(broker)
  • BRIXBOT_SERVER_CA_FILE:是服务器自签名CA证书,用于SSL验证
  • BRIXBOT_CLIENT_CRT_FILEBRIXBOT_CLIENT_KEY_FILE:分别为服务器给客户端生成的客户端证书和密钥文件。请参考《MQTT什么鬼?第三讲:史上最安全的MQTT服务

2、MQTTAsync_createOptions 

◆ sendWhileDisconnected

Whether to allow messages to be sent when the client library is not connected.

This feature was not originally available because with persistence enabled, messages could be stored locally without ever knowing if they could be sent. The client application could have created the client with an erroneous broker address or port for instance.

To enable messages to be published when the application is disconnected MQTTAsync_createWithOptions must be used instead of MQTTAsync_create to create the client object. The MQTTAsync_createOptions field sendWhileDisconnected must be set to non-zero, and the maxBufferedMessages field set as required - the default being 100.

MQTTAsync_getPendingTokens can be called to return the ids of the messages waiting to be sent, or for which the sending process has not completed.

◆ maxBufferedMessages

The maximum number of messages allowed to be buffered. This is intended to be used to limit the number of messages queued while the client is not connected. It also applies when the client is connected, however, so has to be greater than 0.

Pending tokens, inflight messages and buffered messages · Issue #1094 · eclipse/paho.mqtt.c · GitHub

Setting maxBufferedMessages to zero always gets a publish error · Issue #1193 · eclipse/paho.mqtt.c · GitHub

Paho Asynchronous MQTT C Client Library: Publish While Disconnected

Question about persistence and how configure it properly · Issue #1092 · eclipse/paho.mqtt.c · GitHub

ref:

Coding – 砖瓦匠

Paho-MQTT C 库使用 – 人人都懂物联网

Paho Asynchronous MQTT C Client Library: MQTTAsync_createOptions Struct Reference
GitHub - eclipse/paho.mqtt.c: An Eclipse Paho C client library for MQTT for Windows, Linux and MacOS. API documentation: https://eclipse.github.io/paho.mqtt.c/

MQTT----client paho.mqtt.c交叉编译_Stay Hungry Stay Foolish-CSDN博客_paho.mqtt.c编译

 https://github.com/google/boringssl

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值