Skip to content

Commit

Permalink
Format with standard
Browse files Browse the repository at this point in the history
  • Loading branch information
timdorr committed Jan 31, 2021
1 parent 7274c98 commit 3cd4317
Show file tree
Hide file tree
Showing 13 changed files with 444 additions and 432 deletions.
5 changes: 5 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -32,5 +32,10 @@ jobs:
ruby-version: ${{ matrix.ruby-version }}
bundler-cache: true

- name: Lint code
uses: andrewmcodes/[email protected]
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

- name: Run test suite
run: bundle exec rake
2 changes: 1 addition & 1 deletion Gemfile
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
source 'https://rubygems.org'
source "https://rubygems.org"

gemspec
18 changes: 9 additions & 9 deletions Rakefile
Original file line number Diff line number Diff line change
Expand Up @@ -2,32 +2,32 @@ require "bundler/gem_tasks"
require "rspec/core/rake_task"

RSpec::Core::RakeTask.new(:spec) do |task|
task.rspec_opts = ['--color', '--format', 'documentation', '--require', 'spec_helper']
task.rspec_opts = ["--color", "--format", "documentation", "--require", "spec_helper"]
end

desc "Open an irb session preloaded with this library"
task :console do
# Load all gems
require 'rubygems'
require 'bundler/setup'
require "rubygems"
require "bundler/setup"
Bundler.require(:default)

# Load the envs
require 'dotenv'
require "dotenv"
Dotenv.load!

# Set up a global client
def client
@client ||= begin
client = TeslaApi::Client.new(email: ENV['TESLA_EMAIL'])
client.login!(ENV['TESLA_PASS'])
client
client = TeslaApi::Client.new(email: ENV["TESLA_EMAIL"])
client.login!(ENV["TESLA_PASS"])
client
end
end

# Load IRB
require 'irb'
require 'irb/completion'
require "irb"
require "irb/completion"

IRB.conf[:PROMPT_MODE] = :SIMPLE
IRB.conf[:AUTO_INDENT] = true
Expand Down
24 changes: 12 additions & 12 deletions lib/tesla_api.rb
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
require 'date'
require 'base64'
require "date"
require "base64"

require 'faraday'
require 'faraday_middleware'
require "faraday"
require "faraday_middleware"

require 'async'
require 'async/http/endpoint'
require 'async/websocket/client'
require "async"
require "async/http/endpoint"
require "async/websocket/client"

require 'tesla_api/version'
require 'tesla_api/client'
require 'tesla_api/stream'
require 'tesla_api/autopark'
require 'tesla_api/vehicle'
require "tesla_api/version"
require "tesla_api/client"
require "tesla_api/stream"
require "tesla_api/autopark"
require "tesla_api/vehicle"
12 changes: 6 additions & 6 deletions lib/tesla_api/autopark.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@ module Autopark
def start_autopark(&handler)
Async do |task|
Async::WebSocket::Client.connect(autopark_endpoint, headers: headers) do |connection|
while message = connection.read
while (message = connection.read)
case message[:msg_type]
when 'control:hello'
when "control:hello"
interval = message[:autopark][:heartbeat_frequency] / 1000.0
task.async do |subtask|
subtask.sleep interval
connection.write({ msg_type: 'autopark:heartbeat_app', timestamp: Time.now.to_i }.to_json)
connection.write({msg_type: "autopark:heartbeat_app", timestamp: Time.now.to_i}.to_json)
end
end

Expand All @@ -26,17 +26,17 @@ def autopark_endpoint
end

def autopark_endpoint_url
"wss://streaming.vn.teslamotors.com/connect/#{self['vehicle_id']}"
"wss://streaming.vn.teslamotors.com/connect/#{self["vehicle_id"]}"
end

def autopark_headers
{
'Authorization' => "Basic #{socket_auth}"
"Authorization" => "Basic #{socket_auth}"
}
end

def autopark_socket_auth
Base64.strict_encode64("#{email}:#{self['tokens'].first}")
Base64.strict_encode64("#{email}:#{self["tokens"].first}")
end
end
end
118 changes: 59 additions & 59 deletions lib/tesla_api/client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,20 @@ module TeslaApi
class Client
attr_reader :api, :email, :access_token, :access_token_expires_at, :refresh_token, :client_id, :client_secret

