MQTTClient.h

#import <Foundation/Foundation.h>

@protocol MQTTDelegate <NSObject>
/**
* @brief 连接server
*
* @param [in] N/A
* @param [out] N/A
* @return void
* @note
*/ - (void) didConnect: (NSUInteger)code; /**
* @brief 与server断开连接
*
* @param [in] N/A
* @param [out] N/A
* @return void
* @note
*/
- (void) didDisconnect; /**
* @brief
*
* @param [in] N/A
* @param [out] N/A
* @return void
* @note
*/
- (void) didPublish: (NSUInteger)messageId; // FIXME: create MosquittoMessage class
/**
* @brief 接收消息
*
* @param [in] N/A
* @param [out] N/A
* @return void
* @note
*/
- (void) didReceiveMessage: (NSString*)message topic:(NSString*)topic;
/**
* @brief
*
* @param [in] N/A
* @param [out] N/A
* @return void
* @note
*/
- (void) didSubscribe: (NSUInteger)messageId grantedQos:(NSArray*)qos;
/**
* @brief
*
* @param [in] N/A
* @param [out] N/A
* @return void
* @note
*/
- (void) didUnsubscribe: (NSUInteger)messageId; @end @interface MQTTClient : NSObject
{
struct mosquitto *mosq;
NSString *host;
unsigned short port;
NSString *username;
NSString *password;
unsigned short keepAlive;
BOOL cleanSession; id<MQTTDelegate> delegate;
NSTimer *timer;
} @property (readwrite,retain) NSString *host;
@property (readwrite,assign) unsigned short port;
@property (readwrite,retain) NSString *username;
@property (readwrite,retain) NSString *password;
@property (readwrite,assign) unsigned short keepAlive;
@property (readwrite,assign) BOOL cleanSession;
@property (readwrite,assign) id<MQTTDelegate> delegate; /**
* @brief 单例模式的设置
*
* @param [in] N/A
* @param [out] N/A
* @return void
* @note
*/ +(MQTTClient *)getMQTTInstance; /**
* @brief
*
* @param [in] N/A
* @param [out] N/A
* @return void
* @note
*/
+ (void) initialize; /**
* @brief
*
* @param [in] N/A
* @param [out] N/A
* @return void
* @note
*/
+ (NSString*) version; /**
* @brief
*
* @param [in] N/A
* @param [out] N/A
* @return void
* @note
*/
- (MQTTClient *) initWithClientId: (NSString*) clientId; /**
* @brief
*
* @param [in] N/A
* @param [out] N/A
* @return void
* @note
*/
- (void) setMessageRetry: (NSUInteger)seconds; /**
* @brief 连接server
*
* @param [in] N/A
* @param [out] N/A
* @return void
* @note
*/
- (void) connect;
/**
* @brief 连接到主机
*
* @param [in] N/A
* @param [out] N/A
* @return void
* @note
*/
- (void) connectToHost: (NSString*)host; /**
* @brief
*
* @param [in] N/A
* @param [out] N/A
* @return void
* @note
*/
- (void) reconnect;
/**
* @brief
*
* @param [in] N/A
* @param [out] N/A
* @return void
* @note
*/
- (void) disconnect;
/**
* @brief
*
* @param [in] N/A
* @param [out] N/A
* @return void
* @note
*/ - (void)publishString: (NSString *)payload toTopic:(NSString *)topic retain:(BOOL)retain;
//- (void)publishMessage /**
* @brief
*
* @param [in] N/A
* @param [out] N/A
* @return void
* @note
*/
- (void)subscribe: (NSString *)topic;
/**
* @brief
*
* @param [in] N/A
* @param [out] N/A
* @return void
* @note
*/
- (void)subscribe: (NSString *)topic withQos:(NSUInteger)qos; /**
* @brief
*
* @param [in] N/A
* @param [out] N/A
* @return void
* @note
*/
- (void)unsubscribe: (NSString *)topic; // This is called automatically when connected
- (void) loop: (NSTimer *)timer;
@end

