首页 > 解决方案 > 如何在设备启动时从 adafruit 获取 MQTT 主题数据

问题描述

我正在构建一个 iphone 应用程序,它使用 MQTT_Client_Foundation( https://github.com/novastone-media/MQTT-Client-Framework ) 订阅和发布到 Adafruit.com 上的主题。我让它在服务器上更新值时连接并查找更新,并在点击按钮时发布到服务器。我的问题是我想在打开应用程序时获取服务器上的当前主题值,而不必等待更新。这是我现在的代码:

#import "ViewController.h"
#import <MQTTClient/MQTTClient.h>
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *batteryValueLabel;
@property (strong, nonatomic) IBOutlet UIImageView *tempValueLabel;
@property (strong, nonatomic) IBOutlet UILabel *temperatureValueLabel;
@property (weak, nonatomic) IBOutlet UILabel *levelValueLabel;
@property (weak, nonatomic) IBOutlet UILabel *tripValueLabel;
@property (weak, nonatomic) IBOutlet UILabel *dateValueLabel;
@property(nonatomic, strong, readwrite) NSArray *certificates;
@property(nonatomic, weak) IBOutlet UIButton *Fill;


-(IBAction)Turnon:(id)sender;
@end
NSString *trip = @"0";
int trigger =1;
int B = 50;
int T = 90;
MQTTSession *session;
@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tempValueLabel.frame = CGRectMake(20, 250-(T+45),65, T+45);
    _batteryValueLabel.frame = CGRectMake(114, 287, B*1.7, 63);
    NSString* myNewString = [NSString stringWithFormat:@"%d", T];
    self.temperatureValueLabel.text = myNewString;
    MQTTCFSocketTransport *transport = [[MQTTCFSocketTransport alloc] init];
    transport.host = @"io.adafruit.com";
    transport.port = 1883;
   
    session = [[MQTTSession alloc] init];
    session.userName = @"xxxxxxxxx";
    session.password = @"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
    session.transport = transport;
    session.delegate = self;

//这里为/GET修改了代码

     [session connectWithConnectHandler:^(NSError *error) {
   
        if(!error){
            
            [session subscribeToTopic:@"XXXXXX/feeds/+" atLevel:1 subscribeHandler:^(NSError *error, NSArray *gQoss){
                
        if (error) {
            NSLog(@"Subscription failed %@", error.localizedDescription);
        } else {
            NSLog(@"Subscription sucessfull! Granted Qos: %@", gQoss);
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

//在我看来,他们传递的是数字而不是字符串

            trip = @"0";
            NSData* data = [trip dataUsingEncoding:NSUTF8StringEncoding];
            [session publishData:data onTopic:@"gbenna/feeds/temperature/get" retain:NO qos:1 publishHandler:nil];
            NSLog(@"%@", trip);
            NSLog(@"%d",trigger);
                });}
    }];
            }
        else {NSLog(@"[connectWithConnectHandler]Error Connect %@", error.localizedDescription);}
    
    
}];

}

//this is continuously called and gets data when server values are updated
- (void)newMessage:(MQTTSession *)session
              data:(NSData *)data
           onTopic:(NSString *)topic
               qos:(MQTTQosLevel)qos
          retained:(BOOL)retained
               mid:(unsigned int)mid {
    NSString *dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"topic: %@", topic);
    NSLog(@"data:%@", dataString);
    if ([topic isEqualToString:@"xxxxxxx/feeds/temperature"]){
        T = [dataString intValue];
        self.temperatureValueLabel.text = dataString;
        self.tempValueLabel.frame = CGRectMake(20, 250-(T+45),65, T+45);
        if (T <= 69) {
            _tempValueLabel.image = [UIImage imageNamed:@"dk blue rectangle.png"];
        }
        else if ((69< B)&& (B <= 90)) {
            _tempValueLabel.image = [UIImage imageNamed:@"blue rectangle.png"];
        }
        else if (B > 90) {
            _tempValueLabel.image = [UIImage imageNamed:@"red rectangle.png"];
        }
    }
    if ([topic isEqualToString:@"xxxxxxxx/feeds/level"]){
        self.levelValueLabel.text = dataString;}
    if ([topic isEqualToString:@"xxxxxxxx/feeds/date"]){
        self.dateValueLabel.text = dataString;}
    if ([topic isEqualToString:@"xxxxxxxx/feeds/battery"]){
      
        B = [dataString intValue];
        _batteryValueLabel.frame = CGRectMake(114, 287, B*1.7, 63);
        if (B <= 20) {
            _batteryValueLabel.image = [UIImage imageNamed:@"red rectangle.png"];
        }
        else if ((20< B)&& (B <= 100)) {
            _batteryValueLabel.image = [UIImage imageNamed:@"green rectangle.png"];
        }
        else if (B > 100) {
            _batteryValueLabel.image = [UIImage imageNamed:@"red rectangle.png"];
        }
    }
    if ([topic isEqualToString:@"xxxxxxxxx/feeds/trip"]){
        self.tripValueLabel.text = dataString;}


}
//when I tap this button the value on the server is updated
-(IBAction)Turnon:(id)sender;{
    if(trigger ==1){
        trip = @"0";
        trigger = 2;
    }
    else if(trigger==2){
        trip = @"100";
        trigger = 1;
    }
    NSData* data = [trip dataUsingEncoding:NSUTF8StringEncoding];
    [session publishData:data onTopic:@"xxxxxxxxx/feeds/trip" retain:NO qos:1 publishHandler:nil];
    NSLog(@"%@", trip);
    NSLog(@"%d",trigger);
}
@end

