//controlleer de CRC
//cursor is op 0 gezet
//process eerst de header
//dan de payload, als die er is
//dan de ontvangen en berekende CRC met elkaar vegelijk
//zijn ze hetzelfde, dan state = PROCESS_PAYLOAD
//anders error
void GPSTP::_processCRC() {
  //crc of header part
  if (_cursor < HEADER_LENGHT) {
    _crcCalculaded = _crc16_update(_crcCalculaded, _header[_cursor]);
    //_serial->println("CRC Header proccesing");
  }

  //crc of payload part
  else if (_cursor < HEADER_LENGHT + _payloadLen) {
    _crcCalculaded = _crc16_update(_crcCalculaded, _payload[_cursor - HEADER_LENGHT]);
  }

  //check CRC
  else {
    if (_crcCalculaded == _crcRecieved) {
      _state = PROCESS_PAYLOAD;
    }
    else {
      _errorHandler(CRC_ERROR);
    }
  }

  //de volgende locatie, voor de volgende run
  _cursor++;
}
int modbus()
{
	
	if(data[0]!=slave_id) return 2;

	uint16_t modbus_crc=0xFFFF;

	for(i=0; i<(rx_len-2); i++)
	{
		modbus_crc=_crc16_update(modbus_crc, data[i]);
	}


	uint8_t modbus_crc_l=modbus_crc>>8;
	uint8_t modbus_crc_h=modbus_crc;

	if((modbus_crc_h!=data[rx_len-2]) | (modbus_crc_l!=data[rx_len-1])) return 2; // Error CRC.

	function=data[1];
	switch(function)
	{

	case COMMAND_HOLDING_REG: return(read_holding_reg()); break;

	case COMMAND_INPUT_REG: return(read_input_reg()); break;

	case COMMAND_WRITE_REG: return(write_reg()); break;

	}
	

	//Ilegal Function///

	char data_err[5]={slave_id, 0x83, 0x01, 0xFF, 0xFF};

	modbus_crc=0xFFFF;
	for(i=0; i<(sizeof(data_err)-2); i++)
	{
		modbus_crc=_crc16_update(modbus_crc, data_err[i]);
	}

	data_err[(sizeof(data_err)-2)]=modbus_crc;
	data_err[(sizeof(data_err)-1)]=modbus_crc>>8;

	for(i=0; i<sizeof(data_err); i++)
	{
		usart0_write(data_err[i]);
	}


return 1;	
}
Example #3
0
/// @details
/// Handles a RFM12 interrupt depending on rxstate and the status reported by the RF
/// module. 
static void rf12_interrupt() {
    uint8_t in;
    state = rf12_xferState(&in);
    
    // data received or byte needed for sending
    if (state & RF_FIFO_BIT) {
	
	    if (rxstate == TXRECV) {  // we are receiving

            if (rxfill == 0 && group != 0)
                rf12_buf[rxfill++] = group;

            rf12_buf[rxfill++] = in;
        	rf12_crc = _crc16_update(rf12_crc, in);

    	    // do drssi binary-tree search
	        if ( drssi < 3 && ((rxfill-2)%drssi_bytes_per_decision)==0 ) {// not yet final value
	        	// top nibble when going up, bottom one when going down
	        	drssi = bitRead(state,8)
	        			? (drssi_dec_tree[drssi] & B1111)
	        			: (drssi_dec_tree[drssi] >> 4);
	            if ( drssi < 3 ) {     // not yet final destination, set new threshold
                	rf12_xfer(RF_RECV_CONTROL | drssi*2+1);
            	}
           	}

			// check if we got all the bytes (or maximum packet length was reached)
			if (fixedLength) {
				if (rxfill >= fixedLength || rxfill >= RF_MAX) {
					rf12_idle();
				}
			} else if (rxfill >= rf12_len + 5 || rxfill >= RF_MAX) {
       	    	rf12_idle();
			}
    	} else {                  // we are sending
Example #4
0
static bool check_crc(void) {
  uint8_t *eeprom_addr = (uint8_t *)EEPROM_ADDR;
  uint16_t crc = ~0;
  for (uint16_t i=0; i<config_sz; i++)
    crc = _crc16_update(crc, eeprom_read_byte(eeprom_addr + i));
  return crc == 0;
}
Example #5
0
static void write_crc(void) {
  uint8_t *eeprom_addr = (uint8_t *)EEPROM_ADDR;
  uint16_t crc = ~0;
  for (uint16_t i=0; i<config_sz-2; i++)
    crc = _crc16_update(crc, eeprom_read_byte(eeprom_addr + i));
  eeprom_write_word((uint16_t*)(eeprom_addr+config_sz-2), crc);
}
Example #6
0
uint8_t Rfm12b::Send (uint8_t* Data, uint8_t Length) {
	uint8_t i;
	
	RFM12_INT_OFF();
	if ((InputLength > 0) ||
        (Rfm12bSpi.GetWord (RFM12B_STATUS_CMD) & RFM12B_STATUS_RSSI_PIN) != 0) {
        // either already receiving something or RFM12B detects a 
        // signal, so don't send now
	    RFM12_INT_ON();
	    return 0;
        }        
	Rfm12bSpi.SendWord (RF_IDLE_MODE);      // switch off receiver
	OutputData[LENGTH_BYTE] = Length + 2;   // include 2 crc bytes in length
    memcpy ((void*) &OutputData[LENGTH_BYTE+1], Data, Length);
	OutputLength = Length + LENGTH_BYTE + 1;    // include 4 preamble bytes + 1 Length byte
    // calculate crc and put it into output buffer
	Crc = ~0;
	for (i=0; i <= Length; i++)
		Crc = _crc16_update(Crc, OutputData[i+4]);
	OutputData[OutputLength++] = Crc & 0xFF;
	OutputData[OutputLength++] = Crc >> 8;
    // add trailer byte to end of packet to ensure last byte of data is transmitted completely
	OutputData[OutputLength] = PREAMBLE;
    // pre-load preamble byte into transmit buffer to get things going quickly
	Rfm12bSpi.SendWord (RFM12B_TX_CMD + PREAMBLE);
    // turn on transmitter
    Rfm12bSpi.SendWord (RF_XMITTER_ON); // bytes will be fed via interrupts
	RFM12_INT_ON();
    return Length;
	}
/** block-at-once CRC16 calculator
	\param *data data to find crc16 for
	\param len length of data
	\return uint16 crc16 of passed data

	uses avr-libc's optimised crc16 routine
*/
uint16_t	crc_block(void *data, uint16_t len) {
	uint16_t	crc = 0;
	for (; len; data++, len--) {
		crc = _crc16_update(crc, *((uint8_t *) data));
	}
	return crc;
}
Example #8
0
/// @details
/// This calls rf12_initialize() with settings obtained from EEPROM address
/// 0x20 .. 0x3F. These settings can be filled in by the RF12demo sketch in the
/// RFM12B library. If the checksum included in those bytes is not valid, 
/// rf12_initialize() will not be called.
///
/// As side effect, rf12_config() also writes the current configuration to the
/// serial port, ending with a newline.
/// @returns the node ID obtained from EEPROM, or 0 if there was none.
uint8_t rf12_config (uint8_t show) {
    uint16_t crc = ~0;
    for (uint8_t i = 0; i < RF12_EEPROM_SIZE; ++i)
        crc = _crc16_update(crc, eeprom_read_byte(RF12_EEPROM_ADDR + i));
    if (crc != 0)
        return 0;
        
    uint8_t nodeId = 0, group = 0;
    for (uint8_t i = 0; i < RF12_EEPROM_SIZE - 2; ++i) {
        uint8_t b = eeprom_read_byte(RF12_EEPROM_ADDR + i);
        if (i == 0)
            nodeId = b;
        else if (i == 1)
            group = b;
        else if (b == 0)
            break;
        else if (show)
            Serial.print((char) b);
    }
    if (show)
        Serial.println();
    
    rf12_initialize(nodeId, nodeId >> 6, group);
    return nodeId & RF12_HDR_MASK;
}
void CONFIG_SaveTemporalConfig()
{
	uint16_t eeprom_size = sizeof(CONFIG_HEADER_t) + sizeof(NETWORK_CONFIG_t);
	uint16_t acc = 0;
	
	runningConfiguration.topConfiguration.configHeader.checkSum = 0;
	runningConfiguration.topConfiguration.configHeader.firmVersion = 0xFF;
	runningConfiguration.topConfiguration.configHeader.length = eeprom_size;
	runningConfiguration.topConfiguration.configHeader.systemFlags.raw = 0;
	
	if(VALID_DATETIME)
	{
		runningConfiguration.topConfiguration.configHeader.updateDate = currentDate;
		runningConfiguration.topConfiguration.configHeader.updateTime = currentTime;
		runningConfiguration.topConfiguration.configHeader.updateWeekDay = currentWeek;
	}
	
	//Compute checksum
	for(int i = 0; i < eeprom_size; i++)
	acc = _crc16_update(acc, runningConfiguration.raw[i]);
	
	runningConfiguration.topConfiguration.configHeader.checkSum = acc;
	
	EEPROM_Write_Block(&runningConfiguration, 0x00, eeprom_size);
}
Example #10
0
static void rf12_interrupt () {
    // a transfer of 2x 16 bits @ 2 MHz over SPI takes 2x 8 us inside this ISR
    // correction: now takes 2 + 8 µs, since sending can be done at 8 MHz
    rf12_xfer(0x0000);

    if (rxstate == TXRECV) {
        uint8_t in = rf12_xferSlow(RF_RX_FIFO_READ);

        if (rxfill == 0 && group != 0)
            rf12_buf[rxfill++] = group;

        rf12_buf[rxfill++] = in;
        rf12_crc = _crc16_update(rf12_crc, in);

        if (rxfill >= rf12_len + 5 || rxfill >= RF_MAX)
            rf12_xfer(RF_IDLE_MODE);
    } else {
        uint8_t out;

        if (rxstate < 0) {
            uint8_t pos = 3 + rf12_len + rxstate++;
            out = rf12_buf[pos];
            rf12_crc = _crc16_update(rf12_crc, out);
        } else
            switch (rxstate++) {
            case TXSYN1:
                out = 0x2D;
                break;
            case TXSYN2:
                out = group;
                rxstate = - (2 + rf12_len);
                break;
            case TXCRC1:
                out = rf12_crc;
                break;
            case TXCRC2:
                out = rf12_crc >> 8;
                break;
            case TXDONE:
                rf12_xfer(RF_IDLE_MODE); // fall through
            default:
                out = 0xAA;
            }

        rf12_xfer(RF_TXREG_WRITE + out);
    }
}
Example #11
0
uint16_t EnduranceEeprom::memCrc16(uint16_t addr, size_t len)
{
  uint16_t crc = 0xFFFF;
  for (uint16_t i=0; i<len; i++) {
    crc = _crc16_update(crc, m_eeprom.read_byte(addr++));
  }
  return crc;
}
void sserial_sendbyte(byte bt)
{
	uart_send(sserial_portindex,bt);sserial_crc16=_crc16_update(sserial_crc16,bt);
	if (bt==0x98)
	{
		uart_send(sserial_portindex,0);
	}
}
Example #13
0
static uint16_t calcCRCrom (const void* ptr, uint16_t len) {
	// init 0xFFFF
	uint16_t crc = ~0;
	for (uint16_t i = 0; i < len; i++) {
		crc = _crc16_update(crc, pgm_read_byte((uint16_t) ptr + i));
	}
	return crc;
}
Example #14
0
static void rf12_interrupt() {
    // a transfer of 2x 16 bits @ 2 MHz over SPI takes 2x 8 us inside this ISR
    rf12_xfer(0x0000);
    
    if (rxstate == TXRECV) {
        uint8_t in = rf12_xfer(RF_RX_FIFO_READ);

        //if (rxfill == 0 && group != 0)
        //    rf12_buf[rxfill++] = group;

        rf12_buf[rxfill++] = in;
        rf12_crc = _crc16_update(rf12_crc, in);

        if (rxfill >= rf12_len + 2 || rxfill >= RF_MAX) {
          rf12_xfer(RF_IDLE_MODE); // receiver abschalten
          
          rxstate = TXIDLE;
          if (rf12_len > RF12_MAXDATA)
            rf12_crc = 1; // force bad crc if packet length is invalid
          
          if(receive_callback != NULL) {
            (*receive_callback)();
          }
        }
    } else {
        uint8_t out;

        if (rxstate < 0) {
            uint8_t pos = rf12_len + rxstate++;
            out = rf12_buf[pos];
            rf12_crc = _crc16_update(rf12_crc, out);
        } else
            switch (rxstate++) {
                case TXSYN1: out = 0x2D; break;
                case TXSYN2: out = 0xD4; rxstate = - (rf12_len); break;
                case TXCRC1: out = rf12_crc; break;
                case TXCRC2: out = rf12_crc >> 8; break;
                case TXDONE: rf12_xfer(RF_IDLE_MODE); 
                              //Serial.println(micros(), DEC);// fall through
                default:     out = 0xAA;
            }
            
        rf12_xfer(RF_TXREG_WRITE + out);
    }
}
Example #15
0
uint16_t checkcrc(unsigned char *data, unsigned char len) {
	uint16_t crc = 0x00;

	for (int16_t i = 0; i<len; i++) {
		crc = _crc16_update(crc, buffer[i]);
	}

	return crc;
}
Example #16
0
uint16_t
modbus_crc_calc(uint8_t *data, uint8_t len)
{
  uint16_t crc = 0xffff;
  uint8_t i = 0;
  while(i < len)
    crc = _crc16_update(crc, data[i++]);
  return crc;
}
Example #17
0
void MultidropMaster::sendByte(uint8_t b, uint8_t directionCntrl, uint8_t updateCRC) {
    if (directionCntrl) serial->enable_write();
    serial->write(b);
    if (directionCntrl) serial->enable_read();

    if (updateCRC) {
        messageCRC = _crc16_update(messageCRC, b);
    }
}
Example #18
0
void send_msg(uint8_t dirs, char *data, uint8_t dataLength, uint8_t hpFlag){
	if(dataLength>IR_BUFFER_SIZE) printf_P(PSTR("ERROR: Message exceeds IR_BUFFER_SIZE.\r\n"));
	
	uint16_t crc = getDropletID();
	for(uint8_t dir=0; dir<6; dir++){
		if(dirs&(1<<dir)){			
			uint8_t lengthAndStatusByte = dataLength;
			lengthAndStatusByte |= (ir_rxtx[dir].status & IR_STATUS_COMMAND_bm);
			lengthAndStatusByte |= (ir_rxtx[dir].status & IR_STATUS_TIMED_bm);
			crc = _crc16_update(crc, lengthAndStatusByte);
			if(!(ir_rxtx[dir].status&IR_STATUS_TIMED_bm)){
				crc = _crc16_update(crc, ir_rxtx[dir].targetID);
			}
			break;
		}	
	}

	for(uint8_t i=0; i<dataLength; i++) crc = _crc16_update(crc, data[i]); //Calculate CRC of outbound message.
	
	for(uint8_t dir=0; dir<6; dir++){
		if(dirs&(1<<dir)){
			ir_rxtx[dir].status |= IR_STATUS_TRANSMITTING_bm;
			ir_rxtx[dir].data_length = dataLength;
			ir_rxtx[dir].data_crc = crc;
			ir_rxtx[dir].curr_pos = 0;
			ir_rxtx[dir].senderID = getDropletID();
			memcpy((char*)ir_rxtx[dir].buf, data, dataLength);
			TCF2.CTRLB |= ir_carrier_bm[dir];		// Turn on carrier wave on port dir
		}
	}

	for(uint8_t dir=0; dir<6; dir++){
		if(dirs&(1<<dir)){
			ir_rxtx[dir].last_byte = 0;
			if(hpFlag){
				channel[dir]->CTRLA |= USART_DREINTLVL_HI_gc;
			}else{
				channel[dir]->CTRLA |= USART_DREINTLVL_MED_gc;			
			}
		}
	}

	/* The whole transmission will now occur in interrupts. */
}
Example #19
0
static void rf12_recvStart () {
    rxfill = rf12_len = 0;
    rf12_crc = ~0;
#if RF12_VERSION >= 2
    if (group != 0)
        rf12_crc = _crc16_update(~0, group);
#endif
    rxstate = TXRECV;    
    rf12_xfer(RF_RECEIVER_ON);
}
Example #20
0
int16_t
parse_cmd_crc_calc(char *cmd, char *output, uint16_t len)
{
  uint8_t *p;
  uint16_t crc = 0xffff;

  for (p = 0; p < (uint8_t *) CRC_BYTE_POS; p++)
    crc = _crc16_update(crc, pgm_read_byte(p));

  return ECMD_FINAL(sprintf_P(output, PSTR("%.4X"), crc));
}
Example #21
0
static uint16_t crc16_block_update(uint16_t crc, const void *_data, uint16_t size)
{
	const uint8_t *data = _data;

	while (size) {
		crc = _crc16_update(crc, *data);
		data++;
		size--;
	}

	return crc;
}
Example #22
0
void send_message(const void *message, size_t len) {
  uint8_t *ptr = (uint8_t *)message;
  uint16_t crc16 = 0;
  int i;
  for(i=0; i < len; i++) {
    TX_USART_vSendByte(*ptr);
    crc16 = _crc16_update(crc16, *ptr);
    ptr++;
  }

  // pad with zeros
  for(i=len; i < MESSAGE_LENGTH; i++) {
    TX_USART_vSendByte(0);
    crc16 = _crc16_update(crc16, 0);
  }    

  // send crc16 low byte first
  TX_USART_vSendByte((uint8_t)crc16);
  crc16 = crc16 >> 8;
  TX_USART_vSendByte((uint8_t)crc16);
}
Example #23
0
static uint16_t calculate_crc(const configuration_type* configuration) {
	uint16_t calculated_crc = 0;
	uint8_t i = 0;
	uint8_t length = sizeof(configuration_type) - 2;

	while (i < length) {
		_crc16_update(calculated_crc, *((uint8_t*)configuration + i));
		i++;
	}

	return calculated_crc;
}
Example #24
0
void rf12_sendStart (uint8_t hdr) {
    rf12_hdr = hdr & RF12_HDR_DST ? hdr :
               (hdr & ~RF12_HDR_MASK) + (nodeid & NODE_ID);
    if (crypter != 0)
        crypter(1);

    rf12_crc = ~0;
#if RF12_VERSION >= 2
    rf12_crc = _crc16_update(rf12_crc, group);
#endif
    rxstate = TXPRE1;
    rf12_xfer(RF_XMITTER_ON); // bytes will be fed via interrupts
}
Example #25
0
void send_packet(const struct data_packet *message) {
  uint8_t *ptr = (uint8_t *)message;
  uint16_t crc16 = 0;
  int i;
  for(i=0; i < MESSAGE_LENGTH; i++) {
    TX_USART_vSendByte(*ptr);
    crc16 = _crc16_update(crc16, *ptr);
    ptr++;
  }
  // send crc16 low byte first
  TX_USART_vSendByte((uint8_t)crc16);
  crc16 = crc16 >> 8;
  TX_USART_vSendByte((uint8_t)crc16);
}
Example #26
0
uint8_t MultidropMaster::checkForResponses(uint32_t time) {
    uint8_t b, i;

    if (dontTimeout) {
        timeoutTime = time + timeoutDuration;
    }
    dontTimeout = false;

    // Received all responses
    if (waitingOnNodes == 0) {
        finishMessage();
        return true;
    }

    // Get more responses
    while (serial->available()) {
        b = serial->read();
        responseBuff[responseIndex] = b;
        messageCRC = _crc16_update(messageCRC, b);

        responseIndex++;
        dontTimeout = true;

        // Have we received all the data for this node?
        if (responseIndex % dataLength == 0) {
            waitingOnNodes--;
        }
    }

    // Node timeout, send default response
    if (time > timeoutTime) {

        // It's possible the node sent a partial response, so send whatever is left
        for (i = responseIndex % dataLength; i < dataLength; i++) {
            sendByte(defaultResponseValues[i], true);
            responseBuff[responseIndex] = defaultResponseValues[i];
            responseIndex++;
        }

        dontTimeout = true;
        waitingOnNodes--;
    }

    if (waitingOnNodes == 0) {
        finishMessage();
        return true;
    }
    return false;
}
Example #27
0
static void rf12_recvStart () {
    if (rf12_fixed_pkt_len) {
        rf12_len = rf12_fixed_pkt_len;
        rf12_grp = rf12_hdr = 0;
        rxfill = 3;
    } else
        rxfill = rf12_len = 0;
    rf12_crc = ~0;
#if RF12_VERSION >= 2
    if (group != 0)
        rf12_crc = _crc16_update(~0, group);
#endif
    rxstate = TXRECV;

    rf12_xfer(RF_RECEIVER_ON);
}
void error_data_value()
{
	char data_err[5]={slave_id, 0x83, 0x03, 0xFF, 0xFF};

	uint16_t modbus_crc=0xFFFF;
	for(i=0; i<(sizeof(data_err)-2); i++)
	{
		modbus_crc=_crc16_update(modbus_crc, data_err[i]);
	}

	data_err[(sizeof(data_err)-2)]=modbus_crc;
	data_err[(sizeof(data_err)-1)]=modbus_crc>>8;

	for(i=0; i<sizeof(data_err); i++)
	{
		usart0_write(data_err[i]);
	}

}
Example #29
0
/// @details
/// This calls rf12_initialize() with settings obtained from EEPROM address
/// 0x20 .. 0x3F. These settings can be filled in by the RF12demo sketch in the
/// RFM12B library. If the checksum included in those bytes is not valid,
/// rf12_initialize() will not be called.
///
/// As side effect, rf12_config() also writes the current configuration to the
/// serial port, ending with a newline. Use rf12_configSilent() to avoid this.
/// @returns the node ID obtained from EEPROM, or 0 if there was none.
uint8_t rf12_configSilent () {
    uint16_t crc = ~0;
    for (uint8_t i = 0; i < RF12_EEPROM_SIZE; ++i) {
        byte e = eeprom_read_byte(RF12_EEPROM_ADDR + i);
        crc = _crc16_update(crc, e);
    }
    if (crc || eeprom_read_byte(RF12_EEPROM_ADDR + 2) != RF12_EEPROM_VERSION)
        return 0;

    uint8_t nodeId = 0, group = 0;
    uint16_t frequency = 0;

    nodeId = eeprom_read_byte(RF12_EEPROM_ADDR + 0);
    group  = eeprom_read_byte(RF12_EEPROM_ADDR + 1);
    frequency = eeprom_read_word((uint16_t*) (RF12_EEPROM_ADDR + 4));

    rf12_initialize(nodeId, nodeId >> 6, group, frequency);
    return nodeId & RF12_HDR_MASK;
}
Example #30
0
bool RF12Module::SaveConfig() {
	// Variables used by the macros...
	byte pos, len;
	int remainder;
	memset(msg, 0, sizeof msg);
	strcpy(msg, " ");

	byte id = nodeId & 0x1F;
	strcat(msg, " i");
	ADD_INT(msg, id);
	if (nodeId & COLLECT)
		ADD_CHAR(msg, '*');

	strcat(msg, " g");
	ADD_INT(msg, group);

	strcat(msg, " @ ");
	static word bands[4] = { 315, 433, 868, 915 };
	word band = nodeId >> 6;
	ADD_INT(msg, bands[band]);
	strcat(msg, " MHz ");

	crc = ~0;
	for (byte i = 0; i < sizeof(*this) - 2; ++i)
		crc = _crc16_update(crc, ((byte*) this)[i]);

	// save to EEPROM
	for (byte i = 0; i < sizeof(*this); ++i) {
		byte b = ((byte*) this)[i];
		eeprom_write_byte(RF12_EEPROM_ADDR + i, b);
	}
	if (!rf12_config()) {
		Serial.print(RF12_EEPROM_SIZE);
		Serial.print( " vs ");
		Serial.println(sizeof(*this));
		return false;
	}
	return true;
}