diff --git a/pyShelly/utils.py b/pyShelly/utils.py index 3ff4d0b..0f4afe3 100644 --- a/pyShelly/utils.py +++ b/pyShelly/utils.py @@ -4,6 +4,7 @@ import base64 import traceback import json +import urllib from datetime import datetime from .compat import s @@ -79,3 +80,45 @@ def shelly_http_get(host, url, username, password, log_error=True): conn.close() return success, res + +def shelly_http_post(host, url, body, username, password, log_error=True): + """Send HTTP POST request""" + res = "" + success = False + conn = None + try: + LOGGER.debug("http://%s%s", host, url) + conn = httplib.HTTPConnection(host, timeout=5) + headers = {} + if username is not None \ + and password is not None: + combo = '%s:%s' % (username, password) + auth = s( + base64.b64encode(combo.encode())) # .replace('\n', '') + headers["Authorization"] = "Basic %s" % auth + conn.request("POST", url, urllib.parse.urlencode(body), headers) + resp = conn.getresponse() + + if resp.status == 200: + body = resp.read() + #LOGGER.debug("Body: %s", body) + res = json.loads(s(body)) + success = True + LOGGER.debug("http://%s%s - Ok", host, url) + else: + res = "Error, " + str(resp.status) \ + + ' ' + str(resp.reason) + LOGGER.warning(res) + except Exception as ex: + success = False + res = str(ex) + if log_error: + exception_log(ex, "Error http POST: http://{}{}", host, url) + else: + LOGGER.debug( + "Fail http POST: %s %s %s", host, url, ex) + finally: + if conn: + conn.close() + + return success, res