### Example: Scanning and Setting Delegate for Mesh Manager Source: https://developer.tuya.com/en/docs/cubeprivate-cloud/mesh?id=Kcmgh4qeeqb0n Demonstrates how to get a mesh manager, set its delegate, and start a search for devices. It also shows commented-out examples for different scan types. ```objective-c //[ThingSmartSIGMeshManager sharedInstance].delegate = self; // ScanForUnprovision, // Scans for devices that are not paired. // ScanForProxyed, // Scans for paired devices. //[[ThingSmartSIGMeshManager sharedInstance] startScanWithScanType:ScanForUnprovision // meshModel:home.sigMeshModel]; ThingSmartSIGMeshManager *manager = [ThingSmartBleMesh getSIGMeshManager:@"meshId"]; manager.delegate = self; [manager startSearch]; ``` -------------------------------- ### Request Example for Get Start Time of Video Clip Source: https://developer.tuya.com/en/docs/cloud/cb46148a38?id=Kahc78myfpv0p An example GET request demonstrating how to query for video clip start times within a given time range. Replace the placeholder IDs and timestamps with your actual values. ```bash GET: /v1.0/users/ay156402688voY5W****/devices/6c08578d89411afye1****/storage/stream/timeline?time_g_t=1637639832&time_l_t=1637675832 ``` -------------------------------- ### Complete Example: Setup Camera View and P2P Source: https://developer.tuya.com/en/docs/app-development/livestream?id=Ka6nuvynnjk7h A comprehensive example demonstrating the initialization of `IThingSmartCameraP2P`, setting up the video view callback, binding the view, creating the video view, and registering a P2P listener. Includes handling session status changes. ```java // 1. Create `IThingSmartCameraP2P`. IThingSmartCameraP2P mCameraP2P = null; IThingIPCCore cameraInstance = ThingIPCSdk.getCameraInstance(); if (cameraInstance != null) { mCameraP2P = cameraInstance.createCameraP2P(devId)); } ThingCameraView mVideoView = findViewById(R.id.camera_video_view); // 2. Set the callback for the view rendering container. mVideoView.setViewCallback(new AbsVideoViewCallback() { @Override public void onCreated(Object view) { super.onCreated(view); // 3. Bind the rendered view with `IThingSmartCameraP2P`. if (null != mCameraP2P){ mCameraP2P.generateCameraView(view); } } }); // 4. Build the rendered view. mVideoView.createVideoView(devId); // 5. Register a P2P listener. AbsP2pCameraListener absP2pCameraListener = new AbsP2pCameraListener() { @Override public void onSessionStatusChanged(Object camera, int sessionId, int sessionStatus) { super.onSessionStatusChanged(camera, sessionId, sessionStatus); // If sessionStatus = -3 (timeout) or -105 (failed authentication), we recommend that you initiate a reconnection. Make sure to avoid an infinite loop. } }; if (null != mCameraP2P){ mCameraP2P.registerP2PCameraListener(absP2pCameraListener); } ``` -------------------------------- ### Full Camera Initialization and Listener Setup Source: https://developer.tuya.com/en/docs/app-development/livestream?id=Kceuhbtebvxwe Demonstrates the complete process of initializing the camera instance, creating the P2P object, setting up the view callback, and registering a P2P listener. Ensure all necessary components are in place before proceeding. ```java ITuyaSmartCameraP2P mCameraP2P = null; ITuyaIPCCore cameraInstance = TuyaIPCSdk.getCameraInstance(); if (cameraInstance != null) { mCameraP2P = cameraInstance.createCameraP2P(devId)); } TuyaCameraView mVideoView = findViewById(R.id.camera_video_view); // 2. Set the callback for the view rendering container. mVideoView.setViewCallback(new AbsVideoViewCallback() { @Override public void onCreated(Object view) { super.onCreated(view); // 3. Bind the rendered view with `ITuyaSmartCameraP2P`. if (null != mCameraP2P){ mCameraP2P.generateCameraView(view); } } }); // 4. Build the rendered view. mVideoView.createVideoView(devId); // 5. Register a P2P listener. if (null != mCameraP2P){ mCameraP2P.registerP2PCameraListener(new AbsP2pCameraListener() { @Override public void onSessionStatusChanged(Object camera, int sessionId, int sessionStatus) { super.onSessionStatusChanged(camera, sessionId, sessionStatus); } }); } ``` -------------------------------- ### Get Device Track Point Request Example Source: https://developer.tuya.com/en/docs/cloud/3e3f832abe?id=Kaq02nq4aryaq Example of a GET request to the device track point API, specifying device ID, start time, and end time. ```http GET: /v2.0/iot-01/tracks/detail?device_id=vdevo16245017293****&start_time=1625198100154&end_time=1625198190154 ``` -------------------------------- ### Full Example: Initialize Camera View and P2P Source: https://developer.tuya.com/en/docs/cubeprivate-cloud/livestream?id=Kc48rkuj0dzdj This comprehensive example demonstrates the initialization process, including creating the P2P object, setting view callbacks, binding the view, building the video view, and registering the P2P listener. ```java // 1. Creates `ITuyaSmartCameraP2P`. ITuyaSmartCameraP2P mCameraP2P = null; ITuyaIPCCore cameraInstance = TuyaIPCSdk.getCameraInstance(); if (cameraInstance != null) { mCameraP2P = cameraInstance.createCameraP2P(devId)); } TuyaCameraView mVideoView = findViewById(R.id.camera_video_view); // 2. Set the callback for the view rendering container. mVideoView.setViewCallback(new AbsVideoViewCallback() { @Override public void onCreated(Object view) { super.onCreated(view); // 3. Bind the rendered view with `ITuyaSmartCameraP2P`. if (null != mCameraP2P){ mCameraP2P.generateCameraView(view); } } }); // 4. Build the rendered view. mVideoView.createVideoView(devId); // 5. Register a P2P listener. if (null != mCameraP2P){ mCameraP2P.registerP2PCameraListener(new AbsP2pCameraListener() { @Override public void onSessionStatusChanged(Object camera, int sessionId, int sessionStatus) { super.onSessionStatusChanged(camera, sessionId, sessionStatus); } }); } ``` -------------------------------- ### Request Example for Get Resources of Video Clips Source: https://developer.tuya.com/en/docs/cloud/5f28af42c2?id=Kahc78vpsd98q Example of an HTTP GET request to retrieve video clip resources. It includes user ID, device ID, start and end times, and a callback URL. ```http GET: /v1.0/users/ay156402688****oY5W/devices/6c08578d894****11afye1/storage/stream/hls?time_g_t=1637639832&time_l_t=1637675832&callback=http://localhost:3333 ``` -------------------------------- ### Install Dependencies and Run Example Source: https://developer.tuya.com/en/docs/cubeprivate-cloud/integrate-mq?id=Kcmgar9fg5q9t Use 'yarn' to install project dependencies and 'yarn example' to run the provided example script for testing message subscriptions. Ensure Node.js is correctly configured. ```bash yarn ``` ```bash yarn example ``` -------------------------------- ### Request Example for Get Device Track Segment API Source: https://developer.tuya.com/en/docs/cloud/37c080a4e3?id=Kaq02n6urynu6 This example demonstrates how to call the 'Get Device Track Segment' API with required parameters like device ID, start time, and end time. ```bash GET: /v2.0/iot-01/tracks/segments?device_id=vdevo16245017293****&start_time=1625198100154&end_time=1625198190154 ``` -------------------------------- ### Example: Initialize P2P Module Source: https://developer.tuya.com/en/docs/cubeprivate-cloud/android-p2p?id=Kcmgy9ip8x7h4 Demonstrates how to get the P2P instance and initialize it with a local ID. ```java IThingP2P p2p = ThingIPCSdk.getP2P(); if (p2p != null) { p2p.initP2P("xxx"); } ``` -------------------------------- ### Request Example for Get Total Activated Devices Source: https://developer.tuya.com/en/docs/cloud/d96fb0bdd4?id=Kax4ykaltrncw This example demonstrates how to call the 'Get Total Activated Devices' API with specified start and end dates and a dimension for categorization. Ensure the 'params' JSON is correctly formatted. ```http GET: /v1.0/iot-datacenter/app/device/activation/total?params={"startDay":"20210810" ,"endDay":"20210820","dimension":"category_code_1"} ``` -------------------------------- ### Example GET Request for Device Logs Source: https://developer.tuya.com/en/docs/cloud/0a30fc557f?id=Ka7kjybdo0jse An example of a GET request to retrieve device logs, including specific start and end times, and filtering by log types like online, offline, and data point reports. ```http GET: /v1.0/devices/6c9395918f4f4d85d8****/logs?end_time=1699433821000&start_time=1699433221000&type=1,2,7 ``` -------------------------------- ### Start Live Video Streaming Example Source: https://developer.tuya.com/en/docs/app-development/smartlock-video?id=Kbno0aqn72j28 Example demonstrating how to initiate a live video stream. Implement onSuccess and onError for feedback. ```java iIPCManager.startPreview(new IResultCallback() { @Override public void onSuccess() { // Live video streaming is started. } @Override public void onError(String code, String error) { // Failed to start live video streaming. } }); ``` -------------------------------- ### Start Local Video Recording Example Source: https://developer.tuya.com/en/docs/cubeprivate-cloud/test-case?id=Kdempk2d78px1 An example demonstrating how to start local video recording using the `startRecordLocalMp4` method. It includes a callback to show a toast message on success. ```java cloudCamera.startRecordLocalMp4(IPCCameraUtils.recordPath(devId), String.valueOf(System.currentTimeMillis()), new OperationDelegateCallBack() { @Override public void onSuccess(int sessionId, int requestId, String data) { Toast.makeText(CameraCloudStorageActivity.this, "record start success", Toast.LENGTH_SHORT).show(); } @Override public void onFailure(int sessionId, int requestId, int errCode) { } }); ``` -------------------------------- ### Query Policy List Request Example Source: https://developer.tuya.com/en/docs/cloud/d1deaaf629?id=Kcpr7iavwxnc3 Example of a GET request to the policy list API, specifying page size and a starting row key. ```http GET: /v2.0/cloud/iam/policy/list?page_size=10&last_row_key=0 ``` -------------------------------- ### Install CocoaPods and Setup Source: https://developer.tuya.com/en/docs/app-development/mini-app-sdk-integration?id=Kcwzm2u3n0f8h Install CocoaPods and set up the repository source. This is a prerequisite for managing MiniApp SDK components. ```bash sudo gem install cocoapods pod setup ``` -------------------------------- ### Request Example for Get Device Event Log Source: https://developer.tuya.com/en/docs/cloud/cbea13f274?id=Kalmcohrembze This example demonstrates how to construct a GET request to retrieve device event logs. It includes parameters for last row key, event types, start and end times, and the number of logs to query. ```bash GET: /v1.0/iot-03/devices/xxxxx/logs?last_row_key=xxx&event_types=1,2&start_time=1545898159931&end_time=1545898159935&size=20 ``` -------------------------------- ### Request Example for Daily Reports Source: https://developer.tuya.com/en/docs/cloud/8e6f6e390b?id=Kaqifj7jxckls Example of a GET request to the daily reports API. It demonstrates how to specify the start time, end time, and page size for the query. ```http GET: /v1.0/iot-03/meeting-reservations/daily-reports?startTime=1625414400000&endTime=1625500800000&size=1 ``` -------------------------------- ### Initialize Driver SDK in Go Source: https://developer.tuya.com/en/docs/iot/driver-sdk?id=Kag92atlk54y5 Call `startup.Bootstrap` in your `main` function to initialize the SDK. Ensure you provide the service name, version, and a driver implementation. ```go // main.go package main import ( "device-service-template/internal/driver" "github.com/tuya/tuya-edge-driver-sdk-go" "github.com/tuya/tuya-edge-driver-sdk-go/pkg/startup" ) const ( serviceName string = "device-service-template" ) func main() { sd := driver.SimpleDriver{} startup.Bootstrap(serviceName, device.Version, &sd) } ``` -------------------------------- ### Example: Configure Device Info and Network Settings (Objective-C) Source: https://developer.tuya.com/en/docs/cubeprivate-cloud/ipc?id=Kcmgkrvnn8rif This Objective-C example demonstrates how to obtain the ThingCameraSettingProtocol service, generate custom models for device information and network settings (initially hidden), and then apply these configurations. ```objective-c id cameraSettingProtocol = [[ThingSmartBizCore sharedInstance] serviceOfProtocol:@protocol(ThingCameraSettingProtocol)]; id item1 = [cameraSettingProtocol generateSettingCustomModelWithTag:@"cameraSetting_infoItem" visible:NO callBack:nil]; id item2 = [cameraSettingProtocol generateSettingCustomModelWithTag:@"cameraSetting_networkItem" visible:NO callBack:nil]; [cameraSettingProtocol configCustomItemWithItems:@[item1, item2]]; ``` -------------------------------- ### Start Device Pairing Mode (Swift) Source: https://developer.tuya.com/en/docs/app-development/ios-bizbundle-sdk/deviceconfiguration?id=Ka8qf8lipvifj Initiates device pairing using the ThingActivatorProtocol in Swift. This example shows how to get the service and handle the completion block. ```swift let impl = ThingSmartBizCore.sharedInstance().service(of: ThingActivatorProtocol.self) as? ThingActivatorProtocol impl?.gotoCategoryViewController() impl?.activatorCompletion(ThingActivatorCompletionNode.normal, customJump: false, completionBlock: { (devIdList:[Any]?) in print(devIdList ?? []) }) ``` -------------------------------- ### Swift Initialization Example Source: https://developer.tuya.com/en/docs/cubeprivate-cloud/upgrading?id=Kcmgkrvnn8rif Example of how to register and implement the `ThingSmartHomeDataProtocol` in Swift. ```APIDOC ## Swift Implementation Example ### Description This code demonstrates how to register the `ThingSmartHomeDataProtocol` using `ThingSmartBizCore` and implement the `getCurrentHome` method in Swift. ### Code ```swift import ThingSmartDeviceKit class ThingActivatorTest: NSObject, ThingSmartHomeDataProtocol { func test() { ThingSmartBizCore.sharedInstance().registerService(ThingSmartHomeDataProtocol.self, withInstance: self) } func getCurrentHome() -> ThingSmartHome! { // Replace 111 with the actual logic to retrieve the current home ID let home = ThingSmartHome.init(homeId: 111) return home } } ``` ``` -------------------------------- ### Install Go Dependencies and Build Project Source: https://developer.tuya.com/en/docs/iot/webrtc?id=Kacsd4x2hl0se Run these commands in the root directory of the cloned webrtc-demo-go project to fetch dependencies and build the executable. ```bash go get && go build ``` -------------------------------- ### Get Valid Plans Request Example Source: https://developer.tuya.com/en/docs/cloud/ea0fb7a5bf?id=Kavf4tl7g2tyl Example of a GET request to the 'Get Valid Plans' API, specifying a sample ICCID. ```http GET: /v1.0/iot-01/sim/898611212100361****/package/list ``` -------------------------------- ### Get App Information Request Example Source: https://developer.tuya.com/en/docs/cloud/a545296b59?id=Kbi8cu9is5f82 Example of a GET request to the 'Get App Information' API, specifying 'testApp' as the schema. ```http GET: /v1.1/apps/testApp ``` -------------------------------- ### Objective-C Initialization Example Source: https://developer.tuya.com/en/docs/cubeprivate-cloud/upgrading?id=Kcmgkrvnn8rif Example of how to register and implement the `ThingSmartHomeDataProtocol` in Objective-C. ```APIDOC ## Objective-C Implementation Example ### Description This code demonstrates how to register the `ThingSmartHomeDataProtocol` using `ThingSmartBizCore` and implement the `getCurrentHome` method in Objective-C. ### Code ```objectivec #import #import // Register the protocol implementation - (void)initCurrentHome { [[ThingSmartBizCore sharedInstance] registerService:@protocol(ThingSmartHomeDataProtocol) withInstance:self]; } // Implement the protocol method - (ThingSmartHome *)getCurrentHome { // Replace "Current home ID" with the actual logic to retrieve the current home ID ThingSmartHome *home = [ThingSmartHome homeWithHomeId:@"Current home ID"]; return home; } ``` ``` -------------------------------- ### Example: Configure Camera Settings (Objective-C) Source: https://developer.tuya.com/en/docs/cubeprivate-cloud/ipc?id=Kc48sp89e14pc Demonstrates how to obtain the `TYCameraSettingProtocol` service and use it to generate and configure custom setting items for the camera's setting page. ```objective-c id cameraSettingProtocol = [[TuyaSmartBizCore sharedInstance] serviceOfProtocol:@protocol(TYCameraSettingProtocol)]; id item1 = [cameraSettingProtocol generateSettingCustomModelWithTag:@"cameraSetting_infoItem" visible:NO callBack:nil]; id item2 = [cameraSettingProtocol generateSettingCustomModelWithTag:@"cameraSetting_networkItem" visible:NO callBack:nil]; [cameraSettingProtocol configCustomItemWithItems:@[item1, item2]]; ``` -------------------------------- ### Request Example for Get Category List Source: https://developer.tuya.com/en/docs/cloud/980c13c742?id=Kb3oe60dzo6y4 An example of a GET request to the 'Get Category List' API, specifying a placeholder for the `infrared_id`. ```HTTP GET: /v2.0/infrareds/vdevo15345926009****/categories ``` -------------------------------- ### Switch On Light (Java Example) Source: https://developer.tuya.com/en/docs/app-development/andoird_device_control?id=Kceuh1gmmdsm8 Example demonstrating how to switch on a light by sending a specific DP value. The callback handles success or failure notifications. Ensure the context and device objects are properly initialized. ```java mDevice.publishDps("{\"101\": true}", new IResultCallback() { @Override public void onError(String code, String error) { Toast.makeText(mContext, "Failed to switch on the light.", Toast.LENGTH_SHORT).show(); } @Override public void onSuccess() { Toast.makeText(mContext, "The light is switched on successfully.", Toast.LENGTH_SHORT).show(); } }); ``` -------------------------------- ### Get Number of Devices Request Example Source: https://developer.tuya.com/en/docs/cloud/83e7fa0784?id=Kb5r63sg1zzo9 Example of a GET request to the 'Get Number of Devices' API, specifying type and region. ```http GET: /v1.1/iot-03/si/devices/distribution/count?type=0®ion=China ``` -------------------------------- ### Get Device Group Request Example Source: https://developer.tuya.com/en/docs/cloud/19f1c53856?id=Kcp2kz04rqd7a Example of a GET request to the 'Get Device Group' API, specifying a device ID. ```http GET: /v2.0/cloud/thing/group/device/1285************** ``` -------------------------------- ### Basic GPIO Configuration Example Source: https://developer.tuya.com/en/docs/iot-device-dev/1?id=Kavgn8mjqa5hk Demonstrates how to configure GPIO pins for output and input using predefined macros and the `gpio_raw_init` function. Includes setting output levels and registering interrupt handlers. ```c #define LED_1_PORT PORT_A #define LED_1_PIN PIN_4 #define LED_1_MODE GPIO_MODE_OUTPUT_PP /// Configure the GPIO as output. #define LED_1_DOUT GPIO_DOUT_LOW /// Output the default level on the first initialization. #define LED_1_DRIVE GPIO_DOUT_HIGH /// Active high, used for advanced configuration. #define KEY_1_PORT PORT_A #define KEY_1_PIN PIN_3 #define KEY_1_MODE GPIO_MODE_INPUT_PULL /// Input pull-up or pull-down, depending on `KEY_1_DOUT`. #define KEY_1_DOUT GPIO_DOUT_HIGH /// Input pull-up #define KEY_1_DRIVE GPIO_LEVEL_LOW /// Active low, used for advanced configuration. static void __gpio_int_func_t(GPIO_PORT_T port, GPIO_PIN_T pin) { uint8_t vol_level = gpio_raw_input_read_status(KEY_1_PORT, KEY_1_PIN); /// Read the input signal. } static void gpio_demo(void) { const gpio_config_t gpio_ouput_config = { LED_1_PORT, LED_1_PIN, LED_1_MODE, LED_1_DOUT, LED_1_DRIVE, }; const gpio_config_t gpio_input_config = { KEY_1_PORT, KEY_1_PIN, KEY_1_MODE, KEY_1_DOUT, KEY_1_DRIVE, }; gpio_raw_init(gpio_ouput_config); /// Configure PA4 as output, defaulting to output low. gpio_raw_output_write_status(LED_1_PORT, LED_1_PIN, 1); /// Change the output level to high level. gpio_raw_init(gpio_inputput_config); /// Configure PA3 as input, input pull-up, and non-interrupt mode. gpio_int_register(&gpio_inputput_config, __gpio_int_func_t); /// Configure PA3 as input, input pull-up, and falling edge interrupt mode. } ``` -------------------------------- ### MQTT Connection Example in Go Source: https://developer.tuya.com/en/docs/iot/smart_vehicle_service?id=Kbozlbwf7ioli Demonstrates how to establish an MQTT connection using the paho.mqtt.golang library. Includes setup for broker, client ID, username, password generation, and handlers for connection and message reception. Ensure correct broker address and credentials are used. ```go import ( "crypto/md5" "encoding/hex" "fmt" "log" "time" mqtt "github.com/eclipse/paho.mqtt.golang" ) var ( client mqtt.Client pubTopic string subTopic string password string ) func main() { log.SetFlags(log.LstdFlags | log.Lshortfile) var ( username = "tuya_vehicle_***" clientId = "vehicle_*" broker = "tcp://ip:port" ) password = string(genSecKey(clientId, username)) pubTopic = fmt.Sprintf("gateway/vehicle/out/%s", clientId) subTopic = fmt.Sprintf("gateway/vehicle/in/%s", clientId) opts := mqtt.NewClientOptions().SetClientID(clientId).SetUsername(username).SetPassword(password) opts = opts.SetAutoReconnect(true).SetCleanSession(true).SetKeepAlive(5 * time.Second). SetMaxReconnectInterval(10 * time.Second). SetConnectRetry(true).SetConnectRetryInterval(time.Second) opts.AddBroker(broker) opts.SetOnConnectHandler(func(client mqtt.Client) { log.Println("connected") client.Subscribe(subTopic, 1, onMessage) }).SetConnectionLostHandler(func(client mqtt.Client, err error) { log.Println("connect lost") }) client = mqtt.NewClient(opts) token := client.Connect() if ok := token.WaitTimeout(time.Second * 10); ! ok { panic("connect timeout") } for { } } func onMessage(client mqtt.Client, msg mqtt.Message) { log.Printf("onmessage, topic:%v, messageId:%v, msg: %+v\n", msg.Topic(), msg.MessageID(), string(msg.Payload())) // Message processing logic } // publish Send messages func publish(payload []byte) error { token := client.Publish(pubTopic, 1, true, payload) log.Println(token) return nil } func genSecKey(clientID, userName string) []byte { secKey := genMd5(clientID + userName)[:16] return []byte(secKey) } func genMd5(source string) (md5str string) { md5Ctx := md5.New() md5Ctx.Write([]byte(source)) cipherStr := md5Ctx.Sum(nil) md5str = hex.EncodeToString(cipherStr) return } ``` -------------------------------- ### Get User List Source: https://developer.tuya.com/en/docs/cubeprivate-cloud/api-reference?id=Kcmga5rjnn8z9 This snippet demonstrates how to make an API request to get a list of users within a specified date range. It includes the HTTP method, endpoint, and query parameters for pagination and time filtering. The example uses Unix timestamps for start and end times. ```APIDOC ## GET /v2.0/apps/schema/users ### Description Retrieves a list of users with options for pagination and time-based filtering. ### Method GET ### Endpoint `https://${hosts}/v2.0/apps/schema/users` ### Query Parameters - **page_no** (integer) - Required - The page number for the user list. - **page_size** (integer) - Required - The number of entries per page (e.g., 50). - **start_time** (integer) - Required - The start time for filtering users, in Unix timestamp format. - **end_time** (integer) - Required - The end time for filtering users, in Unix timestamp format. ### Request Header Parameters - **client_id** (string) - Required - Your application's client ID. - **sign** (string) - Required - The signature of the request. - **sign_method** (string) - Required - The method used for signing the request (e.g., HMAC-SHA256). - **t** (integer) - Required - The timestamp of the request. - **access_token** (string) - Required - The access token for authentication. - **nonce** (string) - Required - A unique nonce for the request. - **Signature-Headers** (string) - Optional - Headers included in the signature calculation. - **area_id** (string) - Optional - The area ID for the request. - **request_id** (string) - Optional - A unique request ID. ### Request Example ``` GET:https://${hosts}/v2.0/apps/schema/users?page_no=1&page_size=50&start_time=1619798400&end_time=1621008000 ``` ### Request Header Example ``` { "client_id": "1KAD46OrT9HafiKd****", "sign": "C5EFD19AD45E33A060C0BE47AEF65D975D54B2D70CBAA7A1ACA1A7D0E5C0****", "sign_method": "HMAC-SHA256", "t": 1588925778000, "access_token": "3f4eda2bdec17232f67c0b188af3****", "nonce": "5138cc3a9033d69856923fd07b49****", "Signature-Headers": "area_id:request_id", "area_id": "29a33e8796834b1****", "request_id": "8afdb70ab2ed11eb85290242ac13****" } ``` ``` -------------------------------- ### Start Scanning Example (Objective-C) Source: https://developer.tuya.com/en/docs/cubeprivate-cloud/ble?id=Kdemi7747fbpw Demonstrates how to set the delegate and start scanning for Bluetooth devices using `startListening:` or `startListeningWithType:cacheStatu:`. ```objective-c // Sets a delegate. [ThingSmartBLEManager sharedInstance].delegate = self; // Starts scanning. [[ThingSmartBLEManager sharedInstance] startListening:YES]; // Alternatively, starts scanning in the following way. [[ThingSmartBLEManager sharedInstance] startListeningWithType:ThingBLEScanTypeNoraml cacheStatu:YES]; ``` -------------------------------- ### Request Example for Get Update Progress Source: https://developer.tuya.com/en/docs/cloud/4b34803d62?id=Kcp2l1lnnvi1k An example of a GET request to the 'Get Update Progress' API, specifying a device ID and channel. ```http GET: /v2.0/cloud/thing/aab21***/firmware/0/progress ``` -------------------------------- ### Initialize and Start Playback Source: https://developer.tuya.com/en/docs/app-development/ipc-key-sample-sd-playback?id=Kdmyzlv497uqo This Java code demonstrates the initialization of the IPC SDK, setting up the video view, registering listeners, connecting to P2P, and initiating playback. Ensure all necessary components are created and callbacks are registered before starting playback. ```java // 1. Create IThingSmartCameraP2P IThingSmartCameraP2P mCameraP2P = null; IThingIPCCore cameraInstance = ThingIPCSdk.getCameraInstance(); if (cameraInstance != null) { mCameraP2P = cameraInstance.createCameraP2P(devId)); } ThingCameraView mVideoView = findViewById(R.id.camera_video_view); // 2. Set the callback for the view rendering container. mVideoView.setViewCallback(new AbsVideoViewCallback() { @Override public void onCreated(Object view) { super.onCreated(view); // When the rendering view is constructed, bind it to IThingSmartCameraP2P. if (null != mCameraP2P){ mCameraP2P.generateCameraView(view); } } }); // 3. Construct the rendering view. mVideoView.createVideoView(devId); // 4. Register a listener for P2P. AbsP2pCameraListener absP2pCameraListener = new AbsP2pCameraListener() { @Override public void onSessionStatusChanged(Object camera, int sessionId, int sessionStatus) { super.onSessionStatusChanged(camera, sessionId, sessionStatus); // When sessionStatus = -3 (timeout) or -105 (authentication failed), try reconnecting and avoid loop. } }; if (null != mCameraP2P){ mCameraP2P.registerP2PCameraListener(absP2pCameraListener); } // 5. Connect to P2P. if (null != mCameraP2P){ mCameraP2P.connect(devId, new OperationDelegateCallBack() { @Override public void onSuccess(int sessionId, int requestId, String data) { // Connection successful. Send a message to the handler to return to the main thread and then initiate streaming. } @Override public void onFailure(int sessionId, int requestId, int errCode) { // Connection failed. } }); } // 6. Start playback. if (null != mCameraP2P){ mCameraP2P.startPlayBack(timePieceBean.getStartTime(), timePieceBean.getEndTime(), timePieceBean.getStartTime(), new OperationDelegateCallBack() { @Override public void onSuccess(int sessionId, int requestId, String data){ isPlayback = true; } @Override public void onFailure(int sessionId, int requestId, int errCode){ isPlayback = false; } }, new OperationDelegateCallBack() { @Override public void onSuccess(int sessionId, int requestId, String data){ isPlayback = false; } @Override public void onFailure(int sessionId, int requestId, int errCode){ isPlayback = false; } }); } ``` -------------------------------- ### Get Room Details Request Example Source: https://developer.tuya.com/en/docs/cloud/41ed8d688d?id=Kb7q0lz7upo38 Example of a GET request to the Get Room Details API, specifying the room ID in the URL. ```http GET: {url}/v1.0/osaas/rooms/1160823965053****** ``` -------------------------------- ### Fetch Firmware Update Details (Objective-C Example) Source: https://developer.tuya.com/en/docs/app-development/ios-device-firmware?id=Kceufjgki9zxp Example demonstrating how to call the `checkFirmwareUpgrade` method and handle success or failure callbacks. Ensure you have initialized the device object. ```Objective-C - (void)getFirmwareUpgradeInfo { // self.device = [TuyaSmartDevice deviceWithDeviceId:@"your_device_id"]; [self.device checkFirmwareUpgrade:^(NSArray *upgradeModelList) { NSLog(@"getFirmwareUpgradeInfo success"); } failure:^(NSError *error) { NSLog(@"getFirmwareUpgradeInfo failure: %@", error); }]; } ``` -------------------------------- ### Get Current Vehicle Request Example Source: https://developer.tuya.com/en/docs/cloud/3a1828ef2f?id=Kbn028dj9af6j An example of a GET request to the 'Get Current Vehicle' API, showing how to specify the device ID. ```http GET: /v1.0/parking-control/6ce****/cars/current ``` -------------------------------- ### Get Update Information Request Example Source: https://developer.tuya.com/en/docs/cloud/0184fc64cb?id=Kcp2l2jzz44s2 An example of a GET request to the 'Get Update Information' API, demonstrating how to specify the device ID. ```http GET: /v2.0/cloud/thing/vdev1243432***/firmware ``` -------------------------------- ### Request Example for Querying Prepayment Status Source: https://developer.tuya.com/en/docs/cloud/9598c8905d?id=Kb5y2plliccho This example demonstrates how to construct a GET request to query the prepayment feature status for a specific device ID. ```bash GET: /v1.0/iot-03/power-devices/6c814919a3f54fb4eb****/prepayment ``` -------------------------------- ### Run WebRTC Demo Application Source: https://developer.tuya.com/en/docs/iot/webrtc?id=Kacsd4x2hl0se After configuring the `webrtc.json` file with your project and device details, execute the built application to start the WebRTC server. ```bash ./webrtc-demo-go ``` -------------------------------- ### Get All Timers Request Example Source: https://developer.tuya.com/en/docs/cubeprivate-cloud/timing-management?id=Kcb5kopfyq680 This is an example of a GET request to retrieve all timing tasks for a device. ```http GET /v1.0/devices/vdevo154458004640011/timers ``` -------------------------------- ### Example Request for Get Failover Status Source: https://developer.tuya.com/en/docs/cloud/ec4043fa02?id=Kb8blx84dc4sd An example of a GET request to the 'Get Failover Status' API, demonstrating how to include the gateway ID in the URL. ```bash GET: /v1.0/alps/fayl9sn0482hl****/transfer/status ``` -------------------------------- ### Example: Scanning and Callback Handling Source: https://developer.tuya.com/en/docs/app-development/mesh?id=Ka5vdjp3ikagz Demonstrates how to start scanning for a device pending pairing and how to implement the callback to process scanned device information, distinguishing between gateways and sub-devices. ```objective-c // Starts scanning for a device pending pairing. [[ThingBLEMeshManager sharedInstance] startScanWithName:@"out_of_mesh" pwd:@"123456" active:YES wifiAddress:0 otaAddress:0]; // The callback of `ThingBLEMeshManagerDelegate`. - (void)bleMeshManager:(ThingBLEMeshManager *)manager didScanedDevice:(ThingBleMeshDeviceModel *)device { // This callback method applies to scanning for both gateways and sub-devices. // `device.type` and `device.vendorInfo` determines whether the target device is a mesh gateway. if (device.type == [TPUtils getIntValueByHex:@"0x0108"] || ([TPUtils getIntValueByHex:[device.vendorInfo substringWithRange:NSMakeRange(0, 2)]] & 0x08) == 0x08) { // The mesh gateway. return; } else { // Mesh sub-devices. } } ``` ```objective-c // Implements `getIntValueByHex`. + (uint32_t)getIntValueByHex:(NSString *)getStr { NSScanner *tempScaner=[[NSScanner alloc] initWithString:getStr]; uint32_t tempValue; [tempScaner scanHexInt:&tempValue]; return tempValue; } ``` -------------------------------- ### Fetch Firmware Update Details (Swift Example) Source: https://developer.tuya.com/en/docs/app-development/ios-device-firmware?id=Kceufjgki9zxp Example demonstrating how to call the `checkFirmwareUpgrade` method in Swift and handle the completion and error closures. Ensure the device object is properly initialized. ```Swift func getFirmwareUpgradeInfo() { device?.checkFirmwareUpgrade({ (upgradeModelList) in print("getFirmwareUpgradeInfo success") }, failure: { (error) in if let e = error { print("getFirmwareUpgradeInfo failure: \(e)") } }) } ``` -------------------------------- ### Get Device Group Request Example Source: https://developer.tuya.com/en/docs/cloud/device-group-v21?id=Kdq46c0rd3jtk Example of a GET request to the 'Get Device Group' API. Replace `{device_id}` with the actual device ID. ```bash GET: /v2.1/cloud/thing/group/device/vdevo17059963185**** ``` -------------------------------- ### Example: Configure GPIO and Timer Wakeup Sources, then Enter Sleep Source: https://developer.tuya.com/en/docs/iot-device-dev/bluetooth_software_map_mesh_low_power?id=Kd5wtoep6vjto Demonstrates configuring GPIO 8 with a low-level trigger and a 30-second timer as wake-up sources, then setting the sleep mode to suspend and entering sleep. ```c TUYA_WAKEUP_SOURCE_BASE_CFG_T param_gpio; param_gpio.source = TUYA_WAKEUP_SOURCE_GPIO; param_gpio.wakeup_para.gpio_param.gpio_num = TUYA_GPIO_NUM_8; param_gpio.wakeup_para.gpio_param.level = TUYA_GPIO_LEVEL_LOW; TUYA_WAKEUP_SOURCE_BASE_CFG_T param_timer; param_timer.source = TUYA_WAKEUP_SOURCE_TIMER; param_timer.wakeup_para.timer_param.timer_num = TUYA_TIMER_NUM_0; param_timer.wakeup_para.timer_param.mode = TUYA_TIMER_MODE_ONCE; param_timer.wakeup_para.timer_param.ms = 30000; tkl_wakeup_source_set(¶m_gpio); tkl_wakeup_source_set(¶m_timer); tkl_cpu_sleep_mode_set(1, TUYA_CPU_SLEEP); tkl_cpu_allow_sleep(); ``` -------------------------------- ### Get Region List Request Example Source: https://developer.tuya.com/en/docs/cloud/c76c9f9652?id=Kb3oe8ddnsqix An example of a GET request to the 'Get Region List' API, demonstrating the structure of the URI with placeholder IDs. ```http GET: /v2.0/infrareds/vdevo15345926009****/provinces/120000/cities/120100/areas ``` -------------------------------- ### Get Languages Request Example Source: https://developer.tuya.com/en/docs/cloud/a604a280d9?id=Kfee5142s7vpj This example shows the structure of a GET request to the 'Get Languages' API, including the device ID path parameter. ```bash GET: /v1.0/cloud/agent/ai/chat/b/devices/{device_id}/languages ``` ```json { "device_id": "123***" } ``` -------------------------------- ### Example: Start Scan with Specific Parameters Source: https://developer.tuya.com/en/docs/cubeprivate-cloud/mesh?id=Kdemi8e8mbk05 An example demonstrating how to call the `startScanWithName` method with specific parameters for connecting a device to a mesh network. Note that `active`, `wifiAddress`, and `otaAddress` are set to specific values. ```objective-c [[ThingBLEMeshManager sharedInstance] startScanWithName:[ThingSmartUser sharedInstance].meshModel.code pwd:[ThingSmartUser sharedInstance].meshModel.password active:NO wifiAddress:0 otaAddress:0]; ```