Tesla Model S & X Script for Indigo

Posted on
Sun Jan 17, 2016 7:18 pm
Bollar offline
Posts: 528
Joined: Aug 11, 2013

Re: Tesla Model S & X Script for Indigo

Here's a separate script for sending commands to the car. It's basically the same script, but it's looking for contents in an indigo variable called "teslaCommand". If you put a valid command in the variable (like: honk_horn or charge_start) and then run the script, it will send that command to the car. I have created several action groups to put the command I want to send in that variable.

Code: Select all
""" Simple Python class to access the Tesla JSON API
https://github.com/gglockner/teslajson
The Tesla JSON API is described at:
http://docs.timdorr.apiary.io/
Example:
import teslajson
c = teslajson.Connection('youremail', 'yourpassword')
v = c.vehicles[0]
v.wake_up()
v.data_request('charge_state')
v.command('charge_start')
"""

try: # Python 3
   from urllib.parse import urlencode
   from urllib.request import Request, urlopen
except: # Python 2
   from urllib import urlencode
   from urllib2 import Request, urlopen
import json
import math
import datetime

class Connection(object):
   """Connection to Tesla Motors API"""
   def __init__(self,
         email='',
         password='',
         access_token='',
         url="https://owner-api.teslamotors.com",
         api="/api/1/",
         client_id = "e4a9949fcfa04068f59abb5a658f2bac0a3428e4652315490b659d5ab3f35a9e",
         client_secret = "c75f14bbadc8bee3a7594412c31416f8300256d7668ea7e6e7f06727bfb9d220"):
      """Initialize connection object
      
      Sets the vehicles field, a list of Vehicle objects
      associated with your account
      Required parameters:
      email: your login for teslamotors.com
      password: your password for teslamotors.com
      
      Optional parameters:
      access_token: API access token
      url: base URL for the API
      api: API string
      client_id: API identifier
      client_secret: Secret API identifier
      """
      self.url = url
      self.api = api
      if not access_token:
         oauth = {
            "grant_type" : "password",
            "client_id" : client_id,
            "client_secret" : client_secret,
            "email" : email,
            "password" : password }
         auth = self.__open("/oauth/token", data=oauth)
         access_token = auth['access_token']
      self.access_token = access_token
      self.head = {"Authorization": "Bearer %s" % self.access_token}
      self.vehicles = [Vehicle(v, self) for v in self.get('vehicles')['response']]
   
   def get(self, command):
      """Utility command to get data from API"""
      return self.__open("%s%s" % (self.api, command), headers=self.head)
   
   def post(self, command, data={}):
      """Utility command to post data to API"""
      return self.__open("%s%s" % (self.api, command), headers=self.head, data=data)
   
   def __open(self, url, headers={}, data=None):
      """Raw urlopen command"""
      req = Request("%s%s" % (self.url, url), headers=headers)
      try:
         req.data = urlencode(data).encode('utf-8') # Python 3
      except:
         try:
            req.add_data(urlencode(data)) # Python 2
         except:
            pass
      resp = urlopen(req)
      charset = resp.info().get('charset', 'utf-8')
      return json.loads(resp.read().decode(charset))
      

class Vehicle(dict):
   """Vehicle class, subclassed from dictionary.
   
   There are 3 primary methods: wake_up, data_request and command.
   data_request and command both require a name to specify the data
   or command, respectively. These names can be found in the
   Tesla JSON API."""
   def __init__(self, data, connection):
      """Initialize vehicle class
      
      Called automatically by the Connection class
      """
      super(Vehicle, self).__init__(data)
      self.connection = connection
   
   def data_request(self, name):
      """Get vehicle data"""
      result = self.get('data_request/%s' % name)
      return result['response']
   
   def wake_up(self):
      """Wake the vehicle"""
      return self.post('wake_up')
   
   def command(self, name):
      """Run the command for the vehicle"""
      return self.post('command/%s' % name)
   
   def get(self, command):
      """Utility command to get data from API"""
      return self.connection.get('vehicles/%i/%s' % (self['id'], command))
   
   def post(self, command):      
      """Utility command to post data to API"""
      return self.connection.post('vehicles/%i/%s' % (self['id'], command))


try:
   indigo.variables.folder.create("Tesla")                                 # Create Indigo variable folder if necessary
except ValueError:
   pass

