Code Monkey home page Code Monkey logo

Comments (54)

nareso avatar nareso commented on June 21, 2024 8

I found a temporary workaround.

APP_ID: Uw83EKZFxdif7XFXEsrpduz5YyjP7nTl
APP_SECRET: mXLOjea0woSMvK9gw7Fjsy7YlFO4iSu6
works for me.

Thanks, LiorLindvor.
#212 (comment)

from ewelink-api.

karocavo avatar karocavo commented on June 21, 2024 1

Well, I've had problems with Error 401, now it's gone. I have not created API myself, but used keys from this post -
APP_ID: Uw83EKZFxdif7XFXEsrpduz5YyjP7nTl
APP_SECRET: mXLOjea0woSMvK9gw7Fjsy7YlFO4iSu6
/by nareso/
and changed these in settings.js file under command line in nodered container - attached pic for reference
nr2

from ewelink-api.

 avatar commented on June 21, 2024 1

Uw83EKZFxdif7XFXEsrpduz5YyjP7nTl It is an APPID that should not be used, please ignore it.

Through personal developer methods, it is possible to integrate with devices. I will add an example of obtaining device information and controlling devices later, but the specific content needs to be configured based on your device.

from ewelink-api.

 avatar commented on June 21, 2024 1
  1. For 4ch devices, the control instructions are different and the method is the same. Change {"switch": "on"} to {"switches": [{"switch": "off", "outlet": 0}, {"switch": "off", "outlet": 1}, {"switch": "off", "outlet": 2}, {"switch": "off", "outlet": 3}]} to complete this section https://coolkit-technologies.github.io/eWeLink-API/#/en/UIIDProtocol It is stated in the document.

  2. It supports real-time control of devices, whether through interfaces or websockets.

from ewelink-api.

nareso avatar nareso commented on June 21, 2024 1

Thank you for your detailed explanation.

Now, when the V1 interface is deprecated, I would like an alternative environment for ewelink-api, but if anyone knows a recommended environment, please let me know.

Development candidates that can control ewelink device with low code are

  1. node-red-contrib-ewelink-cube
    In my testing, it's still unstable.
  2. Homeassiatant Add-on eWeLink Smart Home
    Does this use the V2 interface?
  3. homebridge-ewelink
    Does this use the V2 interface?
  4. other candidates

Any comments would be appreciated.

from ewelink-api.

 avatar commented on June 21, 2024 1

@coolkit-carl您能展示一个令牌刷新的有效示例吗?
https://github.com/coolkit-carl/eWeLinkOAuthLoginDemo/blob/main/controlDeviceDemo.js

from ewelink-api.

mduchain avatar mduchain commented on June 21, 2024 1

@coolkit-carl, I confirm the same behavior reported by @AndreFvdMerwe.
I use two accounts, and only account 1 has the devices. Account 1 has shared all devices with account 2 via android app ewelink. On the android app, all devices are visibile when using account 2.
Yet, the nodered node "devices" returns an empty array when using account 2. Using account 1, I get the full list of devices.
device id: 1000a4f037

from ewelink-api.

nareso avatar nareso commented on June 21, 2024

Correction, sonoff devices also become errors.

from ewelink-api.

antonioGabrielGomes avatar antonioGabrielGomes commented on June 21, 2024

after registering your ewelink account and creating app, did your app_id and secret_id work normally?

from ewelink-api.

karocavo avatar karocavo commented on June 21, 2024

I've had little problem finding correct directory under my portainer node-red install, found here: //data/node_modules/ewelink-api/src/data$ -if anyone has same problem. Using vi editor I have changed the credentials as above (or create your own under dev.ewelink.cc) and the auth problem solved now!

from ewelink-api.

mduchain avatar mduchain commented on June 21, 2024

@antonioGabrielGomes , all,
I've created my own APP_ID & APP_SECRET on dev.ewelink.cc, - standard role.
However this doens't fully work. I can get devices and events just fine,
but all other nodes just give me "wrong account or password".

With the above credentials from @nareso , I get full functionality.
At this point, should I assume the issue is with the role?

from ewelink-api.

antonioGabrielGomes avatar antonioGabrielGomes commented on June 21, 2024

@karocavo

I did that but got the same error

from ewelink-api.

antonioGabrielGomes avatar antonioGabrielGomes commented on June 21, 2024

