How to quickly develop an IOT app based on app SDK?

Time:2020-11-27

1、 Background and outline

In today’s era of Internet of things, the Internet of things has become a trend. Controlling intelligent devices through app and realizing scene linkage is not a choice, but the key to the end-to-end solution of enterprises.

Intelligent hardware manufacturers are springing up like mushrooms. However, the big framework of the Internet of things – DCM (device, connect, manage) architecture makes IOT app a rigid demand. Intelligent hardware needs to be combined with app to better play its role and facilitate people’s life. For example, the app is used to control the brightness of the light, adjust the temperature of the air conditioner, remotely monitor the situation of the home through IPC, and even make the relevant appliances in the home complete a scene linkage (such as setting “home scene” on the mobile phone. When returning home from work, click“Home scene”Turn on the lights with one button, boil water from the kettle, start the air conditioner, etc.). These scenes, which originally existed only in the imagination, are now passed throughMobile app + smart hardwareIt can be realized.

However, for most enterprises, the development of IOT app is not only new, but also full of challenges

Take time todayDevelopment of smart home app based on app SDKFor example. You can complete the steps of creating an app and controlling your home device through an article such as creating an app, integrating a home device with a SDK, and so on.

Let’s first list the development outline:

  1. Create app SDK
  2. Integrated SDK
  3. Registration and login
  4. Create a family
  5. Distribution network equipment
  6. Equipment control

Let’s briefly introduce the Tuya app SDK:

Graffiti smart app SDKIt is specially designed for the development of IOT mobile app, providing rich components and sample code. Developers can quickly realize the connection and control of mobile app to intelligent devices and rich intelligent scene applications.

The advantages of the product are:

  1. Low threshold rapid integration: quick integration of SDK, providing sample code, demo app, access cases, etc., low threshold easy to start;
  2. Rich development components: component development, providing vertical category SDK, UI business package and other functional components, developers can flexibly combine according to their needs;
  3. Comprehensive intelligent function: it covers users, devices, intelligent scenes and other functional modules, and developers only need to implement UI layer code simply;
  4. Compatibility of mainstream communication protocols: support the addition and use of mainstream communication protocol products in the same app, so as to realize all in one – app easily;
  5. Global data security: dual channel security encryption, five security strategies, global data security compliance certification, to fully protect user data privacy and security;
  6. Global service stability: the global Intelligent Cloud deployment makes it easy for each app to have 100 million class massive devices and 10 million users’ concurrent processing capability.

App SDKThe technical structure of the system is as follows:

How to quickly develop an IOT app based on app SDK?

2、 How to develop an app based on app SDK

Ready, let’s get started!

(1) Create app SDK

  1. Registered developer account

go toGraffiti intelligent development platformPlease refer to the specific process of registering developer account, creating product, creating function point, etcAccess process

  1. Create SDK application

stayDoodling IOT platformMedium“App workbench”Middle click“App SDK”, click“Create app”。

How to quickly develop an IOT app based on app SDK?

  1. Fill in the app information and click OK.

    1. App Name: fill in your app name.
    2. IOS app package name: fill in your IOS app package name (suggested format: com.xxxxx.xxxxx )。
    3. Android App package name: fill in your Android App package name (both can be consistent or inconsistent).
    4. Channel identifier: not required. If it is not filled in, the system will automatically generate it according to the package name.

How to quickly develop an IOT app based on app SDK?

You can choose the solution you need according to your actual needs, support multiple choices, and then integrate the SDK according to podfile and gradle.

How to quickly develop an IOT app based on app SDK?

clickGet password, get the appkey, appsecret, security image and other information of the SDK.

How to quickly develop an IOT app based on app SDK?

(2) Integrated SDK

1. Use cocoapods for rapid integration

Please note: the SDK supports minimum system version 9.0

Add the following to the podfile file:

platform :ios, '9.0'

target 'Your_Project_Name' do

    pod "TuyaSmartHomeKit"

end

It is then executed in the project root directorypod updateCommand for integration.

2. Initialize the SDK

1) Open the project settings, target = > general, and modify the bundle identifier to the IOS package name corresponding to the graffiti developer platform

