Ejemplo n.º 1
0
def setup(hass, base_config):
    """Set up of Tesla component."""
    from tesla_api import TeslaApiClient, AuthenticationError, ApiError

    config = base_config.get(DOMAIN)

    email = config.get(CONF_USERNAME)
    password = config.get(CONF_PASSWORD)
    scan_interval = config.get(CONF_SCAN_INTERVAL)

    api_client = TeslaApiClient(email, password)

    try:
        _LOGGER.info('Initializing Tesla data manager')
        vehicles = api_client.list_vehicles()
        data_manager = TeslaDataManager(hass, vehicles, scan_interval)

        hass.data[DOMAIN] = {DATA_MANAGER: data_manager}

        _LOGGER.info('Tesla data manager intialized')
        _LOGGER.debug('Connected to the Tesla API, found {} vehicles.'.format(
            len(vehicles)))
    except AuthenticationError as ex:
        _LOGGER.error(ex.message)
        return False
    except ApiError as ex:
        _LOGGER.error(ex.message)
        return False

    for platform in TESLA_PLATFORMS:
        discovery.load_platform(hass, platform, DOMAIN, None, base_config)

    return True
Ejemplo n.º 2
0
def setup(hass, base_config):
    """Set up of Tesla component."""
    from tesla_api import TeslaApiClient, AuthenticationError, ApiError

    config = base_config.get(DOMAIN)

    email = config.get(CONF_USERNAME)
    password = config.get(CONF_PASSWORD)
    scan_interval = config.get(CONF_SCAN_INTERVAL)

    api_client = TeslaApiClient(email, password)

    try:
        _LOGGER.info('Initializing Tesla data manager')
        vehicles = api_client.list_vehicles()
        data_manager = TeslaDataManager(hass, vehicles, scan_interval)

        hass.data[DOMAIN] = {DATA_MANAGER: data_manager}

        _LOGGER.info('Tesla data manager intialized')
        _LOGGER.debug('Connected to the Tesla API, found %d vehicles.',
                      len(vehicles))
    except AuthenticationError as ex:
        _LOGGER.error(ex.message)
        return False
    except ApiError as ex:
        _LOGGER.error(ex.message)
        return False

    def execute_controls_service(call):
        vin = call.data.get(ATTR_VIN)
        vehicle = data_manager.get_vehicle(vin)

        if not vehicle:
            _LOGGER.error('No vehicle found with VIN %s', vin)
            return

        func = getattr(vehicle.controls, call.service)

        vehicle.wake_up()
        func()

    for service in CONTROLS_SERVICES:
        hass.services.register(DOMAIN,
                               service,
                               execute_controls_service,
                               schema=SERVICE_SCHEMA)

    for platform in TESLA_PLATFORMS:
        discovery.load_platform(hass, platform, DOMAIN, None, base_config)

    return True
Ejemplo n.º 3
0
def login():
    """After login, choose vehicle and access duration."""
    email = password = token = error_msg = csrf = None

    if request.form['token']:
        token = _get_token(refresh_token=request.form['token'])
    elif request.form['email'] and request.form['password']:
        email = request.form['email']
        password = request.form['password']
    else:
        abort(400)

    if RECAPTCHA_SITE_KEY:
        try:
            response = request.form[RECAPTCHA_RESPONSE_PARAM]
        except ValueError:
            abort(400)
        if verify_recaptcha(response, RECAPTCHA_SITE_SECRET):
            LOG.info('reCAPTCHA success')
        else:
            LOG.warning('reCAPTCHA failure')
            error_msg = 'reCAPTCHA failure'

    client = TeslaApiClient(email, password, token)
    vehicles = token = None
    if error_msg is None:
        try:
            vehicles = client.list_vehicles()
            token = client.token['refresh_token']
            csrf = make_csrf_token(token, SECRET_KEY)
        except AuthenticationError:
            error_msg = 'Authentication failure'

    return render_template("login.html",
                           title=TITLE,
                           vehicles=vehicles,
                           token=token,
                           csrf=csrf,
                           max_access_duration=MAX_ACCESS_DURATION,
                           error_msg=error_msg)
Ejemplo n.º 4
0
from tesla_api import TeslaApiClient
import requests
import time
import json

previouslyActive = True
while True:
    try:
        client = TeslaApiClient('*****@*****.**', 'yourteslapassword')
        vehicles = client.list_vehicles()
        v = vehicles[0]
        state = v.state
        if (state == 'asleep'):
            print("Asleep. Waiting for 5 minutes...")
            previouslyActive = False
            time.sleep(5 * 60)
        else:
            print("getting data...")
            drive_state = v.get_drive_state()
            charge = v.charge.get_state()
            #print(charge)
            print(drive_state)
            speed = drive_state['speed']
            shift_state = drive_state['shift_state']
            if (speed == None):
                speed = 0.0
            else:
                speed = float(speed) * 1.60934  # convert to km/h
            payload = {}
            payload.update(timestamp=int(round(time.time() * 1000)))
            location = {}