@mduchain

It could be the type of account we're creating, maybe individual developer access doesn't have permissions.

from ewelink-api.

 avatar commented on June 21, 2024

Regarding authorization issues, accounts created by individual developers can only be redirected to the authorization page for login. So it cannot directly request the login interface to obtain a Token, the specific information is here: https://coolkit-technologies.github.io/eWeLink-API/#/en/OAuth2.0

from ewelink-api.

nareso avatar nareso commented on June 21, 2024

Hi carl , thanks for your reply.

I do not understand the Create application procedure, but how should I describe it in the redirect URL field?

By the way, in my account,
I can login with https://dev.ewelink.cc/#/login, but with https://c2ccdn.coolkit.cc/oauth/index.html the login process does not proceed.

from ewelink-api.

 avatar commented on June 21, 2024

This is an example of eWeLink OAuth2.0 login:https://github.com/coolkit-carl/eWeLinkOAuthLoginDemo

from ewelink-api.

nareso avatar nareso commented on June 21, 2024

Hi carl, thank you very much for your kind explanation.

But, I can't find config.js in ewelink-api directory.
Isn't your example for ewelink-api-next?

Please tell me the create application procedure when using ewelink-api.

from ewelink-api.

karocavo avatar karocavo commented on June 21, 2024

Hi carl, thank you very much for your kind explanation.

But, I can't find config.js in ewelink-api directory. Isn't your example for ewelink-api-next?

Please tell me the create application procedure when using ewelink-api.

The file to overwrite keys from previous comments is in directory path i’ve mentioned specifically in case of a portainer install (NAS)- keys from ewelink.cc supposedly do not work, as written above

from ewelink-api.

antonioGabrielGomes avatar antonioGabrielGomes commented on June 21, 2024

Hi carl , thanks for your reply.

I do not understand the Create application procedure, but how should I describe it in the redirect URL field?

By the way, in my account, I can login with https://dev.ewelink.cc/#/login, but with https://c2ccdn.coolkit.cc/oauth/index.html the login process does not proceed.

the same here.

from ewelink-api.

antonioGabrielGomes avatar antonioGabrielGomes commented on June 21, 2024

Regarding authorization issues, accounts created by individual developers can only be redirected to the authorization page for login. So it cannot directly request the login interface to obtain a Token, the specific information is here: https://coolkit-technologies.github.io/eWeLink-API/#/en/OAuth2.0

Thanks for the info. Now, with the individual developer method, we can integrate with devices ? making a boost on the demo you sent?

from ewelink-api.

 avatar commented on June 21, 2024

Updated, feat: Add device examples to control the current login account
https://github.com/coolkit-carl/eWeLinkOAuthLoginDemo

from ewelink-api.

thomas350 avatar thomas350 commented on June 21, 2024

@coolkit-carl can we say at least that it is really messy ??
Why Ewelink disables v1 interface while v2 interface does not work for production ?

On my side, my own app_id and app_secret doesn't work but this app_id works : Uw83EKZFxdif7XFXEsrpduz5YyjP7nTl
Which is really weird.

Can you explain us how to easily use your ewelink-api-next to basically turn on/off a device please ?

Documentation here : https://coolkit-technologies.github.io/eWeLink-API/#/en/OAuth2.0
Or here : https://github.com/coolkit-carl/eWeLinkOAuthLoginDemo
are clearly not understandable and seems to not be stable at all.

from ewelink-api.

 avatar commented on June 21, 2024

from ewelink-api.