有谁知道什么代码和放在哪里,这样当我打开应用程序时,它会在服务器上获取当前主题值而无需等待更新?

标签: iosmqttadafruit

解决方案


我得到了这个工作这是我的代码

#import "ViewController.h"
#import <MQTTClient/MQTTClient.h>
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *batteryValueLabel;
@property (strong, nonatomic) IBOutlet UIImageView *tempValueLabel;
@property (strong, nonatomic) IBOutlet UILabel *temperatureValueLabel;
@property (weak, nonatomic) IBOutlet UILabel *levelValueLabel;
@property (weak, nonatomic) IBOutlet UILabel *tripValueLabel;
@property (weak, nonatomic) IBOutlet UILabel *dateValueLabel;
@property(nonatomic, strong, readwrite) NSArray *certificates;
@property(nonatomic, weak) IBOutlet UIButton *Fill;


-(IBAction)Turnon:(id)sender;
-(IBAction)update:(id)sender;
@end
NSString *trip = @"0";
int trigger =1;
int B = 50;
int T = 90;
MQTTSession *session;
@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tempValueLabel.frame = CGRectMake(20, 250-(T+45),65, T+45);
    
    NSString* myNewString = [NSString stringWithFormat:@"%d", T];
    self.temperatureValueLabel.text = myNewString;
    MQTTCFSocketTransport *transport = [[MQTTCFSocketTransport alloc] init];
    transport.host = @"io.adafruit.com";
    transport.port = 1883;
    session = [[MQTTSession alloc] init];
    session.userName = @"xxxxxxxx";
    session.password = @"xxxxxxxxxxxxxxxxxxx";
    session.transport = transport;
    session.delegate = self;
    [session connectWithConnectHandler:^(NSError *error) {
            if(!error){
                
                [session subscribeToTopic:@"xxxxxxxx/feeds/temperature" atLevel:1 subscribeHandler:^(NSError *error, NSArray *gQoss){
                    
            if (error) {
                NSLog(@"Subscription failed %@", error.localizedDescription);
            } else {
                NSLog(@"Subscription sucessfull! Granted Qos: %@", gQoss);
                
                trip = @"0";
                NSData* data = [trip dataUsingEncoding:NSUTF8StringEncoding];
                [session publishData:data onTopic:@"gbenna/feeds/temperature/get" retain:NO qos:0 publishHandler:nil];
                NSLog(@"%@", trip);
                NSLog(@"%d",trigger);
                   }
        }];
                [session subscribeToTopic:@"xxxxxxx/feeds/battery" atLevel:1 subscribeHandler:^(NSError *error, NSArray *gQoss){
                    
            if (error) {
                NSLog(@"Subscription failed %@", error.localizedDescription);
            } else {
                NSLog(@"Subscription sucessfull! Granted Qos: %@", gQoss);
                
                trip = @"0";
                NSData* data = [trip dataUsingEncoding:NSUTF8StringEncoding];
                [session publishData:data onTopic:@"xxxxxxx/feeds/battery/get" retain:NO qos:0 publishHandler:nil];
                NSLog(@"%@", trip);
                NSLog(@"%d",trigger);
                    }
        }];
                [session subscribeToTopic:@"xxxxxxxx/feeds/level" atLevel:1 subscribeHandler:^(NSError *error, NSArray *gQoss){
                    
            if (error) {
                NSLog(@"Subscription failed %@", error.localizedDescription);
            } else {
                NSLog(@"Subscription sucessfull! Granted Qos: %@", gQoss);
                
                trip = @"0";
                NSData* data = [trip dataUsingEncoding:NSUTF8StringEncoding];
                [session publishData:data onTopic:@"xxxxxxx/feeds/level/get" retain:NO qos:0 publishHandler:nil];
                NSLog(@"%@", trip);
                NSLog(@"%d",trigger);
                    }
        }];
                [session subscribeToTopic:@"gbenna/feeds/date" atLevel:1 subscribeHandler:^(NSError *error, NSArray *gQoss){
            
            if (error) {
                NSLog(@"Subscription failed %@", error.localizedDescription);
            } else {
                NSLog(@"Subscription sucessfull! Granted Qos: %@", gQoss);
                
                trip = @"0";
                NSData* data = [trip dataUsingEncoding:NSUTF8StringEncoding];
                [session publishData:data onTopic:@"xxxxxxx/feeds/date/get" retain:NO qos:0 publishHandler:nil];
                NSLog(@"%@", trip);
                NSLog(@"%d",trigger);
                   }
        }];
                [session subscribeToTopic:@"xxxxxxx/feeds/trip" atLevel:1 subscribeHandler:^(NSError *error, NSArray *gQoss){
            
            if (error) {
                NSLog(@"Subscription failed %@", error.localizedDescription);
            } else {
                NSLog(@"Subscription sucessfull! Granted Qos: %@", gQoss);
                
                trip = @"0";
                NSData* data = [trip dataUsingEncoding:NSUTF8StringEncoding];
                [session publishData:data onTopic:@"xxxxxxx/feeds/trip/get" retain:NO qos:0 publishHandler:nil];
                NSLog(@"%@", trip);
                NSLog(@"%d",trigger);
                   }
        }];
                }
            else {NSLog(@"[connectWithConnectHandler]Error Connect %@", error.localizedDescription);}
        
        
    }];
   
  
    
    
}

