Added {} to control structures for clarity (#600)

This commit is contained in:
Thomas Mørch
2016-10-16 12:46:42 +02:00
committed by Olivier
parent 80659ddb00
commit 54776a4520
34 changed files with 740 additions and 406 deletions
+30 -22
View File
@@ -36,13 +36,13 @@
/* This version derived by Mark Tillotson 2012-01-23, tidied up, slimmed down
and tailored to 8-bit microcontroller abilities and Arduino datatypes.
The s-box and inverse s-box were retained as tables (0.5kB PROGMEM) but all
the other transformations are coded to save table space. Many efficiency
The s-box and inverse s-box were retained as tables (0.5kB PROGMEM) but all
the other transformations are coded to save table space. Many efficiency
improvments to the routines mix_sub_columns() and inv_mix_sub_columns()
(mainly common sub-expression elimination).
Only the routines with precalculated subkey schedule are retained (together
with set_key() - this does however mean each AES object takes 240 bytes of
with set_key() - this does however mean each AES object takes 240 bytes of
RAM, alas)
The CBC routines side-effect the iv argument (so that successive calls work
@@ -218,7 +218,7 @@ static void inv_mix_sub_columns (byte dt[N_BLOCK], byte st[N_BLOCK])
byte a8 = f2(a4), b8 = f2(b4), c8 = f2(c4), d8 = f2(d4) ;
byte a9 = a8 ^ a1,b9 = b8 ^ b1,c9 = c8 ^ c1,d9 = d8 ^ d1 ;
byte ac = a8 ^ a4,bc = b8 ^ b4,cc = c8 ^ c4,dc = d8 ^ d4 ;
dt[i] = is_box (ac^a2 ^ b9^b2 ^ cc^c1 ^ d9) ;
dt[(i+5)&15] = is_box (a9 ^ bc^b2 ^ c9^c2 ^ dc^d1) ;
dt[(i+10)&15] = is_box (ac^a1 ^ b9 ^ cc^c2 ^ d9^d2) ;
@@ -257,32 +257,33 @@ byte AES::set_key (byte key [], int keylen)
switch (keylen)
{
case 16:
case 128:
case 128:
keylen = 16; // 10 rounds
round = 10 ;
break;
case 24:
case 192:
case 192:
keylen = 24; // 12 rounds
round = 12 ;
break;
case 32:
case 256:
case 256:
keylen = 32; // 14 rounds
round = 14 ;
break;
default:
round = 0;
default:
round = 0;
return AES_FAILURE;
}
hi = (round + 1) << 4 ;
copy_n_bytes (key_sched, key, keylen) ;
byte t[4] ;
byte next = keylen ;
for (byte cc = keylen, rc = 1 ; cc < hi ; cc += N_COL)
for (byte cc = keylen, rc = 1 ; cc < hi ; cc += N_COL)
{
for (byte i = 0 ; i < N_COL ; i++)
for (byte i = 0 ; i < N_COL ; i++) {
t[i] = key_sched [cc-4+i] ;
}
if (cc == next)
{
next += keylen ;
@@ -295,12 +296,14 @@ byte AES::set_key (byte key [], int keylen)
}
else if (keylen == 32 && (cc & 31) == 16)
{
for (byte i = 0 ; i < 4 ; i++)
for (byte i = 0 ; i < 4 ; i++) {
t[i] = s_box (t[i]) ;
}
}
byte tt = cc - keylen ;
for (byte i = 0 ; i < N_COL ; i++)
for (byte i = 0 ; i < N_COL ; i++) {
key_sched [cc + i] = key_sched [tt + i] ^ t[i] ;
}
}
return AES_SUCCESS ;
}
@@ -309,8 +312,9 @@ byte AES::set_key (byte key [], int keylen)
void AES::clean ()
{
for (byte i = 0 ; i < KEY_SCHEDULE_BYTES ; i++)
for (byte i = 0 ; i < KEY_SCHEDULE_BYTES ; i++) {
key_sched [i] = 0 ;
}
round = 0 ;
}
@@ -340,7 +344,7 @@ byte AES::encrypt (byte plain [N_BLOCK], byte cipher [N_BLOCK])
copy_and_key (s1, plain, (byte*) (key_sched)) ;
for (r = 1 ; r < round ; r++)
{
{
byte s2 [N_BLOCK] ;
mix_sub_columns (s2, s1) ;
copy_and_key (s1, s2, (byte*) (key_sched + r * N_BLOCK)) ;
@@ -360,8 +364,9 @@ byte AES::cbc_encrypt (byte * plain, byte * cipher, int n_block, byte iv [N_BLOC
while (n_block--)
{
xor_block (iv, plain) ;
if (encrypt (iv, iv) != AES_SUCCESS)
if (encrypt (iv, iv) != AES_SUCCESS) {
return AES_FAILURE ;
}
copy_n_bytes (cipher, iv, N_BLOCK) ;
plain += N_BLOCK ;
cipher += N_BLOCK ;
@@ -376,8 +381,9 @@ byte AES::cbc_encrypt (byte * plain, byte * cipher, int n_block)
while (n_block--)
{
xor_block (iv, plain) ;
if (encrypt (iv, iv) != AES_SUCCESS)
if (encrypt (iv, iv) != AES_SUCCESS) {
return AES_FAILURE ;
}
copy_n_bytes (cipher, iv, N_BLOCK) ;
plain += N_BLOCK ;
cipher += N_BLOCK ;
@@ -411,13 +417,14 @@ byte AES::decrypt (byte plain [N_BLOCK], byte cipher [N_BLOCK])
/******************************************************************************/
byte AES::cbc_decrypt (byte * cipher, byte * plain, int n_block, byte iv [N_BLOCK])
{
{
while (n_block--)
{
byte tmp [N_BLOCK] ;
copy_n_bytes (tmp, cipher, N_BLOCK) ;
if (decrypt (cipher, plain) != AES_SUCCESS)
if (decrypt (cipher, plain) != AES_SUCCESS) {
return AES_FAILURE ;
}
xor_block (plain, iv) ;
copy_n_bytes (iv, tmp, N_BLOCK) ;
plain += N_BLOCK ;
@@ -429,13 +436,14 @@ byte AES::cbc_decrypt (byte * cipher, byte * plain, int n_block, byte iv [N_BLOC
/******************************************************************************/
byte AES::cbc_decrypt (byte * cipher, byte * plain, int n_block)
{
{
while (n_block--)
{
byte tmp [N_BLOCK] ;
copy_n_bytes (tmp, cipher, N_BLOCK) ;
if (decrypt (cipher, plain) != AES_SUCCESS)
if (decrypt (cipher, plain) != AES_SUCCESS) {
return AES_FAILURE ;
}
xor_block (plain, iv) ;
copy_n_bytes (iv, tmp, N_BLOCK) ;
plain += N_BLOCK ;
@@ -505,7 +513,7 @@ void AES::padPlaintext(void* in,byte* out)
/******************************************************************************/
bool AES::CheckPad(byte* in,int lsize){
if (in[lsize-1] <= 0x0f){
if (in[lsize-1] <= 0x0f){
int lpad = (int)in[lsize-1];
for (int i = lsize - 1; i >= lsize-lpad; i--){
if (arr_pad[lpad - 1] != in[i]){
+75 -40
View File
@@ -24,10 +24,12 @@ static void swi_set_signal_pin(uint8_t is_high)
{
SHA204_SET_OUTPUT();
if (is_high)
SHA204_POUT_HIGH();
else
SHA204_POUT_LOW();
if (is_high) {
SHA204_POUT_HIGH();
}
else {
SHA204_POUT_LOW();
}
}
static uint8_t swi_send_bytes(uint8_t count, uint8_t *buffer)
@@ -109,8 +111,9 @@ static uint8_t swi_receive_bytes(uint8_t count, uint8_t *buffer)
while (--timeout_count > 0)
{
// Wait for falling edge.
if (SHA204_PIN_READ() == 0)
if (SHA204_PIN_READ() == 0) {
break;
}
}
if (timeout_count == 0)
@@ -159,8 +162,9 @@ static uint8_t swi_receive_bytes(uint8_t count, uint8_t *buffer)
{
do
{
if (SHA204_PIN_READ() != 0)
if (SHA204_PIN_READ() != 0) {
break;
}
} while (timeout_count-- > 0);
}
@@ -169,16 +173,18 @@ static uint8_t swi_receive_bytes(uint8_t count, uint8_t *buffer)
buffer[i] |= bit_mask; // received "one" bit
}
if (status != SWI_FUNCTION_RETCODE_SUCCESS)
if (status != SWI_FUNCTION_RETCODE_SUCCESS) {
break;
}
}
interrupts(); //swi_enable_interrupts();
if (status == SWI_FUNCTION_RETCODE_TIMEOUT)
{
if (i > 0)
// Indicate that we timed out after having received at least one byte.
status = SWI_FUNCTION_RETCODE_RX_FAIL;
if (i > 0) {
// Indicate that we timed out after having received at least one byte.
status = SWI_FUNCTION_RETCODE_RX_FAIL;
}
}
return status;
}
@@ -191,8 +197,9 @@ static uint8_t sha204p_receive_response(uint8_t size, uint8_t *response)
uint8_t i;
uint8_t ret_code;
for (i = 0; i < size; i++)
for (i = 0; i < size; i++) {
response[i] = 0;
}
(void) swi_send_byte(SHA204_SWI_FLAG_TX);
@@ -200,8 +207,9 @@ static uint8_t sha204p_receive_response(uint8_t size, uint8_t *response)
if (ret_code == SWI_FUNCTION_RETCODE_SUCCESS || ret_code == SWI_FUNCTION_RETCODE_RX_FAIL)
{
count_byte = response[SHA204_BUFFER_POS_COUNT];
if ((count_byte < SHA204_RSP_SIZE_MIN) || (count_byte > size))
if ((count_byte < SHA204_RSP_SIZE_MIN) || (count_byte > size)) {
return SHA204_INVALID_SIZE;
}
return SHA204_SUCCESS;
}
@@ -209,10 +217,12 @@ static uint8_t sha204p_receive_response(uint8_t size, uint8_t *response)
// Translate error so that the Communication layer
// can distinguish between a real error or the
// device being busy executing a command.
if (ret_code == SWI_FUNCTION_RETCODE_TIMEOUT)
if (ret_code == SWI_FUNCTION_RETCODE_TIMEOUT) {
return SHA204_RX_NO_RESPONSE;
else
}
else {
return SHA204_RX_FAIL;
}
}
/* Communication functions */
@@ -223,8 +233,9 @@ static uint8_t sha204c_resync(uint8_t size, uint8_t *response)
// (step 1 of the re-synchronization process).
delay(SHA204_SYNC_TIMEOUT);
uint8_t ret_code = sha204p_receive_response(size, response);
if (ret_code == SHA204_SUCCESS)
if (ret_code == SHA204_SUCCESS) {
return ret_code;
}
// We lost communication. Send a Wake pulse and try
// to receive a response (steps 2 and 3 of the
@@ -261,17 +272,21 @@ static uint8_t sha204c_send_and_receive(uint8_t *tx_buffer, uint8_t rx_size, uin
{
// Send command.
ret_code = swi_send_byte(SHA204_SWI_FLAG_CMD);
if (ret_code != SWI_FUNCTION_RETCODE_SUCCESS)
if (ret_code != SWI_FUNCTION_RETCODE_SUCCESS) {
ret_code = SHA204_COMM_FAIL;
else
}
else {
ret_code = swi_send_bytes(count, tx_buffer);
}
if (ret_code != SHA204_SUCCESS)
{
if (sha204c_resync(rx_size, rx_buffer) == SHA204_RX_NO_RESPONSE)
if (sha204c_resync(rx_size, rx_buffer) == SHA204_RX_NO_RESPONSE) {
return ret_code; // The device seems to be dead in the water.
else
}
else {
continue;
}
}
// Wait minimum command execution time and then start polling for a response.
@@ -282,8 +297,9 @@ static uint8_t sha204c_send_and_receive(uint8_t *tx_buffer, uint8_t rx_size, uin
while (n_retries_receive-- > 0)
{
// Reset response buffer.
for (i = 0; i < rx_size; i++)
for (i = 0; i < rx_size; i++) {
rx_buffer[i] = 0;
}
// Poll for response.
timeout_countdown = execution_timeout_us;
@@ -297,11 +313,13 @@ static uint8_t sha204c_send_and_receive(uint8_t *tx_buffer, uint8_t rx_size, uin
if (ret_code == SHA204_RX_NO_RESPONSE)
{
// We did not receive a response. Re-synchronize and send command again.
if (sha204c_resync(rx_size, rx_buffer) == SHA204_RX_NO_RESPONSE)
if (sha204c_resync(rx_size, rx_buffer) == SHA204_RX_NO_RESPONSE) {
// The device seems to be dead in the water.
return ret_code;
else
}
else {
break;
}
}
// Check whether we received a valid response.
@@ -309,16 +327,19 @@ static uint8_t sha204c_send_and_receive(uint8_t *tx_buffer, uint8_t rx_size, uin
{
// We see 0xFF for the count when communication got out of sync.
ret_code_resync = sha204c_resync(rx_size, rx_buffer);
if (ret_code_resync == SHA204_SUCCESS)
if (ret_code_resync == SHA204_SUCCESS) {
// We did not have to wake up the device. Try receiving response again.
continue;
if (ret_code_resync == SHA204_RESYNC_WITH_WAKEUP)
}
if (ret_code_resync == SHA204_RESYNC_WITH_WAKEUP) {
// We could re-synchronize, but only after waking up the device.
// Re-send command.
break;
else
}
else {
// We failed to re-synchronize.
return ret_code;
}
}
// We received a response of valid size.
@@ -327,19 +348,22 @@ static uint8_t sha204c_send_and_receive(uint8_t *tx_buffer, uint8_t rx_size, uin
if (ret_code == SHA204_SUCCESS)
{
// Received valid response.
if (rx_buffer[SHA204_BUFFER_POS_COUNT] > SHA204_RSP_SIZE_MIN)
if (rx_buffer[SHA204_BUFFER_POS_COUNT] > SHA204_RSP_SIZE_MIN) {
// Received non-status response. We are done.
return ret_code;
}
// Received status response.
status_byte = rx_buffer[SHA204_BUFFER_POS_STATUS];
// Translate the three possible device status error codes
// into library return codes.
if (status_byte == SHA204_STATUS_BYTE_PARSE)
if (status_byte == SHA204_STATUS_BYTE_PARSE) {
return SHA204_PARSE_ERROR;
if (status_byte == SHA204_STATUS_BYTE_EXEC)
}
if (status_byte == SHA204_STATUS_BYTE_EXEC) {
return SHA204_CMD_FAIL;
}
if (status_byte == SHA204_STATUS_BYTE_COMM)
{
// In case of the device status byte indicating a communication
@@ -359,16 +383,19 @@ static uint8_t sha204c_send_and_receive(uint8_t *tx_buffer, uint8_t rx_size, uin
{
// Received response with incorrect CRC.
ret_code_resync = sha204c_resync(rx_size, rx_buffer);
if (ret_code_resync == SHA204_SUCCESS)
if (ret_code_resync == SHA204_SUCCESS) {
// We did not have to wake up the device. Try receiving response again.
continue;
if (ret_code_resync == SHA204_RESYNC_WITH_WAKEUP)
}
if (ret_code_resync == SHA204_RESYNC_WITH_WAKEUP) {
// We could re-synchronize, but only after waking up the device.
// Re-send command.
break;
else
}
else {
// We failed to re-synchronize.
return ret_code;
}
} // block end of check response consistency
} // block end of receive retry loop
@@ -418,8 +445,9 @@ static void sha204c_calculate_crc(uint8_t length, uint8_t *data, uint8_t *crc)
// Shift CRC to the left by 1.
crc_register <<= 1;
if ((data_bit ^ crc_bit) != 0)
if ((data_bit ^ crc_bit) != 0) {
crc_register ^= polynom;
}
}
}
crc[0] = (uint8_t) (crc_register & 0x00FF);
@@ -475,22 +503,27 @@ uint8_t atsha204_wakeup(uint8_t *response)
delay(SHA204_WAKEUP_DELAY);
uint8_t ret_code = sha204p_receive_response(SHA204_RSP_SIZE_MIN, response);
if (ret_code != SHA204_SUCCESS)
if (ret_code != SHA204_SUCCESS) {
return ret_code;
}
// Verify status response.
if (response[SHA204_BUFFER_POS_COUNT] != SHA204_RSP_SIZE_MIN)
if (response[SHA204_BUFFER_POS_COUNT] != SHA204_RSP_SIZE_MIN) {
ret_code = SHA204_INVALID_SIZE;
else if (response[SHA204_BUFFER_POS_STATUS] != SHA204_STATUS_BYTE_WAKEUP)
}
else if (response[SHA204_BUFFER_POS_STATUS] != SHA204_STATUS_BYTE_WAKEUP) {
ret_code = SHA204_COMM_FAIL;
}
else
{
if ((response[SHA204_RSP_SIZE_MIN - SHA204_CRC_SIZE] != 0x33)
|| (response[SHA204_RSP_SIZE_MIN + 1 - SHA204_CRC_SIZE] != 0x43))
|| (response[SHA204_RSP_SIZE_MIN + 1 - SHA204_CRC_SIZE] != 0x43)) {
ret_code = SHA204_BAD_CRC;
}
}
if (ret_code != SHA204_SUCCESS)
if (ret_code != SHA204_SUCCESS) {
delay(SHA204_COMMAND_EXEC_MAX);
}
return ret_code;
}
@@ -580,14 +613,16 @@ uint8_t atsha204_getSerialNumber(uint8_t * response)
uint8_t returnCode = sha204m_read(readCommand, readResponse, SHA204_ZONE_CONFIG, ADDRESS_SN03);
if (!returnCode)
{
for (int i=0; i<4; i++) // store bytes 0-3 into respones array
response[i] = readResponse[SHA204_BUFFER_POS_DATA+i];
for (int i=0; i<4; i++) {// store bytes 0-3 into respones array
response[i] = readResponse[SHA204_BUFFER_POS_DATA+i];
}
/* read from bytes 8->11 of config zone */
returnCode = sha204m_read(readCommand, readResponse, SHA204_ZONE_CONFIG, ADDRESS_SN47);
for (int i=4; i<8; i++) // store bytes 4-7 of SN into response array
for (int i=4; i<8; i++) {// store bytes 4-7 of SN into response array
response[i] = readResponse[SHA204_BUFFER_POS_DATA+(i-4)];
}
if (!returnCode)
{ /* Finally if last two reads were successful, read byte 8 of the SN */
+15 -7
View File
@@ -54,7 +54,7 @@ void Sha256Class::hashBlock() {
f=state.w[5];
g=state.w[6];
h=state.w[7];
for (i=0; i<64; i++) {
if (i>=16) {
t1 = buffer.w[i&15] + buffer.w[(i-7)&15];
@@ -102,7 +102,9 @@ void Sha256Class::pad() {
// Pad with 0x80 followed by 0x00 until the end of the block
addUncounted(0x80);
while (bufferOffset != 56) addUncounted(0x00);
while (bufferOffset != 56) {
addUncounted(0x00);
}
// Append length in the last 8 bytes
addUncounted(0); // We're only using 32 bit lengths
@@ -119,7 +121,7 @@ void Sha256Class::pad() {
uint8_t* Sha256Class::result(void) {
// Pad to complete the last block
pad();
// Swap byte order back
for (int i=0; i<8; i++) {
uint32_t a,b;
@@ -130,7 +132,7 @@ uint8_t* Sha256Class::result(void) {
b|=a>>24;
state.w[i]=b;
}
// Return pointer to hash (20 characters)
return state.b;
}
@@ -147,7 +149,9 @@ void Sha256Class::initHmac(const uint8_t* key, int keyLength) {
if (keyLength > BLOCK_LENGTH) {
// Hash long keys
init();
for (;keyLength--;) write(*key++);
for (;keyLength--;) {
write(*key++);
}
memcpy(keyBuffer,result(),HASH_LENGTH);
} else {
// Block length keys are used as is
@@ -166,7 +170,11 @@ uint8_t* Sha256Class::resultHmac(void) {
memcpy(innerHash,result(),HASH_LENGTH);
// Calculate outer hash
init();
for (i=0; i<BLOCK_LENGTH; i++) write(keyBuffer[i] ^ HMAC_OPAD);
for (i=0; i<HASH_LENGTH; i++) write(innerHash[i]);
for (i=0; i<BLOCK_LENGTH; i++) {
write(keyBuffer[i] ^ HMAC_OPAD);
}
for (i=0; i<HASH_LENGTH; i++) {
write(innerHash[i]);
}
return result();
}
+41 -18
View File
@@ -1,17 +1,17 @@
/* An Alternative Software Serial Library
* http://www.pjrc.com/teensy/td_libs_AltSoftSerial.html
* Copyright (c) 2014 PJRC.COM, LLC, Paul Stoffregen, paul@pjrc.com
*
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -108,8 +108,10 @@ void AltSoftSerial::writeByte(uint8_t b)
uint8_t intr_state, head;
head = tx_buffer_head + 1;
if (head >= TX_BUFFER_SIZE) head = 0;
while (tx_buffer_tail == head) ; // wait until space in buffer
if (head >= TX_BUFFER_SIZE) {
head = 0;
}
while (tx_buffer_tail == head) {} // wait until space in buffer
intr_state = SREG;
cli();
if (tx_state) {
@@ -168,7 +170,9 @@ ISR(COMPARE_A_INTERRUPT)
DISABLE_INT_COMPARE_A();
} else {
tx_state = 1;
if (++tail >= TX_BUFFER_SIZE) tail = 0;
if (++tail >= TX_BUFFER_SIZE) {
tail = 0;
}
tx_buffer_tail = tail;
tx_byte = tx_buffer[tail];
tx_bit = 0;
@@ -180,7 +184,7 @@ ISR(COMPARE_A_INTERRUPT)
void AltSoftSerial::flushOutput(void)
{
while (tx_state) /* wait */ ;
while (tx_state) {}/* wait */
}
@@ -216,14 +220,18 @@ ISR(CAPTURE_INTERRUPT)
target = rx_target;
while (1) {
offset = capture - target;
if (offset < 0) break;
if (offset < 0) {
break;
}
rx_byte = (rx_byte >> 1) | rx_bit;
target += ticks_per_bit;
state++;
if (state >= 9) {
DISABLE_INT_COMPARE_B();
head = rx_buffer_head + 1;
if (head >= RX_BUFFER_SIZE) head = 0;
if (head >= RX_BUFFER_SIZE) {
head = 0;
}
if (head != rx_buffer_tail) {
rx_buffer[head] = rx_byte;
rx_buffer_head = head;
@@ -253,7 +261,9 @@ ISR(COMPARE_B_INTERRUPT)
state++;
}
head = rx_buffer_head + 1;
if (head >= RX_BUFFER_SIZE) head = 0;
if (head >= RX_BUFFER_SIZE) {
head = 0;
}
if (head != rx_buffer_tail) {
rx_buffer[head] = rx_byte;
rx_buffer_head = head;
@@ -271,8 +281,12 @@ int AltSoftSerial::read(void)
head = rx_buffer_head;
tail = rx_buffer_tail;
if (head == tail) return -1;
if (++tail >= RX_BUFFER_SIZE) tail = 0;
if (head == tail) {
return -1;
}
if (++tail >= RX_BUFFER_SIZE) {
tail = 0;
}
out = rx_buffer[tail];
rx_buffer_tail = tail;
return out;
@@ -284,7 +298,9 @@ int AltSoftSerial::peek(void)
head = rx_buffer_head;
tail = rx_buffer_tail;
if (head == tail) return -1;
if (head == tail) {
return -1;
}
return rx_buffer[tail];
}
@@ -294,7 +310,9 @@ int AltSoftSerial::available(void)
head = rx_buffer_head;
tail = rx_buffer_tail;
if (head >= tail) return head - tail;
if (head >= tail) {
return head - tail;
}
return RX_BUFFER_SIZE + head - tail;
}
@@ -309,9 +327,14 @@ void ftm0_isr(void)
{
uint32_t flags = FTM0_STATUS;
FTM0_STATUS = 0;
if (flags & (1<<5)) altss_capture_interrupt();
if (flags & (1<<6)) altss_compare_a_interrupt();
if (flags & (1<<0)) altss_compare_b_interrupt();
if (flags & (1<<5)) {
altss_capture_interrupt();
}
if (flags & (1<<6)) {
altss_compare_a_interrupt();
}
if (flags & (1<<0)) {
altss_compare_b_interrupt();
}
}
#endif
+16 -8
View File
@@ -120,7 +120,9 @@ size_t EthernetClient::write(const uint8_t *buf, size_t size) {
}
size_t EthernetClient::write(const char *str) {
if (str == NULL) return 0;
if (str == NULL) {
return 0;
}
return write((const uint8_t *)str, strlen(str));
}
size_t EthernetClient::write(const char *buffer, size_t size) {
@@ -165,8 +167,9 @@ void EthernetClient::flush() {
}
void EthernetClient::stop() {
if (_sock == -1)
if (_sock == -1) {
return;
}
// attempt to close the connection gracefully (send a FIN to other side)
shutdown(_sock, SHUT_RDWR);
@@ -178,21 +181,24 @@ void EthernetClient::stop() {
uint8_t s;
do {
s = status();
if (s == ETHERNETCLIENT_W5100_CLOSED)
if (s == ETHERNETCLIENT_W5100_CLOSED) {
break; // exit the loop
}
usleep(1000);
gettimeofday(&curTime, NULL);
} while (((curTime.tv_sec - startTime.tv_sec) * 1000000) + (curTime.tv_usec - startTime.tv_usec) < 1000000);
// if it hasn't closed, close it forcefully
if (s != ETHERNETCLIENT_W5100_CLOSED)
if (s != ETHERNETCLIENT_W5100_CLOSED) {
close(_sock);
}
_sock = -1;
}
uint8_t EthernetClient::status() {
if (_sock == -1) return ETHERNETCLIENT_W5100_CLOSED;
if (_sock == -1) {
return ETHERNETCLIENT_W5100_CLOSED;
}
struct tcp_info tcp_info;
int tcp_info_length = sizeof(tcp_info);
@@ -227,8 +233,10 @@ uint8_t EthernetClient::status() {
}
uint8_t EthernetClient::connected() {
if (_sock == -1) return 0;
if (_sock == -1) {
return 0;
}
if (peek() < 0) {
if (errno == EAGAIN) {
return 1;
+3 -1
View File
@@ -151,7 +151,9 @@ size_t EthernetServer::write(const uint8_t *buffer, size_t size)
size_t EthernetServer::write(const char *str)
{
if (str == NULL) return 0;
if (str == NULL) {
return 0;
}
return write((const uint8_t *)str, strlen(str));
}
+16 -8
View File
@@ -105,10 +105,12 @@ size_t Print::print(long n, int base) {
}
size_t Print::print(unsigned long n, int base) {
if(base == 0)
if(base == 0) {
return write(n);
else
}
else {
return printNumber(n, base);
}
}
size_t Print::print(double n, int digits) {
@@ -182,8 +184,9 @@ size_t Print::printNumber(unsigned long n, uint8_t base) {
*str = '\0';
// prevent crash if called with base == 1
if(base < 2)
if(base < 2) {
base = 10;
}
do {
unsigned long m = n;
@@ -198,14 +201,18 @@ size_t Print::printNumber(unsigned long n, uint8_t base) {
size_t Print::printFloat(double number, uint8_t digits) {
size_t n = 0;
if(std::isnan(number))
if(std::isnan(number)) {
return print("nan");
if(std::isinf(number))
}
if(std::isinf(number)) {
return print("inf");
if(number > 4294967040.0)
}
if(number > 4294967040.0) {
return print("ovf"); // constant determined empirically
if(number < -4294967040.0)
}
if(number < -4294967040.0) {
return print("ovf"); // constant determined empirically
}
// Handle negative numbers
if(number < 0.0) {
@@ -215,8 +222,9 @@ size_t Print::printFloat(double number, uint8_t digits) {
// Round correctly so that print(1.999, 2) prints as "2.00"
double rounding = 0.5;
for(uint8_t i = 0; i < digits; ++i)
for(uint8_t i = 0; i < digits; ++i) {
rounding /= 10.0;
}
number += rounding;
+3 -1
View File
@@ -212,7 +212,9 @@ int SerialPort::peek()
{
FILE * f = fdopen(sd, "r+");
int c = getc(f);
if (c == EOF) return -1;
if (c == EOF) {
return -1;
}
ungetc(c, f);
return c;
}
+53 -29
View File
@@ -33,8 +33,9 @@ int Stream::timedRead() {
_startMillis = millis();
do {
c = read();
if(c >= 0)
return c;
if(c >= 0) {
return c;
}
yield();
} while(millis() - _startMillis < _timeout);
return -1; // -1 indicates timeout
@@ -46,8 +47,9 @@ int Stream::timedPeek() {
_startMillis = millis();
do {
c = peek();
if(c >= 0)
if(c >= 0) {
return c;
}
yield();
} while(millis() - _startMillis < _timeout);
return -1; // -1 indicates timeout
@@ -59,12 +61,15 @@ int Stream::peekNextDigit() {
int c;
while(1) {
c = timedPeek();
if(c < 0)
if(c < 0) {
return c; // timeout
if(c == '-')
}
if(c == '-') {
return c;
if(c >= '0' && c <= '9')
}
if(c >= '0' && c <= '9') {
return c;
}
read(); // discard non-numeric
}
}
@@ -101,13 +106,14 @@ bool Stream::findUntil(const char *target, size_t targetLen, const char *termina
size_t termIndex = 0;
int c;
if(*target == 0)
if(*target == 0) {
return true; // return true if target is a null string
}
while((c = timedRead()) > 0) {
if(c != target[index])
if(c != target[index]) {
index = 0; // reset index if any char does not match
}
if(c == target[index]) {
//////Serial.print("found "); Serial.write(c); Serial.print("index now"); Serial.println(index+1);
if(++index >= targetLen) { // return true if all chars in the target match
@@ -116,10 +122,12 @@ bool Stream::findUntil(const char *target, size_t targetLen, const char *termina
}
if(termLen > 0 && c == terminator[termIndex]) {
if(++termIndex >= termLen)
if(++termIndex >= termLen) {
return false; // return false if terminate string found before target string
} else
}
} else {
termIndex = 0;
}
}
return false;
}
@@ -140,22 +148,27 @@ long Stream::parseInt(char skipChar) {
c = peekNextDigit();
// ignore non numeric leading characters
if(c < 0)
if(c < 0) {
return 0; // zero returned if timeout
}
do {
if(c == skipChar)
; // ignore this charactor
else if(c == '-')
if(c == skipChar) {
// ignore this charactor
}
else if(c == '-') {
isNegative = true;
else if(c >= '0' && c <= '9') // is c a digit?
}
else if(c >= '0' && c <= '9') { // is c a digit?
value = value * 10 + c - '0';
}
read(); // consume the character we got with peek
c = timedPeek();
} while((c >= '0' && c <= '9') || c == skipChar);
if(isNegative)
if(isNegative) {
value = -value;
}
return value;
}
@@ -175,31 +188,39 @@ float Stream::parseFloat(char skipChar) {
c = peekNextDigit();
// ignore non numeric leading characters
if(c < 0)
if(c < 0) {
return 0; // zero returned if timeout
}
do {
if(c == skipChar)
; // ignore
else if(c == '-')
if(c == skipChar) {
// ignore
}
else if(c == '-') {
isNegative = true;
else if(c == '.')
}
else if(c == '.') {
isFraction = true;
}
else if(c >= '0' && c <= '9') { // is c a digit?
value = value * 10 + c - '0';
if(isFraction)
if(isFraction) {
fraction *= 0.1;
}
}
read(); // consume the character we got with peek
c = timedPeek();
} while((c >= '0' && c <= '9') || c == '.' || c == skipChar);
if(isNegative)
if(isNegative) {
value = -value;
if(isFraction)
}
if(isFraction) {
return value * fraction;
else
}
else {
return value;
}
}
// read characters from stream into buffer
@@ -211,8 +232,9 @@ size_t Stream::readBytes(char *buffer, size_t length) {
size_t count = 0;
while(count < length) {
int c = timedRead();
if(c < 0)
if(c < 0) {
break;
}
*buffer++ = (char) c;
count++;
}
@@ -224,13 +246,15 @@ size_t Stream::readBytes(char *buffer, size_t length) {
// returns the number of characters placed in the buffer (0 means no valid data found)
size_t Stream::readBytesUntil(char terminator, char *buffer, size_t length) {
if(length < 1)
if(length < 1) {
return 0;
}
size_t index = 0;
while(index < length) {
int c = timedRead();
if(c < 0 || c == terminator)
if(c < 0 || c == terminator) {
break;
}
*buffer++ = (char) c;
index++;
}
+6 -4
View File
@@ -1,14 +1,14 @@
/*
noniso.cpp - replacements for non-ISO functions used by Arduino core
Copyright © 2016 Ivan Grokhotkov
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
@@ -61,8 +61,9 @@ char* itoa(int value, char* result, int base) {
} while(quotient);
// Apply negative sign
if(value < 0)
if(value < 0) {
*out++ = '-';
}
reverse(result, out);
*out = 0;
@@ -112,8 +113,9 @@ char* ltoa(long value, char* result, int base) {
} while(quotient);
// Apply negative sign
if(value < 0)
if(value < 0) {
*out++ = '-';
}
reverse(result, out);
*out = 0;
+15 -5
View File
@@ -231,7 +231,9 @@ boolean PubSubClient::readByte(uint8_t * result, uint16_t * index){
uint16_t PubSubClient::readPacket(uint8_t* lengthLength) {
uint16_t len = 0;
if(!readByte(buffer, &len)) return 0;
if(!readByte(buffer, &len)) {
return 0;
}
bool isPublish = (buffer[0]&0xF0) == MQTTPUBLISH;
uint32_t multiplier = 1;
uint16_t length = 0;
@@ -240,7 +242,9 @@ uint16_t PubSubClient::readPacket(uint8_t* lengthLength) {
uint8_t start = 0;
do {
if(!readByte(&digit)) return 0;
if(!readByte(&digit)) {
return 0;
}
buffer[len++] = digit;
length += (digit & 127) * multiplier;
multiplier *= 128;
@@ -249,8 +253,12 @@ uint16_t PubSubClient::readPacket(uint8_t* lengthLength) {
if (isPublish) {
// Read in topic length to calculate bytes to skip over for Stream writing
if(!readByte(buffer, &len)) return 0;
if(!readByte(buffer, &len)) return 0;
if(!readByte(buffer, &len)) {
return 0;
}
if(!readByte(buffer, &len)) {
return 0;
}
skip = (buffer[*lengthLength+1]<<8)+buffer[*lengthLength+2];
start = 2;
if (buffer[0]&MQTTQOS1) {
@@ -260,7 +268,9 @@ uint16_t PubSubClient::readPacket(uint8_t* lengthLength) {
}
for (uint16_t i = start;i<length;i++) {
if(!readByte(&digit)) return 0;
if(!readByte(&digit)) {
return 0;
}
if (this->stream) {
if (isPublish && len-*lengthLength-2>skip) {
this->stream->write(digit);
+18 -15
View File
@@ -71,7 +71,7 @@ LOCAL uint8_t RF24_spiMultiByteTransfer(uint8_t cmd, uint8_t* buf, uint8_t len,
} else {
status = *prx++; // status is 1st byte of receive buffer
// decrement before to skip status byte
while (--size) { *buf++ = *prx++; }
while (--size) { *buf++ = *prx++; }
}
} else {
status = *prx; // status is 1st byte of receive buffer
@@ -79,9 +79,11 @@ LOCAL uint8_t RF24_spiMultiByteTransfer(uint8_t cmd, uint8_t* buf, uint8_t len,
#else
status = _SPI.transfer( cmd );
while ( len-- ) {
if (aReadMode) {
if (aReadMode) {
status = _SPI.transfer( NOP );
if (buf != NULL) *current++ = status;
if (buf != NULL) {
*current++ = status;
}
} else status = _SPI.transfer(*current++);
}
#endif
@@ -92,7 +94,7 @@ LOCAL uint8_t RF24_spiMultiByteTransfer(uint8_t cmd, uint8_t* buf, uint8_t len,
// timing
delayMicroseconds(10);
return status;
}
}
LOCAL uint8_t RF24_spiByteTransfer(uint8_t cmd) {
return RF24_spiMultiByteTransfer( cmd, NULL, 0, false);
@@ -182,8 +184,8 @@ LOCAL void RF24_enableFeatures(void) {
RF24_RAW_writeByteRegister(ACTIVATE, 0x73);
}
LOCAL void RF24_openWritingPipe(uint8_t recipient) {
RF24_DEBUG(PSTR("RF24:open writing pipe, recipient=%d\n"), recipient);
LOCAL void RF24_openWritingPipe(uint8_t recipient) {
RF24_DEBUG(PSTR("RF24:open writing pipe, recipient=%d\n"), recipient);
// only write LSB of RX0 and TX pipe
RF24_setPipeLSB(RX_ADDR_P0, recipient);
RF24_setPipeLSB(TX_ADDR, recipient);
@@ -191,10 +193,12 @@ LOCAL void RF24_openWritingPipe(uint8_t recipient) {
LOCAL void RF24_startListening(void) {
RF24_DEBUG(PSTR("RF24:start listening\n"));
// toggle PRX
// toggle PRX
RF24_setRFConfiguration(MY_RF24_CONFIGURATION | _BV(PWR_UP) | _BV(PRIM_RX) );
// all RX pipe addresses must be unique, therefore skip if node ID is 0xFF
if(MY_RF24_NODE_ADDRESS!=AUTO) RF24_setPipeLSB(RX_ADDR_P0, MY_RF24_NODE_ADDRESS);
if(MY_RF24_NODE_ADDRESS!=AUTO) {
RF24_setPipeLSB(RX_ADDR_P0, MY_RF24_NODE_ADDRESS);
}
// start listening
RF24_ce(HIGH);
}
@@ -219,7 +223,7 @@ LOCAL bool RF24_sendMessage( uint8_t recipient, const void* buf, uint8_t len ) {
uint8_t status;
RF24_stopListening();
RF24_openWritingPipe( recipient );
RF24_openWritingPipe( recipient );
RF24_DEBUG(PSTR("RF24:send message to %d, len=%d\n"),recipient,len);
// flush TX FIFO
RF24_flushTX();
@@ -251,10 +255,10 @@ LOCAL bool RF24_sendMessage( uint8_t recipient, const void* buf, uint8_t len ) {
LOCAL uint8_t RF24_getDynamicPayloadSize(void) {
uint8_t result = RF24_spiMultiByteTransfer(R_RX_PL_WID, NULL, 1, true);
// check if payload size invalid
if(result > 32) {
if(result > 32) {
RF24_DEBUG(PSTR("RF24:invalid payload length = %d\n"),result);
RF24_flushRX();
result = 0;
RF24_flushRX();
result = 0;
}
return result;
}
@@ -267,7 +271,7 @@ LOCAL bool RF24_isDataAvailable() {
LOCAL uint8_t RF24_readMessage( void* buf) {
const uint8_t len = RF24_getDynamicPayloadSize();
RF24_DEBUG(PSTR("RF24:read message, len=%d\n"), len);
RF24_spiMultiByteTransfer( R_RX_PAYLOAD , (uint8_t*)buf, len, true );
RF24_spiMultiByteTransfer( R_RX_PAYLOAD , (uint8_t*)buf, len, true );
// clear RX interrupt
RF24_setStatus(_BV(RX_DR) );
return len;
@@ -314,7 +318,7 @@ LOCAL void RF24_irqHandler( void )
// for a message we've already read.
while (RF24_isDataAvailable()) {
RF24_receiveCallback(); // Must call RF24_readMessage(), which will clear RX_DR IRQ !
}
}
// Restore our interrupt handler.
#if defined(MY_GATEWAY_SERIAL) && !defined(__linux__)
noInterrupts();
@@ -395,4 +399,3 @@ LOCAL bool RF24_initialize(void) {
RF24_setStatus(_BV(TX_DS) | _BV(MAX_RT) | _BV(RX_DR));
return true;
}
+96 -71
View File
@@ -6,23 +6,23 @@
// **********************************************************************************
// License
// **********************************************************************************
// This program is free software; you can redistribute it
// and/or modify it under the terms of the GNU General
// Public License as published by the Free Software
// Foundation; either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will
// be useful, but WITHOUT ANY WARRANTY; without even the
// implied warranty of MERCHANTABILITY or FITNESS FOR A
// PARTICULAR PURPOSE. See the GNU General Public
// License for more details.
//
// You should have received a copy of the GNU General
// This program is free software; you can redistribute it
// and/or modify it under the terms of the GNU General
// Public License as published by the Free Software
// Foundation; either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will
// be useful, but WITHOUT ANY WARRANTY; without even the
// implied warranty of MERCHANTABILITY or FITNESS FOR A
// PARTICULAR PURPOSE. See the GNU General Public
// License for more details.
//
// You should have received a copy of the GNU General
// Public License along with this program.
// If not, see <http://www.gnu.org/licenses/>.
//
// Licence can be viewed at
//
// Licence can be viewed at
// http://www.gnu.org/licenses/gpl-3.0.txt
//
// Please maintain this license information along with authorship
@@ -93,17 +93,18 @@ bool RFM69::initialize(uint8_t freqBand, uint8_t nodeID, uint8_t networkID)
unsigned long start = millis();
uint8_t timeout = 50;
do {
writeReg(REG_SYNCVALUE1, 0xAA);
writeReg(REG_SYNCVALUE1, 0xAA);
yield();
} while (readReg(REG_SYNCVALUE1) != 0xaa && millis()-start < timeout);
start = millis();
do {
writeReg(REG_SYNCVALUE1, 0x55);
writeReg(REG_SYNCVALUE1, 0x55);
yield();
} while (readReg(REG_SYNCVALUE1) != 0x55 && millis()-start < timeout);
for (uint8_t i = 0; CONFIG[i][0] != 255; i++)
for (uint8_t i = 0; CONFIG[i][0] != 255; i++) {
writeReg(CONFIG[i][0], CONFIG[i][1]);
}
// Encryption is persistent between resets and can trip you up during debugging.
// Disable it during initialization so we always start from a known state.
@@ -113,10 +114,11 @@ bool RFM69::initialize(uint8_t freqBand, uint8_t nodeID, uint8_t networkID)
setMode(RF69_MODE_STANDBY);
start = millis();
while (((readReg(REG_IRQFLAGS1) & RF_IRQFLAGS1_MODEREADY) == 0x00) && millis()-start < timeout) {
yield();
yield();
} // wait for ModeReady
if (millis()-start >= timeout)
if (millis()-start >= timeout) {
return false;
}
attachInterrupt(_interruptNum, RFM69::isr0, RISING);
selfPointer = this;
@@ -149,17 +151,22 @@ void RFM69::setFrequency(uint32_t freqHz)
void RFM69::setMode(uint8_t newMode)
{
if (newMode == _mode)
if (newMode == _mode) {
return;
}
switch (newMode) {
case RF69_MODE_TX:
writeReg(REG_OPMODE, (readReg(REG_OPMODE) & 0xE3) | RF_OPMODE_TRANSMITTER);
if (_isRFM69HW) setHighPowerRegs(true);
if (_isRFM69HW) {
setHighPowerRegs(true);
}
break;
case RF69_MODE_RX:
writeReg(REG_OPMODE, (readReg(REG_OPMODE) & 0xE3) | RF_OPMODE_RECEIVER);
if (_isRFM69HW) setHighPowerRegs(false);
if (_isRFM69HW) {
setHighPowerRegs(false);
}
break;
case RF69_MODE_SYNTH:
writeReg(REG_OPMODE, (readReg(REG_OPMODE) & 0xE3) | RF_OPMODE_SYNTHESIZER);
@@ -209,7 +216,9 @@ void RFM69::setNetwork(uint8_t networkID)
void RFM69::setPowerLevel(uint8_t powerLevel)
{
_powerLevel = (powerLevel > 31 ? 31 : powerLevel);
if (_isRFM69HW) _powerLevel /= 2;
if (_isRFM69HW) {
_powerLevel /= 2;
}
writeReg(REG_PALEVEL, (readReg(REG_PALEVEL) & 0xE0) | _powerLevel);
}
@@ -227,7 +236,9 @@ void RFM69::send(uint8_t toAddress, const void* buffer, uint8_t bufferSize, bool
{
writeReg(REG_PACKETCONFIG2, (readReg(REG_PACKETCONFIG2) & 0xFB) | RF_PACKET2_RXRESTART); // avoid RX deadlocks
uint32_t now = millis();
while (!canSend() && millis() - now < RF69_CSMA_LIMIT_MS) receiveDone();
while (!canSend() && millis() - now < RF69_CSMA_LIMIT_MS) {
receiveDone();
}
sendFrame(toAddress, buffer, bufferSize, requestACK, false);
}
@@ -258,8 +269,9 @@ bool RFM69::sendWithRetry(uint8_t toAddress, const void* buffer, uint8_t bufferS
// should be polled immediately after sending a packet with ACK request
bool RFM69::ACKReceived(uint8_t fromNodeID) {
if (receiveDone())
if (receiveDone()) {
return (SENDERID == fromNodeID || fromNodeID == RF69_BROADCAST_ADDR) && ACK_RECEIVED;
}
return false;
}
@@ -287,21 +299,25 @@ void RFM69::sendACK(const void* buffer, uint8_t bufferSize) {
void RFM69::interruptHook(uint8_t CTLbyte) {
(void)CTLbyte;
};
// internal function
void RFM69::sendFrame(uint8_t toAddress, const void* buffer, uint8_t bufferSize, bool requestACK, bool sendACK)
{
setMode(RF69_MODE_STANDBY); // turn off receiver to prevent reception while filling fifo
while ((readReg(REG_IRQFLAGS1) & RF_IRQFLAGS1_MODEREADY) == 0x00); // wait for ModeReady
while ((readReg(REG_IRQFLAGS1) & RF_IRQFLAGS1_MODEREADY) == 0x00) {} // wait for ModeReady
writeReg(REG_DIOMAPPING1, RF_DIOMAPPING1_DIO0_00); // DIO0 is "Packet Sent"
if (bufferSize > RF69_MAX_DATA_LEN) bufferSize = RF69_MAX_DATA_LEN;
if (bufferSize > RF69_MAX_DATA_LEN) {
bufferSize = RF69_MAX_DATA_LEN;
}
// control byte
uint8_t CTLbyte = 0x00;
if (sendACK)
if (sendACK) {
CTLbyte = RFM69_CTL_SENDACK;
else if (requestACK)
}
else if (requestACK) {
CTLbyte = RFM69_CTL_REQACK;
}
// write to FIFO
select();
@@ -311,14 +327,15 @@ void RFM69::sendFrame(uint8_t toAddress, const void* buffer, uint8_t bufferSize,
SPI.transfer(_address);
SPI.transfer(CTLbyte);
for (uint8_t i = 0; i < bufferSize; i++)
for (uint8_t i = 0; i < bufferSize; i++) {
SPI.transfer(((uint8_t*) buffer)[i]);
}
unselect();
// no need to wait for transmit mode to be ready since its handled by the radio
setMode(RF69_MODE_TX);
uint32_t txStart = millis();
while (hwDigitalRead(_interruptPin) == 0 && millis() - txStart < RF69_TX_LIMIT_MS); // wait for DIO0 to turn HIGH signalling transmission finish
while (hwDigitalRead(_interruptPin) == 0 && millis() - txStart < RF69_TX_LIMIT_MS) {} // wait for DIO0 to turn HIGH signalling transmission finish
//while (readReg(REG_IRQFLAGS2) & RF_IRQFLAGS2_PACKETSENT == 0x00); // wait for ModeReady
setMode(RF69_MODE_STANDBY);
}
@@ -352,14 +369,16 @@ void RFM69::interruptHandler() {
ACK_RECEIVED = CTLbyte & RFM69_CTL_SENDACK; // extract ACK-received flag
ACK_REQUESTED = CTLbyte & RFM69_CTL_REQACK; // extract ACK-requested flag
interruptHook(CTLbyte); // TWS: hook to derived class interrupt function
for (uint8_t i = 0; i < DATALEN; i++)
{
DATA[i] = SPI.transfer(0);
}
if (DATALEN < RF69_MAX_DATA_LEN) DATA[DATALEN] = 0; // add null at end of string
if (DATALEN < RF69_MAX_DATA_LEN) {
DATA[DATALEN] = 0; // add null at end of string
}
unselect();
setMode(RF69_MODE_RX);
}
@@ -379,8 +398,9 @@ void RFM69::receiveBegin() {
ACK_REQUESTED = 0;
ACK_RECEIVED = 0;
RSSI = 0;
if (readReg(REG_IRQFLAGS2) & RF_IRQFLAGS2_PAYLOADREADY)
if (readReg(REG_IRQFLAGS2) & RF_IRQFLAGS2_PAYLOADREADY) {
writeReg(REG_PACKETCONFIG2, (readReg(REG_PACKETCONFIG2) & 0xFB) | RF_PACKET2_RXRESTART); // avoid RX deadlocks
}
writeReg(REG_DIOMAPPING1, RF_DIOMAPPING1_DIO0_01); // set DIO0 to "PAYLOADREADY" in receive mode
setMode(RF69_MODE_RX);
}
@@ -414,8 +434,9 @@ void RFM69::encrypt(const char* key) {
{
select();
SPI.transfer(REG_AESKEY1 | 0x80);
for (uint8_t i = 0; i < 16; i++)
for (uint8_t i = 0; i < 16; i++) {
SPI.transfer(key[i]);
}
unselect();
}
writeReg(REG_PACKETCONFIG2, (readReg(REG_PACKETCONFIG2) & 0xFE) | (key ? 1 : 0));
@@ -428,7 +449,7 @@ int16_t RFM69::readRSSI(bool forceTrigger) {
{
// RSSI trigger not needed if DAGC is in continuous mode
writeReg(REG_RSSICONFIG, RF_RSSI_START);
while ((readReg(REG_RSSICONFIG) & RF_RSSI_DONE) == 0x00); // wait for RSSI_Ready
while ((readReg(REG_RSSICONFIG) & RF_RSSI_DONE) == 0x00) {} // wait for RSSI_Ready
}
rssi = -readReg(REG_RSSIVALUE);
rssi >>= 1;
@@ -489,10 +510,12 @@ void RFM69::promiscuous(bool onOff) {
void RFM69::setHighPower(bool onOff) {
_isRFM69HW = onOff;
writeReg(REG_OCP, _isRFM69HW ? RF_OCP_OFF : RF_OCP_ON);
if (_isRFM69HW) // turning ON
if (_isRFM69HW) { // turning ON
writeReg(REG_PALEVEL, (readReg(REG_PALEVEL) & 0x1F) | RF_PALEVEL_PA1_ON | RF_PALEVEL_PA2_ON); // enable P1 & P2 amplifier stages
else
}
else {
writeReg(REG_PALEVEL, RF_PALEVEL_PA0_ON | RF_PALEVEL_PA1_OFF | RF_PALEVEL_PA2_OFF | _powerLevel); // enable P0 only
}
}
// internal function
@@ -501,7 +524,7 @@ void RFM69::setHighPowerRegs(bool onOff) {
writeReg(REG_TESTPA2, onOff ? 0x7C : 0x70);
}
// set the slave select (CS) pin
// set the slave select (CS) pin
void RFM69::setCS(uint8_t newSPISlaveSelect) {
_slaveSelectPin = newSPISlaveSelect;
hwDigitalWrite(_slaveSelectPin, HIGH);
@@ -519,7 +542,9 @@ void SerialWrite ( uint8_t c ) {
}
void SerialPrint_P(PGM_P str, void (*f)(uint8_t) = SerialWrite ) {
for (uint8_t c; (c = pgm_read_byte(str)); str++) (*f)(c);
for (uint8_t c; (c = pgm_read_byte(str)); str++) {
(*f)(c);
}
}
#endif
@@ -527,7 +552,7 @@ void RFM69::readAllRegs()
{
uint8_t regVal;
#if REGISTER_DETAIL
#if REGISTER_DETAIL
int capVal;
//... State Variables for intelligent decoding
@@ -536,7 +561,7 @@ void RFM69::readAllRegs()
int freqDev = 0;
long freqCenter = 0;
#endif
Serial.println("Address - HEX - BIN");
for (uint8_t regAddr = 1; regAddr <= 0x4F; regAddr++)
{
@@ -551,8 +576,8 @@ void RFM69::readAllRegs()
Serial.print(" - ");
Serial.println(regVal,BIN);
#if REGISTER_DETAIL
switch ( regAddr )
#if REGISTER_DETAIL
switch ( regAddr )
{
case 0x1 : {
SerialPrint ( "Controls the automatic Sequencer ( see section 4.2 )\nSequencerOff : " );
@@ -561,19 +586,19 @@ void RFM69::readAllRegs()
} else {
SerialPrint ( "0 -> Operating mode as selected with Mode bits in RegOpMode is automatically reached with the Sequencer\n" );
}
SerialPrint( "\nEnables Listen mode, should be enabled whilst in Standby mode:\nListenOn : " );
if ( 0x40 & regVal ) {
SerialPrint ( "1 -> On\n" );
} else {
SerialPrint ( "0 -> Off ( see section 4.3)\n" );
}
SerialPrint( "\nAborts Listen mode when set together with ListenOn=0 See section 4.3.4 for details (Always reads 0.)\n" );
if ( 0x20 & regVal ) {
SerialPrint ( "ERROR - ListenAbort should NEVER return 1 this is a write only register\n" );
}
SerialPrint("\nTransceiver's operating modes:\nMode : ");
capVal = (regVal >> 2) & 0x7;
if ( capVal == 0b000 ) {
@@ -593,9 +618,9 @@ void RFM69::readAllRegs()
SerialPrint ( "\n" );
break;
}
case 0x2 : {
SerialPrint("Data Processing mode:\nDataMode : ");
capVal = (regVal >> 5) & 0x3;
if ( capVal == 0b00 ) {
@@ -607,7 +632,7 @@ void RFM69::readAllRegs()
} else if ( capVal == 0b11 ) {
SerialPrint ( "11 -> Continuous mode without bit synchronizer\n" );
}
SerialPrint("\nModulation scheme:\nModulation Type : ");
capVal = (regVal >> 3) & 0x3;
if ( capVal == 0b00 ) {
@@ -620,7 +645,7 @@ void RFM69::readAllRegs()
} else if ( capVal == 0b11 ) {
SerialPrint ( "11 -> reserved\n" );
}
SerialPrint("\nData shaping: ");
if ( modeFSK ) {
SerialPrint( "in FSK:\n" );
@@ -650,16 +675,16 @@ void RFM69::readAllRegs()
SerialPrint ( "ERROR - 11 is reserved\n" );
}
}
SerialPrint ( "\n" );
break;
}
case 0x3 : {
bitRate = (regVal << 8);
break;
}
case 0x4 : {
bitRate |= regVal;
SerialPrint ( "Bit Rate (Chip Rate when Manchester encoding is enabled)\nBitRate : ");
@@ -668,12 +693,12 @@ void RFM69::readAllRegs()
SerialPrint( "\n" );
break;
}
case 0x5 : {
freqDev = ( (regVal & 0x3f) << 8 );
break;
}
case 0x6 : {
freqDev |= regVal;
SerialPrint( "Frequency deviation\nFdev : " );
@@ -682,20 +707,20 @@ void RFM69::readAllRegs()
SerialPrint ( "\n" );
break;
}
case 0x7 : {
unsigned long tempVal = regVal;
freqCenter = ( tempVal << 16 );
break;
}
case 0x8 : {
unsigned long tempVal = regVal;
freqCenter = freqCenter | ( tempVal << 8 );
break;
}
case 0x9 : {
case 0x9 : {
freqCenter = freqCenter | regVal;
SerialPrint ( "RF Carrier frequency\nFRF : " );
unsigned long val = 61UL * freqCenter;
@@ -711,7 +736,7 @@ void RFM69::readAllRegs()
} else {
SerialPrint ( "0 -> RC calibration is in progress\n" );
}
SerialPrint ( "\n" );
break;
}
@@ -726,7 +751,7 @@ void RFM69::readAllRegs()
SerialPrint ( "\n" );
break;
}
case 0xc : {
SerialPrint ( "Reserved\n\n" );
break;
@@ -745,7 +770,7 @@ void RFM69::readAllRegs()
} else if ( val == 0b11 ) {
SerialPrint ( "11 -> 262 ms\n" );
}
SerialPrint ( "\nResolution of Listen mode Rx time (calibrated RC osc):\nListenResolRx : " );
val = (regVal >> 4) & 0x3;
if ( val == 0b00 ) {
@@ -764,7 +789,7 @@ void RFM69::readAllRegs()
} else {
SerialPrint ( "0 -> signal strength is above RssiThreshold\n" );
}
SerialPrint ( "\nAction taken after acceptance of a packet in Listen mode:\nListenEnd : " );
val = (regVal >> 1 ) & 0x3;
if ( val == 0b00 ) {
@@ -776,12 +801,12 @@ void RFM69::readAllRegs()
} else if ( val == 0b11 ) {
SerialPrint ( "11 -> Reserved\n" );
}
SerialPrint ( "\n" );
break;
}
default : {
}
}
@@ -794,12 +819,12 @@ uint8_t RFM69::readTemperature(uint8_t calFactor) // returns centigrade
{
setMode(RF69_MODE_STANDBY);
writeReg(REG_TEMP1, RF_TEMP1_MEAS_START);
while ((readReg(REG_TEMP1) & RF_TEMP1_MEAS_RUNNING));
while ((readReg(REG_TEMP1) & RF_TEMP1_MEAS_RUNNING)) {}
return ~readReg(REG_TEMP2) + COURSE_TEMP_COEF + calFactor; // 'complement' corrects the slope, rising temp = rising val
} // COURSE_TEMP_COEF puts reading in the ballpark, user can add additional correction
void RFM69::rcCalibration()
{
writeReg(REG_OSC1, RF_OSC1_RCCAL_START);
while ((readReg(REG_OSC1) & RF_OSC1_RCCAL_DONE) == 0x00);
}
while ((readReg(REG_OSC1) & RF_OSC1_RCCAL_DONE) == 0x00) {}
}
+9 -3
View File
@@ -79,9 +79,15 @@ void SPIClass::setClockDivider(uint16_t divider) {
}
void SPIClass::chipSelect(int csn_pin) {
if (csn_pin == RPI_GPIO_P1_26) csn_pin = BCM2835_SPI_CS1;
else if (csn_pin == RPI_GPIO_P1_24) csn_pin = BCM2835_SPI_CS0;
else csn_pin = BCM2835_SPI_CS0;
if (csn_pin == RPI_GPIO_P1_26) {
csn_pin = BCM2835_SPI_CS1;
}
else if (csn_pin == RPI_GPIO_P1_24) {
csn_pin = BCM2835_SPI_CS0;
}
else {
csn_pin = BCM2835_SPI_CS0;
}
bcm2835_spi_chipSelect(csn_pin);
delayMicroseconds(5);
}
+41 -32
View File
@@ -7,28 +7,28 @@
// > Updated Jan. 5, 2015, TomWS1, modified writeBytes to allow blocks > 256 bytes and handle page misalignment.
// > Updated Feb. 26, 2015 TomWS1, added support for SPI Transactions (Arduino 1.5.8 and above)
// > Selective merge by Felix after testing in IDE 1.0.6, 1.6.4
// > Updated May 19, 2016 D-H-R, added support for SST25/Microchip Flash which does not support Page programming with OPCode 0x02,
// > Updated May 19, 2016 D-H-R, added support for SST25/Microchip Flash which does not support Page programming with OPCode 0x02,
// > use define MY_SPIFLASH_SST25TYPE for SST25 Type Flash Memory
// **********************************************************************************
// License
// **********************************************************************************
// This program is free software; you can redistribute it
// and/or modify it under the terms of the GNU General
// Public License as published by the Free Software
// Foundation; either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will
// be useful, but WITHOUT ANY WARRANTY; without even the
// implied warranty of MERCHANTABILITY or FITNESS FOR A
// PARTICULAR PURPOSE. See the GNU General Public
// License for more details.
//
// You should have received a copy of the GNU General
// This program is free software; you can redistribute it
// and/or modify it under the terms of the GNU General
// Public License as published by the Free Software
// Foundation; either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will
// be useful, but WITHOUT ANY WARRANTY; without even the
// implied warranty of MERCHANTABILITY or FITNESS FOR A
// PARTICULAR PURPOSE. See the GNU General Public
// License for more details.
//
// You should have received a copy of the GNU General
// Public License along with this program.
// If not, see <http://www.gnu.org/licenses/>.
//
// Licence can be viewed at
//
// Licence can be viewed at
// http://www.gnu.org/licenses/gpl-3.0.txt
//
// Please maintain this license information along with authorship
@@ -81,7 +81,7 @@ void SPIFlash::unselect() {
//restore SPI settings to what they were before talking to the FLASH chip
#ifdef SPI_HAS_TRANSACTION
SPI.endTransaction();
#else
#else
interrupts();
#endif
#ifndef ESP8266
@@ -104,7 +104,7 @@ boolean SPIFlash::initialize()
unselect();
wakeup();
if (_jedecID == 0 || readDeviceId() == _jedecID) {
command(SPIFLASH_STATUSWRITE, true); // Write Status Register
SPI.transfer(0); // Global Unprotect
@@ -142,8 +142,9 @@ uint8_t* SPIFlash::readUniqueId()
SPI.transfer(0);
SPI.transfer(0);
SPI.transfer(0);
for (uint8_t i=0;i<8;i++)
for (uint8_t i=0;i<8;i++) {
UNIQUEID[i] = SPI.transfer(0);
}
unselect();
return UNIQUEID;
}
@@ -166,8 +167,9 @@ void SPIFlash::readBytes(uint32_t addr, void* buf, uint16_t len) {
SPI.transfer(addr >> 8);
SPI.transfer(addr);
SPI.transfer(0); //"dont care"
for (uint16_t i = 0; i < len; ++i)
for (uint16_t i = 0; i < len; ++i) {
((uint8_t*) buf)[i] = SPI.transfer(0);
}
unselect();
}
@@ -239,12 +241,12 @@ void SPIFlash::writeBytes(uint32_t addr, const void* buf, uint16_t len) {
uint16_t i=0;
uint8_t oddAdr=0;
char s[5];
command(SPIFLASH_AAIWORDPROGRAM, true); // Byte/Page Program
SPI.transfer(addr >> 16);
SPI.transfer(addr >> 8);
SPI.transfer(addr);
if (addr%2){
//start address is not even, i.e. first byte of word must be 0xff
SPI.transfer(0xff);
@@ -252,25 +254,31 @@ void SPIFlash::writeBytes(uint32_t addr, const void* buf, uint16_t len) {
unselect();
oddAdr=1; //following addresses must all be shifted one off
len--;
if (len > 0) command(SPIFLASH_AAIWORDPROGRAM); //If for loop will run issue Wordprogram command
if (len > 0) {
command(SPIFLASH_AAIWORDPROGRAM); //If for loop will run issue Wordprogram command
}
}
for (i=0;i<(len/2);i++){
//AAI command must be set before every new word
if (i>0) command(SPIFLASH_AAIWORDPROGRAM); //Wordprogram command for first write has been issued before
if (i>0) {
command(SPIFLASH_AAIWORDPROGRAM); //Wordprogram command for first write has been issued before
}
SPI.transfer(((uint8_t*) buf)[i*2+oddAdr]);
SPI.transfer(((uint8_t*) buf)[i*2+1+oddAdr]);
unselect();
}
if (len-i*2 == 1){
//There is one byte (i.e. half word) left. This happens if len was odd or (len was even and addr odd)
if (i>0) command(SPIFLASH_AAIWORDPROGRAM); //if for loop had not run wordprogram command from before is still valid
if (i>0) {
command(SPIFLASH_AAIWORDPROGRAM); //if for loop had not run wordprogram command from before is still valid
}
SPI.transfer(((uint8_t*) buf)[i*2+oddAdr]);
SPI.transfer(0xff);
unselect();
}
command(SPIFLASH_WRITEDISABLE); //end AAI programming
unselect();
#else
@@ -284,11 +292,12 @@ void SPIFlash::writeBytes(uint32_t addr, const void* buf, uint16_t len) {
SPI.transfer(addr >> 16);
SPI.transfer(addr >> 8);
SPI.transfer(addr);
for (uint16_t i = 0; i < n; i++)
SPI.transfer(((uint8_t*) buf)[offset + i]);
for (uint16_t i = 0; i < n; i++) {
SPI.transfer(((uint8_t*) buf)[offset + i]);
}
unselect();
addr+=n; // adjust the addresses and remaining bytes by what we've just transferred.
offset +=n;
len -= n;