antonioGabrielGomes avatar antonioGabrielGomes commented on June 21, 2024
  1. Can you give an example of why you feel unstable? The v2 interface has been running and maintained for 3 years, and there have been no significant changes to the interface. 2. We have stopped maintaining the v1 interface. Its security is not as high as the v2 interface, and its functionality is not as comprehensive as the v2 interface. Stopping is inevitable. 3 https://github.com/coolkit-carl/eWeLinkOAuthLoginDemo <https://github.com/coolkit-carl/eWeLinkOAuthLoginDemo > I updated the latest document for this project yesterday and wrote about the entire process. 4. ewelink-api-next actually has basic examples. In the next few days, it will be open source and provide additional documentation for all functions (in fact, if you use TypeStript, you will get a more perfect prompt, and its source code also has annotations). Dep:产品部|解决方案工程师 Name:刘家乐 @.*** @.*** > Tel:+86(0)755 26404901 Mob:+86 18598029557 ------------------------------------------------------------------ 发件人:thomas350 @.> 发送时间:2023年8月16日(星期三) 19:48 收件人:skydiver/ewelink-api @.> 抄 送:刘家乐 @.>; Mention @.> 主 题:Re: [skydiver/ewelink-api] Error 401: Wrong account or password -- again (Issue #220) @coolkit-carl <https://github.com/coolkit-carl > can we say at least that it is really messy ?? Why Ewelink is disabling v1 interface while v2 interface does not work for production ? On my side, my own app_id and app_secret doesn't work but this app_id works : Uw83EKZFxdif7XFXEsrpduz5YyjP7nTl Which is really weird. Can you explain us how to easily use your ewelink-api-next to basically turn on/off a device please ? Documentation here : https://coolkit-technologies.github.io/eWeLink-API/#/en/OAuth2.0 <https://coolkit-technologies.github.io/eWeLink-API/#/en/OAuth2.0 > Or here : https://github.com/coolkit-carl/eWeLinkOAuthLoginDemo <https://github.com/coolkit-carl/eWeLinkOAuthLoginDemo > are clearly not understandable and seems to not be stable at all. — Reply to this email directly, view it on GitHub <#220 (comment) >, or unsubscribe <https://github.com/notifications/unsubscribe-auth/AMDDIXVSHSAIYH2XMKDTXDTXVSXRZANCNFSM6AAAAAA3K5OG2Q >. You are receiving this because you were mentioned.Message ID: @.***>

Does the method in the demo not work for 4ch devices? and does the library work to enable and disable devices in real time?

from ewelink-api.

nareso avatar nareso commented on June 21, 2024

Hi carl

I noticed that the object structure has changed between V1 and V2.
For example, an ”off” information of a single switch from node-red-contrib-ewelink are
V1 --- msg.payload.params.switch: "off"
V2 --- msg.payload.params.switch.switch: "off"
Like, it's one layer deep.

Could these changes be the reason that node-red-contrib-ewelink doesn't work properly with V2 interfaces?

from ewelink-api.

 avatar commented on June 21, 2024

No, the action for controlling the device have not changed. We have only changed the interface domain name, path, and parameter transfer method.

from ewelink-api.

nareso avatar nareso commented on June 21, 2024

The change from V1 object {"switch":"off"} to V2 object {"switch":{"switch":"off"}} is a very big change for me.

To which of the described changes does such a change apply?

from ewelink-api.

 avatar commented on June 21, 2024

There is no change, {"switch": {"switch": "off"}} is incorrect.

from ewelink-api.

nareso avatar nareso commented on June 21, 2024

Here is my environment and results.

Nod-red version : v3.0.2
node-red-contrib-ewelink version : 2.0.0
node: ewelink-generic-device
input : {"method":"getDevice"}

Using V1 API
output path of "off" is msg.payload.params.switch: "off"

Using V2 API
output path of "off" is msg.payload.params.switch.switch: "off"

please confirm.

from ewelink-api.

thomas350 avatar thomas350 commented on June 21, 2024

@coolkit-carl

Can you explain us how to easily use your ewelink-api-next to basically turn on/off a 4ch device please ?

Documentation here : https://coolkit-technologies.github.io/eWeLink-API/#/en/OAuth2.0
Or here : https://github.com/coolkit-carl/eWeLinkOAuthLoginDemo
are clearly not understandable and doesn't have example.

Thank you.

from ewelink-api.

PhilETaylor avatar PhilETaylor commented on June 21, 2024

Ok I have this working for my hallway 2 channel light switch. I can turn them on and off right now.

in plain English:

  1. Learn what OAuth is... or follow the instructions at https://github.com/coolkit-carl/eWeLinkOAuthLoginDemo to run a local web server and login - after that you will be redirected back to your redirectUrl and a token.json will be saved with your authentication tokens. Keep this safe!

  2. run controlDeviceDemo.js - this listed all my devices... that was good, but the code to toggle the first device as a demo did not work for me... but having the list of devices showed that I was authenticated correctly.

  3. By trial and error I worked out then that I could pass the following code

await client.device.setThingStatus({
          type: 1,
          id: '10007bc171', // not my real id, but I used my real id here
          params:
            {
              "switches": [
                {"switch": "on", "outlet": 0},
                {"switch": "on", "outlet": 1}
              ]
            }
        })

