Packages
nerves_hub_link
2.5.2
2.12.0
2.11.1
2.11.0
retired
2.10.2
2.10.1
2.10.0
2.9.0
2.9.0-rc.3
2.9.0-rc.2
2.9.0-rc.1
2.8.1
2.8.0
2.7.3
2.7.2
2.7.0
retired
2.6.0
2.5.2
2.5.1
2.5.0
2.4.0
2.3.0
2.2.1
2.2.0
2.1.1
2.1.0
2.0.0
1.4.1
1.4.0
1.3.0
1.2.0
1.1.0
1.0.1
1.0.0
0.13.1
0.13.0
0.12.1
0.12.0
0.11.0
0.10.2
0.10.1
retired
0.10.0
retired
0.10.0-rc.0
0.9.4
0.9.3
0.9.2
0.9.1
0.9.0
0.8.2
0.8.1
0.8.0
0.7.6
Manage your Nerves fleet by connecting it to NervesHub
Current section
Files
Jump to
Current section
Files
lib/nerves_hub_link/upload_file.ex
defmodule NervesHubLink.UploadFile do
@moduledoc false
#
# Upload files in a separate process from the socket
#
use GenServer
alias NervesHubLink.Socket
defmodule State do
@type t() :: %__MODULE__{
file_path: Path.t(),
socket_pid: pid()
}
defstruct [:file_path, :socket_pid]
end
@spec start_link(Path.t(), pid()) :: GenServer.on_start()
def start_link(file_path, socket_pid) do
GenServer.start_link(__MODULE__, file_path: file_path, socket_pid: socket_pid)
end
@impl true
def init(opts) do
state = %State{
file_path: opts[:file_path],
socket_pid: opts[:socket_pid]
}
{:ok, state, {:continue, :download}}
end
@impl true
def handle_continue(:download, state) do
filename = Path.basename(state.file_path)
:ok = Socket.start_uploading(state.socket_pid, filename)
file_stream!(state)
|> Stream.with_index()
|> Stream.each(fn {chunk, index} ->
:ok = Socket.upload_data(state.socket_pid, filename, index, chunk)
end)
|> Stream.run()
:ok = Socket.finish_uploading(state.socket_pid, filename)
{:noreply, state}
end
if Version.match?(System.version(), ">= 1.16.0") do
def file_stream!(state), do: File.stream!(state.file_path, 1024, [])
else
def file_stream!(state), do: File.stream!(state.file_path, [], 1024)
end
end