2) Import the security picture to the project root directory and rename it to t_ s. Add “target = > bundle” in “build resource = > phase”.

3) In the project’s PrefixHeader.pch Add the following to the file:

#import <TuyaSmartHomeKit/TuyaSmartKit.h>

4) Open the appdelegate. M file in [appdelegate AP] plication:didFinishLaunchingWithOptions :] method.

Interface description

Initialize SDK

- (void)startWithAppKey:(NSString *)appKey secretKey:(NSString *)secretKey;

Parameter description

How to quickly develop an IOT app based on app SDK?

Instance code

[[TuyaSmartSDK sharedInstance] startWithAppKey:<#your_app_key#> secretKey:<#your_secret_key#>];

3. Open debug mode

During the development process, you can turn on debug mode, print some logs to analyze problems, and it is recommended to close it after the development is completed and online.

#ifdef DEBUG

    [[TuyaSmartSDK sharedInstance] setDebugMode:YES];

#else

#endif

(3) Registration and login

Graffiti cloud supports a variety of user systems: mobile phone, email, uid. There are two main login methods for user ID, which are used for login authentication. We use mobile phone verification code to sign in.

How to quickly develop an IOT app based on app SDK?

In the registration and login method, you need to provide the countrycode parameter (country area code) to select the nearest available zone of graffiti cloud. The data in each available area are independent of each other, so the registered accounts in Chinese mainland (86) are not available in the US (1).

1. Mobile phone password registration

Mobile phone number password registration process is divided into the following two steps: obtain mobile phone verification code – register account

//Send verification code 

[[TuyaSmartUser sharedInstance] sendVerifyCode:@"86" phoneNumber:@"1300****" type:1 success:^{

    [TPDemoProgressUtils showSuccess:@"Verification code sent successfully" toView:nil];

} failure:^(NSError *error) {

    [TPDemoProgressUtils showError:error.localizedDescription];

}];

//Register account number with verification code

[[TuyaSmartUser sharedInstance] registerByPhone:@"86" phoneNumber:@"1300****" password:@"***" code:@"code" success:^{

    //Successful registration, jump to the home page

    [[TYDemoApplicationImpl sharedInstance] resetRootViewController:[TYDemoTabBarViewController class]];

} failure:^(NSError *error) {

    [TPDemoProgressUtils showError:error.localizedDescription];

}];

2. Judge whether you have logged in

After the program is started, if you have logged in, you do not need to log in repeatedly. The validity period of the session is 45 days. You can go to the device list page directly. If you have not logged in, you should log in to the login page first, and then jump to the device list page after successful login.

//Determine whether you have logged in

if ([TuyaSmartUser sharedInstance].isLogin) {

    //Home page

    [self resetRootViewController:[TYDemoTabBarViewController class]];

} else {

    //Landing page

    [[TYDemoRouteManager sharedInstance] openRoute:kTYDemoPopLoginVC withParams:nil];

}

3. Session failure handling

If the account has not been logged in for a long time or the password has been modified, it will return an error of session expiration when accessing the server interface. You need to listen to tuyasmartusernotificationusersessioninvalid notification, and jump to the login page to log in again.

- (void)loadNotification {

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sessionInvalid) name:TuyaSmartUserNotificationUserSessionInvalid object:nil];

}

- (void)sessionInvalid {

        NSLog(@"sessionInvalid");

        //Jump to login page

        MyLoginViewController *vc = [[MyLoginViewController alloc] init];

        self.window.rootViewController = vc;

      [self.window makeKeyAndVisible];

}

(4)Create a family

After successful login, the user needs to obtain the information of the whole family list through tuyasmarthomemanager, and then initialize one of the families tuyasmarthome to obtain the family details information, and then operate and control the devices in the home.

How to quickly develop an IOT app based on app SDK?

1. Get the family list

On the device list page, we first get the family list under the user. If there is no family, we create a default home. When the device is activated, the device needs to be added to the home.

After getting the family list, we can initialize a family, and then get the family details from the cloud to refresh the device list on the home page.