AND MY LIGHTS TURNED ON....

  1. with some playing I was able to dump the actual HTTP request that was being made, which simply looks like (This is not code that you can copy and paste from this comment to make it work, this is a dump of the request for you to look at, and to compile your own HTTP Request that looks like this - any decent developer should be able to make a HTTP request in their programming language of choice)
Send request:  {
  url: '/v2/device/thing/status',
  method: 'post',
  baseURL: 'https://eu-apia.coolkit.cc',
  headers: AxiosHeaders {
    Accept: 'application/json, text/plain, */*',
    'Content-Type': 'application/json',
    Authorization: 'Bearer aa0dbbf06cd1NOTMYREALKEY8e84f9a09ffe536d62',
    'X-CK-Nonce': '4s3p08wn',
    Date: '1692398015055'
  },
  params: undefined,
  data: '{"type":1,"id":"10007bc171","params":{"switches":[{"switch":"off","outlet":0},{"switch":"off","outlet":1}]}}'
}

So now I have a proof of concept working in Javascript, I can switch back to PHP and write real HTTP requests, that consume the OAuth Endpoint, which gives me a token to store, and then I can then just use any HTTP client (mine will continue to be PHP) to make http requests

Once you have an access token from OAuth you can call any of the APIs - here is a scaled down request, made by standard curl command

curl --location 'https://eu-apia.coolkit.cc/v2/device/thing/status' \
--header 'X-CK-Nonce: 9e3NOTREALwR7' \
--header 'Authorization: Bearer 90e4e9c7de5NOTMYREALTOKENd36154e3bbc2' \
--header 'Content-Type: application/json' \
--data '{
    "type": 1,
    "id": "10007bc171",
    "params": {
        "switches": [
                {"switch": "on", "outlet": 1}
              ]
    }
}'

The above all works in real life in my house today. Im not @coolkit-carl, Im a PHP dev with API experience :)

If you are looking for a non-technical project where you can just input your username and password to a config file, and magically control your devices, then you can no longer do that. But if you are willing to learn basic development (like OAuth which is pretty much industry standard for authenticating and authorising external services nowadays) then that can be "easily" done.

The old ewelink-api project should be considered deprecated and no longer used.

from ewelink-api.

PhilETaylor avatar PhilETaylor commented on June 21, 2024

I will also just note that the OAuth 2.0 process they are using is crazy and non-standard. If it were standard OAuth then tools like PostMan would be able to get access tokens automatically.

The Authorisation parameters are simply wrong for standard OAuth -https://coolkit-technologies.github.io/eWeLink-API/#/en/OAuth2.0?id=authorization-page-description (eg client_id is right clientId is non-standard etc.)

