smartrent / grizzly

Elixir Z-Wave Library

Home Page:https://hex.pm/packages/grizzly

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

CRC

mattludwigs opened this issue · comments

We don't need to rely on the CRC package as most of it is not really needed for what we do in Grizzly.

Below is the example code to bring into Grizzly and replace the CRC package.

defmodule NewCRC2.Table do
  use Bitwisedef ccitt_table(poly) do
    table =
      for i <- 0..255 do
        ccitt_entry(i <<< 8, 0, 0, poly)
      end
​
    List.to_tuple(table)
  enddefp ccitt_entry(_, crc, 8, _), do: crc &&& 0xFFFFdefp ccitt_entry(c, crc, bc, poly) do
    next_crc = if (crc ^^^ c &&& 0x8000) > 0, do: (crc <<< 1) ^^^ poly, else: crc <<< 1ccitt_entry(c <<< 1, next_crc, bc + 1, poly)
  end


defmodule NewCRC2 do
  @compile :native
  @compile {:hipe, [:o3]}use Bitwise@table NewCRC2.Table.ccitt_table(0x1021)@type uint16 :: 0..65535@doc """
  CRC-16/AUG-CCITT
  """
  @spec crc16_aug_ccitt(binary() | [byte()]) :: uint16
  def crc16_aug_ccitt(data) when is_binary(data) do
    data
    |> :binary.bin_to_list()
    |> crc16_aug_ccitt()
  enddef crc16_aug_ccitt(data) when is_list(data) do
    crc_ccitt(data, 0x1D0F)
  enddefp crc_ccitt([x | rem], crc) do
    index = (crc >>> 8) ^^^ x
    crc = (crc <<< 8) ^^^ elem(@table, index) &&& 0xFFFF
    crc_ccitt(rem, crc)
  enddefp crc_ccitt([], crc), do: crc
end