Skip to content

Commit

Permalink
1-Wire: bitwise operations, matching mruby for compatibility
Browse files Browse the repository at this point in the history
  • Loading branch information
vickash committed Oct 26, 2024
1 parent 7afc823 commit 326b014
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 11 deletions.
13 changes: 4 additions & 9 deletions lib/denko/one_wire/bus_enumerator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -44,17 +44,14 @@ def search
def parse_search_result(result)
address, complement = split_search_result(result)

if (address & complement) > 0
raise "OneWire device not connected or disconnected during search"
end

raise "OneWire device not connected, or disconnected during search" if (address & complement) > 0
raise "CRC error during OneWire search" unless Helper.crc(address)

# Gives 0 at every discrepancy we didn't write 1 for on this search.
new_discrepancies = address ^ complement

high_discrepancy = -1
(0..63).each { |i| high_discrepancy = i if new_discrepancies[i] == 0 }
(0..63).each { |i| high_discrepancy = i if ((new_discrepancies >> i) & 0b1 == 0) }

# LSByte of address is product family.
klass = family_lookup(address & 0xFF)
Expand All @@ -64,14 +61,12 @@ def parse_search_result(result)

# Result is 16 bytes, 8 byte address and complement interleaved LSByte first.
def split_search_result(data)
address = 0
address = 0
complement = 0

data.reverse.each_slice(2) do |comp_byte, addr_byte|
address = (address << 8) | addr_byte
address = (address << 8) | addr_byte
complement = (complement << 8) | comp_byte
end

[address, complement]
end

Expand Down
6 changes: 4 additions & 2 deletions lib/denko/one_wire/helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ module Denko
module OneWire
class Helper
def self.address_to_bytes(address)
[address].pack('Q<').split("").map(&:ord)
bytes = []
8.times { |i| bytes[i] = address >> (8*i) & 0xFF }
bytes
end

def self.crc(data)
Expand All @@ -20,7 +22,7 @@ def self.calculate_crc(data)
crc = 0b00000000
bytes.take(bytes.length - 1).each do |byte|
for bit in (0..7)
xor = byte[bit] ^ crc[0]
xor = ((byte >> bit) & 0b1) ^ (crc & 0b1)
crc = crc ^ ((xor * (2 ** 3)) | (xor * (2 ** 4)))
crc = crc >> 1
crc = crc | (xor * (2 ** 7))
Expand Down

0 comments on commit 326b014

Please sign in to comment.