The PostMan Collection/Environment provided as an example (https://coolkit-technologies.github.io/eWeLink-API/#/en/APICenterV2?id=postman-example), doesnt even support auto Oauth2.0 to get a bearer token :( so at the moment the only way to get/refresh your token is with the demo app that was provided as an example https://github.com/coolkit-carl/eWeLinkOAuthLoginDemo - or to hand code your OAuth authorisation signature as per the documentation on how to hash the authorisation signatures.

from ewelink-api.

antonioGabrielGomes avatar antonioGabrielGomes commented on June 21, 2024

@coolkit-carl Can you show a valid example of token refresh?

from ewelink-api.

AndreFvdMerwe avatar AndreFvdMerwe commented on June 21, 2024

@coolkit-carl您能展示一个令牌刷新的有效示例吗?
https://github.com/coolkit-carl/eWeLinkOAuthLoginDemo/blob/main/controlDeviceDemo.js

@coolkit-carl . I have registered and received my APPID and APPsecret, used both to update ewelink api in node-red on the rpi. I receive all info on my own devices on NodeRed using "devices" node. IT WORKS !!!

Problem:
However, in NodeRed "devices" node I do not receive any info on devices shared with me from other ewelink users.

HOW can I set to also receive info on devices shared with me by others in "devices" node?

( Note: on Home Assistant I am receiving info from both my own sonoff devices, and from sonoff devices shared with me by other users. BUT, it does not work the same in NodeRed)

UPDATE: I tested NodeRed "event listener". There I do receive info from devices shared with me

from ewelink-api.

 avatar commented on June 21, 2024

@coolkit-carl您能展示一个令牌刷新的有效示例吗?
https://github.com/coolkit-carl/eWeLinkOAuthLoginDemo/blob/main/controlDeviceDemo.js

@coolkit-carl . I have registered and received my APPID and APPsecret, used both to update ewelink api in node-red on the rpi. I receive all info on my own devices on NodeRed. IT WORKS !!!

Problem: However, in NodeRed I do not receive any info on devices shared with me from other ewelink users.

HOW can I set to also receive info on devices shared with me by others ?

( Note: on Home Assistant I am receiving info from both my own sonoff devices, and from sonoff devices shared with me by other users. BUT, it does not work the same in NodeRed)

Please provide me with a shared device ID, and I will check the device status for you. In theory, this situation can only occur on the device shared with you, and its brand is not included in the free authorization list of eWeLink.

from ewelink-api.

AndreFvdMerwe avatar AndreFvdMerwe commented on June 21, 2024

my own device: 10017c1e94
shared with me device: 10017c198a

from ewelink-api.

 avatar commented on June 21, 2024

my own device: 10017c1e94 shared with me device: 10017c198a

10017c1e94 SONOFF UIID181, switch control command: {"switch": "on"} or {"switch": "off"}

10017c198a is also the same, theoretically no problem.

I think it is still necessary to check the code and return to ensure that all devices have been obtained (please refer to my code example: https://github.com/coolkit-carl/ewelink-api-next/blob/main/src/web/apis/device/getAllThings.ts ). I am sure that under normal parameter transmission, this device information will definitely be returned

from ewelink-api.

 avatar commented on June 21, 2024

@coolkit-carl, I confirm the same behavior reported by @AndreFvdMerwe. I use two accounts, and only account 1 has the devices. Account 1 has shared all devices with account 2 via android app ewelink. On the android app, all devices are visibile when using account 2. Yet, the nodered node "devices" returns an empty array when using account 2. Using account 1, I get the full list of devices. device id: 1000a4f037

1000a4f037

1000a4f037 SONOFF UIID1 a socket, The same as my previous answer, we do not restrict the return of information on this device (its brand is licensed to you for free)

from ewelink-api.

 avatar commented on June 21, 2024

@coolkit-carl, I confirm the same behavior reported by @AndreFvdMerwe. I use two accounts, and only account 1 has the devices. Account 1 has shared all devices with account 2 via android app ewelink. On the android app, all devices are visibile when using account 2. Yet, the nodered node "devices" returns an empty array when using account 2. Using account 1, I get the full list of devices. device id: 1000a4f037

1000a4f037

1000a4f037 SONOFF UIID1 a socket, The same as my previous answer, we do not restrict the return of information on this device (its brand is licensed to you for free)

from ewelink-api.

michelefa1988 avatar michelefa1988 commented on June 21, 2024

Good afternon, ive been following this chat and I am very curious if there is a way to toggle ewelink smart switches directly via internal network using curl. I do not see why a simple toggle needs to be done via third party apis

Also has anyone figured out a way to do all of the above via curl since so that switch can be attached to node red since after to going over the thread, I still don't have a clear idea on how to do this with node red.

Thanks

from ewelink-api.

soki2001 avatar soki2001 commented on June 21, 2024

I was using ewelink node red module for a couple of years to control my solar system.
3 weeks ago fails and I followed the instructions to change api stuff on constants file.

Now get devices node is working but SET state or GET state nodes are not working and show:
error: 401
msg: "Wrong account or password"

There are any "how to" to solve it because I'm not a developer and I don't understand very well what is the issue

Thanks in advance

from ewelink-api.

apadilla83 avatar apadilla83 commented on June 21, 2024

Ok I have this working for my hallway 2 channel light switch. I can turn them on and off right now.

in plain English:

  1. Learn what OAuth is... or follow the instructions at https://github.com/coolkit-carl/eWeLinkOAuthLoginDemo to run a local web server and login - after that you will be redirected back to your redirectUrl and a token.json will be saved with your authentication tokens. Keep this safe!
  2. run controlDeviceDemo.js - this listed all my devices... that was good, but the code to toggle the first device as a demo did not work for me... but having the list of devices showed that I was authenticated correctly.
  3. By trial and error I worked out then that I could pass the following code
await client.device.setThingStatus({
          type: 1,
          id: '10007bc171', // not my real id, but I used my real id here
          params:
            {
              "switches": [
                {"switch": "on", "outlet": 0},
                {"switch": "on", "outlet": 1}
              ]
            }
        })

AND MY LIGHTS TURNED ON....

  1. with some playing I was able to dump the actual HTTP request that was being made, which simply looks like (This is not code that you can copy and paste from this comment to make it work, this is a dump of the request for you to look at, and to compile your own HTTP Request that looks like this - any decent developer should be able to make a HTTP request in their programming language of choice)
Send request:  {
  url: '/v2/device/thing/status',
  method: 'post',
  baseURL: 'https://eu-apia.coolkit.cc',
  headers: AxiosHeaders {
    Accept: 'application/json, text/plain, */*',
    'Content-Type': 'application/json',
    Authorization: 'Bearer aa0dbbf06cd1NOTMYREALKEY8e84f9a09ffe536d62',
    'X-CK-Nonce': '4s3p08wn',
    Date: '1692398015055'
  },
  params: undefined,
  data: '{"type":1,"id":"10007bc171","params":{"switches":[{"switch":"off","outlet":0},{"switch":"off","outlet":1}]}}'
}

So now I have a proof of concept working in Javascript, I can switch back to PHP and write real HTTP requests, that consume the OAuth Endpoint, which gives me a token to store, and then I can then just use any HTTP client (mine will continue to be PHP) to make http requests

Once you have an access token from OAuth you can call any of the APIs - here is a scaled down request, made by standard curl command

curl --location 'https://eu-apia.coolkit.cc/v2/device/thing/status' \
--header 'X-CK-Nonce: 9e3NOTREALwR7' \
--header 'Authorization: Bearer 90e4e9c7de5NOTMYREALTOKENd36154e3bbc2' \
--header 'Content-Type: application/json' \
--data '{
    "type": 1,
    "id": "10007bc171",
    "params": {
        "switches": [
                {"switch": "on", "outlet": 1}
              ]
    }
}'

The above all works in real life in my house today. Im not @coolkit-carl, Im a PHP dev with API experience :)

