def connect(self, given_password): # type: (Optional[str]) -> None if not given_password: creds = Credentials(self.account_key, self.username, None) try: stored_access_token = self.get_credentials(creds) except Exception as e: print(e) raise Exception("For user %s: Password not provided and not found in keyring" % self.username) self.connection = teslajson.Connection(email=self.username, access_token=stored_access_token) else: self.connection = teslajson.Connection(email=self.username, password=given_password)
def establish_connection(token=None): logT.debug("Connecting to Tesla") c = teslajson.Connection(email=TESLA_EMAIL, password=TESLA_PASSWORD, access_token=token) logT.debug(" connected. Token: %s", c.access_token) return c
def getVehicles(self): if not self.vehicles: indigo.server.log("Fetching vehicles...") connection = teslajson.Connection(self.pluginPrefs['username'], self.pluginPrefs['password']) self.vehicles = dict( (unicode(v['id']), v) for v in connection.vehicles) indigo.server.log("%i vehicles found" % len(self.vehicles)) return self.vehicles
def connect_to_tesla_api(username, password): output = None try: output = teslajson.Connection(username, password) except Exception as err: log("Could not connect to the Tesla API: {}".format(str(err)), level="WARNING") return output
def __init__(self, tesla_email, tesla_password): self.requests = ("charge_state", "climate_state", "drive_state", "gui_settings", "vehicle_state") self.priority_requests = {1: ("drive_state",), 2: ("drive_state",), 4: ("charge_state", "drive_state",)} self.old_values = dict([(r, {}) for r in self.requests]) self.connection = teslajson.Connection(tesla_email, tesla_password) self.vehicle = self.connection.vehicles[a_tesla_car_idx]
def __init__(self, name=None, device=None): App.__init__(self, name, device) device = self.get_device() self.connection = teslajson.Connection(device.username, device.get_password()) try: self.vehicle = self.connection.vehicles[0] except IndexError: logger.error('This account has no tesla vehicles')
def POST(self): web.header("Content-type", "application/json") reqStart = time.time() request = json.loads(web.data()) connection = teslajson.Connection(Credentials.TESLA_EMAIL, Credentials.TESLA_PASSWORD) tesla = connection.vehicles[0] speechReturn = "" try: # Try/catch around any request to Tesla, so we can send an appropriate response tesla.wake_up() intent = request["result"]["metadata"]["intentName"] param = request["result"]["parameters"]["carParam"] log.info("Received intent %s with params: %s" % (intent, request["result"]["parameters"])) if intent == "Query parameter": qp = queryParameter(tesla) speechReturn = qp.parse(param) elif intent == "Set generic parameter": if request["result"]["parameters"]["level"]: bp = setBooleanParameter(tesla) speechReturn = bp.parse( param, request["result"]["parameters"]["level"]) elif request["result"]["parameters"]["percentage"]: rp = setRangeParameter(tesla) speechReturn = rp.parse( param, request["result"]["parameters"]["percentage"]) elif request["result"]["parameters"]["temperature"] is not "": tp = setTemperatureParameter(tesla) speechReturn = tp.parse( param, request["result"]["parameters"]["temperature"]) else: speechReturn = "I'm sorry, I couldn't work out how to do %s" % ( request["result"]["metadata"]["intentName"]) except: log.error("Exception talking to Tesla servers", exc_info=True) speechReturn = "I'm sorry, there was a problem communicating with the Tesla servers" response = {} response["speech"] = speechReturn response["displayText"] = speechReturn response["source"] = "Wattson" # TODO: Swap with actual name log.debug("Response processed in %s seconds" % (time.time() - reqStart)) return json.dumps(response)
def establish_connection(token=None): userEmail = TESLA_EMAIL userPassword = TESLA_PASSWORD for x in range(1, 4): try: c = teslajson.Connection(userEmail, userPassword) return c except urllib2.HTTPError as e: LOGGER.error("\n>>>>> Wrong email or password. Tried {} times. Retrying in 60 seconds...\nError: {}\n".format(x, e)) time.sleep(60) x =+ 1 return False
def is_asleep(self): delay = 1 while True: try: logger.info("Getting vehicle state") connection = teslajson.Connection(a_tesla_email, a_tesla_passwd) self.vehicle = connection.vehicles[0] return self.vehicle except (KeyError, urllib2.HTTPError, urllib2.URLError) as details: delay *= 2 logger.warning("HTTP Error:" + str(details)) logger.info("Waiting %d seconds before retrying." % delay) time.sleep(delay)
def getVehicle(vehicle): pdebug('start getVehicle') try: tToken = secretGET('tToken') access_token = json.loads(tToken)['access_token'] connection = teslajson.Connection( access_token=access_token, tesla_client= '{"v1": {"id": "e4a9949fcfa04068f59abb5a658f2bac0a3428e4652315490b659d5ab3f35a9e", "secret": "c75f14bbadc8bee3a7594412c31416f8300256d7668ea7e6e7f06727bfb9d220", "baseurl": "https://owner-api.teslamotors.com", "api": "/api/1/"}}' ) vehicle = connection.vehicles[vehicle] #pprint.pprint(vehicle, indent=2) return vehicle except: return {'state': 'failed'}
def establish_connection(): userEmail = TESLA_EMAIL userPassword = TESLA_PASSWORD for x in range(1, 4): try: c = teslajson.Connection(userEmail, userPassword) return c except urllib.error.HTTPError as e: if e.code == 401: write_log( 'error', "Wrong email or password. Tried {} times. Retrying in 60 seconds. Error: {}: {}" .format(x, e.code, e.reason)) time.sleep(60) x = +1 write_log('error', "Can not connect to Tesla account. Verify credentials.") return False
def collect_data(ge, let_sleep): try: print("collect_data: connecting, time = " + str(time.ctime())) c = teslajson.Connection(tesla_info=tesla_info, access_token=access_token) print("collect_data: connected, time = " + str(time.ctime())) v = c.vehicles[0] print("collect_data: vehicle = " + str(v)) #print("collect_data: id = " + str(v['id'])) #print("collect_data: vehicle_id = " + str(v['vehicle_id'])) print("collect_data: display_name = " + str(v['display_name'])) print("collect_data: vin = " + str(v['vin'])) print("collect_data: state = " + str(v['state'])) # # v['state'] = 'online'|'offline'|'asleep' # if v['state'] == 'online': # # online # print("collect_data: " + str(v['state']) + " (-> STATE_ONLINE)") if let_sleep == True: print("collect_data: letting car go asleep") print("collect_data: " + str(v['state']) + " -> STATE_NOT_CHARGING") print_state(STATE_NOT_CHARGING, v, {}, {}, {}, {}) return STATE_NOT_CHARGING return collect_state(ge, c, v) elif v['state'] == 'offline': # # offline # print_state(STATE_OFFLINE, v, {}, {}, {}, {}) print("collect_data: " + str(v['state']) + " -> STATE_OFFLINE") return STATE_OFFLINE else: # # asleep # print_state(STATE_ASLEEP, v, {}, {}, {}, {}) print("collect_data: " + str(v['state']) + " -> STATE_ASLEEP") return STATE_ASLEEP except Exception as e: print("collect_data: EXCEPTION -> STATE_ERROR: " + str(e)) return STATE_ERROR
def __init__(self, tesla_email, tesla_password, vehicle_index): self.requests = ('charge_state', 'climate_state', 'drive_state', 'gui_settings', 'vehicle_state') self.priority_requests = { 1: ('drive_state', ), 2: ('drive_state', ), 4: ( 'charge_state', 'drive_state', ) } self.old_values = dict([(r, {}) for r in self.requests]) self.connection = teslajson.Connection(tesla_email, tesla_password) self.vehicle = self.connection.vehicles[vehicle_index] self.vehicle_index = vehicle_index self.pollTimes = [ 2, 5, 15, 30, 45, 60, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 2000, 120 ] self.noChangesPollCount = 0
import string import shelve import time import sys def now(): return time.strftime("%Y-%m-%d %H:%M:%S") # Load the configuration config = RawConfigParser() config.read('teslacal.cfg') # Connect to the Tesla cloud c = teslajson.Connection(config.get('tesla', 'username'), config.get('tesla', 'password')) # Filter the vehicles list based on VIN if specified va = c.vehicles vin = config.get('tesla', 'vin') if vin is not None: va = [ v for v in va if v['vin'] == vin ] # Make sure we did find a vehicle and then select the first if not len(va): raise Exception("Tesla not found!") v = va[0] print "Tesla "+v['display_name']+" found!" v.wake_up()
# basic vars aChargeMode = [] # time until charge must be finished (-1=start immediate) aPricesChosen = [] #logging.basicConfig(format='%(asctime)s - %(message)s', level=logging.DEBUG) logging.basicConfig(filename="file.log", format='%(asctime)s - %(message)s', level=logging.DEBUG) logging.critical("Startup Tesla Avatar") time.sleep(10) logging.info("Opening connection to Tesla API...") while True: try: c = teslajson.Connection(username, password) break except: logging.error("...could not connect (yet), wait, then try again...", exc_info=True) time.sleep(60) nNumCars = 0 while nNumCars < len(c.vehicles): v = c.vehicles[nNumCars] logging.info("Car #%u VIN=%s Name=%s, State=%s", nNumCars + 1, v["vin"], v["display_name"], v["state"]) nNumCars += 1 cntExceptions = 0 startHour = datetime.now().hour
time.sleep(10) cs = v.data_request('charge_state') cRate = float(cs["charge_rate"]) current = int(cs["charger_actual_current"]) volt = int(cs["charger_voltage"]) min_to_full = int(cs["minutes_to_full_charge"]) ct = get_car_ct() lprint( "Charge rate at: {0}amp | {1}V | CT: {2}w | Actual current: {3}amp | time-to-full: {4}" .format(cRate, volt, ct, current, min_to_full)) lprint("Checking if start-charge is scheduled") #getting scheduled charge time and wake up 10 minutes before hand c = teslajson.Connection(t_log, t_pass) v = c.vehicles[0] wake_car(v) cs = v.data_request('charge_state') start_time = cs["scheduled_charging_start_time"] if start_time is None: sys.exit("exit: No scheduled charge or not connected") epoch_now = int(time.time()) time_to_go = start_time - epoch_now lprint("Seconds before scheduled charge: {0}".format(time_to_go)) if time_to_go < ahead_sec: sys.exit( "exit: not enough time before scheduled charge - min 10min required")
def establish_connection(token=None): conn = teslajson.Connection(email=TESLA_EMAIL, password=TESLA_PASSWORD, access_token=token) return conn
print('No such file '+file) exit(1) cmds = sys.argv[1:] if len(cmds) == 0: print("Must have at least one command") exit(0) today = datetime.datetime.today() ftoday = '{:%a %d %b %H:%M:%S %Y}'.format(today) tesla_email = readfile('~/.teslaemail') # your email adresse when logging into tesla.com tesla_pwd = readfile('~/.teslapwd') # your password when logging into tesla.com try: c = teslajson.Connection(email=tesla_email, password=tesla_pwd) except: try: print ftoday+" can't contact api - retry after 15 seconds" sleep(15) # wait 15 seconds c = teslajson.Connection(email=tesla_email, password=tesla_pwd) except: print ftoday+" can't contact api - do nothing" exit(1) v = c.vehicles[0] #just use the first car - at least I can't afford more than one :) drive_state = None vehicle_state = None charge_state = None climate_state = None
def periodic(): expected_variables = [ 'TESLA_USERNAME', 'TESLA_PASSWORD', 'THING_BATTERY', 'THING_CLIMATE', 'THING_DRIVE' ] for expected_variable in expected_variables: if not expected_variable in os.environ: print 'Missing environment variable "%s"' % expected_variable sys.exit(1) if not 'AWS_DEFAULT_REGION' in os.environ: os.environ['AWS_DEFAULT_REGION'] = 'eu-central-1' # IoT client client = boto3.client('iot-data') print 'Connecting to Tesla...' c = teslajson.Connection(os.environ['TESLA_USERNAME'], os.environ['TESLA_PASSWORD']) v = c.vehicles[0] # charge state d = v.data_request('charge_state') print 'Battery level: %d' % d['battery_level'] print 'Publishing charge state to IoT...' data = { 'state': { 'reported': { 'level': d['battery_level'], 'state': d['charging_state'].lower(), 'time_to_full_charge': d['time_to_full_charge'], 'battery_heater_on': d['battery_heater_on'] } } } publish_iot(client, os.environ['THING_BATTERY'], data) # climate d = v.data_request('climate_state') print 'Temperature inside is: %d' % d['inside_temp'] print 'Publishing climate state to IoT...' data = { 'state': { 'reported': { 'temperature': d['inside_temp'], 'inside_temp': d['inside_temp'], 'outside_temp': d['outside_temp'] } } } publish_iot(client, os.environ['THING_CLIMATE'], data) # drive state d = v.data_request('drive_state') if not d['speed']: d['speed'] = 0 print 'Driving speed is: %d' % d['speed'] print 'Publishing drive state to IoT...' data = { 'state': { 'reported': { 'speed': d['speed'], 'latitude': d['latitude'], 'longitude': d['longitude'], 'heading': d['heading'], 'gps_as_of': d['gps_as_of'] } } } publish_iot(client, os.environ['THING_DRIVE'], data) return
import sys sys.path.append('/usr/local/lib/python3.8/site-packages') import teslajson import json c = teslajson.Connection('YOUREMAIL', 'YOURPASSWORD') v = c.vehicles[0] v.wake_up() i = v.data_request('charge_state') j = v.data_request('drive_state') k = v.data_request('climate_state') l = v.data_request('gui_settings') m = v.data_request('vehicle_state') q = v.data_request('vehicle_config') i = json.dumps(i) j = json.dumps(j) k = json.dumps(k) l = json.dumps(l) m = json.dumps(m) q = json.dumps(q) print("{ \"charger_state\":" + i + ",\"drive_state\":" + j + ",\"climate_state\":" + k + ",\"gui_settings\":" + l + ",\"vehicle_state\":" + m + ",\"vehicle_config\":" + q + "}")
MAX_RUNTIME = int(getTeslaconf['MAX_RUNTIME']) logfile = getTeslaconf['logfile'] poilistfile = getTeslaconf['poilistfile'] if debugmode: '''Ausgeben der Programm startzeit''' now = datetime.datetime.now() jetzt = now.strftime("%Y-%m-%d %H:%M:%S") os.system('clear') print "Programmstart:", jetzt if debugmode: print "Starte Verbindung zu Tesla:", round(time.time() - startzeit, 2) '''Verbindung zum TeslaServer''' try: connection = teslajson.Connection(TESLA_EMAIL, TESLA_PASSWORD) except: print "Fehler beim Verbindungsaufbau zu Tesla" sys.exit(1) logwrite("Start") run = True while run: '''Hier läuft der Hauptaufruf''' tesladaten = gettesla() run = tesladaten['poi'] data.append(tesladaten) laufzeit = time.time() - startzeit if debugmode and run:
raise Exception("Credential check failed") except: log.info("GCal credentials not correct, please generate new code") eg.generateAuth() eg = EventGatherer() # We should now have good credentials, so try gathering an event log.info("GCal credentials seem good, next event at: %s" % (eg.getNextEventTime())) sys.exit() if args.tauth: # Check our Tesla authentication log.info("Running Tesla credential check") try: c = teslajson.Connection(Credentials.TESLA_EMAIL, Credentials.TESLA_PASSWORD) v = c.vehicles[0] log.info( "Credentials seem okay, waking up vehicle to fetch information" ) v.wake_up() log.info("Fetching data from car") log.info("Tesla credentials seem good, current range is %s miles" % (v.data_request('charge_state')['ideal_battery_range'])) except: log.error( "Exception with Tesla authentication, check email and password", exc_info=True) sys.exit()
#!/usr/bin/env python3 # Tesla API docs: #http://docs.timdorr.apiary.io/#reference/vehicles/state-and-settings/climate-settings import teslajson import subprocess c = teslajson.Connection('*****@*****.**', 'password') v = c.vehicles[0] verbose = False #v.wake_up() # May be needed to get all data, but will also increase car battery usage charge_state = v.data_request('charge_state') for key, value in charge_state.items(): if verbose: print("*", key, "->", value) subprocess.run([ "mosquitto_pub", "-h", "192.168.1.11", "-u", "tesla", "-P", "password", "-t", "sensor/tesla/" + key, "-r", "-m", str(value) ]) climate_state = v.data_request('climate_state') for key, value in climate_state.items(): if verbose: print("*", key, "->", value)
#Function to use passed token or global variable def assign_tesla_token(): if passed_token(): return session.user.accessToken else: return os.environ['TESLA_TOKEN'] # Tesla API connection # Tesla Username and Password are stored separately as environment variables TESLA_USER = os.environ['TESLA_USER'] TESLA_PASSWORD = os.environ['TESLA_PASSWORD'] ASSIGNED_TOKEN = assign_tesla_token() if use_token(): tesla_connection = teslajson.Connection(TESLA_USER, TESLA_PASSWORD, ASSIGNED_TOKEN) else: tesla_connection = teslajson.Connection(TESLA_USER, TESLA_PASSWORD) vehicle = tesla_connection.vehicles[0] #Global State Variables unlock_timer_state = "Off" # Start with unlock_timer_state "Off" unlock_end_time = datetime.now() #initialize the UnlockEndTime global unlock_timer = Timer(1, "") charge_timer_state = "Off" # Start with charge_timer_state = "Off" charge_start_time = datetime.now() # initialize charge_timer charge_timer = Timer(1, "") t = Timer(1, "") def GetCarTimezone(latitude, longitude):
#APP_ID = os.environ['APP_ID'] #WK commented this out # Hosting service looks for an 'application' callable by default. application = Flask(__name__) ask = Ask(application, '/') logging.getLogger('flask_ask').setLevel(logging.DEBUG) #WK added this if len(sys.argv) < 3: sys.exit( "You must pass an email and password as arguments when starting this script" ) # Tesla API connection # Tesla Username and Password are stored separately as environment variables TESLA_USER = str(sys.argv[1]) TESLA_PASSWORD = str(sys.argv[2]) tesla_connection = teslajson.Connection( TESLA_USER, TESLA_PASSWORD) #WK removed quotes from variable names vehicle = tesla_connection.vehicles[0] #Global State Variables unlock_timer_state = "Off" # Start with unlock_timer_state "Off" unlock_end_time = datetime.now() #initialize the UnlockEndTime global unlock_timer = Timer(1, "") charge_timer_state = "Off" # Start with charge_timer_state = "Off" charge_start_time = datetime.now() # initialize charge_timer charge_timer = Timer(1, "") t = Timer(1, "") states = { 'AK': 'Alaska', 'AL': 'Alabama', 'AR': 'Arkansas',
import teslajson import json import sys usern = str(sys.argv[1]) passw = str(sys.argv[2]) carnumb = int(sys.argv[3]) c = teslajson.Connection(usern, passw) v = c.vehicles[carnumb] v.wake_up() result = v.data_request('charge_state') newr = json.dumps(result) print newr
def run(options): try: conn = teslajson.Connection(options.user, options.passwd) except Exception as e: fatalError(f"Failed to connect: {e}") logging.info(f"Connection: {conn}") logging.info(f"Number of vehicles: {len(conn.vehicles)}") if options.verbose > 1: n = 1 for v in conn.vehicles: print(f"Vehicle #{n}:", end='') json.dump(v, sys.stdout, indent=4, sort_keys=True) print("") n += 1 carVINs = opts.confs['cars'].keys() if opts.VIN: carVINs = [opts.VIN] if not carVINs: fatalError( "Must provide the VIN(s) of one or more car(s) to be tracked") logging.debug(f"cars: {carVINs}") teslaVINs = [v['vin'] for v in conn.vehicles] vinList = [v for v in teslaVINs if v in carVINs] if not vinList: fatalError("Unable to find requested cars in Tesla API") notFound = list(set(carVINs) - set(vinList)) if notFound: fatalError(f"Cars asked for, but not found in Tesla API: {notFound}") logging.debug(f"Watching: {vinList}") notAskedFor = list(set(teslaVINs) - set(vinList)) if notAskedFor: logging.warning( f"Cars Tesla API knows about, but not asked for: {notAskedFor}") vehicles = {v['vin']: v for v in conn.vehicles if v['vin'] in vinList} if options.verbose > 3: print("VEHICLES:") json.dump(vehicles, sys.stdout, indent=4, sort_keys=True) print("") if opts.schemaFile: schemaFile = opts.schemaFile else: schemaFile = opts.confs.get('schema') if not os.path.isfile(schemaFile): fatalError(f"Invalid DB schema file: {schemaFile}") with open(schemaFile, "r") as f: schema = yaml.load(f, Loader=yaml.Loader) if opts.dbDir: dbDir = opts.dbDir else: dbDir = opts.confs.get('dbDir') if dbDir: if not os.path.isdir(dbDir): fatalError(f"Invalid DB directory path: {dbDir}") else: if opts.verbose: logging.warning("Not logging data to DB") cars = {} cmdQs = {} respQs = {} trackers = {} for vin in vinList: conf = opts.confs['cars'][vin] cars[vin] = car = Car(vin, conf, vehicles[vin]) logging.info(f"Waking up {vin}: {car.getName()}") if not car.wakeUp(): logging.warning( f"Unable to wake up '{car.getName()}', skipping...") time.sleep(random.randint(5, 15)) continue # give car time to wake up and dither start times across cars #### FIXME time.sleep(random.randint(15, 45)) cdb = None if dbDir: dbFile = os.path.join(dbDir, vin + ".db") cdb = teslaDB.CarDB(vin, dbFile, schema) tables = schema['tables'].keys() settings = dict(DEF_SETTINGS) dictMerge(settings, opts.confs.get('config', {}).get('settings', {})) regions = [Region(r) for r in conf.get('regions', [])] notifier = Notifier( opts.confs.get('config', {}).get('eventNotifiers', {})) cmdQs[vin] = mp.Queue() respQs[vin] = mp.Queue() tracker = Tracker(car, cdb, tables, settings, regions, notifier, cmdQs[vin], respQs[vin]) logging.info(f"Tracker: {vin}") trackers[vin] = mp.Process(target=tracker.run, args=()) for vin in trackers: trackers[vin].start() if options.interactive: commandInterpreter(trackers, cmdQs, respQs) for vin in trackers: trackers[vin].join() logging.debug(f"Results for {vin}: {dumpQueue(respQs[vin])}")
import teslajson c = teslajson.Connection('email', 'password') v = c.vehicles[0] v.wake_up() # v.command('auto_conditioning_start') stat = v.data_request('climate_state') stat2 = v.data_request('charge_state') print("charge state:", stat2) #start_time = datetime.timedelta #while (datetime.timedelta - start_time) < 5 if stat['inside_temp'] > 37.7: v.command('auto_conditioning_start') print("TianGong air conditioner started:", stat['inside_temp']) v.command('set_temps', 27.2) if stat['inside_temp'] < 32.2: v.command('auto_conditioning_stop') print("TianGong air conditioner stopped:", stat['inside_temp']) print(stat['driver_temp_setting']) # v.command('set_temps', 25.0) # print(stat['driver_temp_setting']) #print(stat['inside_temp'])