English
English
简体中文
Contact Us
Register
Log In

Develop with Node.js SDK

Last Updated on : 2021-11-17 06:41:55download

This topic describes how to develop a program to control devices based on the open capabilities and SDK of the Tuya IoT Development Platform.

Prerequisites

Procedure

Step 1: Set up development environment

This step is based on the Tuya-connector-Nodejs SDK. Tuya-connector helps you efficiently create cloud development projects regarding the OpenAPI or message subscription capabilities. You can put all the focus on business logic without taking care of server-side programming nor relational databases. Perform the following steps:

  1. Get the SDK address at Tuya-connector-Nodejs.

    Develop with Node.js SDK

  2. Go to Projects > Get from Version Control > URL, enter the SDK address, and then click Clone.

    Develop with Node.js SDK

  3. Choose View > Tool Windows > Terminal, open the terminal, and then install the dependency package. The following two methods are supported.

    • yarn add @tuya/tuya-connector-nodejs
    • npm install @tuya/tuya-connector-nodejs

    Develop with Node.js SDK

Step 2: Edit profile

Before development, you need to configure environment variables in example > index.ts.

  1. Go to the Tuya IoT Platform and select your cloud project. Click Overview and find the Cloud Application Authorization Key, including Access ID and Access Secret.

    Develop with Node.js SDK

  2. Configure environment variables in the index.ts file.

    • baseUrl: the data center URL of the API request.
    • accessKey: Enter the value of the Access ID in the Authorization Key section.
    • secretKey: Enter the value of the Access Secret in the Authorization Key section.

    Develop with Node.js SDK

    Sample code:

    const context = new TuyaContext({
    	baseUrl: 'https://openapi.tuyacn.com',
    	accessKey: 'xtu7m*****48ufo',
    	secretKey: '479bcba6d*******d9c4e080f7',
    });
    

Step 3: Control devices

After the environment is ready, you can start your coding journey.

Note: The strip lights are controlled in this example. The standard instruction set for turning lights on or off is switch_led. To control other devices, query the standard instruction set and modify the code.

  1. Create OpenAPIs.
    Certain APIs are encapsulated in the SDK and can be called as needed.

    Sample code:

      const device_id = "vdevo162799080003567";
      const devicedetail  = await context.device.detail({
        device_id: device_id,
      });
      if(!devicedetail.success) {
        new Error();
      }
      console.log("Device details:",devicedetail);
    
  2. Create a custom API.
    tuya-connector encapsulates common APIs, and declares the types of request and response parameters. You can customize additional API requests.

    const { data } = await context.request({
      method: 'GET',
      path: '/v1.0/xx',
      body: {},
    });
    

    Sample code:

      const commands = await context.request({
        path: `/v1.0/iot-03/devices/${device_id}/commands`,
        method: 'POST',
        body: {"commands":[{"code":"switch_led","value":true}]}
      });
      if(!commands.success) {
        new Error();
      }
      console.log("Execution result:",commands);
    

    Complete sample code of index.ts

    import { TuyaContext } from '@tuya/tuya-connector-nodejs';
    
    const context = new TuyaContext({
      baseUrl: 'https://openapi.tuyacn.com',
    	accessKey: 'xtu7m*****48ufo',
    	secretKey: '479bcba6d*******d9c4e080f7',
    });
    
    const main = async () => {
     // Define the device ID
      const device_id = "vdev*******80003567";
      // Query device details
      const devicedetail  = await context.device.detail({
        device_id: device_id,
      });
      if(!devicedetail.success) {
        new Error();
      }
      console.log("Device details:",devicedetail);
    // Send commands
      const commands = await context.request({
        path: `/v1.0/iot-03/devices/${device_id}/commands`,
        method: 'POST',
        body: {
          "commands":[{"code":"switch_led","value":true}]
        }
      });
      if(!commands.success) {
        new Error();
      }
      console.log("Execution result:",commands);
    };
    main().catch(err => {
      console.log(err);
    });
    
  3. Perform debugging.

    1. Compile the .ts file with the TypeScript compiler.
      Use the terminal to enter the specified folder and compile the index.ts file.

      Sample code: tsc index.ts
      Develop with Node.js SDK

    2. node runs the compiled .js file.

      Sample code: node index.js

      Develop with Node.js SDK

      Execution result

      even@*******deMacBook-Air examples % node index.js
      Device details: {
        result: {
          active_time: 1627990800,
          asset_id: '1417*******823672832',
          category: 'dj',
          category_name: 'Light source',
          create_time: 1627990800,
          gateway_id: '',
          icon: 'smart/program_category_icon/dj.png',
          id: 'vdev*******80003567',
          ip: '',
          lat: '',
          local_key: '25bfe*******3a5b257',
          lon: '',
          model: '',
          name: 'smart bulb 800lm rgb+cct-vdevo',
          online: true,
          product_id: 'yju2*******ujr5zx',
          product_name: 'smart bulb 800lm rgb+cct',
          sub: false,
          time_zone: '+08:00',
          update_time: 1627990800,
          uuid: 'vdev*******080003567'
        },
        success: true,
        t: 1629363047422
      }
      Execution result: { result: true, success: true, t: 1629363047600 }			
      
    3. (Optional) Use ts-node to compile and run the index.ts file.

      Note: You need to install ts-node.

      Sample code: ts-node index.ts

      Develop with Node.js SDK

      Execution result

      even@*******deMacBook-Air examples % node index.js
      Device details: {
        result: {
          active_time: 1627990800,
          asset_id: '1417*******823672832',
          category: 'dj',
          category_name: 'Light source',
          create_time: 1627990800,
          gateway_id: '',
          icon: 'smart/program_category_icon/dj.png',
          id: 'vdev*******80003567',
          ip: '',
          lat: '',
          local_key: '25bfe*******3a5b257',
          lon: '',
          model: '',
          name: 'smart bulb 800lm rgb+cct-vdevo',
          online: true,
          product_id: 'yju2*******ujr5zx',
          product_name: 'smart bulb 800lm rgb+cct',
          sub: false,
          time_zone: '+08:00',
          update_time: 1627990800,
          uuid: 'vdev*******080003567'
        },
        success: true,
        t: 1629363504545
      }
      Execution result: { result: true, success: true, t: 1629363504706 }			
      

Conclusion

In this topic, you have learned how to use the Node.js SDK based on the Tuya IoT Development Platform. You can call device APIs to control smart devices. Thanks to the standard ecosystem of devices, you can extend this control method to all devices of Tuya’s ecosystem, and accelerate your SaaS development based on smart devices without regard to device differences.