#!/usr/bin/env elixir Mix.install([]) defmodule BCDTPDUTest do import Bitwise def bcd_to_binary(bcd_string, byte_length) when is_binary(bcd_string) and is_integer(byte_length) do try do # Pad with leading zeros to ensure even length padded = bcd_string |> String.pad_leading(byte_length * 2, "0") |> String.slice(0, byte_length * 2) # Convert each pair of digits to BCD byte binary = padded |> String.graphemes() |> Enum.chunk_every(2) |> Enum.map(fn [high, low] -> (String.to_integer(high) <<< 4) ||| String.to_integer(low) end) |> :binary.list_to_bin() {:ok, binary} rescue _ -> {:error, :invalid_bcd} end end def test_bcd_tpdu do IO.puts("šŸ” Testing BCD TPDU Processing") # Your TPDU pattern from configuration tpdu_pattern = "6000782000" expected_bytes = 5 IO.puts("TPDU Pattern: #{tpdu_pattern}") IO.puts("Expected bytes: #{expected_bytes}") # Convert BCD pattern to binary case bcd_to_binary(tpdu_pattern, expected_bytes) do {:ok, pattern_binary} -> pattern_hex = Base.encode16(pattern_binary) IO.puts("āœ… BCD pattern converted to binary successfully") IO.puts(" Pattern binary (hex): #{pattern_hex}") IO.puts(" Pattern binary size: #{byte_size(pattern_binary)} bytes") # Your actual packet data packet_hex = "60007820000400703C078000C282051648549806007367400000000000000050000000220912500917310500510000078200313233343536373131323334353637383930313233343500817B226F72696744617465223A223230323530393137222C226F7269674D7469223A2230323030222C226F7269675472616365223A22303030303232222C226F72696754696D65223A22303931323530227D3738340028950500800400009F1E0832333733303030319F100706011203A0A80200063030303030311234567812345678" case Base.decode16(packet_hex) do {:ok, packet_data} -> IO.puts("\nšŸ“¦ Processing actual packet:") IO.puts(" Total packet size: #{byte_size(packet_data)} bytes") # Extract first 5 bytes (TPDU) <> = packet_data tpdu_hex = Base.encode16(tpdu_data) IO.puts(" Extracted TPDU (hex): #{tpdu_hex}") IO.puts(" Pattern expected (hex): #{pattern_hex}") if tpdu_data == pattern_binary do IO.puts("āœ… TPDU matches BCD pattern perfectly!") IO.puts(" Remaining ISO data: #{byte_size(remaining_data)} bytes") # Show first part of ISO data iso_start = Base.encode16(binary_part(remaining_data, 0, min(10, byte_size(remaining_data)))) IO.puts(" ISO data starts with: #{iso_start}") else IO.puts("āŒ TPDU does not match pattern") IO.puts(" This suggests the data might not be BCD encoded") end :error -> IO.puts("āŒ Failed to decode packet hex") end {:error, reason} -> IO.puts("āŒ Failed to convert BCD pattern: #{inspect(reason)}") end end end BCDTPDUTest.test_bcd_tpdu()