BASE_URI = 'https://owner-api.teslamotors.com'
SSO_URI = 'https://auth.tesla.com'
BASE_URI = "https://owner-api.teslamotors.com"
SSO_URI = "https://auth.tesla.com"

def initialize(
email: nil,
access_token: nil,
access_token_expires_at: nil,
refresh_token: nil,
client_id: ENV['TESLA_CLIENT_ID'],
client_secret: ENV['TESLA_CLIENT_SECRET'],
retry_options: nil,
base_uri: nil,
sso_uri: nil,
client_options: {}
email: nil,
access_token: nil,
access_token_expires_at: nil,
refresh_token: nil,
client_id: ENV["TESLA_CLIENT_ID"],
client_secret: ENV["TESLA_CLIENT_SECRET"],
retry_options: nil,
base_uri: nil,
sso_uri: nil,
client_options: {}
)
@email = email
@base_uri = base_uri || BASE_URI
Expand All @@ -29,45 +29,45 @@ def initialize(
@refresh_token = refresh_token

@api = Faraday.new(
@base_uri + '/api/1',
@base_uri + "/api/1",
{
headers: { 'User-Agent' => "github.com/timdorr/tesla-api v:#{VERSION}" }
headers: {"User-Agent" => "github.com/timdorr/tesla-api v:#{VERSION}"}
}.merge(client_options)
) do |conn|
) { |conn|
conn.request :json
conn.response :json
conn.response :raise_error
conn.request :retry, retry_options if retry_options # Must be registered after :raise_error
conn.adapter Faraday.default_adapter
end
}
end

def refresh_access_token
response = @api.post(
@sso_uri + '/oauth2/v3/token',
@sso_uri + "/oauth2/v3/token",
{
grant_type: 'refresh_token',
client_id: 'ownerapi',
grant_type: "refresh_token",
client_id: "ownerapi",
client_secret: client_secret,
refresh_token: refresh_token,
scope: 'openid email offline_access'
scope: "openid email offline_access"
}
).body

@refresh_token = response['refresh_token']
@refresh_token = response["refresh_token"]

response = api.post(
@base_uri + '/oauth/token',
@base_uri + "/oauth/token",
{
grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
client_id: client_id,
client_secret: client_secret
},
'Authorization' => "Bearer #{response['access_token']}"
"Authorization" => "Bearer #{response["access_token"]}"
).body

@access_token = response['access_token']
@access_token_expires_at = Time.at(response['created_at'].to_f + response['expires_in'].to_f).to_datetime
@access_token = response["access_token"]
@access_token_expires_at = Time.at(response["created_at"].to_f + response["expires_in"].to_f).to_datetime

response
end
Expand All @@ -78,65 +78,65 @@ def login!(password)
state = rand(36**20).to_s(36)

response = Faraday.get(
@sso_uri + '/oauth2/v3/authorize',
@sso_uri + "/oauth2/v3/authorize",
{
client_id: 'ownerapi',
client_id: "ownerapi",
code_challenge: code_challenge,
code_challenge_method: 'S256',
redirect_uri: 'https://auth.tesla.com/void/callback',
response_type: 'code',
scope: 'openid email offline_access',
state: state,
code_challenge_method: "S256",
redirect_uri: "https://auth.tesla.com/void/callback",
response_type: "code",
scope: "openid email offline_access",
state: state
}
)

cookie = response.headers['set-cookie'].split(' ').first
cookie = response.headers["set-cookie"].split(" ").first
parameters = Hash[response.body.scan(/type="hidden" name="(.*?)" value="(.*?)"/)]

