You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

FreeFareTag.cpp 2.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. //
  2. // Created by robin on 6/19/16.
  3. //
  4. #include <sstream>
  5. #include <map>
  6. #include "FreeFareTag.h"
  7. FreeFareTag::FreeFareTag(FreefareTag tag)
  8. : _tag(tag)
  9. {
  10. _type = freefare_get_tag_type(tag);
  11. _uid = freefare_get_tag_uid(tag);
  12. }
  13. FreeFareTag::~FreeFareTag()
  14. {
  15. freefare_free_tag(_tag);
  16. }
  17. ResultBool FreeFareTag::authenticate(int sector, int block, std::string key, int keyType)
  18. {
  19. if (mifare_classic_connect(_tag) != 0) {
  20. return ResultBool::error("Failed to connect to MIFARE tag");
  21. }
  22. block = mifare_classic_sector_first_block((MifareClassicBlockNumber)sector) + block;
  23. if (mifare_classic_authenticate(_tag, (MifareClassicBlockNumber)block, (const unsigned char*)key.c_str(),
  24. (MifareClassicKeyType)keyType) != 0) {
  25. return ResultBool::error("Failed to authenticate to MIFARE tag");
  26. }
  27. mifare_classic_disconnect(_tag);
  28. return ResultBool::ok(true);
  29. }
  30. ResultString FreeFareTag::readBlock(int sector, int block, std::string key, int keyType)
  31. {
  32. if (mifare_classic_connect(_tag) != 0) {
  33. return ResultString::error("Failed to connect to MIFARE tag");
  34. }
  35. block = mifare_classic_sector_first_block((MifareClassicBlockNumber)sector) + block;
  36. if (mifare_classic_authenticate(_tag, (MifareClassicBlockNumber)block, (const unsigned char*)key.c_str(),
  37. (MifareClassicKeyType)keyType) != 0) {
  38. return ResultString::error("Failed to authenticate to MIFARE tag");
  39. }
  40. MifareClassicBlock data;
  41. if (mifare_classic_read(_tag, (MifareClassicBlockNumber)block, &data)) {
  42. return ResultString::error("Failed to read MIFARE tag data");
  43. }
  44. mifare_classic_disconnect(_tag);
  45. return ResultString::ok(std::string((const char*)data, sizeof(data)));
  46. }
  47. const freefare_tag *FreeFareTag::getTag() const
  48. {
  49. return _tag;
  50. }
  51. int FreeFareTag::getFirstBlock(int sector) const
  52. {
  53. return mifare_classic_sector_first_block(sector);
  54. }
  55. int FreeFareTag::getLastBlock(int sector) const
  56. {
  57. return mifare_classic_sector_last_block(sector);
  58. }
  59. int FreeFareTag::getSectorBlockCount(int sector)
  60. {
  61. return mifare_classic_sector_block_count(sector);
  62. }
  63. freefare_tag_type FreeFareTag::getType() const
  64. {
  65. return _type;
  66. }
  67. const std::string &FreeFareTag::getUid() const
  68. {
  69. return _uid;
  70. }