Class: Denko::Sensor::DHT

Inherits:
Object
  • Object
show all
Includes:
Behaviors::Poller, Behaviors::SinglePin
Defined in:
lib/denko/sensor/dht.rb

Instance Attribute Summary

Attributes included from Behaviors::Threaded

#interrupts_enabled, #thread

Attributes included from Behaviors::Callbacks

#callback_mutex

Attributes included from Behaviors::SinglePin

#mode, #pin

Attributes included from Behaviors::Component

#board

Instance Method Summary collapse

Methods included from Behaviors::Poller

#poll, #poll_using, #stop

Methods included from Behaviors::Threaded

#enable_interrupts, included, #stop, #stop_thread, #threaded, #threaded_loop

Methods included from Behaviors::Reader

#read, #read_using, #wait_for_read

Methods included from Behaviors::Callbacks

#add_callback, #callbacks, #initialize, #remove_callback, #update

Methods included from Behaviors::State

#initialize, #state

Methods included from Behaviors::Component

#initialize, #micro_delay

Instance Method Details

#_readObject



7
8
9
# File 'lib/denko/sensor/dht.rb', line 7

def _read
  board.pulse_read(pin, reset: board.low, reset_time: 20000, pulse_limit: 84, timeout: 100)
end

#crc(bytes) ⇒ Object



38
39
40
# File 'lib/denko/sensor/dht.rb', line 38

def crc(bytes)
  bytes[0..3].reduce(0, :+) & 0xFF == bytes[4]
end

#decode(data) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/denko/sensor/dht.rb', line 15

def decode(data)
  data = data.last(81)
  return { error: 'missing data' } unless data.length == 81
  data = data[0..79]

  bytes = []
  data.each_slice(16) do |b|
    byte = 0b00000000
    b.each_slice(2) do |x,y|
      bit = (y<x) ? 0 : 1
      byte = (byte << 1) | bit
    end
    bytes << byte
  end
  return { error: 'CRC failure' } unless crc(bytes)

  celsius   = ((bytes[2] << 8) | bytes[3]).to_f / 10
  humidity  = ((bytes[0] << 8) | bytes[1]).to_f / 10
  fahrenheit = (celsius * 1.8 + 32).round(1)

  { celsius: celsius, fahrenheit: fahrenheit, humidity: humidity }
end

#pre_callback_filter(data) ⇒ Object



11
12
13
# File 'lib/denko/sensor/dht.rb', line 11

def pre_callback_filter(data)
  decode(data.split(",").map(&:to_i))
end