From 94d24d95c6bf7e5c7d31e10a1d4b73f99db69b0a Mon Sep 17 00:00:00 2001 From: Georg Date: Tue, 7 Nov 2017 15:53:23 +0100 Subject: [PATCH] unified indentation --- Firmware/Chameleon-Mini/AntennaLevel.c | 18 +- Firmware/Chameleon-Mini/AntennaLevel.h | 24 +- .../Chameleon-Mini/Application/Application.h | 4 +- Firmware/Chameleon-Mini/Application/Crypto1.c | 210 +-- .../Chameleon-Mini/Application/ISO14443-3A.h | 22 +- .../Application/MifareClassic.c | 878 ++++++------ .../Application/MifareUltralight.c | 2 +- .../Chameleon-Mini/Application/Reader14443A.c | 1226 ++++++++--------- .../Chameleon-Mini/Application/Reader14443A.h | 14 +- Firmware/Chameleon-Mini/Battery.h | 14 +- Firmware/Chameleon-Mini/Button.c | 160 +-- Firmware/Chameleon-Mini/Button.h | 16 +- Firmware/Chameleon-Mini/Chameleon-Mini.c | 28 +- Firmware/Chameleon-Mini/Codec/Codec.c | 70 +- Firmware/Chameleon-Mini/Codec/Codec.h | 72 +- Firmware/Chameleon-Mini/Codec/ISO14443-2A.c | 144 +- .../Chameleon-Mini/Codec/Reader14443-2A.c | 514 +++---- Firmware/Chameleon-Mini/Common.c | 32 +- Firmware/Chameleon-Mini/Common.h | 24 +- Firmware/Chameleon-Mini/Configuration.c | 112 +- Firmware/Chameleon-Mini/Configuration.h | 38 +- Firmware/Chameleon-Mini/LED.c | 210 +-- Firmware/Chameleon-Mini/LED.h | 56 +- Firmware/Chameleon-Mini/LEDHook.h | 16 +- Firmware/Chameleon-Mini/LUFADescriptors.c | 4 +- Firmware/Chameleon-Mini/Log.c | 172 +-- Firmware/Chameleon-Mini/Log.h | 2 +- Firmware/Chameleon-Mini/Map.c | 78 +- Firmware/Chameleon-Mini/Map.h | 4 +- Firmware/Chameleon-Mini/Memory.c | 594 ++++---- Firmware/Chameleon-Mini/MemoryAsm.S | 106 +- Firmware/Chameleon-Mini/Settings.c | 70 +- Firmware/Chameleon-Mini/Settings.h | 18 +- Firmware/Chameleon-Mini/System.c | 22 +- Firmware/Chameleon-Mini/System.h | 10 +- .../Chameleon-Mini/Terminal/CommandLine.c | 282 ++-- Firmware/Chameleon-Mini/Terminal/Commands.c | 444 +++--- Firmware/Chameleon-Mini/Terminal/Terminal.c | 70 +- Firmware/Chameleon-Mini/Terminal/Terminal.h | 8 +- Firmware/Chameleon-Mini/Terminal/XModem.c | 2 +- 40 files changed, 2895 insertions(+), 2895 deletions(-) diff --git a/Firmware/Chameleon-Mini/AntennaLevel.c b/Firmware/Chameleon-Mini/AntennaLevel.c index 30baed6..15aa284 100644 --- a/Firmware/Chameleon-Mini/AntennaLevel.c +++ b/Firmware/Chameleon-Mini/AntennaLevel.c @@ -6,14 +6,14 @@ void AntennaLevelTick(void) { - uint16_t rssi = AntennaLevelGet(); + uint16_t rssi = AntennaLevelGet(); - if (rssi < FIELD_MIN_RSSI) - { - LEDHook(LED_FIELD_DETECTED, LED_OFF); - if (ActiveConfiguration.UidSize != 0) // this implies that we are emulating right now - ApplicationReset(); // reset the application just like a real card gets reset when there is no field - } else { - LEDHook(LED_FIELD_DETECTED, LED_ON); - } + if (rssi < FIELD_MIN_RSSI) + { + LEDHook(LED_FIELD_DETECTED, LED_OFF); + if (ActiveConfiguration.UidSize != 0) // this implies that we are emulating right now + ApplicationReset(); // reset the application just like a real card gets reset when there is no field + } else { + LEDHook(LED_FIELD_DETECTED, LED_ON); + } } diff --git a/Firmware/Chameleon-Mini/AntennaLevel.h b/Firmware/Chameleon-Mini/AntennaLevel.h index 5af7368..2ca58e4 100644 --- a/Firmware/Chameleon-Mini/AntennaLevel.h +++ b/Firmware/Chameleon-Mini/AntennaLevel.h @@ -25,27 +25,27 @@ static inline void AntennaLevelInit(void) { - ADCA.CTRLA = ADC_ENABLE_bm; - ADCA.CTRLB = ADC_RESOLUTION_12BIT_gc; - ADCA.REFCTRL = ADC_REFSEL_INT1V_gc | ADC_BANDGAP_bm; - ADCA.PRESCALER = ADC_PRESCALER_DIV32_gc; - ADCA.CH0.CTRL = ADC_CH_INPUTMODE_SINGLEENDED_gc; - ADCA.CH0.MUXCTRL = ADC_CH_MUXPOS_PIN1_gc; + ADCA.CTRLA = ADC_ENABLE_bm; + ADCA.CTRLB = ADC_RESOLUTION_12BIT_gc; + ADCA.REFCTRL = ADC_REFSEL_INT1V_gc | ADC_BANDGAP_bm; + ADCA.PRESCALER = ADC_PRESCALER_DIV32_gc; + ADCA.CH0.CTRL = ADC_CH_INPUTMODE_SINGLEENDED_gc; + ADCA.CH0.MUXCTRL = ADC_CH_MUXPOS_PIN1_gc; } static inline uint16_t AntennaLevelGet(void) { - ADCA.CH0.CTRL |= ADC_CH_START_bm; - while( !(ADCA.CH0.INTFLAGS & ADC_CH_CHIF_bm) ); + ADCA.CH0.CTRL |= ADC_CH_START_bm; + while( !(ADCA.CH0.INTFLAGS & ADC_CH_CHIF_bm) ); - ADCA.CH0.INTFLAGS = ADC_CH_CHIF_bm; + ADCA.CH0.INTFLAGS = ADC_CH_CHIF_bm; - int16_t Result = ADCA.CH0RES - ANTENNA_LEVEL_OFFSET; - if (Result < 0) Result = 0; + int16_t Result = ADCA.CH0RES - ANTENNA_LEVEL_OFFSET; + if (Result < 0) Result = 0; - return (uint16_t) (((uint32_t) Result * ANTENNA_LEVEL_NUMERATOR) / ANTENNA_LEVEL_DENOMINATOR); + return (uint16_t) (((uint32_t) Result * ANTENNA_LEVEL_NUMERATOR) / ANTENNA_LEVEL_DENOMINATOR); } void AntennaLevelTick(void); diff --git a/Firmware/Chameleon-Mini/Application/Application.h b/Firmware/Chameleon-Mini/Application/Application.h index 6667477..0b94960 100644 --- a/Firmware/Chameleon-Mini/Application/Application.h +++ b/Firmware/Chameleon-Mini/Application/Application.h @@ -23,11 +23,11 @@ INLINE void ApplicationInit(void) { } INLINE void ApplicationTask(void) { - ActiveConfiguration.ApplicationTaskFunc(); + ActiveConfiguration.ApplicationTaskFunc(); } INLINE void ApplicationTick(void) { - ActiveConfiguration.ApplicationTickFunc(); + ActiveConfiguration.ApplicationTickFunc(); } INLINE uint16_t ApplicationProcess(uint8_t* ByteBuffer, uint16_t ByteCount) { diff --git a/Firmware/Chameleon-Mini/Application/Crypto1.c b/Firmware/Chameleon-Mini/Application/Crypto1.c index f4f3d18..6be6780 100644 --- a/Firmware/Chameleon-Mini/Application/Crypto1.c +++ b/Firmware/Chameleon-Mini/Application/Crypto1.c @@ -50,42 +50,42 @@ /* Used for LFSR setup. */ #define SPLIT_BYTE(__even, __odd, __byte) \ __asm__ __volatile__ ( \ - "lsr %2" "\n\t" \ - "ror %0" "\n\t" \ - "lsr %2" "\n\t" \ - "ror %1" "\n\t" \ - "lsr %2" "\n\t" \ - "ror %0" "\n\t" \ - "lsr %2" "\n\t" \ - "ror %1" "\n\t" \ - "lsr %2" "\n\t" \ - "ror %0" "\n\t" \ - "lsr %2" "\n\t" \ - "ror %1" "\n\t" \ - "lsr %2" "\n\t" \ - "ror %0" "\n\t" \ - "lsr %2" "\n\t" \ - "ror %1" \ - : "+r" (__even), \ + "lsr %2" "\n\t" \ + "ror %0" "\n\t" \ + "lsr %2" "\n\t" \ + "ror %1" "\n\t" \ + "lsr %2" "\n\t" \ + "ror %0" "\n\t" \ + "lsr %2" "\n\t" \ + "ror %1" "\n\t" \ + "lsr %2" "\n\t" \ + "ror %0" "\n\t" \ + "lsr %2" "\n\t" \ + "ror %1" "\n\t" \ + "lsr %2" "\n\t" \ + "ror %0" "\n\t" \ + "lsr %2" "\n\t" \ + "ror %1" \ + : "+r" (__even), \ "+r" (__odd), \ - "+r" (__byte) \ + "+r" (__byte) \ : \ - : "r0" ) + : "r0" ) /* Shift half LFSR state stored in three registers */ /* Input is bit 0 of __in */ #define SHIFT24(__b0, __b1, __b2, __in) \ __asm__ __volatile__ ( \ - "lsr %3" "\n\t" \ - "ror %2" "\n\t" \ - "ror %1" "\n\t" \ - "ror %0" \ - : "+r" (__b0), \ + "lsr %3" "\n\t" \ + "ror %2" "\n\t" \ + "ror %1" "\n\t" \ + "ror %0" \ + : "+r" (__b0), \ "+r" (__b1), \ "+r" (__b2), \ - "+r" (__in) \ + "+r" (__in) \ : \ - : ) + : ) /* Shift half LFSR state stored in three registers */ /* Input is bit 0 of __in */ @@ -93,29 +93,29 @@ #define SHIFT24_COND_DECRYPT(__b0, __b1, __b2, __in, __stream, __decrypt) \ __asm__ __volatile__ ( \ "sbrc %5, 0" "\n\t" \ - "eor %3, %4" "\n\t" \ + "eor %3, %4" "\n\t" \ "lsr %3" "\n\t" \ - "ror %2" "\n\t" \ - "ror %1" "\n\t" \ - "ror %0" \ - : "+r" (__b0), \ + "ror %2" "\n\t" \ + "ror %1" "\n\t" \ + "ror %0" \ + : "+r" (__b0), \ "+r" (__b1), \ "+r" (__b2), \ - "+r" (__in) \ - : "r" (__stream), \ - "r" (__decrypt) \ - : "r0" ) + "+r" (__in) \ + : "r" (__stream), \ + "r" (__decrypt) \ + : "r0" ) /* Shift a byte with input from an other byte */ /* Input is bit 0 of __in */ #define SHIFT8(__byte, __in) \ - __asm__ __volatile__ ( \ - "lsr %1" "\n\t" \ - "ror %0" \ - : "+r" (__byte), \ - "+r" (__in) \ + __asm__ __volatile__ ( \ + "lsr %1" "\n\t" \ + "ror %0" \ + : "+r" (__byte), \ + "+r" (__in) \ : \ - : "r0" ) + : "r0" ) /* End AVR specific */ #else @@ -142,14 +142,14 @@ #define SHIFT8(__byte, __in) __byte = (__byte>>1) | ((__in)<<7) #define SPLIT_BYTE(__even, __odd, __byte) \ - __even = (__even >> 1) | (__byte<<7); __byte>>=1; \ - __odd = (__odd >> 1) | (__byte<<7); __byte>>=1; \ - __even = (__even >> 1) | (__byte<<7); __byte>>=1; \ - __odd = (__odd >> 1) | (__byte<<7); __byte>>=1; \ - __even = (__even >> 1) | (__byte<<7); __byte>>=1; \ - __odd = (__odd >> 1) | (__byte<<7); __byte>>=1; \ - __even = (__even >> 1) | (__byte<<7); __byte>>=1; \ - __odd = (__odd >> 1) | (__byte<<7) + __even = (__even >> 1) | (__byte<<7); __byte>>=1; \ + __odd = (__odd >> 1) | (__byte<<7); __byte>>=1; \ + __even = (__even >> 1) | (__byte<<7); __byte>>=1; \ + __odd = (__odd >> 1) | (__byte<<7); __byte>>=1; \ + __even = (__even >> 1) | (__byte<<7); __byte>>=1; \ + __odd = (__odd >> 1) | (__byte<<7); __byte>>=1; \ + __even = (__even >> 1) | (__byte<<7); __byte>>=1; \ + __odd = (__odd >> 1) | (__byte<<7) /* Generate odd parity bit */ @@ -319,26 +319,26 @@ static const uint8_t TableC3[32] = { /* Filter Output Macros */ /* Output at bit 7 for optimized byte processing */ #define CRYPTO1_FILTER_OUTPUT_B7_24(__O0, __O1, __O2) TableC7[ abFilterTable[0][__O0] | \ - abFilterTable[1][__O1] | \ - abFilterTable[2][__O2]] + abFilterTable[1][__O1] | \ + abFilterTable[2][__O2]] /* Output at bit 3 for optimized nibble processing */ #define CRYPTO1_FILTER_OUTPUT_B3_24(__O0, __O1, __O2) TableC3[ abFilterTable[0][__O0] | \ - abFilterTable[1][__O1] | \ - abFilterTable[2][__O2]] + abFilterTable[1][__O1] | \ + abFilterTable[2][__O2]] /* Output at bit 0 for general purpose */ #define CRYPTO1_FILTER_OUTPUT_B0_24(__O0, __O1, __O2) TableC0[ abFilterTable[0][__O0] | \ - abFilterTable[1][__O1] | \ - abFilterTable[2][__O2]] + abFilterTable[1][__O1] | \ + abFilterTable[2][__O2]] /* Split Crypto1 state into even and odd bits */ /* to speed up the output filter network */ /* Put both into one struct to enable relative adressing */ typedef struct { - uint8_t Even[LFSR_SIZE/2]; - uint8_t Odd[LFSR_SIZE/2]; + uint8_t Even[LFSR_SIZE/2]; + uint8_t Odd[LFSR_SIZE/2]; } Crypto1LfsrState_t; static Crypto1LfsrState_t State = {{0},{0}}; @@ -346,35 +346,35 @@ static Crypto1LfsrState_t State = {{0},{0}}; /* Debug output of state */ void Crypto1GetState(uint8_t* pEven, uint8_t* pOdd) { - if (pEven) - { - pEven[0] = State.Even[0]; - pEven[1] = State.Even[1]; - pEven[2] = State.Even[2]; - } - if (pOdd) - { - pOdd[0] = State.Odd[0]; - pOdd[1] = State.Odd[1]; - pOdd[2] = State.Odd[2]; - } + if (pEven) + { + pEven[0] = State.Even[0]; + pEven[1] = State.Even[1]; + pEven[2] = State.Even[2]; + } + if (pOdd) + { + pOdd[0] = State.Odd[0]; + pOdd[1] = State.Odd[1]; + pOdd[2] = State.Odd[2]; + } } /* Proceed LFSR by one clock cycle */ /* Prototype to force inlining */ static __inline__ uint8_t Crypto1LFSRbyteFeedback (uint8_t E0, - uint8_t E1, - uint8_t E2, - uint8_t O0, - uint8_t O1, - uint8_t O2) __attribute__((always_inline)); + uint8_t E1, + uint8_t E2, + uint8_t O0, + uint8_t O1, + uint8_t O2) __attribute__((always_inline)); static uint8_t Crypto1LFSRbyteFeedback (uint8_t E0, - uint8_t E1, - uint8_t E2, - uint8_t O0, - uint8_t O1, - uint8_t O2) + uint8_t E1, + uint8_t E2, + uint8_t O0, + uint8_t O1, + uint8_t O2) { uint8_t Feedback; @@ -448,8 +448,8 @@ uint8_t Crypto1FilterOutput(void) { /* Setup LFSR split into odd and even states, feed in uid ^nonce */ /* Version for first (not nested) authentication. */ void Crypto1Setup(uint8_t Key[6], - uint8_t Uid[4], - uint8_t CardNonce[4]) + uint8_t Uid[4], + uint8_t CardNonce[4]) { /* state registers */ register uint8_t Even0, Even1, Even2; @@ -1061,32 +1061,32 @@ void Crypto1PRNG(uint8_t State[4], uint8_t ClockCount) void Crypto1EncryptWithParity(uint8_t * Buffer, uint8_t BitCount) { - uint8_t i = 0; - while (i < BitCount) - { - Buffer[i/8] ^= - CRYPTO1_FILTER_OUTPUT_B0_24(State.Odd[0], State.Odd[1], State.Odd[2]) - << (i % 8); - if (++i % 9 != 0) // only shift, if this was no parity bit - Crypto1LFSR(0); - } + uint8_t i = 0; + while (i < BitCount) + { + Buffer[i/8] ^= + CRYPTO1_FILTER_OUTPUT_B0_24(State.Odd[0], State.Odd[1], State.Odd[2]) + << (i % 8); + if (++i % 9 != 0) // only shift, if this was no parity bit + Crypto1LFSR(0); + } } void Crypto1ReaderAuthWithParity(uint8_t PlainReaderAnswerWithParityBits[9]) { - uint8_t i = 0, feedback; - while (i < 72) - { - feedback = PlainReaderAnswerWithParityBits[i/8] >> (i % 8); - PlainReaderAnswerWithParityBits[i/8] ^= - CRYPTO1_FILTER_OUTPUT_B0_24(State.Odd[0], State.Odd[1], State.Odd[2]) - << (i % 8); - if (++i % 9 != 0) // only shift, if this was no parity bit - { - if (i <= 36) - Crypto1LFSR(feedback & 1); - else - Crypto1LFSR(0); - } - } + uint8_t i = 0, feedback; + while (i < 72) + { + feedback = PlainReaderAnswerWithParityBits[i/8] >> (i % 8); + PlainReaderAnswerWithParityBits[i/8] ^= + CRYPTO1_FILTER_OUTPUT_B0_24(State.Odd[0], State.Odd[1], State.Odd[2]) + << (i % 8); + if (++i % 9 != 0) // only shift, if this was no parity bit + { + if (i <= 36) + Crypto1LFSR(feedback & 1); + else + Crypto1LFSR(0); + } + } } diff --git a/Firmware/Chameleon-Mini/Application/ISO14443-3A.h b/Firmware/Chameleon-Mini/Application/ISO14443-3A.h index be55418..a8c1663 100644 --- a/Firmware/Chameleon-Mini/Application/ISO14443-3A.h +++ b/Firmware/Chameleon-Mini/Application/ISO14443-3A.h @@ -93,16 +93,16 @@ bool ISO14443ASelect(void* Buffer, uint16_t* BitCount, uint8_t* UidCL, uint8_t S } default: { - uint8_t CollisionByteCount = ((NVB >> 4) & 0x0f) - 2; - uint8_t CollisionBitCount = (NVB >> 0) & 0x0f; - uint8_t mask = 0xFF >> (8 - CollisionBitCount); - // Since the UidCL does not contain the BCC, we have to distinguish here + uint8_t CollisionByteCount = ((NVB >> 4) & 0x0f) - 2; + uint8_t CollisionBitCount = (NVB >> 0) & 0x0f; + uint8_t mask = 0xFF >> (8 - CollisionBitCount); + // Since the UidCL does not contain the BCC, we have to distinguish here if ( - ((CollisionByteCount == 5 || (CollisionByteCount == 4 && CollisionBitCount > 0)) && memcmp(UidCL, &DataPtr[2], 4) == 0 && (ISO14443A_CALC_BCC(UidCL) & mask) == (DataPtr[6] & mask)) - || - (CollisionByteCount == 4 && CollisionBitCount == 0 && memcmp(UidCL, &DataPtr[2], 4) == 0) - || - (CollisionByteCount < 4 && memcmp(UidCL, &DataPtr[2], CollisionByteCount) == 0 && (UidCL[CollisionByteCount] & mask) == (DataPtr[CollisionByteCount + 2] & mask)) + ((CollisionByteCount == 5 || (CollisionByteCount == 4 && CollisionBitCount > 0)) && memcmp(UidCL, &DataPtr[2], 4) == 0 && (ISO14443A_CALC_BCC(UidCL) & mask) == (DataPtr[6] & mask)) + || + (CollisionByteCount == 4 && CollisionBitCount == 0 && memcmp(UidCL, &DataPtr[2], 4) == 0) + || + (CollisionByteCount < 4 && memcmp(UidCL, &DataPtr[2], CollisionByteCount) == 0 && (UidCL[CollisionByteCount] & mask) == (DataPtr[CollisionByteCount + 2] & mask)) ) { DataPtr[0] = UidCL[0]; @@ -113,7 +113,7 @@ bool ISO14443ASelect(void* Buffer, uint16_t* BitCount, uint8_t* UidCL, uint8_t S *BitCount = ISO14443A_CL_FRAME_SIZE; } else { - *BitCount = 0; + *BitCount = 0; } return false; } @@ -137,7 +137,7 @@ bool ISO14443AWakeUp(void* Buffer, uint16_t* BitCount, uint16_t ATQAValue, bool return true; } else { - *BitCount = 0; + *BitCount = 0; return false; } diff --git a/Firmware/Chameleon-Mini/Application/MifareClassic.c b/Firmware/Chameleon-Mini/Application/MifareClassic.c index 093a570..e96cf45 100644 --- a/Firmware/Chameleon-Mini/Application/MifareClassic.c +++ b/Firmware/Chameleon-Mini/Application/MifareClassic.c @@ -86,7 +86,7 @@ Source: NXP: MF1S50YYX Product data sheet Access conditions for the sector trailer Access bits Access condition for Remark - KEYA Access bits KEYB + KEYA Access bits KEYB C1 C2 C3 read write read write read write 0 0 0 never key A key A never key A key A Key B may be read[1] 0 1 0 never never key A never key A never Key B may be read[1] @@ -137,124 +137,124 @@ C1 C2 C3 read write increment decrement, /* Decoding table for Access conditions of a data block */ static const uint8_t abBlockAccessConditions[8][2] = { - /*C1C2C3 */ - /* 0 0 0 R:key A|B W: key A|B I:key A|B D:key A|B transport configuration */ - { - /* Access with Key A */ - ACC_BLOCK_READ | ACC_BLOCK_WRITE | ACC_BLOCK_INCREMENT | ACC_BLOCK_DECREMENT, - /* Access with Key B */ - ACC_BLOCK_READ | ACC_BLOCK_WRITE | ACC_BLOCK_INCREMENT | ACC_BLOCK_DECREMENT - }, - /* 1 0 0 R:key A|B W:key B I:never D:never read/write block */ - { - /* Access with Key A */ - ACC_BLOCK_READ, - /* Access with Key B */ - ACC_BLOCK_READ | ACC_BLOCK_WRITE - }, - /* 0 1 0 R:key A|B W:never I:never D:never read/write block */ - { - /* Access with Key A */ - ACC_BLOCK_READ, - /* Access with Key B */ - ACC_BLOCK_READ - }, - /* 1 1 0 R:key A|B W:key B I:key B D:key A|B value block */ - { - /* Access with Key A */ - ACC_BLOCK_READ | ACC_BLOCK_DECREMENT, - /* Access with Key B */ - ACC_BLOCK_READ | ACC_BLOCK_WRITE | ACC_BLOCK_INCREMENT | ACC_BLOCK_DECREMENT - }, - /* 0 0 1 R:key A|B W:never I:never D:key A|B value block */ - { - /* Access with Key A */ - ACC_BLOCK_READ | ACC_BLOCK_DECREMENT, - /* Access with Key B */ - ACC_BLOCK_READ | ACC_BLOCK_DECREMENT - }, - /* 1 0 1 R:key B W:never I:never D:never read/write block */ - { - /* Access with Key A */ - 0, - /* Access with Key B */ - ACC_BLOCK_READ - }, - /* 0 1 1 R:key B W:key B I:never D:never read/write block */ - { - /* Access with Key A */ - 0, - /* Access with Key B */ - ACC_BLOCK_READ | ACC_BLOCK_WRITE - }, - /* 1 1 1 R:never W:never I:never D:never read/write block */ - { - /* Access with Key A */ - 0, - /* Access with Key B */ - 0 - } + /*C1C2C3 */ + /* 0 0 0 R:key A|B W: key A|B I:key A|B D:key A|B transport configuration */ + { + /* Access with Key A */ + ACC_BLOCK_READ | ACC_BLOCK_WRITE | ACC_BLOCK_INCREMENT | ACC_BLOCK_DECREMENT, + /* Access with Key B */ + ACC_BLOCK_READ | ACC_BLOCK_WRITE | ACC_BLOCK_INCREMENT | ACC_BLOCK_DECREMENT + }, + /* 1 0 0 R:key A|B W:key B I:never D:never read/write block */ + { + /* Access with Key A */ + ACC_BLOCK_READ, + /* Access with Key B */ + ACC_BLOCK_READ | ACC_BLOCK_WRITE + }, + /* 0 1 0 R:key A|B W:never I:never D:never read/write block */ + { + /* Access with Key A */ + ACC_BLOCK_READ, + /* Access with Key B */ + ACC_BLOCK_READ + }, + /* 1 1 0 R:key A|B W:key B I:key B D:key A|B value block */ + { + /* Access with Key A */ + ACC_BLOCK_READ | ACC_BLOCK_DECREMENT, + /* Access with Key B */ + ACC_BLOCK_READ | ACC_BLOCK_WRITE | ACC_BLOCK_INCREMENT | ACC_BLOCK_DECREMENT + }, + /* 0 0 1 R:key A|B W:never I:never D:key A|B value block */ + { + /* Access with Key A */ + ACC_BLOCK_READ | ACC_BLOCK_DECREMENT, + /* Access with Key B */ + ACC_BLOCK_READ | ACC_BLOCK_DECREMENT + }, + /* 1 0 1 R:key B W:never I:never D:never read/write block */ + { + /* Access with Key A */ + 0, + /* Access with Key B */ + ACC_BLOCK_READ + }, + /* 0 1 1 R:key B W:key B I:never D:never read/write block */ + { + /* Access with Key A */ + 0, + /* Access with Key B */ + ACC_BLOCK_READ | ACC_BLOCK_WRITE + }, + /* 1 1 1 R:never W:never I:never D:never read/write block */ + { + /* Access with Key A */ + 0, + /* Access with Key B */ + 0 + } }; /* Decoding table for Access conditions of the sector trailor */ static const uint8_t abTrailorAccessConditions[8][2] = { - /* 0 0 0 RdKA:never WrKA:key A RdAcc:key A WrAcc:never RdKB:key A WrKB:key A Key B may be read[1] */ - { - /* Access with Key A */ - ACC_TRAILOR_WRITE_KEYA | ACC_TRAILOR_READ_ACC | ACC_TRAILOR_WRITE_ACC | ACC_TRAILOR_READ_KEYB | ACC_TRAILOR_WRITE_KEYB, - /* Access with Key B */ - 0 - }, - /* 1 0 0 RdKA:never WrKA:key B RdAcc:keyA|B WrAcc:never RdKB:never WrKB:key B */ - { - /* Access with Key A */ - ACC_TRAILOR_READ_ACC, - /* Access with Key B */ - ACC_TRAILOR_WRITE_KEYA | ACC_TRAILOR_READ_ACC | ACC_TRAILOR_WRITE_KEYB - }, - /* 0 1 0 RdKA:never WrKA:never RdAcc:key A WrAcc:never RdKB:key A WrKB:never Key B may be read[1] */ - { - /* Access with Key A */ - ACC_TRAILOR_READ_ACC | ACC_TRAILOR_READ_KEYB, - /* Access with Key B */ - 0 - }, - /* 1 1 0 never never keyA|B never never never */ - { - /* Access with Key A */ - ACC_TRAILOR_READ_ACC, - /* Access with Key B */ - ACC_TRAILOR_READ_ACC - }, - /* 0 0 1 never key A key A key A key A key A Key B may be read,transport configuration[1] */ - { - /* Access with Key A */ - ACC_TRAILOR_WRITE_KEYA | ACC_TRAILOR_READ_ACC | ACC_TRAILOR_WRITE_ACC | ACC_TRAILOR_READ_KEYB | ACC_TRAILOR_WRITE_KEYB, - /* Access with Key B */ - 0 - }, - /* 0 1 1 never key B keyA|B key B never key B */ - { - /* Access with Key A */ - ACC_TRAILOR_READ_ACC, - /* Access with Key B */ - ACC_TRAILOR_WRITE_KEYA | ACC_TRAILOR_READ_ACC | ACC_TRAILOR_WRITE_ACC | ACC_TRAILOR_WRITE_KEYB - }, - /* 1 0 1 never never keyA|B key B never never */ - { - /* Access with Key A */ - ACC_TRAILOR_READ_ACC, - /* Access with Key B */ - ACC_TRAILOR_READ_ACC | ACC_TRAILOR_WRITE_ACC - }, - /* 1 1 1 never never keyA|B never never never */ - { - /* Access with Key A */ - ACC_TRAILOR_READ_ACC, - /* Access with Key B */ - ACC_TRAILOR_READ_ACC - }, + /* 0 0 0 RdKA:never WrKA:key A RdAcc:key A WrAcc:never RdKB:key A WrKB:key A Key B may be read[1] */ + { + /* Access with Key A */ + ACC_TRAILOR_WRITE_KEYA | ACC_TRAILOR_READ_ACC | ACC_TRAILOR_WRITE_ACC | ACC_TRAILOR_READ_KEYB | ACC_TRAILOR_WRITE_KEYB, + /* Access with Key B */ + 0 + }, + /* 1 0 0 RdKA:never WrKA:key B RdAcc:keyA|B WrAcc:never RdKB:never WrKB:key B */ + { + /* Access with Key A */ + ACC_TRAILOR_READ_ACC, + /* Access with Key B */ + ACC_TRAILOR_WRITE_KEYA | ACC_TRAILOR_READ_ACC | ACC_TRAILOR_WRITE_KEYB + }, + /* 0 1 0 RdKA:never WrKA:never RdAcc:key A WrAcc:never RdKB:key A WrKB:never Key B may be read[1] */ + { + /* Access with Key A */ + ACC_TRAILOR_READ_ACC | ACC_TRAILOR_READ_KEYB, + /* Access with Key B */ + 0 + }, + /* 1 1 0 never never keyA|B never never never */ + { + /* Access with Key A */ + ACC_TRAILOR_READ_ACC, + /* Access with Key B */ + ACC_TRAILOR_READ_ACC + }, + /* 0 0 1 never key A key A key A key A key A Key B may be read,transport configuration[1] */ + { + /* Access with Key A */ + ACC_TRAILOR_WRITE_KEYA | ACC_TRAILOR_READ_ACC | ACC_TRAILOR_WRITE_ACC | ACC_TRAILOR_READ_KEYB | ACC_TRAILOR_WRITE_KEYB, + /* Access with Key B */ + 0 + }, + /* 0 1 1 never key B keyA|B key B never key B */ + { + /* Access with Key A */ + ACC_TRAILOR_READ_ACC, + /* Access with Key B */ + ACC_TRAILOR_WRITE_KEYA | ACC_TRAILOR_READ_ACC | ACC_TRAILOR_WRITE_ACC | ACC_TRAILOR_WRITE_KEYB + }, + /* 1 0 1 never never keyA|B key B never never */ + { + /* Access with Key A */ + ACC_TRAILOR_READ_ACC, + /* Access with Key B */ + ACC_TRAILOR_READ_ACC | ACC_TRAILOR_WRITE_ACC + }, + /* 1 1 1 never never keyA|B never never never */ + { + /* Access with Key A */ + ACC_TRAILOR_READ_ACC, + /* Access with Key B */ + ACC_TRAILOR_READ_ACC + }, }; static enum { @@ -309,17 +309,17 @@ INLINE uint8_t GetAccessCondition(uint8_t Block) } /* Fix for MFClassic 4K cards */ if(Block<128) - Block &= 3; + Block &= 3; else { - Block &= 15; - if (Block& 15) - Block=3; - else if (Block<=4) - Block=0; - else if (Block<=9) - Block=1; - else - Block=2; + Block &= 15; + if (Block& 15) + Block=3; + else if (Block<=4) + Block=0; + else if (Block<=9) + Block=1; + else + Block=2; } Acc0 = ~Acc0; /* C1x Bits to bit 0..3 */ @@ -431,7 +431,7 @@ uint16_t MifareClassicAppProcess(uint8_t* Buffer, uint16_t BitCount) /* precheck of WUP/REQ because ISO14443AWakeUp destroys BitCount */ (((State != STATE_HALT) && (Buffer[0] == ISO14443A_CMD_REQA)) || (Buffer[0] == ISO14443A_CMD_WUPA) )){ - FromHalt = State == STATE_HALT; + FromHalt = State == STATE_HALT; if (ISO14443AWakeUp(Buffer, &BitCount, CardATQAValue, FromHalt)) { AccessAddress = 0xff; State = STATE_READY1; @@ -442,7 +442,7 @@ uint16_t MifareClassicAppProcess(uint8_t* Buffer, uint16_t BitCount) switch(State) { case STATE_IDLE: case STATE_HALT: - FromHalt = State == STATE_HALT; + FromHalt = State == STATE_HALT; if (ISO14443AWakeUp(Buffer, &BitCount, CardATQAValue, FromHalt)) { State = STATE_READY1; return BitCount; @@ -499,7 +499,7 @@ uint16_t MifareClassicAppProcess(uint8_t* Buffer, uint16_t BitCount) if (ISO14443ACheckCRCA(Buffer, CMD_HALT_FRAME_SIZE)) { /* According to ISO14443, we must not send anything * in order to acknowledge the HALT command. */ - LogEntry(LOG_INFO_APP_CMD_HALT, NULL, 0); + LogEntry(LOG_INFO_APP_CMD_HALT, NULL, 0); State = STATE_HALT; return ISO14443A_APP_NO_RESPONSE; } else { @@ -538,17 +538,17 @@ uint16_t MifareClassicAppProcess(uint8_t* Buffer, uint16_t BitCount) } else if (Buffer[0] == ISO14443A_CMD_SELECT_CL1) { /* Load UID CL1 and perform anticollision */ uint8_t UidCL1[ISO14443A_CL_UID_SIZE]; - /* For Longer UIDs indicate that more UID-Bytes follow (-> CL2) */ + /* For Longer UIDs indicate that more UID-Bytes follow (-> CL2) */ if (ActiveConfiguration.UidSize == 7) { - MemoryReadBlock(&UidCL1[1], MEM_UID_CL1_ADDRESS, MEM_UID_CL1_SIZE-1); - UidCL1[0] = ISO14443A_UID0_CT; - if (ISO14443ASelect(Buffer, &BitCount, UidCL1, SAK_UID_NOT_FINISHED)) - State = STATE_READY2; + MemoryReadBlock(&UidCL1[1], MEM_UID_CL1_ADDRESS, MEM_UID_CL1_SIZE-1); + UidCL1[0] = ISO14443A_UID0_CT; + if (ISO14443ASelect(Buffer, &BitCount, UidCL1, SAK_UID_NOT_FINISHED)) + State = STATE_READY2; } else { - MemoryReadBlock(UidCL1, MEM_UID_CL1_ADDRESS, MEM_UID_CL1_SIZE); - if (ISO14443ASelect(Buffer, &BitCount, UidCL1, CardSAKValue)) { + MemoryReadBlock(UidCL1, MEM_UID_CL1_ADDRESS, MEM_UID_CL1_SIZE); + if (ISO14443ASelect(Buffer, &BitCount, UidCL1, CardSAKValue)) { AccessAddress = 0xff; /* invalid, force reload */ - State = STATE_ACTIVE; + State = STATE_ACTIVE; } } @@ -562,21 +562,21 @@ uint16_t MifareClassicAppProcess(uint8_t* Buffer, uint16_t BitCount) case STATE_READY2: if (ISO14443AWakeUp(Buffer, &BitCount, CardATQAValue, FromHalt)) { State = FromHalt ? STATE_HALT : STATE_IDLE; - return ISO14443A_APP_NO_RESPONSE; - } else if (Buffer[0] == ISO14443A_CMD_SELECT_CL2) { - /* Load UID CL2 and perform anticollision */ - uint8_t UidCL2[ISO14443A_CL_UID_SIZE]; - MemoryReadBlock(UidCL2, MEM_UID_CL2_ADDRESS, MEM_UID_CL2_SIZE); + return ISO14443A_APP_NO_RESPONSE; + } else if (Buffer[0] == ISO14443A_CMD_SELECT_CL2) { + /* Load UID CL2 and perform anticollision */ + uint8_t UidCL2[ISO14443A_CL_UID_SIZE]; + MemoryReadBlock(UidCL2, MEM_UID_CL2_ADDRESS, MEM_UID_CL2_SIZE); - if (ISO14443ASelect(Buffer, &BitCount, UidCL2, CardSAKValue)) { + if (ISO14443ASelect(Buffer, &BitCount, UidCL2, CardSAKValue)) { AccessAddress = 0xff; /* invalid, force reload */ - State = STATE_ACTIVE; - } + State = STATE_ACTIVE; + } - return BitCount; - } else { - /* Unknown command. Enter HALT state. */ - State = STATE_HALT; + return BitCount; + } else { + /* Unknown command. Enter HALT state. */ + State = STATE_HALT; } break; case STATE_ACTIVE: @@ -590,9 +590,9 @@ uint16_t MifareClassicAppProcess(uint8_t* Buffer, uint16_t BitCount) if (ISO14443ACheckCRCA(Buffer, CMD_HALT_FRAME_SIZE)) { /* According to ISO14443, we must not send anything * in order to acknowledge the HALT command. */ - LogEntry(LOG_INFO_APP_CMD_HALT, NULL, 0); + LogEntry(LOG_INFO_APP_CMD_HALT, NULL, 0); - State = STATE_HALT; + State = STATE_HALT; return ISO14443A_APP_NO_RESPONSE; } else { Buffer[0] = NAK_CRC_ERROR; @@ -603,93 +603,93 @@ uint16_t MifareClassicAppProcess(uint8_t* Buffer, uint16_t BitCount) return ACK_NAK_FRAME_SIZE; } } else if ( (Buffer[0] == CMD_AUTH_A) || (Buffer[0] == CMD_AUTH_B)) { - if (ISO14443ACheckCRCA(Buffer, CMD_AUTH_FRAME_SIZE)) { + if (ISO14443ACheckCRCA(Buffer, CMD_AUTH_FRAME_SIZE)) { - //uint16_t SectorAddress = Buffer[1] & MEM_SECTOR_ADDR_MASK; - uint16_t KeyOffset = (Buffer[0] == CMD_AUTH_A ? MEM_KEY_A_OFFSET : MEM_KEY_B_OFFSET); - uint16_t AccessOffset = MEM_KEY_A_OFFSET + MEM_KEY_SIZE; - uint16_t SectorStartAddress; - uint8_t Key[6]; - uint8_t Uid[4]; - uint8_t CardNonce[8]; + //uint16_t SectorAddress = Buffer[1] & MEM_SECTOR_ADDR_MASK; + uint16_t KeyOffset = (Buffer[0] == CMD_AUTH_A ? MEM_KEY_A_OFFSET : MEM_KEY_B_OFFSET); + uint16_t AccessOffset = MEM_KEY_A_OFFSET + MEM_KEY_SIZE; + uint16_t SectorStartAddress; + uint8_t Key[6]; + uint8_t Uid[4]; + uint8_t CardNonce[8]; - /* Fix for MFClassic 4k cards */ - if(Buffer[1] >= 128) { - SectorStartAddress = (Buffer[1] & MEM_BIGSECTOR_ADDR_MASK) * MEM_BYTES_PER_BLOCK ; - KeyOffset += MEM_KEY_BIGSECTOR_OFFSET; - AccessOffset += MEM_KEY_BIGSECTOR_OFFSET; - } else { - SectorStartAddress = (Buffer[1] & MEM_SECTOR_ADDR_MASK) * MEM_BYTES_PER_BLOCK ; - } + /* Fix for MFClassic 4k cards */ + if(Buffer[1] >= 128) { + SectorStartAddress = (Buffer[1] & MEM_BIGSECTOR_ADDR_MASK) * MEM_BYTES_PER_BLOCK ; + KeyOffset += MEM_KEY_BIGSECTOR_OFFSET; + AccessOffset += MEM_KEY_BIGSECTOR_OFFSET; + } else { + SectorStartAddress = (Buffer[1] & MEM_SECTOR_ADDR_MASK) * MEM_BYTES_PER_BLOCK ; + } - LogEntry(LOG_INFO_APP_CMD_AUTH, Buffer, 2); - /* set KeyInUse for global use to keep info about authentication */ - KeyInUse = Buffer[0] & 1; - CurrentAddress = SectorStartAddress / MEM_BYTES_PER_BLOCK; - //if (!AccessConditions[MEM_ACC_GPB_SIZE-1] ||(CurrentAddress != AccessAddress)) { - /* Get access conditions from the sector trailor */ - MemoryReadBlock(AccessConditions, SectorStartAddress + AccessOffset, MEM_ACC_GPB_SIZE); - AccessAddress = CurrentAddress; - //} + LogEntry(LOG_INFO_APP_CMD_AUTH, Buffer, 2); + /* set KeyInUse for global use to keep info about authentication */ + KeyInUse = Buffer[0] & 1; + CurrentAddress = SectorStartAddress / MEM_BYTES_PER_BLOCK; + //if (!AccessConditions[MEM_ACC_GPB_SIZE-1] ||(CurrentAddress != AccessAddress)) { + /* Get access conditions from the sector trailor */ + MemoryReadBlock(AccessConditions, SectorStartAddress + AccessOffset, MEM_ACC_GPB_SIZE); + AccessAddress = CurrentAddress; + //} - /* Generate a random nonce and read UID and key from memory */ - RandomGetBuffer(CardNonce, sizeof(CardNonce)); - if (ActiveConfiguration.UidSize == 7) - MemoryReadBlock(Uid, MEM_UID_CL2_ADDRESS, MEM_UID_CL2_SIZE); - else - MemoryReadBlock(Uid, MEM_UID_CL1_ADDRESS, MEM_UID_CL1_SIZE); - MemoryReadBlock(Key, SectorStartAddress + KeyOffset, MEM_KEY_SIZE); + /* Generate a random nonce and read UID and key from memory */ + RandomGetBuffer(CardNonce, sizeof(CardNonce)); + if (ActiveConfiguration.UidSize == 7) + MemoryReadBlock(Uid, MEM_UID_CL2_ADDRESS, MEM_UID_CL2_SIZE); + else + MemoryReadBlock(Uid, MEM_UID_CL1_ADDRESS, MEM_UID_CL1_SIZE); + MemoryReadBlock(Key, SectorStartAddress + KeyOffset, MEM_KEY_SIZE); - /* Precalculate the reader response from card-nonce */ - for (uint8_t i=0; i= 128) { - SectorStartAddress = (Buffer[1] & MEM_BIGSECTOR_ADDR_MASK) * MEM_BYTES_PER_BLOCK ; - KeyOffset += MEM_KEY_BIGSECTOR_OFFSET; - AccOffset += MEM_KEY_BIGSECTOR_OFFSET; - } else { - SectorStartAddress = (Buffer[1] & MEM_SECTOR_ADDR_MASK) * MEM_BYTES_PER_BLOCK ; - } + /* Fix for MFClassic 4k cards */ + if(Buffer[1] >= 128) { + SectorStartAddress = (Buffer[1] & MEM_BIGSECTOR_ADDR_MASK) * MEM_BYTES_PER_BLOCK ; + KeyOffset += MEM_KEY_BIGSECTOR_OFFSET; + AccOffset += MEM_KEY_BIGSECTOR_OFFSET; + } else { + SectorStartAddress = (Buffer[1] & MEM_SECTOR_ADDR_MASK) * MEM_BYTES_PER_BLOCK ; + } - LogEntry(LOG_INFO_APP_CMD_AUTH, Buffer, 2); - /* set KeyInUse for global use to keep info about authentication */ - KeyInUse = Buffer[0] & 1; - CurrentAddress = SectorStartAddress / MEM_BYTES_PER_BLOCK; - if (CurrentAddress != AccessAddress) { - /* Get access conditions from the sector trailor */ - MemoryReadBlock(AccessConditions, SectorStartAddress + AccOffset, MEM_ACC_GPB_SIZE); - AccessAddress = CurrentAddress; - } + LogEntry(LOG_INFO_APP_CMD_AUTH, Buffer, 2); + /* set KeyInUse for global use to keep info about authentication */ + KeyInUse = Buffer[0] & 1; + CurrentAddress = SectorStartAddress / MEM_BYTES_PER_BLOCK; + if (CurrentAddress != AccessAddress) { + /* Get access conditions from the sector trailor */ + MemoryReadBlock(AccessConditions, SectorStartAddress + AccOffset, MEM_ACC_GPB_SIZE); + AccessAddress = CurrentAddress; + } - /* Generate a random nonce and read UID and key from memory */ - RandomGetBuffer(CardNonce, sizeof(CardNonce)); - if (ActiveConfiguration.UidSize == 7) - MemoryReadBlock(Uid, MEM_UID_CL2_ADDRESS, MEM_UID_CL2_SIZE); - else - MemoryReadBlock(Uid, MEM_UID_CL1_ADDRESS, MEM_UID_CL1_SIZE); - MemoryReadBlock(Key, SectorStartAddress + KeyOffset, MEM_KEY_SIZE); + /* Generate a random nonce and read UID and key from memory */ + RandomGetBuffer(CardNonce, sizeof(CardNonce)); + if (ActiveConfiguration.UidSize == 7) + MemoryReadBlock(Uid, MEM_UID_CL2_ADDRESS, MEM_UID_CL2_SIZE); + else + MemoryReadBlock(Uid, MEM_UID_CL1_ADDRESS, MEM_UID_CL1_SIZE); + MemoryReadBlock(Key, SectorStartAddress + KeyOffset, MEM_KEY_SIZE); - /* Precalculate the reader response from card-nonce */ - for (uint8_t i=0; i= Buffer) // loop over all input bytes - { - parity = OddParityBit(*currByte); // get parity bit - tmpByte = lastByte; - while (tmpByte > currByte) // loop over all bytes from the last byte to the current one -- shifts the whole byte string - { - *tmpByte <<= 1; // shift this byte - *tmpByte |= (*(tmpByte-1) & 0x80) >> 7; // insert the last bit from the previous byte - tmpByte--; // go to the previous byte - } - *(++tmpByte) &= 0xFE; // zeroize the bit, where we want to put the parity bit - *tmpByte |= parity & 1; // add the parity bit - currByte--; // go to previous input byte - } - return BitCount + (BitCount / 8); + if (BitCount == 7) + return 7; + if (BitCount % 8) + return BitCount; + uint8_t * currByte, * tmpByte; + uint8_t * const lastByte = Buffer + BitCount/8 + BitCount/64; // starting address + number of bytes + number of parity bytes + currByte = Buffer + BitCount/8 - 1; + uint8_t parity; + memset(currByte+1, 0, lastByte-currByte); // zeroize all bytes used for parity bits + while (currByte >= Buffer) // loop over all input bytes + { + parity = OddParityBit(*currByte); // get parity bit + tmpByte = lastByte; + while (tmpByte > currByte) // loop over all bytes from the last byte to the current one -- shifts the whole byte string + { + *tmpByte <<= 1; // shift this byte + *tmpByte |= (*(tmpByte-1) & 0x80) >> 7; // insert the last bit from the previous byte + tmpByte--; // go to the previous byte + } + *(++tmpByte) &= 0xFE; // zeroize the bit, where we want to put the parity bit + *tmpByte |= parity & 1; // add the parity bit + currByte--; // go to previous input byte + } + return BitCount + (BitCount / 8); } uint16_t removeParityBits(uint8_t * Buffer, uint16_t BitCount) { - if (BitCount == 7) - return 7; + if (BitCount == 7) + return 7; - uint16_t i; - for (i = 0; i < (BitCount / 9); i++) - { - Buffer[i] = (Buffer[i + i/8] >> (i%8)); - if (i%8) - Buffer[i] |= (Buffer[i + i/8 + 1] << (8 - (i % 8))); - } - return BitCount/9*8; + uint16_t i; + for (i = 0; i < (BitCount / 9); i++) + { + Buffer[i] = (Buffer[i + i/8] >> (i%8)); + if (i%8) + Buffer[i] |= (Buffer[i + i/8 + 1] << (8 - (i % 8))); + } + return BitCount/9*8; } uint16_t removeSOC(uint8_t * Buffer, uint16_t BitCount) { - if (BitCount == 0) - return 0; - uint16_t i; - Buffer[0] >>= 1; - for (i = 1; i < (BitCount + 7) / 8; i++) - { - Buffer[i-1] |= Buffer[i] << 7; - Buffer[i] >>= 1; - } - return BitCount - 1; + if (BitCount == 0) + return 0; + uint16_t i; + Buffer[0] >>= 1; + for (i = 1; i < (BitCount + 7) / 8; i++) + { + Buffer[i-1] |= Buffer[i] << 7; + Buffer[i] >>= 1; + } + return BitCount - 1; } bool checkParityBits(uint8_t * Buffer, uint16_t BitCount) { - if (BitCount == 7) - return true; + if (BitCount == 7) + return true; - //if (BitCount % 9 || BitCount == 0) - // return false; + //if (BitCount % 9 || BitCount == 0) + // return false; - uint16_t i; - uint8_t currentByte, parity; - for (i = 0; i < (BitCount / 9); i++) - { - currentByte = (Buffer[i + i/8] >> (i%8)); - if (i%8) - currentByte |= (Buffer[i + i/8 + 1] << (8 - (i % 8))); - parity = OddParityBit(currentByte); - if (((Buffer[i + i/8 + 1] >> (i % 8)) ^ parity) & 1) { - return false; - } - } - return true; + uint16_t i; + uint8_t currentByte, parity; + for (i = 0; i < (BitCount / 9); i++) + { + currentByte = (Buffer[i + i/8] >> (i%8)); + if (i%8) + currentByte |= (Buffer[i + i/8 + 1] << (8 - (i % 8))); + parity = OddParityBit(currentByte); + if (((Buffer[i + i/8 + 1] >> (i % 8)) ^ parity) & 1) { + return false; + } + } + return true; } void Reader14443AAppTimeout(void) { - Reader14443AAppReset(); - Reader14443ACodecReset(); - ReaderState = STATE_IDLE; + Reader14443AAppReset(); + Reader14443ACodecReset(); + ReaderState = STATE_IDLE; } void Reader14443AAppInit(void) { - ReaderState = STATE_IDLE; + ReaderState = STATE_IDLE; } void Reader14443AAppReset(void) { - ReaderState = STATE_IDLE; - Reader14443CurrentCommand = Reader14443_Do_Nothing; - Selected = false; + ReaderState = STATE_IDLE; + Reader14443CurrentCommand = Reader14443_Do_Nothing; + Selected = false; } void Reader14443AAppTask(void) @@ -210,265 +210,265 @@ void Reader14443AAppTick(void) INLINE uint16_t Reader14443A_Deselect(uint8_t* Buffer) // deselects the card because of an error, so we will continue to select the card afterwards { - Buffer[0] = 0xC2; - uint16_t crc = ISO14443_CRCA(Buffer, 1); - Buffer[1] = crc; - Buffer[2] = crc >> 8; - ReaderState = STATE_DESELECT; - Selected = false; - return addParityBits(Buffer, 24); + Buffer[0] = 0xC2; + uint16_t crc = ISO14443_CRCA(Buffer, 1); + Buffer[1] = crc; + Buffer[2] = crc >> 8; + ReaderState = STATE_DESELECT; + Selected = false; + return addParityBits(Buffer, 24); } INLINE uint16_t Reader14443A_Select(uint8_t * Buffer, uint16_t BitCount) { - if (Selected) - { - if (ReaderState > STATE_HALT) - return 0; - else - Selected = false; - } - switch (ReaderState) - { - case STATE_IDLE: - case STATE_HALT: - Reader_FWT = ISO14443A_RX_PENDING_TIMEOUT; - /* Send a REQA */ - Buffer[0] = ISO14443A_CMD_WUPA; // whenever REQA works, WUPA also works, so we choose WUPA always - ReaderState = STATE_READY; - return 7; + if (Selected) + { + if (ReaderState > STATE_HALT) + return 0; + else + Selected = false; + } + switch (ReaderState) + { + case STATE_IDLE: + case STATE_HALT: + Reader_FWT = ISO14443A_RX_PENDING_TIMEOUT; + /* Send a REQA */ + Buffer[0] = ISO14443A_CMD_WUPA; // whenever REQA works, WUPA also works, so we choose WUPA always + ReaderState = STATE_READY; + return 7; - case STATE_READY: - if (BitCount < 19) - { - ReaderState = STATE_IDLE; - Reader14443ACodecStart(); - return 0; - } - BitCount = removeSOC(Buffer, BitCount); - if (!checkParityBits(Buffer, BitCount)) - { - ReaderState = STATE_IDLE; - LogEntry(LOG_ERR_APP_CHECKSUM_FAIL, Buffer, (BitCount + 8) / 7); - Reader14443ACodecStart(); - return 0; - } - BitCount = removeParityBits(Buffer, BitCount); - CardCharacteristics.ATQA = Buffer[1] << 8 | Buffer[0]; // save ATQA for possible later use - Buffer[0] = ISO14443A_CMD_SELECT_CL1; - Buffer[1] = 0x20; // NVB = 16 - ReaderState = STATE_ACTIVE_CL1; - return addParityBits(Buffer, 16); + case STATE_READY: + if (BitCount < 19) + { + ReaderState = STATE_IDLE; + Reader14443ACodecStart(); + return 0; + } + BitCount = removeSOC(Buffer, BitCount); + if (!checkParityBits(Buffer, BitCount)) + { + ReaderState = STATE_IDLE; + LogEntry(LOG_ERR_APP_CHECKSUM_FAIL, Buffer, (BitCount + 8) / 7); + Reader14443ACodecStart(); + return 0; + } + BitCount = removeParityBits(Buffer, BitCount); + CardCharacteristics.ATQA = Buffer[1] << 8 | Buffer[0]; // save ATQA for possible later use + Buffer[0] = ISO14443A_CMD_SELECT_CL1; + Buffer[1] = 0x20; // NVB = 16 + ReaderState = STATE_ACTIVE_CL1; + return addParityBits(Buffer, 16); - case STATE_ACTIVE_CL1 ... STATE_ACTIVE_CL3: - BitCount = removeSOC(Buffer, BitCount); - if (!checkParityBits(Buffer, BitCount) || BitCount < 8) - { - ReaderState = STATE_IDLE; - LogEntry(LOG_ERR_APP_CHECKSUM_FAIL, Buffer, (BitCount + 8) / 7); - Reader14443ACodecStart(); - return 0; - } - BitCount = removeParityBits(Buffer, BitCount); - if (!CHECK_BCC(Buffer)) - { - ReaderState = STATE_IDLE; - Reader14443ACodecStart(); - return 0; - } + case STATE_ACTIVE_CL1 ... STATE_ACTIVE_CL3: + BitCount = removeSOC(Buffer, BitCount); + if (!checkParityBits(Buffer, BitCount) || BitCount < 8) + { + ReaderState = STATE_IDLE; + LogEntry(LOG_ERR_APP_CHECKSUM_FAIL, Buffer, (BitCount + 8) / 7); + Reader14443ACodecStart(); + return 0; + } + BitCount = removeParityBits(Buffer, BitCount); + if (!CHECK_BCC(Buffer)) + { + ReaderState = STATE_IDLE; + Reader14443ACodecStart(); + return 0; + } - if (Buffer[0] == ISO14443A_UID0_CT) - { - memcpy(CardCharacteristics.UID + (ReaderState - STATE_ACTIVE_CL1) * 3, Buffer + 1, 3); - } else { - memcpy(CardCharacteristics.UID + (ReaderState - STATE_ACTIVE_CL1) * 3, Buffer, 4); - } - // shift received UID two bytes to the right - memmove(Buffer+2, Buffer, 5); - Buffer[0] = (ReaderState == STATE_ACTIVE_CL1) ? ISO14443A_CMD_SELECT_CL1 : (ReaderState == STATE_ACTIVE_CL2) ? ISO14443A_CMD_SELECT_CL2 : ISO14443A_CMD_SELECT_CL3; - Buffer[1] = 0x70; // NVB = 56 - uint16_t crc = ISO14443_CRCA(Buffer, 7); - Buffer[7] = crc & 0xFF; - Buffer[8] = crc >> 8; - ReaderState = ReaderState - STATE_ACTIVE_CL1 + STATE_SAK_CL1; - return addParityBits(Buffer, 72); + if (Buffer[0] == ISO14443A_UID0_CT) + { + memcpy(CardCharacteristics.UID + (ReaderState - STATE_ACTIVE_CL1) * 3, Buffer + 1, 3); + } else { + memcpy(CardCharacteristics.UID + (ReaderState - STATE_ACTIVE_CL1) * 3, Buffer, 4); + } + // shift received UID two bytes to the right + memmove(Buffer+2, Buffer, 5); + Buffer[0] = (ReaderState == STATE_ACTIVE_CL1) ? ISO14443A_CMD_SELECT_CL1 : (ReaderState == STATE_ACTIVE_CL2) ? ISO14443A_CMD_SELECT_CL2 : ISO14443A_CMD_SELECT_CL3; + Buffer[1] = 0x70; // NVB = 56 + uint16_t crc = ISO14443_CRCA(Buffer, 7); + Buffer[7] = crc & 0xFF; + Buffer[8] = crc >> 8; + ReaderState = ReaderState - STATE_ACTIVE_CL1 + STATE_SAK_CL1; + return addParityBits(Buffer, 72); - case STATE_SAK_CL1 ... STATE_SAK_CL3: - if (BitCount < 9) - { - ReaderState = STATE_IDLE; - Reader14443ACodecStart(); - return 0; - } - BitCount = removeSOC(Buffer, BitCount); - if (!checkParityBits(Buffer, BitCount)) - { - LogEntry(LOG_ERR_APP_CHECKSUM_FAIL, Buffer, (BitCount + 8) / 7); - ReaderState = STATE_IDLE; - Reader14443ACodecStart(); - return 0; - } - BitCount = removeParityBits(Buffer, BitCount); - if (ISO14443_CRCA(Buffer, 3)) - { - ReaderState = STATE_IDLE; - Reader14443ACodecStart(); - return 0; - } - if (IS_CASCADE_BIT_SET(Buffer) && ReaderState != STATE_SAK_CL3) - { - Buffer[0] = (ReaderState == STATE_SAK_CL1) ? ISO14443A_CMD_SELECT_CL2 : ISO14443A_CMD_SELECT_CL3; - Buffer[1] = 0x20; // NVB = 16 bit - ReaderState = ReaderState - STATE_SAK_CL1 + STATE_ACTIVE_CL1 + 1; - return addParityBits(Buffer, 16); - } else if (IS_CASCADE_BIT_SET(Buffer) && ReaderState == STATE_SAK_CL3) { - // TODO handle this very strange hopefully not happening error - } - Selected = true; - CardCharacteristics.UIDSize = (ReaderState - STATE_SAK_CL1) * 3 + 4; - CardCharacteristics.SAK = Buffer[0]; // save last SAK for possible later use + case STATE_SAK_CL1 ... STATE_SAK_CL3: + if (BitCount < 9) + { + ReaderState = STATE_IDLE; + Reader14443ACodecStart(); + return 0; + } + BitCount = removeSOC(Buffer, BitCount); + if (!checkParityBits(Buffer, BitCount)) + { + LogEntry(LOG_ERR_APP_CHECKSUM_FAIL, Buffer, (BitCount + 8) / 7); + ReaderState = STATE_IDLE; + Reader14443ACodecStart(); + return 0; + } + BitCount = removeParityBits(Buffer, BitCount); + if (ISO14443_CRCA(Buffer, 3)) + { + ReaderState = STATE_IDLE; + Reader14443ACodecStart(); + return 0; + } + if (IS_CASCADE_BIT_SET(Buffer) && ReaderState != STATE_SAK_CL3) + { + Buffer[0] = (ReaderState == STATE_SAK_CL1) ? ISO14443A_CMD_SELECT_CL2 : ISO14443A_CMD_SELECT_CL3; + Buffer[1] = 0x20; // NVB = 16 bit + ReaderState = ReaderState - STATE_SAK_CL1 + STATE_ACTIVE_CL1 + 1; + return addParityBits(Buffer, 16); + } else if (IS_CASCADE_BIT_SET(Buffer) && ReaderState == STATE_SAK_CL3) { + // TODO handle this very strange hopefully not happening error + } + Selected = true; + CardCharacteristics.UIDSize = (ReaderState - STATE_SAK_CL1) * 3 + 4; + CardCharacteristics.SAK = Buffer[0]; // save last SAK for possible later use - return 0; + return 0; - case STATE_DESELECT: - if (BitCount == 0) // most likely the card already understood the deselect - { - ReaderState = STATE_HALT; - Reader14443ACodecStart(); - return 0; - } - BitCount = removeSOC(Buffer, BitCount); - if (!checkParityBits(Buffer, BitCount)) - { - LogEntry(LOG_ERR_APP_CHECKSUM_FAIL, Buffer, (BitCount + 8) / 7); - return Reader14443A_Deselect(Buffer); - } - BitCount = removeParityBits(Buffer, BitCount); - if (ISO14443_CRCA(Buffer, 3)) - { - return Reader14443A_Deselect(Buffer); - } - ReaderState = STATE_HALT; - Reader14443ACodecStart(); - return 0; + case STATE_DESELECT: + if (BitCount == 0) // most likely the card already understood the deselect + { + ReaderState = STATE_HALT; + Reader14443ACodecStart(); + return 0; + } + BitCount = removeSOC(Buffer, BitCount); + if (!checkParityBits(Buffer, BitCount)) + { + LogEntry(LOG_ERR_APP_CHECKSUM_FAIL, Buffer, (BitCount + 8) / 7); + return Reader14443A_Deselect(Buffer); + } + BitCount = removeParityBits(Buffer, BitCount); + if (ISO14443_CRCA(Buffer, 3)) + { + return Reader14443A_Deselect(Buffer); + } + ReaderState = STATE_HALT; + Reader14443ACodecStart(); + return 0; - default: - return 0; - } + default: + return 0; + } } INLINE uint16_t Reader14443A_Halt(uint8_t* Buffer) { - Buffer[0] = ISO14443A_CMD_HLTA; - Buffer[1] = 0x00; - uint16_t crc = ISO14443_CRCA(Buffer, 2); - Buffer[2] = crc; - Buffer[3] = crc >> 8; - ReaderState = STATE_HALT; - Selected = false; - return addParityBits(Buffer, 32); + Buffer[0] = ISO14443A_CMD_HLTA; + Buffer[1] = 0x00; + uint16_t crc = ISO14443_CRCA(Buffer, 2); + Buffer[2] = crc; + Buffer[3] = crc >> 8; + ReaderState = STATE_HALT; + Selected = false; + return addParityBits(Buffer, 32); } INLINE uint16_t Reader14443A_RATS(uint8_t* Buffer) { - Buffer[0] = 0xE0; // RATS command - Buffer[1] = 0x80; - uint16_t crc = ISO14443_CRCA(Buffer, 2); - Buffer[2] = crc; - Buffer[3] = crc >> 8; - ReaderState = STATE_ATS; - return addParityBits(Buffer, 32); + Buffer[0] = 0xE0; // RATS command + Buffer[1] = 0x80; + uint16_t crc = ISO14443_CRCA(Buffer, 2); + Buffer[2] = crc; + Buffer[3] = crc >> 8; + ReaderState = STATE_ATS; + return addParityBits(Buffer, 32); } uint16_t Reader14443AAppProcess(uint8_t* Buffer, uint16_t BitCount) { - switch (Reader14443CurrentCommand) - { - case Reader14443_Send: - { - if (ReaderSendBitCount) - { - memcpy(Buffer, ReaderSendBuffer, (ReaderSendBitCount + 7) / 8); - uint16_t tmp = addParityBits(Buffer, ReaderSendBitCount); - ReaderSendBitCount = 0; - return tmp; - } + switch (Reader14443CurrentCommand) + { + case Reader14443_Send: + { + if (ReaderSendBitCount) + { + memcpy(Buffer, ReaderSendBuffer, (ReaderSendBitCount + 7) / 8); + uint16_t tmp = addParityBits(Buffer, ReaderSendBitCount); + ReaderSendBitCount = 0; + return tmp; + } - if (BitCount == 0) - { - char tmpBuf[] = "NO DATA"; - Reader14443CurrentCommand = Reader14443_Do_Nothing; - CommandLinePendingTaskFinished(COMMAND_INFO_OK_WITH_TEXT_ID, tmpBuf); - return 0; - } - char tmpBuf[128]; - BitCount = removeSOC(Buffer, BitCount); - bool parity = checkParityBits(Buffer, BitCount); - BitCount = removeParityBits(Buffer, BitCount); - if ((2 * (BitCount + 7) / 8 + 2 + 4) > 128) // 2 = \r\n, 4 = size of bitcount in hex - { - sprintf(tmpBuf, "Too many data."); - Reader14443CurrentCommand = Reader14443_Do_Nothing; - CommandLinePendingTaskFinished(COMMAND_INFO_OK_WITH_TEXT_ID, tmpBuf); - return 0; - } - uint16_t charCnt = BufferToHexString(tmpBuf, 128, Buffer, (BitCount + 7) / 8); - uint8_t count[2] = {(BitCount>>8)&0xFF, BitCount&0xFF}; - charCnt += snprintf(tmpBuf + charCnt, 128 - charCnt, "\r\n"); - charCnt += BufferToHexString(tmpBuf + charCnt, 128 - charCnt, count, 2); - if (!parity) - snprintf(tmpBuf + charCnt, 128 - charCnt, "\r\nPARITY ERROR"); - else - snprintf(tmpBuf + charCnt, 128 - charCnt, "\r\nPARITY OK"); - Reader14443CurrentCommand = Reader14443_Do_Nothing; - CommandLinePendingTaskFinished(COMMAND_INFO_OK_WITH_TEXT_ID, tmpBuf); - return 0; - } + if (BitCount == 0) + { + char tmpBuf[] = "NO DATA"; + Reader14443CurrentCommand = Reader14443_Do_Nothing; + CommandLinePendingTaskFinished(COMMAND_INFO_OK_WITH_TEXT_ID, tmpBuf); + return 0; + } + char tmpBuf[128]; + BitCount = removeSOC(Buffer, BitCount); + bool parity = checkParityBits(Buffer, BitCount); + BitCount = removeParityBits(Buffer, BitCount); + if ((2 * (BitCount + 7) / 8 + 2 + 4) > 128) // 2 = \r\n, 4 = size of bitcount in hex + { + sprintf(tmpBuf, "Too many data."); + Reader14443CurrentCommand = Reader14443_Do_Nothing; + CommandLinePendingTaskFinished(COMMAND_INFO_OK_WITH_TEXT_ID, tmpBuf); + return 0; + } + uint16_t charCnt = BufferToHexString(tmpBuf, 128, Buffer, (BitCount + 7) / 8); + uint8_t count[2] = {(BitCount>>8)&0xFF, BitCount&0xFF}; + charCnt += snprintf(tmpBuf + charCnt, 128 - charCnt, "\r\n"); + charCnt += BufferToHexString(tmpBuf + charCnt, 128 - charCnt, count, 2); + if (!parity) + snprintf(tmpBuf + charCnt, 128 - charCnt, "\r\nPARITY ERROR"); + else + snprintf(tmpBuf + charCnt, 128 - charCnt, "\r\nPARITY OK"); + Reader14443CurrentCommand = Reader14443_Do_Nothing; + CommandLinePendingTaskFinished(COMMAND_INFO_OK_WITH_TEXT_ID, tmpBuf); + return 0; + } - case Reader14443_Send_Raw: - { - if (ReaderSendBitCount) - { - memcpy(Buffer, ReaderSendBuffer, (ReaderSendBitCount + 7) / 8); - uint16_t tmp = ReaderSendBitCount; - ReaderSendBitCount = 0; - return tmp; - } + case Reader14443_Send_Raw: + { + if (ReaderSendBitCount) + { + memcpy(Buffer, ReaderSendBuffer, (ReaderSendBitCount + 7) / 8); + uint16_t tmp = ReaderSendBitCount; + ReaderSendBitCount = 0; + return tmp; + } - if (BitCount == 0) - { - char tmpBuf[] = "NO DATA"; - Reader14443CurrentCommand = Reader14443_Do_Nothing; - CommandLinePendingTaskFinished(COMMAND_INFO_OK_WITH_TEXT_ID, tmpBuf); - return 0; - } + if (BitCount == 0) + { + char tmpBuf[] = "NO DATA"; + Reader14443CurrentCommand = Reader14443_Do_Nothing; + CommandLinePendingTaskFinished(COMMAND_INFO_OK_WITH_TEXT_ID, tmpBuf); + return 0; + } - char tmpBuf[128]; - uint16_t charCnt = BufferToHexString(tmpBuf, 128, Buffer, (BitCount + 7) / 8); - uint8_t count[2] = {(BitCount>>8)&0xFF, BitCount&0xFF}; - charCnt += snprintf(tmpBuf + charCnt, 128 - charCnt, "\r\n"); - charCnt += BufferToHexString(tmpBuf + charCnt, 128 - charCnt, count, 2); - Reader14443CurrentCommand = Reader14443_Do_Nothing; - CommandLinePendingTaskFinished(COMMAND_INFO_OK_WITH_TEXT_ID, tmpBuf); - return 0; - } + char tmpBuf[128]; + uint16_t charCnt = BufferToHexString(tmpBuf, 128, Buffer, (BitCount + 7) / 8); + uint8_t count[2] = {(BitCount>>8)&0xFF, BitCount&0xFF}; + charCnt += snprintf(tmpBuf + charCnt, 128 - charCnt, "\r\n"); + charCnt += BufferToHexString(tmpBuf + charCnt, 128 - charCnt, count, 2); + Reader14443CurrentCommand = Reader14443_Do_Nothing; + CommandLinePendingTaskFinished(COMMAND_INFO_OK_WITH_TEXT_ID, tmpBuf); + return 0; + } - case Reader14443_Get_UID: - { - uint16_t rVal = Reader14443A_Select(Buffer, BitCount); - if (Selected) // we are done finding the UID - { - char tmpBuf[20]; - BufferToHexString(tmpBuf, 20, CardCharacteristics.UID, CardCharacteristics.UIDSize); - CommandLinePendingTaskFinished(COMMAND_INFO_OK_WITH_TEXT_ID, tmpBuf); - Selected = false; - Reader14443CurrentCommand = Reader14443_Do_Nothing; - CodecReaderFieldStop(); - return 0; - } - return rVal; - } + case Reader14443_Get_UID: + { + uint16_t rVal = Reader14443A_Select(Buffer, BitCount); + if (Selected) // we are done finding the UID + { + char tmpBuf[20]; + BufferToHexString(tmpBuf, 20, CardCharacteristics.UID, CardCharacteristics.UIDSize); + CommandLinePendingTaskFinished(COMMAND_INFO_OK_WITH_TEXT_ID, tmpBuf); + Selected = false; + Reader14443CurrentCommand = Reader14443_Do_Nothing; + CodecReaderFieldStop(); + return 0; + } + return rVal; + } case Reader14443_Autocalibrate: { @@ -554,282 +554,282 @@ uint16_t Reader14443AAppProcess(uint8_t* Buffer, uint16_t BitCount) return rVal; } - case Reader14443_Read_MF_Ultralight: - { - static uint8_t MFURead_CurrentAdress = 0; - static uint8_t MFUContents[64]; + case Reader14443_Read_MF_Ultralight: + { + static uint8_t MFURead_CurrentAdress = 0; + static uint8_t MFUContents[64]; - uint16_t rVal = Reader14443A_Select(Buffer, BitCount); - if (Selected) - { - if (MFURead_CurrentAdress != 0) - { - BitCount = removeSOC(Buffer, BitCount); - if (BitCount == 0) // relaunch select protocol - { - MFURead_CurrentAdress = 0; // reset read address - Selected = false; - ReaderState = STATE_IDLE; - Reader14443ACodecStart(); - return 0; - } - bool readPageAgain = (BitCount < 162) || !checkParityBits(Buffer, BitCount); - BitCount = removeParityBits(Buffer, BitCount); - if (readPageAgain || ISO14443_CRCA(Buffer, 18)) // the CRC function should return 0 if everything is ok - { - MFURead_CurrentAdress -= 4; - } else { // everything is ok for this page - memcpy(MFUContents + (MFURead_CurrentAdress - 4) * 4, Buffer, 16); - } - } else { - uint16_t RefATQA; - memcpy_P(&RefATQA, &CardIdentificationList[CardType_NXP_MIFARE_Ultralight].ATQA, 2); - uint8_t RefSAK = pgm_read_byte(&CardIdentificationList[CardType_NXP_MIFARE_Ultralight].SAK); - if (CardCharacteristics.ATQA != RefATQA || CardCharacteristics.SAK != RefSAK) // seems to be no MiFare Ultralight card, so retry - { - ReaderState = STATE_IDLE; - Reader14443ACodecStart(); - return 0; - } - } - if (MFURead_CurrentAdress == 16) - { - Selected = false; - MFURead_CurrentAdress = 0; - Reader14443CurrentCommand = Reader14443_Do_Nothing; + uint16_t rVal = Reader14443A_Select(Buffer, BitCount); + if (Selected) + { + if (MFURead_CurrentAdress != 0) + { + BitCount = removeSOC(Buffer, BitCount); + if (BitCount == 0) // relaunch select protocol + { + MFURead_CurrentAdress = 0; // reset read address + Selected = false; + ReaderState = STATE_IDLE; + Reader14443ACodecStart(); + return 0; + } + bool readPageAgain = (BitCount < 162) || !checkParityBits(Buffer, BitCount); + BitCount = removeParityBits(Buffer, BitCount); + if (readPageAgain || ISO14443_CRCA(Buffer, 18)) // the CRC function should return 0 if everything is ok + { + MFURead_CurrentAdress -= 4; + } else { // everything is ok for this page + memcpy(MFUContents + (MFURead_CurrentAdress - 4) * 4, Buffer, 16); + } + } else { + uint16_t RefATQA; + memcpy_P(&RefATQA, &CardIdentificationList[CardType_NXP_MIFARE_Ultralight].ATQA, 2); + uint8_t RefSAK = pgm_read_byte(&CardIdentificationList[CardType_NXP_MIFARE_Ultralight].SAK); + if (CardCharacteristics.ATQA != RefATQA || CardCharacteristics.SAK != RefSAK) // seems to be no MiFare Ultralight card, so retry + { + ReaderState = STATE_IDLE; + Reader14443ACodecStart(); + return 0; + } + } + if (MFURead_CurrentAdress == 16) + { + Selected = false; + MFURead_CurrentAdress = 0; + Reader14443CurrentCommand = Reader14443_Do_Nothing; - char tmpBuf[135]; // 135 = 128 hex digits + 3 * \r\n + \0 - BufferToHexString( tmpBuf, 135, MFUContents, 16); - snprintf( tmpBuf + 32, 135 - 32, "\r\n"); - BufferToHexString( tmpBuf + 32 + 2, 135 - 32 - 2, MFUContents + 16, 16); - snprintf( tmpBuf + 32 + 2 + 32, 135 - 32 - 2 - 32, "\r\n"); - BufferToHexString( tmpBuf + 32 + 2 + 32 + 2, 135 - 32 - 2 - 32 - 2, MFUContents + 32, 16); - snprintf( tmpBuf + 32 + 2 + 32 + 2 + 32, 135 - 32 - 2 - 32 - 2 - 32, "\r\n"); - BufferToHexString( tmpBuf + 32 + 2 + 32 + 2 + 32 + 2, 135 - 32 - 2 - 32 - 2 - 32 - 2, MFUContents + 48, 16); - CodecReaderFieldStop(); - CommandLinePendingTaskFinished(COMMAND_INFO_OK_WITH_TEXT_ID, tmpBuf); - return 0; - } - Buffer[0] = 0x30; // MiFare Ultralight read command - Buffer[1] = MFURead_CurrentAdress; - uint16_t crc = ISO14443_CRCA(Buffer, 2); - Buffer[2] = crc; - Buffer[3] = crc >> 8; + char tmpBuf[135]; // 135 = 128 hex digits + 3 * \r\n + \0 + BufferToHexString( tmpBuf, 135, MFUContents, 16); + snprintf( tmpBuf + 32, 135 - 32, "\r\n"); + BufferToHexString( tmpBuf + 32 + 2, 135 - 32 - 2, MFUContents + 16, 16); + snprintf( tmpBuf + 32 + 2 + 32, 135 - 32 - 2 - 32, "\r\n"); + BufferToHexString( tmpBuf + 32 + 2 + 32 + 2, 135 - 32 - 2 - 32 - 2, MFUContents + 32, 16); + snprintf( tmpBuf + 32 + 2 + 32 + 2 + 32, 135 - 32 - 2 - 32 - 2 - 32, "\r\n"); + BufferToHexString( tmpBuf + 32 + 2 + 32 + 2 + 32 + 2, 135 - 32 - 2 - 32 - 2 - 32 - 2, MFUContents + 48, 16); + CodecReaderFieldStop(); + CommandLinePendingTaskFinished(COMMAND_INFO_OK_WITH_TEXT_ID, tmpBuf); + return 0; + } + Buffer[0] = 0x30; // MiFare Ultralight read command + Buffer[1] = MFURead_CurrentAdress; + uint16_t crc = ISO14443_CRCA(Buffer, 2); + Buffer[2] = crc; + Buffer[3] = crc >> 8; - MFURead_CurrentAdress += 4; + MFURead_CurrentAdress += 4; - return addParityBits(Buffer, 32); - } - return rVal; - } + return addParityBits(Buffer, 32); + } + return rVal; + } - /************************************ - * This function identifies a PICC. * - ************************************/ - case Reader14443_Identify: - { - uint16_t rVal = Reader14443A_Select(Buffer, BitCount); - if (Selected) - { - if (ReaderState >= STATE_SAK_CL1 && ReaderState <= STATE_SAK_CL3) - { - bool ISO14443_4A_compliant = IS_ISO14443A_4_COMPLIANT(Buffer); - CardCandidatesIdx = 0; + /************************************ + * This function identifies a PICC. * + ************************************/ + case Reader14443_Identify: + { + uint16_t rVal = Reader14443A_Select(Buffer, BitCount); + if (Selected) + { + if (ReaderState >= STATE_SAK_CL1 && ReaderState <= STATE_SAK_CL3) + { + bool ISO14443_4A_compliant = IS_ISO14443A_4_COMPLIANT(Buffer); + CardCandidatesIdx = 0; - uint8_t i; - for (i = 0; i < ARRAY_COUNT(CardIdentificationList); i++) - { - CardIdentificationType card; - memcpy_P(&card, &CardIdentificationList[i], sizeof(CardIdentificationType)); - if (card.ATQARelevant && card.ATQA != CardCharacteristics.ATQA) - continue; - if (card.SAKRelevant && card.SAK != CardCharacteristics.SAK) - continue; - if (card.ATSRelevant && !ISO14443_4A_compliant) - continue; // for this card type candidate, the ATS is relevant, but the card does not support ISO14443-4A - CardCandidates[CardCandidatesIdx++] = i; - } + uint8_t i; + for (i = 0; i < ARRAY_COUNT(CardIdentificationList); i++) + { + CardIdentificationType card; + memcpy_P(&card, &CardIdentificationList[i], sizeof(CardIdentificationType)); + if (card.ATQARelevant && card.ATQA != CardCharacteristics.ATQA) + continue; + if (card.SAKRelevant && card.SAK != CardCharacteristics.SAK) + continue; + if (card.ATSRelevant && !ISO14443_4A_compliant) + continue; // for this card type candidate, the ATS is relevant, but the card does not support ISO14443-4A + CardCandidates[CardCandidatesIdx++] = i; + } - if (ISO14443_4A_compliant) - { - // send RATS - return Reader14443A_RATS(Buffer); - } - // if we don't have to send the RATS, we are finished for distinguishing with ISO 14443A + if (ISO14443_4A_compliant) + { + // send RATS + return Reader14443A_RATS(Buffer); + } + // if we don't have to send the RATS, we are finished for distinguishing with ISO 14443A - } else if (ReaderState == STATE_ATS) { // we have got the ATS - BitCount = removeSOC(Buffer, BitCount); - if (!checkParityBits(Buffer, BitCount)) - { - LogEntry(LOG_ERR_APP_CHECKSUM_FAIL, Buffer, (BitCount + 8) / 7); - return Reader14443A_Deselect(Buffer); - } - BitCount = removeParityBits(Buffer, BitCount); + } else if (ReaderState == STATE_ATS) { // we have got the ATS + BitCount = removeSOC(Buffer, BitCount); + if (!checkParityBits(Buffer, BitCount)) + { + LogEntry(LOG_ERR_APP_CHECKSUM_FAIL, Buffer, (BitCount + 8) / 7); + return Reader14443A_Deselect(Buffer); + } + BitCount = removeParityBits(Buffer, BitCount); - if (Buffer[0] != BitCount / 8 - 2 || ISO14443_CRCA(Buffer, Buffer[0] + 2)) - { - return Reader14443A_Deselect(Buffer); - } + if (Buffer[0] != BitCount / 8 - 2 || ISO14443_CRCA(Buffer, Buffer[0] + 2)) + { + return Reader14443A_Deselect(Buffer); + } - uint8_t i; - for (i = 0; i < CardCandidatesIdx; i++) - { - CardIdentificationType card; - memcpy_P(&card, &CardIdentificationList[CardCandidates[i]], sizeof(CardIdentificationType)); - if (!card.ATSRelevant || (card.ATSRelevant && card.ATSSize == Buffer[0] - 1 && memcmp(card.ATS, Buffer + 1, card.ATSSize) == 0)) - /* - * If for this candidate the ATS is not relevant, it remains being a candidate. - * If the ATS is relevant and the size is correct and the ATS is the same as the reference value, this candidate remains a candidate. - */ - continue; + uint8_t i; + for (i = 0; i < CardCandidatesIdx; i++) + { + CardIdentificationType card; + memcpy_P(&card, &CardIdentificationList[CardCandidates[i]], sizeof(CardIdentificationType)); + if (!card.ATSRelevant || (card.ATSRelevant && card.ATSSize == Buffer[0] - 1 && memcmp(card.ATS, Buffer + 1, card.ATSSize) == 0)) + /* + * If for this candidate the ATS is not relevant, it remains being a candidate. + * If the ATS is relevant and the size is correct and the ATS is the same as the reference value, this candidate remains a candidate. + */ + continue; - // Else, we have to delete this candidate - uint8_t j; - for (j = i; j < CardCandidatesIdx - 1; j++) - CardCandidates[j] = CardCandidates[j+1]; - CardCandidatesIdx--; - i--; - } - } + // Else, we have to delete this candidate + uint8_t j; + for (j = i; j < CardCandidatesIdx - 1; j++) + CardCandidates[j] = CardCandidates[j+1]; + CardCandidatesIdx--; + i--; + } + } - /* - * If any cards are not distinguishable with ISO14443A commands only, this is the place to run some proprietary commands. - */ + /* + * If any cards are not distinguishable with ISO14443A commands only, this is the place to run some proprietary commands. + */ - if ((ReaderState >= STATE_SAK_CL1 && ReaderState <= STATE_SAK_CL3) || ReaderState == STATE_ATS) - { - uint8_t i; - for (i = 0; i < CardCandidatesIdx; i++) - { - switch (CardCandidates[i]) - { - case CardType_NXP_MIFARE_DESFire: - case CardType_NXP_MIFARE_DESFire_EV1: - Buffer[0] = 0x02; - Buffer[1] = 0x60; - uint16_t crc = ISO14443_CRCA(Buffer, 2); - Buffer[2] = crc; - Buffer[3] = crc >> 8; - ReaderState = STATE_DESFIRE_INFO; - return addParityBits(Buffer, 32); + if ((ReaderState >= STATE_SAK_CL1 && ReaderState <= STATE_SAK_CL3) || ReaderState == STATE_ATS) + { + uint8_t i; + for (i = 0; i < CardCandidatesIdx; i++) + { + switch (CardCandidates[i]) + { + case CardType_NXP_MIFARE_DESFire: + case CardType_NXP_MIFARE_DESFire_EV1: + Buffer[0] = 0x02; + Buffer[1] = 0x60; + uint16_t crc = ISO14443_CRCA(Buffer, 2); + Buffer[2] = crc; + Buffer[3] = crc >> 8; + ReaderState = STATE_DESFIRE_INFO; + return addParityBits(Buffer, 32); - default: - break; - } - } - } else { - switch (ReaderState) - { - case STATE_DESFIRE_INFO: - if (BitCount == 0) - { - CardCandidatesIdx = 0; // this will return that this card is unknown to us - break; - } - BitCount = removeSOC(Buffer, BitCount); - if (!checkParityBits(Buffer, BitCount)) - { - LogEntry(LOG_ERR_APP_CHECKSUM_FAIL, Buffer, (BitCount + 8) / 7); - CardCandidatesIdx = 0; - return Reader14443A_Deselect(Buffer); - } - BitCount = removeParityBits(Buffer, BitCount); - if (ISO14443_CRCA(Buffer, BitCount / 8)) - { - CardCandidatesIdx = 0; - return Reader14443A_Deselect(Buffer); - } - switch (Buffer[5]) - { - case 0x00: - CardCandidatesIdx = 1; - CardCandidates[0] = CardType_NXP_MIFARE_DESFire; - break; + default: + break; + } + } + } else { + switch (ReaderState) + { + case STATE_DESFIRE_INFO: + if (BitCount == 0) + { + CardCandidatesIdx = 0; // this will return that this card is unknown to us + break; + } + BitCount = removeSOC(Buffer, BitCount); + if (!checkParityBits(Buffer, BitCount)) + { + LogEntry(LOG_ERR_APP_CHECKSUM_FAIL, Buffer, (BitCount + 8) / 7); + CardCandidatesIdx = 0; + return Reader14443A_Deselect(Buffer); + } + BitCount = removeParityBits(Buffer, BitCount); + if (ISO14443_CRCA(Buffer, BitCount / 8)) + { + CardCandidatesIdx = 0; + return Reader14443A_Deselect(Buffer); + } + switch (Buffer[5]) + { + case 0x00: + CardCandidatesIdx = 1; + CardCandidates[0] = CardType_NXP_MIFARE_DESFire; + break; - case 0x01: - CardCandidatesIdx = 1; - CardCandidates[0] = CardType_NXP_MIFARE_DESFire_EV1; - break; + case 0x01: + CardCandidatesIdx = 1; + CardCandidates[0] = CardType_NXP_MIFARE_DESFire_EV1; + break; - default: - CardCandidatesIdx = 0; - } - break; + default: + CardCandidatesIdx = 0; + } + break; - default: - break; - } - } + default: + break; + } + } - if (CardCandidatesIdx == 0) - { - CommandLinePendingTaskFinished(COMMAND_INFO_OK_WITH_TEXT_ID, "Unknown card type."); - } else if (CardCandidatesIdx == 1) { - char tmpType[64]; - memcpy_P(tmpType, &CardIdentificationList[CardCandidates[0]].Type, 64); - CommandLinePendingTaskFinished(COMMAND_INFO_OK_WITH_TEXT_ID, tmpType); - } else { - char tmpBuf[TERMINAL_BUFFER_SIZE]; - uint16_t size = 0, tmpsize = 0; - bool enoughspace = true; + if (CardCandidatesIdx == 0) + { + CommandLinePendingTaskFinished(COMMAND_INFO_OK_WITH_TEXT_ID, "Unknown card type."); + } else if (CardCandidatesIdx == 1) { + char tmpType[64]; + memcpy_P(tmpType, &CardIdentificationList[CardCandidates[0]].Type, 64); + CommandLinePendingTaskFinished(COMMAND_INFO_OK_WITH_TEXT_ID, tmpType); + } else { + char tmpBuf[TERMINAL_BUFFER_SIZE]; + uint16_t size = 0, tmpsize = 0; + bool enoughspace = true; - uint8_t i; - for (i = 0; i < CardCandidatesIdx; i++) - { - if (size <= TERMINAL_BUFFER_SIZE) // prevents buffer overflow - { - char tmpType[64]; - memcpy_P(tmpType, &CardIdentificationList[CardCandidates[i]].Type, 64); - tmpsize = snprintf(tmpBuf + size, TERMINAL_BUFFER_SIZE - size, "%s or ", tmpType); - size += tmpsize; - } else { - break; - } - } - if (size > TERMINAL_BUFFER_SIZE) - { - size -= tmpsize; - enoughspace = false; - } - tmpBuf[size-4] = '.'; - tmpBuf[size-3] = '\0'; - CommandLinePendingTaskFinished(COMMAND_INFO_OK_WITH_TEXT_ID, tmpBuf); - if (!enoughspace) - TerminalSendStringP(PSTR("There is at least one more card type candidate, but there was not enough terminal buffer space.\r\n")); - } - // print general data - TerminalSendStringP(PSTR("ATQA:\t")); - CommandLineAppendData(&CardCharacteristics.ATQA, 2); - TerminalSendStringP(PSTR("UID:\t")); - CommandLineAppendData(CardCharacteristics.UID, CardCharacteristics.UIDSize); - TerminalSendStringP(PSTR("SAK:\t")); - CommandLineAppendData(&CardCharacteristics.SAK, 1); + uint8_t i; + for (i = 0; i < CardCandidatesIdx; i++) + { + if (size <= TERMINAL_BUFFER_SIZE) // prevents buffer overflow + { + char tmpType[64]; + memcpy_P(tmpType, &CardIdentificationList[CardCandidates[i]].Type, 64); + tmpsize = snprintf(tmpBuf + size, TERMINAL_BUFFER_SIZE - size, "%s or ", tmpType); + size += tmpsize; + } else { + break; + } + } + if (size > TERMINAL_BUFFER_SIZE) + { + size -= tmpsize; + enoughspace = false; + } + tmpBuf[size-4] = '.'; + tmpBuf[size-3] = '\0'; + CommandLinePendingTaskFinished(COMMAND_INFO_OK_WITH_TEXT_ID, tmpBuf); + if (!enoughspace) + TerminalSendStringP(PSTR("There is at least one more card type candidate, but there was not enough terminal buffer space.\r\n")); + } + // print general data + TerminalSendStringP(PSTR("ATQA:\t")); + CommandLineAppendData(&CardCharacteristics.ATQA, 2); + TerminalSendStringP(PSTR("UID:\t")); + CommandLineAppendData(CardCharacteristics.UID, CardCharacteristics.UIDSize); + TerminalSendStringP(PSTR("SAK:\t")); + CommandLineAppendData(&CardCharacteristics.SAK, 1); - Reader14443CurrentCommand = Reader14443_Do_Nothing; - CardCandidatesIdx = 0; - CodecReaderFieldStop(); - Selected = false; - return 0; - } - return rVal; - } + Reader14443CurrentCommand = Reader14443_Do_Nothing; + CardCandidatesIdx = 0; + CodecReaderFieldStop(); + Selected = false; + return 0; + } + return rVal; + } - default: // e.g. Do_Nothing - return 0; - } - return 0; + default: // e.g. Do_Nothing + return 0; + } + return 0; } uint16_t ISO14443_CRCA(uint8_t * Buffer, uint8_t ByteCount) { - uint8_t * DataPtr = Buffer; - uint16_t crc = 0x6363; - uint8_t ch; - while (ByteCount--) - { - ch = *DataPtr++ ^ crc; - ch = ch ^ (ch << 4); - crc = (crc >> 8) ^ (ch << 8) ^ (ch << 3) ^ (ch >> 4); - } - return crc; + uint8_t * DataPtr = Buffer; + uint16_t crc = 0x6363; + uint8_t ch; + while (ByteCount--) + { + ch = *DataPtr++ ^ crc; + ch = ch ^ (ch << 4); + crc = (crc >> 8) ^ (ch << 8) ^ (ch << 3) ^ (ch >> 4); + } + return crc; } diff --git a/Firmware/Chameleon-Mini/Application/Reader14443A.h b/Firmware/Chameleon-Mini/Application/Reader14443A.h index 97bff8f..e9519ed 100644 --- a/Firmware/Chameleon-Mini/Application/Reader14443A.h +++ b/Firmware/Chameleon-Mini/Application/Reader14443A.h @@ -24,13 +24,13 @@ bool checkParityBits(uint8_t * Buffer, uint16_t BitCount); uint16_t ISO14443_CRCA(uint8_t * Buffer, uint8_t ByteCount); typedef enum { - Reader14443_Do_Nothing, - Reader14443_Send, - Reader14443_Send_Raw, - Reader14443_Get_UID, - Reader14443_Autocalibrate, - Reader14443_Read_MF_Ultralight, - Reader14443_Identify + Reader14443_Do_Nothing, + Reader14443_Send, + Reader14443_Send_Raw, + Reader14443_Get_UID, + Reader14443_Autocalibrate, + Reader14443_Read_MF_Ultralight, + Reader14443_Identify } Reader14443Command; diff --git a/Firmware/Chameleon-Mini/Battery.h b/Firmware/Chameleon-Mini/Battery.h index 3cb335b..850954b 100644 --- a/Firmware/Chameleon-Mini/Battery.h +++ b/Firmware/Chameleon-Mini/Battery.h @@ -16,16 +16,16 @@ #define BATTERY_PORT_MASK (BATTERY_STAT_PIN) INLINE void BatteryInit(void) { - BATTERY_PORT.DIRCLR = BATTERY_PORT_MASK; - BATTERY_PORT.BATTERY_STAT_PINCTRL = PORT_OPC_PULLUP_gc; + BATTERY_PORT.DIRCLR = BATTERY_PORT_MASK; + BATTERY_PORT.BATTERY_STAT_PINCTRL = PORT_OPC_PULLUP_gc; } INLINE bool BatteryIsCharging(void) { - if (!(BATTERY_PORT.IN & BATTERY_STAT_PIN)) { - return true; - } else { - return false; - } + if (!(BATTERY_PORT.IN & BATTERY_STAT_PIN)) { + return true; + } else { + return false; + } } #endif /* BATTERY_H_ */ diff --git a/Firmware/Chameleon-Mini/Button.c b/Firmware/Chameleon-Mini/Button.c index 458db97..d7d5e82 100644 --- a/Firmware/Chameleon-Mini/Button.c +++ b/Firmware/Chameleon-Mini/Button.c @@ -16,17 +16,17 @@ #define LONG_PRESS_TICK_COUNT 10 static const MapEntryType PROGMEM ButtonActionMap[] = { - { .Id = BUTTON_ACTION_NONE, .Text = "NONE" }, - { .Id = BUTTON_ACTION_UID_RANDOM, .Text = "UID_RANDOM" }, - { .Id = BUTTON_ACTION_UID_LEFT_INCREMENT, .Text = "UID_LEFT_INCREMENT" }, - { .Id = BUTTON_ACTION_UID_RIGHT_INCREMENT, .Text = "UID_RIGHT_INCREMENT" }, - { .Id = BUTTON_ACTION_UID_LEFT_DECREMENT, .Text = "UID_LEFT_DECREMENT" }, - { .Id = BUTTON_ACTION_UID_RIGHT_DECREMENT, .Text = "UID_RIGHT_DECREMENT" }, - { .Id = BUTTON_ACTION_CYCLE_SETTINGS, .Text = "CYCLE_SETTINGS" }, - { .Id = BUTTON_ACTION_STORE_MEM, .Text = "STORE_MEM" }, - { .Id = BUTTON_ACTION_RECALL_MEM, .Text = "RECALL_MEM" }, - { .Id = BUTTON_ACTION_TOGGLE_FIELD, .Text = "TOGGLE_FIELD" }, - { .Id = BUTTON_ACTION_STORE_LOG, .Text = "STORE_LOG" }, + { .Id = BUTTON_ACTION_NONE, .Text = "NONE" }, + { .Id = BUTTON_ACTION_UID_RANDOM, .Text = "UID_RANDOM" }, + { .Id = BUTTON_ACTION_UID_LEFT_INCREMENT, .Text = "UID_LEFT_INCREMENT" }, + { .Id = BUTTON_ACTION_UID_RIGHT_INCREMENT, .Text = "UID_RIGHT_INCREMENT" }, + { .Id = BUTTON_ACTION_UID_LEFT_DECREMENT, .Text = "UID_LEFT_DECREMENT" }, + { .Id = BUTTON_ACTION_UID_RIGHT_DECREMENT, .Text = "UID_RIGHT_DECREMENT" }, + { .Id = BUTTON_ACTION_CYCLE_SETTINGS, .Text = "CYCLE_SETTINGS" }, + { .Id = BUTTON_ACTION_STORE_MEM, .Text = "STORE_MEM" }, + { .Id = BUTTON_ACTION_RECALL_MEM, .Text = "RECALL_MEM" }, + { .Id = BUTTON_ACTION_TOGGLE_FIELD, .Text = "TOGGLE_FIELD" }, + { .Id = BUTTON_ACTION_STORE_LOG, .Text = "STORE_LOG" }, }; static void ExecuteButtonAction(ButtonActionEnum ButtonAction) @@ -147,51 +147,51 @@ static void ExecuteButtonAction(ButtonActionEnum ButtonAction) case BUTTON_ACTION_CYCLE_SETTINGS: { - SettingsCycle(); + SettingsCycle(); break; } case BUTTON_ACTION_STORE_MEM: { - MemoryStore(); + MemoryStore(); break; } case BUTTON_ACTION_RECALL_MEM: { - MemoryRecall(); + MemoryRecall(); break; } case BUTTON_ACTION_TOGGLE_FIELD: { - if (!CodecGetReaderField()) - { - CodecReaderFieldStart(); - } else { - CodecReaderFieldStop(); - } - break; + if (!CodecGetReaderField()) + { + CodecReaderFieldStart(); + } else { + CodecReaderFieldStop(); + } + break; } case BUTTON_ACTION_STORE_LOG: { - LogSRAMToFRAM(); - break; + LogSRAMToFRAM(); + break; } default: - break; + break; } } void ButtonInit(void) { - BUTTON_PORT.DIRCLR = BUTTON_MASK; - BUTTON_PORT.BUTTON_R_PINCTRL = PORT_OPC_PULLUP_gc; - BUTTON_PORT.BUTTON_L_PINCTRL = PORT_OPC_PULLUP_gc; + BUTTON_PORT.DIRCLR = BUTTON_MASK; + BUTTON_PORT.BUTTON_R_PINCTRL = PORT_OPC_PULLUP_gc; + BUTTON_PORT.BUTTON_L_PINCTRL = PORT_OPC_PULLUP_gc; } void ButtonTick(void) @@ -201,85 +201,85 @@ void ButtonTick(void) uint8_t ThisButtonState = ~BUTTON_PORT.IN; if (ThisButtonState & BUTTON_R) { - /* Button is currently pressed */ - if (ButtonRPressTick < LONG_PRESS_TICK_COUNT) { - /* Count ticks while button is being pressed */ - ButtonRPressTick++; - } else if (ButtonRPressTick == LONG_PRESS_TICK_COUNT) { - /* Long button press detected execute button action and advance PressTickCounter - * to an invalid state. */ - ExecuteButtonAction(GlobalSettings.ActiveSettingPtr->ButtonActions[BUTTON_R_PRESS_LONG]); - ButtonRPressTick++; - } else { - /* Button is still pressed, ignore */ - } + /* Button is currently pressed */ + if (ButtonRPressTick < LONG_PRESS_TICK_COUNT) { + /* Count ticks while button is being pressed */ + ButtonRPressTick++; + } else if (ButtonRPressTick == LONG_PRESS_TICK_COUNT) { + /* Long button press detected execute button action and advance PressTickCounter + * to an invalid state. */ + ExecuteButtonAction(GlobalSettings.ActiveSettingPtr->ButtonActions[BUTTON_R_PRESS_LONG]); + ButtonRPressTick++; + } else { + /* Button is still pressed, ignore */ + } } else if (!(ThisButtonState & BUTTON_MASK)) { - /* Button is currently not being pressed. Check if PressTickCounter contains - * a recent short button press. */ - if ( (ButtonRPressTick > 0) && (ButtonRPressTick <= LONG_PRESS_TICK_COUNT) ) { - /* We have a short button press */ - ExecuteButtonAction(GlobalSettings.ActiveSettingPtr->ButtonActions[BUTTON_R_PRESS_SHORT]); - } + /* Button is currently not being pressed. Check if PressTickCounter contains + * a recent short button press. */ + if ( (ButtonRPressTick > 0) && (ButtonRPressTick <= LONG_PRESS_TICK_COUNT) ) { + /* We have a short button press */ + ExecuteButtonAction(GlobalSettings.ActiveSettingPtr->ButtonActions[BUTTON_R_PRESS_SHORT]); + } - ButtonRPressTick = 0; + ButtonRPressTick = 0; } if (ThisButtonState & BUTTON_L) { - /* Button is currently pressed */ - if (ButtonLPressTick < LONG_PRESS_TICK_COUNT) { - /* Count ticks while button is being pressed */ - ButtonLPressTick++; - } else if (ButtonLPressTick == LONG_PRESS_TICK_COUNT) { - /* Long button press detected execute button action and advance PressTickCounter - * to an invalid state. */ - ExecuteButtonAction(GlobalSettings.ActiveSettingPtr->ButtonActions[BUTTON_L_PRESS_LONG]); - ButtonLPressTick++; - } else { - /* Button is still pressed, ignore */ - } + /* Button is currently pressed */ + if (ButtonLPressTick < LONG_PRESS_TICK_COUNT) { + /* Count ticks while button is being pressed */ + ButtonLPressTick++; + } else if (ButtonLPressTick == LONG_PRESS_TICK_COUNT) { + /* Long button press detected execute button action and advance PressTickCounter + * to an invalid state. */ + ExecuteButtonAction(GlobalSettings.ActiveSettingPtr->ButtonActions[BUTTON_L_PRESS_LONG]); + ButtonLPressTick++; + } else { + /* Button is still pressed, ignore */ + } } else if (!(ThisButtonState & BUTTON_MASK)) { - /* Button is currently not being pressed. Check if PressTickCounter contains - * a recent short button press. */ - if ( (ButtonLPressTick > 0) && (ButtonLPressTick <= LONG_PRESS_TICK_COUNT) ) { - /* We have a short button press */ - ExecuteButtonAction(GlobalSettings.ActiveSettingPtr->ButtonActions[BUTTON_L_PRESS_SHORT]); - } + /* Button is currently not being pressed. Check if PressTickCounter contains + * a recent short button press. */ + if ( (ButtonLPressTick > 0) && (ButtonLPressTick <= LONG_PRESS_TICK_COUNT) ) { + /* We have a short button press */ + ExecuteButtonAction(GlobalSettings.ActiveSettingPtr->ButtonActions[BUTTON_L_PRESS_SHORT]); + } - ButtonLPressTick = 0; + ButtonLPressTick = 0; } } void ButtonGetActionList(char* List, uint16_t BufferSize) { - MapToString(ButtonActionMap, ARRAY_COUNT(ButtonActionMap), List, BufferSize); + MapToString(ButtonActionMap, ARRAY_COUNT(ButtonActionMap), List, BufferSize); } void ButtonSetActionById(ButtonTypeEnum Type, ButtonActionEnum Action) { #ifndef BUTTON_SETTING_GLOBAL - GlobalSettings.ActiveSettingPtr->ButtonActions[Type] = Action; + GlobalSettings.ActiveSettingPtr->ButtonActions[Type] = Action; #else - /* Write button action to all settings when using global settings */ - for (uint8_t i=0; iButtonActions[Type], Action, BufferSize); + MapIdToText(ButtonActionMap, ARRAY_COUNT(ButtonActionMap), + GlobalSettings.ActiveSettingPtr->ButtonActions[Type], Action, BufferSize); } bool ButtonSetActionByName(ButtonTypeEnum Type, const char* Action) { - MapIdType Id; + MapIdType Id; - if (MapTextToId(ButtonActionMap, ARRAY_COUNT(ButtonActionMap), Action, &Id)) { - ButtonSetActionById(Type, Id); - return true; - } else { - return false; - } + if (MapTextToId(ButtonActionMap, ARRAY_COUNT(ButtonActionMap), Action, &Id)) { + ButtonSetActionById(Type, Id); + return true; + } else { + return false; + } } diff --git a/Firmware/Chameleon-Mini/Button.h b/Firmware/Chameleon-Mini/Button.h index 0bc67c9..77c9e5b 100644 --- a/Firmware/Chameleon-Mini/Button.h +++ b/Firmware/Chameleon-Mini/Button.h @@ -11,13 +11,13 @@ #include "Common.h" typedef enum { - BUTTON_R_PRESS_SHORT = 0, - BUTTON_R_PRESS_LONG, - BUTTON_L_PRESS_SHORT, - BUTTON_L_PRESS_LONG, + BUTTON_R_PRESS_SHORT = 0, + BUTTON_R_PRESS_LONG, + BUTTON_L_PRESS_SHORT, + BUTTON_L_PRESS_LONG, - /* Must be last element */ - BUTTON_TYPE_COUNT + /* Must be last element */ + BUTTON_TYPE_COUNT } ButtonTypeEnum; typedef enum { @@ -30,8 +30,8 @@ typedef enum { BUTTON_ACTION_CYCLE_SETTINGS, BUTTON_ACTION_STORE_MEM, BUTTON_ACTION_RECALL_MEM, - BUTTON_ACTION_TOGGLE_FIELD, - BUTTON_ACTION_STORE_LOG, + BUTTON_ACTION_TOGGLE_FIELD, + BUTTON_ACTION_STORE_LOG, /* This has to be last element */ BUTTON_ACTION_COUNT diff --git a/Firmware/Chameleon-Mini/Chameleon-Mini.c b/Firmware/Chameleon-Mini/Chameleon-Mini.c index d969af6..18a0a2b 100644 --- a/Firmware/Chameleon-Mini/Chameleon-Mini.c +++ b/Firmware/Chameleon-Mini/Chameleon-Mini.c @@ -16,24 +16,24 @@ int main(void) SystemInterruptInit(); while(1) { - if (SystemTick100ms()) { + if (SystemTick100ms()) { LEDTick(); // this has to be the first function called here, since it is time-critical - the functions below may have non-negligible runtimes! - RandomTick(); - TerminalTick(); - ButtonTick(); - LogTick(); - ApplicationTick(); - CommandLineTick(); - AntennaLevelTick(); + RandomTick(); + TerminalTick(); + ButtonTick(); + LogTick(); + ApplicationTick(); + CommandLineTick(); + AntennaLevelTick(); - LEDHook(LED_POWERED, LED_ON); - } + LEDHook(LED_POWERED, LED_ON); + } - TerminalTask(); - LogTask(); - ApplicationTask(); - CodecTask(); + TerminalTask(); + LogTask(); + ApplicationTask(); + CodecTask(); } } diff --git a/Firmware/Chameleon-Mini/Codec/Codec.c b/Firmware/Chameleon-Mini/Codec/Codec.c index 8d5b7cc..f9ac2fa 100644 --- a/Firmware/Chameleon-Mini/Codec/Codec.c +++ b/Firmware/Chameleon-Mini/Codec/Codec.c @@ -17,9 +17,9 @@ static uint16_t ReaderFieldStartTimestamp = 0; static uint16_t ReaderFieldRestartTimestamp = 0; static uint16_t ReaderFieldRestartDelay = 0; static volatile struct { - bool Started; - bool Ready; - bool ToBeRestarted; + bool Started; + bool Ready; + bool ToBeRestarted; } ReaderFieldFlags = { false }; uint8_t CodecBuffer[CODEC_BUFFER_SIZE]; @@ -28,28 +28,28 @@ uint16_t ReaderThreshold = 400; // standard value // the following three functions prevent sending data directly after turning on the reader field void CodecReaderFieldStart(void) // DO NOT CALL THIS FUNCTION INSIDE APPLICATION! { - if (!CodecGetReaderField() && !ReaderFieldFlags.ToBeRestarted) - { - CodecSetReaderField(true); - ReaderFieldFlags.Started = true; - ReaderFieldFlags.Ready = false; - ReaderFieldStartTimestamp = SystemGetSysTick(); - } + if (!CodecGetReaderField() && !ReaderFieldFlags.ToBeRestarted) + { + CodecSetReaderField(true); + ReaderFieldFlags.Started = true; + ReaderFieldFlags.Ready = false; + ReaderFieldStartTimestamp = SystemGetSysTick(); + } } void CodecReaderFieldStop(void) { - CodecSetReaderField(false); - ReaderFieldFlags.Started = false; - ReaderFieldFlags.Ready = false; + CodecSetReaderField(false); + ReaderFieldFlags.Started = false; + ReaderFieldFlags.Ready = false; } void CodecReaderFieldRestart(uint16_t delay) { - ReaderFieldFlags.ToBeRestarted = true; - ReaderFieldRestartTimestamp = SystemGetSysTick(); - ReaderFieldRestartDelay = delay; - CodecReaderFieldStop(); + ReaderFieldFlags.ToBeRestarted = true; + ReaderFieldRestartTimestamp = SystemGetSysTick(); + ReaderFieldRestartDelay = delay; + CodecReaderFieldStop(); } /* @@ -58,28 +58,28 @@ void CodecReaderFieldRestart(uint16_t delay) */ bool CodecIsReaderFieldReady(void) { - if (!ReaderFieldFlags.Started) - return true; - if (ReaderFieldFlags.Ready || (ReaderFieldFlags.Started && SYSTICK_DIFF(ReaderFieldStartTimestamp) >= READER_FIELD_MINIMUM_WAITING_TIME)) - { - ReaderFieldFlags.Ready = true; - return true; - } - return false; + if (!ReaderFieldFlags.Started) + return true; + if (ReaderFieldFlags.Ready || (ReaderFieldFlags.Started && SYSTICK_DIFF(ReaderFieldStartTimestamp) >= READER_FIELD_MINIMUM_WAITING_TIME)) + { + ReaderFieldFlags.Ready = true; + return true; + } + return false; } bool CodecIsReaderToBeRestarted(void) { - if (ReaderFieldFlags.ToBeRestarted) - { - if (SYSTICK_DIFF(ReaderFieldRestartTimestamp) >= ReaderFieldRestartDelay) - { - ReaderFieldFlags.ToBeRestarted = false; - CodecReaderFieldStart(); - } - return true; - } - return false; + if (ReaderFieldFlags.ToBeRestarted) + { + if (SYSTICK_DIFF(ReaderFieldRestartTimestamp) >= ReaderFieldRestartDelay) + { + ReaderFieldFlags.ToBeRestarted = false; + CodecReaderFieldStart(); + } + return true; + } + return false; } void CodecThresholdSet(uint16_t th) diff --git a/Firmware/Chameleon-Mini/Codec/Codec.h b/Firmware/Chameleon-Mini/Codec/Codec.h index 14bf6ef..38927dc 100644 --- a/Firmware/Chameleon-Mini/Codec/Codec.h +++ b/Firmware/Chameleon-Mini/Codec/Codec.h @@ -98,8 +98,8 @@ extern uint16_t Reader_FWT; #define FWI2FWT(x) ((uint32_t)(256 * 16 * ((uint32_t)1 << (x))) / (CODEC_CARRIER_FREQ / 1000) + 1) typedef enum { - CODEC_SUBCARRIERMOD_OFF, - CODEC_SUBCARRIERMOD_OOK + CODEC_SUBCARRIERMOD_OFF, + CODEC_SUBCARRIERMOD_OOK } SubcarrierModType; extern uint8_t CodecBuffer[CODEC_BUFFER_SIZE]; @@ -127,7 +127,7 @@ INLINE void CodecInitCommon(void) #else #error Option not supported #endif - CODEC_CARRIER_IN_PORT.DIRCLR = CODEC_CARRIER_IN_MASK; + CODEC_CARRIER_IN_PORT.DIRCLR = CODEC_CARRIER_IN_MASK; EVSYS.CH6MUX = CODEC_CARRIER_IN_EVMUX; /* Configure two DEMOD pins for input. @@ -143,8 +143,8 @@ INLINE void CodecInitCommon(void) EVSYS.CH0MUX = CODEC_DEMOD_IN_EVMUX0; EVSYS.CH1MUX = CODEC_DEMOD_IN_EVMUX1; - /* Configure loadmod pin configuration and use a virtual port configuration - * for single instruction cycle access */ + /* Configure loadmod pin configuration and use a virtual port configuration + * for single instruction cycle access */ CODEC_LOADMOD_PORT.DIRSET = CODEC_LOADMOD_MASK; CODEC_LOADMOD_PORT.OUTCLR = CODEC_LOADMOD_MASK; PORTCFG.VPCTRLA &= ~PORTCFG_VP0MAP_gm; @@ -188,21 +188,21 @@ INLINE void CodecInitCommon(void) INLINE void CodecSetSubcarrier(SubcarrierModType ModType, uint16_t Divider) { - if (ModType == CODEC_SUBCARRIERMOD_OFF) { - CODEC_SUBCARRIER_TIMER.CTRLA = TC_CLKSEL_OFF_gc; - CODEC_SUBCARRIER_TIMER.CTRLB = 0; - } else if (ModType == CODEC_SUBCARRIERMOD_OOK) { - /* Configure subcarrier generation with 50% DC output using OOK */ - CODEC_SUBCARRIER_TIMER.CNT = 0; - CODEC_SUBCARRIER_TIMER.PER = Divider - 1; - CODEC_SUBCARRIER_TIMER.CODEC_SUBCARRIER_CC_OOK = Divider/2; - CODEC_SUBCARRIER_TIMER.CTRLB = CODEC_SUBCARRIER_CCEN_OOK | TC_WGMODE_SINGLESLOPE_gc; - } + if (ModType == CODEC_SUBCARRIERMOD_OFF) { + CODEC_SUBCARRIER_TIMER.CTRLA = TC_CLKSEL_OFF_gc; + CODEC_SUBCARRIER_TIMER.CTRLB = 0; + } else if (ModType == CODEC_SUBCARRIERMOD_OOK) { + /* Configure subcarrier generation with 50% DC output using OOK */ + CODEC_SUBCARRIER_TIMER.CNT = 0; + CODEC_SUBCARRIER_TIMER.PER = Divider - 1; + CODEC_SUBCARRIER_TIMER.CODEC_SUBCARRIER_CC_OOK = Divider/2; + CODEC_SUBCARRIER_TIMER.CTRLB = CODEC_SUBCARRIER_CCEN_OOK | TC_WGMODE_SINGLESLOPE_gc; + } } INLINE void CodecStartSubcarrier(void) { - CODEC_SUBCARRIER_TIMER.CTRLA = CODEC_TIMER_CARRIER_CLKSEL; + CODEC_SUBCARRIER_TIMER.CTRLA = CODEC_TIMER_CARRIER_CLKSEL; } INLINE void CodecSetDemodPower(bool bOnOff) @@ -215,36 +215,36 @@ INLINE void CodecSetDemodPower(bool bOnOff) } INLINE bool CodecGetLoadmodState(void) { - if (ACA.STATUS & AC_AC0STATE_bm) { - return true; - } else { - return false; - } + if (ACA.STATUS & AC_AC0STATE_bm) { + return true; + } else { + return false; + } } INLINE void CodecSetLoadmodState(bool bOnOff) { - if (bOnOff) { - VPORT0.OUT |= CODEC_LOADMOD_MASK; - } else { - VPORT0.OUT &= ~CODEC_LOADMOD_MASK; - } + if (bOnOff) { + VPORT0.OUT |= CODEC_LOADMOD_MASK; + } else { + VPORT0.OUT &= ~CODEC_LOADMOD_MASK; + } } INLINE void CodecSetReaderField(bool bOnOff) { // this is the function for turning on/off the reader field dumbly; before using this function, please consider to use CodecReaderField{Start,Stop} - if (bOnOff) { - /* Start timer for field generation and unmask outputs */ - CODEC_READER_TIMER.CTRLA = TC_CLKSEL_DIV1_gc; - AWEXC.OUTOVEN = CODEC_READER_MASK; - } else { - /* Disable outputs of AWEX and stop field generation */ - AWEXC.OUTOVEN = 0x00; - CODEC_READER_TIMER.CTRLA = TC_CLKSEL_OFF_gc; - } + if (bOnOff) { + /* Start timer for field generation and unmask outputs */ + CODEC_READER_TIMER.CTRLA = TC_CLKSEL_DIV1_gc; + AWEXC.OUTOVEN = CODEC_READER_MASK; + } else { + /* Disable outputs of AWEX and stop field generation */ + AWEXC.OUTOVEN = 0x00; + CODEC_READER_TIMER.CTRLA = TC_CLKSEL_OFF_gc; + } } INLINE bool CodecGetReaderField(void) { - return (CODEC_READER_TIMER.CTRLA == TC_CLKSEL_DIV1_gc) && (AWEXC.OUTOVEN == CODEC_READER_MASK); + return (CODEC_READER_TIMER.CTRLA == TC_CLKSEL_DIV1_gc) && (AWEXC.OUTOVEN == CODEC_READER_MASK); } void CodecReaderFieldStart(void); diff --git a/Firmware/Chameleon-Mini/Codec/ISO14443-2A.c b/Firmware/Chameleon-Mini/Codec/ISO14443-2A.c index 7c621d5..e43ea61 100644 --- a/Firmware/Chameleon-Mini/Codec/ISO14443-2A.c +++ b/Firmware/Chameleon-Mini/Codec/ISO14443-2A.c @@ -24,11 +24,11 @@ static volatile struct { } Flags = { 0 }; typedef enum { - /* Demod */ - DEMOD_DATA_BIT, - DEMOD_PARITY_BIT, + /* Demod */ + DEMOD_DATA_BIT, + DEMOD_PARITY_BIT, - /* Loadmod */ + /* Loadmod */ LOADMOD_FDT, LOADMOD_START, LOADMOD_START_BIT0, @@ -120,7 +120,7 @@ ISR(CODEC_TIMER_SAMPLING_CCA_VECT) { SampleRegister = (SampleRegister << 1) | (!SamplePin ? 0x01 : 0x00); if (SampleIdxRegister) { - SampleIdxRegister = 0; + SampleIdxRegister = 0; /* Analyze the sampling register after 2 samples. */ if ((SampleRegister & 0x07) == 0x07) { /* No carrier modulation for 3 sample points. EOC! */ @@ -201,7 +201,7 @@ ISR(CODEC_TIMER_SAMPLING_CCA_VECT) { *ParityBufferPtr++ = Bit; StateRegister = DEMOD_DATA_BIT; } else { - /* Should never Happen (TM) */ + /* Should never Happen (TM) */ } } else { /* 00 sequence. -> No valid data yet. This also occurs if we just started @@ -210,7 +210,7 @@ ISR(CODEC_TIMER_SAMPLING_CCA_VECT) { } } else { /* On odd sample position just sample. */ - SampleIdxRegister = ~SampleIdxRegister; + SampleIdxRegister = ~SampleIdxRegister; } /* Make sure the sampling timer gets automatically aligned to the @@ -224,23 +224,23 @@ ISR(CODEC_TIMER_LOADMOD_OVF_VECT) { /* Bit rate timer. Output a half bit on the output. */ static void* JumpTable[] = { - [LOADMOD_FDT] = &&LOADMOD_FDT_LABEL, - [LOADMOD_START] = &&LOADMOD_START_LABEL, - [LOADMOD_START_BIT0] = &&LOADMOD_START_BIT0_LABEL, - [LOADMOD_START_BIT1] = &&LOADMOD_START_BIT1_LABEL, - [LOADMOD_DATA0] = &&LOADMOD_DATA0_LABEL, - [LOADMOD_DATA1] = &&LOADMOD_DATA1_LABEL, - [LOADMOD_PARITY0] = &&LOADMOD_PARITY0_LABEL, - [LOADMOD_PARITY1] = &&LOADMOD_PARITY1_LABEL, - [LOADMOD_STOP_BIT0] = &&LOADMOD_STOP_BIT0_LABEL, - [LOADMOD_STOP_BIT1] = &&LOADMOD_STOP_BIT1_LABEL, - [LOADMOD_FINISHED] = &&LOADMOD_FINISHED_LABEL + [LOADMOD_FDT] = &&LOADMOD_FDT_LABEL, + [LOADMOD_START] = &&LOADMOD_START_LABEL, + [LOADMOD_START_BIT0] = &&LOADMOD_START_BIT0_LABEL, + [LOADMOD_START_BIT1] = &&LOADMOD_START_BIT1_LABEL, + [LOADMOD_DATA0] = &&LOADMOD_DATA0_LABEL, + [LOADMOD_DATA1] = &&LOADMOD_DATA1_LABEL, + [LOADMOD_PARITY0] = &&LOADMOD_PARITY0_LABEL, + [LOADMOD_PARITY1] = &&LOADMOD_PARITY1_LABEL, + [LOADMOD_STOP_BIT0] = &&LOADMOD_STOP_BIT0_LABEL, + [LOADMOD_STOP_BIT1] = &&LOADMOD_STOP_BIT1_LABEL, + [LOADMOD_FINISHED] = &&LOADMOD_FINISHED_LABEL }; if ( (StateRegister >= LOADMOD_FDT) && (StateRegister <= LOADMOD_FINISHED) ) { - goto *JumpTable[StateRegister]; + goto *JumpTable[StateRegister]; } else { - return; + return; } LOADMOD_FDT_LABEL: @@ -253,17 +253,17 @@ ISR(CODEC_TIMER_LOADMOD_OVF_VECT) { /* Fallthrough to first bit */ LOADMOD_START_BIT0_LABEL: - /* Start subcarrier generation, output startbit and align to bitrate. */ - CodecSetLoadmodState(true); - CodecStartSubcarrier(); + /* Start subcarrier generation, output startbit and align to bitrate. */ + CodecSetLoadmodState(true); + CodecStartSubcarrier(); - CODEC_TIMER_LOADMOD.PER = ISO14443A_BIT_RATE_CYCLES / 2 - 1; + CODEC_TIMER_LOADMOD.PER = ISO14443A_BIT_RATE_CYCLES / 2 - 1; StateRegister = LOADMOD_START_BIT1; return; LOADMOD_START_BIT1_LABEL: - CodecSetLoadmodState(false); + CodecSetLoadmodState(false); StateRegister = LOADMOD_DATA0; ParityRegister = ~0; BitSent = 0; @@ -272,12 +272,12 @@ ISR(CODEC_TIMER_LOADMOD_OVF_VECT) { DataRegister = *CodecBufferPtr; return; - LOADMOD_DATA0_LABEL: + LOADMOD_DATA0_LABEL: if (DataRegister & 1) { - CodecSetLoadmodState(true); - ParityRegister = ~ParityRegister; + CodecSetLoadmodState(true); + ParityRegister = ~ParityRegister; } else { - CodecSetLoadmodState(false); + CodecSetLoadmodState(false); } StateRegister = LOADMOD_DATA1; @@ -285,9 +285,9 @@ ISR(CODEC_TIMER_LOADMOD_OVF_VECT) { LOADMOD_DATA1_LABEL: if (DataRegister & 1) { - CodecSetLoadmodState(false); + CodecSetLoadmodState(false); } else { - CodecSetLoadmodState(true); + CodecSetLoadmodState(true); } DataRegister = DataRegister >> 1; @@ -300,47 +300,47 @@ ISR(CODEC_TIMER_LOADMOD_OVF_VECT) { /* End of transmission without byte boundary. Don't send parity. */ StateRegister = LOADMOD_STOP_BIT0; } else { - /* Next bit is data */ - StateRegister = LOADMOD_DATA0; + /* Next bit is data */ + StateRegister = LOADMOD_DATA0; } return; LOADMOD_PARITY0_LABEL: - if (ParityBufferPtr != NULL) { - if (*ParityBufferPtr) { - CodecSetLoadmodState(true); - } else { - CodecSetLoadmodState(false); - } - } else { - if (ParityRegister) { - CodecSetLoadmodState(true); - } else { - CodecSetLoadmodState(false); - } - } + if (ParityBufferPtr != NULL) { + if (*ParityBufferPtr) { + CodecSetLoadmodState(true); + } else { + CodecSetLoadmodState(false); + } + } else { + if (ParityRegister) { + CodecSetLoadmodState(true); + } else { + CodecSetLoadmodState(false); + } + } StateRegister = LOADMOD_PARITY1; return; LOADMOD_PARITY1_LABEL: - if (ParityBufferPtr != NULL) { - if (*ParityBufferPtr) { - CodecSetLoadmodState(false); - } else { - CodecSetLoadmodState(true); - } + if (ParityBufferPtr != NULL) { + if (*ParityBufferPtr) { + CodecSetLoadmodState(false); + } else { + CodecSetLoadmodState(true); + } ParityBufferPtr++; - } else { - if (ParityRegister) { - CodecSetLoadmodState(false); - } else { - CodecSetLoadmodState(true); - } + } else { + if (ParityRegister) { + CodecSetLoadmodState(false); + } else { + CodecSetLoadmodState(true); + } - ParityRegister = ~0; - } + ParityRegister = ~0; + } if (BitSent == BitCount) { /* No data left */ @@ -354,12 +354,12 @@ ISR(CODEC_TIMER_LOADMOD_OVF_VECT) { return; LOADMOD_STOP_BIT0_LABEL: - CodecSetLoadmodState(false); + CodecSetLoadmodState(false); StateRegister = LOADMOD_STOP_BIT1; return; LOADMOD_STOP_BIT1_LABEL: - CodecSetLoadmodState(false); + CodecSetLoadmodState(false); StateRegister = LOADMOD_FINISHED; return; @@ -378,25 +378,25 @@ ISR(CODEC_TIMER_LOADMOD_OVF_VECT) { void ISO14443ACodecInit(void) { /* Initialize some global vars and start looking out for reader commands */ - Flags.DemodFinished = 0; - Flags.LoadmodFinished = 0; + Flags.DemodFinished = 0; + Flags.LoadmodFinished = 0; - CodecInitCommon(); + CodecInitCommon(); StartDemod(); } void ISO14443ACodecDeInit(void) { - /* Gracefully shutdown codec */ - CODEC_DEMOD_IN_PORT.INT0MASK = 0; + /* Gracefully shutdown codec */ + CODEC_DEMOD_IN_PORT.INT0MASK = 0; - Flags.DemodFinished = 0; - Flags.LoadmodFinished = 0; + Flags.DemodFinished = 0; + Flags.LoadmodFinished = 0; CODEC_TIMER_SAMPLING.CTRLA = TC_CLKSEL_OFF_gc; - CODEC_TIMER_SAMPLING.CTRLD = TC_EVACT_OFF_gc; + CODEC_TIMER_SAMPLING.CTRLD = TC_EVACT_OFF_gc; CODEC_TIMER_SAMPLING.INTCTRLB = TC_CCAINTLVL_OFF_gc; - CODEC_TIMER_SAMPLING.INTFLAGS = TC0_CCAIF_bm; + CODEC_TIMER_SAMPLING.INTFLAGS = TC0_CCAIF_bm; CODEC_TIMER_LOADMOD.CTRLA = TC_CLKSEL_OFF_gc; @@ -431,7 +431,7 @@ void ISO14443ACodecTask(void) { ParityBufferPtr = &CodecBuffer[ISO14443A_BUFFER_PARITY_OFFSET]; } else { /* We have to generate the parity bits ourself */ - ParityBufferPtr = 0; + ParityBufferPtr = 0; } } diff --git a/Firmware/Chameleon-Mini/Codec/Reader14443-2A.c b/Firmware/Chameleon-Mini/Codec/Reader14443-2A.c index a2f9d1c..10bb076 100644 --- a/Firmware/Chameleon-Mini/Codec/Reader14443-2A.c +++ b/Firmware/Chameleon-Mini/Codec/Reader14443-2A.c @@ -27,14 +27,14 @@ static volatile struct { static volatile uint16_t RxPendingSince; static volatile enum { - STATE_IDLE, - STATE_MILLER_SOF0, - STATE_MILLER_SOF1, - STATE_MILLER_TX0, - STATE_MILLER_TX1, - STATE_MILLER_EOF0, - STATE_MILLER_EOF1, - STATE_FDT + STATE_IDLE, + STATE_MILLER_SOF0, + STATE_MILLER_SOF1, + STATE_MILLER_TX0, + STATE_MILLER_TX1, + STATE_MILLER_EOF0, + STATE_MILLER_EOF1, + STATE_FDT } State; // GPIOR0 and 1 are used as storage for the timer value of the current modulation @@ -51,8 +51,8 @@ static volatile enum { void Reader14443ACodecInit(void) { /* Initialize common peripherals and start listening * for incoming data. */ - CodecInitCommon(); - CodecSetDemodPower(true); + CodecInitCommon(); + CodecSetDemodPower(true); CODEC_TIMER_SAMPLING.PER = SAMPLE_RATE_SYSTEM_CYCLES/2 - 1; CODEC_TIMER_SAMPLING.CCB = 1; @@ -69,27 +69,27 @@ void Reader14443ACodecInit(void) { } void Reader14443ACodecDeInit(void) { - CodecSetDemodPower(false); - CodecReaderFieldStop(); - CODEC_TIMER_SAMPLING.CTRLA = 0; - CODEC_TIMER_SAMPLING.INTCTRLB = 0; - CODEC_TIMER_LOADMOD.CTRLA = 0; - CODEC_TIMER_LOADMOD.INTCTRLB = 0; - Flags.RxDone = false; - Flags.RxPending = false; - Flags.Start = false; + CodecSetDemodPower(false); + CodecReaderFieldStop(); + CODEC_TIMER_SAMPLING.CTRLA = 0; + CODEC_TIMER_SAMPLING.INTCTRLB = 0; + CODEC_TIMER_LOADMOD.CTRLA = 0; + CODEC_TIMER_LOADMOD.INTCTRLB = 0; + Flags.RxDone = false; + Flags.RxPending = false; + Flags.Start = false; } INLINE void Reader14443A_EOC(void) { - CODEC_TIMER_LOADMOD.INTCTRLB = 0; + CODEC_TIMER_LOADMOD.INTCTRLB = 0; CODEC_TIMER_LOADMOD.CTRLA = TC_CLKSEL_OFF_gc; CODEC_TIMER_TIMESTAMPS.INTCTRLB = 0; CODEC_TIMER_TIMESTAMPS.CTRLA = TC_CLKSEL_OFF_gc; ACA.AC1CTRL &= ~AC_ENABLE_bm; - if (BitCount % 8) // copy the last byte, if there is an incomplete byte - CodecBuffer[BitCount / 8] = SampleRegister >> (8 - (BitCount % 8)); + if (BitCount % 8) // copy the last byte, if there is an incomplete byte + CodecBuffer[BitCount / 8] = SampleRegister >> (8 - (BitCount % 8)); Flags.RxDone = true; Flags.RxPending = false; @@ -106,309 +106,309 @@ INLINE void Reader14443A_EOC(void) ISR(CODEC_TIMER_SAMPLING_CCB_VECT) { - static void * JumpTable[] = { - [STATE_IDLE] = &&STATE_IDLE_LABEL, - [STATE_MILLER_SOF0] = &&STATE_MILLER_SOF0_LABEL, - [STATE_MILLER_SOF1] = &&STATE_MILLER_SOF1_LABEL, - [STATE_MILLER_TX0] = &&STATE_MILLER_TX0_LABEL, - [STATE_MILLER_TX1] = &&STATE_MILLER_TX1_LABEL, - [STATE_MILLER_EOF0] = &&STATE_MILLER_EOF0_LABEL, - [STATE_MILLER_EOF1] = &&STATE_MILLER_EOF1_LABEL, - [STATE_FDT] = &&STATE_FDT_LABEL - }; + static void * JumpTable[] = { + [STATE_IDLE] = &&STATE_IDLE_LABEL, + [STATE_MILLER_SOF0] = &&STATE_MILLER_SOF0_LABEL, + [STATE_MILLER_SOF1] = &&STATE_MILLER_SOF1_LABEL, + [STATE_MILLER_TX0] = &&STATE_MILLER_TX0_LABEL, + [STATE_MILLER_TX1] = &&STATE_MILLER_TX1_LABEL, + [STATE_MILLER_EOF0] = &&STATE_MILLER_EOF0_LABEL, + [STATE_MILLER_EOF1] = &&STATE_MILLER_EOF1_LABEL, + [STATE_FDT] = &&STATE_FDT_LABEL + }; - goto *JumpTable[State]; + goto *JumpTable[State]; - STATE_MILLER_SOF0_LABEL: - /* Output a SOF */ - CodecSetReaderField(false); - _delay_us(2.5); - CodecSetReaderField(true); + STATE_MILLER_SOF0_LABEL: + /* Output a SOF */ + CodecSetReaderField(false); + _delay_us(2.5); + CodecSetReaderField(true); - CodecBufferIdx = 0; - SampleRegister = CodecBuffer[0]; - BitCountUp = 0; + CodecBufferIdx = 0; + SampleRegister = CodecBuffer[0]; + BitCountUp = 0; - State = STATE_MILLER_SOF1; - return; + State = STATE_MILLER_SOF1; + return; - STATE_MILLER_SOF1_LABEL: - State = STATE_MILLER_TX0; - return; + STATE_MILLER_SOF1_LABEL: + State = STATE_MILLER_TX0; + return; - STATE_MILLER_TX0_LABEL: - /* First half of bit-slot */ - if (SampleRegister & 0x01) { - /* Do Nothing */ - } else { - if (LastBit == 0) { - CodecSetReaderField(false); - _delay_us(2.5); - CodecSetReaderField(true); - } else { - /* Do Nothing */ - } - } + STATE_MILLER_TX0_LABEL: + /* First half of bit-slot */ + if (SampleRegister & 0x01) { + /* Do Nothing */ + } else { + if (LastBit == 0) { + CodecSetReaderField(false); + _delay_us(2.5); + CodecSetReaderField(true); + } else { + /* Do Nothing */ + } + } - State = STATE_MILLER_TX1; - return; + State = STATE_MILLER_TX1; + return; - STATE_MILLER_TX1_LABEL: - /* Second half of bit-slot */ - if (SampleRegister & 0x01) { - CodecSetReaderField(false); - _delay_us(2.5); - CodecSetReaderField(true); - LastBit = 1; - } else { - /* No modulation pauses */ - LastBit = 0; - } + STATE_MILLER_TX1_LABEL: + /* Second half of bit-slot */ + if (SampleRegister & 0x01) { + CodecSetReaderField(false); + _delay_us(2.5); + CodecSetReaderField(true); + LastBit = 1; + } else { + /* No modulation pauses */ + LastBit = 0; + } - SampleRegister >>= 1; - if (--BitCount == 0) { - State = STATE_MILLER_EOF0; - } else { - State = STATE_MILLER_TX0; - } + SampleRegister >>= 1; + if (--BitCount == 0) { + State = STATE_MILLER_EOF0; + } else { + State = STATE_MILLER_TX0; + } - if ((++BitCountUp % 8) == 0) - SampleRegister = CodecBuffer[++CodecBufferIdx]; - return; + if ((++BitCountUp % 8) == 0) + SampleRegister = CodecBuffer[++CodecBufferIdx]; + return; - STATE_MILLER_EOF0_LABEL: - if (LastBit == 0) { - CodecSetReaderField(false); - _delay_us(2.5); - CodecSetReaderField(true); - } else { - /* Do Nothing */ - } + STATE_MILLER_EOF0_LABEL: + if (LastBit == 0) { + CodecSetReaderField(false); + _delay_us(2.5); + CodecSetReaderField(true); + } else { + /* Do Nothing */ + } - State = STATE_MILLER_EOF1; - return; + State = STATE_MILLER_EOF1; + return; - STATE_MILLER_EOF1_LABEL: - CODEC_TIMER_SAMPLING.CTRLA = TC_CLKSEL_OFF_gc; - _delay_us(50); // wait for DEMOD signal to stabilize + STATE_MILLER_EOF1_LABEL: + CODEC_TIMER_SAMPLING.CTRLA = TC_CLKSEL_OFF_gc; + _delay_us(50); // wait for DEMOD signal to stabilize - /* Enable the AC interrupt, which either finds the SOC and then starts the pause-finding timer, - * or it is triggered before the SOC, which mostly isn't bad at all, since the first pause - * needs to be found. */ - ACA.STATUS = AC_AC1IF_bm; - ACA.AC1CTRL = AC_HSMODE_bm | AC_HYSMODE_NO_gc | AC_INTMODE_BOTHEDGES_gc | AC_INTLVL_HI_gc | AC_ENABLE_bm; + /* Enable the AC interrupt, which either finds the SOC and then starts the pause-finding timer, + * or it is triggered before the SOC, which mostly isn't bad at all, since the first pause + * needs to be found. */ + ACA.STATUS = AC_AC1IF_bm; + ACA.AC1CTRL = AC_HSMODE_bm | AC_HYSMODE_NO_gc | AC_INTMODE_BOTHEDGES_gc | AC_INTLVL_HI_gc | AC_ENABLE_bm; - CodecBufferPtr = CodecBuffer; // use GPIOR for faster access - BitCount = 1; // the first modulation of the SOC is "found" implicitly - SampleRegister = 0x80; + CodecBufferPtr = CodecBuffer; // use GPIOR for faster access + BitCount = 1; // the first modulation of the SOC is "found" implicitly + SampleRegister = 0x80; - RxPendingSince = SystemGetSysTick(); - Flags.RxPending = true; + RxPendingSince = SystemGetSysTick(); + Flags.RxPending = true; - // reset for future use - CodecBufferIdx = 0; - BitCountUp = 0; + // reset for future use + CodecBufferIdx = 0; + BitCountUp = 0; - State = STATE_IDLE; - return; + State = STATE_IDLE; + return; - STATE_IDLE_LABEL: - STATE_FDT_LABEL: - return; - } + STATE_IDLE_LABEL: + STATE_FDT_LABEL: + return; + } ISR(CODEC_TIMER_TIMESTAMPS_CCA_VECT) // EOC found { - Reader14443A_EOC(); + Reader14443A_EOC(); } INLINE void Insert0(void) { - SampleRegister >>= 1; - if (++BitCount % 8) - return; - *CodecBufferPtr++ = SampleRegister; + SampleRegister >>= 1; + if (++BitCount % 8) + return; + *CodecBufferPtr++ = SampleRegister; } INLINE void Insert1(void) { - SampleRegister = (SampleRegister >> 1) | 0x80; - if (++BitCount % 8) - return; - *CodecBufferPtr++ = SampleRegister; + SampleRegister = (SampleRegister >> 1) | 0x80; + if (++BitCount % 8) + return; + *CodecBufferPtr++ = SampleRegister; } ISR(ACA_AC1_vect) // this interrupt either finds the SOC or gets triggered before { - ACA.AC1CTRL &= ~AC_INTLVL_HI_gc; // disable this interrupt - // enable the pause-finding timer - CODEC_TIMER_LOADMOD.CTRLD = TC_EVACT_RESTART_gc | TC_EVSEL_CH0_gc; - CODEC_TIMER_LOADMOD.CTRLA = TC_CLKSEL_DIV1_gc; + ACA.AC1CTRL &= ~AC_INTLVL_HI_gc; // disable this interrupt + // enable the pause-finding timer + CODEC_TIMER_LOADMOD.CTRLD = TC_EVACT_RESTART_gc | TC_EVSEL_CH0_gc; + CODEC_TIMER_LOADMOD.CTRLA = TC_CLKSEL_DIV1_gc; } ISR(CODEC_TIMER_LOADMOD_CCA_VECT) // pause found { - uint8_t tmp = CODEC_TIMER_TIMESTAMPS.CNTL; - CODEC_TIMER_TIMESTAMPS.CNT = 0; + uint8_t tmp = CODEC_TIMER_TIMESTAMPS.CNTL; + CODEC_TIMER_TIMESTAMPS.CNT = 0; - /* This needs to be done only on the first call, - * but doing this only on a condition means wasting time, so we do it every time. */ - CODEC_TIMER_TIMESTAMPS.CTRLA = TC_CLKSEL_DIV2_gc; + /* This needs to be done only on the first call, + * but doing this only on a condition means wasting time, so we do it every time. */ + CODEC_TIMER_TIMESTAMPS.CTRLA = TC_CLKSEL_DIV2_gc; - switch (tmp) // decide how many half bit periods have been modulations - { - case 0 ... 96: // 64 ticks is one half of a bit period - Insert0(); - // If one full bit period is over AND the last half bit period also was a pause, - // we have found the EOC. - if ((BitCount & 1) == 0 && (SampleRegister & 0x40) == 0) - Reader14443A_EOC(); - return; + switch (tmp) // decide how many half bit periods have been modulations + { + case 0 ... 96: // 64 ticks is one half of a bit period + Insert0(); + // If one full bit period is over AND the last half bit period also was a pause, + // we have found the EOC. + if ((BitCount & 1) == 0 && (SampleRegister & 0x40) == 0) + Reader14443A_EOC(); + return; - case 97 ... 160: // 128 ticks is a full bit period - Insert1(); - Insert0(); - return; + case 97 ... 160: // 128 ticks is a full bit period + Insert1(); + Insert0(); + return; - default: // every value over 128 + 32 (tolerance) is considered to be 3 half bit periods - Insert1(); - Insert1(); - Insert0(); - return; - } - return; + default: // every value over 128 + 32 (tolerance) is considered to be 3 half bit periods + Insert1(); + Insert1(); + Insert0(); + return; + } + return; } void Reader14443ACodecTask(void) { - if (Flags.RxPending && SYSTICK_DIFF(RxPendingSince) > Reader_FWT + 1) - { - BitCount = 0; - Flags.RxDone = true; - Flags.RxPending = false; - } - if (CodecIsReaderToBeRestarted() || !CodecIsReaderFieldReady()) - return; - if (!Flags.RxPending && (Flags.Start || Flags.RxDone)) - { - if (State == STATE_FDT && CODEC_TIMER_LOADMOD.CNT < ISO14443A_PICC_TO_PCD_MIN_FDT) // we are in frame delay time, so we can return later - return; - if (Flags.RxDone && BitCount > 0) // decode the raw received data - { - if (BitCount < ISO14443A_RX_MINIMUM_BITCOUNT * 2) - { - BitCount = 0; - } else { - uint8_t TmpCodecBuffer[CODEC_BUFFER_SIZE]; - memcpy(TmpCodecBuffer, CodecBuffer, (BitCount + 7) / 8); + if (Flags.RxPending && SYSTICK_DIFF(RxPendingSince) > Reader_FWT + 1) + { + BitCount = 0; + Flags.RxDone = true; + Flags.RxPending = false; + } + if (CodecIsReaderToBeRestarted() || !CodecIsReaderFieldReady()) + return; + if (!Flags.RxPending && (Flags.Start || Flags.RxDone)) + { + if (State == STATE_FDT && CODEC_TIMER_LOADMOD.CNT < ISO14443A_PICC_TO_PCD_MIN_FDT) // we are in frame delay time, so we can return later + return; + if (Flags.RxDone && BitCount > 0) // decode the raw received data + { + if (BitCount < ISO14443A_RX_MINIMUM_BITCOUNT * 2) + { + BitCount = 0; + } else { + uint8_t TmpCodecBuffer[CODEC_BUFFER_SIZE]; + memcpy(TmpCodecBuffer, CodecBuffer, (BitCount + 7) / 8); - CodecBufferPtr = CodecBuffer; - uint16_t BitCountTmp = 0, TotalBitCount = BitCount; - BitCount = 0; + CodecBufferPtr = CodecBuffer; + uint16_t BitCountTmp = 0, TotalBitCount = BitCount; + BitCount = 0; - bool breakflag = false; + bool breakflag = false; - while (!breakflag && BitCountTmp < TotalBitCount) - { - uint8_t Bit = TmpCodecBuffer[BitCountTmp / 8] & 0x03; - TmpCodecBuffer[BitCountTmp / 8] >>= 2; - switch (Bit) - { - case 0b10: - Insert0(); - break; + while (!breakflag && BitCountTmp < TotalBitCount) + { + uint8_t Bit = TmpCodecBuffer[BitCountTmp / 8] & 0x03; + TmpCodecBuffer[BitCountTmp / 8] >>= 2; + switch (Bit) + { + case 0b10: + Insert0(); + break; - case 0b01: - Insert1(); - break; + case 0b01: + Insert1(); + break; - case 0b00: // EOC - if (BitCount % 8) // copy the last byte, if there is an incomplete byte - CodecBuffer[BitCount / 8] = SampleRegister >> (8 - (BitCount % 8)); - LEDHook(LED_CODEC_RX, LED_PULSE); - LogEntry(LOG_INFO_CODEC_RX_DATA_W_PARITY, CodecBuffer, (BitCount + 7) / 8); - breakflag = true; - break; + case 0b00: // EOC + if (BitCount % 8) // copy the last byte, if there is an incomplete byte + CodecBuffer[BitCount / 8] = SampleRegister >> (8 - (BitCount % 8)); + LEDHook(LED_CODEC_RX, LED_PULSE); + LogEntry(LOG_INFO_CODEC_RX_DATA_W_PARITY, CodecBuffer, (BitCount + 7) / 8); + breakflag = true; + break; - default: - // error, should not happen, TODO handle this - break; - } - BitCountTmp += 2; - } - } - } - Flags.Start = false; - Flags.RxDone = false; + default: + // error, should not happen, TODO handle this + break; + } + BitCountTmp += 2; + } + } + } + Flags.Start = false; + Flags.RxDone = false; - /* Call application with received data */ - BitCount = ApplicationProcess(CodecBuffer, BitCount); + /* Call application with received data */ + BitCount = ApplicationProcess(CodecBuffer, BitCount); - if (BitCount > 0) - { - /* - * Prepare for Manchester decoding. - * The basic idea is to use two timers. The first one will be reset everytime the DEMOD signal - * passes a (configurable) threshold. This is realized with the event system and an analog - * comparator. - * Once this timer reaches 3/4 of a bit half (this means it has not been reset this long), we - * assume there is a pause. Now we read the second timers count value and can decide how many - * bit halves had modulations since the last pause. - */ + if (BitCount > 0) + { + /* + * Prepare for Manchester decoding. + * The basic idea is to use two timers. The first one will be reset everytime the DEMOD signal + * passes a (configurable) threshold. This is realized with the event system and an analog + * comparator. + * Once this timer reaches 3/4 of a bit half (this means it has not been reset this long), we + * assume there is a pause. Now we read the second timers count value and can decide how many + * bit halves had modulations since the last pause. + */ - /* Configure and enable the analog comparator for finding pauses in the DEMOD signal. */ - ACA.AC1CTRL = AC_HSMODE_bm | AC_HYSMODE_NO_gc | AC_INTMODE_BOTHEDGES_gc | AC_ENABLE_bm; + /* Configure and enable the analog comparator for finding pauses in the DEMOD signal. */ + ACA.AC1CTRL = AC_HSMODE_bm | AC_HYSMODE_NO_gc | AC_INTMODE_BOTHEDGES_gc | AC_ENABLE_bm; - /* This timer will be used to detect the pauses between the modulation sequences. */ - CODEC_TIMER_LOADMOD.CTRLA = 0; - CODEC_TIMER_LOADMOD.CNT = 0; - CODEC_TIMER_LOADMOD.PER = 127; // with 27.12 MHz this is exactly one half bit width - CODEC_TIMER_LOADMOD.CCA = 95; // with 27.12 MHz this is 3/4 of a half bit width - CODEC_TIMER_LOADMOD.INTCTRLA = 0; - CODEC_TIMER_LOADMOD.INTFLAGS = TC1_CCAIF_bm; - CODEC_TIMER_LOADMOD.INTCTRLB = TC_CCAINTLVL_HI_gc; + /* This timer will be used to detect the pauses between the modulation sequences. */ + CODEC_TIMER_LOADMOD.CTRLA = 0; + CODEC_TIMER_LOADMOD.CNT = 0; + CODEC_TIMER_LOADMOD.PER = 127; // with 27.12 MHz this is exactly one half bit width + CODEC_TIMER_LOADMOD.CCA = 95; // with 27.12 MHz this is 3/4 of a half bit width + CODEC_TIMER_LOADMOD.INTCTRLA = 0; + CODEC_TIMER_LOADMOD.INTFLAGS = TC1_CCAIF_bm; + CODEC_TIMER_LOADMOD.INTCTRLB = TC_CCAINTLVL_HI_gc; - /* This timer will be used to find out how many bit halfs since the last pause have been passed. */ - CODEC_TIMER_TIMESTAMPS.CNT = 0; - CODEC_TIMER_TIMESTAMPS.PER = 0xFFFF; - CODEC_TIMER_TIMESTAMPS.CCA = 256; - CODEC_TIMER_TIMESTAMPS.INTCTRLA = 0; - CODEC_TIMER_TIMESTAMPS.INTFLAGS = TC1_CCAIF_bm; - CODEC_TIMER_TIMESTAMPS.INTCTRLB = TC_CCAINTLVL_LO_gc; + /* This timer will be used to find out how many bit halfs since the last pause have been passed. */ + CODEC_TIMER_TIMESTAMPS.CNT = 0; + CODEC_TIMER_TIMESTAMPS.PER = 0xFFFF; + CODEC_TIMER_TIMESTAMPS.CCA = 256; + CODEC_TIMER_TIMESTAMPS.INTCTRLA = 0; + CODEC_TIMER_TIMESTAMPS.INTFLAGS = TC1_CCAIF_bm; + CODEC_TIMER_TIMESTAMPS.INTCTRLB = TC_CCAINTLVL_LO_gc; - /* Use the event system for resetting the pause-detecting timer. */ - EVSYS.CH0MUX = EVSYS_CHMUX_ACA_CH1_gc; // on every ACA_AC1 INT - EVSYS.CH0CTRL = EVSYS_DIGFILT_1SAMPLE_gc; + /* Use the event system for resetting the pause-detecting timer. */ + EVSYS.CH0MUX = EVSYS_CHMUX_ACA_CH1_gc; // on every ACA_AC1 INT + EVSYS.CH0CTRL = EVSYS_DIGFILT_1SAMPLE_gc; - ACA.AC0CTRL = 0; - CODEC_DEMOD_IN_PORT.INTCTRL = 0; + ACA.AC0CTRL = 0; + CODEC_DEMOD_IN_PORT.INTCTRL = 0; - LEDHook(LED_CODEC_TX, LED_PULSE); - LogEntry(LOG_INFO_CODEC_TX_DATA_W_PARITY, CodecBuffer, (BitCount + 7) / 8); + LEDHook(LED_CODEC_TX, LED_PULSE); + LogEntry(LOG_INFO_CODEC_TX_DATA_W_PARITY, CodecBuffer, (BitCount + 7) / 8); - /* Set state and start timer for Miller encoding. */ - State = STATE_MILLER_SOF0; - LastBit = 0; - CODEC_TIMER_SAMPLING.CNT = 0; - CODEC_TIMER_SAMPLING.CTRLA = TC_CLKSEL_DIV1_gc; - } - } + /* Set state and start timer for Miller encoding. */ + State = STATE_MILLER_SOF0; + LastBit = 0; + CODEC_TIMER_SAMPLING.CNT = 0; + CODEC_TIMER_SAMPLING.CTRLA = TC_CLKSEL_DIV1_gc; + } + } } void Reader14443ACodecStart(void) { - /* Application wants us to start a card transaction */ - BitCount = 0; - Flags.Start = true; + /* Application wants us to start a card transaction */ + BitCount = 0; + Flags.Start = true; - CodecReaderFieldStart(); + CodecReaderFieldStart(); } void Reader14443ACodecReset(void) { - Reader14443A_EOC(); // this breaks every interrupt etc. - State = STATE_IDLE; - Flags.RxDone = false; - Flags.Start = false; - CodecReaderFieldStop(); + Reader14443A_EOC(); // this breaks every interrupt etc. + State = STATE_IDLE; + Flags.RxDone = false; + Flags.Start = false; + CodecReaderFieldStop(); } diff --git a/Firmware/Chameleon-Mini/Common.c b/Firmware/Chameleon-Mini/Common.c index 51dd452..1e33304 100644 --- a/Firmware/Chameleon-Mini/Common.c +++ b/Firmware/Chameleon-Mini/Common.c @@ -8,22 +8,22 @@ const uint8_t PROGMEM BitReverseByteTable[256] = { }; const uint8_t PROGMEM OddParityByteTable[256] = { - 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, - 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, - 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, - 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, - 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, - 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, - 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, - 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, - 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, - 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, - 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, - 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, - 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, - 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, - 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, - 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, + 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, + 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, + 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, + 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, + 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, + 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, + 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, + 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, + 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, + 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, + 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, + 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, + 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, + 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, + 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, + 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, }; uint16_t BufferToHexString(char* HexOut, uint16_t MaxChars, const void* Buffer, uint16_t ByteCount) diff --git a/Firmware/Chameleon-Mini/Common.h b/Firmware/Chameleon-Mini/Common.h index 86875bc..80cd0f0 100644 --- a/Firmware/Chameleon-Mini/Common.h +++ b/Firmware/Chameleon-Mini/Common.h @@ -38,31 +38,31 @@ uint16_t HexStringToBuffer(void* Buffer, uint16_t MaxBytes, const char* HexIn); INLINE uint8_t BitReverseByte(uint8_t Byte) { - extern const uint8_t PROGMEM BitReverseByteTable[]; + extern const uint8_t PROGMEM BitReverseByteTable[]; - return pgm_read_byte(&BitReverseByteTable[Byte]); + return pgm_read_byte(&BitReverseByteTable[Byte]); } INLINE uint8_t OddParityBit(uint8_t Byte) { - extern const uint8_t PROGMEM OddParityByteTable[]; + extern const uint8_t PROGMEM OddParityByteTable[]; - return pgm_read_byte(&OddParityByteTable[Byte]); + return pgm_read_byte(&OddParityByteTable[Byte]); } INLINE uint8_t StringLength(const char* Str, uint8_t MaxLen) { - uint8_t StrLen = 0; + uint8_t StrLen = 0; - while(MaxLen > 0) { - if (*Str++ == '\0') - break; + while(MaxLen > 0) { + if (*Str++ == '\0') + break; - MaxLen--; - StrLen++; - } + MaxLen--; + StrLen++; + } - return StrLen; + return StrLen; } #endif /* COMMON_H_ */ diff --git a/Firmware/Chameleon-Mini/Configuration.c b/Firmware/Chameleon-Mini/Configuration.c index d7cad61..ebbea50 100644 --- a/Firmware/Chameleon-Mini/Configuration.c +++ b/Firmware/Chameleon-Mini/Configuration.c @@ -13,27 +13,27 @@ /* Map IDs to text */ static const MapEntryType PROGMEM ConfigurationMap[] = { - { .Id = CONFIG_NONE, .Text = "NONE" }, + { .Id = CONFIG_NONE, .Text = "NONE" }, #ifdef CONFIG_MF_ULTRALIGHT_SUPPORT - { .Id = CONFIG_MF_ULTRALIGHT, .Text = "MF_ULTRALIGHT" }, + { .Id = CONFIG_MF_ULTRALIGHT, .Text = "MF_ULTRALIGHT" }, #endif #ifdef CONFIG_MF_CLASSIC_1K_SUPPORT - { .Id = CONFIG_MF_CLASSIC_1K, .Text = "MF_CLASSIC_1K" }, + { .Id = CONFIG_MF_CLASSIC_1K, .Text = "MF_CLASSIC_1K" }, #endif #ifdef CONFIG_MF_CLASSIC_1K_7B_SUPPORT - { .Id = CONFIG_MF_CLASSIC_1K_7B, .Text = "MF_CLASSIC_1K_7B" }, + { .Id = CONFIG_MF_CLASSIC_1K_7B, .Text = "MF_CLASSIC_1K_7B" }, #endif #ifdef CONFIG_MF_CLASSIC_4K_SUPPORT - { .Id = CONFIG_MF_CLASSIC_4K, .Text = "MF_CLASSIC_4K" }, + { .Id = CONFIG_MF_CLASSIC_4K, .Text = "MF_CLASSIC_4K" }, #endif #ifdef CONFIG_MF_CLASSIC_4K_7B_SUPPORT - { .Id = CONFIG_MF_CLASSIC_4K_7B, .Text = "MF_CLASSIC_4K_7B" }, + { .Id = CONFIG_MF_CLASSIC_4K_7B, .Text = "MF_CLASSIC_4K_7B" }, #endif #ifdef CONFIG_ISO14443A_SNIFF_SUPPORT - { .Id = CONFIG_ISO14443A_SNIFF, .Text = "ISO14443A_SNIFF" }, + { .Id = CONFIG_ISO14443A_SNIFF, .Text = "ISO14443A_SNIFF" }, #endif #ifdef CONFIG_ISO14443A_READER_SUPPORT - { .Id = CONFIG_ISO14443A_READER, .Text = "ISO14443A_READER" }, + { .Id = CONFIG_ISO14443A_READER, .Text = "ISO14443A_READER" }, #endif }; @@ -105,19 +105,19 @@ static const PROGMEM ConfigurationType ConfigurationTable[] = { #endif #ifdef CONFIG_MF_CLASSIC_1K_7B_SUPPORT [CONFIG_MF_CLASSIC_1K_7B] = { - .CodecInitFunc = ISO14443ACodecInit, - .CodecDeInitFunc = ISO14443ACodecDeInit, - .CodecTaskFunc = ISO14443ACodecTask, - .ApplicationInitFunc = MifareClassicAppInit1K7B, - .ApplicationResetFunc = MifareClassicAppReset, - .ApplicationTaskFunc = MifareClassicAppTask, - .ApplicationTickFunc = ApplicationTickDummy, - .ApplicationProcessFunc = MifareClassicAppProcess, - .ApplicationGetUidFunc = MifareClassicGetUid, - .ApplicationSetUidFunc = MifareClassicSetUid, - .UidSize = ISO14443A_UID_SIZE_DOUBLE, - .MemorySize = MIFARE_CLASSIC_1K_MEM_SIZE, - .ReadOnly = false + .CodecInitFunc = ISO14443ACodecInit, + .CodecDeInitFunc = ISO14443ACodecDeInit, + .CodecTaskFunc = ISO14443ACodecTask, + .ApplicationInitFunc = MifareClassicAppInit1K7B, + .ApplicationResetFunc = MifareClassicAppReset, + .ApplicationTaskFunc = MifareClassicAppTask, + .ApplicationTickFunc = ApplicationTickDummy, + .ApplicationProcessFunc = MifareClassicAppProcess, + .ApplicationGetUidFunc = MifareClassicGetUid, + .ApplicationSetUidFunc = MifareClassicSetUid, + .UidSize = ISO14443A_UID_SIZE_DOUBLE, + .MemorySize = MIFARE_CLASSIC_1K_MEM_SIZE, + .ReadOnly = false }, #endif #ifdef CONFIG_MF_CLASSIC_4K_SUPPORT @@ -156,36 +156,36 @@ static const PROGMEM ConfigurationType ConfigurationTable[] = { #endif #ifdef CONFIG_ISO14443A_SNIFF_SUPPORT [CONFIG_ISO14443A_SNIFF] = { - .CodecInitFunc = ISO14443ACodecInit, - .CodecDeInitFunc = ISO14443ACodecDeInit, - .CodecTaskFunc = ISO14443ACodecTask, - .ApplicationInitFunc = ApplicationInitDummy, - .ApplicationResetFunc = ApplicationResetDummy, - .ApplicationTaskFunc = ApplicationTaskDummy, - .ApplicationTickFunc = ApplicationTickDummy, - .ApplicationProcessFunc = ApplicationProcessDummy, - .ApplicationGetUidFunc = ApplicationGetUidDummy, - .ApplicationSetUidFunc = ApplicationSetUidDummy, - .UidSize = 0, - .MemorySize = 0, - .ReadOnly = true + .CodecInitFunc = ISO14443ACodecInit, + .CodecDeInitFunc = ISO14443ACodecDeInit, + .CodecTaskFunc = ISO14443ACodecTask, + .ApplicationInitFunc = ApplicationInitDummy, + .ApplicationResetFunc = ApplicationResetDummy, + .ApplicationTaskFunc = ApplicationTaskDummy, + .ApplicationTickFunc = ApplicationTickDummy, + .ApplicationProcessFunc = ApplicationProcessDummy, + .ApplicationGetUidFunc = ApplicationGetUidDummy, + .ApplicationSetUidFunc = ApplicationSetUidDummy, + .UidSize = 0, + .MemorySize = 0, + .ReadOnly = true }, #endif #ifdef CONFIG_ISO14443A_READER_SUPPORT [CONFIG_ISO14443A_READER] = { - .CodecInitFunc = Reader14443ACodecInit, - .CodecDeInitFunc = Reader14443ACodecDeInit, - .CodecTaskFunc = Reader14443ACodecTask, - .ApplicationInitFunc = Reader14443AAppInit, - .ApplicationResetFunc = Reader14443AAppReset, - .ApplicationTaskFunc = Reader14443AAppTask, - .ApplicationTickFunc = Reader14443AAppTick, - .ApplicationProcessFunc = Reader14443AAppProcess, - .ApplicationGetUidFunc = ApplicationGetUidDummy, - .ApplicationSetUidFunc = ApplicationSetUidDummy, - .UidSize = 0, - .MemorySize = 0, - .ReadOnly = false + .CodecInitFunc = Reader14443ACodecInit, + .CodecDeInitFunc = Reader14443ACodecDeInit, + .CodecTaskFunc = Reader14443ACodecTask, + .ApplicationInitFunc = Reader14443AAppInit, + .ApplicationResetFunc = Reader14443AAppReset, + .ApplicationTaskFunc = Reader14443AAppTask, + .ApplicationTickFunc = Reader14443AAppTick, + .ApplicationProcessFunc = Reader14443AAppProcess, + .ApplicationGetUidFunc = ApplicationGetUidDummy, + .ApplicationSetUidFunc = ApplicationSetUidDummy, + .UidSize = 0, + .MemorySize = 0, + .ReadOnly = false }, #endif }; @@ -202,11 +202,11 @@ void ConfigurationInit(void) void ConfigurationSetById( ConfigurationEnum Configuration ) { - CodecDeInit(); + CodecDeInit(); - CommandLinePendingTaskBreak(); // break possibly pending task + CommandLinePendingTaskBreak(); // break possibly pending task - GlobalSettings.ActiveSettingPtr->Configuration = Configuration; + GlobalSettings.ActiveSettingPtr->Configuration = Configuration; /* Copy struct from PROGMEM to RAM */ memcpy_P(&ActiveConfiguration, @@ -218,7 +218,7 @@ void ConfigurationSetById( ConfigurationEnum Configuration ) void ConfigurationGetByName(char* Configuration, uint16_t BufferSize) { - MapIdToText(ConfigurationMap, ARRAY_COUNT(ConfigurationMap), GlobalSettings.ActiveSettingPtr->Configuration, Configuration, BufferSize); + MapIdToText(ConfigurationMap, ARRAY_COUNT(ConfigurationMap), GlobalSettings.ActiveSettingPtr->Configuration, Configuration, BufferSize); } bool ConfigurationSetByName(const char* Configuration) @@ -226,16 +226,16 @@ bool ConfigurationSetByName(const char* Configuration) MapIdType Id; if (MapTextToId(ConfigurationMap, ARRAY_COUNT(ConfigurationMap), Configuration, &Id)) { - ConfigurationSetById(Id); - LogEntry(LOG_INFO_CONFIG_SET, Configuration, StringLength(Configuration, CONFIGURATION_NAME_LENGTH_MAX-1)); - return true; + ConfigurationSetById(Id); + LogEntry(LOG_INFO_CONFIG_SET, Configuration, StringLength(Configuration, CONFIGURATION_NAME_LENGTH_MAX-1)); + return true; } else { - return false; + return false; } } void ConfigurationGetList(char* List, uint16_t BufferSize) { - MapToString(ConfigurationMap, ARRAY_COUNT(ConfigurationMap), List, BufferSize); + MapToString(ConfigurationMap, ARRAY_COUNT(ConfigurationMap), List, BufferSize); } diff --git a/Firmware/Chameleon-Mini/Configuration.h b/Firmware/Chameleon-Mini/Configuration.h index d645857..52d1e23 100644 --- a/Firmware/Chameleon-Mini/Configuration.h +++ b/Firmware/Chameleon-Mini/Configuration.h @@ -39,7 +39,7 @@ typedef enum { CONFIG_ISO14443A_SNIFF, #endif #ifdef CONFIG_ISO14443A_READER_SUPPORT - CONFIG_ISO14443A_READER, + CONFIG_ISO14443A_READER, #endif /* This HAS to be the last element */ CONFIG_COUNT @@ -53,7 +53,7 @@ typedef struct { * Codec related methods. * @{ */ - /** Function that initializes the codec. */ + /** Function that initializes the codec. */ void (*CodecInitFunc) (void); /** Function that deinitializes the codec. */ void (*CodecDeInitFunc) (void); @@ -79,17 +79,17 @@ typedef struct { void (*ApplicationTaskFunc) (void); /** Function that is called roughly every 100ms. This can be used for parallel tasks of the application, that is independent of the codec module. */ void (*ApplicationTickFunc) (void); - /** This function does two important things. It gets called by the codec. - * The first task is to deliver data that have been received by the codec module to - * the application module. The application then can decide how to answer to these data and return - * the response to the codec module, which will process it according to the configured codec. - * - * \param ByteBuffer Pointer to the start of the buffer, where the received data are and where the - * application can put the response data. - * \param BitCount Number of bits that have been received. - * - * \return Number of bits of the response. - */ + /** This function does two important things. It gets called by the codec. + * The first task is to deliver data that have been received by the codec module to + * the application module. The application then can decide how to answer to these data and return + * the response to the codec module, which will process it according to the configured codec. + * + * \param ByteBuffer Pointer to the start of the buffer, where the received data are and where the + * application can put the response data. + * \param BitCount Number of bits that have been received. + * + * \return Number of bits of the response. + */ uint16_t (*ApplicationProcessFunc) (uint8_t* ByteBuffer, uint16_t BitCount); /** * Writes the UID for the current configuration to the given buffer. @@ -105,12 +105,12 @@ typedef struct { * @} */ - /** - * Defines how many space the configuration needs. For emulating configurations this is the memory space of - * the emulated card. - * - * \note For reader or sniff configurations this is set to zero. - */ + /** + * Defines how many space the configuration needs. For emulating configurations this is the memory space of + * the emulated card. + * + * \note For reader or sniff configurations this is set to zero. + */ uint16_t MemorySize; /** * Defines the size of the UID for emulating configurations. diff --git a/Firmware/Chameleon-Mini/LED.c b/Firmware/Chameleon-Mini/LED.c index d0c8fdc..6ae69e2 100644 --- a/Firmware/Chameleon-Mini/LED.c +++ b/Firmware/Chameleon-Mini/LED.c @@ -11,158 +11,158 @@ LEDActionEnum LEDGreenAction = LED_NO_ACTION; LEDActionEnum LEDRedAction = LED_NO_ACTION; static const MapEntryType PROGMEM LEDFunctionMap[] = { - { .Id = LED_NO_FUNC, .Text = "NONE" }, - { .Id = LED_POWERED, .Text = "POWERED" }, - { .Id = LED_TERMINAL_CONN, .Text = "TERMINAL_CONN" }, - { .Id = LED_TERMINAL_RXTX, .Text = "TERMINAL_RXTX" }, - { .Id = LED_SETTING_CHANGE, .Text = "SETTING_CHANGE" }, - { .Id = LED_MEMORY_STORED, .Text = "MEMORY_STORED" }, - { .Id = LED_MEMORY_CHANGED, .Text = "MEMORY_CHANGED" }, - { .Id = LED_CODEC_RX, .Text = "CODEC_RX" }, - { .Id = LED_CODEC_TX, .Text = "CODEC_TX" }, - { .Id = LED_FIELD_DETECTED, .Text = "FIELD_DETECTED" }, - { .Id = LED_LOG_MEM_FULL, .Text = "LOGMEM_FULL" }, + { .Id = LED_NO_FUNC, .Text = "NONE" }, + { .Id = LED_POWERED, .Text = "POWERED" }, + { .Id = LED_TERMINAL_CONN, .Text = "TERMINAL_CONN" }, + { .Id = LED_TERMINAL_RXTX, .Text = "TERMINAL_RXTX" }, + { .Id = LED_SETTING_CHANGE, .Text = "SETTING_CHANGE" }, + { .Id = LED_MEMORY_STORED, .Text = "MEMORY_STORED" }, + { .Id = LED_MEMORY_CHANGED, .Text = "MEMORY_CHANGED" }, + { .Id = LED_CODEC_RX, .Text = "CODEC_RX" }, + { .Id = LED_CODEC_TX, .Text = "CODEC_TX" }, + { .Id = LED_FIELD_DETECTED, .Text = "FIELD_DETECTED" }, + { .Id = LED_LOG_MEM_FULL, .Text = "LOGMEM_FULL" }, }; INLINE void Tick(uint8_t Mask, LEDActionEnum* Action) { - static uint8_t LEDRedBlinkPrescaler = 0; - static uint8_t LEDGreenBlinkPrescaler = 0; - uint8_t * BlinkPrescaler = (Action == &LEDGreenAction) ? &LEDGreenBlinkPrescaler : &LEDRedBlinkPrescaler; + static uint8_t LEDRedBlinkPrescaler = 0; + static uint8_t LEDGreenBlinkPrescaler = 0; + uint8_t * BlinkPrescaler = (Action == &LEDGreenAction) ? &LEDGreenBlinkPrescaler : &LEDRedBlinkPrescaler; - switch (*Action) - { - case LED_NO_ACTION: - /* Do nothing */ - break; + switch (*Action) + { + case LED_NO_ACTION: + /* Do nothing */ + break; - case LED_OFF: - LED_PORT.OUTCLR = Mask; - *Action = LED_NO_ACTION; - break; + case LED_OFF: + LED_PORT.OUTCLR = Mask; + *Action = LED_NO_ACTION; + break; - case LED_ON: - LED_PORT.OUTSET = Mask; - *Action = LED_NO_ACTION; - break; + case LED_ON: + LED_PORT.OUTSET = Mask; + *Action = LED_NO_ACTION; + break; - case LED_TOGGLE: - LED_PORT.OUTTGL = Mask; - *Action = LED_NO_ACTION; - break; + case LED_TOGGLE: + LED_PORT.OUTTGL = Mask; + *Action = LED_NO_ACTION; + break; - case LED_PULSE: - if (!(LED_PORT.OUT & Mask)) { - LED_PORT.OUTSET = Mask; - } else { - LED_PORT.OUTCLR = Mask; - *Action = LED_NO_ACTION; - } - break; + case LED_PULSE: + if (!(LED_PORT.OUT & Mask)) { + LED_PORT.OUTSET = Mask; + } else { + LED_PORT.OUTCLR = Mask; + *Action = LED_NO_ACTION; + } + break; - case LED_BLINK_1X ... LED_BLINK_8X: - if (++(*BlinkPrescaler) == BLINK_PRESCALER) { - *BlinkPrescaler = 0; + case LED_BLINK_1X ... LED_BLINK_8X: + if (++(*BlinkPrescaler) == BLINK_PRESCALER) { + *BlinkPrescaler = 0; - /* Blink functionality occurs at slower speed than Tick-frequency */ - if (!(LED_PORT.OUT & Mask)) { - /* LED is off, turn it on */ - LED_PORT.OUTSET = Mask; - } else { - /* LED is on, turn it off and change state */ - LED_PORT.OUTCLR = Mask; + /* Blink functionality occurs at slower speed than Tick-frequency */ + if (!(LED_PORT.OUT & Mask)) { + /* LED is off, turn it on */ + LED_PORT.OUTSET = Mask; + } else { + /* LED is on, turn it off and change state */ + LED_PORT.OUTCLR = Mask; - if (*Action == LED_BLINK_1X) { - *Action = LED_NO_ACTION; - } else { - /* Still some blinks to do. Use the fact that LED_BLINK_XY are ordered sequentially */ - *Action = *Action - 1; - } - } - } - break; + if (*Action == LED_BLINK_1X) { + *Action = LED_NO_ACTION; + } else { + /* Still some blinks to do. Use the fact that LED_BLINK_XY are ordered sequentially */ + *Action = *Action - 1; + } + } + } + break; - default: - /* Should not happen (TM) */ - *Action = LED_NO_ACTION; - break; + default: + /* Should not happen (TM) */ + *Action = LED_NO_ACTION; + break; - } + } } void LEDInit(void) { - LED_PORT.DIRSET = LED_MASK; + LED_PORT.DIRSET = LED_MASK; } void LEDTick(void) { - Tick(LED_RED, &LEDRedAction); - Tick(LED_GREEN, &LEDGreenAction); + Tick(LED_RED, &LEDRedAction); + Tick(LED_GREEN, &LEDGreenAction); } void LEDGetFuncList(char* List, uint16_t BufferSize) { - MapToString(LEDFunctionMap, ARRAY_COUNT(LEDFunctionMap), List, BufferSize); + MapToString(LEDFunctionMap, ARRAY_COUNT(LEDFunctionMap), List, BufferSize); } void LEDSetFuncById(uint8_t Mask, LEDHookEnum Function) { #ifndef LED_SETTING_GLOBAL - if (Mask & LED_GREEN) { - GlobalSettings.ActiveSettingPtr->LEDGreenFunction = Function; - } + if (Mask & LED_GREEN) { + GlobalSettings.ActiveSettingPtr->LEDGreenFunction = Function; + } - if (Mask & LED_RED) { - GlobalSettings.ActiveSettingPtr->LEDRedFunction = Function; - } + if (Mask & LED_RED) { + GlobalSettings.ActiveSettingPtr->LEDRedFunction = Function; + } #else - /* Write LED func to all settings when using global settings */ - for (uint8_t i=0; iLEDGreenFunction, Function, BufferSize); - } else if (Mask == LED_RED) { - MapIdToText(LEDFunctionMap, ARRAY_COUNT(LEDFunctionMap), - GlobalSettings.ActiveSettingPtr->LEDRedFunction, Function, BufferSize); - } + if (Mask == LED_GREEN) { + MapIdToText(LEDFunctionMap, ARRAY_COUNT(LEDFunctionMap), + GlobalSettings.ActiveSettingPtr->LEDGreenFunction, Function, BufferSize); + } else if (Mask == LED_RED) { + MapIdToText(LEDFunctionMap, ARRAY_COUNT(LEDFunctionMap), + GlobalSettings.ActiveSettingPtr->LEDRedFunction, Function, BufferSize); + } } bool LEDSetFuncByName(uint8_t Mask, const char* Function) { - MapIdType Id; + MapIdType Id; - if (MapTextToId(LEDFunctionMap, ARRAY_COUNT(LEDFunctionMap), Function, &Id)) { - LEDSetFuncById(Mask, Id); - return true; - } else { - return false; - } + if (MapTextToId(LEDFunctionMap, ARRAY_COUNT(LEDFunctionMap), Function, &Id)) { + LEDSetFuncById(Mask, Id); + return true; + } else { + return false; + } } diff --git a/Firmware/Chameleon-Mini/LED.h b/Firmware/Chameleon-Mini/LED.h index b739dd1..e13ee05 100644 --- a/Firmware/Chameleon-Mini/LED.h +++ b/Firmware/Chameleon-Mini/LED.h @@ -17,44 +17,44 @@ #define LED_MASK (LED_GREEN | LED_RED) typedef enum LEDFunctionEnum { - LED_NO_FUNC = 0, /* Don't light up the LED */ - LED_POWERED, /* Light up the LED whenever the Chameleon is powered */ + LED_NO_FUNC = 0, /* Don't light up the LED */ + LED_POWERED, /* Light up the LED whenever the Chameleon is powered */ - LED_TERMINAL_CONN, /* A Terminal/USB connection has been established */ - LED_TERMINAL_RXTX, /* There is traffic on the terminal */ + LED_TERMINAL_CONN, /* A Terminal/USB connection has been established */ + LED_TERMINAL_RXTX, /* There is traffic on the terminal */ - LED_SETTING_CHANGE, /* Outputs a blink code that shows the current setting */ + LED_SETTING_CHANGE, /* Outputs a blink code that shows the current setting */ - LED_MEMORY_STORED, /* Blink once when memory has been stored to flash */ - LED_MEMORY_CHANGED, /* Switch LED on when card memory has changed compared to flash */ + LED_MEMORY_STORED, /* Blink once when memory has been stored to flash */ + LED_MEMORY_CHANGED, /* Switch LED on when card memory has changed compared to flash */ - LED_FIELD_DETECTED, /* Shows LED while a reader field is being detected or turned on by the chameleon itself */ + LED_FIELD_DETECTED, /* Shows LED while a reader field is being detected or turned on by the chameleon itself */ - LED_CODEC_RX, /* Blink LED when receiving codec data */ - LED_CODEC_TX, /* Blink LED when transmitting codec data */ + LED_CODEC_RX, /* Blink LED when receiving codec data */ + LED_CODEC_TX, /* Blink LED when transmitting codec data */ - LED_LOG_MEM_FULL, /* Light up if log memory is full. */ + LED_LOG_MEM_FULL, /* Light up if log memory is full. */ - //TODO: LED_APP_SELECTED, /* Show LED while the correct UID has been selected and the application is active */ - /* Has to be last element */ - LED_FUNC_COUNT + //TODO: LED_APP_SELECTED, /* Show LED while the correct UID has been selected and the application is active */ + /* Has to be last element */ + LED_FUNC_COUNT } LEDHookEnum; typedef enum LEDActionEnum { - LED_NO_ACTION = 0x00, - LED_OFF = 0x10, - LED_ON = 0x11, - LED_TOGGLE = 0x12, - LED_PULSE = 0x13, - LED_BLINK = 0x20, - LED_BLINK_1X = 0x20, - LED_BLINK_2X, /* Have to be sequentially ordered */ - LED_BLINK_3X, - LED_BLINK_4X, - LED_BLINK_5X, - LED_BLINK_6X, - LED_BLINK_7X, - LED_BLINK_8X, + LED_NO_ACTION = 0x00, + LED_OFF = 0x10, + LED_ON = 0x11, + LED_TOGGLE = 0x12, + LED_PULSE = 0x13, + LED_BLINK = 0x20, + LED_BLINK_1X = 0x20, + LED_BLINK_2X, /* Have to be sequentially ordered */ + LED_BLINK_3X, + LED_BLINK_4X, + LED_BLINK_5X, + LED_BLINK_6X, + LED_BLINK_7X, + LED_BLINK_8X, } LEDActionEnum; diff --git a/Firmware/Chameleon-Mini/LEDHook.h b/Firmware/Chameleon-Mini/LEDHook.h index ac88351..9827ae0 100644 --- a/Firmware/Chameleon-Mini/LEDHook.h +++ b/Firmware/Chameleon-Mini/LEDHook.h @@ -11,16 +11,16 @@ #include "Settings.h" INLINE void LEDHook(LEDHookEnum Func, LEDActionEnum Action) { - extern LEDActionEnum LEDGreenAction; - extern LEDActionEnum LEDRedAction; + extern LEDActionEnum LEDGreenAction; + extern LEDActionEnum LEDRedAction; - if (GlobalSettings.ActiveSettingPtr->LEDGreenFunction == Func) { - LEDGreenAction = Action; - } + if (GlobalSettings.ActiveSettingPtr->LEDGreenFunction == Func) { + LEDGreenAction = Action; + } - if (GlobalSettings.ActiveSettingPtr->LEDRedFunction == Func) { - LEDRedAction = Action; - } + if (GlobalSettings.ActiveSettingPtr->LEDRedFunction == Func) { + LEDRedAction = Action; + } } #endif /* LEDHOOK_H_ */ diff --git a/Firmware/Chameleon-Mini/LUFADescriptors.c b/Firmware/Chameleon-Mini/LUFADescriptors.c index 2ae5366..c8fddb9 100644 --- a/Firmware/Chameleon-Mini/LUFADescriptors.c +++ b/Firmware/Chameleon-Mini/LUFADescriptors.c @@ -58,8 +58,8 @@ const USB_Descriptor_Device_t PROGMEM DeviceDescriptor = .Endpoint0Size = FIXED_CONTROL_ENDPOINT_SIZE, - .VendorID = 0x16D0, // MCS Electronics (http://www.mcselec.com) - .ProductID = 0x04B2, // darksimpson's PID #2 granted to Chameleon-Mini + .VendorID = 0x16D0, // MCS Electronics (http://www.mcselec.com) + .ProductID = 0x04B2, // darksimpson's PID #2 granted to Chameleon-Mini #if LUFA_VERSION_INTEGER >= 0x140928 .ReleaseNumber = VERSION_BCD(0,0,1), #else diff --git a/Firmware/Chameleon-Mini/Log.c b/Firmware/Chameleon-Mini/Log.c index c805c07..facb0a1 100644 --- a/Firmware/Chameleon-Mini/Log.c +++ b/Firmware/Chameleon-Mini/Log.c @@ -14,9 +14,9 @@ static bool EnableLogSRAMtoFRAM = false; LogFuncType CurrentLogFunc; static const MapEntryType PROGMEM LogModeMap[] = { - { .Id = LOG_MODE_OFF, .Text = "OFF" }, - { .Id = LOG_MODE_MEMORY, .Text = "MEMORY" }, - { .Id = LOG_MODE_LIVE, .Text = "LIVE" } + { .Id = LOG_MODE_OFF, .Text = "OFF" }, + { .Id = LOG_MODE_MEMORY, .Text = "MEMORY" }, + { .Id = LOG_MODE_LIVE, .Text = "LIVE" } }; static void LogFuncOff(LogEntryEnum Entry, const void* Data, uint8_t Length) @@ -26,7 +26,7 @@ static void LogFuncOff(LogEntryEnum Entry, const void* Data, uint8_t Length) static void LogFuncMemory(LogEntryEnum Entry, const void* Data, uint8_t Length) { - uint16_t SysTick = SystemGetSysTick(); + uint16_t SysTick = SystemGetSysTick(); if (LogMemLeft >= (Length + 4)) { LogMemLeft -= Length + 4; @@ -52,13 +52,13 @@ static void LogFuncMemory(LogEntryEnum Entry, const void* Data, uint8_t Length) static void LogFuncLive(LogEntryEnum Entry, const void* Data, uint8_t Length) { - uint16_t SysTick = SystemGetSysTick(); + uint16_t SysTick = SystemGetSysTick(); - TerminalSendByte((uint8_t) Entry); - TerminalSendByte((uint8_t) Length); - TerminalSendByte((uint8_t) (SysTick >> 8)); - TerminalSendByte((uint8_t) (SysTick >> 0)); - TerminalSendBlock(Data, Length); + TerminalSendByte((uint8_t) Entry); + TerminalSendByte((uint8_t) Length); + TerminalSendByte((uint8_t) (SysTick >> 8)); + TerminalSendByte((uint8_t) (SysTick >> 0)); + TerminalSendBlock(Data, Length); } void LogInit(void) @@ -72,12 +72,12 @@ void LogInit(void) memset(LogMemPtr, LOG_EMPTY, LOG_SIZE); if (result) { - MemoryReadBlock(&LogFRAMAddr, FRAM_LOG_ADDR_ADDR, 2); + MemoryReadBlock(&LogFRAMAddr, FRAM_LOG_ADDR_ADDR, 2); } else { - LogFRAMAddr = FRAM_LOG_START_ADDR; - MemoryWriteBlock(&LogFRAMAddr, FRAM_LOG_ADDR_ADDR, 2); - result = true; - WriteEEPBlock((uint16_t) &LogFRAMAddrValid, &result, 1); + LogFRAMAddr = FRAM_LOG_START_ADDR; + MemoryWriteBlock(&LogFRAMAddr, FRAM_LOG_ADDR_ADDR, 2); + result = true; + WriteEEPBlock((uint16_t) &LogFRAMAddrValid, &result, 1); } LogEntry(LOG_INFO_SYSTEM_BOOT, NULL, 0); @@ -85,8 +85,8 @@ void LogInit(void) void LogTick(void) { - if (EnableLogSRAMtoFRAM) - LogSRAMToFRAM(); + if (EnableLogSRAMtoFRAM) + LogSRAMToFRAM(); } void LogTask(void) @@ -96,58 +96,58 @@ void LogTask(void) bool LogMemLoadBlock(void* Buffer, uint32_t BlockAddress, uint16_t ByteCount) { - if (BlockAddress < sizeof(LogMem) + (LogFRAMAddr - FRAM_LOG_START_ADDR)) - { - bool overflow = false; - uint16_t remainderByteCount = 0; - uint16_t SizeInFRAMStored = LogFRAMAddr - FRAM_LOG_START_ADDR; - // prevent buffer overflows: - if ((BlockAddress + ByteCount) >= sizeof(LogMem) + SizeInFRAMStored) - { - overflow = true; - uint16_t tmp = sizeof(LogMem) + SizeInFRAMStored - BlockAddress; - remainderByteCount = ByteCount - tmp; - ByteCount = tmp; - } + if (BlockAddress < sizeof(LogMem) + (LogFRAMAddr - FRAM_LOG_START_ADDR)) + { + bool overflow = false; + uint16_t remainderByteCount = 0; + uint16_t SizeInFRAMStored = LogFRAMAddr - FRAM_LOG_START_ADDR; + // prevent buffer overflows: + if ((BlockAddress + ByteCount) >= sizeof(LogMem) + SizeInFRAMStored) + { + overflow = true; + uint16_t tmp = sizeof(LogMem) + SizeInFRAMStored - BlockAddress; + remainderByteCount = ByteCount - tmp; + ByteCount = tmp; + } - /* - * 1. case: The whole block is in FRAM. - * 2. case: The block wraps from FRAM to SRAM - * 3. case: The whole block is in SRAM. - */ - if (BlockAddress < SizeInFRAMStored && (BlockAddress + ByteCount) < SizeInFRAMStored) - { - MemoryReadBlock(Buffer, BlockAddress + FRAM_LOG_START_ADDR, ByteCount); - } else if (BlockAddress < SizeInFRAMStored) { - uint16_t FramByteCount = SizeInFRAMStored - BlockAddress; - MemoryReadBlock(Buffer, BlockAddress + FRAM_LOG_START_ADDR, FramByteCount); - memcpy(Buffer + FramByteCount, LogMem, ByteCount - FramByteCount); - } else { - memcpy(Buffer, LogMem + BlockAddress - SizeInFRAMStored, ByteCount); - } + /* + * 1. case: The whole block is in FRAM. + * 2. case: The block wraps from FRAM to SRAM + * 3. case: The whole block is in SRAM. + */ + if (BlockAddress < SizeInFRAMStored && (BlockAddress + ByteCount) < SizeInFRAMStored) + { + MemoryReadBlock(Buffer, BlockAddress + FRAM_LOG_START_ADDR, ByteCount); + } else if (BlockAddress < SizeInFRAMStored) { + uint16_t FramByteCount = SizeInFRAMStored - BlockAddress; + MemoryReadBlock(Buffer, BlockAddress + FRAM_LOG_START_ADDR, FramByteCount); + memcpy(Buffer + FramByteCount, LogMem, ByteCount - FramByteCount); + } else { + memcpy(Buffer, LogMem + BlockAddress - SizeInFRAMStored, ByteCount); + } - if (overflow) - { - while (remainderByteCount--) - ((uint8_t*) Buffer)[ByteCount + remainderByteCount] = 0x00; - } + if (overflow) + { + while (remainderByteCount--) + ((uint8_t*) Buffer)[ByteCount + remainderByteCount] = 0x00; + } - return true; - } else { - return false; - } + return true; + } else { + return false; + } } INLINE void LogSRAMClear(void) { - uint16_t i, until = LOG_SIZE - LogMemLeft; + uint16_t i, until = LOG_SIZE - LogMemLeft; - for (i=0; i < until; i++) { - LogMem[i] = (uint8_t) LOG_EMPTY; - } + for (i=0; i < until; i++) { + LogMem[i] = (uint8_t) LOG_EMPTY; + } - LogMemPtr = LogMem; - LogMemLeft = sizeof(LogMem); + LogMemPtr = LogMem; + LogMemLeft = sizeof(LogMem); } void LogMemClear(void) @@ -169,25 +169,25 @@ void LogSetModeById(LogModeEnum Mode) #ifndef LOG_SETTING_GLOBAL GlobalSettings.ActiveSettingPtr->LogMode = Mode; #else - /* Write Log settings globally */ - for (uint8_t i=0; iLogMode, Mode, BufferSize); + MapIdToText(LogModeMap, ARRAY_COUNT(LogModeMap), + GlobalSettings.ActiveSettingPtr->LogMode, Mode, BufferSize); } void LogGetModeList(char* List, uint16_t BufferSize) @@ -222,16 +222,16 @@ void LogGetModeList(char* List, uint16_t BufferSize) void LogSRAMToFRAM(void) { - if (LogMemLeft < LOG_SIZE) - { - if (FRAM_LOG_SIZE - (LogFRAMAddr - FRAM_LOG_START_ADDR) >= LOG_SIZE - LogMemLeft) - { - MemoryWriteBlock(LogMem, LogFRAMAddr, LOG_SIZE - LogMemLeft); - LogFRAMAddr += LOG_SIZE - LogMemLeft; - LogSRAMClear(); - MemoryWriteBlock(&LogFRAMAddr, FRAM_LOG_ADDR_ADDR, 2); - } else { - // TODO handle the case in which the FRAM is full - } - } + if (LogMemLeft < LOG_SIZE) + { + if (FRAM_LOG_SIZE - (LogFRAMAddr - FRAM_LOG_START_ADDR) >= LOG_SIZE - LogMemLeft) + { + MemoryWriteBlock(LogMem, LogFRAMAddr, LOG_SIZE - LogMemLeft); + LogFRAMAddr += LOG_SIZE - LogMemLeft; + LogSRAMClear(); + MemoryWriteBlock(&LogFRAMAddr, FRAM_LOG_ADDR_ADDR, 2); + } else { + // TODO handle the case in which the FRAM is full + } + } } diff --git a/Firmware/Chameleon-Mini/Log.h b/Firmware/Chameleon-Mini/Log.h index 3d41896..ce0bbfd 100644 --- a/Firmware/Chameleon-Mini/Log.h +++ b/Firmware/Chameleon-Mini/Log.h @@ -39,7 +39,7 @@ typedef enum { LOG_ERR_APP_CHECKSUM_FAIL = 0xC1, ///< Application had a checksum fail. LOG_ERR_APP_NOT_AUTHED = 0xC2, ///< Application is not authenticated. - LOG_INFO_SYSTEM_BOOT = 0xFF, ///< Chameleon boots + LOG_INFO_SYSTEM_BOOT = 0xFF, ///< Chameleon boots LOG_EMPTY = 0x00 ///< Empty Log Entry. This is not followed by a length byte nor the two systick bytes nor any data. } LogEntryEnum; diff --git a/Firmware/Chameleon-Mini/Map.c b/Firmware/Chameleon-Mini/Map.c index b6011d4..97e9db6 100644 --- a/Firmware/Chameleon-Mini/Map.c +++ b/Firmware/Chameleon-Mini/Map.c @@ -2,49 +2,49 @@ bool MapIdToText(const MapEntryType* MapPtr, uint8_t MapSize, MapIdType Id, char* Text, uint16_t MaxBufferSize) { - while (MapSize--) { - if (pgm_read_byte(&MapPtr->Id) == Id) { - strncpy_P(Text, MapPtr->Text, MaxBufferSize); - return true; - } + while (MapSize--) { + if (pgm_read_byte(&MapPtr->Id) == Id) { + strncpy_P(Text, MapPtr->Text, MaxBufferSize); + return true; + } - MapPtr++; - } + MapPtr++; + } - return false; + return false; } bool MapTextToId(const MapEntryType* MapPtr, uint8_t MapSize, MapTextPtrType Text, MapIdType* IdPtr) { - while (MapSize--) { - if (strcmp_P(Text, MapPtr->Text) == 0) { - if (sizeof(MapIdType) == 1) { - *IdPtr = pgm_read_byte(&MapPtr->Id); - } else if (sizeof(MapIdType) == 2) { - *IdPtr = pgm_read_word(&MapPtr->Id); - } - return true; - } + while (MapSize--) { + if (strcmp_P(Text, MapPtr->Text) == 0) { + if (sizeof(MapIdType) == 1) { + *IdPtr = pgm_read_byte(&MapPtr->Id); + } else if (sizeof(MapIdType) == 2) { + *IdPtr = pgm_read_word(&MapPtr->Id); + } + return true; + } - MapPtr++; - } + MapPtr++; + } - return false; + return false; } void MapToString(MapEntryType* MapPtr, uint8_t MapSize, char* String, uint16_t MaxBufferSize) { - uint8_t EntriesLeft = MapSize; - uint16_t BytesLeft = MaxBufferSize; + uint8_t EntriesLeft = MapSize; + uint16_t BytesLeft = MaxBufferSize; - while (EntriesLeft > 0) { - const char* Text = MapPtr->Text; - char c; + while (EntriesLeft > 0) { + const char* Text = MapPtr->Text; + char c; while( (c = pgm_read_byte(Text)) != '\0') { - if (BytesLeft == 0) { - return; - } + if (BytesLeft == 0) { + return; + } *String++ = c; Text++; @@ -52,21 +52,21 @@ void MapToString(MapEntryType* MapPtr, uint8_t MapSize, char* String, uint16_t M } if (EntriesLeft > 1) { - /* More than one map entries left */ - if (BytesLeft == 0) { - return; - } + /* More than one map entries left */ + if (BytesLeft == 0) { + return; + } - *String++ = ','; + *String++ = ','; } MapPtr++; EntriesLeft--; - } + } - /* Terminate string */ - if (BytesLeft > 0) { - *String++ = '\0'; - BytesLeft--; - } + /* Terminate string */ + if (BytesLeft > 0) { + *String++ = '\0'; + BytesLeft--; + } } diff --git a/Firmware/Chameleon-Mini/Map.h b/Firmware/Chameleon-Mini/Map.h index 7180280..76bd19f 100644 --- a/Firmware/Chameleon-Mini/Map.h +++ b/Firmware/Chameleon-Mini/Map.h @@ -19,8 +19,8 @@ typedef uint8_t MapIdType; typedef const char* MapTextPtrType; const typedef struct { - MapIdType Id; - const char Text[MAP_TEXT_BUF_SIZE]; + MapIdType Id; + const char Text[MAP_TEXT_BUF_SIZE]; } MapEntryType; bool MapIdToText(const MapEntryType* MapPtr, uint8_t MapSize, MapIdType Id, char* Text, uint16_t MaxBufferSize); diff --git a/Firmware/Chameleon-Mini/Memory.c b/Firmware/Chameleon-Mini/Memory.c index f82e680..68551a0 100644 --- a/Firmware/Chameleon-Mini/Memory.c +++ b/Firmware/Chameleon-Mini/Memory.c @@ -40,50 +40,50 @@ static uint8_t ScrapBuffer[] = {0}; INLINE uint8_t SPITransferByte(uint8_t Data) { - FRAM_USART.DATA = Data; + FRAM_USART.DATA = Data; - while (!(FRAM_USART.STATUS & USART_RXCIF_bm)); + while (!(FRAM_USART.STATUS & USART_RXCIF_bm)); - return FRAM_USART.DATA; + return FRAM_USART.DATA; } #ifdef USE_DMA INLINE void SPIReadBlock(void* Buffer, uint16_t ByteCount) { - /* Set up read and write transfers */ - RECV_DMA.ADDRCTRL = DMA_CH_SRCRELOAD_NONE_gc | DMA_CH_SRCDIR_FIXED_gc | DMA_CH_DESTRELOAD_NONE_gc | DMA_CH_DESTDIR_INC_gc; - RECV_DMA.DESTADDR0 = ((uintptr_t) Buffer >> 0) & 0xFF; - RECV_DMA.DESTADDR1 = ((uintptr_t) Buffer >> 8) & 0xFF; - RECV_DMA.TRFCNT = ByteCount; - SEND_DMA.ADDRCTRL = DMA_CH_SRCRELOAD_NONE_gc | DMA_CH_SRCDIR_FIXED_gc | DMA_CH_DESTRELOAD_NONE_gc | DMA_CH_DESTDIR_FIXED_gc; - SEND_DMA.SRCADDR0 = ((uintptr_t) ScrapBuffer >> 0) & 0xFF; - SEND_DMA.SRCADDR1 = ((uintptr_t) ScrapBuffer >> 8) & 0xFF; - SEND_DMA.TRFCNT = ByteCount; + /* Set up read and write transfers */ + RECV_DMA.ADDRCTRL = DMA_CH_SRCRELOAD_NONE_gc | DMA_CH_SRCDIR_FIXED_gc | DMA_CH_DESTRELOAD_NONE_gc | DMA_CH_DESTDIR_INC_gc; + RECV_DMA.DESTADDR0 = ((uintptr_t) Buffer >> 0) & 0xFF; + RECV_DMA.DESTADDR1 = ((uintptr_t) Buffer >> 8) & 0xFF; + RECV_DMA.TRFCNT = ByteCount; + SEND_DMA.ADDRCTRL = DMA_CH_SRCRELOAD_NONE_gc | DMA_CH_SRCDIR_FIXED_gc | DMA_CH_DESTRELOAD_NONE_gc | DMA_CH_DESTDIR_FIXED_gc; + SEND_DMA.SRCADDR0 = ((uintptr_t) ScrapBuffer >> 0) & 0xFF; + SEND_DMA.SRCADDR1 = ((uintptr_t) ScrapBuffer >> 8) & 0xFF; + SEND_DMA.TRFCNT = ByteCount; - /* Enable read and write transfers */ - RECV_DMA.CTRLA |= DMA_CH_ENABLE_bm; - SEND_DMA.CTRLA |= DMA_CH_ENABLE_bm; + /* Enable read and write transfers */ + RECV_DMA.CTRLA |= DMA_CH_ENABLE_bm; + SEND_DMA.CTRLA |= DMA_CH_ENABLE_bm; - /* Wait for DMA to finish */ - while( RECV_DMA.CTRLA & DMA_CH_ENABLE_bm ) - ; + /* Wait for DMA to finish */ + while( RECV_DMA.CTRLA & DMA_CH_ENABLE_bm ) + ; - /* Clear Interrupt flag */ - RECV_DMA.CTRLB = DMA_CH_TRNIF_bm | DMA_CH_ERRIF_bm; - SEND_DMA.CTRLB = DMA_CH_TRNIF_bm | DMA_CH_ERRIF_bm; + /* Clear Interrupt flag */ + RECV_DMA.CTRLB = DMA_CH_TRNIF_bm | DMA_CH_ERRIF_bm; + SEND_DMA.CTRLB = DMA_CH_TRNIF_bm | DMA_CH_ERRIF_bm; } #else INLINE void SPIReadBlock(void* Buffer, uint16_t ByteCount) { - uint8_t* ByteBuffer = (uint8_t*) Buffer; + uint8_t* ByteBuffer = (uint8_t*) Buffer; - while(ByteCount-- > 0) { - FRAM_USART.DATA = 0; - while (!(FRAM_USART.STATUS & USART_RXCIF_bm)); + while(ByteCount-- > 0) { + FRAM_USART.DATA = 0; + while (!(FRAM_USART.STATUS & USART_RXCIF_bm)); - *ByteBuffer++ = FRAM_USART.DATA; - } + *ByteBuffer++ = FRAM_USART.DATA; + } } #endif @@ -91,322 +91,322 @@ INLINE void SPIReadBlock(void* Buffer, uint16_t ByteCount) #ifdef USE_DMA INLINE void SPIWriteBlock(const void* Buffer, uint16_t ByteCount) { - /* Set up read and write transfers */ - RECV_DMA.ADDRCTRL = DMA_CH_SRCRELOAD_NONE_gc | DMA_CH_SRCDIR_FIXED_gc | DMA_CH_DESTRELOAD_NONE_gc | DMA_CH_DESTDIR_FIXED_gc; - RECV_DMA.DESTADDR0 = ((uintptr_t) ScrapBuffer >> 0) & 0xFF; - RECV_DMA.DESTADDR1 = ((uintptr_t) ScrapBuffer >> 8) & 0xFF; - RECV_DMA.TRFCNT = ByteCount; - SEND_DMA.ADDRCTRL = DMA_CH_SRCRELOAD_NONE_gc | DMA_CH_SRCDIR_INC_gc | DMA_CH_DESTRELOAD_NONE_gc | DMA_CH_DESTDIR_FIXED_gc; - SEND_DMA.SRCADDR0 = ((uintptr_t) Buffer >> 0) & 0xFF; - SEND_DMA.SRCADDR1 = ((uintptr_t) Buffer >> 8) & 0xFF; - SEND_DMA.TRFCNT = ByteCount; + /* Set up read and write transfers */ + RECV_DMA.ADDRCTRL = DMA_CH_SRCRELOAD_NONE_gc | DMA_CH_SRCDIR_FIXED_gc | DMA_CH_DESTRELOAD_NONE_gc | DMA_CH_DESTDIR_FIXED_gc; + RECV_DMA.DESTADDR0 = ((uintptr_t) ScrapBuffer >> 0) & 0xFF; + RECV_DMA.DESTADDR1 = ((uintptr_t) ScrapBuffer >> 8) & 0xFF; + RECV_DMA.TRFCNT = ByteCount; + SEND_DMA.ADDRCTRL = DMA_CH_SRCRELOAD_NONE_gc | DMA_CH_SRCDIR_INC_gc | DMA_CH_DESTRELOAD_NONE_gc | DMA_CH_DESTDIR_FIXED_gc; + SEND_DMA.SRCADDR0 = ((uintptr_t) Buffer >> 0) & 0xFF; + SEND_DMA.SRCADDR1 = ((uintptr_t) Buffer >> 8) & 0xFF; + SEND_DMA.TRFCNT = ByteCount; - /* Enable read and write transfers */ - RECV_DMA.CTRLA |= DMA_CH_ENABLE_bm; - SEND_DMA.CTRLA |= DMA_CH_ENABLE_bm; + /* Enable read and write transfers */ + RECV_DMA.CTRLA |= DMA_CH_ENABLE_bm; + SEND_DMA.CTRLA |= DMA_CH_ENABLE_bm; - /* Wait for DMA to finish */ - while( RECV_DMA.CTRLA & DMA_CH_ENABLE_bm ) - ; + /* Wait for DMA to finish */ + while( RECV_DMA.CTRLA & DMA_CH_ENABLE_bm ) + ; - /* Clear Interrupt flag */ - RECV_DMA.CTRLB = DMA_CH_TRNIF_bm | DMA_CH_ERRIF_bm; - SEND_DMA.CTRLB = DMA_CH_TRNIF_bm | DMA_CH_ERRIF_bm; + /* Clear Interrupt flag */ + RECV_DMA.CTRLB = DMA_CH_TRNIF_bm | DMA_CH_ERRIF_bm; + SEND_DMA.CTRLB = DMA_CH_TRNIF_bm | DMA_CH_ERRIF_bm; } #else INLINE void SPIWriteBlock(const void* Buffer, uint16_t ByteCount) { - uint8_t* ByteBuffer = (uint8_t*) Buffer; + uint8_t* ByteBuffer = (uint8_t*) Buffer; - while(ByteCount-- > 0) { - FRAM_USART.DATA = *ByteBuffer++; - while (!(FRAM_USART.STATUS & USART_RXCIF_bm)); + while(ByteCount-- > 0) { + FRAM_USART.DATA = *ByteBuffer++; + while (!(FRAM_USART.STATUS & USART_RXCIF_bm)); - FRAM_USART.DATA; /* Flush Buffer */ - } + FRAM_USART.DATA; /* Flush Buffer */ + } } #endif INLINE void FRAMRead(void* Buffer, uint16_t Address, uint16_t ByteCount) { - FRAM_PORT.OUTCLR = FRAM_CS; + FRAM_PORT.OUTCLR = FRAM_CS; - SPITransferByte(0x03); /* Read command */ - SPITransferByte( (Address >> 8) & 0xFF ); /* Address hi and lo byte */ - SPITransferByte( (Address >> 0) & 0xFF ); + SPITransferByte(0x03); /* Read command */ + SPITransferByte( (Address >> 8) & 0xFF ); /* Address hi and lo byte */ + SPITransferByte( (Address >> 0) & 0xFF ); - SPIReadBlock(Buffer, ByteCount); + SPIReadBlock(Buffer, ByteCount); - FRAM_PORT.OUTSET = FRAM_CS; + FRAM_PORT.OUTSET = FRAM_CS; } INLINE void FRAMWrite(const void* Buffer, uint16_t Address, uint16_t ByteCount) { - FRAM_PORT.OUTCLR = FRAM_CS; - SPITransferByte(0x06); /* Write Enable */ - FRAM_PORT.OUTSET = FRAM_CS; + FRAM_PORT.OUTCLR = FRAM_CS; + SPITransferByte(0x06); /* Write Enable */ + FRAM_PORT.OUTSET = FRAM_CS; - asm volatile ("nop"); - asm volatile ("nop"); + asm volatile ("nop"); + asm volatile ("nop"); - FRAM_PORT.OUTCLR = FRAM_CS; + FRAM_PORT.OUTCLR = FRAM_CS; - SPITransferByte(0x02); /* Write command */ - SPITransferByte( (Address >> 8) & 0xFF ); /* Address hi and lo byte */ - SPITransferByte( (Address >> 0) & 0xFF ); + SPITransferByte(0x02); /* Write command */ + SPITransferByte( (Address >> 8) & 0xFF ); /* Address hi and lo byte */ + SPITransferByte( (Address >> 0) & 0xFF ); - SPIWriteBlock(Buffer, ByteCount); + SPIWriteBlock(Buffer, ByteCount); - FRAM_PORT.OUTSET = FRAM_CS; + FRAM_PORT.OUTSET = FRAM_CS; } INLINE void FlashRead(void* Buffer, uint32_t Address, uint16_t ByteCount) { - uint8_t* BufPtr = (uint8_t*) Buffer; + uint8_t* BufPtr = (uint8_t*) Buffer; - /* We assume that ByteCount is a multiple of 2 */ - uint32_t PhysicalAddress = Address + FLASH_DATA_ADDR; + /* We assume that ByteCount is a multiple of 2 */ + uint32_t PhysicalAddress = Address + FLASH_DATA_ADDR; - if ( (PhysicalAddress >= FLASH_DATA_START) && (PhysicalAddress <= FLASH_DATA_END) ) { - /* Sanity check to limit access to the allocated area */ - while(ByteCount > 1) { - uint16_t Word = FlashReadWord(PhysicalAddress); + if ( (PhysicalAddress >= FLASH_DATA_START) && (PhysicalAddress <= FLASH_DATA_END) ) { + /* Sanity check to limit access to the allocated area */ + while(ByteCount > 1) { + uint16_t Word = FlashReadWord(PhysicalAddress); - *BufPtr++ = (Word >> 0) & 0xFF; - *BufPtr++ = (Word >> 8) & 0xFF; + *BufPtr++ = (Word >> 0) & 0xFF; + *BufPtr++ = (Word >> 8) & 0xFF; - PhysicalAddress += 2; - ByteCount -= 2; - } - } + PhysicalAddress += 2; + ByteCount -= 2; + } + } } INLINE void FlashWrite(const void* Buffer, uint32_t Address, uint16_t ByteCount) { - const uint8_t* BufPtr = (uint8_t*) Buffer; + const uint8_t* BufPtr = (uint8_t*) Buffer; - /* We assume that FlashWrite is always called for write actions that are - * aligned to APP_SECTION_PAGE_SIZE and a multiple of APP_SECTION_PAGE_SIZE. - * Thus only full pages are written into the flash. */ - uint16_t PageCount = ByteCount / APP_SECTION_PAGE_SIZE; - uint32_t PhysicalAddress = Address + FLASH_DATA_ADDR; + /* We assume that FlashWrite is always called for write actions that are + * aligned to APP_SECTION_PAGE_SIZE and a multiple of APP_SECTION_PAGE_SIZE. + * Thus only full pages are written into the flash. */ + uint16_t PageCount = ByteCount / APP_SECTION_PAGE_SIZE; + uint32_t PhysicalAddress = Address + FLASH_DATA_ADDR; - if ( (PhysicalAddress >= FLASH_DATA_START) && (PhysicalAddress <= FLASH_DATA_END) ) { - /* Sanity check to limit access to the allocated area */ + if ( (PhysicalAddress >= FLASH_DATA_START) && (PhysicalAddress <= FLASH_DATA_END) ) { + /* Sanity check to limit access to the allocated area */ - while(PageCount-- > 0) { - /* For each page to program, wait for NVM to get ready, - * erase the flash page buffer, program all data to the - * flash page buffer and write buffer to flash using - * the atomic erase and write operation. */ + while(PageCount-- > 0) { + /* For each page to program, wait for NVM to get ready, + * erase the flash page buffer, program all data to the + * flash page buffer and write buffer to flash using + * the atomic erase and write operation. */ - FlashWaitForSPM(); + FlashWaitForSPM(); - FlashEraseFlashBuffer(); - FlashWaitForSPM(); + FlashEraseFlashBuffer(); + FlashWaitForSPM(); - for (uint16_t i=0; i= FLASH_DATA_START) && (PhysicalAddress <= FLASH_DATA_END) ) { - /* Sanity check to limit access to the allocated area */ - while(PageCount-- > 0) { - FlashWaitForSPM(); + if ( (PhysicalAddress >= FLASH_DATA_START) && (PhysicalAddress <= FLASH_DATA_END) ) { + /* Sanity check to limit access to the allocated area */ + while(PageCount-- > 0) { + FlashWaitForSPM(); - FlashEraseApplicationPage(PhysicalAddress); - FlashWaitForSPM(); + FlashEraseApplicationPage(PhysicalAddress); + FlashWaitForSPM(); - PhysicalAddress += APP_SECTION_PAGE_SIZE; - } - } + PhysicalAddress += APP_SECTION_PAGE_SIZE; + } + } } INLINE void FlashToFRAM(uint32_t Address, uint16_t ByteCount) { - /* We assume that ByteCount is a multiple of 2 */ - uint32_t PhysicalAddress = Address + FLASH_DATA_ADDR; + /* We assume that ByteCount is a multiple of 2 */ + uint32_t PhysicalAddress = Address + FLASH_DATA_ADDR; - if ( (PhysicalAddress >= FLASH_DATA_START) && (PhysicalAddress <= FLASH_DATA_END) ) { - /* Sanity check to limit access to the allocated area. - * Set up FRAM memory for writing. */ - FRAM_PORT.OUTCLR = FRAM_CS; - SPITransferByte(0x06); /* Write Enable */ - FRAM_PORT.OUTSET = FRAM_CS; + if ( (PhysicalAddress >= FLASH_DATA_START) && (PhysicalAddress <= FLASH_DATA_END) ) { + /* Sanity check to limit access to the allocated area. + * Set up FRAM memory for writing. */ + FRAM_PORT.OUTCLR = FRAM_CS; + SPITransferByte(0x06); /* Write Enable */ + FRAM_PORT.OUTSET = FRAM_CS; - asm volatile ("nop"); - asm volatile ("nop"); + asm volatile ("nop"); + asm volatile ("nop"); - FRAM_PORT.OUTCLR = FRAM_CS; + FRAM_PORT.OUTCLR = FRAM_CS; - SPITransferByte(0x02); /* Write command */ - SPITransferByte(0); /* Address hi and lo byte */ - SPITransferByte(0); + SPITransferByte(0x02); /* Write command */ + SPITransferByte(0); /* Address hi and lo byte */ + SPITransferByte(0); - /* Loop through bytes, read words from flash and write - * double byte into FRAM. */ - while(ByteCount > 1) { - uint16_t Word = FlashReadWord(PhysicalAddress); + /* Loop through bytes, read words from flash and write + * double byte into FRAM. */ + while(ByteCount > 1) { + uint16_t Word = FlashReadWord(PhysicalAddress); - SPITransferByte( (Word >> 0) & 0xFF ); - SPITransferByte( (Word >> 8) & 0xFF ); + SPITransferByte( (Word >> 0) & 0xFF ); + SPITransferByte( (Word >> 8) & 0xFF ); - PhysicalAddress += 2; - ByteCount -= 2; - } + PhysicalAddress += 2; + ByteCount -= 2; + } - /* End write procedure of FRAM */ - FRAM_PORT.OUTSET = FRAM_CS; - } + /* End write procedure of FRAM */ + FRAM_PORT.OUTSET = FRAM_CS; + } } INLINE void FRAMToFlash(uint32_t Address, uint16_t ByteCount) { - /* We assume that FlashWrite is always called for write actions that are - * aligned to APP_SECTION_PAGE_SIZE and a multiple of APP_SECTION_PAGE_SIZE. - * Thus only full pages are written into the flash. */ - uint16_t PageCount = ByteCount / APP_SECTION_PAGE_SIZE; - uint32_t PhysicalAddress = Address + FLASH_DATA_ADDR; + /* We assume that FlashWrite is always called for write actions that are + * aligned to APP_SECTION_PAGE_SIZE and a multiple of APP_SECTION_PAGE_SIZE. + * Thus only full pages are written into the flash. */ + uint16_t PageCount = ByteCount / APP_SECTION_PAGE_SIZE; + uint32_t PhysicalAddress = Address + FLASH_DATA_ADDR; - if ( (PhysicalAddress >= FLASH_DATA_START) && (PhysicalAddress <= FLASH_DATA_END) ) { - /* Sanity check to limit access to the allocated area and setup FRAM - * read. */ - FRAM_PORT.OUTCLR = FRAM_CS; + if ( (PhysicalAddress >= FLASH_DATA_START) && (PhysicalAddress <= FLASH_DATA_END) ) { + /* Sanity check to limit access to the allocated area and setup FRAM + * read. */ + FRAM_PORT.OUTCLR = FRAM_CS; - SPITransferByte(0x03); /* Read command */ - SPITransferByte(0); /* Address hi and lo byte */ - SPITransferByte(0); + SPITransferByte(0x03); /* Read command */ + SPITransferByte(0); /* Address hi and lo byte */ + SPITransferByte(0); - while(PageCount-- > 0) { - /* For each page to program, wait for NVM to get ready, - * erase the flash page buffer, program all data to the - * flash page buffer and write buffer to flash using - * the atomic erase and write operation. */ + while(PageCount-- > 0) { + /* For each page to program, wait for NVM to get ready, + * erase the flash page buffer, program all data to the + * flash page buffer and write buffer to flash using + * the atomic erase and write operation. */ - FlashWaitForSPM(); + FlashWaitForSPM(); - FlashEraseFlashBuffer(); - FlashWaitForSPM(); + FlashEraseFlashBuffer(); + FlashWaitForSPM(); - /* Write one page worth of data into flash buffer */ - for (uint16_t i=0; i> 0) & 0xFF; - RECV_DMA.SRCADDR1 = ((uintptr_t) &FRAM_USART.DATA >> 8) & 0xFF; - RECV_DMA.SRCADDR2 = 0; - RECV_DMA.DESTADDR0 = 0; - RECV_DMA.DESTADDR1 = 0; - RECV_DMA.DESTADDR2 = 0; - RECV_DMA.CTRLA = DMA_CH_SINGLE_bm | DMA_CH_BURSTLEN_1BYTE_gc; + /* Init DMAs for reading and writing */ + RECV_DMA.ADDRCTRL = DMA_CH_SRCRELOAD_NONE_gc | DMA_CH_SRCDIR_FIXED_gc | DMA_CH_DESTRELOAD_NONE_gc | DMA_CH_DESTDIR_FIXED_gc; + RECV_DMA.TRIGSRC = DMA_CH_TRIGSRC_USARTD0_RXC_gc; + RECV_DMA.TRFCNT = 0; + RECV_DMA.SRCADDR0 = ((uintptr_t) &FRAM_USART.DATA >> 0) & 0xFF; + RECV_DMA.SRCADDR1 = ((uintptr_t) &FRAM_USART.DATA >> 8) & 0xFF; + RECV_DMA.SRCADDR2 = 0; + RECV_DMA.DESTADDR0 = 0; + RECV_DMA.DESTADDR1 = 0; + RECV_DMA.DESTADDR2 = 0; + RECV_DMA.CTRLA = DMA_CH_SINGLE_bm | DMA_CH_BURSTLEN_1BYTE_gc; - SEND_DMA.ADDRCTRL = DMA_CH_SRCRELOAD_NONE_gc | DMA_CH_SRCDIR_FIXED_gc | DMA_CH_DESTRELOAD_NONE_gc | DMA_CH_DESTDIR_FIXED_gc; - SEND_DMA.TRIGSRC = DMA_CH_TRIGSRC_USARTD0_DRE_gc; - SEND_DMA.TRFCNT = 0; - SEND_DMA.SRCADDR0 = 0; - SEND_DMA.SRCADDR1 = 0; - SEND_DMA.SRCADDR2 = 0; - SEND_DMA.DESTADDR0 = ((uintptr_t) &FRAM_USART.DATA >> 0) & 0xFF; - SEND_DMA.DESTADDR1 = ((uintptr_t) &FRAM_USART.DATA >> 8) & 0xFF; - SEND_DMA.DESTADDR2 = 0; - SEND_DMA.CTRLA = DMA_CH_SINGLE_bm | DMA_CH_BURSTLEN_1BYTE_gc; + SEND_DMA.ADDRCTRL = DMA_CH_SRCRELOAD_NONE_gc | DMA_CH_SRCDIR_FIXED_gc | DMA_CH_DESTRELOAD_NONE_gc | DMA_CH_DESTDIR_FIXED_gc; + SEND_DMA.TRIGSRC = DMA_CH_TRIGSRC_USARTD0_DRE_gc; + SEND_DMA.TRFCNT = 0; + SEND_DMA.SRCADDR0 = 0; + SEND_DMA.SRCADDR1 = 0; + SEND_DMA.SRCADDR2 = 0; + SEND_DMA.DESTADDR0 = ((uintptr_t) &FRAM_USART.DATA >> 0) & 0xFF; + SEND_DMA.DESTADDR1 = ((uintptr_t) &FRAM_USART.DATA >> 8) & 0xFF; + SEND_DMA.DESTADDR2 = 0; + SEND_DMA.CTRLA = DMA_CH_SINGLE_bm | DMA_CH_BURSTLEN_1BYTE_gc; } void MemoryReadBlock(void* Buffer, uint16_t Address, uint16_t ByteCount) { - if (ByteCount == 0) - return; - FRAMRead(Buffer, Address, ByteCount); + if (ByteCount == 0) + return; + FRAMRead(Buffer, Address, ByteCount); } void MemoryWriteBlock(const void* Buffer, uint16_t Address, uint16_t ByteCount) { - if (ByteCount == 0) - return; - FRAMWrite(Buffer, Address, ByteCount); + if (ByteCount == 0) + return; + FRAMWrite(Buffer, Address, ByteCount); - LEDHook(LED_MEMORY_CHANGED, LED_ON); + LEDHook(LED_MEMORY_CHANGED, LED_ON); } void MemoryClear(void) { - FlashErase((uint32_t) GlobalSettings.ActiveSettingIdx * MEMORY_SIZE_PER_SETTING, MEMORY_SIZE_PER_SETTING); + FlashErase((uint32_t) GlobalSettings.ActiveSettingIdx * MEMORY_SIZE_PER_SETTING, MEMORY_SIZE_PER_SETTING); - MemoryRecall(); + MemoryRecall(); } void MemoryRecall(void) { - /* Recall memory from permanent flash */ - FlashToFRAM((uint32_t) GlobalSettings.ActiveSettingIdx * MEMORY_SIZE_PER_SETTING, MEMORY_SIZE_PER_SETTING); + /* Recall memory from permanent flash */ + FlashToFRAM((uint32_t) GlobalSettings.ActiveSettingIdx * MEMORY_SIZE_PER_SETTING, MEMORY_SIZE_PER_SETTING); SystemTickClearFlag(); } void MemoryStore(void) { - /* Store current memory into permanent flash */ - FRAMToFlash((uint32_t) GlobalSettings.ActiveSettingIdx * MEMORY_SIZE_PER_SETTING, MEMORY_SIZE_PER_SETTING); + /* Store current memory into permanent flash */ + FRAMToFlash((uint32_t) GlobalSettings.ActiveSettingIdx * MEMORY_SIZE_PER_SETTING, MEMORY_SIZE_PER_SETTING); - LEDHook(LED_MEMORY_CHANGED, LED_OFF); - LEDHook(LED_MEMORY_STORED, LED_PULSE); + LEDHook(LED_MEMORY_CHANGED, LED_OFF); + LEDHook(LED_MEMORY_STORED, LED_PULSE); SystemTickClearFlag(); } @@ -417,14 +417,14 @@ bool MemoryUploadBlock(void* Buffer, uint32_t BlockAddress, uint16_t ByteCount) /* Prevent writing out of bounds by silently ignoring it */ return true; } else { - /* Calculate bytes left in memory and start writing */ - uint32_t BytesLeft = MEMORY_SIZE_PER_SETTING - BlockAddress; - ByteCount = MIN(ByteCount, BytesLeft); + /* Calculate bytes left in memory and start writing */ + uint32_t BytesLeft = MEMORY_SIZE_PER_SETTING - BlockAddress; + ByteCount = MIN(ByteCount, BytesLeft); - /* Store to local memory */ - FRAMWrite(Buffer, BlockAddress, ByteCount); + /* Store to local memory */ + FRAMWrite(Buffer, BlockAddress, ByteCount); - return true; + return true; } } @@ -434,12 +434,12 @@ bool MemoryDownloadBlock(void* Buffer, uint32_t BlockAddress, uint16_t ByteCount /* There are bytes out of bounds to be read. Notify that we are done. */ return false; } else { - /* Calculate bytes left in memory and issue reading */ - uint32_t BytesLeft = MEMORY_SIZE_PER_SETTING - BlockAddress; - ByteCount = MIN(ByteCount, BytesLeft); + /* Calculate bytes left in memory and issue reading */ + uint32_t BytesLeft = MEMORY_SIZE_PER_SETTING - BlockAddress; + ByteCount = MIN(ByteCount, BytesLeft); - /* Output local memory contents */ - FRAMRead(Buffer, BlockAddress, ByteCount); + /* Output local memory contents */ + FRAMRead(Buffer, BlockAddress, ByteCount); return true; } @@ -449,16 +449,16 @@ bool MemoryDownloadBlock(void* Buffer, uint32_t BlockAddress, uint16_t ByteCount static inline void NVM_EXEC(void) { - void *z = (void *)&NVM_CTRLA; + void *z = (void *)&NVM_CTRLA; - __asm__ volatile("out %[ccp], %[ioreg]" "\n\t" - "st z, %[cmdex]" - : - : [ccp] "I" (_SFR_IO_ADDR(CCP)), - [ioreg] "d" (CCP_IOREG_gc), - [cmdex] "r" (NVM_CMDEX_bm), - [z] "z" (z) - ); + __asm__ volatile("out %[ccp], %[ioreg]" "\n\t" + "st z, %[cmdex]" + : + : [ccp] "I" (_SFR_IO_ADDR(CCP)), + [ioreg] "d" (CCP_IOREG_gc), + [cmdex] "r" (NVM_CMDEX_bm), + [z] "z" (z) + ); } void WaitForNVM(void) @@ -468,82 +468,82 @@ void WaitForNVM(void) void FlushNVMBuffer(void) { - WaitForNVM(); + WaitForNVM(); - if ((NVM.STATUS & NVM_EELOAD_bm) != 0) { - NVM.CMD = NVM_CMD_ERASE_EEPROM_BUFFER_gc; - NVM_EXEC(); - } + if ((NVM.STATUS & NVM_EELOAD_bm) != 0) { + NVM.CMD = NVM_CMD_ERASE_EEPROM_BUFFER_gc; + NVM_EXEC(); + } } uint16_t ReadEEPBlock(uint16_t Address, void *DestPtr, uint16_t ByteCount) { - uint16_t BytesRead = 0; - uint8_t* BytePtr = (uint8_t*) DestPtr; - NVM.ADDR2 = 0; + uint16_t BytesRead = 0; + uint8_t* BytePtr = (uint8_t*) DestPtr; + NVM.ADDR2 = 0; - WaitForNVM(); + WaitForNVM(); - while (ByteCount > 0) - { - NVM.ADDR0 = Address & 0xFF; - NVM.ADDR1 = (Address >> 8) & 0x1F; + while (ByteCount > 0) + { + NVM.ADDR0 = Address & 0xFF; + NVM.ADDR1 = (Address >> 8) & 0x1F; - NVM.CMD = NVM_CMD_READ_EEPROM_gc; - NVM_EXEC(); + NVM.CMD = NVM_CMD_READ_EEPROM_gc; + NVM_EXEC(); - *BytePtr++ = NVM.DATA0; - Address++; + *BytePtr++ = NVM.DATA0; + Address++; - ByteCount--; - BytesRead++; - } + ByteCount--; + BytesRead++; + } - return BytesRead; + return BytesRead; } uint16_t WriteEEPBlock(uint16_t Address, const void *SrcPtr, uint16_t ByteCount) { - const uint8_t* BytePtr = (const uint8_t*) SrcPtr; - uint8_t ByteAddress = Address % EEPROM_PAGE_SIZE; - uint16_t PageAddress = Address - ByteAddress; - uint16_t BytesWritten = 0; + const uint8_t* BytePtr = (const uint8_t*) SrcPtr; + uint8_t ByteAddress = Address % EEPROM_PAGE_SIZE; + uint16_t PageAddress = Address - ByteAddress; + uint16_t BytesWritten = 0; - FlushNVMBuffer(); - WaitForNVM(); - NVM.CMD = NVM_CMD_LOAD_EEPROM_BUFFER_gc; + FlushNVMBuffer(); + WaitForNVM(); + NVM.CMD = NVM_CMD_LOAD_EEPROM_BUFFER_gc; - NVM.ADDR1 = 0; - NVM.ADDR2 = 0; + NVM.ADDR1 = 0; + NVM.ADDR2 = 0; - while (ByteCount > 0) - { - NVM.ADDR0 = ByteAddress; + while (ByteCount > 0) + { + NVM.ADDR0 = ByteAddress; - NVM.DATA0 = *BytePtr++; + NVM.DATA0 = *BytePtr++; - ByteAddress++; - ByteCount--; + ByteAddress++; + ByteCount--; - if (ByteCount == 0 || ByteAddress >= EEPROM_PAGE_SIZE) - { - NVM.ADDR0 = PageAddress & 0xFF; - NVM.ADDR1 = (PageAddress >> 8) & 0x1F; + if (ByteCount == 0 || ByteAddress >= EEPROM_PAGE_SIZE) + { + NVM.ADDR0 = PageAddress & 0xFF; + NVM.ADDR1 = (PageAddress >> 8) & 0x1F; - NVM.CMD = NVM_CMD_ERASE_WRITE_EEPROM_PAGE_gc; - NVM_EXEC(); + NVM.CMD = NVM_CMD_ERASE_WRITE_EEPROM_PAGE_gc; + NVM_EXEC(); - PageAddress += EEPROM_PAGE_SIZE; - ByteAddress = 0; + PageAddress += EEPROM_PAGE_SIZE; + ByteAddress = 0; - WaitForNVM(); + WaitForNVM(); - NVM.CMD = NVM_CMD_LOAD_EEPROM_BUFFER_gc; - } + NVM.CMD = NVM_CMD_LOAD_EEPROM_BUFFER_gc; + } - BytesWritten++; - } + BytesWritten++; + } - return BytesWritten; + return BytesWritten; } diff --git a/Firmware/Chameleon-Mini/MemoryAsm.S b/Firmware/Chameleon-Mini/MemoryAsm.S index efb3374..be91df9 100644 --- a/Firmware/Chameleon-Mini/MemoryAsm.S +++ b/Firmware/Chameleon-Mini/MemoryAsm.S @@ -53,13 +53,13 @@ .section .text .global FlashReadWord FlashReadWord: - in r19, RAMPZ ; Save RAMPZ. - out RAMPZ, r24 ; Load RAMPZ with the MSB of the address. - movw ZL, r22 ; Move the low bytes to the Z pointer - elpm r24, Z+ ; Extended load byte from address pointed to by Z. - elpm r25, Z ; Extended load byte from address pointed to by Z. - out RAMPZ, r19 ; Restore RAMPZ register. - ret + in r19, RAMPZ ; Save RAMPZ. + out RAMPZ, r24 ; Load RAMPZ with the MSB of the address. + movw ZL, r22 ; Move the low bytes to the Z pointer + elpm r24, Z+ ; Extended load byte from address pointed to by Z. + elpm r25, Z ; Extended load byte from address pointed to by Z. + out RAMPZ, r19 ; Restore RAMPZ register. + ret ; This routine erases the page at address R25:R24:R23:R22 in the application ; section. The address can point anywhere inside the page. @@ -72,11 +72,11 @@ FlashReadWord: .section .text .global FlashEraseApplicationPage FlashEraseApplicationPage: - in r19, RAMPZ ; Save RAMPZ, which is restored in FlashCommonSPM. - out RAMPZ, r24 ; Load RAMPZ with the MSB of the address. - movw r24, r22 ; Move low bytes for ZH:ZL to R25:R24 - ldi r20, NVM_CMD_ERASE_APP_PAGE_gc ; Prepare NVM command in R20. - jmp FlashCommonSPM ; Jump to common SPM code. + in r19, RAMPZ ; Save RAMPZ, which is restored in FlashCommonSPM. + out RAMPZ, r24 ; Load RAMPZ with the MSB of the address. + movw r24, r22 ; Move low bytes for ZH:ZL to R25:R24 + ldi r20, NVM_CMD_ERASE_APP_PAGE_gc ; Prepare NVM command in R20. + jmp FlashCommonSPM ; Jump to common SPM code. ; This routine writes the word from R23:R22 into the Flash page buffer at ; address R25:R24. @@ -90,10 +90,10 @@ FlashEraseApplicationPage: .section .text .global FlashLoadFlashWord FlashLoadFlashWord: - in r19, RAMPZ ; Save RAMPZ, which is restored in FlashCommonSPM. - movw r0, r22 ; Prepare flash word in R1:R0. - ldi r20, NVM_CMD_LOAD_FLASH_BUFFER_gc ; Prepare NVM command in R20. - jmp FlashCommonSPM ; Jump to common SPM code. + in r19, RAMPZ ; Save RAMPZ, which is restored in FlashCommonSPM. + movw r0, r22 ; Prepare flash word in R1:R0. + ldi r20, NVM_CMD_LOAD_FLASH_BUFFER_gc ; Prepare NVM command in R20. + jmp FlashCommonSPM ; Jump to common SPM code. ; This routine erases first and then writes the page buffer to the @@ -108,11 +108,11 @@ FlashLoadFlashWord: .section .text .global FlashEraseWriteApplicationPage FlashEraseWriteApplicationPage: - in r19, RAMPZ ; Save RAMPZ, which is restored in FlashCommonSPM. - out RAMPZ, r24 ; Load RAMPZ with the MSB of the address. - movw r24, r22 ; Move low bytes of address to ZH:ZL from R23:R22 - ldi r20, NVM_CMD_ERASE_WRITE_APP_PAGE_gc ; Prepare NVM command in R20. - jmp FlashCommonSPM ; Jump to common SPM code. + in r19, RAMPZ ; Save RAMPZ, which is restored in FlashCommonSPM. + out RAMPZ, r24 ; Load RAMPZ with the MSB of the address. + movw r24, r22 ; Move low bytes of address to ZH:ZL from R23:R22 + ldi r20, NVM_CMD_ERASE_WRITE_APP_PAGE_gc ; Prepare NVM command in R20. + jmp FlashCommonSPM ; Jump to common SPM code. ; This routine flushes the Flash page buffer. ; @@ -124,10 +124,10 @@ FlashEraseWriteApplicationPage: .section .text .global FlashEraseFlashBuffer FlashEraseFlashBuffer: - in r19, RAMPZ ; Save RAMPZ, which is restored in FlashCommonSPM. - ldi r20, NVM_CMD_ERASE_FLASH_BUFFER_gc ; Prepare NVM command in R20. - ;jmp FlashCommonSPM ; Jump to common SPM code. - jmp FlashCommonCMD + in r19, RAMPZ ; Save RAMPZ, which is restored in FlashCommonSPM. + ldi r20, NVM_CMD_ERASE_FLASH_BUFFER_gc ; Prepare NVM command in R20. + ;jmp FlashCommonSPM ; Jump to common SPM code. + jmp FlashCommonCMD ; This routine wait for the SPM to finish and clears the command register. ; @@ -142,12 +142,12 @@ FlashEraseFlashBuffer: .section .text .global FlashWaitForSPM FlashWaitForSPM: - lds r18, NVM_STATUS ; Load the NVM Status register. - sbrc r18, NVM_NVMBUSY_bp ; Check if bit is cleared. - rjmp FlashWaitForSPM ; Repeat check if bit is not cleared. - clr r18 - sts NVM_CMD, r18 ; Clear up command register to NO_OPERATION. - ret + lds r18, NVM_STATUS ; Load the NVM Status register. + sbrc r18, NVM_NVMBUSY_bp ; Check if bit is cleared. + rjmp FlashWaitForSPM ; Repeat check if bit is not cleared. + clr r18 + sts NVM_CMD, r18 ; Clear up command register to NO_OPERATION. + ret ; This routine is called by several other routines, and contains common code ; for executing an NVM command, including the return statement itself. @@ -165,16 +165,16 @@ FlashWaitForSPM: ; R25:R24:R23:R22 - 32-bit result from NVM operation. .section .text FlashCommonCMD: - sts NVM_CMD, r20 ; Load command into NVM Command register. - ldi r18, CCP_IOREG_gc ; Prepare Protect IO-register signature in R18. - ldi r19, NVM_CMDEX_bm ; Prepare bitmask for setting NVM Command Execute bit into R19. - sts CCP, r18 ; Enable IO-register operation (this disables interrupts for 4 cycles). - sts NVM_CTRLA, r19 ; Load bitmask into NVM Control Register A, which executes the command. - lds r22, NVM_DATA0 ; Load NVM Data Register 0 into R22. - lds r23, NVM_DATA1 ; Load NVM Data Register 1 into R23. - lds r24, NVM_DATA2 ; Load NVM Data Register 2 into R24. - clr r25 ; Clear R25 in order to return a clean 32-bit value. - ret + sts NVM_CMD, r20 ; Load command into NVM Command register. + ldi r18, CCP_IOREG_gc ; Prepare Protect IO-register signature in R18. + ldi r19, NVM_CMDEX_bm ; Prepare bitmask for setting NVM Command Execute bit into R19. + sts CCP, r18 ; Enable IO-register operation (this disables interrupts for 4 cycles). + sts NVM_CTRLA, r19 ; Load bitmask into NVM Control Register A, which executes the command. + lds r22, NVM_DATA0 ; Load NVM Data Register 0 into R22. + lds r23, NVM_DATA1 ; Load NVM Data Register 1 into R23. + lds r24, NVM_DATA2 ; Load NVM Data Register 2 into R24. + clr r25 ; Clear R25 in order to return a clean 32-bit value. + ret ; This routine is called by several other routines, and contains common code ; for executing an LPM command, including the return statement itself. @@ -190,10 +190,10 @@ FlashCommonCMD: ; R24 - Result from LPM operation. .section .text FlashCommonLPM: - movw ZL, r24 ; Load index into Z. - sts NVM_CMD, r20 ; Load prepared command into NVM Command register. - lpm r24,Z - ret + movw ZL, r24 ; Load index into Z. + sts NVM_CMD, r20 ; Load prepared command into NVM Command register. + lpm r24,Z + ret ; This routine is called by several other routines, and contains common code ; for executing an SPM command, including the return statement itself. @@ -210,14 +210,14 @@ FlashCommonLPM: ; Nothing. .section .spmhelper FlashCommonSPM: - movw ZL, r24 ; Load R25:R24 into Z. - sts NVM_CMD, r20 ; Load prepared command into NVM Command register. - ldi r18, CCP_SPM_gc ; Prepare Protect SPM signature in R18 - sts CCP, r18 ; Enable SPM operation (this disables interrupts for 4 cycles). - spm ; Self-program. - clr r1 ; Clear R1 for GCC _zero_reg_ to function properly. - out RAMPZ, r19 ; Restore RAMPZ register. - ret + movw ZL, r24 ; Load R25:R24 into Z. + sts NVM_CMD, r20 ; Load prepared command into NVM Command register. + ldi r18, CCP_SPM_gc ; Prepare Protect SPM signature in R18 + sts CCP, r18 ; Enable SPM operation (this disables interrupts for 4 cycles). + spm ; Self-program. + clr r1 ; Clear R1 for GCC _zero_reg_ to function properly. + out RAMPZ, r19 ; Restore RAMPZ register. + ret /* Reserve memory for data */ .section .flashdata diff --git a/Firmware/Chameleon-Mini/Settings.c b/Firmware/Chameleon-Mini/Settings.c index 7f7b384..6ef2d33 100644 --- a/Firmware/Chameleon-Mini/Settings.c +++ b/Firmware/Chameleon-Mini/Settings.c @@ -13,24 +13,24 @@ SettingsType GlobalSettings; SettingsType EEMEM StoredSettings = { - .ActiveSettingIdx = SETTING_TO_INDEX(DEFAULT_SETTING), - .ActiveSettingPtr = &GlobalSettings.Settings[SETTING_TO_INDEX(DEFAULT_SETTING)], + .ActiveSettingIdx = SETTING_TO_INDEX(DEFAULT_SETTING), + .ActiveSettingPtr = &GlobalSettings.Settings[SETTING_TO_INDEX(DEFAULT_SETTING)], - .Settings = { [0 ... (SETTINGS_COUNT-1)] = { - .Configuration = DEFAULT_CONFIGURATION, - .ButtonActions = { - [BUTTON_L_PRESS_SHORT] = DEFAULT_LBUTTON_ACTION, [BUTTON_R_PRESS_SHORT] = DEFAULT_RBUTTON_ACTION, - [BUTTON_L_PRESS_LONG] = DEFAULT_LBUTTON_ACTION, [BUTTON_R_PRESS_LONG] = DEFAULT_RBUTTON_ACTION - }, - .LogMode = DEFAULT_LOG_MODE, - .LEDRedFunction = DEFAULT_RED_LED_ACTION, - .LEDGreenFunction = DEFAULT_GREEN_LED_ACTION, - .PendingTaskTimeout = DEFAULT_PENDING_TASK_TIMEOUT - }} + .Settings = { [0 ... (SETTINGS_COUNT-1)] = { + .Configuration = DEFAULT_CONFIGURATION, + .ButtonActions = { + [BUTTON_L_PRESS_SHORT] = DEFAULT_LBUTTON_ACTION, [BUTTON_R_PRESS_SHORT] = DEFAULT_RBUTTON_ACTION, + [BUTTON_L_PRESS_LONG] = DEFAULT_LBUTTON_ACTION, [BUTTON_R_PRESS_LONG] = DEFAULT_RBUTTON_ACTION + }, + .LogMode = DEFAULT_LOG_MODE, + .LEDRedFunction = DEFAULT_RED_LED_ACTION, + .LEDGreenFunction = DEFAULT_GREEN_LED_ACTION, + .PendingTaskTimeout = DEFAULT_PENDING_TASK_TIMEOUT + }} }; void SettingsLoad(void) { - ReadEEPBlock((uint16_t) &StoredSettings, &GlobalSettings, sizeof(SettingsType)); + ReadEEPBlock((uint16_t) &StoredSettings, &GlobalSettings, sizeof(SettingsType)); } void SettingsSave(void) { @@ -47,19 +47,19 @@ void ActiveSettingNumberSave(void) { } void SettingsCycle(void) { - uint8_t i = SETTINGS_COUNT; - uint8_t SettingIdx = GlobalSettings.ActiveSettingIdx; + uint8_t i = SETTINGS_COUNT; + uint8_t SettingIdx = GlobalSettings.ActiveSettingIdx; - while (i-- > 0) { - /* Try to set one of the SETTINGS_COUNT following settings. - * But only set if it is not CONFIG_NONE. */ - SettingIdx = (SettingIdx + 1) % SETTINGS_COUNT; + while (i-- > 0) { + /* Try to set one of the SETTINGS_COUNT following settings. + * But only set if it is not CONFIG_NONE. */ + SettingIdx = (SettingIdx + 1) % SETTINGS_COUNT; - if (GlobalSettings.Settings[SettingIdx].Configuration != CONFIG_NONE) { - SettingsSetActiveById(INDEX_TO_SETTING(SettingIdx)); - break; - } - } + if (GlobalSettings.Settings[SettingIdx].Configuration != CONFIG_NONE) { + SettingsSetActiveById(INDEX_TO_SETTING(SettingIdx)); + break; + } + } } bool SettingsSetActiveById(uint8_t Setting) { @@ -96,22 +96,22 @@ bool SettingsSetActiveById(uint8_t Setting) { } uint8_t SettingsGetActiveById(void) { - return INDEX_TO_SETTING(GlobalSettings.ActiveSettingIdx); + return INDEX_TO_SETTING(GlobalSettings.ActiveSettingIdx); } void SettingsGetActiveByName(char* SettingOut, uint16_t BufferSize) { - SettingOut[0] = SettingsGetActiveById() + '0'; - SettingOut[1] = '\0'; + SettingOut[0] = SettingsGetActiveById() + '0'; + SettingOut[1] = '\0'; } bool SettingsSetActiveByName(const char* Setting) { - uint8_t SettingNr = Setting[0] - '0'; + uint8_t SettingNr = Setting[0] - '0'; - if (Setting[1] == '\0') { - LogEntry(LOG_INFO_SETTING_SET, Setting, 1); - return SettingsSetActiveById(SettingNr); - } else { - return false; - } + if (Setting[1] == '\0') { + LogEntry(LOG_INFO_SETTING_SET, Setting, 1); + return SettingsSetActiveById(SettingNr); + } else { + return false; + } } diff --git a/Firmware/Chameleon-Mini/Settings.h b/Firmware/Chameleon-Mini/Settings.h index 987bfd7..4d5bd3d 100644 --- a/Firmware/Chameleon-Mini/Settings.h +++ b/Firmware/Chameleon-Mini/Settings.h @@ -23,18 +23,18 @@ * \note Some properties may change globally if this is defined in the Makefile. */ typedef struct { - ButtonActionEnum ButtonActions[BUTTON_TYPE_COUNT]; /// Button actions for this setting. - LogModeEnum LogMode; /// Log mode for this setting. - ConfigurationEnum Configuration; /// Active configuration for this setting. - LEDHookEnum LEDRedFunction; /// Red LED function for this setting. - LEDHookEnum LEDGreenFunction; /// Green LED function for this setting. - uint16_t PendingTaskTimeout; /// Timeout for timeout commands for this setting, in multiples of 100 ms. + ButtonActionEnum ButtonActions[BUTTON_TYPE_COUNT]; /// Button actions for this setting. + LogModeEnum LogMode; /// Log mode for this setting. + ConfigurationEnum Configuration; /// Active configuration for this setting. + LEDHookEnum LEDRedFunction; /// Red LED function for this setting. + LEDHookEnum LEDGreenFunction; /// Green LED function for this setting. + uint16_t PendingTaskTimeout; /// Timeout for timeout commands for this setting, in multiples of 100 ms. } SettingsEntryType; typedef struct { - uint8_t ActiveSettingIdx; - SettingsEntryType* ActiveSettingPtr; - SettingsEntryType Settings[SETTINGS_COUNT]; + uint8_t ActiveSettingIdx; + SettingsEntryType* ActiveSettingPtr; + SettingsEntryType Settings[SETTINGS_COUNT]; } SettingsType; extern SettingsType GlobalSettings; diff --git a/Firmware/Chameleon-Mini/System.c b/Firmware/Chameleon-Mini/System.c index 978bf49..fd44543 100644 --- a/Firmware/Chameleon-Mini/System.c +++ b/Firmware/Chameleon-Mini/System.c @@ -15,13 +15,13 @@ ISR(BADISR_vect) { - //LED_PORT.OUTSET = LED_RED; + //LED_PORT.OUTSET = LED_RED; while(1); } ISR(RTC_OVF_vect) { - SYSTEM_TICK_REGISTER += SYSTEM_TICK_PERIOD; + SYSTEM_TICK_REGISTER += SYSTEM_TICK_PERIOD; } void SystemInit(void) @@ -46,14 +46,14 @@ void SystemInit(void) OSC.PLLCTRL = OSC_PLLSRC_XOSC_gc | (2 << OSC_PLLFAC_gp); OSC.CTRL |= OSC_PLLEN_bm; - while(!(OSC.STATUS & OSC_PLLRDY_bm)) - ; + while(!(OSC.STATUS & OSC_PLLRDY_bm)) + ; - /* Set PLL as main clock */ - CCP = CCP_IOREG_gc; - CLK.CTRL = CLK_SCLKSEL_PLL_gc; + /* Set PLL as main clock */ + CCP = CCP_IOREG_gc; + CLK.CTRL = CLK_SCLKSEL_PLL_gc; - SYSTEM_TICK_REGISTER = 0; + SYSTEM_TICK_REGISTER = 0; /* Enable RTC with roughly 1kHz clock for system tick * and to wake up while sleeping. */ @@ -67,7 +67,7 @@ void SystemInit(void) //NVM.CTRLB |= NVM_EEMAPEN_bm; /* Enable DMA */ - DMA.CTRL = DMA_ENABLE_bm | DMA_DBUFMODE_DISABLED_gc | DMA_PRIMODE_RR0123_gc; + DMA.CTRL = DMA_ENABLE_bm | DMA_DBUFMODE_DISABLED_gc | DMA_PRIMODE_RR0123_gc; } @@ -87,7 +87,7 @@ void SystemEnterBootloader(void) void SystemStartUSBClock(void) { - //SystemSleepDisable(); + //SystemSleepDisable(); #if 0 /* 48MHz USB Clock using 12MHz XTAL */ OSC.XOSCCTRL = OSC_FRQRANGE_12TO16_gc | OSC_XOSCSEL_XTAL_16KCLK_gc; @@ -127,7 +127,7 @@ void SystemStartUSBClock(void) void SystemStopUSBClock(void) { - //SystemSleepEnable(); + //SystemSleepEnable(); #if 0 /* Disable USB Clock to minimize power consumption */ diff --git a/Firmware/Chameleon-Mini/System.h b/Firmware/Chameleon-Mini/System.h index 45e8fc2..2f648b4 100644 --- a/Firmware/Chameleon-Mini/System.h +++ b/Firmware/Chameleon-Mini/System.h @@ -41,11 +41,11 @@ INLINE bool SystemTick100ms(void); INLINE bool SystemTick100ms(void) { if (RTC.INTFLAGS & RTC_COMPIF_bm) { - while(RTC.STATUS & RTC_SYNCBUSY_bm) - ; + while(RTC.STATUS & RTC_SYNCBUSY_bm) + ; - RTC.INTFLAGS = RTC_COMPIF_bm; - return true; + RTC.INTFLAGS = RTC_COMPIF_bm; + return true; } return false; @@ -60,7 +60,7 @@ INLINE void SystemTickClearFlag(void) } INLINE uint16_t SystemGetSysTick(void) { - return SYSTEM_TICK_REGISTER | RTC.CNT; + return SYSTEM_TICK_REGISTER | RTC.CNT; } #endif /* SYSTEM_H */ diff --git a/Firmware/Chameleon-Mini/Terminal/CommandLine.c b/Firmware/Chameleon-Mini/Terminal/CommandLine.c index 78d5225..ce94bff 100644 --- a/Firmware/Chameleon-Mini/Terminal/CommandLine.c +++ b/Firmware/Chameleon-Mini/Terminal/CommandLine.c @@ -191,32 +191,32 @@ const PROGMEM CommandEntryType CommandTable[] = { .GetFunc = NO_FUNCTION }, { - .Command = COMMAND_SETTING, - .ExecFunc = NO_FUNCTION, + .Command = COMMAND_SETTING, + .ExecFunc = NO_FUNCTION, .ExecParamFunc = NO_FUNCTION, - .SetFunc = CommandSetSetting, - .GetFunc = CommandGetSetting + .SetFunc = CommandSetSetting, + .GetFunc = CommandGetSetting }, { - .Command = COMMAND_CLEAR, - .ExecFunc = CommandExecClear, + .Command = COMMAND_CLEAR, + .ExecFunc = CommandExecClear, .ExecParamFunc = NO_FUNCTION, - .SetFunc = NO_FUNCTION, - .GetFunc = NO_FUNCTION + .SetFunc = NO_FUNCTION, + .GetFunc = NO_FUNCTION }, { - .Command = COMMAND_STORE, - .ExecFunc = CommandExecStore, + .Command = COMMAND_STORE, + .ExecFunc = CommandExecStore, .ExecParamFunc = NO_FUNCTION, - .SetFunc = NO_FUNCTION, - .GetFunc = NO_FUNCTION + .SetFunc = NO_FUNCTION, + .GetFunc = NO_FUNCTION }, { - .Command = COMMAND_RECALL, - .ExecFunc = CommandExecRecall, + .Command = COMMAND_RECALL, + .ExecFunc = CommandExecRecall, .ExecParamFunc = NO_FUNCTION, - .SetFunc = NO_FUNCTION, - .GetFunc = NO_FUNCTION + .SetFunc = NO_FUNCTION, + .GetFunc = NO_FUNCTION }, { .Command = COMMAND_CHARGING, @@ -233,67 +233,67 @@ const PROGMEM CommandEntryType CommandTable[] = { .GetFunc = NO_FUNCTION }, { - .Command = COMMAND_RSSI, - .ExecFunc = NO_FUNCTION, + .Command = COMMAND_RSSI, + .ExecFunc = NO_FUNCTION, .ExecParamFunc = NO_FUNCTION, - .SetFunc = NO_FUNCTION, - .GetFunc = CommandGetRssi + .SetFunc = NO_FUNCTION, + .GetFunc = CommandGetRssi }, { - .Command = COMMAND_SYSTICK, - .ExecFunc = NO_FUNCTION, + .Command = COMMAND_SYSTICK, + .ExecFunc = NO_FUNCTION, .ExecParamFunc = NO_FUNCTION, - .SetFunc = NO_FUNCTION, - .GetFunc = CommandGetSysTick + .SetFunc = NO_FUNCTION, + .GetFunc = CommandGetSysTick }, { - .Command = COMMAND_SEND_RAW, - .ExecFunc = NO_FUNCTION, + .Command = COMMAND_SEND_RAW, + .ExecFunc = NO_FUNCTION, .ExecParamFunc = CommandExecParamSendRaw, - .SetFunc = NO_FUNCTION, - .GetFunc = NO_FUNCTION + .SetFunc = NO_FUNCTION, + .GetFunc = NO_FUNCTION }, { - .Command = COMMAND_SEND, - .ExecFunc = NO_FUNCTION, + .Command = COMMAND_SEND, + .ExecFunc = NO_FUNCTION, .ExecParamFunc = CommandExecParamSend, - .SetFunc = NO_FUNCTION, - .GetFunc = NO_FUNCTION + .SetFunc = NO_FUNCTION, + .GetFunc = NO_FUNCTION }, { - .Command = COMMAND_GETUID, - .ExecFunc = CommandExecGetUid, + .Command = COMMAND_GETUID, + .ExecFunc = CommandExecGetUid, .ExecParamFunc = NO_FUNCTION, - .SetFunc = NO_FUNCTION, - .GetFunc = NO_FUNCTION + .SetFunc = NO_FUNCTION, + .GetFunc = NO_FUNCTION }, { - .Command = COMMAND_DUMP_MFU, - .ExecFunc = CommandExecDumpMFU, + .Command = COMMAND_DUMP_MFU, + .ExecFunc = CommandExecDumpMFU, .ExecParamFunc = NO_FUNCTION, - .SetFunc = NO_FUNCTION, - .GetFunc = NO_FUNCTION + .SetFunc = NO_FUNCTION, + .GetFunc = NO_FUNCTION }, { - .Command = COMMAND_IDENTIFY_CARD, - .ExecFunc = CommandExecIdentifyCard, + .Command = COMMAND_IDENTIFY_CARD, + .ExecFunc = CommandExecIdentifyCard, .ExecParamFunc = NO_FUNCTION, - .SetFunc = NO_FUNCTION, - .GetFunc = NO_FUNCTION + .SetFunc = NO_FUNCTION, + .GetFunc = NO_FUNCTION }, { - .Command = COMMAND_TIMEOUT, - .ExecFunc = NO_FUNCTION, + .Command = COMMAND_TIMEOUT, + .ExecFunc = NO_FUNCTION, .ExecParamFunc = NO_FUNCTION, - .SetFunc = CommandSetTimeout, - .GetFunc = CommandGetTimeout + .SetFunc = CommandSetTimeout, + .GetFunc = CommandGetTimeout }, { - .Command = COMMAND_THRESHOLD, - .ExecFunc = NO_FUNCTION, + .Command = COMMAND_THRESHOLD, + .ExecFunc = NO_FUNCTION, .ExecParamFunc = NO_FUNCTION, - .SetFunc = CommandSetThreshold, - .GetFunc = CommandGetThreshold + .SetFunc = CommandSetThreshold, + .GetFunc = CommandGetThreshold }, { .Command = COMMAND_AUTOCALIBRATE, @@ -361,39 +361,39 @@ static CommandStatusIdType CallCommandFunc( char* pTerminalBuffer = (char*) TerminalBuffer; CommandStatusIdType Status = COMMAND_ERR_INVALID_USAGE_ID; - /* Call appropriate function depending on CommandDelimiter */ - if (CommandDelimiter == CHAR_GET_MODE) { - CommandGetFuncType GetFunc = pgm_read_ptr(&CommandEntry->GetFunc); - if (GetFunc != NO_FUNCTION) { - Status = GetFunc(pTerminalBuffer); - } - } else if (CommandDelimiter == CHAR_SET_MODE) { - CommandSetFuncType SetFunc = pgm_read_ptr(&CommandEntry->SetFunc); - if (SetFunc != NO_FUNCTION) { - Status = SetFunc(pTerminalBuffer, pParam); - } - } else if (CommandDelimiter == CHAR_EXEC_MODE) { - CommandExecFuncType ExecFunc = pgm_read_ptr(&CommandEntry->ExecFunc); - if (ExecFunc != NO_FUNCTION) { - Status = ExecFunc(pTerminalBuffer); - } - } else if (CommandDelimiter == CHAR_EXEC_MODE_PARAM) { - CommandExecParamFuncType ExecParamFunc = pgm_read_ptr(&CommandEntry->ExecParamFunc); - if (ExecParamFunc != NO_FUNCTION) { - Status = ExecParamFunc(pTerminalBuffer, pParam); - } - } else { - /* This should not happen (TM) */ - } + /* Call appropriate function depending on CommandDelimiter */ + if (CommandDelimiter == CHAR_GET_MODE) { + CommandGetFuncType GetFunc = pgm_read_ptr(&CommandEntry->GetFunc); + if (GetFunc != NO_FUNCTION) { + Status = GetFunc(pTerminalBuffer); + } + } else if (CommandDelimiter == CHAR_SET_MODE) { + CommandSetFuncType SetFunc = pgm_read_ptr(&CommandEntry->SetFunc); + if (SetFunc != NO_FUNCTION) { + Status = SetFunc(pTerminalBuffer, pParam); + } + } else if (CommandDelimiter == CHAR_EXEC_MODE) { + CommandExecFuncType ExecFunc = pgm_read_ptr(&CommandEntry->ExecFunc); + if (ExecFunc != NO_FUNCTION) { + Status = ExecFunc(pTerminalBuffer); + } + } else if (CommandDelimiter == CHAR_EXEC_MODE_PARAM) { + CommandExecParamFuncType ExecParamFunc = pgm_read_ptr(&CommandEntry->ExecParamFunc); + if (ExecParamFunc != NO_FUNCTION) { + Status = ExecParamFunc(pTerminalBuffer, pParam); + } + } else { + /* This should not happen (TM) */ + } - if (Status == TIMEOUT_COMMAND) - { - TaskPending = true; - TaskPendingSince = SystemGetSysTick(); - } + if (Status == TIMEOUT_COMMAND) + { + TaskPending = true; + TaskPendingSince = SystemGetSysTick(); + } - /* This delimiter has not been registered with this command */ - return Status; + /* This delimiter has not been registered with this command */ + return Status; } static void DecodeCommand(void) @@ -432,7 +432,7 @@ static void DecodeCommand(void) } if (StatusId == TIMEOUT_COMMAND) // it is a timeout command, so we return - return; + return; /* Send command status message */ TerminalSendStringP(GetStatusMessageP(StatusId)); @@ -451,83 +451,83 @@ void CommandLineInit(void) } bool CommandLineProcessByte(uint8_t Byte) { - if (IS_CHARACTER(Byte)) { - /* Store uppercase character */ - if (IS_LOWERCASE(Byte)) { - Byte = TO_UPPERCASE(Byte); - } + if (IS_CHARACTER(Byte)) { + /* Store uppercase character */ + if (IS_LOWERCASE(Byte)) { + Byte = TO_UPPERCASE(Byte); + } - /* Prevent buffer overflow and account for '\0' */ - if (BufferIdx < TERMINAL_BUFFER_SIZE - 1) { - TerminalBuffer[BufferIdx++] = Byte; - } - } else if (Byte == '\r') { - /* Process on \r. Terminate string and decode. */ - TerminalBuffer[BufferIdx] = '\0'; - BufferIdx = 0; + /* Prevent buffer overflow and account for '\0' */ + if (BufferIdx < TERMINAL_BUFFER_SIZE - 1) { + TerminalBuffer[BufferIdx++] = Byte; + } + } else if (Byte == '\r') { + /* Process on \r. Terminate string and decode. */ + TerminalBuffer[BufferIdx] = '\0'; + BufferIdx = 0; - if (!TaskPending) - DecodeCommand(); - } else if (Byte == '\b') { - /* Backspace. Delete last character in buffer. */ - if (BufferIdx > 0) { - BufferIdx--; - } - } else if (Byte == 0x1B) { - /* Drop buffer on escape */ - BufferIdx = 0; - } else { - /* Ignore other chars */ - } + if (!TaskPending) + DecodeCommand(); + } else if (Byte == '\b') { + /* Backspace. Delete last character in buffer. */ + if (BufferIdx > 0) { + BufferIdx--; + } + } else if (Byte == 0x1B) { + /* Drop buffer on escape */ + BufferIdx = 0; + } else { + /* Ignore other chars */ + } - return true; + return true; } INLINE void Timeout(void) { - TaskPending = false; - TerminalSendStringP(GetStatusMessageP(COMMAND_ERR_TIMEOUT_ID)); - TerminalSendStringP(PSTR(STATUS_MESSAGE_TRAILER)); + TaskPending = false; + TerminalSendStringP(GetStatusMessageP(COMMAND_ERR_TIMEOUT_ID)); + TerminalSendStringP(PSTR(STATUS_MESSAGE_TRAILER)); - if (CommandLinePendingTaskTimeout != NO_FUNCTION) - { - CommandLinePendingTaskTimeout(); // call the function that ends the task - CommandLinePendingTaskTimeout = NO_FUNCTION; - } + if (CommandLinePendingTaskTimeout != NO_FUNCTION) + { + CommandLinePendingTaskTimeout(); // call the function that ends the task + CommandLinePendingTaskTimeout = NO_FUNCTION; + } } void CommandLineTick(void) { - if (TaskPending && - GlobalSettings.ActiveSettingPtr->PendingTaskTimeout != 0 && // 0 means no timeout - SYSTICK_DIFF_100MS(TaskPendingSince) >= GlobalSettings.ActiveSettingPtr->PendingTaskTimeout) // timeout expired - { - Timeout(); - } + if (TaskPending && + GlobalSettings.ActiveSettingPtr->PendingTaskTimeout != 0 && // 0 means no timeout + SYSTICK_DIFF_100MS(TaskPendingSince) >= GlobalSettings.ActiveSettingPtr->PendingTaskTimeout) // timeout expired + { + Timeout(); + } } void CommandLinePendingTaskBreak(void) { - if (!TaskPending) - return; + if (!TaskPending) + return; - Timeout(); + Timeout(); } void CommandLinePendingTaskFinished(CommandStatusIdType ReturnStatusID, char const * const OutMessage) { - if (!TaskPending) // if no task is pending, no task can be finished - return; - TaskPending = false; + if (!TaskPending) // if no task is pending, no task can be finished + return; + TaskPending = false; - TerminalSendStringP(GetStatusMessageP(ReturnStatusID)); - TerminalSendStringP(PSTR(STATUS_MESSAGE_TRAILER)); + TerminalSendStringP(GetStatusMessageP(ReturnStatusID)); + TerminalSendStringP(PSTR(STATUS_MESSAGE_TRAILER)); - if (OutMessage != NULL) - { - TerminalSendString(OutMessage); - TerminalSendStringP(PSTR(OPTIONAL_ANSWER_TRAILER)); - } + if (OutMessage != NULL) + { + TerminalSendString(OutMessage); + TerminalSendStringP(PSTR(OPTIONAL_ANSWER_TRAILER)); + } } void CommandLineAppendData(void const * const Buffer, uint16_t Bytes) @@ -536,7 +536,7 @@ void CommandLineAppendData(void const * const Buffer, uint16_t Bytes) uint16_t tmpBytes = Bytes; if (Bytes > (TERMINAL_BUFFER_SIZE / 2)) - tmpBytes = TERMINAL_BUFFER_SIZE / 2; + tmpBytes = TERMINAL_BUFFER_SIZE / 2; Bytes -= tmpBytes; BufferToHexString(pTerminalBuffer, TERMINAL_BUFFER_SIZE, Buffer, tmpBytes); @@ -545,10 +545,10 @@ void CommandLineAppendData(void const * const Buffer, uint16_t Bytes) uint8_t i = 1; while (Bytes > (TERMINAL_BUFFER_SIZE / 2)) { - Bytes -= TERMINAL_BUFFER_SIZE / 2; + Bytes -= TERMINAL_BUFFER_SIZE / 2; BufferToHexString(pTerminalBuffer, TERMINAL_BUFFER_SIZE, Buffer + i * TERMINAL_BUFFER_SIZE / 2, TERMINAL_BUFFER_SIZE); TerminalSendString(pTerminalBuffer); - i++; + i++; } if (Bytes > 0) diff --git a/Firmware/Chameleon-Mini/Terminal/Commands.c b/Firmware/Chameleon-Mini/Terminal/Commands.c index efd5cf8..5eb60b6 100644 --- a/Firmware/Chameleon-Mini/Terminal/Commands.c +++ b/Firmware/Chameleon-Mini/Terminal/Commands.c @@ -38,15 +38,15 @@ CommandStatusIdType CommandGetConfig(char* OutParam) CommandStatusIdType CommandSetConfig(char* OutMessage, const char* InParam) { - if (COMMAND_IS_SUGGEST_STRING(InParam)) { - ConfigurationGetList(OutMessage, TERMINAL_BUFFER_SIZE); - return COMMAND_INFO_OK_WITH_TEXT_ID; - } else if (ConfigurationSetByName(InParam)) { - SettingsSave(); - return COMMAND_INFO_OK_ID; - } else { - return COMMAND_ERR_INVALID_PARAM_ID; - } + if (COMMAND_IS_SUGGEST_STRING(InParam)) { + ConfigurationGetList(OutMessage, TERMINAL_BUFFER_SIZE); + return COMMAND_INFO_OK_WITH_TEXT_ID; + } else if (ConfigurationSetByName(InParam)) { + SettingsSave(); + return COMMAND_INFO_OK_ID; + } else { + return COMMAND_ERR_INVALID_PARAM_ID; + } } CommandStatusIdType CommandGetUid(char* OutParam) @@ -56,8 +56,8 @@ CommandStatusIdType CommandGetUid(char* OutParam) if (UidSize == 0) { - snprintf_P(OutParam, TERMINAL_BUFFER_SIZE, PSTR("NO UID.")); - return COMMAND_INFO_OK_WITH_TEXT_ID; + snprintf_P(OutParam, TERMINAL_BUFFER_SIZE, PSTR("NO UID.")); + return COMMAND_INFO_OK_WITH_TEXT_ID; } ApplicationGetUid(UidBuffer); @@ -114,8 +114,8 @@ CommandStatusIdType CommandSetReadOnly(char* OutMessage, const char* InParam) ActiveConfiguration.ReadOnly = false; return COMMAND_INFO_OK_ID; } else if (InParam[0] == COMMAND_CHAR_SUGGEST) { - snprintf_P(OutMessage, TERMINAL_BUFFER_SIZE, PSTR("%c,%c"), COMMAND_CHAR_TRUE, COMMAND_CHAR_FALSE); - return COMMAND_INFO_OK_WITH_TEXT_ID; + snprintf_P(OutMessage, TERMINAL_BUFFER_SIZE, PSTR("%c,%c"), COMMAND_CHAR_TRUE, COMMAND_CHAR_FALSE); + return COMMAND_INFO_OK_WITH_TEXT_ID; } } @@ -179,12 +179,12 @@ CommandStatusIdType CommandGetRButton(char* OutParam) CommandStatusIdType CommandSetRButton(char* OutMessage, const char* InParam) { - if (COMMAND_IS_SUGGEST_STRING(InParam)) { - /* Get suggestion list */ - ButtonGetActionList(OutMessage, TERMINAL_BUFFER_SIZE); - return COMMAND_INFO_OK_WITH_TEXT_ID; - } else if (ButtonSetActionByName(BUTTON_R_PRESS_SHORT, InParam)) { - /* Try to set action name */ + if (COMMAND_IS_SUGGEST_STRING(InParam)) { + /* Get suggestion list */ + ButtonGetActionList(OutMessage, TERMINAL_BUFFER_SIZE); + return COMMAND_INFO_OK_WITH_TEXT_ID; + } else if (ButtonSetActionByName(BUTTON_R_PRESS_SHORT, InParam)) { + /* Try to set action name */ SettingsSave(); return COMMAND_INFO_OK_ID; } else { @@ -201,12 +201,12 @@ CommandStatusIdType CommandGetRButtonLong(char* OutParam) CommandStatusIdType CommandSetRButtonLong(char* OutMessage, const char* InParam) { - if (COMMAND_IS_SUGGEST_STRING(InParam)) { - /* Get suggestion list */ - ButtonGetActionList(OutMessage, TERMINAL_BUFFER_SIZE); - return COMMAND_INFO_OK_WITH_TEXT_ID; - } else if (ButtonSetActionByName(BUTTON_R_PRESS_LONG, InParam)) { - /* Try to set action name */ + if (COMMAND_IS_SUGGEST_STRING(InParam)) { + /* Get suggestion list */ + ButtonGetActionList(OutMessage, TERMINAL_BUFFER_SIZE); + return COMMAND_INFO_OK_WITH_TEXT_ID; + } else if (ButtonSetActionByName(BUTTON_R_PRESS_LONG, InParam)) { + /* Try to set action name */ SettingsSave(); return COMMAND_INFO_OK_ID; } else { @@ -223,12 +223,12 @@ CommandStatusIdType CommandGetLButton(char* OutParam) CommandStatusIdType CommandSetLButton(char* OutMessage, const char* InParam) { - if (COMMAND_IS_SUGGEST_STRING(InParam)) { - /* Get suggestion list */ - ButtonGetActionList(OutMessage, TERMINAL_BUFFER_SIZE); - return COMMAND_INFO_OK_WITH_TEXT_ID; - } else if (ButtonSetActionByName(BUTTON_L_PRESS_SHORT, InParam)) { - /* Try to set action name */ + if (COMMAND_IS_SUGGEST_STRING(InParam)) { + /* Get suggestion list */ + ButtonGetActionList(OutMessage, TERMINAL_BUFFER_SIZE); + return COMMAND_INFO_OK_WITH_TEXT_ID; + } else if (ButtonSetActionByName(BUTTON_L_PRESS_SHORT, InParam)) { + /* Try to set action name */ SettingsSave(); return COMMAND_INFO_OK_ID; } else { @@ -245,12 +245,12 @@ CommandStatusIdType CommandGetLButtonLong(char* OutParam) CommandStatusIdType CommandSetLButtonLong(char* OutMessage, const char* InParam) { - if (COMMAND_IS_SUGGEST_STRING(InParam)) { - /* Get suggestion list */ - ButtonGetActionList(OutMessage, TERMINAL_BUFFER_SIZE); - return COMMAND_INFO_OK_WITH_TEXT_ID; - } else if (ButtonSetActionByName(BUTTON_L_PRESS_LONG, InParam)) { - /* Try to set action name */ + if (COMMAND_IS_SUGGEST_STRING(InParam)) { + /* Get suggestion list */ + ButtonGetActionList(OutMessage, TERMINAL_BUFFER_SIZE); + return COMMAND_INFO_OK_WITH_TEXT_ID; + } else if (ButtonSetActionByName(BUTTON_L_PRESS_LONG, InParam)) { + /* Try to set action name */ SettingsSave(); return COMMAND_INFO_OK_ID; } else { @@ -260,42 +260,42 @@ CommandStatusIdType CommandSetLButtonLong(char* OutMessage, const char* InParam) CommandStatusIdType CommandGetLedGreen(char* OutParam) { - LEDGetFuncByName(LED_GREEN, OutParam, TERMINAL_BUFFER_SIZE); + LEDGetFuncByName(LED_GREEN, OutParam, TERMINAL_BUFFER_SIZE); - return COMMAND_INFO_OK_WITH_TEXT_ID; + return COMMAND_INFO_OK_WITH_TEXT_ID; } CommandStatusIdType CommandSetLedGreen(char* OutMessage, const char* InParam) { - if (COMMAND_IS_SUGGEST_STRING(InParam)) { - LEDGetFuncList(OutMessage, TERMINAL_BUFFER_SIZE); - return COMMAND_INFO_OK_WITH_TEXT_ID; - } else if (LEDSetFuncByName(LED_GREEN, InParam)) { - SettingsSave(); - return COMMAND_INFO_OK_ID; - } else { - return COMMAND_ERR_INVALID_PARAM_ID; - } + if (COMMAND_IS_SUGGEST_STRING(InParam)) { + LEDGetFuncList(OutMessage, TERMINAL_BUFFER_SIZE); + return COMMAND_INFO_OK_WITH_TEXT_ID; + } else if (LEDSetFuncByName(LED_GREEN, InParam)) { + SettingsSave(); + return COMMAND_INFO_OK_ID; + } else { + return COMMAND_ERR_INVALID_PARAM_ID; + } } CommandStatusIdType CommandGetLedRed(char* OutParam) { - LEDGetFuncByName(LED_RED, OutParam, TERMINAL_BUFFER_SIZE); + LEDGetFuncByName(LED_RED, OutParam, TERMINAL_BUFFER_SIZE); - return COMMAND_INFO_OK_WITH_TEXT_ID; + return COMMAND_INFO_OK_WITH_TEXT_ID; } CommandStatusIdType CommandSetLedRed(char* OutMessage, const char* InParam) { - if (COMMAND_IS_SUGGEST_STRING(InParam)) { - LEDGetFuncList(OutMessage, TERMINAL_BUFFER_SIZE); - return COMMAND_INFO_OK_WITH_TEXT_ID; - } else if (LEDSetFuncByName(LED_RED, InParam)) { - SettingsSave(); - return COMMAND_INFO_OK_ID; - } else { - return COMMAND_ERR_INVALID_PARAM_ID; - } + if (COMMAND_IS_SUGGEST_STRING(InParam)) { + LEDGetFuncList(OutMessage, TERMINAL_BUFFER_SIZE); + return COMMAND_INFO_OK_WITH_TEXT_ID; + } else if (LEDSetFuncByName(LED_RED, InParam)) { + SettingsSave(); + return COMMAND_INFO_OK_ID; + } else { + return COMMAND_ERR_INVALID_PARAM_ID; + } } CommandStatusIdType CommandGetLogMode(char* OutParam) @@ -308,10 +308,10 @@ CommandStatusIdType CommandGetLogMode(char* OutParam) CommandStatusIdType CommandSetLogMode(char* OutMessage, const char* InParam) { - if (COMMAND_IS_SUGGEST_STRING(InParam)) { - LogGetModeList(OutMessage, TERMINAL_BUFFER_SIZE); - return COMMAND_INFO_OK_WITH_TEXT_ID; - } else if (LogSetModeByName(InParam)) { + if (COMMAND_IS_SUGGEST_STRING(InParam)) { + LogGetModeList(OutMessage, TERMINAL_BUFFER_SIZE); + return COMMAND_INFO_OK_WITH_TEXT_ID; + } else if (LogSetModeByName(InParam)) { SettingsSave(); return COMMAND_INFO_OK_ID; } else { @@ -321,7 +321,7 @@ CommandStatusIdType CommandSetLogMode(char* OutMessage, const char* InParam) CommandStatusIdType CommandGetLogMem(char* OutParam) { - uint16_t free = LogMemFree(); + uint16_t free = LogMemFree(); snprintf_P(OutParam, TERMINAL_BUFFER_SIZE, PSTR("%u (from which %u non-volatile)"), free, (free <= LOG_SIZE) ? 0 : (free - LOG_SIZE)); @@ -338,8 +338,8 @@ CommandStatusIdType CommandExecLogDownload(char* OutMessage) CommandStatusIdType CommandExecStoreLog(char* OutMessage) { - LogSRAMToFRAM(); - return COMMAND_INFO_OK_ID; + LogSRAMToFRAM(); + return COMMAND_INFO_OK_ID; } CommandStatusIdType CommandExecLogClear(char* OutMessage) @@ -350,44 +350,44 @@ CommandStatusIdType CommandExecLogClear(char* OutMessage) CommandStatusIdType CommandGetSetting(char* OutParam) { - SettingsGetActiveByName(OutParam, TERMINAL_BUFFER_SIZE); - return COMMAND_INFO_OK_WITH_TEXT_ID; + SettingsGetActiveByName(OutParam, TERMINAL_BUFFER_SIZE); + return COMMAND_INFO_OK_WITH_TEXT_ID; } CommandStatusIdType CommandSetSetting(char* OutMessage, const char* InParam) { - if (SettingsSetActiveByName(InParam)) { - return COMMAND_INFO_OK_ID; - } else { - return COMMAND_ERR_INVALID_PARAM_ID; - } + if (SettingsSetActiveByName(InParam)) { + return COMMAND_INFO_OK_ID; + } else { + return COMMAND_ERR_INVALID_PARAM_ID; + } } CommandStatusIdType CommandExecClear(char* OutMessage) { - MemoryClear(); - return COMMAND_INFO_OK_ID; + MemoryClear(); + return COMMAND_INFO_OK_ID; } CommandStatusIdType CommandExecStore(char* OutMessage) { - MemoryStore(); - return COMMAND_INFO_OK_ID; + MemoryStore(); + return COMMAND_INFO_OK_ID; } CommandStatusIdType CommandExecRecall(char* OutMessage) { - MemoryRecall(); - return COMMAND_INFO_OK_ID; + MemoryRecall(); + return COMMAND_INFO_OK_ID; } CommandStatusIdType CommandGetCharging(char* OutMessage) { - if (BatteryIsCharging()) { - return COMMAND_INFO_TRUE_ID; - } else { - return COMMAND_INFO_FALSE_ID; - } + if (BatteryIsCharging()) { + return COMMAND_INFO_TRUE_ID; + } else { + return COMMAND_INFO_FALSE_ID; + } } CommandStatusIdType CommandExecHelp(char* OutMessage) @@ -426,202 +426,202 @@ CommandStatusIdType CommandGetRssi(char* OutParam) CommandStatusIdType CommandGetSysTick(char* OutParam) { - snprintf_P(OutParam, TERMINAL_BUFFER_SIZE, PSTR("%4.4X"), SystemGetSysTick()); + snprintf_P(OutParam, TERMINAL_BUFFER_SIZE, PSTR("%4.4X"), SystemGetSysTick()); - return COMMAND_INFO_OK_WITH_TEXT_ID; + return COMMAND_INFO_OK_WITH_TEXT_ID; } CommandStatusIdType CommandExecParamSend(char* OutMessage, const char* InParams) { - if (GlobalSettings.ActiveSettingPtr->Configuration != CONFIG_ISO14443A_READER) - return COMMAND_ERR_INVALID_USAGE_ID; + if (GlobalSettings.ActiveSettingPtr->Configuration != CONFIG_ISO14443A_READER) + return COMMAND_ERR_INVALID_USAGE_ID; - ApplicationReset(); - Reader14443CurrentCommand = Reader14443_Send; + ApplicationReset(); + Reader14443CurrentCommand = Reader14443_Send; - char const * paramTwo = strchr(InParams, ' '); - uint16_t length; - if (paramTwo == NULL) // this means, we have to calculate the length - { - length = strlen(InParams); - if (length&1) // return error when length is odd - return COMMAND_ERR_INVALID_PARAM_ID; - length /= 2; - if (length == 1) - { - ReaderSendBitCount = 7; // this is a short frame - } else { - ReaderSendBitCount = length * 8; - } - } else if(paramTwo == (InParams+4)) { // we have a bitcount prepended - uint8_t tmp[2]; - HexStringToBuffer(tmp, 2, InParams); - ReaderSendBitCount = (tmp[0]<<8) + tmp[1]; // set our BitCount to the given value - InParams = ++paramTwo; // set InParams to the beginning of the second parameter - length = strlen(InParams); - if ((length&1) || (length / 2 * 8) < ReaderSendBitCount) // this parameter is malformed, if it is odd or if there are less bits than the BitCount indicates - return COMMAND_ERR_INVALID_PARAM_ID; - } else { // any other case means we have malformed parameters - return COMMAND_ERR_INVALID_PARAM_ID; - } + char const * paramTwo = strchr(InParams, ' '); + uint16_t length; + if (paramTwo == NULL) // this means, we have to calculate the length + { + length = strlen(InParams); + if (length&1) // return error when length is odd + return COMMAND_ERR_INVALID_PARAM_ID; + length /= 2; + if (length == 1) + { + ReaderSendBitCount = 7; // this is a short frame + } else { + ReaderSendBitCount = length * 8; + } + } else if(paramTwo == (InParams+4)) { // we have a bitcount prepended + uint8_t tmp[2]; + HexStringToBuffer(tmp, 2, InParams); + ReaderSendBitCount = (tmp[0]<<8) + tmp[1]; // set our BitCount to the given value + InParams = ++paramTwo; // set InParams to the beginning of the second parameter + length = strlen(InParams); + if ((length&1) || (length / 2 * 8) < ReaderSendBitCount) // this parameter is malformed, if it is odd or if there are less bits than the BitCount indicates + return COMMAND_ERR_INVALID_PARAM_ID; + } else { // any other case means we have malformed parameters + return COMMAND_ERR_INVALID_PARAM_ID; + } - HexStringToBuffer(ReaderSendBuffer, (ReaderSendBitCount+7)/8, InParams); + HexStringToBuffer(ReaderSendBuffer, (ReaderSendBitCount+7)/8, InParams); - Reader14443ACodecStart(); + Reader14443ACodecStart(); - return TIMEOUT_COMMAND; + return TIMEOUT_COMMAND; } CommandStatusIdType CommandExecParamSendRaw(char* OutMessage, const char* InParams) { - if (GlobalSettings.ActiveSettingPtr->Configuration != CONFIG_ISO14443A_READER) - return COMMAND_ERR_INVALID_USAGE_ID; + if (GlobalSettings.ActiveSettingPtr->Configuration != CONFIG_ISO14443A_READER) + return COMMAND_ERR_INVALID_USAGE_ID; - ApplicationReset(); - Reader14443CurrentCommand = Reader14443_Send_Raw; + ApplicationReset(); + Reader14443CurrentCommand = Reader14443_Send_Raw; - char const * paramTwo = strchr(InParams, ' '); - uint16_t length; - if (paramTwo == NULL) // this means, we have to calculate the length - { - length = strlen(InParams); - if (length&1) // return error when length is odd - return COMMAND_ERR_INVALID_PARAM_ID; - length /= 2; - if (length == 1) - { - ReaderSendBitCount = 7; // this is a short frame - } else { - length *= 8; - ReaderSendBitCount = length - (length % 9); // how many bytes+paritybit match into our input? - } - } else if(paramTwo == (InParams+4)) { // we have a bitcount prepended - uint8_t tmp[2]; - HexStringToBuffer(tmp, 2, InParams); - ReaderSendBitCount = (tmp[0]<<8) + tmp[1]; // set our BitCount to the given value - if (ReaderSendBitCount != 7 && (ReaderSendBitCount % 8)) // since we have to add parity bits here (in case this is not a short frame), the number of bits to be sent has to be a multiple of 8 - return COMMAND_ERR_INVALID_PARAM_ID; - InParams = ++paramTwo; // set InParams to the beginning of the second parameter - length = strlen(InParams); - if ((length&1) || (length / 2 * 8) < ReaderSendBitCount) // this parameter is malformed, if it is odd or if there are less bits than the BitCount indicates - return COMMAND_ERR_INVALID_PARAM_ID; - } else { // any other case means we have malformed parameters - return COMMAND_ERR_INVALID_PARAM_ID; - } + char const * paramTwo = strchr(InParams, ' '); + uint16_t length; + if (paramTwo == NULL) // this means, we have to calculate the length + { + length = strlen(InParams); + if (length&1) // return error when length is odd + return COMMAND_ERR_INVALID_PARAM_ID; + length /= 2; + if (length == 1) + { + ReaderSendBitCount = 7; // this is a short frame + } else { + length *= 8; + ReaderSendBitCount = length - (length % 9); // how many bytes+paritybit match into our input? + } + } else if(paramTwo == (InParams+4)) { // we have a bitcount prepended + uint8_t tmp[2]; + HexStringToBuffer(tmp, 2, InParams); + ReaderSendBitCount = (tmp[0]<<8) + tmp[1]; // set our BitCount to the given value + if (ReaderSendBitCount != 7 && (ReaderSendBitCount % 8)) // since we have to add parity bits here (in case this is not a short frame), the number of bits to be sent has to be a multiple of 8 + return COMMAND_ERR_INVALID_PARAM_ID; + InParams = ++paramTwo; // set InParams to the beginning of the second parameter + length = strlen(InParams); + if ((length&1) || (length / 2 * 8) < ReaderSendBitCount) // this parameter is malformed, if it is odd or if there are less bits than the BitCount indicates + return COMMAND_ERR_INVALID_PARAM_ID; + } else { // any other case means we have malformed parameters + return COMMAND_ERR_INVALID_PARAM_ID; + } - HexStringToBuffer(ReaderSendBuffer, (ReaderSendBitCount+7)/8, InParams); + HexStringToBuffer(ReaderSendBuffer, (ReaderSendBitCount+7)/8, InParams); - Reader14443ACodecStart(); + Reader14443ACodecStart(); - return TIMEOUT_COMMAND; + return TIMEOUT_COMMAND; } CommandStatusIdType CommandExecDumpMFU(char* OutMessage) { - if (GlobalSettings.ActiveSettingPtr->Configuration != CONFIG_ISO14443A_READER) - return COMMAND_ERR_INVALID_USAGE_ID; - ApplicationReset(); + if (GlobalSettings.ActiveSettingPtr->Configuration != CONFIG_ISO14443A_READER) + return COMMAND_ERR_INVALID_USAGE_ID; + ApplicationReset(); - Reader14443CurrentCommand = Reader14443_Read_MF_Ultralight; - Reader14443AAppInit(); - Reader14443ACodecStart(); - CommandLinePendingTaskTimeout = &Reader14443AAppTimeout; - return TIMEOUT_COMMAND; + Reader14443CurrentCommand = Reader14443_Read_MF_Ultralight; + Reader14443AAppInit(); + Reader14443ACodecStart(); + CommandLinePendingTaskTimeout = &Reader14443AAppTimeout; + return TIMEOUT_COMMAND; } CommandStatusIdType CommandExecGetUid(char* OutMessage) // this function is for reading the uid in reader mode { - if (GlobalSettings.ActiveSettingPtr->Configuration != CONFIG_ISO14443A_READER) - return COMMAND_ERR_INVALID_USAGE_ID; - ApplicationReset(); + if (GlobalSettings.ActiveSettingPtr->Configuration != CONFIG_ISO14443A_READER) + return COMMAND_ERR_INVALID_USAGE_ID; + ApplicationReset(); - Reader14443CurrentCommand = Reader14443_Get_UID; - Reader14443AAppInit(); - Reader14443ACodecStart(); - CommandLinePendingTaskTimeout = &Reader14443AAppTimeout; - return TIMEOUT_COMMAND; + Reader14443CurrentCommand = Reader14443_Get_UID; + Reader14443AAppInit(); + Reader14443ACodecStart(); + CommandLinePendingTaskTimeout = &Reader14443AAppTimeout; + return TIMEOUT_COMMAND; } CommandStatusIdType CommandExecIdentifyCard(char* OutMessage) { - if (GlobalSettings.ActiveSettingPtr->Configuration != CONFIG_ISO14443A_READER) - return COMMAND_ERR_INVALID_USAGE_ID; - ApplicationReset(); + if (GlobalSettings.ActiveSettingPtr->Configuration != CONFIG_ISO14443A_READER) + return COMMAND_ERR_INVALID_USAGE_ID; + ApplicationReset(); - Reader14443CurrentCommand = Reader14443_Identify; - Reader14443AAppInit(); - Reader14443ACodecStart(); - CommandLinePendingTaskTimeout = &Reader14443AAppTimeout; - return TIMEOUT_COMMAND; + Reader14443CurrentCommand = Reader14443_Identify; + Reader14443AAppInit(); + Reader14443ACodecStart(); + CommandLinePendingTaskTimeout = &Reader14443AAppTimeout; + return TIMEOUT_COMMAND; } CommandStatusIdType CommandGetTimeout(char* OutParam) { - snprintf_P(OutParam, TERMINAL_BUFFER_SIZE, PSTR("%u ms"), GlobalSettings.ActiveSettingPtr->PendingTaskTimeout * 100); - return COMMAND_INFO_OK_WITH_TEXT_ID; + snprintf_P(OutParam, TERMINAL_BUFFER_SIZE, PSTR("%u ms"), GlobalSettings.ActiveSettingPtr->PendingTaskTimeout * 100); + return COMMAND_INFO_OK_WITH_TEXT_ID; } CommandStatusIdType CommandSetTimeout(char* OutMessage, const char* InParam) { - if (COMMAND_IS_SUGGEST_STRING(InParam)) - { - snprintf_P(OutMessage, TERMINAL_BUFFER_SIZE, PSTR("0 = no timeout\r\n1-600 = 100 ms - 60000 ms timeout")); - return COMMAND_INFO_OK_WITH_TEXT_ID; - } - uint16_t tmp = 601; - if (!sscanf_P(InParam, PSTR("%5d"), &tmp) || tmp > 600) - return COMMAND_ERR_INVALID_PARAM_ID; - GlobalSettings.ActiveSettingPtr->PendingTaskTimeout = tmp; - return COMMAND_INFO_OK_ID; + if (COMMAND_IS_SUGGEST_STRING(InParam)) + { + snprintf_P(OutMessage, TERMINAL_BUFFER_SIZE, PSTR("0 = no timeout\r\n1-600 = 100 ms - 60000 ms timeout")); + return COMMAND_INFO_OK_WITH_TEXT_ID; + } + uint16_t tmp = 601; + if (!sscanf_P(InParam, PSTR("%5d"), &tmp) || tmp > 600) + return COMMAND_ERR_INVALID_PARAM_ID; + GlobalSettings.ActiveSettingPtr->PendingTaskTimeout = tmp; + return COMMAND_INFO_OK_ID; } CommandStatusIdType CommandGetThreshold(char* OutParam) { - snprintf_P(OutParam, TERMINAL_BUFFER_SIZE, PSTR("%u"), ReaderThreshold); - return COMMAND_INFO_OK_WITH_TEXT_ID; + snprintf_P(OutParam, TERMINAL_BUFFER_SIZE, PSTR("%u"), ReaderThreshold); + return COMMAND_INFO_OK_WITH_TEXT_ID; } CommandStatusIdType CommandSetThreshold(char* OutMessage, const char* InParam) { - if (COMMAND_IS_SUGGEST_STRING(InParam)) - { - snprintf_P(OutMessage, TERMINAL_BUFFER_SIZE, PSTR("Any integer from 0 to %u. Reference voltage will be (VCC * THRESHOLD / 4095) mV."), CODEC_MAXIMUM_THRESHOLD); - return COMMAND_INFO_OK_WITH_TEXT_ID; - } - uint16_t tmp = 0; - if (!sscanf_P(InParam, PSTR("%5d"), &tmp) || tmp > CODEC_MAXIMUM_THRESHOLD) - return COMMAND_ERR_INVALID_PARAM_ID; - DACB.CH0DATA = tmp; - ReaderThreshold = tmp; - return COMMAND_INFO_OK_ID; + if (COMMAND_IS_SUGGEST_STRING(InParam)) + { + snprintf_P(OutMessage, TERMINAL_BUFFER_SIZE, PSTR("Any integer from 0 to %u. Reference voltage will be (VCC * THRESHOLD / 4095) mV."), CODEC_MAXIMUM_THRESHOLD); + return COMMAND_INFO_OK_WITH_TEXT_ID; + } + uint16_t tmp = 0; + if (!sscanf_P(InParam, PSTR("%5d"), &tmp) || tmp > CODEC_MAXIMUM_THRESHOLD) + return COMMAND_ERR_INVALID_PARAM_ID; + DACB.CH0DATA = tmp; + ReaderThreshold = tmp; + return COMMAND_INFO_OK_ID; } CommandStatusIdType CommandSetField(char* OutMessage, const char* InParam) { - if (COMMAND_IS_SUGGEST_STRING(InParam)) - { - snprintf_P(OutMessage, TERMINAL_BUFFER_SIZE, PSTR("%c,%c"), COMMAND_CHAR_TRUE, COMMAND_CHAR_FALSE); - return COMMAND_INFO_OK_WITH_TEXT_ID; - } - if (InParam[0] == COMMAND_CHAR_TRUE) - { - CodecReaderFieldStart(); - } else if(InParam[0] == COMMAND_CHAR_FALSE) { - CodecReaderFieldStop(); - } else { - return COMMAND_ERR_INVALID_PARAM_ID; - } - return COMMAND_INFO_OK_ID; + if (COMMAND_IS_SUGGEST_STRING(InParam)) + { + snprintf_P(OutMessage, TERMINAL_BUFFER_SIZE, PSTR("%c,%c"), COMMAND_CHAR_TRUE, COMMAND_CHAR_FALSE); + return COMMAND_INFO_OK_WITH_TEXT_ID; + } + if (InParam[0] == COMMAND_CHAR_TRUE) + { + CodecReaderFieldStart(); + } else if(InParam[0] == COMMAND_CHAR_FALSE) { + CodecReaderFieldStop(); + } else { + return COMMAND_ERR_INVALID_PARAM_ID; + } + return COMMAND_INFO_OK_ID; } CommandStatusIdType CommandGetField(char* OutMessage) { - if (CodecGetReaderField()) - OutMessage[0] = COMMAND_CHAR_TRUE; - else - OutMessage[0] = COMMAND_CHAR_FALSE; - OutMessage[1] = '\0'; - return COMMAND_INFO_OK_WITH_TEXT_ID; + if (CodecGetReaderField()) + OutMessage[0] = COMMAND_CHAR_TRUE; + else + OutMessage[0] = COMMAND_CHAR_FALSE; + OutMessage[1] = '\0'; + return COMMAND_INFO_OK_WITH_TEXT_ID; } diff --git a/Firmware/Chameleon-Mini/Terminal/Terminal.c b/Firmware/Chameleon-Mini/Terminal/Terminal.c index 9b77998..dfb15ca 100644 --- a/Firmware/Chameleon-Mini/Terminal/Terminal.c +++ b/Firmware/Chameleon-Mini/Terminal/Terminal.c @@ -32,7 +32,7 @@ TerminalStateEnum TerminalState = TERMINAL_UNINITIALIZED; static uint8_t TerminalInitDelay = INIT_DELAY; void TerminalSendString(const char* s) { - CDC_Device_SendString(&TerminalHandle, s); + CDC_Device_SendString(&TerminalHandle, s); } void TerminalSendStringP(const char* s) { @@ -67,7 +67,7 @@ static void ProcessByte(void) { if (Byte >= 0) { /* Byte received */ - LEDHook(LED_TERMINAL_RXTX, LED_PULSE); + LEDHook(LED_TERMINAL_RXTX, LED_PULSE); if (XModemProcessByte(Byte)) { /* XModem handled the byte */ @@ -81,39 +81,39 @@ static void SenseVBus(void) { switch(TerminalState) { case TERMINAL_UNINITIALIZED: - if (TERMINAL_VBUS_PORT.IN & TERMINAL_VBUS_MASK) { - /* Not initialized and VBUS sense high */ - TerminalInitDelay = INIT_DELAY; - TerminalState = TERMINAL_INITIALIZING; - } + if (TERMINAL_VBUS_PORT.IN & TERMINAL_VBUS_MASK) { + /* Not initialized and VBUS sense high */ + TerminalInitDelay = INIT_DELAY; + TerminalState = TERMINAL_INITIALIZING; + } break; case TERMINAL_INITIALIZING: - if (--TerminalInitDelay == 0) { + if (--TerminalInitDelay == 0) { SystemStartUSBClock(); USB_Init(); TerminalState = TERMINAL_INITIALIZED; - } - break; + } + break; case TERMINAL_INITIALIZED: - if (!(TERMINAL_VBUS_PORT.IN & TERMINAL_VBUS_MASK)) { - /* Initialized and VBUS sense low */ - TerminalInitDelay = INIT_DELAY; - TerminalState = TERMINAL_UNITIALIZING; - } - break; + if (!(TERMINAL_VBUS_PORT.IN & TERMINAL_VBUS_MASK)) { + /* Initialized and VBUS sense low */ + TerminalInitDelay = INIT_DELAY; + TerminalState = TERMINAL_UNITIALIZING; + } + break; case TERMINAL_UNITIALIZING: - if (--TerminalInitDelay == 0) { - USB_Disable(); - SystemStopUSBClock(); - TerminalState = TERMINAL_UNINITIALIZED; - } - break; + if (--TerminalInitDelay == 0) { + USB_Disable(); + SystemStopUSBClock(); + TerminalState = TERMINAL_UNINITIALIZED; + } + break; default: - break; + break; } } @@ -124,34 +124,34 @@ void TerminalInit(void) void TerminalTask(void) { - if (TerminalState == TERMINAL_INITIALIZED) { - CDC_Device_USBTask(&TerminalHandle); - USB_USBTask(); + if (TerminalState == TERMINAL_INITIALIZED) { + CDC_Device_USBTask(&TerminalHandle); + USB_USBTask(); - ProcessByte(); - } + ProcessByte(); + } } void TerminalTick(void) { - SenseVBus(); + SenseVBus(); - if (TerminalState == TERMINAL_INITIALIZED) { - XModemTick(); - CommandLineTick(); - } + if (TerminalState == TERMINAL_INITIALIZED) { + XModemTick(); + CommandLineTick(); + } } /** Event handler for the library USB Connection event. */ void EVENT_USB_Device_Connect(void) { - LEDHook(LED_TERMINAL_CONN, LED_ON); + LEDHook(LED_TERMINAL_CONN, LED_ON); } /** Event handler for the library USB Disconnection event. */ void EVENT_USB_Device_Disconnect(void) { - LEDHook(LED_TERMINAL_CONN, LED_OFF); + LEDHook(LED_TERMINAL_CONN, LED_OFF); } diff --git a/Firmware/Chameleon-Mini/Terminal/Terminal.h b/Firmware/Chameleon-Mini/Terminal/Terminal.h index 47e4069..06194a5 100644 --- a/Firmware/Chameleon-Mini/Terminal/Terminal.h +++ b/Firmware/Chameleon-Mini/Terminal/Terminal.h @@ -19,10 +19,10 @@ #define TERMINAL_BUFFER_SIZE 512 typedef enum { - TERMINAL_UNINITIALIZED, - TERMINAL_INITIALIZING, - TERMINAL_INITIALIZED, - TERMINAL_UNITIALIZING + TERMINAL_UNINITIALIZED, + TERMINAL_INITIALIZING, + TERMINAL_INITIALIZED, + TERMINAL_UNITIALIZING } TerminalStateEnum; extern uint8_t TerminalBuffer[TERMINAL_BUFFER_SIZE]; diff --git a/Firmware/Chameleon-Mini/Terminal/XModem.c b/Firmware/Chameleon-Mini/Terminal/XModem.c index 6ea379f..8881525 100644 --- a/Firmware/Chameleon-Mini/Terminal/XModem.c +++ b/Firmware/Chameleon-Mini/Terminal/XModem.c @@ -165,7 +165,7 @@ bool XModemProcessByte(uint8_t Byte) CurrentFrameNumber = FIRST_FRAME_NUMBER - 1; Byte = BYTE_ACK; } else if (Byte == BYTE_ESC) { - State = STATE_OFF; + State = STATE_OFF; } /* Fallthrough */