- (void)newMessage:(MQTTSession *)session
              data:(NSData *)data
           onTopic:(NSString *)topic
               qos:(MQTTQosLevel)qos
          retained:(BOOL)retained
               mid:(unsigned int)mid {
    NSString *dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"topic: %@", topic);
    NSLog(@"data:%@", dataString);
    if ([topic isEqualToString:@"xxxxxx/feeds/temperature"]){
        T = [dataString intValue];
        self.temperatureValueLabel.text = dataString;
        self.tempValueLabel.frame = CGRectMake(20, 250-(T+45),65, T+45);
        if (T <= 69) {
            _tempValueLabel.image = [UIImage imageNamed:@"dk blue rectangle.png"];
        }
        else if ((69< B)&& (B <= 90)) {
            _tempValueLabel.image = [UIImage imageNamed:@"blue rectangle.png"];
        }
        else if (B > 90) {
            _tempValueLabel.image = [UIImage imageNamed:@"red rectangle.png"];
        }
    }
    if ([topic isEqualToString:@"xxxxxx/feeds/level"]){
        self.levelValueLabel.text = dataString;}
    if ([topic isEqualToString:@"xxxxxx/feeds/date"]){
        self.dateValueLabel.text = dataString;}
    if ([topic isEqualToString:@"xxxxxxx/feeds/battery"]){
      
        B = [dataString intValue];
        self.batteryValueLabel.frame = CGRectMake(332, 250-(B*1.7), 65, B);
        if (B <= 20) {
            _batteryValueLabel.image = [UIImage imageNamed:@"red rectangle.png"];
        }
        else if ((20< B)&& (B <= 100)) {
            _batteryValueLabel.image = [UIImage imageNamed:@"green rectangle.png"];
        }
        else if (B > 100) {
            _batteryValueLabel.image = [UIImage imageNamed:@"red rectangle.png"];
        }
    }
    if ([topic isEqualToString:@"xxxxxxx/feeds/trip"]){
        self.tripValueLabel.text = dataString;}


}
-(IBAction)Turnon:(id)sender;{
    if(trigger ==1){
        trip = @"0";
        trigger = 2;
    }
    else if(trigger==2){
        trip = @"100";
        trigger = 1;
    }
    NSData* data = [trip dataUsingEncoding:NSUTF8StringEncoding];
    [session publishData:data onTopic:@"xxxxxxx/feeds/trip" retain:NO qos:1 publishHandler:nil];
    NSLog(@"%@", trip);
    NSLog(@"%d",trigger);
    
}

@end

连接到服务器后,我订阅了一个主题,然后当我订阅了该主题时,我发布了 /get 方法。我对每个主题都这样做了。当我启动我的应用程序时,它们都会更新为每个主题的最后一个当前值。我将尝试看看当我回到后台时会发生什么,并可能添加一个按钮来更新(/获取)所有主题。

感谢大家的帮助。


推荐阅读