I. MQTT
MQTT protocol is used in an Internet of things project, which can be used to communicate between devices and software
MQTT: instant messaging protocol, transport layer protocol
Two. Commonly used:
1. Mqttkit (no longer maintained)
2.MQTTClient
a. set address port, account password and other basic information
b. subscribe to topics (you can subscribe to multiple topics)
c. implement the proxy callback method (processing data)
Three message transmission modes: (depending on the situation)
a. at least one time (message loss or repetition will occur)
b. at least once (make sure the message arrives, and message repetition will occur)
c. only once (make sure the message arrives once)
Four. Code:
#import <MQTTClient/MQTTClient.h> #import <MQTTClient/MQTTSessionManager.h>
Basic configuration information
- (void)setParameterWithManager { /** host: server address port: Server port tls: If tls protocol is used, mosca supports tls. If it is used, it should be set to true keepalive: Heartbeat time, in seconds, sending heartbeat packets every fixed time, heartbeat interval shall not be greater than 120s clean: session It needs to be noted whether to clear. If it is false, it means to keep the login. If the client logs in again offline, it can receive the offline message auth: Use login authentication or not user: User name pass: Password willTopic: Subscription theme willMsg: Customized offline messages willQos: Level of offline messages received clientId: Client id, it should be noted that this id needs to be globally unique, because the server distinguishes different clients according to this id. by default, after an id is logged in, if another connection is logged in with this id, the previous connection will be kicked out of the line. The UUID of the device I use */ NSString *clientId = [UIDevice currentDevice].identifierForVendor.UUIDString; self.sessionManager = [[MQTTSessionManager alloc] init]; [self.sessionManager connectTo:MQTTHOST port:MQTTPORT tls:false keepalive:60 //Heartbeat interval shall not be greater than 120 s clean:true auth:true user:MQTTUSERNAME pass:MQTTPASSWORD will:false willTopic:nil willMsg:nil willQos:0 willRetainFlag:false withClientId:clientId]; self.sessionManager.delegate = self; // Add monitor state observer [self.sessionManager addObserver:self forKeyPath:@"state" options:NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew context:nil]; // Subscription theme NSDictionary Type, Object by QoS,key by Topic self.sessionManager.subscriptions = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:MQTTQosLevelExactlyOnce] forKey:@"Topics you want to subscribe to(Talk to the backstage)"]; }
Monitor connection status
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context { switch (self.sessionManager.state) { case MQTTSessionManagerStateClosed: NSLog(@"Connection closed"); break; case MQTTSessionManagerStateClosing: NSLog(@"Connection closing"); break; case MQTTSessionManagerStateConnected: NSLog(@"Already connected"); break; case MQTTSessionManagerStateConnecting: NSLog(@"Connecting"); break; case MQTTSessionManagerStateError: { NSString *errorCode = self.sessionManager.lastErrorCode.localizedDescription; NSLog(@"Connection exception ----- %@",errorCode); } break; case MQTTSessionManagerStateStarting: NSLog(@"Start connecting"); break; default: break; } }
Processing data
// Realization MQTTSessionManagerDelegate Agent method, processing data. - (void)handleMessage:(NSData *)data onTopic:(NSString *)topic retained:(BOOL)retained { NSLog(@"theme:%@",topic); NSString *dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSData * newData = [dataString dataUsingEncoding:NSUTF8StringEncoding]; NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:newData options:NSJSONReadingMutableLeaves error:nil]; NSLog(@"data:%@",jsonDict); }
Finally, don't forget to remove the observer, otherwise the program will crash
[self.sessionManager removeObserver:self forKeyPath:@"state"];
If you think it's helpful, you can use your hard-working hands to like or pay attention to it~
Your affirmation is very important to me!