MQTTClient.m

#import "MQTTClient.h"
#import "mosquitto.h" @implementation MQTTClient @synthesize host;
@synthesize port;
@synthesize username;
@synthesize password;
@synthesize keepAlive;
@synthesize cleanSession;
@synthesize delegate; /**
* @brief 单例模式的设置
*
* @param [in] N/A
* @param [out] N/A
* @return void
* @note
*/ static MQTTClient *qttInstance = nil; +(MQTTClient *)getMQTTInstance
{
@synchronized(self)
{
if(qttInstance==nil)
{
qttInstance=[[self alloc]init];
}
}
return qttInstance;
} /**
* @brief 连接mqtt
*
* @param [in] N/A
* @param [out] N/A
* @return void
* @note
*/
static void on_connect(struct mosquitto *mosq, void *obj, int rc)
{
MQTTClient* client = (MQTTClient *)obj;
[[client delegate] didConnect:(NSUInteger)rc];
} /**
* @brief 断开与mqtt的连接
*
* @param [in] N/A
* @param [out] N/A
* @return void
* @note
*/
static void on_disconnect(struct mosquitto *mosq, void *obj, int rc)
{
MQTTClient* client = (MQTTClient *)obj;
[[client delegate] didDisconnect];
} /**
* @brief publish message
*
* @param [in] N/A
* @param [out] N/A
* @return void
* @note
*/
static void on_publish(struct mosquitto *mosq, void *obj, int message_id)
{
MQTTClient* client = (MQTTClient *)obj;
[[client delegate] didPublish:(NSUInteger)message_id];
} /**
* @brief receive message
*
* @param [in] N/A
* @param [out] N/A
* @return void
* @note
*/
static void on_message(struct mosquitto *mosq, void *obj, const struct mosquitto_message *message)
{
MQTTClient * client = (MQTTClient *)obj;
NSString *topic = [NSString stringWithUTF8String: message->topic];
NSString *payload = [[[NSString alloc] initWithBytes:message->payload
length:message->payloadlen
encoding:NSUTF8StringEncoding] autorelease]; // FIXME: create MosquittoMessage class instead
[[client delegate] didReceiveMessage:payload topic:topic];
} /**
* @brief didSubscribe
*
* @param [in] N/A
* @param [out] N/A
* @return void
* @note
*/
static void on_subscribe(struct mosquitto *mosq, void *obj, int message_id, int qos_count, const int *granted_qos)
{
MQTTClient * client = (MQTTClient *)obj;
// FIXME: implement this
[[client delegate] didSubscribe:message_id grantedQos:nil];
} /**
* @brief
*
* @param [in] N/A
* @param [out] N/A
* @return void
* @note
*/
static void on_unsubscribe(struct mosquitto *mosq, void *obj, int message_id)
{
MQTTClient * client = (MQTTClient *)obj;
[[client delegate] didUnsubscribe:message_id];
} /**
* @brief Initialize is called just before the first object is allocated
*
* @param [in] N/A
* @param [out] N/A
* @return void
* @note
*/ + (void)initialize
{
mosquitto_lib_init();
} /**
* @brief 版本号信息
*
* @param [in] N/A
* @param [out] N/A
* @return void
* @note
*/
+ (NSString*)version
{
int major, minor, revision;
mosquitto_lib_version(&major, &minor, &revision);
return [NSString stringWithFormat:@"%d.%d.%d", major, minor, revision];
} /**
* @brief 设置些參数状态配置
*
* @param [in] N/A
* @param [out] N/A
* @return void
* @note
*/
- (MQTTClient *) initWithClientId: (NSString*) clientId
{
if ((self = [super init]))
{
const char* cstrClientId = [clientId cStringUsingEncoding:NSUTF8StringEncoding];
[self setHost: nil];
[self setPort: 1883];
[self setKeepAlive: 60];
[self setCleanSession: YES]; mosq = mosquitto_new(cstrClientId, cleanSession, self);
mosquitto_connect_callback_set(mosq, on_connect);
mosquitto_disconnect_callback_set(mosq, on_disconnect);
mosquitto_publish_callback_set(mosq, on_publish);
mosquitto_message_callback_set(mosq, on_message);
mosquitto_subscribe_callback_set(mosq, on_subscribe);
mosquitto_unsubscribe_callback_set(mosq, on_unsubscribe);
timer = nil;
}
return self;
} - (void) connect
{
const char *cstrHost = [host cStringUsingEncoding:NSASCIIStringEncoding];
const char *cstrUsername = NULL, *cstrPassword = NULL; if (username)
cstrUsername = [username cStringUsingEncoding:NSUTF8StringEncoding]; if (password)
cstrPassword = [password cStringUsingEncoding:NSUTF8StringEncoding]; // FIXME: check for errors
mosquitto_username_pw_set(mosq, cstrUsername, cstrPassword); int ret = mosquitto_connect(mosq, cstrHost, port, keepAlive); NSLog(@"mqtt-ret-code = %d",ret);
if (ret == 0)
{
NSLog(@"//连接成功 设置ud");
}
else
{ NSLog(@"//连接失败");
} // Setup timer to handle network events
// FIXME: better way to do this - hook into iOS Run Loop select() ? // or run in seperate thread?
timer = [NSTimer scheduledTimerWithTimeInterval:0.01 // 10ms
target:self
selector:@selector(loop:)
userInfo:nil
repeats:YES];
} - (void) connectToHost: (NSString*)aHost
{
[self setHost:aHost];
[self connect];
} - (void) reconnect
{
mosquitto_reconnect(mosq);
} - (void) disconnect
{
mosquitto_disconnect(mosq);
} - (void) loop: (NSTimer *)timer
{
mosquitto_loop(mosq, 1, 1);
} // FIXME: add QoS parameter? - (void)publishString: (NSString *)payload toTopic:(NSString *)topic retain:(BOOL)retain
{
const char* cstrTopic = [topic cStringUsingEncoding:NSUTF8StringEncoding];
const uint8_t* cstrPayload = (const uint8_t*)[payload cStringUsingEncoding:NSUTF8StringEncoding];
mosquitto_publish(mosq, NULL, cstrTopic, [payload length], cstrPayload, 0, retain);
} - (void)subscribe: (NSString *)topic
{
[self subscribe:topic withQos:0];
} - (void)subscribe: (NSString *)topic withQos:(NSUInteger)qos
{
const char* cstrTopic = [topic cStringUsingEncoding:NSUTF8StringEncoding];
mosquitto_subscribe(mosq, NULL, cstrTopic, qos);
} - (void)unsubscribe: (NSString *)topic
{
const char* cstrTopic = [topic cStringUsingEncoding:NSUTF8StringEncoding];
mosquitto_unsubscribe(mosq, NULL, cstrTopic);
} - (void) setMessageRetry: (NSUInteger)seconds
{
mosquitto_message_retry_set(mosq, (unsigned int)seconds);
} - (void) dealloc
{
if (mosq)
{
mosquitto_destroy(mosq);
mosq = NULL;
} if (timer) {
[timer invalidate];
timer = nil;
} [super dealloc];
} // FIXME: how and when to call mosquitto_lib_cleanup() ? @end

