class Device::Crypto

Constants

CCITT_16

Public Class Methods

adapter() click to toggle source
# File lib/device/crypto.rb, line 6
def self.adapter
  if Device.adapter && Device.adapter.const_defined?(:Crypto)
    Device.adapter::Crypto
  end
end
crc16(buf, crc=0) click to toggle source
# File lib/device/crypto.rb, line 54
def self.crc16(buf, crc=0)
  if self.adapter.respond_to? :crc16
    self.adapter.crc16(buf, crc)
  else
    buf.each_byte{|x| crc = ((crc<<8) ^ CCITT_16[(crc>>8) ^ x])&0xffff}
    crc
  end
end
crc16_hex(buf) click to toggle source
# File lib/device/crypto.rb, line 47
def self.crc16_hex(buf)
  crc = crc16(buf)
  # to swap the number just invert the order of the indexes [0..1] and [2..3]
  #"#{crc.to_s(16).rjust(4,"0")[0..1]}#{crc.to_s(16).rjust(4,"0")[2..3]}".upcase
  rjust(crc.to_s(16).upcase, 4, "0")
end
file_crc16_hex(path) click to toggle source
# File lib/device/crypto.rb, line 63
def self.file_crc16_hex(path)
  if File.exists?(path) && (len = File.size(path))
    if len > 500_000
      crc = 0
      File.open(path) do |file|
        loop do
          break unless buf = file.read(10_000)
          crc = self.crc16(buf, crc)
        end
      end
      rjust(crc.to_s(16).upcase, 4, "0")
    else
      crc16_hex(File.read(path))
    end
  else
    "0000"
  end
ensure
  GC.start
end