Module: TeslaApi::Stream

Included in:
Vehicle
Defined in:
lib/tesla_api/stream.rb

Instance Method Summary collapse

Instance Method Details

#stream(&receiver) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/tesla_api/stream.rb', line 3

def stream(&receiver)
  EventMachine.run do
    socket = create_streaming_socket

    socket.on(:open) do |event|
      socket.send(JSON.generate(stream_connect_message))
    end

    socket.on(:message) do |event|
      data = JSON.parse(event.data.pack('c*'))

      if data['msg_type'] == 'data:update'
        attributes = data['value'].split(',')

        receiver.call({
          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,
          elevation: attributes[4].to_f,
          est_heading: attributes[5].to_f,
          est_lat: attributes[6].to_f,
          est_lng: attributes[7].to_f,
          power: attributes[8].to_f,
          shift_state: attributes[9].to_s,
          range: attributes[10].to_f,
          est_range: attributes[11].to_f,
          heading: attributes[12].to_f
        })
      end
    end

    socket.on(:close) do |event|
      EventMachine.stop
    end
  end
end