Skip to content

Commit e9f62ec

Browse files
committed
Raise ArgumentErrors with help on incorrect GPIO.open call
This addresses some confusion when `:write` was passed rather than `:output` for the second parameter. Raising ArgumentError with the allowed values saves a look at the docs. This also does something similar with the gpio spec.
1 parent e50daea commit e9f62ec

File tree

2 files changed

+25
-3
lines changed

2 files changed

+25
-3
lines changed

lib/gpio.ex

+17-3
Original file line numberDiff line numberDiff line change
@@ -239,8 +239,9 @@ defmodule Circuits.GPIO do
239239
open(gpio_spec, direction, options)
240240
end
241241

242-
def open(gpio_spec, direction, options)
243-
when is_gpio_spec(gpio_spec) and direction in [:input, :output] do
242+
def open(gpio_spec, direction, options) do
243+
check_gpio_spec!(gpio_spec)
244+
check_direction!(direction)
244245
check_options!(options)
245246

246247
{backend, backend_defaults} = default_backend()
@@ -254,14 +255,27 @@ defmodule Circuits.GPIO do
254255
backend.open(gpio_spec, direction, all_options)
255256
end
256257

258+
defp check_gpio_spec!(gpio_spec) do
259+
if not gpio_spec?(gpio_spec) do
260+
raise ArgumentError, "Invalid GPIO spec: #{inspect(gpio_spec)}"
261+
end
262+
end
263+
264+
defp check_direction!(direction) do
265+
if direction not in [:input, :output] do
266+
raise ArgumentError,
267+
"Invalid direction: #{inspect(direction)}. Options are :input or :output"
268+
end
269+
end
270+
257271
defp check_options!([]), do: :ok
258272

259273
defp check_options!([{:initial_value, value} | rest]) do
260274
case value do
261275
0 -> :ok
262276
1 -> :ok
263277
:not_set -> Logger.warning("Circuits.GPIO no longer supports :not_set for :initial_value")
264-
_ -> raise(ArgumentError, ":initial_value should be :not_set, 0, or 1")
278+
_ -> raise ArgumentError, ":initial_value should be :not_set, 0, or 1"
265279
end
266280

267281
check_options!(rest)

test/circuits_gpio_test.exs

+8
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,14 @@ defmodule Circuits.GPIOTest do
233233
GPIO.close(gpio)
234234
end
235235

236+
test "raises argument error on invalid gpio_spec" do
237+
assert_raise ArgumentError, fn -> GPIO.open(:invalid_gpio_spec, :output) end
238+
end
239+
240+
test "raises argument error on invalid direction" do
241+
assert_raise ArgumentError, fn -> GPIO.open({@gpiochip, 0}, :bogus) end
242+
end
243+
236244
test "ignores unknown open options" do
237245
{:ok, gpio} = GPIO.open({@gpiochip, 1}, :input, bogus: true)
238246
GPIO.close(gpio)

0 commit comments

Comments
 (0)