   end
 
   @impl GenServer
-  def terminate(reason, %{conn: conn}) do
-    if Process.alive?(conn.pid) do
-      try do
-        Logger.info("Closing AMQP connection: #{inspect(reason)}")
-        :ok = AMQP.Connection.close(conn)
-      rescue
-        ex ->
-          message = Exception.message(ex)
-          Logger.error("Could not close AMQP connection: #{message}")
-      end
-    end
+  def terminate(_reason, %{conn: conn}) do
+    close_connection(conn)
   end
 
   @impl GenServer


  use GenServer
  require Logger
  alias AMQP.{Basic, Channel, Queue}

  alias FarmbotExt.{JWT, AMQP.ConnectionWorker}


    case open_connection(token, email, jwt.bot, jwt.mqtt, jwt.vhost) do
      {:ok, conn} ->
        Process.monitor(conn.pid)
        {:noreply, %{state | conn: conn}}

      err ->
        Logger.error("Error connecting to AMPQ: #{inspect(err)}")
        Process.send_after(self(), :timeout, 5000)
        {:noreply, %{state | conn: nil}}
    end
  end

  def handle_info({:DOWN, _ref, :process, _pid, reason}, state) do
    FarmbotCore.Logger.error(2, "AMQP Connection exit")
    _ = close_connection(state.conn)
    {:stop, reason, state}
  end

  @impl GenServer
  def handle_call(:connection, _, %{conn: conn} = state) do
    {:reply, conn, state}
  end

  def handle_call(:close, _from, %{conn: _conn} = state) do
    FarmbotCore.Logger.error(2, "AMQP Connection closing")
    reply = close_connection(state.conn)
    {:stop, :close, reply, %{state | conn: nil}}
  end

  # Public function because the NervesHub channel requires it.