If you are looking for a non-technical project where you can just input your username and password to a config file, and magically control your devices, then you can no longer do that. But if you are willing to learn basic development (like OAuth which is pretty much industry standard for authenticating and authorising external services nowadays) then that can be "easily" done.

The old ewelink-api project should be considered deprecated and no longer used.
This work for me , but in short time I have this error; {"status":200,"responseTime":257,"error":401,"msg":"cannot found access token info","data":{}}

There are a procces to renew token and I used it, but only work for me in a short time after get token, then when I try to refesh token I get this:
{
status: 200,
responseTime: 300,
error: 405,
msg: "can't find the account with this rt!",
data: {}
}
any ideas?

from ewelink-api.

 avatar commented on June 21, 2024

Explanation on rt invalidation: If you use the same APPID, account, request login, refresh token, reset password, or other interfaces or behaviors, it will return a new at, rt, and cause the previous login credentials to become invalid.

from ewelink-api.

apadilla83 avatar apadilla83 commented on June 21, 2024

Explanation on rt invalidation: If you use the same APPID, account, request login, refresh token, reset password, or other interfaces or behaviors, it will return a new at, rt, and cause the previous login credentials to become invalid.

Then , what can I do to refresh token when the token are expired or before expired? Because in short time i received this:
{"status":200,"responseTime":257,"error":401,"msg":"cannot found access token info","data":{}}
Thanks

from ewelink-api.

 avatar commented on June 21, 2024

Explanation on rt invalidation: If you use the same APPID, account, request login, refresh token, reset password, or other interfaces or behaviors, it will return a new at, rt, and cause the previous login credentials to become invalid.

Then , what can I do to refresh token when the token are expired or before expired? Because in short time i received this: {"status":200,"responseTime":257,"error":401,"msg":"cannot found access token info","data":{}} Thanks

  1. You can tell me your account and I will check your login records for you. 2. When you receive this message, you can request to refresh the token interface and use rt to obtain new at and rt. If rt also fails, it proves that you have indeed reset it elsewhere.

from ewelink-api.

apadilla83 avatar apadilla83 commented on June 21, 2024

