ya_gpio 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/README.md ADDED
@@ -0,0 +1,86 @@
1
+ # Yet Another GPIO gem for Raspberry Pi
2
+
3
+ ## But why ?
4
+
5
+ Because making a new wheel is always fun !
6
+
7
+ There is already plenty of GPIO libraries for Raspberry Pi :
8
+
9
+ - some using plain C : [c_GPIO](https://github.com/hujiko/c_GPIO)
10
+ - some using the BCM C libs : [rpi_gpio](https://github.com/ClockVapor/rpi_gpio)
11
+ - some small ones using Sysfs : [ruby-gpio](https://github.com/sausheong/ruby-gpio), [gpio](https://github.com/klappy/gpio), [raspi-gpio-rb](https://github.com/exybore/raspi-gpio-rb)
12
+ - some big ones based on EventMachine : [pi_piper](https://github.com/jwhitehorn/pi_piper), [em-gpio](https://github.com/railsbob/em-gpio)
13
+
14
+ But none of them support interruptions to trigger events. I mean proper interruption without pooling within an infinite loop (and sometimes a sleep).
15
+ For example, _rpi-gpio_ gem is very good but the `wait_for_edge()` method is not available (yet).
16
+
17
+ This implementation is based on the Sysfs interface and so do not support integrated pull-down an pull-up resistors.
18
+ See [official kernel documentation](https://www.kernel.org/doc/Documentation/gpio/sysfs.txt) for more details.
19
+
20
+ NOTE: The pin number specified in the initializer uses *BCM numbering*.
21
+
22
+ ## Permissions
23
+
24
+ Please note that lib require read/write access to the GPIO Sysfs subdirectory `/sys/class/gpio/`. If your script is not running as root, add your user to the `gpio` group.
25
+ On most Raspberry Pi compatible distributions, an UDEV event will automatically set proper permissions once the port is exported.
26
+
27
+ ## Using interruptions
28
+
29
+ The implementation of the interrupt hander is based on Sysfs and uses the select(2) syscall, according to the offical linux kernel documentation. You can find an example in C here : [Attentes passives sur GPIO](https://www.blaess.fr/christophe/2013/04/15/attentes-passives-sur-gpio/).
30
+
31
+ Another implementation using poll(2) in ruby : [Evented GPIO on Raspberry PI with Ruby](https://tenderlovemaking.com/2017/01/17/evented-gpio-on-raspberry-pi-with-ruby.html)
32
+
33
+ ### Example
34
+
35
+ ```ruby
36
+ require 'ya_gpio'
37
+
38
+ led = YaGPIO.new(23, YaGPIO::OUTPUT)
39
+ button1 = YaGPIO.new(22, YaGPIO::INPUT)
40
+ button2 = YaGPIO.new(25, YaGPIO::INPUT)
41
+
42
+ # Turn the led on when button 1 is pressed and
43
+ # off when released
44
+ button1.set_interrupt(YaGPIO::EDGE_BOTH) do |high|
45
+ if high
46
+ led.high
47
+ else
48
+ led.low
49
+ end
50
+ end
51
+
52
+ # Stop the wait() loop when button 2 is pressed
53
+ button2.set_interrupt(YaGPIO::EDGE_RISING) do |high|
54
+ YaGPIO::resume
55
+ end
56
+
57
+ puts "ready"
58
+ YaGPIO::wait([button1, button2])
59
+ puts "wait() loop terminated"
60
+
61
+ ```
62
+
63
+ If your application needs to listen to other file descriptors, you can override the `wait()` method to include those FDs in the `select()` call. See `lib/ya_gpio.rb` source file for more information.
64
+
65
+
66
+ ## Testing
67
+
68
+ This module is fully tested on Raspberry Pi and has testing with rspec. To run them :
69
+
70
+ ```
71
+ bundle install
72
+ bundle exec rake spec
73
+ ```
74
+
75
+ ## API documentation
76
+
77
+ The API documentation is available in the Yard format. To generate it under the `doc` directory, run :
78
+
79
+ ```
80
+ bundle exec rake yard
81
+ ```
82
+
83
+ ## License
84
+
85
+ Copyleft 2019 - Nicolas AGIUS - GNU GPLv3
86
+
data/Rakefile ADDED
@@ -0,0 +1,11 @@
1
+ require 'rspec/core/rake_task'
2
+ require 'bundler/gem_tasks'
3
+ require 'yard'
4
+
5
+ YARD::Rake::YardocTask.new do |t|
6
+ t.files = ['lib/*.rb']
7
+ t.stats_options = ['--list-undoc']
8
+ end
9
+
10
+ RSpec::Core::RakeTask.new(:spec)
11
+
data/lib/ya_gpio.rb ADDED
@@ -0,0 +1,242 @@
1
+ # YaGPIO - Yet Another GPIO module for Raspberry Pi
2
+ # Copyleft 2019 - Nicolas AGIUS <nicolas.agius@lps-it.fr>
3
+
4
+ ###########################################################################
5
+ #
6
+ # This program is free software: you can redistribute it and/or modify
7
+ # it under the terms of the GNU General Public License as published by
8
+ # the Free Software Foundation, either version 3 of the License, or
9
+ # (at your option) any later version.
10
+ #
11
+ # This program is distributed in the hope that it will be useful,
12
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
13
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
+ # GNU General Public License for more details.
15
+ #
16
+ # You should have received a copy of the GNU General Public License
17
+ # along with this program. If not, see <http://www.gnu.org/licenses/>.
18
+ #
19
+ ###########################################################################
20
+
21
+ # YaGPIO is a simple module to control GPIO port on a Raspberry Pi.
22
+ # It's based on the Sysfs interface.
23
+ #
24
+ # @example Open port 22 as output and set it to high
25
+ # pin = YaGPIO.new(22, YaGPIO::OUTPUT)
26
+ # pin.high
27
+ #
28
+ # @example Open port 23 as input and read its state
29
+ # pin = YaGPIO.new(23, YaGPIO::INPUT)
30
+ # pp pin.low?
31
+ #
32
+ class YaGPIO
33
+ # File descriptor to the sysfs entry of the pin. It is not recommended to access the file
34
+ # directly. Use high() lov() helpers instead.
35
+ attr_reader :file
36
+
37
+ # Direction input
38
+ INPUT = 'in'
39
+
40
+ # Direction output with default low
41
+ OUTPUT = 'out'
42
+
43
+ # Direction output with default high
44
+ OUTPUT_HIGH = 'high'
45
+
46
+ # Interruption on rising edge
47
+ EDGE_RISING = 'rising'
48
+
49
+ # Interruption on falling edge
50
+ EDGE_FALLING = 'falling'
51
+
52
+ # Interruption on rising and falling edge
53
+ EDGE_BOTH = 'both'
54
+
55
+ # Disable interruption
56
+ EDGE_NONE = 'none'
57
+
58
+
59
+ # Create and configure a new GPIO pin. The pin will be _exported_ via the sysfs interface.
60
+ # The pin will be _unexported_ and released for other use upon garbage collection.
61
+ #
62
+ # @param pin [Integer] Pin number to configure, using the BCM numbering
63
+ # @param direction [String] The direction if the port. Must be one of INPUT, OUTPUT or OUTPUT_HIGH
64
+ def initialize(pin, direction)
65
+ raise 'direction must be one of INPUT, OUTPUT, OUTPUT_HIGH' unless [INPUT, OUTPUT, OUTPUT_HIGH].include?(direction)
66
+
67
+ @pin = pin
68
+ @callback = nil
69
+ @direction = direction
70
+
71
+ export
72
+ open
73
+
74
+ ObjectSpace.define_finalizer(self, self.class.finalize(@pin))
75
+ end
76
+
77
+
78
+ # Return true if the pin is high
79
+ #
80
+ # @return [Boolean] State of the pin
81
+ def high?
82
+ read() != 0
83
+ end
84
+
85
+ # Return true if the pin is low
86
+ #
87
+ # @return [Boolean] State of the pin
88
+ def low?
89
+ read() == 0
90
+ end
91
+
92
+ # Set the pin to high
93
+ def high
94
+ write(1)
95
+ end
96
+
97
+ # Set the pin to low
98
+ def low
99
+ write(0)
100
+ end
101
+
102
+ # Invert all values and settings. After set to true, HIGH means LOW and LOW means HIGH.
103
+ # Be prepared to be confused if you're using this feature.
104
+ #
105
+ # @param active [Boolean] Feature state
106
+ def active_low=(active)
107
+ File.write("/sys/class/gpio/gpio#{@pin}/active_low", active ? '1' : '0')
108
+ end
109
+
110
+ # Return true is active_low feature is enabled
111
+ #
112
+ # @return [Boolean] Feature state
113
+ def active_low?
114
+ File.read("/sys/class/gpio/gpio#{@pin}/active_low") != '0'
115
+ end
116
+
117
+ # Define a callback to execute when an interruption will be triggered.
118
+ #
119
+ # @param edge [String] Edge to trigger interrution. Can be EDGE_RISING, EDGE_FALLING or EDGE_BOTH
120
+ # @param block [Block] Block to execute as callback
121
+ def set_interrupt(edge, &block)
122
+ raise 'interrupt can only be set on input pin' unless @direction == INPUT
123
+
124
+ set_edge(edge)
125
+ @callback = block
126
+ end
127
+
128
+ # Disable a previously set interruption
129
+ def clear_interrupt()
130
+ set_edge(EDGE_NONE)
131
+ @callback = nil
132
+ end
133
+
134
+ # Execute the interruption's callback.
135
+ #
136
+ # @param active [Boolean] Should be true if the pin is high
137
+ def trigger(active)
138
+ if @callback.nil?
139
+ puts "No Callback defined for #{@pin}"
140
+ else
141
+ @callback.call(active)
142
+ end
143
+ end
144
+
145
+ # Release the pin.
146
+ # The object cannot be used after this method is called as the pin will not be configured anymore.
147
+ def unexport()
148
+ @file.close
149
+ File.write('/sys/class/gpio/unexport', @pin.to_s)
150
+ end
151
+
152
+ alias :close :unexport
153
+
154
+ # Wait for an interruption to be trigerred and run the associated callback.
155
+ # This method will block until the program exits or YaGPIO::resume() is called from a callback.
156
+ #
157
+ # Note that software debounce has not been implemented.
158
+ # You can use a 1µF capacitor in your setup to fix bounce issues.
159
+ #
160
+ # @param gpios [Array] Array of YaGPIO to monitor
161
+ def self.wait(gpios)
162
+ # Initial read to clear interrupt triggered during setup
163
+ gpios.map{|g| g.high?}
164
+
165
+ @@wait = true
166
+ while @@wait do
167
+ rs, ws, es = IO.select(nil, nil, gpios.map{|g| g.file})
168
+
169
+ es.each do |f|
170
+ gpio = gpios.select{|g| g.file == f}.first
171
+ gpio.trigger(gpio.high?)
172
+ end
173
+ end
174
+ end
175
+
176
+ # Stop the wait loop, must be run from a callback triggered by YaGPIO::wait()
177
+ def self.resume
178
+ @@wait = false
179
+ end
180
+
181
+ private
182
+
183
+ MAX_RETRY = 3 # Number of retries when openning the sysfs file
184
+ @@wait = true # Flag to enable the wait infinite loop
185
+
186
+ def export()
187
+ begin
188
+ File.write('/sys/class/gpio/export', @pin.to_s)
189
+ rescue Errno::EBUSY
190
+ puts "WARNING: GPIO #{@pin} is already exported, may be in use."
191
+ end
192
+ end
193
+
194
+ def open
195
+ begin
196
+ retries ||= 0
197
+ case @direction
198
+ when INPUT
199
+ @file=File.open("/sys/class/gpio/gpio#{@pin}/value", 'r')
200
+ else
201
+ @file=File.open("/sys/class/gpio/gpio#{@pin}/value", 'r+')
202
+ end
203
+
204
+ @file.sync=true # Auto flush
205
+ File.write("/sys/class/gpio/gpio#{@pin}/direction", @direction)
206
+ rescue Errno::EACCES
207
+ if (retries += 1) <= MAX_RETRY
208
+ puts "Permission on sysfs not ready yet, retrying (#{retries}/#{MAX_RETRY})..."
209
+ sleep 0.1
210
+ retry
211
+ end
212
+
213
+ raise
214
+ end
215
+ end
216
+
217
+ def set_edge(edge)
218
+ raise 'edge must be one of EDGE_RISING, EDGE_FALLING, EDGE_BOTH, EDGE_NONE' unless [EDGE_RISING, EDGE_FALLING, EDGE_BOTH, EDGE_NONE].include?(edge)
219
+
220
+ File.write("/sys/class/gpio/gpio#{@pin}/edge", edge)
221
+ end
222
+
223
+ def read()
224
+ @file.seek(0, IO::SEEK_SET)
225
+ @file.read().to_i
226
+ end
227
+
228
+ def write(value)
229
+ @file.seek(0, IO::SEEK_SET)
230
+ @file.write(value)
231
+ end
232
+
233
+ # Unexport the port when the program exits
234
+ def self.finalize(pin)
235
+ proc do
236
+ File.write('/sys/class/gpio/unexport', pin)
237
+ end
238
+ end
239
+
240
+ end
241
+
242
+ # vim: ts=4:sw=4:ai
@@ -0,0 +1,3 @@
1
+ class YaGPIO
2
+ VERSION = "0.1.0"
3
+ end
@@ -0,0 +1,108 @@
1
+ # This file was generated by the `rspec --init` command. Conventionally, all
2
+ # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
3
+ # The generated `.rspec` file contains `--require spec_helper` which will cause
4
+ # this file to always be loaded, without a need to explicitly require it in any
5
+ # files.
6
+ #
7
+ # Given that it is always loaded, you are encouraged to keep this file as
8
+ # light-weight as possible. Requiring heavyweight dependencies from this file
9
+ # will add to the boot time of your test suite on EVERY test run, even for an
10
+ # individual file that may not need all of that loaded. Instead, consider making
11
+ # a separate helper file that requires the additional dependencies and performs
12
+ # the additional setup, and require it from the spec files that actually need
13
+ # it.
14
+ #
15
+ # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
16
+
17
+ require 'bundler/setup'
18
+ Bundler.setup
19
+
20
+ require 'ya_gpio'
21
+ require 'pp' # Conflict with fakefs, need to be required before fakefs
22
+ require 'fakefs/spec_helpers'
23
+
24
+ RSpec.configure do |config|
25
+ # rspec-expectations config goes here. You can use an alternate
26
+ # assertion/expectation library such as wrong or the stdlib/minitest
27
+ # assertions if you prefer.
28
+ config.expect_with :rspec do |expectations|
29
+ # This option will default to `true` in RSpec 4. It makes the `description`
30
+ # and `failure_message` of custom matchers include text for helper methods
31
+ # defined using `chain`, e.g.:
32
+ # be_bigger_than(2).and_smaller_than(4).description
33
+ # # => "be bigger than 2 and smaller than 4"
34
+ # ...rather than:
35
+ # # => "be bigger than 2"
36
+ expectations.include_chain_clauses_in_custom_matcher_descriptions = true
37
+ end
38
+
39
+ # rspec-mocks config goes here. You can use an alternate test double
40
+ # library (such as bogus or mocha) by changing the `mock_with` option here.
41
+ config.mock_with :rspec do |mocks|
42
+ # Prevents you from mocking or stubbing a method that does not exist on
43
+ # a real object. This is generally recommended, and will default to
44
+ # `true` in RSpec 4.
45
+ mocks.verify_partial_doubles = true
46
+ end
47
+
48
+ # This option will default to `:apply_to_host_groups` in RSpec 4 (and will
49
+ # have no way to turn it off -- the option exists only for backwards
50
+ # compatibility in RSpec 3). It causes shared context metadata to be
51
+ # inherited by the metadata hash of host groups and examples, rather than
52
+ # triggering implicit auto-inclusion in groups with matching metadata.
53
+ config.shared_context_metadata_behavior = :apply_to_host_groups
54
+
55
+ # The settings below are suggested to provide a good initial experience
56
+ # with RSpec, but feel free to customize to your heart's content.
57
+ =begin
58
+ # This allows you to limit a spec run to individual examples or groups
59
+ # you care about by tagging them with `:focus` metadata. When nothing
60
+ # is tagged with `:focus`, all examples get run. RSpec also provides
61
+ # aliases for `it`, `describe`, and `context` that include `:focus`
62
+ # metadata: `fit`, `fdescribe` and `fcontext`, respectively.
63
+ config.filter_run_when_matching :focus
64
+
65
+ # Allows RSpec to persist some state between runs in order to support
66
+ # the `--only-failures` and `--next-failure` CLI options. We recommend
67
+ # you configure your source control system to ignore this file.
68
+ config.example_status_persistence_file_path = "spec/examples.txt"
69
+
70
+ # Limits the available syntax to the non-monkey patched syntax that is
71
+ # recommended. For more details, see:
72
+ # - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/
73
+ # - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
74
+ # - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode
75
+ config.disable_monkey_patching!
76
+
77
+ # This setting enables warnings. It's recommended, but in some cases may
78
+ # be too noisy due to issues in dependencies.
79
+ config.warnings = true
80
+
81
+ # Many RSpec users commonly either run the entire suite or an individual
82
+ # file, and it's useful to allow more verbose output when running an
83
+ # individual spec file.
84
+ if config.files_to_run.one?
85
+ # Use the documentation formatter for detailed output,
86
+ # unless a formatter has already been configured
87
+ # (e.g. via a command-line flag).
88
+ config.default_formatter = "doc"
89
+ end
90
+
91
+ # Print the 10 slowest examples and example groups at the
92
+ # end of the spec run, to help surface which specs are running
93
+ # particularly slow.
94
+ config.profile_examples = 10
95
+
96
+ # Run specs in random order to surface order dependencies. If you find an
97
+ # order dependency and want to debug it, you can fix the order by providing
98
+ # the seed, which is printed after each run.
99
+ # --seed 1234
100
+ config.order = :random
101
+
102
+ # Seed global randomization in this process using the `--seed` CLI option.
103
+ # Setting this allows you to use `--seed` to deterministically reproduce
104
+ # test failures related to randomization by passing the same `--seed` value
105
+ # as the one that triggered the failure.
106
+ Kernel.srand config.seed
107
+ =end
108
+ end