|
| 1 | +defmodule NervesHub.AWSIoT do |
| 2 | + @moduledoc """ |
| 3 | + Support for common AWS IOT infrastructure including MQTT and SQS |
| 4 | +
|
| 5 | + Requires `:queues` to be defined in the application config or |
| 6 | + the supervisor is simply ignored |
| 7 | +
|
| 8 | + See docs.nerves-hub.org for a general overview of the architecture |
| 9 | + """ |
| 10 | + use Supervisor |
| 11 | + |
| 12 | + @type opt :: {:queues, [keyword()]} |
| 13 | + @spec start_link([opt]) :: Supervisor.on_start() |
| 14 | + def start_link(opts) do |
| 15 | + Supervisor.start_link(__MODULE__, opts, name: __MODULE__) |
| 16 | + end |
| 17 | + |
| 18 | + @impl Supervisor |
| 19 | + def init(opts) do |
| 20 | + opts = |
| 21 | + Application.get_env(:nerves_hub, __MODULE__, []) |
| 22 | + |> Keyword.merge(opts) |
| 23 | + |
| 24 | + case opts[:queues] do |
| 25 | + queues when is_list(queues) and length(queues) > 0 -> |
| 26 | + children = |
| 27 | + Enum.map(queues, &{__MODULE__.SQS, &1}) |
| 28 | + |> maybe_add_local_broker(opts) |
| 29 | + |
| 30 | + Supervisor.init(children, strategy: :one_for_one) |
| 31 | + |
| 32 | + _ -> |
| 33 | + :ignore |
| 34 | + end |
| 35 | + end |
| 36 | + |
| 37 | + defp maybe_add_local_broker(children, opts) do |
| 38 | + if broker_spec = opts[:local_broker] do |
| 39 | + [broker_spec | children] |
| 40 | + else |
| 41 | + children |
| 42 | + end |
| 43 | + end |
| 44 | + |
| 45 | + if Application.compile_env(:nerves_hub, [__MODULE__, :local_broker], false) do |
| 46 | + def publish(serial, event, payload) do |
| 47 | + data = Jason.encode!(%{event: event, payload: payload}) |
| 48 | + PintBroker.publish(__MODULE__.PintBroker, "nh/#{serial}", data) |
| 49 | + end |
| 50 | + else |
| 51 | + def publish(serial, event, payload) do |
| 52 | + # TODO: Topic and data may change soon |
| 53 | + # Stubbing out initial idea here for now |
| 54 | + data = %{event: event, payload: payload} |
| 55 | + topic = "/topics/nh/#{serial}" |
| 56 | + |
| 57 | + ExAws.Operation.JSON.new(:iot_data, %{path: topic, data: data}) |
| 58 | + |> ExAws.request() |
| 59 | + end |
| 60 | + end |
| 61 | + |
| 62 | + defmodule SQS do |
| 63 | + @moduledoc """ |
| 64 | + Consumer for AWS SQS messages |
| 65 | +
|
| 66 | + This is the ingestion point of devices coming from the MQTT |
| 67 | + broker. A message from a device must include the `"identifier"` |
| 68 | + key either in the payload or pulled from the topic via the |
| 69 | + AWS IoT rule that forwards to the queue. |
| 70 | +
|
| 71 | + The system must also be setup with a rule to forward [AWS Lifecycle |
| 72 | + events](https://docs.aws.amazon.com/iot/latest/developerguide/life-cycle-events.html) |
| 73 | + to a queue for tracking device online/offline presence |
| 74 | +
|
| 75 | + Right now, all configured queues are handled by this module. |
| 76 | + In the future, we may want to separate handling for each |
| 77 | + queue in it's own module. |
| 78 | + """ |
| 79 | + use Broadway |
| 80 | + |
| 81 | + alias Broadway.Message |
| 82 | + alias NervesHub.Devices |
| 83 | + alias NervesHub.Devices.DeviceLink |
| 84 | + |
| 85 | + require Logger |
| 86 | + |
| 87 | + def start_link(opts), do: Broadway.start_link(__MODULE__, opts) |
| 88 | + |
| 89 | + @impl Broadway |
| 90 | + def handle_message(_processor, %{data: raw} = msg, _context) do |
| 91 | + case Jason.decode(raw) do |
| 92 | + {:ok, data} -> |
| 93 | + Message.put_data(msg, data) |
| 94 | + |> process_message() |
| 95 | + |
| 96 | + _ -> |
| 97 | + Message.failed(msg, :malformed) |
| 98 | + end |
| 99 | + end |
| 100 | + |
| 101 | + @impl Broadway |
| 102 | + def handle_batch(_batcher, messages, batch_info, _context) do |
| 103 | + Logger.debug("[SQS] Handled #{inspect(batch_info.size)}") |
| 104 | + messages |
| 105 | + end |
| 106 | + |
| 107 | + defp process_message(%{data: %{"eventType" => "connected"} = data} = msg) do |
| 108 | + # TODO: Maybe use more info from the connection? |
| 109 | + # Example payload of AWS lifecycle connected event |
| 110 | + # principalIdentifier is a SHA256 fingerprint of the certificate that |
| 111 | + # is Base16 encoded |
| 112 | + # { |
| 113 | + # "clientId": "186b5", |
| 114 | + # "timestamp": 1573002230757, |
| 115 | + # "eventType": "connected", |
| 116 | + # "sessionIdentifier": "a4666d2a7d844ae4ac5d7b38c9cb7967", |
| 117 | + # "principalIdentifier": "12345678901234567890123456789012", |
| 118 | + # "ipAddress": "192.0.2.0", |
| 119 | + # "versionNumber": 0 |
| 120 | + # } |
| 121 | + |
| 122 | + with {:ok, device} <- Devices.get_by_identifier(data["clientId"]), |
| 123 | + push_cb = &NervesHub.AWSIoT.publish(device.identifier, &1, &2), |
| 124 | + # TODO: Adjust DeviceLink for this since we won't have |
| 125 | + # metadata at this point |
| 126 | + {:ok, _device} <- DeviceLink.connect(device, push_cb, %{}) do |
| 127 | + msg |
| 128 | + else |
| 129 | + _ -> |
| 130 | + Message.failed(msg, :unknown_device) |
| 131 | + end |
| 132 | + end |
| 133 | + |
| 134 | + defp process_message(%{data: %{"eventType" => "disconnected"} = data} = msg) do |
| 135 | + # TODO: Maybe use more of the disconnect data? |
| 136 | + # Example payload of AWS lifecyle disconnect event |
| 137 | + # { |
| 138 | + # "clientId": "186b5", |
| 139 | + # "timestamp": 1573002340451, |
| 140 | + # "eventType": "disconnected", |
| 141 | + # "sessionIdentifier": "a4666d2a7d844ae4ac5d7b38c9cb7967", |
| 142 | + # "principalIdentifier": "12345678901234567890123456789012", |
| 143 | + # "clientInitiatedDisconnect": true, |
| 144 | + # "disconnectReason": "CLIENT_INITIATED_DISCONNECT", |
| 145 | + # "versionNumber": 0 |
| 146 | + # } |
| 147 | + with {:ok, device} <- Devices.get_by_identifier(data["clientId"]) do |
| 148 | + # TODO: Update DeviceLink.disconect with reason and track? |
| 149 | + Logger.debug( |
| 150 | + "[AWS IoT] device #{data["clientId"]} disconnected: #{data["disconnectReason"]}" |
| 151 | + ) |
| 152 | + |
| 153 | + DeviceLink.disconnect(device) |
| 154 | + end |
| 155 | + |
| 156 | + msg |
| 157 | + end |
| 158 | + |
| 159 | + defp process_message(msg) do |
| 160 | + # TODO: Track unhandled msg |
| 161 | + msg |
| 162 | + end |
| 163 | + end |
| 164 | +end |
0 commit comments