MQTT protocol iOS Port porting 1

Source: Internet
Author: User

MQTTClient.h

#import <Foundation/Foundation.h> @protocol mqttdelegate <nsobject>/** * @brief Connection Server * * @param [in] n/A * @pa Ram [out] N/A * @return void * @note */-(void) Didconnect: (Nsuinteger) code;/** * @brief disconnected from the server * * @param [in] n/A * @ param [out] n/A * @return void * @note */-(void) diddisconnect;/** * @brief * * @param [in] n/A * @param [out] n/A * @re  turn void * @note */-(void) Didpublish: (nsuinteger) messageid;//fixme:create mosquittomessage class/** * @brief receive messages * * @param [in] n/A * @param [out] n/A * @return void * @note */-(void) Didreceivemessage: (nsstring*) message topic: (NSSTR ing*) topic;/** * @brief * * @param [in] n/A * @param [out] n/A * @return void * @note */-(void) Didsubscribe: (Nsuintege R) 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 (re adwrite,assign) unsigned short keepAlive; @property (readwrite,assign) BOOL cleansession; @property (r  eadwrite,assign) id<mqttdelegate> delegate;/** * @brief Singleton mode Setting * * @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 Connection Server * * @param [in] n/A * @param [out] n/A * @return void * @note */-(void) connect;/** * @brief connected to host * * @param [in] n/A * @param [out] n/A * @return void * @note */-(void) Connecttohost: (nsstring*) host;/** * @brief * * @pa Ram [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 * @n OTE */-(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 * * @p Aram [in] n/A * @param [out] n/A * @return void * @note */-(void) Unsubscribe: (NSString *) topic;//this is called Automat ically 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 Setting of the Singleton mode * * @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 Connection to MQTT * * @param [in] n/A * @param [out] n/A * @return void * @note */static void on_connect (struct Mosquitt    o *mosq, void *obj, int rc) {mqttclient* client = (mqttclient *) obj; [[Client Delegate] Didconnect: (Nsuinteger) RC];} /** * @brief disconnected from MQTT * * @param [in] n/A * @param [out] n/A * @return void * @note */static void on_disconnect (struct m    Osquitto *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 (Struc    T 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 was allocated * * @param [in] n/A * @param [out] n/A * @ret urn void * @note */+ (void) initialize{mosquitto_lib_init ();} /** * @brief Version information * * @param [in] n/A * @param [out] n/A * @return void * @note */+ (nsstring*) version{int Major, Mino    R, Revision;    Mosquitto_lib_version (&major, &minor, &revision); return [NSString stringwithformat:@ "%d.%d.%d", major, minor, revision];} /** * @brief Set some parameter status configuration * * @param [in] n/A * @pAram [out] N/A * @return void * @note */-(mqttclient *) Initwithclientid: (nsstring*) clientid{if (self = [Super ini        T]) {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 (@ "//connection successfully set UD");    } else {NSLog (@ "//Connection Failed");    }//Setup timer to handle network events//Fixme:better-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{C    Onst 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:nsutf    8StringEncoding]; 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



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.