lucien2k / sonoff-python Goto Github PK
View Code? Open in Web Editor NEWMake use of your sonoff smart switches without flashing them via the cloud APIs
License: MIT License
Make use of your sonoff smart switches without flashing them via the cloud APIs
License: MIT License
First off, let's start off with displaying my code:
import sonoff
username = "usrname"
password = "pass"
api_region = "region"
s = sonoff.Sonoff(username, password, api_region)
devices = s.get_devices()
print(devices)
if devices:
# We found a device, lets turn something on
device_id = devices[0]['device id']
s.switch('on', device_id, None)
This code was copied straight from the example, and modified to drop config
, since it was making trouble on my end.
After running this, I get quite the abnormal error from the code.
Exception has occurred: KeyError
'at'
After delving into the source of this library, I found the exact line from where the exception originates.
Line 123: self._bearer_token = resp['at']
I have absolutely no idea how to fix this, as I am not willing to make modifications to a library I don't understand, unless guided by someone who does.
If anyone can lend a hand with this, you'd have my sincere gratitude.
I'm logging in properly, then when I try to get list of devices I'm getting error in response
('response :', {u'msg': u'params incomplete', u'error': 400})
Response code: 200
Tried with 2 accounts, one has 2 devices (POW R2 and 4CH), the other has just one shared from the first one (POW R2).
If it makes any difference, both were created from Android app, not iPhone.
on Python 3.6
I have installed the library: pip install sonoff-python
and requirements websocket,requests, websocket-client
running the example "Usage"
i get below error:
File "S:\Development\Python_Scripts\teste_nevalidate\sonofflan_test-1.py", line 4, in
s = sonoff.Sonoff(config.username, config.password, config.api_region, config.user_apikey, config.bearer_token)
AttributeError: module 'config' has no attribute 'username'
Do I missed something?
Dan
As eWeLink will stop provide the support and maintance of current APPID & APP secret on Aug 31th 2020.
That means that this project may work improperly.
eWeLink will offer a special APPID and APP secret for this project.
@lucien2k Please contact me via the mail
To: [email protected]
and cc: [email protected]
Daniel
I managed to correctly log in, but the list of devices is empty.
This is what I'm doing:
import sonoff
s = sonoff.Sonoff("[email protected]", "mypassword", "eu")
devices = s.get_devices()
And I'm actively using the devices on the ewelink application and with google home.
Maybe something changed in the API?
ModuleNotFoundError: No module named 'requests
running python 3.7.3
Since yesterday I'm able to list devices but switching sockets end with error.
If I print output of wsresponse I'm getting this:
{"error":406,"sequence":"16043159535"}
Maybe it has something to do with the old appid and secret as mentioned on other issue ?
Hi, great initiative. WOuld be good to get it a little more robust. In running your suggested code after install using:
pip3 install sonoff-python
which is successful and then if I run the following test code:
import sonoff
import typing
class Config(typing.NamedTuple):
username: str
password: str
api_region: str
grace_period: int
config = Config('ba###@######le.com', 'S#######B', 'us', 600)
print(f"config = {config}")
s = sonoff.Sonoff(config.username, config.password, config.api_region)
devices = s.get_devices()
if devices:
# We found a device, lets turn something on
device_id = devices[0]['deviceid']
s.switch('on', device_id, 0),
I get the following error:
python3 test_sonoff.py
Traceback (most recent call last):
File "test_sonoff.py", line 3, in <module>
import sonoff
File "/usr/local/lib/python3.7/dist-packages/sonoff/__init__.py", line 3, in <module>
from sonoff import Sonoff
ImportError: cannot import name 'Sonoff' from 'sonoff' (/usr/local/lib/python3.7/dist-packages/sonoff/__init__.py)
I have tried uninstalling the package and linking directly tothe
sonoff.py file which partially works , (i.e. it can read the available devices and get their states) but I then get an error from websocket as per the following when the code tries to change the switch state:
Traceback (most recent call last):
File "test_sonoff.py", line 22, in <module>
s.switch('on', device_id, 0)
File "sonoff-python-0.1/sonoff/sonoff.py", line 215, in switch
self._ws = self._get_ws()
File "sonoff-python-0.1/sonoff/sonoff.py", line 180, in _get_ws
self._ws = create_connection(('wss://{}:8080/api/ws'.format(self._wshost)), timeout=10)
File "/usr/lib/python3.6/site-packages/websocket/_core.py", line 514, in create_connection
websock.connect(url, **options)
File "/usr/lib/python3.6/site-packages/websocket/_core.py", line 223, in connect
options.pop('socket', None))
File "/usr/lib/python3.6/site-packages/websocket/_http.py", line 120, in connect
sock = _open_socket(addrinfo_list, options.sockopt, options.timeout)
File "/usr/lib/python3.6/site-packages/websocket/_http.py", line 161, in _open_socket
sock = socket.socket(family, socktype, proto)
File "/usr/lib/python3.6/socket.py", line 144, in __init__
_socket.socket.__init__(self, family, type, proto, fileno)
OSError: [Errno 22] Invalid argument
Appreciate your help as this is a really useful tool/concept and if I can get it working will help me a lot!
Cheers
Barry
Hello,
maybe it would be possible to add an event driven handler to be able to trigger changes in device states. Currently I'm working on a GUI based on sonoff-python and I have to trigger an update manually or timer-based.
Also it would be nice, if the instantiation wouldn't block the execution - although I can resolve that with threads or subprocesses...
Overall, this library s a nice job, guys!
Best Regards
D.Sánchez
Hello, I am able to fetch the list of devices available in ewelink but unable to toggle their states. Any idea how to resolve this?
I can not get devices by get_devices, I am sure the username, password, and region are correct. And the code on my side is also the latest version. Thank you.
I can't run the code due to missing definitions on HTTP_MOVED_PERMANENTLY/HTTP_NOT_FOUND/HTTP_BAD_REQUEST/HTTP_UNAUTHORIZED....
I don't see them defined in the code, and I don't see any "from (%s) import *", so I really don't understand where those are supposed to be defined...
I can obviously define them myself (I assume they're just the status code numbers?)
What am I missing/doing wrong?
Hello,
I am having the following error when I call s.switch('on', device_id, 0)
:
Traceback (most recent call last):
File "/tmp/test.py", line 14, in <module>
s.switch('on', device_id, 0)
File "/usr/local/lib/python2.7/dist-packages/sonoff/sonoff.py", line 246, in switch
params = { 'switches' : device['params']['switches'] }
KeyError: 'switches'
Looking at the device object, I see:
u'params': {u'fwVersion': u'1.6.0',
u'rssi': -51,
u'staMac': u'68:C6:3A:A3:8B:B4',
u'startup': u'off',
u'switch': u'off'},
There is no 'switches' key in 'params'
Create work.
Had also to install:
Now i'm getting an error: AttributeError: Sonoff instance has no attribute 'get_api_region'
Since these 3 lines are not relevant I have removed them.
vanni@domon:~/src/sonoff/1/sonoff-python$ python3 ./prova.py
[{'createdAt': '2018-12-10T08:43:46.266Z', 'onlineTime': '2019-11-02T22:36:14.911Z', 'location': '', '__v': 0, 'apikey': '7f6ad353-5b15-424a-91a7-00e6b8ca9992
', 'sharedTo': [], 'type': '10', 'showBrand': True, 'group': '', 'ip': '46.234.201.3', 'productModel': 'Sonoff Pow', 'devConfig': {}, 'devicekey': '85468a4c-e
e1f-460e-aa10-a486fd0f473c', 'deviceUrl': '', 'deviceid': '10001bd399', 'params': {'uiActive': 60, 'fwVersion': '2.6.1', 'startup': 'stay', 'switch': 'off', '
rssi': -51, 'staMac': '60:01:94:5E:09:35', 'timers': [], 'init': 1, 'power': '0', 'timeZone': 1, 'controlType': '7', 'sledOnline': 'on'}, 'deviceStatus': '',
'brandName': 'Maker', 'settings': {'opsNotify': 0, 'opsHistory': 1, 'alarmNotify': 1}, 'extra': {'_id': '59e4513b5c1af3a660cd57b2', 'extra': {'apmac': 'd0:27:
00:37:a4:83', 'mac': 'd0:27:00:37:a4:82', 'manufacturer': '深圳创易智能系统有限公司', 'staMac': '60:01:94:5E:09:35', 'description': 'WWJG001093', 'model': 'PSC-B01-GL', '
brandId': '5611402280a0e2630f7b102d', 'ui': '功率检测单通道插座', 'uiid': 5, 'modelInfo': '578df9d0cc81455a5831eaea'}}, 'devGroups': [], 'groups': [], 'brandLogoUrl':
'', 'offlineTime': '2019-11-02T22:34:28.302Z', 'name': 'Presa 02', '_id': '5c0e2742ccb92c9f850a98ef', 'uiid': 5, 'online': True}]
Traceback (most recent call last):
File "./prova.py", line 10, in
s.switch('on', device_id, 0)
File "/home/vanni/src/sonoff/1/sonoff-python/sonoff/sonoff.py", line 268, in switch
params = { 'switches' : device['params']['switches'] }
KeyError: 'switches'
Any play to support sensors like current/power on the POW R2?
An empty list returns by method get_devices()
I found that response from server in method update_devices() return {"error":400,"msg":"params incomplete"}
Fix: #13
I was getting following error:
Traceback (most recent call last): File "./sonoff_test.py", line 12, in <module> s.switch('off', device_id, None) File "/opt/lib/python3.6/site-packages/sonoff/sonoff.py", line 255, in switch self._ws = self._get_ws() File "/opt/lib/python3.6/site-packages/sonoff/sonoff.py", line 219, in _get_ws self._ws = create_connection(('wss://{}:8080/api/ws'.format(self._wshost)), timeout=10) File "/opt/lib/python3.6/site-packages/websocket/_core.py", line 515, in create_connection websock.connect(url, **options) File "/opt/lib/python3.6/site-packages/websocket/_core.py", line 223, in connect options.pop('socket', None)) File "/opt/lib/python3.6/site-packages/websocket/_http.py", line 127, in connect sock = _ssl_socket(sock, options.sslopt, hostname) File "/opt/lib/python3.6/site-packages/websocket/_http.py", line 264, in _ssl_socket sock = _wrap_sni_socket(sock, sslopt, hostname, check_hostname) File "/opt/lib/python3.6/site-packages/websocket/_http.py", line 243, in _wrap_sni_socket server_hostname=hostname, File "/opt/lib/python2.7/ssl.py", line 363, in wrap_socket File "/opt/lib/python2.7/ssl.py", line 611, in __init__ File "/opt/lib/python2.7/ssl.py", line 840, in do_handshake ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] unknown error (_ssl.c:661)
I have fixed it by modifying _get_ws method.
instead of create_connection I use those 2 lines:
self._ws = websocket.WebSocket(sslopt={"cert_reqs": ssl.CERT_NONE}) self._ws.connect('wss://{}:8080/api/ws'.format(self._wshost)) #self._ws = create_connection(('wss://{}:8080/api/ws'.format(self._wshost)), timeout=10)
it requires also import ssl and import websocket
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.