版权声明:本文博客原创文章。博客,未经同意,不得转载。

Mqtt协议IOS移植完1的更多相关文章

  1. Mqtt协议IOS端移植2

    MqttFramework.h #import <Foundation/Foundation.h> #import "MQTTClient.h" #import &qu ...

  2. Mqtt协议IOS端移植3

    ServerMqFramework.h #import "MqttFramework.h" @interface ServerMqFramework : MqttFramework ...

  3. MQTT 协议学习:008-在STM32上移植MQTT

    前言 通过前面了解MQTT有关概念.分析了有关的报文,我们对于这个协议也有了更深的认识.但纸上谈来终觉浅,绝知此事要躬行. 本文参考:<STM32+W5500+MQTT+Android实现远程数 ...

  4. 基于MQTT协议进行应用开发

    官方协议有句如下的话来形容MQTT的设计思想: "It is designed for connections with remote locations where a "sma ...

  5. MQTT协议通俗讲解

    参考 Reference v3.1.1 英文原版 中文翻译版 其他资源 网站 MQTT官方主页 Eclipse Paho 项目主页 测试工具 MQTT Spy(基于JDK) Chrome插件 MQTT ...

  6. MQTT 协议是个啥?这篇文章告诉你!

    文章首发于我的公众号「程序员cxuan」,欢迎大家关注呀- 说到做到! 之前有位读者给我留言说想要了解一下什么是 MQTT 协议,顺便还把我夸了一把,有点不好意思啦. 那么读者的要求必须要满足啊,所以 ...

  7. MQTT协议(一)

    MQTT(Message Queue Telemetry Transport),遥测传输协议,提供订阅/发布模式,更为简约.轻量,易于使用,针对受限环境(带宽低.网络延迟高.网络通信不稳定),可以简单 ...

  8. MQTT协议详解一

    首先给出MQTT协议的查看地址:http://public.dhe.ibm.com/software/dw/webservices/ws-mqtt/mqtt-v3r1.html 当然也有PDF版的,百 ...

  9. Lua编写wireshark插件初探——解析Websocket上的MQTT协议

    一.背景 最近在做物联网流量分析时发现, App在使用MQTT协议时往往通过SSL+WebSocket+MQTT这种方式与服务器通信,在使用SSL中间人截获数据后,Wireshark不能自动解析出MQ ...