try:
   indigo.variable.create("teslaUserName", value="Need Tesla Motors e-mail", folder=str("Tesla"))      
except ValueError:
   pass

try:
   indigo.variable.create("teslaPassword", value="Need Tesla Motors password", folder=str("Tesla"))      
except ValueError:
   pass


c = Connection(indigo.variables["teslaUserName"].value, indigo.variables["teslaPassword"].value)
v = c.vehicles[0]

for k,i in v.items():
   try:
      indigo.variable.create(str(k), value=str(i), folder=str("Tesla"))      
   except ValueError:
      indigo.variable.updateValue(str(k), value=str(i))

v.wake_up()

# for k,i in v.data_request('mobile_enabled').items():
#    try:
#       indigo.variable.create(str(k), value=str(i), folder=str("Tesla"))      
#    except ValueError:
#       indigo.variable.updateValue(str(k), value=str(i))

v.command(indigo.variables["teslaCommand"].value)
Last edited by Bollar on Mon Jan 18, 2016 4:38 pm, edited 2 times in total.

Insteon / Z-Wave / Bryant Evolution Connex /Tesla / Roomba / Elk M1 / SiteSage / Enphase Enlighten / NOAA Alerts

Posted on
Sun Jan 17, 2016 7:28 pm
Bollar offline
Posts: 528
Joined: Aug 11, 2013

Re: Tesla Model S & X Script for Indigo

Dewster35 wrote:
I think it is hilarious how anytime anyone hears about my home automation system that they automatically think I'm rich... when in reality, the fact that every single one of the forum users, save one, including the developers are all begging for a free tesla! Sure puts things in perspective that we're all either poor/cheap bastards :)

Weeeelllllll... Not that they're cheap, but you can get a used, certified pre-owned Tesla starting at $50K, including a 50K mile warranty and an 8 year, unlimited mile warranty on the battery & drive train. Begin your shopping here: http://ev-cpo.com :D
Last edited by Bollar on Sun Jan 17, 2016 7:35 pm, edited 1 time in total.

Insteon / Z-Wave / Bryant Evolution Connex /Tesla / Roomba / Elk M1 / SiteSage / Enphase Enlighten / NOAA Alerts

Posted on
Sun Jan 17, 2016 7:30 pm
Decker offline
Posts: 22
Joined: Jun 13, 2013

Re: Tesla Model S & X Script for Indigo

Wow. Thanks again. I was waiting to get my kid to bed and was going to start messing around with sending commands. Now I can setup my keypad on the nightstand to turn on the climate control when I wake up. It's -1 in Chicago.

Posted on
Sun Jan 17, 2016 7:35 pm
Bollar offline
Posts: 528
Joined: Aug 11, 2013

Re: Tesla Model S & X Script for Indigo

Decker wrote:
Wow. Thanks again. I was waiting to get my kid to bed and was going to start messing around with sending commands. Now I can setup my keypad on the nightstand to turn on the climate control when I wake up. It's -1 in Chicago.

The command is auto_conditioning_start and it only stays on for 30 minutes. I have mine on an Indigo schedule, so I don't forget.

Insteon / Z-Wave / Bryant Evolution Connex /Tesla / Roomba / Elk M1 / SiteSage / Enphase Enlighten / NOAA Alerts

Posted on
Sun Jan 17, 2016 7:44 pm
Decker offline
Posts: 22
Joined: Jun 13, 2013

Re: Tesla Model S & X Script for Indigo

Another cool thing.... Using the homebridge hack we can control our Tesla's using Siri.

Hey Siri, turn on Tessie's heat.

Posted on
Mon Jan 18, 2016 9:31 am
Decker offline
Posts: 22
Joined: Jun 13, 2013

Re: Tesla Model S & X Script for Indigo

Hi Bollar.

What kind of result are you getting from the distance calculation? I'm getting 0.28 when I'm about 20 miles away from my house. I know it's not going to be exact but are you getting results less than 1 as well?

Thanks,

Posted on
Mon Jan 18, 2016 9:35 am
Bollar offline
Posts: 528
Joined: Aug 11, 2013

Re: Tesla Model S & X Script for Indigo

Decker wrote:
Hi Bollar.

What kind of result are you getting from the distance calculation? I'm getting 0.28 when I'm about 20 miles away from my house. I know it's not going to be exact but are you getting results less than 1 as well?

Thanks,

