Is this page helpful?
YesNoLast 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:
Get a Free Developer Account Code Sample in GitHub
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.
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.
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.
Log in to the Tuya IoT Platform.
In the left-side navigation bar, choose Cloud > Projects.
On the page that appears, click Create.
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.
Click Create to continue project configuration.
In the Configuration Wizard dialog box, select the Device status notification API.
By default, industrial general and authorization APIs are selected.
Click Authorize.
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.
Choose Cloud > Projects > My Project.
Click the target project.
On the page that appears, choose Applications > App and click Add Application.
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.
(Optional) Create a Podfile
if you do not have one.
$ cd your-project-directory
$ pod init
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
Install the pods and open your .xcworkspace
file to see the project in Xcode.
$ pod install
$ open your-project.xcworkspace
Import the SDK.
Swift:
import TuyaIoTAppSDK
Objective-C:
#import <TuyaIoTAppSDK/TuyaIoTAppSDK-Swift.h>
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.
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.
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)
}
}
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.
Process:
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:
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.
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 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.
Search the device:
To pair a sub-device with a gateway, firstly, you need to enable the gateway to discover sub-devices. For this purpose, you can call discoverSubDevices(gatewayDeviceID:duration:completionHandle:) in TYDeviceRegistrationManager.
deviceRegistrationManager.discoverSubDevices(gatewayDeviceID: gateway.id) { success, error in
guard success else {
print(error?.localizedDescription)
return
}
// Polling for the result
// ...
}
Get the result:
This process is the same as that in AP mode.
Stop searching devices:
After the pairing result is returned or searching timed out, you can call stopDiscoveringSubDevice(gatewayDeviceID:completionHandle:) in TYDeviceRegistrationManager to stop the gateway from searching for sub-devices.
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
.
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:)
.
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.
Is this page helpful?
YesNoIs this page helpful?
YesNo