随机推荐

  1. perl 传递对象到模块

    perl 中的对象 就是引用 通过new方法传递数据结构给各个模块 [root@wx03 test]# cat x1.pm package x1; use Data::Dumper; sub new ...

  2. 基于visual Studio2013解决C语言竞赛题之0907删除记录

       题目

  3. 西门子PLC学习笔记七-(位逻辑指令)

    位逻辑指令处理的对象为二进制位信号.存储在状态字"RLO"中. 1.触点与线圈指令 1)常开触点 在PLC中规定:操作数为1,则常开触点"动作(闭合)":操作数 ...

  4. IOS开发之UILabel动态高度设置方法

    项目中有这样的需求,要显示一本书的概述,默认显示2行,点击展开按钮,显示全部,点击收回,有显示2行. 开始的时候按钮事件中,可能写的是这样一段代码: if (isExpand) { [lblBrief ...

  5. protected的一些功能

    java的访问限制有private.protected.public.这里只想进一步认识一下protected. 我对protected有4个疑问: 1,在相同包中,是否可以调用其它类的protect ...

  6. 获取DOM元素位置和尺寸大小

    JavaScript获取DOM元素位置和尺寸大小 在一些复杂的页面中经常会用JavaScript处理一些DOM元素的动态效果,这种时候我们经常会用到一些元素位置和尺寸的计算,浏览器兼容性问题也是不可忽 ...

  7. hive regex insert join group cli

    1.insert Insert时,from子句既能够放在select子句后,也能够放在insert子句前,以下两句是等价的 hive> FROM invites a INSERT OVERWRI ...

  8. Response.AppendCookie

    //写入 protected void Button2_Click(object sender, EventArgs e) { HttpCookie cookie=new HttpCookie(&qu ...

  9. paip.提升用户体验---c++ qt自定义窗体(1)---标题栏的绘制

    源地址:http://blog.csdn.net/attilax/article/details/12343625 paip.提升用户体验---c++ qt自定义窗体(1)---标题栏的绘制 效果图: ...

  10. thinkphp 设置跨域请求

    场景:我的本地网页服务器无法访问本地的接口服务器接口提示一下错误:大致意思是:是一个跨域请求我的没有访问该地址的权限(接口服务器采用的是PHP编写) XMLHttpRequest cannot loa ...