Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple library/command-line-utility to control a EDIMAX Smart Plug Switch (SP-1101W) from Python
##
# The MIT License (MIT)
#
# Copyright (c) 2014 Stefan Wendler
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
##
__author__ = 'Stefan Wendler, sw@kaltpost.de'
import requests as req
import optparse as par
import logging as log
from xml.dom.minidom import getDOMImplementation
from xml.dom.minidom import parseString
class SmartPlug(object):
"""
Simple class to access a "EDIMAX Smart Plug Switch SP-1101W"
Usage example when used as library:
p = SmartPlug("172.16.100.75", ('admin', '1234'))
p.state = "OFF"
p.state = "ON"
print(p.state)
Usage example when used as command line utility:
turn plug on:
python smartplug.py -H 172.16.100.75 -l admin -p 1234 -s ON
turn plug off:
python smartplug.py -H 172.16.100.75-l admin -p 1234 -s OFF
get plug state:
python smartplug.py -H 172.16.100.75-l admin -p 1234 -g
"""
def __init__(self, host, auth):
"""
Create a new SmartPlug instance identified by the given URL.
:rtype : object
:param host: The IP/hostname of the SmartPlug. E.g. '172.16.100.75'
:param auth: User and password to authenticate with the plug. E.g. ('admin', '1234')
"""
self.url = "http://%s:10000/smartplug.cgi" % host
self.auth = auth
self.domi = getDOMImplementation()
def __xml_cmd(self, cmdId, cmdStr):
"""
Create XML representation of a command.
:param cmdId: Use 'get' to request plug state, use 'setup' change plug state.
:param cmdStr: Empty string for 'get', 'ON' or 'OFF' for 'setup'
:return: XML representation of command
"""
doc = self.domi.createDocument(None, "SMARTPLUG", None)
doc.documentElement.setAttribute("id", "edimax")
cmd = doc.createElement("CMD")
cmd.setAttribute("id", cmdId)
state = doc.createElement("Device.System.Power.State")
cmd.appendChild(state)
state.appendChild(doc.createTextNode(cmdStr))
doc.documentElement.appendChild(cmd)
return doc.toxml()
def __post_xml(self, xml):
"""
Post XML command as multipart file to SmartPlug, parse XML response.
:param xml: XML representation of command (as generated by __xml_cmd)
:return: 'OK' on success, 'FAILED' otherwise
"""
files = {'file': xml}
res = req.post(self.url, auth=self.auth, files=files)
if res.status_code == req.codes.ok:
dom = parseString(res.text)
try:
val = dom.getElementsByTagName("CMD")[0].firstChild.nodeValue
if val is None:
val = dom.getElementsByTagName("CMD")[0].getElementsByTagName("Device.System.Power.State")[0].\
firstChild.nodeValue
return val
except Exception as e:
print(e.__str__())
return None
@property
def state(self):
"""
Get the current state of the SmartPlug.
:return: 'ON' or 'OFF'
"""
res = self.__post_xml(self.__xml_cmd("get", ""))
if res != "ON" and res != "OFF":
raise Exception("Failed to communicate with SmartPlug")
return res
@state.setter
def state(self, value):
"""
Set the state of the SmartPlug
:param value: 'ON', 'on', 'OFF' or 'off'
"""
if value == "ON" or value == "on":
res = self.__post_xml(self.__xml_cmd("setup", "ON"))
else:
res = self.__post_xml(self.__xml_cmd("setup", "OFF"))
if res != "OK":
raise Exception("Failed to communicate with SmartPlug")
if __name__ == "__main__":
# this turns on debugging from requests library
log.basicConfig(level=log.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
usage = "%prog [options]"
parser = par.OptionParser(usage)
parser.add_option("-H", "--host", default="172.16.100.75", help="Base URL of the SmartPlug")
parser.add_option("-l", "--login", default="admin", help="Login user to authenticate with SmartPlug")
parser.add_option("-p", "--password", default="1234", help="Password to authenticate with SmartPlug")
parser.add_option("-g", "--get", action="store_true", help="Get state of plug")
parser.add_option("-s", "--set", help="Set state of plug: ON or OFF")
(options, args) = parser.parse_args()
try:
p = SmartPlug(options.host, (options.login, options.password))
if options.get:
print(p.state)
elif options.set:
p.state = options.set
except Exception as e:
print(e.__str__())
@wendlers

This comment has been minimized.

Copy link
Owner Author

commented Jun 19, 2014

Simple class to access a "EDIMAX Smart Plug Switch SP-1101W"

For some more information on how the communication with the Smart Plug works, see this post on ELV.

Using as library

p = SmartPlug("http://172.16.100.75:10000/smartplug.cgi", ('admin', '1234'))

# turn plug off
p.state = "OFF"

# turn plug on
p.state = "ON"

# get plug state
print(p.state)

Using as command line utility

turn plug on:

python smartplug.py -u http://172.16.100.75:10000 -l admin -p 1234 -s ON

turn plug off:

python smartplug.py -u http://172.16.100.75:10000 -l admin -p 1234 -s OFF

get plug state:

python smartplug.py -u http://172.16.100.75:10000 -l admin -p 1234 -g
@2nd-quadrant

This comment has been minimized.

Copy link

commented Jun 23, 2014

Thanks very much developing this. I have been running around trying to work out an easy way to control multiple mains devices from my Pi ranging from direct connect via relay (dangerous), 433mhz radio (number of mains devices limited to the number of unique addresses on the wireless sockets, Lightwave (expensive), Belkin Wemo (nearly there) and then I found this. Perfect.

Bought two Edimax Smartplugs yesterday and they worked right out of the box with my iPhone. Fired up the Pi this evening and got one of them working via the command line straight away - no problem.

The problem is when I tried to use it as a library (and this is certainly my lack of Python skills rather than anything else) I get the error

File "netio_server.py", line 58, in
Mains01 = SmartPlug("192.168.123.9",('admin', '1234'))
NameError: name 'SmartPlug' is not defined

netio_server.py has

import smartplug
.
.
.
Mains01 = SmartPlug('192.168.123.9',('admin', '1234'))

Which I believe is as per the examples in the code.

I have not changed smartplug.py from the code posted here. It is in the same directory as netio_server.py and is the same code as worked from the command line.

Any help would be gratefully appreciated

Thanks

@rainjack

This comment has been minimized.

Copy link

commented Apr 18, 2015

Thanks for that, its working fine.
How can I setup the fix IP address for SmartPlug? I can't find it.

@alfem

This comment has been minimized.

Copy link

commented Oct 13, 2015

Great work!

Any clue about getting power consumption data?

@windbender

This comment has been minimized.

Copy link

commented Oct 31, 2015

Just fired up wireshark to watch the power consumption request:

request:

<?xml version="1.0" encoding="UTF8"?><SMARTPLUG id="edimax"><CMD id="get"><NOW_POWER><Device.System.Power.NowCurrent></Device.System.Power.NowCurrent><Device.System.Power.NowPower></Device.System.Power.NowPower></NOW_POWER></CMD></SMARTPLUG>

response:

<?xml version="1.0" encoding="UTF8"?><SMARTPLUG id="edimax"><CMD id="get"><NOW_POWER><Device.System.Power.NowCurrent>0.1539</Device.System.Power.NowCurrent><Device.System.Power.NowPower>9.72</Device.System.Power.NowPower></NOW_POWER></CMD></SMARTPLUG>

It doesn't specify the units there, but they would be Amps of current and Watts of power. Since I was watching the phone UI at the same time.

@arminwasicek

This comment has been minimized.

Copy link

commented May 16, 2016

Thanks, I've added support for power consumption in hellospencer/smartplug.py
Btw. this is a node module for the Edimax SmartPlug.

@christopherpaquin

This comment has been minimized.

Copy link

commented Feb 27, 2017

Question for you guys - I just picked up one of these plugs. Edimax support informs me that the device will not listen on port 10000 if it is configured/connected to home wifi. They have stated that it only listens on port 10000 before setup. Once setup only port 22 is listening. So am I missing something? Are you guys connecting it its default IP address via a wifi adapter? I'm trying to use homeassistant on raspberry pi 2

@Skysurfer-14

This comment has been minimized.

Copy link

commented Mar 29, 2017

Hi, I am trying to make it work, but I get this error message on my raspi:

$ python smartplug.py -u http://192.168.178.144:10000 -l admin -p 1234 -s ON
Usage: smartplug.py [options]

smartplug.py: error: no such option: -u

Any idea?

Ok, I've seen it option -u must be -H. But now there is an other error:

$ python smartplug.py -H 192.168.178.144 -l admin -p 1234 -s ON
2017-03-29 18:23:35,459 - DEBUG - Starting new HTTP connection (1): 192.168.178.144
2017-03-29 18:23:35,501 - DEBUG - http://192.168.178.144:10000 "POST /smartplug.cgi HTTP/1.1" 401 333
Failed to communicate with SmartPlug

I guess that the Firmware version 2.04 of the Edimax SP-1101W is the reason of the problem. The FW-Update tool from Edimax can't find my plug. And the older App EdiPlug did not work with the 2.04 Firmware anymore. With the App EdiLife my plug works.

@jonabert

This comment has been minimized.

Copy link

commented Apr 15, 2017

hi SkySurfer-14, did you solve your issue with Firmware version 2.04?

@robgru

This comment has been minimized.

Copy link

commented May 21, 2017

Hi, since the Update of Version 2.08 for the Edimax SP-2101W, I have the same problem like SkySurfer-14.
I hope someone knows what's wrong.

@baferon

This comment has been minimized.

Copy link

commented May 30, 2017

Hi,
I'm trying to control my Edimax SP 2101 (Firmware 2.08 according to Edi life) and I get this error:
Exception: Failed to communicate with SmartPlug
The IP adress, the login and password are right as well...
I used exactly the same code for my SP 1101 and it was working perfectly...
Do you have any idea?
Thanks for your answer

@agent4788

This comment has been minimized.

Copy link

commented Jun 3, 2017

I have the same problem. The new firmware has a completely new interface.
Currently I can switch with the new firmware and my java api (https://gist.github.com/agent4788/6447f030b32c182550476dda068453cf) only the socket on / off. But the password must be 123456789. The new authentication method is a challenge / response procedure, the task for it is however unknown, only fragments and the result.

@derbot

This comment has been minimized.

Copy link

commented Sep 6, 2017

Seems that since firmware 2.04 they switched from http basic auth to http digest auth.
This works for me: https://gist.github.com/derbot/15f444d679c672ae3edc03f4b5b3897b

@Tutti86

This comment has been minimized.

Copy link

commented Dec 8, 2017

Läuft es bei euch mit der aktuellen Version?
Wenn ich das Script per curl aufrufe, muss ich den Befehl auf die neue auth-Methode anpassen?
Aktueller Status:
python smartplug.py -H 192.168.43.228 -l admin -p 1234 -s ON
2017-12-07 17:28:32,729 - DEBUG - Starting new HTTP connection (1): 192.168.43.228
2017-12-07 17:28:32,764 - DEBUG - http://192.168.43.228:10000 "POST /smartplug.cgi HTTP/1.1" 401 333
2017-12-07 17:28:32,799 - DEBUG - http://192.168.43.228:10000 "POST /smartplug.cgi HTTP/1.1" 401 333
Failed to communicate with SmartPlug

@Max-Down

This comment has been minimized.

Copy link

commented Dec 10, 2017

Ich habe mir die Edimax SP-1101W gekauft mit der Hoffnung, endlich eine Steckdose zu haben, die ich mit dem PI schalten kann. Jetzt merke ich erst, dass dies doch nicht funktioniert. Zumindest nicht mit dem obigen Script und schon gar nicht mit der aktuellen Firmware 3.0.1.
Ich bekomme den gleichen Fehler wie Tutti86 angezeigt. Hat denn niemand eine Idee, wie sich die Steckdose vom RaspberryPI schalten lässt?

@mwittig

This comment has been minimized.

Copy link

commented Dec 16, 2017

Mit den aktuellen Firmwares (Stichwort: EdiSmart / Alexa Integration) gibt es Probleme. Ich vermute mal, dass nun zusätzlich TLS Verschlüsselung erforderlich ist. Demnächst mehr.

mwittig/edimax-smartplug#8

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.