<gh_stars>0
import requests
import json

try:
    from http.client import HTTPSConnection, HTTPException
except:
    from httplib import HTTPSConnection, HTTPException

class NoOpLogger:
    def write(self, str):
        pass
    def debug(self, str):
        pass

# Session class for connecting to the local powerwall gateway.
class LocalSession:
    def __init__(self, host, log):
        if host.startswith('https://'):
            self._host = host
        elif host.startswith('http://'):
            # Force https
            self._host = 'https://' + host[7:]
        else:
            self._host = 'https://' + host

        if log == None:
            log = NoOpLogger()

        self._log = log
        self._is_open = False

        # Disable SSL verification warnings.
        requests.packages.urllib3.disable_warnings()

    def open(self):
        self._session = requests.Session()

        self._is_open = True

    def close(self):
        if self._is_open:
            self._session.close()
            self._session = None

            self._is_open = False

    def request(self, path, post_data = None):
        """
        Send a request for the path 'path'. Does a POST of post_data if given,
        else a GET of the given path.
        """

        if not self._is_open:
            self.open()

        headers = {
            'Content-Type': 'application/json; charset=utf-8'
        }

        if type(post_data) == dict:
            post = json.dumps(post_data)
        else:
            post = post_data

        if post:
            response = self._session.post(self._host + path, headers = headers,
                                          data = post, verify = False)
        else:
            response = self._session.get(self._host + path, headers = headers,
                                         verify = False)

        if response.status_code != 200:
            self._log.write("{} request failed: {}: {}" \
                            .format(path, response.status_code,
                                    response.reason))

            raise HTTPException(response.status_code, response.reason)

        return response

    def read_json(self, path, post_data = None):
        return self.request(path, post_data).json()

class Powerwall:
    def __init__(self, host, log = None):
        self._host = host

        if log == None:
            log = NoOpLogger()

        self._log = log

        self.session = LocalSession(host, log)

    def login(self, password, email = ""):
        return self.session.read_json('/api/login/Basic', {
            "username": "customer",
            "email": email,
            "password": password,
            "force_sm_off": False
            })

    def aggregates(self):
        return self.session.read_json('/api/meters/aggregates')

    def site(self):
        return self.session.read_json('/api/meters/site')

    def solar(self):
        return self.session.read_json('/api/meters/solar')

    # State of Charge / State of Energy
    def soe(self):
        return self.session.read_json('/api/system_status/soe')

    def sitemaster(self):
        return self.session.read_json('/api/sitemaster')

    def powerwalls(self):
        return self.session.read_json('/api/powerwalls')

    def registration(self):
        return self.session.read_json('/api/customer/registration')

    def grid_status(self):
        return self.session.read_json('/api/system_status/grid_status')

    # Not working? 403 Forbidden
    #def update_status(self):
    #    return self.session.read_json('/api/system/update/status')

    def site_info(self):
        return self.session.read_json('/api/site_info')

    def site_name(self):
        return self.session.read_json('/api/site_info/site_name')

    def status(self):
        return self.session.read_json('/api/status')

    def grid_faults(self):
        return self.session.read_json('/api/system_status/grid_faults')

    def stop(self):
        return self.session.read_json('/api/sitemaster/stop')

    def run(self):
        return self.session.read_json('/api/sitemaster/run')

    def completed(self):
        return self.session.read_json('/api/config/completed')

import requests
import json

try:
    from http.client import HTTPSConnection, HTTPException
except:
    from httplib import HTTPSConnection, HTTPException

class NoOpLogger:
    def write(self, str):
        pass
    def debug(self, str):
        pass

# Session class for connecting to the local powerwall gateway.
class LocalSession:
    def __init__(self, host, log):
        if host.startswith('https://'):
            self._host = host
        elif host.startswith('http://'):
            # Force https
            self._host = 'https://' + host[7:]
        else:
            self._host = 'https://' + host

        if log == None:
            log = NoOpLogger()

        self._log = log
        self._is_open = False

        # Disable SSL verification warnings.
        requests.packages.urllib3.disable_warnings()

    def open(self):
        self._session = requests.Session()

        self._is_open = True

    def close(self):
        if self._is_open:
            self._session.close()
            self._session = None

            self._is_open = False

    def request(self, path, post_data = None):
        """
        Send a request for the path 'path'. Does a POST of post_data if given,
        else a GET of the given path.
        """

        if not self._is_open:
            self.open()

        headers = {
            'Content-Type': 'application/json; charset=utf-8'
        }

        if type(post_data) == dict:
            post = json.dumps(post_data)
        else:
            post = post_data

        if post:
            response = self._session.post(self._host + path, headers = headers,
                                          data = post, verify = False)
        else:
            response = self._session.get(self._host + path, headers = headers,
                                         verify = False)

        if response.status_code != 200:
            self._log.write("{} request failed: {}: {}" \
                            .format(path, response.status_code,
                                    response.reason))

            raise HTTPException(response.status_code, response.reason)

        return response

    def read_json(self, path, post_data = None):
        return self.request(path, post_data).json()

class Powerwall:
    def __init__(self, host, log = None):
        self._host = host

        if log == None:
            log = NoOpLogger()

        self._log = log

        self.session = LocalSession(host, log)

    def login(self, password, email = ""):
        return self.session.read_json('/api/login/Basic', {
            "username": "customer",
            "email": email,
            "password": password,
            "force_sm_off": False
            })

    def aggregates(self):
        return self.session.read_json('/api/meters/aggregates')

    def site(self):
        return self.session.read_json('/api/meters/site')

    def solar(self):
        return self.session.read_json('/api/meters/solar')

    # State of Charge / State of Energy
    def soe(self):
        return self.session.read_json('/api/system_status/soe')

    def sitemaster(self):
        return self.session.read_json('/api/sitemaster')

    def powerwalls(self):
        return self.session.read_json('/api/powerwalls')

    def registration(self):
        return self.session.read_json('/api/customer/registration')

    def grid_status(self):
        return self.session.read_json('/api/system_status/grid_status')

    # Not working? 403 Forbidden
    #def update_status(self):
    #    return self.session.read_json('/api/system/update/status')

    def site_info(self):
        return self.session.read_json('/api/site_info')

    def site_name(self):
        return self.session.read_json('/api/site_info/site_name')

    def status(self):
        return self.session.read_json('/api/status')

    def grid_faults(self):
        return self.session.read_json('/api/system_status/grid_faults')

    def stop(self):
        return self.session.read_json('/api/sitemaster/stop')

    def run(self):
        return self.session.read_json('/api/sitemaster/run')

    def completed(self):
        return self.session.read_json('/api/config/completed')
# Session class for connecting to the local powerwall gateway. # Force https # Disable SSL verification warnings. Send a request for the path 'path'. Does a POST of post_data if given,         else a GET of the given path. # State of Charge / State of Energy # Not working? 403 Forbidden #def update_status(self): #    return self.session.read_json('/api/system/update/status')