Skip to content

Commit

Permalink
Add location topic
Browse files Browse the repository at this point in the history
Fixes #3660.
  • Loading branch information
brianmay committed Mar 12, 2024
1 parent aa4d87a commit 406f9c4
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 1 deletion.
30 changes: 30 additions & 0 deletions lib/teslamate/mqtt/pubsub/vehicle_subscriber.ex
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,36 @@ defmodule TeslaMate.Mqtt.PubSub.VehicleSubscriber do
nil
end)

if state.last_summary == nil or
(state.last_summary.latitude != summary.latitude and
state.last_summary.longitude != summary.longitude) do
lat_lng =
case {summary.latitude, summary.longitude} do
{nil, _} -> nil
{_, nil} -> nil
{%Decimal{} = lat, %Decimal{} = lon} -> {Decimal.to_float(lat), Decimal.to_float(lon)}
{lat, lon} -> {lat, lon}
end

case lat_lng do
nil ->
nil

{lat, lon} ->
location =
%{
latitude: lat,
longitude: lon
}
|> Jason.encode!()

case publish({"location", location}, state) do
:ok -> nil
{:error, reason} -> Logger.warning("Failed to publish location: #{inspect(reason)}")
end
end
end

{:noreply, %State{state | last_summary: summary}}
end

Expand Down
10 changes: 9 additions & 1 deletion test/teslamate/mqtt/pubsub/vehicle_subscriber_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,14 @@ defmodule TeslaMate.Mqtt.PubSub.VehicleSubscriberTest do
assert_receive {MqttPublisherMock, {:publish, ^topic, "", [retain: true, qos: 1]}}
end

assert_receive {MqttPublisherMock,
{:publish, "teslamate/cars/0/location", data, [retain: true, qos: 1]}}

assert Jason.decode!(data) == %{
"latitude" => 37.889602,
"longitude" => 41.129182
}

refute_receive _
end

Expand Down Expand Up @@ -158,7 +166,7 @@ defmodule TeslaMate.Mqtt.PubSub.VehicleSubscriberTest do
geofence = %GeoFence{id: 0, name: "Home", latitude: 0.0, longitude: 0.0, radius: 20}
other_geofence = %GeoFence{id: 0, name: "Work", latitude: 0.0, longitude: 0.0, radius: 20}

# Send geofence
# Send geofence
send(pid, %Summary{geofence: geofence, version: "1"})
assert_receive {MqttPublisherMock, {:publish, "teslamate/cars/0/geofence", "Home", _}}
assert_receive {MqttPublisherMock, {:publish, "teslamate/cars/0/version", "1", _}}
Expand Down
8 changes: 8 additions & 0 deletions test/teslamate/vehicles/vehicle_sync_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,14 @@ defmodule TeslaMate.Vehicles.VehicleSyncTest do
assert_receive {MqttPublisherMock, {:publish, ^topic, ^data, [retain: true, qos: 1]}}
end

topic = "teslamate/cars/#{car.id}/location"
assert_receive {MqttPublisherMock, {:publish, ^topic, data, [retain: true, qos: 1]}}

assert Jason.decode!(data) == %{
"latitude" => 37.889544,
"longitude" => 41.128817
}

refute_receive _
end
end
Expand Down

0 comments on commit 406f9c4

Please sign in to comment.