Skip to content

Commit

Permalink
Switch over the autopark code to async.
Browse files Browse the repository at this point in the history
  • Loading branch information
timdorr committed Oct 11, 2019
1 parent 0ea61a0 commit 2494bc9
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 44 deletions.
2 changes: 0 additions & 2 deletions lib/tesla_api.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@

require 'faraday'
require 'faraday_middleware'
require 'eventmachine'
require 'faye/websocket'

require 'async'
require 'async/http/endpoint'
Expand Down
64 changes: 23 additions & 41 deletions lib/tesla_api/autopark.rb
Original file line number Diff line number Diff line change
@@ -1,60 +1,42 @@
module TeslaApi
module Autopark
def start_autopark(&handler)
EventMachine.run do
autopark_socket.on(:message) do |event|
message = if event.data.is_a?(Array)
JSON.parse(event.data.map(&:chr).join)
else
JSON.parse(event.data)
end

default_handler(message)
handler.call(message.delete('msg_type'), message)
end
Async do |task|
Async::WebSocket::Client.connect(endpoint, headers: headers) do |connection|
while message = connection.read
case message[:msg_type]
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)
end
end

autopark_socket.on(:close) do |_|
@autopark_socket = nil
@heartbeat && @heartbeat.cancel
EventMachine.stop
handler.call(message)
end
end
end
end

private

def default_handler(message)
case message['msg_type']
when 'control:hello'
interval = message['autopark']['heartbeat_frequency'] / 1000.0
@heartbeat = EventMachine::Timer.new(interval) do
beat = {
msg_type: 'autopark:heartbeat_app',
timestamp: Time.now.to_i
}
autopark_socket.send(beat.to_json)
end
end
def endpoint
Async::HTTP::Endpoint.parse(autopark_socket_endpoint)
end

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

def autopark_socket
@autopark_socket ||= Faye::WebSocket::Client.new(
autopark_socket_endpoint,
nil,
{
headers: {
'Authorization' => "Basic #{socket_auth}"
}
}
)
def headers
{
'Authorization' => "Basic #{socket_auth}"
}
end

def socket_auth
Base64.strict_encode64("#{email}:#{self['tokens'].first}")
end

def autopark_socket_endpoint
"wss://streaming.vn.teslamotors.com/connect/#{self['vehicle_id']}"
end
end
end
1 change: 0 additions & 1 deletion tesla_api.gemspec
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ Gem::Specification.new do |spec|
spec.add_dependency 'async-websocket'
spec.add_dependency 'faraday'
spec.add_dependency 'faraday_middleware'
spec.add_dependency 'faye-websocket'

spec.add_development_dependency 'bundler', '~> 2.0'
spec.add_development_dependency 'rake', '~> 12.0'
Expand Down

0 comments on commit 2494bc9

Please sign in to comment.