Skip to content

Commit c4b7ced

Browse files
committed
Use a Task to isolate zbar Port response messages
1 parent 7e2331f commit c4b7ced

File tree

1 file changed

+15
-2
lines changed

1 file changed

+15
-2
lines changed

lib/zbar.ex

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,22 @@ defmodule Zbar do
1414
{:error, string} if there was an error in the scanning process
1515
"""
1616
def scan(jpeg_data, timeout \\ 2000) do
17+
# We run this is a `Task` so that `collect_output` can use `receive`
18+
# without interfering with the caller's mailbox.
19+
Task.async(fn ->
20+
write_image_to_temp_file(jpeg_data)
21+
open_zbar_port()
22+
|> collect_output(timeout)
23+
|> format_result()
24+
end)
25+
|> Task.await(:infinity)
26+
end
27+
28+
defp write_image_to_temp_file(jpeg_data) do
1729
File.open!(temp_file(), [:write, :binary], & IO.binwrite(&1, jpeg_data))
30+
end
31+
32+
defp open_zbar_port do
1833
{:spawn_executable, zbar_binary()}
1934
|> Port.open([
2035
{:args, [temp_file()]},
@@ -24,8 +39,6 @@ defmodule Zbar do
2439
:use_stdio,
2540
:stderr_to_stdout
2641
])
27-
|> collect_output(timeout)
28-
|> format_result()
2942
end
3043

3144
defp temp_file, do: Path.join(System.tmp_dir!(), "zbar_image.jpg")

0 commit comments

Comments
 (0)