Module: Denko::Behaviors::Callbacks
- Includes:
- State
- Included in:
- AnalogIO::Output, Listener, Reader, DigitalIO::Output, DigitalIO::RotaryEncoder, SPI::Peripheral, UART::BitBang, UART::Hardware, UART::UARTRxPin
- Defined in:
- lib/denko/behaviors/callbacks.rb
Instance Attribute Summary collapse
-
#callback_mutex ⇒ Object
readonly
Returns the value of attribute callback_mutex.
Instance Method Summary collapse
- #add_callback(key = :persistent, &block) ⇒ Object (also: #on_data)
- #callbacks ⇒ Object
- #initialize(options = {}) ⇒ Object
-
#pre_callback_filter(data) ⇒ Object
Override to process data before giving to callbacks and state.
- #remove_callback(key = nil) ⇒ Object (also: #remove_callbacks)
- #update(data) ⇒ Object
Methods included from State
Instance Attribute Details
#callback_mutex ⇒ Object (readonly)
Returns the value of attribute callback_mutex.
5 6 7 |
# File 'lib/denko/behaviors/callbacks.rb', line 5 def callback_mutex @callback_mutex end |
Instance Method Details
#add_callback(key = :persistent, &block) ⇒ Object Also known as: on_data
17 18 19 20 21 22 |
# File 'lib/denko/behaviors/callbacks.rb', line 17 def add_callback(key=:persistent, &block) callback_mutex.synchronize do @callbacks[key] ||= [] @callbacks[key] << block end end |
#callbacks ⇒ Object
13 14 15 |
# File 'lib/denko/behaviors/callbacks.rb', line 13 def callbacks callback_mutex.synchronize { @callbacks } end |
#initialize(options = {}) ⇒ Object
7 8 9 10 11 |
# File 'lib/denko/behaviors/callbacks.rb', line 7 def initialize(={}) @callback_mutex = Mutex.new remove_callbacks super() end |
#pre_callback_filter(data) ⇒ Object
Override to process data before giving to callbacks and state.
62 63 64 |
# File 'lib/denko/behaviors/callbacks.rb', line 62 def pre_callback_filter(data) data end |
#remove_callback(key = nil) ⇒ Object Also known as: remove_callbacks
24 25 26 27 28 |
# File 'lib/denko/behaviors/callbacks.rb', line 24 def remove_callback(key=nil) callback_mutex.synchronize do key ? @callbacks.delete(key) : @callbacks = {} end end |
#update(data) ⇒ Object
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
# File 'lib/denko/behaviors/callbacks.rb', line 33 def update(data) # nil will unblock #read without running callbacks. unless data remove_callback(:read) return nil end filtered_data = pre_callback_filter(data) # nil will unblock #read without running callbacks. unless filtered_data remove_callback(:read) return nil end callback_mutex.synchronize do @callbacks.each_value do |array| array.each do |callback| callback.call(filtered_data) end end # Remove one-time callbacks added by #read. @callbacks.delete(:read) end update_state(filtered_data) end |