Add a background timer to do an HTTP for the consistency checker

pull/974/head
connor rigby 2019-07-18 19:33:20 -07:00 committed by Connor Rigby
parent debb3fbc55
commit 830f6894d8
No known key found for this signature in database
GPG Key ID: 29A88B24B70456E0
1 changed files with 32 additions and 3 deletions

View File

@ -8,14 +8,17 @@ defmodule FarmbotExt.AMQP.PingPongChannel do
use GenServer
use AMQP
alias FarmbotExt.AMQP.ConnectionWorker
alias FarmbotExt.{API, AMQP.ConnectionWorker}
require Logger
require FarmbotCore.Logger
@exchange "amq.topic"
defstruct [:conn, :chan, :jwt]
@lower_bound_ms 900_000
@upper_bound_ms 1_200_000
defstruct [:conn, :chan, :jwt, :http_ping_timer, :ping_fails]
alias __MODULE__, as: State
@doc false
@ -26,7 +29,17 @@ defmodule FarmbotExt.AMQP.PingPongChannel do
def init(args) do
Process.flag(:sensitive, true)
jwt = Keyword.fetch!(args, :jwt)
{:ok, %State{conn: nil, chan: nil, jwt: jwt}, 1000}
http_ping_timer = Process.send_after(self(), :http_ping, 5000)
state = %State{
conn: nil,
chan: nil,
jwt: jwt,
http_ping_timer: http_ping_timer,
ping_fails: 0
}
{:ok, state, 1000}
end
def terminate(reason, state) do
@ -60,6 +73,22 @@ defmodule FarmbotExt.AMQP.PingPongChannel do
end
end
def handle_info(:http_ping, state) do
ms = Enum.random(@lower_bound_ms..@upper_bound_ms)
case API.get(API.client(), "/api/device") do
{:ok, _} ->
http_ping_timer = Process.send_after(self(), :http_ping, ms)
{:noreply, %{state | http_ping_timer: http_ping_timer, ping_fails: 0}}
_ ->
ping_fails = state.ping_fails + 1
FarmbotCore.Logger.error(3, "Ping failed (#{ping_fails})")
http_ping_timer = Process.send_after(self(), :http_ping, ms)
{:noreply, %{state | http_ping_timer: http_ping_timer, ping_fails: ping_fails}}
end
end
# Confirmation sent by the broker after registering this process as a consumer
def handle_info({:basic_consume_ok, _}, state) do
{:noreply, state}