 
   def init([]) do
     token = ConfigStorage.get_config_value(:string, "authorization", "token")
-    with {:ok, %{bot: device, mqtt: mqtt_server, vhost: vhost}} <- Farmbot.Jwt.decode(token),
-         {:ok, conn} <- AMQP.Connection.open([host: mqtt_server, username: device, password: token, virtual_host: vhost || "/"]),
-         {:ok, chan} <- AMQP.Channel.open(conn),
-         queue_name  <- Enum.join([device, UUID.uuid1()], "-"),
-         :ok         <- Basic.qos(chan, []),
-         {:ok, _}    <- AMQP.Queue.declare(chan, queue_name, [auto_delete: true]),
-         :ok         <- AMQP.Queue.bind(chan, queue_name, @exchange, [routing_key: "bot.#{device}.from_clients"]),
-         :ok         <- AMQP.Queue.bind(chan, queue_name, @exchange, [routing_key: "bot.#{device}.sync.#"]),
-         {:ok, _tag} <- Basic.consume(chan, queue_name),
-         state       <- struct(State, [conn: conn, chan: chan, queue_name: queue_name, bot: device])
+
+    import Farmbot.Jwt, only: [decode: 1]
+    with {:ok, %{bot: device, mqtt: mqtt_server, vhost: vhost}} <- decode(token),
+         {:ok, conn}  <- open_connection(token, device, mqtt_server, vhost),
+         {:ok, chan}  <- AMQP.Channel.open(conn),
+         q_name       <- Enum.join([device, UUID.uuid1()], "-"),
+         :ok          <- Basic.qos(chan, []),
+         {:ok, _}     <- AMQP.Queue.declare(chan, q_name, [auto_delete: true]),
+         from_clients <- [routing_key: "bot.#{device}.from_clients"],
+         sync         <- [routing_key: "bot.#{device}.sync.#"],
+         :ok          <- AMQP.Queue.bind(chan, q_name, @exchange, from_clients),
+         :ok          <- AMQP.Queue.bind(chan, q_name, @exchange, sync),
+         {:ok, _tag}  <- Basic.consume(chan, q_name),
+         opts      <- [conn: conn, chan: chan, queue_name: q_name, bot: device],
+         state <- struct(State, opts)
     do
       # Logger.success(3, "Connected to real time services.")
       {:consumer, state, subscribe_to: [Farmbot.BotState, Farmbot.Logger]}

  defp handle_sync_cmd(kind, id, payload, state) do
    mod = Module.concat(["Farmbot", "Repo", kind])
    if Code.ensure_loaded?(mod) do
      %{"body" => body, "args" => %{"label" => uuid}} = Poison.decode!(payload, as: %{"body" => struct(mod)})
      Farmbot.Repo.register_sync_cmd(String.to_integer(id), kind, body)

      if Farmbot.System.ConfigStorage.get_config_value(:bool, "settings", "auto_sync") do
        Farmbot.Repo.flip()
      end

      Farmbot.CeleryScript.AST.Node.RpcOk.execute(%{label: uuid}, [], struct(Macro.Env))
    else
      Logger.warn 2, "Unknown syncable: #{mod}: #{inspect Poison.decode!(payload)}"
    end
    {:noreply, [], state}
  end

  end

  defp emit_cs(chan, bot, cs) do
    with {:ok, map} <- AST.encode(cs),
         {:ok, json} <- Poison.encode(map)
    do
      :ok = AMQP.Basic.publish chan, @exchange, "bot.#{bot}.from_device", json
