Mqtt协议IOS移植完1

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

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

时间: 2024-11-08 14:21:40

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

Mqtt协议IOS端移植1

MQTTClient.h #import <Foundation/Foundation.h> @protocol MQTTDelegate <NSObject> /** * @brief 连接服务器 * * @param [in] N/A * @param [out] N/A * @return void * @note */ - (void) didConnect: (NSUInteger)code; /** * @brief 与服务器断开连接 * * @param [in] N

Mqtt协议IOS端移植3

ServerMqFramework.h #import "MqttFramework.h" @interface ServerMqFramework : MqttFramework /** * @brief 得到模块控制器的句柄单例 * * @param [in] N/A * @param [out] N/A * @return void * @note */ +(ServerMqFramework*)getMQttServerFrameInstance; - (int)callBus

Mqtt协议IOS端移植2

MqttFramework.h #import <Foundation/Foundation.h> #import "MQTTClient.h" #import "BusinessModuleProtocol.h" #import "BusinessFramework.h" #import "AppDelegate.h" @interface MqttFramework : NSObject<MQTTDele

MQTT协议简记

 一.定义 MQTT - MQ Telemetry Transport 轻量级的 machine-to-machine 通信协议. publish/subscribe模式. 基于TCP/IP. 支持QoS. 适合于低带宽.不可靠连接.嵌入式设备.CPU内存资源紧张. 是一种比较不错的Android消息推送方案. FacebookMessenger采用了MQTT. MQTT有可能成为物联网的重要协议. MQTT是轻量级基于代理的发布/订阅的消息传输协议,它可以通过很少的代码和带宽和远程设备连接.例

MQTT协议的使用

MQTT协议的使用: MQTT协议:是发布者,服务器(代理),客户(订阅者).之间通信的协议.客户通过MQTT协议,订阅自己的信息,订阅的内容给服务器.当需要有内容发布的时候,发布者将消息内容发送给服务器,服务器根据订阅了该消息的所有客户,将消息进行推送给所有订阅 该消息的客户(订阅者). MQTT协议在使用上,首先我们要将关于MQTT协议的代码弄到自己的工程中.这里只讲大致的使用过程,不确切的去讲. 首先要创建socket连接,这个和我们和网络通信的时候是一样的,首先都要去socket建立连接

MQTT协议笔记之消息流

前言 前面的笔记已把所有消息类型都过了一遍,这里从消息流的角度尝试解读一下. 网络故障 在任何网络环境下,都会出现一方连接失败,比如离开公司大门那一刻没有了WIFI信号.但持续连接的另一端-服务器可能不能立即知道对方已断开.类似网络异常情况,都有可能在消息发送的过程中出现,消息发送出去,就丢失了. MQTT协议假定客户端和服务器端稳定情况一般,彼此之通信管道不可靠,一旦客户端网络断开,情况就会很严重,很难恢复原状. 但别忘记,很多客户端会有永久性存储设备支持,比如闪存ROM.存储卡等,在通信出现

深度剖析MQTT协议的整个通信流程

http://www.elecfans.com/d/587483.html MQTT,目前物联网的最主要的协议,基本所有收费的云平台都是基于MQTT协议,比如机智云,和所有的开放云平台比如中国移动的oneNet.百度的云平台也都支持MQTT的接入.虽然MQTT很火,但是目前对MQTT的很少,尤其是在如何移植到嵌入式上来.大部分的平台商的做法都是跟模块商合作把MQTT协议集成到WiFi模块跟GPRS模块里面,捆绑一销售,不让用户过多的了解物联网最核心的东西. 在还没有深入去了解MQTT协议之前,总

基于MQTT协议谈谈物联网开发

1.MQTT协议: MQTT(Message Queuing Telemetry Transport,消息队列遥测传输协议),是一种基于TCP/IP实现发布/订阅模式的应用层协议,其主要特点有: (1)基于发布/订阅模式,应用程序解耦; (2)基于TCP/IP建立网络连接; (3)协议交换最小化,降低网络流量; 2.基于MQTT协议应用: (1)简单的发布订阅应用: (2)消息系统推送应用: (3)阿里云物联网应用: 由于知识能力受限,无法一一列举基于MQTT协议的各种应用,下面就以上述消息推送

MQTT协议及推送服务(二)

MQTT简介 MQTT全称叫做Message Queuing Telemetry Transport,意为消息队列遥测传输,是IBM开发的一个即时通讯协议.由于其维护一个长连接以轻量级低消耗著称,所以常用于移动端消息推送服务开发. MQTT特性 MQTT具有如下特性: 使用发布/订阅消息模式,提供一对多消息发布: 对负载内容屏蔽的消息传输: 使用TCP/IP进行网络连接: 主流的MQTT是基于TCP进行连接的,同样也有UDP版本的MQTT,但是不太常用,叫做MQTT-SN. 具有三种消息发布服务