- (void)initData {

   

    _homeManager = [[TuyaSmartHomeManager alloc] init];

    _homeManager.delegate = self;

   

    //Get local current family

    NSString *homeId = [[NSUserDefaults standardUserDefaults] objectForKey:kDefaultCurrentHomeId];

    if ([homeId longLongValue] > 0) {

        self.home = [TuyaSmartHome homeWithHomeId:[homeId longLongValue]];

        if (self.home) {

            self.home.delegate = self;

            self.topBarView.leftItem.title = [NSString stringWithFormat:@"%@ ∨", self.home.homeModel.name];

            [TYDemoSmartHomeManager sharedInstance].currentHomeModel = self.home.homeModel;

            //Refresh device list data

            [self reloadDataFromCloud];

        } else {

            //If not, get the first family

            [self loadFirstHomeData];

        }

    } else {

        //If not, get the first family

        [self loadFirstHomeData];

    }

}

- (void)reloadDataFromCloud {

    WEAKSELF_AT

    [self.refreshControl beginRefreshing];

    //And refresh the current family list

    [self.home getHomeDetailWithSuccess:^(TuyaSmartHomeModel *homeModel) {

       

        [weakSelf_AT reloadData];

    } failure:^(NSError *error) {

        if ([error.localizedFailureReason isEqualToString:@"PERMISSION_DENIED"]) {

            [weakSelf_AT loadFirstHomeData];

        }

        [weakSelf_AT.refreshControl endRefreshing];

    }];

}

2. Add a family

// add home

- (void)rightBtnAction {

    NSString *homeName = [NSString stringWithFormat:@"Home_%@", @(self.homeManager.homes.count)];

    WEAKSELF_AT

    [self.homeManager addHomeWithName:homeName geoName:@"hangzhou" rooms:@[@"room1"] latitude:0 longitude:0 success:^(long long homeId) {

        [TPDemoProgressUtils showSuccess:@"Add Success" toView:nil];

        //Switch to new family

        TuyaSmartHome *home = [TuyaSmartHome homeWithHomeId:homeId];

        [weakSelf_AT swithCurrentHomeIdWithHomeModel:home.homeModel];

    } failure:^(NSError *error) {

        [TPDemoProgressUtils showError:error.localizedDescription];

    }];

}

3. Callback of family list information change

After the implementation of tuyasmart homemanager delegate agent protocol, it can be processed in the callback of home list change.

#pragma mark - TuyaSmartHomeManagerDelegate

//Add a family

- (void)homeManager:(TuyaSmartHomeManager *)manager didAddHome:(TuyaSmartHomeModel *)home {

    NSLog(@"Add a home %@", home.name);

}

//Delete a family

- (void)homeManager:(TuyaSmartHomeManager *)manager didRemoveHome:(long long)homeId {

    //If the deleted family is the current family, the current family switches to another one

    if ([TYDemoSmartHomeManager sharedInstance].currentHomeModel.homeId == homeId) {

        [self loadFirstHomeData];

    }

}

//Mqtt connection successful

- (void)serviceConnectedSuccess {

    //Go to the cloud to get the details of the current family, and then refresh the UI

    [self reloadDataFromCloud];

}

4. Callback of single family information change

After the implementation of tuyasmarthomedelegate agent protocol, it can be processed in the callback of single family information change.

#pragma mark - TuyaSmartHomeDelegate

//Name, for example, to update family information

- (void)homeDidUpdateInfo:(TuyaSmartHome *)home {

    [self.tableView reloadData];

}

//Add a room

- (void)home:(TuyaSmartHome *)home didAddRoom:(TuyaSmartRoomModel *)room {

    [self.tableView reloadData];

}

//Delete a room

- (void)home:(TuyaSmartHome *)home didRemoveRoom:(long long)roomId {

    [self.tableView reloadData];

}

//The list of shared devices I received changed

- (void)homeDidUpdateSharedInfo:(TuyaSmartHome *)home {

    [self.tableView reloadData];

}

//Room information changes, such as name

- (void)home:(TuyaSmartHome *)home roomInfoUpdate:(TuyaSmartRoomModel *)room {

    [self.tableView reloadData];

}

//Changes in the relationship between rooms, equipment and groups

- (void)home:(TuyaSmartHome *)home roomRelationUpdate:(TuyaSmartRoomModel *)room {

    [self.tableView reloadData];

}

//Add device

- (void)home:(TuyaSmartHome *)home didAddDeivice:(TuyaSmartDeviceModel *)device {

    [self.tableView reloadData];

}

//Delete device

- (void)home:(TuyaSmartHome *)home didRemoveDeivice:(NSString *)devId {

    [self.tableView reloadData];

}

//Device information updates, such as name

- (void)home:(TuyaSmartHome *)home deviceInfoUpdate:(TuyaSmartDeviceModel *)device {

    [self.tableView reloadData];

}

//Device DP data update

- (void)home:(TuyaSmartHome *)home device:(TuyaSmartDeviceModel *)device dpsUpdate:(NSDictionary *)dps {

    [self.tableView reloadData];

}

//Add group

- (void)home:(TuyaSmartHome *)home didAddGroup:(TuyaSmartGroupModel *)group {

    [self.tableView reloadData];

}

//Group DP data update

- (void)home:(TuyaSmartHome *)home group:(TuyaSmartGroupModel *)group dpsUpdate:(NSDictionary *)dps {

    [self.tableView reloadData];

}

//Delete group

- (void)home:(TuyaSmartHome *)home didRemoveGroup:(NSString *)groupId {

    [self.tableView reloadData];

}

//Group information update, such as name

- (void)home:(TuyaSmartHome *)home groupInfoUpdate:(TuyaSmartGroupModel *)group {

    [self.tableView reloadData];

}

(5) Equipment distribution network

Equipment distribution network refers to the activation and registration of equipment in the cloud.

1. Related categories

How to quickly develop an IOT app based on app SDK?

2. EZ distribution network

This paper mainly introduces the development of EZ mode, also known as smartconfig.

How to quickly develop an IOT app based on app SDK?

- (void)addDeviceWithEZMode {

   

    //Get token

    WEAKSELF_AT

    id<TYDemoDeviceListModuleProtocol> impl = [[TYDemoConfiguration sharedInstance] serviceOfProtocol:@protocol(TYDemoDeviceListModuleProtocol)];

    long long homeId = [impl currentHomeId];

    [[TuyaSmartActivator sharedInstance] getTokenWithHomeId:homeId success:^(NSString *token) {

        //Start distribution network

        [weakSelf_AT commitEZModeActionWithToken:token];

    } failure:^(NSError *error) {

       

        info = [NSString stringWithFormat:@"%@: token fetch failed, error message is %@",NSStringFromSelector(_cmd),error.localizedDescription];

        [weakSelf_AT appendConsoleLog:info];

    }];

}

//Start distribution network

- (void)commitEZModeActionWithToken:(NSString *)token {

    [TuyaSmartActivator sharedInstance].delegate = self;

    [[TuyaSmartActivator sharedInstance] startConfigWiFi:TYActivatorModeEZ ssid:self.ssidField.text password:self.passwordField.text token:token timeout:timeout];

}

#pragma mark - TuyaSmartActivatorDelegate

- (void)activator:(TuyaSmartActivator *)activator didReceiveDevice:(TuyaSmartDeviceModel *)deviceModel error:(NSError *)error {

   

    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(countDown) object:nil];

    timeout = timeLeft;

    [self hideProgressView];

   

    NSString *info = [NSString stringWithFormat:@"%@: Finished!", NSStringFromSelector(_cmd)];

    [self appendConsoleLog:info];

    if (error) {

        //Distribution network failure

        info = [NSString stringWithFormat:@"%@: Error-%@!", NSStringFromSelector(_cmd), error.localizedDescription];

        [self appendConsoleLog:info];

    } else {

        //Distribution network success

        info = [NSString stringWithFormat:@"%@: Success-You've added device %@ successfully!", NSStringFromSelector(_cmd), deviceModel.name];

        [self appendConsoleLog:info];

    }

}

After the intelligent equipment distribution network is successful, it has the networking ability and can be remote controlled.

(6) Equipment control

After the device is activated, the intelligent device can be controlled, and then the callback of the device control change can be monitored.

1. Related categories

How to quickly develop an IOT app based on app SDK?Before the equipment control, we first understand the concept of equipment function point.

2. Equipment function point

Function point is the abstract representation of product function and the abstraction of specific intelligent device function, which is used to describe product function and its parameters.

