Coder Social home page Coder Social logo

tuya-connector-nodejs's Introduction

English | 中文版

What is tuya-connector?

Tuya Open Platform—API Reference

Tuya provides a set of HTTP APIs and signature verification logic. You need to implement the logic when you make the API requests.

tuya-connector provides capabilities to sign a request, refresh, store, and renew a token, and encapsulate common APIs, helping you quickly connect to Tuya's open platform.

Install

npm install @tuya/tuya-connector-nodejs

# or
yarn add @tuya/tuya-connector-nodejs

Get started

import { TuyaContext  } from '@tuya/tuya-connector-nodejs';

const tuya = new TuyaContext({
  baseUrl: 'https://openapi.tuyacn.com',
  accessKey: 'xx',
  secretKey: 'xx',
});

const device = await tuya.device.detail({
  device_id: 'device_id'
});

Advanced development

Custom tokenStore

By default, tokenStore is implemented based on memory. We recommend that you implement the store instance in your service. In the following code block, the Redis Store is used as an example.

// tokenStore.ts
import { TuyaTokenStorInterface, TuyaTokensSave } from '@tuya/tuya-connector-nodejs';
import IORedis from 'ioredis';

export class RedisTokenStore implements TuyaTokenStorInterface {
  private readonly client: IORedis.Redis;
  private readonly key: string;
  constructor(client: IORedis.Redis, key: string = 'tuya::token') {
    this.client = client;
    this.key = key;
  }

  async setTokens(tokens: TuyaTokensSave): Promise<boolean> {
    const res = await this.client.set(this.key, JSON.stringify(tokens));
    return ! ! res;
  }
  async getAccessToken(): Promise<string | undefined> {
    const jsonStr = await this.client.get(this.key) || '{}';
    const tokens: TuyaTokensSave = JSON.parse(jsonStr);
    return tokens && tokens.access_token;
  }
  async getRefreshToken(): Promise<string | undefined> {
    const jsonStr = await this.client.get(this.key) || '{}';
    const tokens: TuyaTokensSave = JSON.parse(jsonStr);
    return tokens.refresh_token;
  }
}

// index.ts
import { RedisTokenStore } from './tokenStore';
import IoRedis from 'ioredis';
const redis = new IoRedis();

const tuya = new TuyaContext({
  baseUrl: 'https://openapi.tuyacn.com',
  accessKey: 'xx',
  secretKey: 'xx',
  store: new RedisTokenStore(redis),
});

Custom request of httpClient

tuya-connector uses Axios as httpClient by default, and exposes replaceable parameters. If necessary, you can also customize httpClient.

import axios from 'axios';
import { TuyaContext  } from '@tuya/tuya-connector-nodejs';

const tuya = new TuyaContext({
  baseUrl: 'https://openapi.tuyacn.com',
  accessKey: 'xx',
  secretKey: 'xx',
  rpc: axios
});

Requests of other OpenAPIs

tuya-connector encapsulates common APIs, and declares the types of request and response parameters. You can customize additional API requests.

import { TuyaContext  } from '@tuya/tuya-connector-nodejs';

const tuya = new TuyaContext({
  baseUrl: 'https://openapi.tuyacn.com',
  accessKey: 'xx',
  secretKey: 'xx',
});

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

Other issues

  1. Apply for an authorization key. On the platform, you can create a project to get the access ID and access secret of the cloud application.

  2. For more information about global error codes, see Global Error Codes.

tuya-connector-nodejs's People

Contributors

erchoc avatar funnybunnyqaq avatar killianhmyd avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

tuya-connector-nodejs's Issues

No License associated with this project

Hi,

The other official Tuya SDK projects have licenses associated with them - either Apache 2.0 or MIT from what I've seen. Is there a chance one of these could be applied to this NodeJS code? It's unclear how 'safe' it is to use within projects without this!

Thanks!

How to use this SDK?

At the moment the project seems to not be published on NPM, moreover it's a Typescript project, and needs to be built (in ./lib as I read the config file) to be consumed

How can we help?

Always got sign invalid

I tried to send a api call witht his sdk, i provide correcte secret and access key. but it always return an sign invalid error. Here the example of the code

const result = await client.request({
    method: 'post',
    path: `/v1.0/iot-03/devices/${deviceID}/commands`,
    body: {
      device_id: deviceID,
      commands: [{
        code: 'switch_led',
        value: value,
      }]
    }
  });

Issue in passing comma separated values in query TuyaContext.request

This code says Invalid token:

let deviceIdArray = ["someid","someOtherId"]
let deviceList = deviceIdArray.join()
let statusResponse=  await tuya.request({
            path: `/v1.0/iot-03/devices/status`,
            method: 'GET',
           query:{
              device_ids: deviceList
        });

And this one works:

let deviceIdArray = ["someid","someOtherId"]
let deviceList = deviceIdArray.join()
let statusResponse= await tuya.request({
            path: `/v1.0/iot-03/devices/status?device_ids=${deviceList}`,
            method: 'GET',
        });`

Ideally, both imply same things, but looks like the query formation has some issue, using v2.0.2

"Get the device list" api not working

Here is my code snippet to get all list of devices:

var device = await tuya.request({
        method: 'GET',
        path: '/v1.0/devices',
        body: {
            page_size:10,
            page_no:1
        }
    })

But its giving the following response:
{ code: 1100, msg: 'param is empty', success: false, t: 1629498362573 }
I have also tried this api explorer at https://iot.tuya.com/ but getting the same response. Please let me know what other parameter need to be passed in this api for getting the correct response.

Wrong request for tuya.deviceFunction.command()

I saw the .deviceFunction.command() function but get every time an error with 'uri path invalid'.
After looking in the functions.ts file of this repo, I saw that I was right. There is an param to add commands (line 55).
But I think the Request Function is messed up because it is missing the command param and set to GET instead of POST (line 94).

Am I right in my suspicion?

/iot-03/ Causing login errors

Hi,

I think there is a bug. I cannot login from central europe. using this url:

return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.client.request({ path: "/v1.0/iot-03/categories/" + param.category + "/functions", method: 'GET', })]; case 1: res = _a.sent(); return [2 /*return*/, res.data]; } });

But removing the /iot-03/ works....

"No permissions. This API is not subscribed"

I followed the README file, to create a small tuya.device.detail request for one of my devices. While the call is without any problems working when using the Tuya IoT Platform (https://iot.tuya.com/) I just get the error message No permissions. This API is not subscribed. when using this module. I verified access key and secret multiple times.

Permission Deny error

When I try to connect to the Central Europe server to get the device as per the "getting started" code I get a 1106 permission deny error. The gateway device that I am trying to connect to has "Read, write, and Manage" permissions.

import { TuyaContext  } from '@tuya/tuya-connector-nodejs';

const tuya = new TuyaContext({
  baseUrl: 'https://openapi.tuyaeu.com',
  accessKey: process.env['ACCESSID'],
  secretKey: process.env['ACCESSSECRET'],
});

export const getDevice = async () => {
    const device = await tuya.device.detail({
      device_id: process.env['DEVICEID']
    });
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.