Explanation on rt invalidation: If you use the same APPID, account, request login, refresh token, reset password, or other interfaces or behaviors, it will return a new at, rt, and cause the previous login credentials to become invalid.

Then , what can I do to refresh token when the token are expired or before expired? Because in short time i received this: {"status":200,"responseTime":257,"error":401,"msg":"cannot found access token info","data":{}} Thanks

Then , what can I do to refresh token when the token are expired or before expired? Because in short time i received this: {"status":200,"responseTime":257,"error":401,"msg":"cannot found access token info","data":{}} Thanks

  1. You can tell me your account and I will check your login records for you. 2. When you receive this message, you can request to refresh the token interface and use rt to obtain new at and rt. If rt also fails, it proves that you have indeed reset it elsewhere.
    <
    Ok this is the case, Mi application login with oauth demo, I login manually and obtain the token. then all work correcty on mi application, after some time I received this mensage when the application try to control some device: :

{"status":200,"responseTime":257,"error":401,"msg":"cannot found access token info","data":{}}

I call the function refreshToken like that:
console.log('Token expired, refreshing token')
const refreshStatus = await client.user.refreshToken({
rt: LoggedInfo.data?.refreshToken,
})

And I get always the same error

{
status: 200,
responseTime: 380,
error: 405,
msg: "can't find the account with this rt!",
data: {}
}

then when you say that I have to reset it , is that I have to login again? Because this happend after short time..

Thanks!

from ewelink-api.

apadilla83 avatar apadilla83 commented on June 21, 2024

Ok this is the case, Mi application login with oauth demo, I login manually and obtain the token. then all work correcty on mi application, after some time I received this mensage when the application try to control some device: :

{"status":200,"responseTime":257,"error":401,"msg":"cannot found access token info","data":{}}

I call the function refreshToken like that:
console.log('Token expired, refreshing token')
const refreshStatus = await client.user.refreshToken({
rt: LoggedInfo.data?.refreshToken,
})

And I get always the same error

{
status: 200,
responseTime: 380,
error: 405,
msg: "can't find the account with this rt!",
data: {}
}

then when you say that I have to reset it , is that I have to login again? Because this happend after short time..

Thanks!

from ewelink-api.

 avatar commented on June 21, 2024

It looks like it has been reset. You need to log in again. It is recommended to check the code to see if there are any other places that will refresh this token, as each refresh will reset at and rt.

from ewelink-api.

apadilla83 avatar apadilla83 commented on June 21, 2024

Hi this is the code...

import { client } from '../../config.js'
import {refreshToken} from './refresh.token.js';

import * as fs from 'fs'

export async function SonoffChangeState (ctx) {
if (!fs.existsSync('./token.json')) {
throw new Error('token.json not found, please run login.js first')
}

  // get token
  let LoggedInfo = JSON.parse(fs.readFileSync('./token.json', 'utf-8'))
  // console.info(LoggedInfo)
  client.at = LoggedInfo.data?.accessToken
  client.region = LoggedInfo?.region || 'eu'
  client.setUrl(LoggedInfo?.region || 'eu')
  // Check if the token has expired, and refresh the token if it has expired
  if (
    LoggedInfo.data?.atExpiredTime < Date.now() &&
    LoggedInfo.data?.rtExpiredTime > Date.now()
  ) {
    console.log('Token expired, refreshing token')
    const refreshStatus = await client.user.refreshToken({
      rt: LoggedInfo.data?.refreshToken,
    })
    console.log(refreshStatus)
    if (refreshStatus.error === 0) {
      // You can also use built-in storage
      // client.storage.set('token', {...})
      fs.writeFileSync(
        './token.json',
        JSON.stringify({
          status: 200,
          responseTime: 0,
          error: 0,
          msg: '',
          data: {
            accessToken: refreshStatus?.data?.at,
            atExpiredTime: Date.now() + 2592000000,
            refreshToken: refreshStatus?.data?.rt,
            rtExpiredTime: Date.now() + 5184000000,
          },
          region: client.region,
        })
      )
      LoggedInfo = JSON.parse(fs.readFileSync('./token.json', 'utf-8'))
    }
  }

  if (LoggedInfo.data?.rtExpiredTime < Date.now()) {
    console.log('Failed to refresh token, need to log in again to obtain token')
    return
  }

const body = ctx.request.body
const deviceId = body.deviceId;
const channel = body.channel;
const channels= body.channels;
const state = body.state;
if(deviceId !=undefined && state !=undefined  && channel!=undefined && channels==undefined ){
let nchannels=parseFloat(channel)
let nchannel=--nchannels
console.log(`se va a cambiar el estado del dispositivo ${deviceId}  a ${state} canal ${nchannel} `)

try {
    let status = await client.device.setThingStatus({
      type: 1,
      id: deviceId,
      params: {
        switches: [
           { switch: state, outlet: nchannel },
         
        ],
      },
      //params: {
      //  switch: state, // Specific control instructions: https://coolkit-technologies.github.io/eWeLink-API/#/en/UIIDProtocol

      //},
      
    })
    console.log(status)
    if(status.error==401 || status.error==4002){
      refreshToken();
    }
    //res.send({DeviceStateChangueTo: status});
    ctx.body =status;

}catch(error){
    console.log(error)
   // res.send({DeviceStateChangueError: error});
   //ctx.body({status: error});
   ctx.body =error;
   //ctx.body(error);

  }     
}else{
  console.log(`se va a cambiar el estado del dispositivo de doble canal ${deviceId}  a ${state} canal ${channel} `)
  let nchannel=parseFloat(channel)
  try {
      let status = await client.device.setThingStatus({
        type: 1,
        id: deviceId,
        params: {
          switches: [
             { switch: state, outlet: nchannel },
           
          ],
        },
      })
      console.log(status)
      //res.send({DeviceStateChangueTo: status});
      ctx.body =status;
  }catch(error){
      console.log(error)
     // res.send({DeviceStateChangueError: error});
     //ctx.body({status: error});
     ctx.body =error;
     //ctx.body(error);

    }      
}

}

