diff --git a/lib/denko/one_wire/bus_enumerator.rb b/lib/denko/one_wire/bus_enumerator.rb index 9988bd0..0dc1288 100644 --- a/lib/denko/one_wire/bus_enumerator.rb +++ b/lib/denko/one_wire/bus_enumerator.rb @@ -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) @@ -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 diff --git a/lib/denko/one_wire/helper.rb b/lib/denko/one_wire/helper.rb index 7b45026..f976a36 100644 --- a/lib/denko/one_wire/helper.rb +++ b/lib/denko/one_wire/helper.rb @@ -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) @@ -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))