     topic_notify = "/World/Fog/1/#{pi_name}/Notify"
 
     ssl = [cacertfile: Path.join(:code.priv_dir(:doorpi), cacert_name)]
+    will_payload = Poison.encode!(%{disconnected: %{device: pi_name}})
     {:ok, pid} = :emqttc.start_link([host: host,
                                      port: port,
                                      username: un,
                                      password: pw,
                                      ssl: ssl, reconnect: {3, 120, 10},
-                                     auto_resub: true])
+                                     auto_resub: true,
+                                     will: [qos: 1, reatin: true, topic: topic_connection, payload: will_payload]])
     #Process.send_after(self(), :heart_beat, 500)
     state = %{pid: pid,
               pi_name: pi_name,

  end

  def handle_info({:publish, topic_notify, payload}, state = %{topic_notify: topic_notify}) do
    IO.puts "Received notification:"
    IO.inspect payload
    {:noreply, state}
  end

  def handle_info({:publish, unknown_topic, payload}, state) do
    IO.puts "Received:"
    IO.inspect unknown_topic
    IO.inspect payload
    {:noreply, state}
  end


  end

  defp handle_command("ping", id, pid, topic_event) do
    timestamp = DateTime.utc_now |> DateTime.to_string
    msg = %{pong: %{id: id, timestamp: timestamp}}
    msg_raw = Poison.encode!(msg)
    :emqttc.publish(pid, topic_event, msg_raw)
  end

  defp handle_command(unknown_command, _id, _pid, _topic_event) do
    Logger.warn("Unknown command: #{unknown_command}")
  end

  defp send_connected(pid, topic_connection) do
    timestamp = DateTime.utc_now |> DateTime.to_string
    boot_time = "unknown" # TODO: Try to get boot time
    addresses = "TODO" # TODO: Try to get IP-addresses
    msg = %{connected: %{boot_time: boot_time, addresses: addresses, timestamp: timestamp}}
    payload = Poison.encode!(msg)
    :emqttc.publish(pid, topic_connection, payload, [qos: 1, retain: true])
  end
end