response = Faraday.post(
@sso_uri + '/oauth2/v3/authorize?' + URI.encode_www_form({
client_id: 'ownerapi',
@sso_uri + "/oauth2/v3/authorize?" + URI.encode_www_form({
client_id: "ownerapi",
code_challenge: code_challenge,
code_challenge_method: 'S256',
redirect_uri: 'https://auth.tesla.com/void/callback',
response_type: 'code',
scope: 'openid email offline_access',
state: state,
code_challenge_method: "S256",
redirect_uri: "https://auth.tesla.com/void/callback",
response_type: "code",
scope: "openid email offline_access",
state: state
}),
URI.encode_www_form(parameters.merge(
'identity' => email,
'credential' => password
"identity" => email,
"credential" => password
)),
'Cookie' => cookie
"Cookie" => cookie
)

code = CGI.parse(URI(response.headers['location']).query)['code'].first
code = CGI.parse(URI(response.headers["location"]).query)["code"].first

response = @api.post(
@sso_uri + '/oauth2/v3/token',
@sso_uri + "/oauth2/v3/token",
{
grant_type: 'authorization_code',
client_id: 'ownerapi',
grant_type: "authorization_code",
client_id: "ownerapi",
code: code,
code_verifier: code_verifier,
redirect_uri: 'https://auth.tesla.com/void/callback'
redirect_uri: "https://auth.tesla.com/void/callback"
}
).body

@refresh_token = response['refresh_token']
@refresh_token = response["refresh_token"]

response = api.post(
@base_uri + '/oauth/token',
@base_uri + "/oauth/token",
{
grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
client_id: client_id,
client_secret: client_secret
},
'Authorization' => "Bearer #{response['access_token']}"
"Authorization" => "Bearer #{response["access_token"]}"
).body

@access_token = response['access_token']
@access_token_expires_at = Time.at(response['created_at'].to_f + response['expires_in'].to_f).to_datetime
@access_token = response["access_token"]
@access_token_expires_at = Time.at(response["created_at"].to_f + response["expires_in"].to_f).to_datetime

response
end
Expand All @@ -147,19 +147,19 @@ def expired?
end

def get(url)
api.get(url.sub(/^\//, ''), nil, { 'Authorization' => "Bearer #{access_token}" }).body
api.get(url.sub(/^\//, ""), nil, {"Authorization" => "Bearer #{access_token}"}).body
end

def post(url, body: nil)
api.post(url.sub(/^\//, ''), body, { 'Authorization' => "Bearer #{access_token}" }).body
api.post(url.sub(/^\//, ""), body, {"Authorization" => "Bearer #{access_token}"}).body
end

def vehicles
get('/vehicles')['response'].map { |v| Vehicle.new(self, email, v['id'], v) }
get("/vehicles")["response"].map { |v| Vehicle.new(self, email, v["id"], v) }
end

def vehicle(id)
Vehicle.new(self, email, id, self.get("/vehicles/#{id}")['response'])
Vehicle.new(self, email, id, get("/vehicles/#{id}")["response"])
end
end
end
18 changes: 9 additions & 9 deletions lib/tesla_api/stream.rb
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
module TeslaApi
module Stream
def self.streaming_endpoint_url
'wss://streaming.vn.teslamotors.com/streaming/'
"wss://streaming.vn.teslamotors.com/streaming/"
end

def self.streaming_endpoint
Expand All @@ -19,16 +19,16 @@ def stream(endpoint: Stream.streaming_endpoint, &receiver)
connection.write(streaming_connect_message)
timeout = task.async(&on_timeout)

while message = connection.read
while (message = connection.read)
timeout.stop
timeout = task.async(&on_timeout)

case message[:msg_type]
when 'data:update'
attributes = message[:value].split(',')
when "data:update"
attributes = message[:value].split(",")

receiver.call({
time: DateTime.strptime((attributes[0].to_i/1000).to_s, '%s'),
time: DateTime.strptime((attributes[0].to_i / 1000).to_s, "%s"),
speed: attributes[1].to_f,
odometer: attributes[2].to_f,
soc: attributes[3].to_f,
Expand All @@ -42,7 +42,7 @@ def stream(endpoint: Stream.streaming_endpoint, &receiver)
est_range: attributes[11].to_f,
heading: attributes[12].to_f
})
when 'data:error'
when "data:error"
task.stop
end
end
Expand All @@ -56,10 +56,10 @@ def stream(endpoint: Stream.streaming_endpoint, &receiver)

def streaming_connect_message
{
msg_type: 'data:subscribe_oauth',
msg_type: "data:subscribe_oauth",
token: client.access_token,
value: 'speed,odometer,soc,elevation,est_heading,est_lat,est_lng,power,shift_state,range,est_range,heading',
tag: self['vehicle_id'].to_s,
value: "speed,odometer,soc,elevation,est_heading,est_lat,est_lng,power,shift_state,range,est_range,heading",
tag: self["vehicle_id"].to_s
}
end
end
Expand Down
Loading

0 comments on commit 3cd4317

Please sign in to comment.