#!/usr/bin/python2
#  froschtest.py - test frosch HTRM112 reader`
#
#  Adam Laurie <adam@algroup.co.uk>
#  http://rfidiot.org/
#
#  This code is copyright (c) Adam Laurie, 2006, All rights reserved.
#  For non-commercial use only, the following terms apply - for all other
#  uses, please contact the author:
#
#    This code is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This code is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#

import sys
# import os
import rfidiot

try:
    card = rfidiot.card
except Exception as e:
    print("Couldn't open reader! (%s)" % e)
    sys.exit(True)

card.info("froschtest v3.0b")
print()
print("Trying Hitag1: ", end="")
if card.frosch(card.FR_HT1_Get_Snr, ""):
    print(card.data[: len(card.data) - 2])
    if not card.select():
        print("Select failed: ", end="")
        print(card.FROSCH_Errors[card.errorcode])
    else:
        for x in range(0, 8):
            if card.readblock(x):
                print(f"\tBlock {x:02d}: {card.data}")
            else:
                print(f"\tBlock {x} read failed: ", end="")
                print(card.FROSCH_Errors[card.errorcode])
else:
    print(card.FROSCH_Errors[card.errorcode])

print("Trying Hitag2: ", end="")
if card.frosch(card.FR_HT2_Get_Snr_PWD, "") or card.frosch(card.FR_HT2_Get_Snr_CRYPTO, ""):
    print(card.data[: len(card.data) - 2])
    if not card.select():
        print("Select failed: ", end="")
        print(card.FROSCH_Errors[card.errorcode])
    else:
        for x in range(0, 8):
            if card.readblock(x):
                print(f"\tBlock {x:02d}: {card.data}")
            else:
                print(f"\tBlock {x:0d} read failed", end="")
                print(card.FROSCH_Errors[card.errorcode])
else:
    print(card.FROSCH_Errors[card.errorcode])

print("Trying Hitag2 Public A (Unique / Miro): ", end="")
if card.frosch(card.FR_HT2_Read_Miro, ""):
    print(card.data)
else:
    print(card.FROSCH_Errors[card.errorcode])

print("Trying Hitag2 Public B (FDX-B): ", end="")
if card.frosch(card.FR_HT2_Read_PublicB, ""):
    print("Raw: " + card.data, end="")
    print("ID: " + card.FDXBID128BitDecode(card.ToBinaryString(card.ToBinary(card.data))))
    card.FDXBIDPrint(card.FDXBID128BitDecode(card.ToBinaryString(card.ToBinary(card.data))))
else:
    print(card.FROSCH_Errors[card.errorcode])
sys.exit(False)