Yeah, that's my doing. I borked the formula. I will correct it.


Sent from my iPhone using Tapatalk

Insteon / Z-Wave / Bryant Evolution Connex /Tesla / Roomba / Elk M1 / SiteSage / Enphase Enlighten / NOAA Alerts

Posted on
Mon Jan 18, 2016 4:30 pm
Bollar offline
Posts: 528
Joined: Aug 11, 2013

Re: Tesla Model S & X Script for Indigo

Decker wrote:
Hi Bollar.

What kind of result are you getting from the distance calculation? I'm getting 0.28 when I'm about 20 miles away from my house. I know it's not going to be exact but are you getting results less than 1 as well?


Code: Select all
Current version at end of thread.
Last edited by Bollar on Tue Dec 13, 2016 8:00 am, edited 1 time in total.

Insteon / Z-Wave / Bryant Evolution Connex /Tesla / Roomba / Elk M1 / SiteSage / Enphase Enlighten / NOAA Alerts

Posted on
Mon Jan 18, 2016 5:50 pm
Decker offline
Posts: 22
Joined: Jun 13, 2013

Re: Tesla Model S & X Script for Indigo

Thanks! Inserted the code and will check it out when I leave in the morning.

Posted on
Tue Jan 19, 2016 8:24 am
Decker offline
Posts: 22
Joined: Jun 13, 2013

Re: Tesla Model S & X Script for Indigo

Works great. Thanks

Posted on
Tue Jan 19, 2016 8:39 am
Bollar offline
Posts: 528
Joined: Aug 11, 2013

Re: Tesla Model S & X Script for Indigo

Decker wrote:
Works great. Thanks

Okay good. Amazing what you can do when you use the right formula...

Insteon / Z-Wave / Bryant Evolution Connex /Tesla / Roomba / Elk M1 / SiteSage / Enphase Enlighten / NOAA Alerts

Posted on
Sun Sep 11, 2016 2:10 pm
ethank offline
Posts: 55
Joined: Oct 12, 2006

Re: Tesla Model S & X Script for Indigo

Any ideas how to get this to work as an external script? I get this error when I try, but timeouts if its embedded.

Sep 11, 2016, 1:02:03 PM
Script Error teslalogger.py: HTTP Error 502: Bad Gateway
Script Error Exception Traceback (most recent call shown last):

teslalogger.py, line 149, at top level
teslalogger.py, line 109, in wake_up
teslalogger.py, line 121, in post
teslalogger.py, line 70, in post
teslalogger.py, line 82, in __open
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/urllib2.py", line 126, in urlopen
return _opener.open(url, data, timeout)
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/urllib2.py", line 397, in open
response = meth(req, response)
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/urllib2.py", line 510, in http_response
'http', request, response, code, msg, hdrs)
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/urllib2.py", line 435, in error
return self._call_chain(*args)
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/urllib2.py", line 369, in _call_chain
result = func(*args)
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/urllib2.py", line 518, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
HTTPError: HTTP Error 502: Bad Gateway

Posted on
Tue Sep 27, 2016 10:00 am
petematheson offline
Posts: 847
Joined: Sep 14, 2014
Location: Southampton, UK

Re: Tesla Model S & X Script for Indigo

Hi Guys,
Just checking on the state of play for the Tesla script above. Does this still work since the latest v8 update?
Any chance it could be turned into an Indigo plugin?

Posted on
Tue Sep 27, 2016 10:27 am
durosity offline
User avatar
Posts: 4320
Joined: May 10, 2012
Location: Newcastle Upon Tyne, Ye Ol' England.

Re: Tesla Model S & X Script for Indigo

petematheson wrote:
Hi Guys,
Just checking on the state of play for the Tesla script above. Does this still work since the latest v8 update?
Any chance it could be turned into an Indigo plugin?


You're not getting a tesla are you?!?

Computer says no.

Posted on
Tue Sep 27, 2016 1:16 pm
petematheson offline
Posts: 847
Joined: Sep 14, 2014
Location: Southampton, UK

Re: Tesla Model S & X Script for Indigo

durosity wrote:
You're not getting a tesla are you?!?


Would you believe me if I said it saved my company about £20k which effectively makes it zero deposit, costs less per month and around £5k less over the next 3 years than my existing car!?



Sent from my iPhone using Tapatalk

Who is online

Users browsing this forum: No registered users and 6 guests