Ejemplo n.º 5
0
    def run(self):
        # Setup Tesla API client
        tclient = TeslaApiClient(self.email, self.password)
        vehicles = tclient.list_vehicles()
        # Currently, only one vehicle is supported. It would be nice to be
        # able to click through multipe vehicles.
        thisvehicle = vehicles[0]
        display_name = thisvehicle.display_name

        # If vehicle is offline, do not bother grabbing info
        if thisvehicle.state != 'online':
            self.output = {
                "full_text": "%s: %s" % (display_name, thisvehicle.state),
                "color": self.offline_color
            }
        else:
            charge_info = vehicles[0].charge.get_state()

            # Miles or meters?
            if self.units != "miles":
                battery_range = charge_info[
                    'battery_range'] * self.conversion_factor
                charge_rate = charge_info[
                    'charge_rate'] * self.conversion_factor
            else:
                battery_range = charge_info['battery_range']
                charge_rate = charge_info['charge_rate']

            # Set colors for charging status
            if charge_info['charging_state'] == 'Charging':
                color = self.charging
                charge_state_icon = self.charging_icon
            else:
                color = self.charge_complete
                charge_state_icon = self.disconnect_icon

            cdict = {
                "name":
                display_name,
                "charge_state_icon":
                charge_state_icon,
                "battery_level":
                charge_info['battery_level'],
                "battery_range":
                "%s %s" % (battery_range, self.units),
                "battery_heater_on":
                charge_info['battery_heater_on'],
                "charge_current_request":
                charge_info['charge_current_request'],
                "charge_current_request_max":
                charge_info['charge_current_request_max'],
                "charge_enable_request":
                charge_info['charge_enable_request'],
                "charge_energy_added":
                charge_info['charge_energy_added'],
                "charge_limit_soc":
                charge_info['charge_limit_soc'],
                "charge_limit_soc_max":
                charge_info['charge_limit_soc_max'],
                "charge_limit_soc_min":
                charge_info['charge_limit_soc_min'],
                "charge_limit_soc_std":
                charge_info['charge_limit_soc_std'],
                "charge_miles_added_ideal":
                charge_info['charge_miles_added_ideal'],
                "charge_miles_added_rated":
                charge_info['charge_miles_added_rated'],
                "charge_port_cold_weather_mode":
                charge_info['charge_port_cold_weather_mode'],
                "charge_port_door_open":
                charge_info['charge_port_door_open'],
                "charge_port_latch":
                charge_info['charge_port_latch'],
                "charge_rate":
                "%s%s/hr" % (charge_rate, self.units),
                "charge_to_max_range":
                charge_info['charge_to_max_range'],
                "charger_actual_current":
                charge_info['charger_actual_current'],
                "charger_phases":
                charge_info['charger_phases'],
                "charger_pilot_current":
                charge_info['charger_pilot_current'],
                "charger_power":
                charge_info['charger_power'],
                "charger_voltage":
                charge_info['charger_voltage'],
                "charging_state":
                charge_info['charging_state'],
                "conn_charge_cable":
                charge_info['conn_charge_cable'],
                "est_battery_range":
                charge_info['est_battery_range'],
                "fast_charger_brand":
                charge_info['fast_charger_brand'],
                "fast_charger_present":
                charge_info['fast_charger_present'],
                "fast_charger_type":
                charge_info['fast_charger_type'],
                "ideal_battery_range":
                charge_info['ideal_battery_range'],
                "managed_charging_active":
                charge_info['managed_charging_active'],
                "managed_charging_start_time":
                charge_info['managed_charging_start_time'],
                "managed_charging_user_canceled":
                charge_info['managed_charging_user_canceled'],
                "max_range_charge_counter":
                charge_info['max_range_charge_counter'],
                "minutes_to_full_charge":
                charge_info['minutes_to_full_charge'],
                "not_enough_power_to_heat":
                charge_info['not_enough_power_to_heat'],
                "scheduled_charging_pending":
                charge_info['scheduled_charging_pending'],
                "scheduled_charging_start_time":
                charge_info['scheduled_charging_start_time'],
                "time_to_full_charge":
                charge_info['time_to_full_charge'],
                "timestamp":
                charge_info['timestamp'],
                "trip_charging":
                charge_info['trip_charging'],
                "usable_battery_level":
                charge_info['usable_battery_level'],
                "user_charge_enable_request":
                charge_info['user_charge_enable_request']
            }

            if charge_info['charging_state'] == 'Charging':
                self.output = {
                    "full_text": self.format_with_charge.format(**cdict),
                    "color": color
                }
            else:
                self.output = {
                    "full_text": self.format_without_charge.format(**cdict),
                    "color": color
                }
Ejemplo n.º 6
0
        # commit the changes to the database
        conn.commit()
        # close communication with the database
        cur.close()
    except (Exception, psycopg2.DatabaseError) as error:
        print(error)
    finally:
        if conn is not None:
            conn.close()


if __name__ == "__main__":
    client = TeslaApiClient(os.getenv("TESLA_EMAIL"), os.getenv("TESLA_PASSWORD"))

    # There is just one car...
    oto = client.list_vehicles()[0]
    print("Optimize charging for: " + oto.display_name)

    oto.wake_up()
    inc = 0
    charge_state = {}
    while inc < 22:
        try:
            charge_state = oto.charge.get_state()
            break
        except ApiError as e:
            inc += 1
            print(str(e))
            time.sleep(1)

    # Summer saving