bool HanResponse::checkChecksum() { uint16_t *checksum = (uint16_t *) &frame[CHECKSUM]; if (*checksum == calculateChecksum()) { return true; } return false; }
SerialCommand flashDownloadStart(unsigned int totalSize, unsigned int numberOfBlocks, unsigned int blockSize, unsigned int offset) { QByteArray data; data.append(ByteArrayHelpers::uint32ToByteArrayLittle(totalSize)); data.append(ByteArrayHelpers::uint32ToByteArrayLittle(numberOfBlocks)); data.append(ByteArrayHelpers::uint32ToByteArrayLittle(blockSize)); data.append(ByteArrayHelpers::uint32ToByteArrayLittle(offset)); QByteArray command = buildCommand(Opcode_FlashDownloadStart, data, calculateChecksum(data)); QByteArray expectedResponse; expectedResponse.append(0x01); expectedResponse.append(Opcode_FlashDownloadStart); expectedResponse.append(ByteArrayHelpers::uint16ToByteArrayLittle(2)); expectedResponse.append((char)0x07); expectedResponse.append((char)0x07); expectedResponse.append((char)0x12); expectedResponse.append((char)0x20); expectedResponse.append((char)0x00); expectedResponse.append((char)0x00); return SerialCommand("flashDownloadStart", slipEncode(command), slipEncode(expectedResponse)); }
/** * @brief Checks CRC of frame * * @param buffer Buffer containing message to check * @param msgLength Length of message in bytes * * @return success/failure */ sInt32_t rsi_validateFrame( uInt8_t *buffer, uInt16_t msgLength ) { uInt8_t crcVal[CRC_SIZE]; // CRC value sInt32_t retVal = STATUS_FAILURE; // Variable for Return value //assume frame has CRC... calculateCrc( buffer, msgLength-2, crcVal); //uInt32_t crc = (crcVal[1] << 8) | crcVal[0]; //printf("expected crc = 0x%04x\n", crc); if ((crcVal[CRC_LSB_INDEX] == buffer[msgLength - 2]) && (crcVal[CRC_MSB_INDEX] == buffer[msgLength - 1])) { //printf("validate CRC: OK!\n"); retVal = STATUS_SUCCESS; } else { //frame must have 1-byte checksum... uInt8_t checkSum = calculateChecksum( buffer, msgLength-1 ); if (checkSum == buffer[msgLength - 1]) { //printf("validate checksum: OK!\n"); retVal = STATUS_SUCCESS; } else printf("invalid RSI frame check sequence!\n"); } //FIXME: validate RSD/ACP frame address here? return retVal; }
int sendACK(int seq_num, int sockfd,struct sockaddr *dest_addr,socklen_t addrlen){ char *ACK[sizeof(uint32_t)+sizeof(uint16_t)+3]; void *offset = ACK; uint32_t seqOut = htonl((uint32_t)seq_num); memcpy(offset,&seqOut,sizeof(uint32_t)); char *msg = "ACK"; uint16_t checkSum = calculateChecksum(&seqOut,sizeof(uint32_t)); checkSum += calculateChecksum(msg,3); checkSum = 0xffff - checkSum; offset+=sizeof(uint32_t); memcpy(offset,&checkSum,sizeof(uint16_t)); offset+=sizeof(uint16_t); memcpy(offset,msg,3); int n = sendto(sockfd,ACK,sizeof(ACK),0,dest_addr,addrlen); return n; }
SerialCommand flashDownloadData(unsigned int sequence, QByteArray flashData) { QByteArray data; data.append(ByteArrayHelpers::uint32ToByteArrayLittle(flashData.length())); data.append(ByteArrayHelpers::uint32ToByteArrayLittle(sequence)); data.append(ByteArrayHelpers::uint32ToByteArrayLittle(0)); // Mystery value data.append(ByteArrayHelpers::uint32ToByteArrayLittle(0)); // Mystery value data.append(flashData); QByteArray command = buildCommand(Opcode_FlashDownloadData, data, calculateChecksum(flashData)); QByteArray expectedResponse; expectedResponse.append(0x01); expectedResponse.append(Opcode_FlashDownloadData); expectedResponse.append(ByteArrayHelpers::uint16ToByteArrayLittle(2)); expectedResponse.append((char)0x07); expectedResponse.append((char)0x07); expectedResponse.append((char)0x12); expectedResponse.append((char)0x20); expectedResponse.append((char)0x00); expectedResponse.append((char)0x00); return SerialCommand("flashDownloadData", slipEncode(command), slipEncode(expectedResponse)); }
//--------------------------------------------------------------------- StreamSerialiser::Chunk* StreamSerialiser::readChunkImpl() { Chunk *chunk = OGRE_NEW Chunk(); chunk->offset = static_cast<uint32>(mStream->tell()); read(&chunk->id); read(&chunk->version); read(&chunk->length); uint32 checksum; read(&checksum); if (checksum != calculateChecksum(chunk)) { // no good, this is an invalid chunk uint32 off = chunk->offset; OGRE_DELETE chunk; OGRE_EXCEPT(Exception::ERR_INVALID_STATE, "Corrupt chunk detected in stream " + mStream->getName() + " at byte " + StringConverter::toString(off), "StreamSerialiser::readChunkImpl"); } else { return chunk; } }
// ping message void createPingMessage(Message* m, int length) { printf("%sMessage: PingRequest\n", KGRN); configMessage(m, PingConfigurationObject, length); uint16_t rv = calculateChecksum(m); printf("Calculated checksum: %04x\n", rv); }
// custom message with TX_GAIN=31 dB void createCustomRequestMessage31dB(Message* m, int length) { printf("%sMessage: MIB_WriteRequest - TX_GAIN=31 dB\n", KGRN); configMessage(m, CustomConfigurationObject31dB, length); uint16_t rv = calculateChecksum(m); printf("Calculated checksum: %04x\n", rv); }
bool Frames::checkResFrame() { uint16_t *location = (uint16_t *) &response[CHECKSUM]; if(*location != calculateChecksum(response)){ return false; } else { return true; } }
bool isChecksumOkIa6b(const uint8_t *ibusPacket, const uint8_t length) { uint16_t calculatedChecksum = calculateChecksum(ibusPacket, length); // Note that there's a byte order swap to little endian here return (calculatedChecksum >> 8) == ibusPacket[length - 1] && (calculatedChecksum & 0xFF) == ibusPacket[length - 2]; }
void closeMessage(char *message) { size_t messageLength = strlen(message); int checksum = calculateChecksum(&(message[1]), messageLength - 1); message[messageLength++] = '*'; sprintf(&(message[messageLength]), "%02X", checksum); messageLength += 2; sprintf(&(message[messageLength]), "\r\n"); }
// physical message void createPhysicalRequestMessage(Message* m, int length) { printf("%sMessage: MIB_WriteRequest\n", KGRN); configMessage(m, PhysicalConfigurationObject, length); uint16_t rv = calculateChecksum(m); printf("Calculated checksum: %04x\n", rv); }
bool writeEEPROM(void) { // Generate compile time error if the config does not fit in the reserved area of flash. BUILD_BUG_ON(sizeof(master_t) > FLASH_TO_RESERVE_FOR_CONFIG); FLASH_Status status = 0; uint32_t wordOffset; int8_t attemptsRemaining = 3; bool changed; // prepare checksum/version constants masterConfig.version = EEPROM_CONF_VERSION; masterConfig.size = sizeof(master_t); masterConfig.magic_be = 0xBE; masterConfig.magic_ef = 0xEF; masterConfig.chk = 0; // erase checksum before recalculating masterConfig.chk = calculateChecksum((const uint8_t *) &masterConfig, sizeof(master_t)); changed = (memcmp((const master_t *)CONFIG_START_FLASH_ADDRESS, &masterConfig, sizeof(master_t)) != 0); // write it if(changed) { FLASH_Unlock(); while (attemptsRemaining--) { #ifdef STM32F303 FLASH_ClearFlag(FLASH_FLAG_EOP | FLASH_FLAG_PGERR | FLASH_FLAG_WRPERR); #endif #ifdef STM32F10X FLASH_ClearFlag(FLASH_FLAG_EOP | FLASH_FLAG_PGERR | FLASH_FLAG_WRPRTERR); #endif for (wordOffset = 0; wordOffset < sizeof(master_t); wordOffset += 4) { if (wordOffset % FLASH_PAGE_SIZE == 0) { status = FLASH_ErasePage(CONFIG_START_FLASH_ADDRESS + wordOffset); if (status != FLASH_COMPLETE) { break; } } status = FLASH_ProgramWord(CONFIG_START_FLASH_ADDRESS + wordOffset, *(uint32_t *) ((char *) &masterConfig + wordOffset)); if (status != FLASH_COMPLETE) { break; } } if (status == FLASH_COMPLETE) { break; } } FLASH_Lock(); // Flash write failed - just die now if (status != FLASH_COMPLETE || !isEEPROMContentValid()) { failureMode(10); } } return changed; }
void Frames::createRequest(const uint16_t *lockID, const uint32_t *userID, const uint16_t *pincode, const uint8_t *flags, const uint8_t *data) { emptyFrame(request, sizeof(request)); setReqLockID(lockID); setReqUserID(userID); setReqPin(pincode); setReqFlags(flags); setReqData(data); uint16_t *location = (uint16_t *) &request[CHECKSUM]; *location = calculateChecksum(request); }
void createPingRequestMessage(Message* m, int length) { printf("Message: PingRequest\n"); m->stx = 0x02; m->length = (uint8_t)PingRequest_Length; m->command = PingRequest; memcpy(m->data, dataPingRequest, sizeof(dataPingRequest)); calculateChecksum(m->length, m->command, m->data); }
FILE* safeLoadFile(char* filename) { char checksum = calculateChecksum(filename); FILE* fp = NULL; if ( checksum != 0 || fopen_s(&fp, filename, "rbc") != 0 ) { // uh-oh! file problem. is there a backup? char bakFilename[256] = "backup/"; strcat_s(bakFilename, 256, filename); checksum = calculateChecksum(bakFilename); if ( checksum != 0 || fopen_s(&fp, bakFilename, "rbc") != 0 ) { return NULL; // oh darn } } return fp; }
int isCorrupt(PacketData* packet) { unsigned short checksum = calculateChecksum(packet); if (checksum != packet->checksum) return 1; return 0; }
// request message with TX_GAIN=31 dB void createMibWriteRequestMessage31dB(Message* m, int length) { printf("Message: MIB_WriteRequest - TX_GAIN=31 dB, Data=0x77\n"); m->stx = 0x02; m->length = MIB_WriteRequest_Length; m->command = MIB_WriteRequest; memcpy(m->data, dataMibWriteRequest31dB, sizeof(dataMibWriteRequest31dB)); calculateChecksum(m->length, m->command, m->data); }
// custom configuration, i.e TX_GAIN is a part of the message void createDlDataRequestMessage31dB(Message* m, int length) { printf("Message: DL_DataRequest with Custom configuration of TX_GAIN=31 dB, Data=0x77\n"); m->stx = 0x02; m->length = DL_DataRequest_LengthCustom; m->command = DL_DataRequest; memcpy(m->data, dataDlDataRequest_TxGain31, sizeof(dataDlDataRequest_TxGain31)); calculateChecksum(m->length, m->command, m->data); }
// PHY configuration void createDlDataRequestMessagePhy(Message* m, int length) { printf("Message: DL_DataRequest with PHY configuration of TX_GAIN\n"); m->stx = 0x02; m->length = DL_DataRequest_LengthPhy; m->command = DL_DataRequest; memcpy(m->data, dataDlDataRequest_PHY, sizeof(dataDlDataRequest_PHY)); calculateChecksum(m->length, m->command, m->data); }
static uint8_t transmitIbusPacket(uint8_t *ibusPacket, size_t payloadLength) { uint16_t checksum = calculateChecksum(ibusPacket, payloadLength + IBUS_CHECKSUM_SIZE); for (size_t i = 0; i < payloadLength; i++) { serialWrite(ibusSerialPort, ibusPacket[i]); } serialWrite(ibusSerialPort, checksum & 0xFF); serialWrite(ibusSerialPort, checksum >> 8); return payloadLength + IBUS_CHECKSUM_SIZE; }
uint8_t updateNewConfig() { memset(&board_temp,0,sizeof(board_temp)); getInvariate(&board_temp,sizeof(board_temp)); //得到之前flash中的数据 if(calculateChecksum(&board_temp,sizeof(board_temp),18) != calculateChecksum(&board,sizeof(board),18)){ //判断两个board的检验和是否相同 //updateInvariate(&board,sizeof(board)); if(updateInvariate(&board,sizeof(board))){//向Flash中写入数据 //printf("update flash sucessful\n\r"); return 1; } else{ //printf("update flash failed\n\r"); return 0; } }else{ //printf("not need update flash\n\r"); return 2; } //return Update_InVariate(&board,sizeof(BOARD)); }
void ClientAJAKumoTCP::parseIncoming(uint8_t *buffer, uint8_t len) { if(buffer[0] == 0x01 && buffer[len-1] == 0x04) { uint16_t checksum = calculateChecksum(buffer, len-3); if(checksum == (buffer[len-3]<<8) | buffer[len-2]) { if(buffer[3] == 'E' && buffer[4] == 'R') { if(buffer[6] == '0' && buffer[7] == '0') { if(_serialOutput > 1) { Serial << "OK\n"; } } else { if(_serialOutput > 1) { Serial << "Received error response from AJA KUMO\n"; } } } else { char cmd[3]; char parameter[11]; char data[21]; memset(cmd, 0, 3); memset(parameter, 0, 11); memset(data, 0, 21); cmd[0] = buffer[4]; cmd[1] = buffer[3]; uint8_t i = 5; uint8_t pos = 0; while(i++ < len-3) { if(buffer[i] == 0x09 || pos++ == 10) { strncpy(parameter, (char*)(buffer+i-pos), pos); break; } } strncpy(data, (char*)(buffer+i), len-i-4 > 20 ? 20 : len-i-4); handleCmd(cmd, parameter, data); } } else { if(_serialOutput > 1) { Serial << "Checksum mismatch!\n"; } } } else { if(_serialOutput > 1) Serial << "ERROR: Malformed packet\n"; } }
void getMoistureReading(char plant) { if (plant < 0 || plant >= NUM_PLANTS) { handleError('S', 1); return; } char outStr[3] = {'M', plant, '0'}; outStr[2] = calculateChecksum(outStr, 2); write(serial[activePort], outStr, 3); printf("Requesting moisture reading... "); awaitingMoistureResponse = TRUE; forPlant = plant; timeSentCommand = time(NULL); }
void setDryLevel(char plant) { if (plant != forPlant || plant < 0 || plant >= NUM_PLANTS) { handleError('S', 2); return; } char outStr[5] = {'D', plant, g_moisture & 0xFF, g_moisture >> 8, '0'}; outStr[4] = calculateChecksum(outStr, 4); write(serial[activePort], outStr, 5); printf("Sending dry level... "); awaitingDryLevelAck = TRUE; forPlant = plant; timeSentCommand = time(NULL); }
void sendConfiguration(char* buf) { int i; char outStr[CONFIG_BLOCK_SIZE+2]; for (i = 0; i < CONFIG_BLOCK_SIZE+1; i++) { outStr[i] = buf[i]; } outStr[CONFIG_BLOCK_SIZE+1] = calculateChecksum(outStr, CONFIG_BLOCK_SIZE+1); //assert(validateChecksum(outStr, CONFIG_BLOCK_SIZE+2)); write(serial[activePort], outStr, CONFIG_BLOCK_SIZE+2); printf("Sending configuration... "); awaitingConfigurationAck = TRUE; timeSentCommand = time(NULL); }
int LedDeviceP9813::write(const std::vector<ColorRgb> &ledValues) { if (_ledCount != ledValues.size()) { _ledBuf.resize(ledValues.size() * 4 + 8, 0x00); _ledCount = ledValues.size(); } uint8_t * dataPtr = _ledBuf.data(); for (const ColorRgb & color : ledValues) { *dataPtr++ = calculateChecksum(color); *dataPtr++ = color.blue; *dataPtr++ = color.green; *dataPtr++ = color.red; } return writeBytes(_ledBuf.size(), _ledBuf.data()); }
void safeCloseFile(FILE* fp, char* filename) { fflush(fp); fclose(fp); // calculate the checksum and append it to the original file FILE* oldfile = NULL; char checksum = calculateChecksum(filename); if ( fopen_s(&oldfile, filename, "a+b") != 0 ) // if an error happens while appending the checksum then the resulting file will be interpreted as corrupt later, bummer { TRACE("ERROR APPENDING CHECKSUM"); } else { fprintf_s(oldfile, "%c", -checksum); fclose(oldfile); makeBackupFile(filename); } }
static int writePacket (BrailleDisplay *brl, unsigned char code, const void *data, unsigned char length) { MD_Packet packet; unsigned char *byte = packet.fields.data.bytes; packet.fields.soh = SOH; packet.fields.stx = STX; packet.fields.etx = ETX; packet.fields.code = code; packet.fields.length = length; byte = mempcpy(byte, data, length); uint16_t checksum = calculateChecksum(&packet.fields.stx, byte); *byte++ = checksum & 0XFF; *byte++ = checksum >> 8; return writeBytes(brl, packet.bytes, byte-packet.bytes); }
// FIXME: HAL for now this will only work for F4/F7 as flash layout is different void writeEEPROM(void) { // Generate compile time error if the config does not fit in the reserved area of flash. BUILD_BUG_ON(sizeof(master_t) > FLASH_TO_RESERVE_FOR_CONFIG); HAL_StatusTypeDef status; uint32_t wordOffset; int8_t attemptsRemaining = 3; suspendRxSignal(); // prepare checksum/version constants masterConfig.version = EEPROM_CONF_VERSION; masterConfig.size = sizeof(master_t); masterConfig.magic_be = 0xBE; masterConfig.magic_ef = 0xEF; masterConfig.chk = 0; // erase checksum before recalculating masterConfig.chk = calculateChecksum((const uint8_t *) &masterConfig, sizeof(master_t)); // write it /* Unlock the Flash to enable the flash control register access *************/ HAL_FLASH_Unlock(); while (attemptsRemaining--) { /* Fill EraseInit structure*/ FLASH_EraseInitTypeDef EraseInitStruct = {0}; EraseInitStruct.TypeErase = FLASH_TYPEERASE_SECTORS; EraseInitStruct.VoltageRange = FLASH_VOLTAGE_RANGE_3; // 2.7-3.6V EraseInitStruct.Sector = (FLASH_SECTOR_TOTAL-1); EraseInitStruct.NbSectors = 1; uint32_t SECTORError; status = HAL_FLASHEx_Erase(&EraseInitStruct, &SECTORError); if (status != HAL_OK) { continue; } else { for (wordOffset = 0; wordOffset < sizeof(master_t); wordOffset += 4) { status = HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, CONFIG_START_FLASH_ADDRESS + wordOffset, *(uint32_t *) ((char *) &masterConfig + wordOffset)); if(status != HAL_OK) { break; } } } if (status == HAL_OK) { break; } } HAL_FLASH_Lock(); // Flash write failed - just die now if (status != HAL_OK || !isEEPROMContentValid()) { failureMode(FAILURE_FLASH_WRITE_FAILED); } resumeRxSignal(); }