English
English
简体中文
Contact Us
Register
Log In
layoutIndex

Get Started with Industry App SDK for iOS

Last Updated on : 2022-01-07 07:03:31download

This tutorial introduces to you the Tuya Industry App SDK for iOS. The techniques you learn in the tutorial are fundamental to build IoT apps by using this SDK. In the following hands-on approaches, the sample code for Swift is used to describe the process.

In this tutorial, you will learn the following sections:

  • What is Industry App SDK: gives you an overview of what is the SDK and what you can take advantage of.
  • Add the SDK to your iOS project: teaches you how to import the SDK to your iOS project.
  • Login as a user: shows you how to create a user account and add asset permissions to users and other basic user management knowledge.
  • Pair devices: helps you get familiar with the typical device pairing process and how to pair a device in code.
  • Manage devices: introduces several useful device management methods.
  • Manage assets: guides you on how to add, query, modify, or delete your created assets.

Get a Free Developer Account Code Sample in GitHub

Before you begin

Tuya Industry App SDK for iOS is an iOS library. Therefore, this tutorial assumes that you have a basic understanding of iOS development, either in Objective-C or Swift, and you are familiar with Xcode.

The SDK is written in Swift, but the concept and API can be applied to Objective-C. In this tutorial, Swift is used as the programming language.

What is Industry App SDK?

Tuya Industry App SDK is an important part of the Tuya SaaS Development Framework product families. This tutorial provides examples of multiple functions based on Tuya OpenAPI, such as device pairing, user login and registration, and asset management.

Add the SDK to your iOS project

To use the SDK and the capabilities of the Tuya IoT Platform, you must first register your app to the Tuya IoT Platform, and then install the SDK.

Prerequisites

  • The following software is installed:
    • Xcode 12.0 or later.
    • CocoaPods 1.10.0 or later.
  • Your project must target iOS 10.0 or later.

Register the app to Tuya IoT Platform

Create a project

  1. Log in to the Tuya IoT Platform.

  2. In the left-side navigation bar, choose Cloud > Projects.

  3. On the page that appears, click Create.

  4. In the Create Project dialog box:

    • Set Project Name, Description, Industry, and Availability Zone.

      Tuya deploys six data centers globally and provides reliable IoT cloud services worldwide. You can select one or multiple availability zones where your services are deployed. This can be changed later.

    • In the Development Method field, select Custom Development from the drop-down list.

      Get Started with Industry App SDK for iOS
  5. Click Create to continue project configuration.

  6. In the Configuration Wizard dialog box, select the Device status notification API.

    Get Started with Industry App SDK for iOS

    By default, industrial general and authorization APIs are selected.

  7. Click Authorize.

  8. Fill in the asset and account information. The asset is automatically created and assigned to this account.

    For more information about assets, see Manage Assets.

Create an application

  1. Choose Cloud > Projects > My Project.

  2. Click the target project.

  3. On the page that appears, choose Applications > App and click Add Application.

    Get Started with Industry App SDK for iOS
  4. In the Add Application dialog box, select the iOS application type.

    Make sure that the bundle identifier is the same as your created Xcode project.

Import the SDK

  1. (Optional) Create a Podfile if you do not have one.

    $ cd your-project-directory
    
    $ pod init
    
  2. In your Podfile, add Tuya Industry App SDK and the sources.

    source 'https://cdn.cocoapods.org/'
    source 'https://github.com/TuyaInc/TuyaPublicSpecs.git'
    
    target 'your-project' do
    pod 'TuyaIoTAppSDK'
    end
    
  3. Install the pods and open your .xcworkspace file to see the project in Xcode.

    $ pod install
    
    $ open your-project.xcworkspace
    
  4. Import the SDK.

    Swift:

    import TuyaIoTAppSDK
    

    Objective-C:

    #import <TuyaIoTAppSDK/TuyaIoTAppSDK-Swift.h>
    

Objective-C projects

Tuya Industry App SDK is a Swift closed source library. To use the library in a pure Objective-C project, you must add an empty Swift file to your project. The Xcode will ask you whether to create a bridging header. Choose to create it.

Initialize the SDK

In AppDelegate.swift, add the following code to didFinishLaunchingWithOptions:

TYSDK.initialize(clientID: "YourClientID",
                 clientSecret: "YourClientSecret",
                 hostRegion: .US)

The preceding clientID and clientSecret are obtained in the Authorization Key field that is used when you create the application.

Log in as a user

The class TYUserManager provides methods to log in as a user and keep the session.

Currently, the SDK cannot be used to register a user. All registration processes are finished on the platform. You must manually add users to your project to log in successfully.

Call login(userName:password:completionHandle:) to login a user:

let manager = TYUserManager()

manager.login(userName: account, password: password) { (isSuccess, error) in
	// Check whether the login operation is successful.
	if isSuccess{
		// Success handle
	} else {
		// Faliure handle
		print(error?.localizedDescription)
	}
}

Pair devices