Function point ID: Code of function point. The function data between the device and the cloud is transmitted through the function point ID.

Function point name: user defined function name.

Identification name: function point code value, which is used for multi language management of APP display function name. Supports letters, numbers, and underscores, starting with a letter.

Data type:

How to quickly develop an IOT app based on app SDK?

Data transmission type:

|-Can be issued and reported: command data can be sent to the device, and the device data can be transmitted to the cloud.

|-Report only: data can only be transmitted from the device to the cloud.

|-Distribute only: data can only be sent from the cloud to the device.

The DPS property (nsdictionary type) of the tuyasmartdevicemodel class defines the state of the current device, called a data point (DP point) or function point

Each key in the DPS dictionary corresponds to the dpid of a function point, value corresponds to the dpvalue of a function point, and dpvalue is the value of the function point

Please refer toGraffiti Developer PlatformAs shown in the figure below:

How to quickly develop an IOT app based on app SDK?

The control command is sent in the following format:

{“<dpId>”:”<dpValue>”}

According to the function point definition of the product in the background, it is as follows:

Sample code

- (void)publishDps {

    // self.device = [TuyaSmartDevice deviceWithDeviceId:@"your_device_id"];

    // self.device.delegate = self;

   

    NSDictionary *dps;

    //Set the Boolean function point of dpid to 1 example function: switch on

    dps = @{@"1": @(YES)};

    //Set dpid to 4 string function point example function: set RGB color to ff5500

    dps = @{@"4": @"ff5500"};

    //Set dpid to 5 enumeration function point example function: set gear to 2

    dps = @{@"5": @"2"};

    //Set dpid to 6 numerical function point example function: set temperature to 20 degrees

    dps = @{@"6": @(20)};

    //Set dpid to 15 transparent type (byte array) function point example function: transparent infrared data to 1122

    dps = @{@"15": @"1122"};

    //Multi function merge sending

    dps = @{@"1": @(YES), @"4": @(ff5500)};

    [self.device publishDps:dps success:^{

        NSLog(@"publishDps success");

        //The status report is called back through the devicedpsupdate method

    } failure:^(NSError *error) {

        NSLog(@"publishDps failure: %@", error);

    }];

}

matters needing attention

The sending of control commands requires special attention to the data type

For example, if the data type of function point is value, the control command should send @ {@ “2”: @ (25)} instead of @ {@ “2”: @ “25”}

The byte array transmitted by passthrough type is in string format (hexadecimal string), and the letters must be lower case and even digits

For example, the correct format is: @ {@ “1”: @ “011f”} instead of @ {@ “1”: @ “11F”}

For more concepts of function points, seeQuick start – related concepts of function points

3. Device initialization and device change agent monitoring

You need to initialize a home instance through TuyaSmartHome, and then call the interface getHomeDetailWi. thSuccess:failure : get the details of the home. After synchronizing the details of the family, the initialization of the device can be successful. Wrong device ID may cause initialization failure, and the instance of device will return nil.

- (void)publishDps {

    self.device = [TuyaSmartDevice deviceWithDeviceId:@"your_device_id"];

    self.device.delegate = self;

 

    [self.device publishDps:@{@"1" : @{YES}} success:^{

        NSLog(@"publishDps success");

        //The status report is called back through the devicedpsupdate method

    } failure:^(NSError *error) {

        NSLog(@"publishDps failure: %@", error);

    }];

}

#pragma mark - TuyaSmartDeviceDelegate

///DP data update

- (void)device:(TuyaSmartDevice *)device dpsUpdate:(NSDictionary *)dps {

    [self.tableView reloadData];

}

///Equipment information update

- (void)deviceInfoUpdate:(TuyaSmartDevice *)device {

   

}

///Device removed

- (void)deviceRemoved:(TuyaSmartDevice *)device {

   

}

3、 Summary

We have completed the activation of an IOT app for intelligent hardware devices, network access, device control and other major links. Through the above process description, I believe you can complete the development of a smart home app based on the app SDK. If you are interested, you can try it. If you have any questions, you can comment or chat privately!

4. Reference

Introduction to IOT app SDK

Tuya Home SDK

Demo link