from ewelink-api.

apadilla83 avatar apadilla83 commented on June 21, 2024

HI, I think that is not error on my application, I have another application that connect to websocket with the same APP_ID AND APP_SECRET with the old api ewelink-api. ¿may be? I need to created another app en https://dev.ewelink.cc/ , but there is not possible..

from ewelink-api.

 avatar commented on June 21, 2024

HI, I think that is not error on my application, I have another application that connect to websocket with the same APP_ID AND APP_SECRET with the old api ewelink-api. ¿may be? I need to created another app en https://dev.ewelink.cc/ , but there is not possible..

It is recommended to share a token or split the devices into two accounts and share them with another account.

from ewelink-api.

apadilla83 avatar apadilla83 commented on June 21, 2024

HI, I think that is not error on my application, I have another application that connect to websocket with the same APP_ID AND APP_SECRET with the old api ewelink-api. ¿may be? I need to created another app en https://dev.ewelink.cc/ , but there is not possible..

It is recommended to share a token or split the devices into two accounts and share them with another account.

Yes, i will do it thanks

from ewelink-api.

baugp avatar baugp commented on June 21, 2024

I managed to patch this repo in my fork. It works on my Sonoff S31 plug, but I haven't tested on other devices. I only spent a few hours as I needed to get it to work asap. Therefore, I haven't patched every function, don't expect it to work well on other devices. The changes between v1 and v2 API are minimal.
I only patched these:

  • login
  • getDevice
  • getDevices
  • getDevicePowerState
  • setDevicePowerState
  • getDevicePowerUsage

If you look at the diff, it's not that much. I belive this project can be patched to migrate to v2 API entirely with minimal effort.
baugp@2f4d1b0

from ewelink-api.

majeka avatar majeka commented on June 21, 2024

I managed to patch this repo in my fork. It works on my Sonoff S31 plug, but I haven't tested on other devices. I only spent a few hours as I needed to get it to work asap. Therefore, I haven't patched every function, don't expect it to work well on other devices. The changes between v1 and v2 API are minimal. I only patched these:

* login

* getDevice

* getDevices

* getDevicePowerState

* setDevicePowerState

* getDevicePowerUsage

If you look at the diff, it's not that much. I belive this project can be patched to migrate to v2 API entirely with minimal effort. baugp@2f4d1b0

Hello!
Can you tell me how you made the transition from v1 to v2?
It is possible to give example code, etc.
Do I understand correctly that changes were made to node-red-contrib-ewelink?
or did they transfer everything to HTTP requests?

I managed to get the token, I would like to continue using node-red-contrib-ewelink

from ewelink-api.

Related Issues (20)

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.