Skip to content

Instantly share code, notes, and snippets.

@wendlers
Last active October 16, 2023 21:41
Show Gist options
  • Star 21 You must be signed in to star a gist
  • Fork 10 You must be signed in to fork a gist
  • Save wendlers/a5fc0bf06bbe656c7291 to your computer and use it in GitHub Desktop.
Save wendlers/a5fc0bf06bbe656c7291 to your computer and use it in GitHub Desktop.
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__())
@rainjack
Copy link

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

@alfem
Copy link

alfem commented Oct 13, 2015

Great work!

Any clue about getting power consumption data?

@windbender
Copy link

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
Copy link

arminwasicek 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
Copy link

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
Copy link

Skysurfer-14 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
Copy link

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

@robgru
Copy link

robgru 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
Copy link

baferon 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
Copy link

agent4788 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
Copy link

derbot 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
Copy link

Tutti86 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
Copy link

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
Copy link

mwittig 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

@marvi3
Copy link

marvi3 commented Jul 14, 2020

Leider geht das script nicht mehr :(

@marvi3
Copy link

marvi3 commented Jul 14, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment