Skip to content

Commit

Permalink
Initial version
Browse files Browse the repository at this point in the history
  • Loading branch information
clarkd committed Oct 16, 2020
0 parents commit c6599ba
Show file tree
Hide file tree
Showing 7 changed files with 394 additions and 0 deletions.
145 changes: 145 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@

# Created by https://www.toptal.com/developers/gitignore/api/python
# Edit at https://www.toptal.com/developers/gitignore?templates=python

### Python ###
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
pip-wheel-metadata/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
pytestdebug.log

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/
doc/_build/

# PyBuilder
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
.python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
pythonenv*

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# pytype static type analyzer
.pytype/

# profiling data
.prof

# End of https://www.toptal.com/developers/gitignore/api/python
21 changes: 21 additions & 0 deletions LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2020 Dave Clarke

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
26 changes: 26 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# fordpass-python

This is a basic Python wrapper around the FordPass APIs. It's more or less a straight port of @d4v3y0rk's NPM module [d4v3y0rk/ffpass](https://github.com/d4v3y0rk/ffpass-module) - props to him for his work figuring out the relevant API requests needed.

## Features

* Automatically auth & re-fetches tokens once expired
* Get status of the vehicle (this returns a ton of info about the car: lat/long, oil, battery, fuel, odometer, tire pressures, open windows and a bunch of other stuff that may/may not apply to your car, e.g. charge level, diesel filters.)
* Start the engine (if supported)
* Stop the engine (if supported)
* Lock the doors
* Unlock the doors

## Demo

To test the libary there is a demo script `demo.py`.

```
demo.py USERNAME PASSWORD VIN
```

e.g.

```
demo.py [email protected] mypassword WX12345678901234
```
1 change: 1 addition & 0 deletions fordpass/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from .fordpass import Vehicle
23 changes: 23 additions & 0 deletions fordpass/bin/demo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
#!/usr/bin/env python

"""
Simple script to demo the API
"""

import sys, os, logging, time
from fordpass import Vehicle

if __name__ == "__main__":

if len(sys.argv) != 4:
raise Exception('Must specify Username, Password and VIN as arguments, e.g. demo.py [email protected] password123 WX231231232')
else:
r = Vehicle(sys.argv[1], sys.argv[2], sys.argv[3]) # Username, Password, VIN

print(r.status()) # Print the status of the car

# r.unlock() # Unlock the doors

# time.sleep(10) # Wait 10 seconds

# r.lock() # Lock the doors
151 changes: 151 additions & 0 deletions fordpass/fordpass.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
import requests
import logging
import time

defaultHeaders = {
'Accept': '*/*',
'Accept-Language': 'en-us',
'User-Agent': 'fordpass-na/353 CFNetwork/1121.2.2 Darwin/19.3.0',
'Accept-Encoding': 'gzip, deflate, br',
}

apiHeaders = {
**defaultHeaders,
'Application-Id': '71A3AD0A-CF46-4CCF-B473-FC7FE5BC4592',
'Content-Type': 'application/json',
}

baseUrl = 'https://usapi.cv.ford.com/api'

class Vehicle(object):
'''Represents a Ford vehicle, with methods for status and issuing commands'''

def __init__(self, username, password, vin):
self.username = username
self.password = password
self.vin = vin
self.token = None
self.expires = None

def __auth(self):
'''Authenticate and store the token'''

data = {
'client_id': '9fb503e0-715b-47e8-adfd-ad4b7770f73b',
'grant_type': 'password',
'username': self.username,
'password': self.password
}

headers = {
**defaultHeaders,
'Content-Type': 'application/x-www-form-urlencoded'
}

r = requests.post('https://fcis.ice.ibmcloud.com/v1.0/endpoint/default/token', data=data, headers=headers)

if r.status_code == 200:
logging.info('Succesfully fetched token')
result = r.json()
self.token = result['access_token']
self.expiresAt = time.time() + result['expires_in']
return True
else:
r.raise_for_status()

def __acquireToken(self):
'''Fetch and refresh token as needed'''

if (self.token == None) or (time.time() >= self.expiresAt):
logging.info('No token, or has expired, requesting new token')
self.__auth()
else:
logging.info('Token is valid, continuing')
pass

def status(self):
'''Get the status of the vehicle'''

self.__acquireToken()

params = {
'lrdt': '01-01-1970 00:00:00'
}

headers = {
**apiHeaders,
'auth-token': self.token
}

r = requests.get(f'{baseUrl}/vehicles/v4/{self.vin}/status', params=params, headers=headers)

if r.status_code == 200:
result = r.json()
return result['vehiclestatus']
else:
r.raise_for_status()

def start(self):
'''
Issue a start command to the engine
'''
return self.__requestAndPoll('PUT', f'{baseUrl}/vehicles/v2/{self.vin}/engine/start')

def stop(self):
'''
Issue a stop command to the engine
'''
return self.__requestAndPoll('DELETE', f'{baseUrl}/vehicles/v2/{self.vin}/engine/start')


def lock(self):
'''
Issue a lock command to the doors
'''
return self.__requestAndPoll('PUT', f'{baseUrl}/vehicles/v2/{self.vin}/doors/lock')


def unlock(self):
'''
Issue an unlock command to the doors
'''
return self.__requestAndPoll('DELETE', f'{baseUrl}/vehicles/v2/{self.vin}/engine/start')

def __makeRequest(self, method, url, data, params):
'''
Make a request to the given URL, passing data/params as needed
'''

headers = {
**apiHeaders,
'auth-token': self.token
}

return getattr(requests, method.lower())(url, headers=headers, data=data, params=params)

def __pollStatus(self, url, id):
'''
Poll the given URL with the given command ID until the command is completed
'''
status = self.__makeRequest('GET', f'{url}/{id}', None, None)
result = status.json()
if result['status'] == 552:
logging.info('Command is pending')
time.sleep(5)
return self.__pollStatus(url, id) # retry after 5s
elif result['status'] == 200:
logging.info('Command completed succesfully')
return True
else:
logging.info('Command failed')
return False

def __requestAndPoll(self, method, url):
self.__acquireToken()
command = self.__makeRequest(method, url, None, None)

if command.status_code == 200:
result = command.json()
return self.__pollStatus(url, result['commandId'])
else:
command.raise_for_status()
Loading

0 comments on commit c6599ba

Please sign in to comment.