Tuya Industry App SDK provides several pairing modes for different conditions, such as the Access Point (AP) mode, wired mode, Narrowband Internet of Things (NB-IoT) mode, QR code mode, and sub-device mode.

  • AP mode: also known as the hotspot mode. A mobile phone connects to the hotspot of a smart device, and the two parties establish a socket connection to exchange data through the agreed port.

  • Wired mode: Devices are connected to the router over a wired network. For example, Zigbee wired gateways and wired cameras can be such devices.

  • Sub-device mode: Zigbee sub-devices and Bluetooth sub-devices can be such devices. These devices interact with the app and cloud through gateways.

  • QR code mode: A camera device gets the pairing information by scanning the QR code on the app.

AP mode

  • Process:

    Get Started with Industry App SDK for iOS
  • Get a token:

    Before the pairing process in AP mode, the SDK must get the pairing token from the Tuya IoT Cloud. The validity period of the token is 10 minutes, and the token becomes invalid once the pairing operation succeeds. A new token must be obtained if you want to pair devices again.

    To get the token, call generateToken(for:uid:timeZoneID:assetID:deviceUUID:completionHandle:) in TYDeviceRegistrationManager.

    let manager = TYDeviceRegistrationManager()
    
    manager.generateToken(for: .AP, uid: TYUserInfo.uid, assetID: assetID) { [weak self] (deviceRegistrationToken, error) in
    	// Check error first, then retrieve the token from deviceRegistrationToken
    }
    

    There are two types of tokens in TYDeviceRegistrationToken:

    • pairingToken is used to send to the device directly.
    • token is used to poll for registration result from the cloud.
  • Activate the device:

    Initialize TYAPActivator and call start().

    let activator = TYAPActivator(SSID: ssid, password: password, pairingToken: pairingToken)
    activator.start()
    

    After the successful or failed pairing operation, call stop().

    activator.stop()
    
  • Get the result:

    To get the pairing result, call queryRegistrationResult(of:completionHandle:) in TYDeviceRegistrationManager.

    Device pairing is an asynchronous process. The duration of device pairing depends on the network quality. You must make the API request to check the device pairing result. The polling task is stopped when a list of paired devices is returned or when the pairing task timed out.

    The polling task is suggested to run once per second. The timeout value of the pairing task is recommended to be 100 seconds.

Wired mode

In this mode, the wired device is connected to the network. You do not need to provide the name and password of the router during the device pairing.

In the following figure, a Zigbee wired gateway is used as an example to describe the wired gateway pairing process.

Get Started with Industry App SDK for iOS
  • Get a token:

    This process is the same as that in AP mode.

  • Search the device:

    Initialize TYWiredActivator:

    let activator = TYWiredActivator(pairingToken: pairingToken)
    

    Call start() to search for devices:

    activator.start(timeout: 120) { error in
    	print(error.localizedDescription)
    }
    

    The failureHandle will be called if the scanning process times out and no device is found.

  • Get the result:

    This process is the same as that in AP mode.

Sub-device mode

Get Started with Industry App SDK for iOS

QR code mode

In this mode, a QR code is used to pair a device, such as an IP camera. The device scans the QR code. A generated QR code image must be displayed on a mobile phone.

TYQRCodeActivator gives you methods to implement the pairing mode. Initialize the device instance and call either generateQRCodeData() or generateQRCodeUIImage() on the instance. The first call returns the data that is required to generate a QR code. Then, you must create the QR code image. The latter call returns a value of UIImage that can be rendered in UIImageView.

Manage devices

TYDeviceManager includes device management methods.

You can call queryDeviceInfo(of:completionHandle:) to get the details of one device, and call queryDevicesInfo(of:completionHandle:) to get the details of multiple devices.

To control a device, call queryCommandSetFromCategory(category:completionHandle:) to return a device instruction set from a specific category, and call queryCommandSetFromDeviceID(deviceID:completionHandle:) to return a device instruction set from a device ID. TYStandardCommand contains the following information of a command:

  • code: used to send the command.
  • value: the range of this command.
  • type: the value type of the command.

To send a command to control a device, you must construct TYDeviceCommand including code and value. For example, to switch on or off a light bulb, you can set code to switch and set type to boolean in TYStandardCommand. You must construct TYDeviceCommand in a similar way as the following setting:

let command = TYDeviceCommand(code: "switch", value: true)

Then, call sendCommands(commands:to:completionHandle:) to send the command.

To get the latest status of the device, use queryDeviceStatus(of:completionHandle:) or queryDevicesStatus(of:completionHandle:).

Manage assets

TYAssetManager contains methods to interact with assets. Currently, the SDK cannot be used to add, modify, or delete an asset. All these operations can only be finished on the Tuya IoT Platform. For more information, see Manage Assets.

You can call queryAssets(parentAssetID:pageNumber:pageSize:completionHandle:) to get all assets that are assigned to a specific user. You can also call queryDevices(in:pageSize:lastRowKey:completionHandle:) to get the devices that are bound to a specific asset.

This section contains the following topics to help you quickly understand related concepts and how-to guides: