void SBBTA252::sendChangeAddressCommand(int thruster, int new_address) { // Declare variables char cmd[10]; Serial::buf_send = cmd; if (new_address < 1 || new_address > 255) { ROS_WARN("New address %d is not in the range from 1-255", new_address); return; } // Send command if (Serial::fd > 0) { cmd[0] = SBBTA252_SC; cmd[1] = getAddress(1, thruster); cmd[2] = getAddress(2, thruster); cmd[3] = '0'; // Command specific char cmd[4] = 'B'; // Command specific char cmd[5] = dec2hex(new_address / 16); cmd[6] = dec2hex(new_address % 16); cmd[7] = getChecksum(1, cmd, 10); cmd[8] = getChecksum(2, cmd, 10); cmd[9] = SBBTA252_EC; Serial::length_send = 10; send(); usleep(SBBTA252_SERIAL_DELAY); ROS_DEBUG("Changing address from %d to %d.", thruster, new_address); } } // end SendChangeAddressCommand()
void SBBTA252::sendSpeedCommand(int thruster, int speed) { // Declare variables. char cmd[10]; Serial::buf_send = cmd; // Send command. if (Serial::fd > 0) { cmd[0] = SBBTA252_SC; cmd[1] = getAddress(1, thruster); cmd[2] = getAddress(2, thruster); cmd[3] = getSpeed(1, speed); cmd[4] = getSpeed(2, speed); cmd[5] = '0'; cmd[6] = '0'; cmd[7] = getChecksum(1, cmd, 10); cmd[8] = getChecksum(2, cmd, 10); cmd[9] = SBBTA252_EC; Serial::length_send = 10; send(); usleep(SBBTA252_SERIAL_DELAY); ROS_DEBUG("Send Speed Command (%d): %s.", thruster, cmd); } } // end sendSpeedCommand()
int readData (void *theData, uint8_t theLeng) { if (theLeng > PRO_MAX) return -1; uint8_t pro_size = theLeng+3; uint8_t buffer[pro_size]; int leng = serialRead (Serial, buffer, pro_size, 4); if (leng == 0) { return 0; } if (leng != pro_size) { #ifdef _debug Serial.print ("data leng error:"); printHex (buffer, leng); #endif return -2; } if (!checksum (buffer, leng)) { #ifdef _debug Serial.println ("checksum error"); printHex (buffer, leng); Serial.print ("checksum is:"); Serial.println (getChecksum (buffer, leng-1), HEX); #endif return -3; } memcpy ((void*)theData, (void*)(buffer+2), theLeng); }
String Communication::getUnpackedMessage(String message) { // Check Start of Header if (!checkStartOfHeader(message)) { return ""; } // Parse Header int message_size = parseHeader(message); if (message_size < 0) { return ""; } // Parse Text String unpacked_message = parseText(message); if (unpacked_message == "") { return ""; } // Check Message Size if (message_size != unpacked_message.length()) { return ""; } // Compute & Compare Checksums String incoming_checksum = parseFooter(message); String computed_checksum = getChecksum(unpacked_message); if (incoming_checksum != computed_checksum) { return ""; } // Received Valid Message return unpacked_message; }
/** *Sends a message through Xbee API to a particular address *Address: XBee address to send data to *txData: data to send to desired XBee */ void sendMessage(long long xbeeAddr, char* txData){ //Calculate message length and checksum unsigned int messageLength=strlen(txData)+TX_FRAME_LENGTH_WO_TXDATA; volatile unsigned char checksum; checksum=getChecksum(TX_REQUEST,GET_FRAME_ID,&xbeeAddr,RESERVED_BYTES,MAX_BROADCAST_RAD,USE_TO_PARAM,txData); //Send Delimiter sendByte(START_DELIMITER); //Send message length sendInt(messageLength); //Send Frame type and GetFrameID sendByte(TX_REQUEST); sendByte(GET_FRAME_ID); //Send destination address sendXbeeAddr(&xbeeAddr); //Send the rest of Xbee header bytes sendInt(RESERVED_BYTES); sendByte(MAX_BROADCAST_RAD); sendByte(USE_TO_PARAM); //Send actual data sendByteArray(txData); //Send checksum sendByte(checksum); //Toggle an LED //P4OUT ^= BIT7; } //sendMessage()
bool frame::checksumIsValid() const { //mengembalikan true bila checksum benar assert(formatIsValid()); unsigned int STXpos=5; unsigned int ETXpos; for (ETXpos=STXpos; bytes[ETXpos]!=ETX; ETXpos++) {} return checkChecksum(getChecksum(),bytes.substr(0,ETXpos+1)); }
checksum_t getChecksum(ReflectableClass* object, workflow::Node* node, int flags) { boost::crc_optimal<32, 0x04C11DB7> checksum; assert(object); workflow::CollectionElement* collection = dynamic_cast<workflow::CollectionElement*>(object); std::vector<capputils::reflection::IClassProperty*>& properties = object->getProperties(); for (unsigned i = 0; i < properties.size(); ++i) { if (properties[i]->getAttribute<LabelAttribute>()) { //std::cout << /*std::endl <<*/ "Updating checksum of " << properties[i]->getStringValue(*object) << std::endl; break; } } // Add more for each parameter for (unsigned i = 0; i < properties.size(); ++i) { if (node) { if (node->isInputNode() && properties[i]->getAttribute<OutputAttribute>()) { // skip NoParameter test } else if ((flags & ChecksumUpdater::ExcludeNoParameters) == ChecksumUpdater::ExcludeNoParameters && properties[i]->getAttribute<NoParameterAttribute>()) { //std::cout << "No parameter: " << properties[i]->getName() << std::endl; continue; } // Check if the property depends on something else if ((flags & ChecksumUpdater::ExcludeDependent) == ChecksumUpdater::ExcludeDependent && node && node->isDependentProperty(properties[i]->getName())) { //std::cout << "Dependent: " << properties[i]->getName() << std::endl; continue; } } //std::cout << "Parameter: " << properties[i]->getName() << std::endl; //std::cout << properties[i]->getName() << ": "; checksum_t cs = getChecksum(properties[i], *object); //std::cout << cs << std::endl; checksum.process_bytes(&cs, sizeof(cs)); } // Add UUID of node if (node) { std::string uuid = node->getUuid(); checksum.process_bytes((void*)&uuid[0], uuid.size()); } // Add the class name std::string className = object->getClassName(); checksum.process_bytes((void*)&className[0], className.size()); // If it is a combiner class, add the progress to it if (collection && !collection->getCalculateCombinations()) { double progress = collection->getProgress(); checksum.process_bytes(&progress, sizeof(progress)); } return checksum.checksum(); }
// copy common fields from xbee response to target response void XBeeResponse::setCommon(XBeeResponse &target) { target.setApiId(getApiId()); target.setAvailable(isAvailable()); target.setChecksum(getChecksum()); target.setErrorCode(getErrorCode()); target.setFrameLength(getFrameDataLength()); target.setMsbLength(getMsbLength()); target.setLsbLength(getLsbLength()); }
void buildAndCheckSentence(unsigned char characterIn) { // Full specification for NMEA0138 specifies a maximum sentence length // of 255 characters. We're going to ignore this for half the length as // we shouldn't get anything that big. // This contains the function's state of whether // it is currently building a sentence. // 0 - Awaiting start character ($) // 1 - Building sentence // 2 - Building first checksum character // 3 - Building second checksum character //printf("char: %c\r\n",characterIn); // We start recording a new sentence if we see a dollarsign. // The sentenceIndex is hard-set to 1 so that multiple dollar-signs // keep you at the beginning. if (characterIn == '$') { //printf("start character at least"); sentence[0] = characterIn; sentenceIndex = 1; sentenceState = 1; } else if (sentenceState == 1) { // Record every character that comes in now that we're building a sentence. // Only stop if we run out of room or an asterisk is found. sentence[sentenceIndex++] = characterIn; if (characterIn == '*') { sentenceState = 2; } else if (sentenceIndex > 127) { // If we've filled up the buffer, ignore the entire message as we can't store it all sentenceState = 0; sentenceIndex = 0; } } else if (sentenceState == 2) { // Record the first ASCII-hex character of the checksum byte. checksum = hex2char(characterIn) << 4; sentenceState = 3; } else if (sentenceState == 3) { // Record the second ASCII-hex character of the checksum byte. checksum |= hex2char(characterIn); // Now that we've compiled a complete GPS sentence, let's check the checksum and parse it. // This code currently only supports RMC and GGA messages. if (checksum == getChecksum(sentence, sentenceIndex)) { if (sentence[3] == 'R' && sentence[4] == 'M' && sentence[5] == 'C') { parseRMC(sentence); } else if (sentence[3] == 'G' && sentence[4] == 'G' && sentence[5] == 'A') { parseGGA(sentence); } } // We clear all state variables here regardless of success. sentenceIndex = 0; sentenceState = 0; } }
uint8_t Protocol::parse(uint16_t* _data, bool _mod) { if (available(!_mod)) { time = millis(); do { if (this->sta) { this->sta = false; this->num = 0; if (this->inChar == this->channel) { this->error = false; if (!_mod) { return P_BUSY; } } else { this->error = true; return P_ERROR; } } if (this->inChar == 0xBB && this->inCache == 0xAA) { this->sta = true; if (!_mod) { return P_BUSY; } } if (this->num == (CHANNEL_NUM * 2 + 1) && !this->error) { this->inCache = this->buffer[CHANNEL_NUM * 2]; this->buffer[CHANNEL_NUM * 2] = NULL; this->inChar = getChecksum(CHANNEL_NUM * 2, 200, this->buffer); this->num = 0; if (!this->error && this->inCache == this->inChar) { for (uint8_t a = 0; a < CHANNEL_NUM; a++) { _data[a] = ((uint16_t)(this->buffer[a * 2])) | ((uint16_t)this->buffer[a * 2 + 1] << 8); } return P_FINE; } else { return P_ERROR; } } else if (!_mod) { return P_BUSY; } } while (_mod && (available(true) && millis() - time < 100)); if (_mod) { return P_TIMEOUT; } } else { return P_NONE; } }
int EIsupported(void) { static int returnValue=LIC_FAIL, firstTime=1; if(firstTime) { if(getChecksum()) { // 2nd number is determining number if(regSerialNumber[1] == '3' || regSerialNumber[1] == '5') { returnValue = LIC_SUCCESS; } } firstTime = 0; } return(returnValue); }
string IcmpPacket::toString () { ostringstream out; out << "ICMP packet" << std::endl << "\ttype: \t" << (int)getType () << std::endl << "\tcode: \t" << (int)getCode () << std::endl << "\tchecksum: \t" << getChecksum () ; return out.str (); }
void sendData (void *theData, uint8_t theLeng) { uint8_t pro_size = theLeng+3; uint8_t buffer[pro_size]; buffer[0]= 0xff; buffer[1] = theLeng; memcpy ((void*)(buffer+2), theData, theLeng); buffer[pro_size-1] = getChecksum ((uint8_t*)theData, pro_size-1); #ifdef _debug printHex (buffer, pro_size); #endif bleSend ((uint8_t*)(buffer), pro_size); }
String Communication::getPackedMessage(String message) { String packed_message = ""; String checksum = getChecksum(message); packed_message += kStartOfHeaderChar; packed_message += message.length(); packed_message += kStartOfTextChar; packed_message += message; packed_message += kEndOfTextChar; packed_message += checksum; packed_message += kEndOfTransmissionChar; return packed_message; }
checksum_t getChecksum(const capputils::reflection::IClassProperty* property, const capputils::reflection::ReflectableClass& object) { IEnumerableAttribute* enumerable = property->getAttribute<IEnumerableAttribute>(); IReflectableAttribute* reflectable = property->getAttribute<IReflectableAttribute>(); IChecksumAttribute* checksumAttribute = property->getAttribute<IChecksumAttribute>(); if (checksumAttribute) { return checksumAttribute->getChecksum(property, object); } else if (reflectable) { ReflectableClass* subobject = reflectable->getValuePtr(object, property); if (subobject) return getChecksum(subobject); } else if (enumerable) { boost::crc_optimal<32, 0x04C11DB7> valueSum; checksum_t checksum; boost::shared_ptr<IPropertyIterator> iterator = enumerable->getPropertyIterator(object, property); if (iterator) { for (iterator->reset(); !iterator->eof(); iterator->next()) { checksum = getChecksum(iterator.get(), object); valueSum.process_bytes(&checksum, sizeof(checksum)); } } else { valueSum.process_bytes(&iterator, sizeof(iterator)); } return valueSum.checksum(); } else { boost::crc_optimal<32, 0x04C11DB7> valueSum; const std::string& str = property->getStringValue(object); valueSum.process_bytes(&str[0], str.size()); if (property->getAttribute<FilenameAttribute>() && property->getAttribute<FileExistsAttribute>() && boost::filesystem::exists(str)) { time_t modifiedTime = boost::filesystem::last_write_time(str); valueSum.process_bytes(&modifiedTime, sizeof(modifiedTime)); } return valueSum.checksum(); } return 0; }
int IsEnterprise(void) { static int returnValue=LIC_FAIL, firstTime=1; if(firstTime) { if(getChecksum()) { // 3rd number is determining number if(regSerialNumber[2] == '1' || regSerialNumber[2] == '3') { returnValue = LIC_SUCCESS; } } firstTime = 0; } return(returnValue); }
void SBBTA252::sendReadCommand(int thruster) { // Declare variables. char cmd[6]; Serial::buf_send = cmd; // Send command. if (Serial::fd > 0) { cmd[0] = SBBTA252_SC; cmd[1] = getAddress(1, thruster); cmd[2] = getAddress(2, thruster); cmd[3] = getChecksum(1, cmd, 6); cmd[4] = getChecksum(2, cmd, 6); cmd[5] = SBBTA252_EC; Serial::length_send = 6; send(); usleep(SBBTA252_SERIAL_DELAY); ROS_DEBUG("Send Read Command (%d): %s.", thruster, cmd); } } // end sendReadCommand()
int dump(int len) { HEADER *head; int i = 0, j = 0, d = 0, v = 0, c = 0, c0 = 0, c1 = 0; int csum = 0; int csum1 = 0; int length = 0; if (tag() != 0) return -1; if (len == 0) len = 128; while(1) { v = getByte(IN); csum += getChecksum(v); if (fgetc(IN) != '1') break; b[d++] = v; if (len <= 0) break; else len--; if (length % 16 == 0) printf("\n%04x:", length); length++; printf("%02x ", v); } csum1 += getByte(IN); fgetc(IN); csum1 += getByte(IN) << 8; fgetc(IN); printf("\n\n", d); if (d == 129) { head = (HEADER *) b; printf("Name: %s\n", head->name); printf("Type: %s\n", head->type == 1 ? "Machine" : "Basic"); printf("Length: %04xh\n", head->size); printf("Loading address: %04xh\n", head->load); printf("Checksum: %04xh (%04xh)\n", csum1, csum); printf("Header Size: %d\n", d-1); if (head->type == 1) printf("Jump address: %04xh\n", head->jump); return head->size; } else { printf("Body Loading..\n"); printf("Length: %d\n", d-1); printf("Checksum: %04xh (%04xh)\n", csum1, csum); } return 0; }
void buildAndCheckSentence(unsigned char characterIn, char *sentence, unsigned char *sentenceIndex, unsigned char *sentenceState, unsigned char *checksum, void (*processResult)(char *)) { // Full specification for NMEA0138 specifies a maximum sentence length // of 255 characters. We're going to ignore this for half the length as // we shouldn't get anything that big. // This contains the function's state of whether // it is currently building a sentence. // 0 - Awaiting start character ($) // 1 - Building sentence // 2 - Building first checksum character // 3 - Building second checksum character // We start recording a new sentence if we see a dollarsign. // The sentenceIndex is hard-set to 1 so that multiple dollar-signs // keep you at the beginning. if ((*sentenceState) == 0) { if (characterIn == '$') { (*sentenceIndex) = 0; (*sentenceState) = 1; } } else if ((*sentenceState) == 1) { // Record every character that comes in now that we're building a sentence. // Only stop if we run out of room or an asterisk is found. if (characterIn == '*') { (*sentenceState) = 2; } else if ((*sentenceIndex) > 127) { // If we've filled up the buffer, ignore the entire message as we can't store it all (*sentenceState) = 0; } else { sentence[(*sentenceIndex)++] = characterIn; } } else if ((*sentenceState) == 2) { // Record the first ASCII-hex character of the checksum byte. (*checksum) = hex2char(characterIn) << 4; (*sentenceState) = 3; } else if ((*sentenceState) == 3) { // Record the second ASCII-hex character of the checksum byte. (*checksum) |= hex2char(characterIn); // Now that we've compiled a complete GPS sentence, let's check the checksum and parse it. // This code currently only supports RMC and GGA messages. unsigned char test = getChecksum(sentence, (*sentenceIndex)); if ((*checksum) == test) { processResult(sentence); } // We clear all state variables here regardless of success. (*sentenceState) = 0; } }
void TXRequest::assemblePacket(){ packet.clear(); packet.append(getFrameType()); packet.append(getFrameId()); packet.append(getDestAddr64()); packet.append(getDestAddr16()); packet.append(getBroadcastRadius()); packet.append(getTransmitOptions()); packet.append(getData()); setLength(packet.size()); createChecksum(packet); packet.append(getChecksum()); packet.insert(0, getStartDelimiter()); packet.insert(1, getLength()); }
bool Nfc::serialWrite(const uint16_t addr, const uint8_t num, const std::vector<uint8_t>& data){ std::vector<uint8_t> senddata(5+num); auto ite = senddata.begin(); *ite++ = SYNC_CODE; *ite++ = SERIAL_READ; *ite++ = static_cast<uint8_t>((addr>>8)&0x00FF); *ite++ = static_cast<uint8_t>(addr&0x00FF); for (auto v : data){ *ite++ = v; } *ite = getChecksum(data, 4+num); sendnbyte(senddata, 5+num); std::vector<uint8_t> tmpdata(3); uint8_t tmp1data; if(!recvnbyte(tmpdata, 2)) return false; if(!recv1byte(tmp1data)) return false; if(tmpdata[1] != RESPONCE_ACK) return false; return true; }
string TcpPacket::toString () { ostringstream out; Packet::PAYLOAD_BUFFER opts = getOptions (); out << "TCP packet" << std::endl << "\tsource port: \t" << getSourceport() << std::endl << "\tdest port: \t" << getDestport() << std::endl << "\tsequencenum: \t" << getSequencenum() << std::endl << "\tacknum: \t" << getAcknum() << std::endl << "\theaderlen: \t" << getHeaderlength() << " bytes" << std::endl << "\tflags: \t\t0x" << std::hex << std::setw(4) << std::setfill ('0') << getFlags () << std::endl << std::dec << "\twindowsize: \t" << getWindowsize() << std::endl << "\tchecksum: \t0x" << std::hex << std::setw(4) << std::setfill ('0') << getChecksum () << std::endl << std::dec << "\turgent pnt: \t" << getUrgentpointer() << std::endl << "\toptions len: \t" << opts.size << std::endl << "\toptions: \t" << opts.toString (); opts.destroy (); return out.str (); }
void libHubsan::bind() { Serial.println("Sending beacon packets..."); byte status_byte = 0x00; // variable to hold W/R register data. // Generate 4 byte random session id. randomSeed(analogRead(0)); for (int i=0;i<4;i++){ _sessionid[i] = random(255); } for (int i=0;i<16;i++){ // Initialize packet array. _txpacket[i] = 0x00; } _txpacket[0] = 0x01; // Bind level = 01 (Unbound - BEACON lvl 1 Packet) _txpacket[1] = _channel; // Selected Channel for (int i=0;i<4;i++){ _txpacket[i+2] = _sessionid[i]; } getChecksum(_txpacket); // Transmit ANNOUNCE Packet until a response is heard. while (true){ txPacket(_txpacket); a7105.sendStrobe(A7105_RX); // Switch to RX mode. bool response = false; for (int i=0;i<15;i++){ // Listen to see if there was a response. a7105.readRegister(A7105_00_MODE,status_byte); if (CHECK_BIT(status_byte,0)==false){ response = true; break; } delay(1); } if (response){ break; } a7105.sendStrobe(A7105_STANDBY); } rxPacket(_rxpacket); // Escalate handshake. _txpacket[0] = 0x03; // Bind Level = 01 (Unbound - BEACON lvl 3 Packet) getChecksum(_txpacket); while (true){ txPacket(_txpacket); a7105.sendStrobe(A7105_RX); // Switch to RX mode. bool response = false; for (int i=0;i<15;i++){ // Listen to see if there was a response. a7105.readRegister(A7105_00_MODE,status_byte); if (CHECK_BIT(status_byte,0)==false){ response = true; break; } delay(1); } if (response){ break; } a7105.sendStrobe(A7105_STANDBY); } rxPacket(_rxpacket); // Set IDCode to the session value. a7105.writeRegister(A7105_06_ID_DATA,4,_sessionid); // Commence confirmation handshake. _txpacket[0] = 0x01; // Bind Level = 01 (Mid-Bind - Confirmation of IDCODE change packet) getChecksum(_txpacket); while (true){ txPacket(_txpacket); a7105.sendStrobe(A7105_RX); // Switch to RX mode. bool response = false; for (int i=0;i<15;i++){ // Listen to see if there was a response. a7105.readRegister(A7105_00_MODE,status_byte); if (CHECK_BIT(status_byte,0)==false){ response = true; break; } delay(1); } if (response){ break; } a7105.sendStrobe(A7105_STANDBY); } rxPacket(_rxpacket); // Commence full handshake escalation. _txpacket[0] = 0x09; for (int i=0;i<10;i++){ _txpacket[2] = byte(i); getChecksum(_txpacket); while (true){ txPacket(_txpacket); a7105.sendStrobe(A7105_RX); // Switch to RX mode. bool response = false; for (int i=0;i<15;i++){ // Listen to see if there was a response. a7105.readRegister(A7105_00_MODE,status_byte); if (CHECK_BIT(status_byte,0)==false){ response = true; break; } delay(1); } if (response){ break; } a7105.sendStrobe(A7105_STANDBY); } rxPacket(_rxpacket); } a7105.writeRegister(A7105_1F_CODE_I,0x0F); // Enable FEC. a7105.sendStrobe(A7105_STANDBY); }
/* * Function: Send a packet from one XBee to another XBee in API mode * * Parameters: * packet : A struct of packetXBee type * * Returns: Integer that determines if there has been any error * error=2 --> The command has not been executed * error=1 --> There has been an error while executing the command * error=0 --> The command has been executed with no errors * * --> DIGI's XBee Packet inner structure: * * StartDelimiter(1B) + Length(2B) + Frame Data(variable) + Checksum(1B) * ______________ ___________ __________________ __________ * | | | | | | | | | * | 0x7E | + | MSB | LSB | + | Frame Data | + | 1 Byte | * |______________| |_____|_____| |__________________| |__________| * */ uint8_t WaspXBeeDM::sendXBeePriv(struct packetXBee* packet) { // Local variables uint8_t TX[120]; uint8_t counter=0; uint16_t aux=0; uint8_t protegido=0; uint8_t tipo=0; int8_t error=2; clearCommand(); error_TX=2; // clear TX variable where the frame is going to be filled memset(TX,0x00,120); /* Create the XBee frame */ TX[0]=0x7E; TX[1]=0x00; // set frame ID as 0x01, so response message will be sent TX[4]=0x01; it=0; error_AT=2; if( (packet->mode==BROADCAST) || (packet->mode==UNICAST) ) { // set fragment length for 'Transmit Request' frames (0x10) TX[2]=14+packet->data_length; aux=0; TX[3]=0x10; // frame ID tipo=18; // set 64-Destination Address if(packet->mode == BROADCAST) { // set BROADCAST address TX[5]=0x00; TX[6]=0x00; TX[7]=0x00; TX[8]=0x00; TX[9]=0x00; TX[10]=0x00; TX[11]=0xFF; TX[12]=0xFF; } else if(packet->mode==UNICAST) { // set chosen address in setDestinationParams function TX[5]=packet->macDH[0]; TX[6]=packet->macDH[1]; TX[7]=packet->macDH[2]; TX[8]=packet->macDH[3]; TX[9]=packet->macDL[0]; TX[10]=packet->macDL[1]; TX[11]=packet->macDL[2]; TX[12]=packet->macDL[3]; } // set frame bytes TX[13]=0xFF; TX[14]=0xFE; TX[15]=0x00; TX[16]=0x00; it=0; // generate RF Data payload which is composed by [Api header]+[Data] genDataPayload(packet,TX,17); // set checksum TX[packet->data_length+17]=getChecksum(TX); } else // CLUSTER Type (Explicit Addressing Command Frame) { // set fragment length for 'Explicit Addressing Command' frames (0x11) TX[2]=20 + packet->data_length; // set frame ID TX[3]=0x11; tipo=24; TX[5]=packet->macDH[0]; TX[6]=packet->macDH[1]; TX[7]=packet->macDH[2]; TX[8]=packet->macDH[3]; TX[9]=packet->macDL[0]; TX[10]=packet->macDL[1]; TX[11]=packet->macDL[2]; TX[12]=packet->macDL[3]; TX[13]=0xFF; TX[14]=0xFE; TX[15]=packet->SD; TX[16]=packet->DE; TX[17]=0x00; TX[18]=packet->CID[0]; TX[19]=packet->PID[0]; TX[20]=packet->PID[1]; TX[21]=0x00; TX[22]=0x00; it=0; // generate RF Data payload which is composed by [Api header]+[Data] genDataPayload(packet,TX,23); // set checksum TX[packet->data_length+23]=getChecksum(TX); } // Generate the escaped API frame (it is necessary because AP=2) gen_frame_ap2(packet,TX,protegido,tipo); // send frame through correspondent UART while(counter<(packet->data_length+tipo+protegido)) { // switch MUX in case SOCKET1 is used if( uart==SOCKET1 ) { Utils.setMuxSocket1(); } // print byte through correspondent UART printByte(TX[counter], uart); counter++; } counter=0; // read XBee's answer to TX request error_TX=txZBStatusResponse(); error = error_TX; packet->deliv_status=delivery_status; packet->discov_status=discovery_status; packet->true_naD[0]=true_naD[0]; packet->true_naD[1]=true_naD[1]; packet->retries=retries_sending; return error; }
int main(void) { unsigned char frameHead = 0x7e; unsigned char frameTail = 0xac; unsigned char cmd = 11; unsigned char mode = 1; unsigned char ADNumber = 1; int originADValue = 0x7e12ac1b; int originWeight = 80; unsigned char checksum = 0; // originADValue -> ADValue // 1. 主机序转网络序 originADValue = htonl(originADValue); // 2. 转义特殊字符 unsigned char *ADValue; int ADValueLen = 0; ADValueLen = convertValue((unsigned char *)&originADValue, sizeof(int), &ADValue); if (ADValueLen < 0) { fprintf(stderr, "Error: Convert value error!\n"); return -1; } printf(">> ADValueLen:%d\n", ADValueLen); originWeight = htonl(originWeight); unsigned char *weight; int weightLen = 0; weightLen = convertValue((unsigned char *)&originWeight, sizeof(int), &weight); if (weightLen < 0) { fprintf(stderr, "Error: Convert value error!\n"); return -1; } printf(">> weightLen:%d\n", weightLen); printf("Convert OK!\n"); int frameLen = 1+1+1+1+ADValueLen+weightLen+1+1; printf("frameLen:%d\n", frameLen); unsigned char *frame = malloc(frameLen); if (frame == NULL) { perror("malloc()"); return -1; } int index = 0; frame[index++] = frameHead; frame[index++] = cmd; frame[index++] = mode; frame[index++] = ADNumber; printf("** index = %d\n", index); memcpy(&frame[index], ADValue, ADValueLen); index += ADValueLen; printf("** index = %d\n", index); memcpy(&frame[index], weight, weightLen); index += weightLen; printf("** index = %d\n", index); checksum = getChecksum(frame-1, frameLen-2); frame[index++] = checksum; frame[index++] = frameTail; printf("index: %d\t frame len: %d\n", index, frameLen); printFrame(frame, frameLen); free(ADValue); free(weight); return 0; }
checksum_t ChecksumUpdater::GetChecksum(boost::shared_ptr<workflow::Node> node, int flags) { assert(node); return getChecksum(node->getModule().get(), node.get(), flags); }
int main(int argc, char* argv[]) { char i; /* //CBRef A = newCircBuffer(10); //CBRef B = newCircBuffer(20); struct CircBuffer Anp; struct CircBuffer Bnp; CBRef A = &Anp; CBRef B = &Bnp; newCircBuffer(A); newCircBuffer(B); for(i=0; i<=12; i++) { writeBack(B, i); writeBack(A, 15-i); } //printCircBuf(A); //printCircBuf(B); printf("\n"); printf("\n"); for(i=0; i<=12; i++) { printf("Read byte A: %d\n", readFront(A)); printf("Read byte B: %d\n", readFront(B)); //printCircBuf(A); } makeEmpty(A); //printCircBuf(A); freeCircBuffer(&A); freeCircBuffer(&B); */ unsigned char msg1 [] = "@$GPRMC,040302.663,A,3939.7,N,10506.6,W,5.27,358.86,200804,,*1A\r\n"; unsigned char msg2 [] = "N$GPGGA,213924.000,4221.1129,N,07102.9146,W,1,04,3.9,129.7,M,-33.7,M,,0000*68\r\n"; unsigned char msg3 [] = "&$GPGGA,213922.000,4221.1129,N,07102.91"; unsigned char msg4 [] = "(46,W,1,04,3.9,129.7,M,-33.7,M,,0000*6E\r\n"; unsigned char outBuffer [128] ={0}, parsedData[128]={0}; gpsInit(); printf("Message 1\n"); gpsSeparate(msg2, outBuffer); printf("\n"); printf(outBuffer); printf("\nValid: %d Type:%d", outBuffer[MSIZE-1], outBuffer[0]); printf("\n"); printf(msg2); gpsParse(outBuffer, parsedData); for(i=0;i<6;i++){ printf("%d ", parsedData[i]); } tFloatToChar flCh; tIntToChar inCh; flCh.chData[0] = parsedData[6]; flCh.chData[1] = parsedData[7]; flCh.chData[2] = parsedData[8]; flCh.chData[3] = parsedData[9]; printf("%f ", flCh.flData); flCh.chData[0] = parsedData[10]; flCh.chData[1] = parsedData[11]; flCh.chData[2] = parsedData[12]; flCh.chData[3] = parsedData[13]; printf("%f ", flCh.flData); flCh.chData[0] = parsedData[14]; flCh.chData[1] = parsedData[15]; flCh.chData[2] = parsedData[16]; flCh.chData[3] = parsedData[17]; printf("%f ", flCh.flData); inCh.chData[0] = parsedData[18]; inCh.chData[1] = parsedData[19]; printf("%d ", inCh.inData); inCh.chData[0] = parsedData[20]; inCh.chData[1] = parsedData[21]; printf("%d ", inCh.inData); inCh.chData[0] = parsedData[22]; inCh.chData[1] = parsedData[23]; printf("%d ", inCh.inData); for(i=24;i<26;i++){ printf("%d ", parsedData[i]); } printf("\n"); unsigned char thischr [] = "$PMTK251,19200*22\r\n"; printf("Baud Rate %d", getChecksum(thischr, 17)); unsigned char thischr2 [] = "$PMTK300,200,0,0,0,0*2F\r\n"; printf("Frequency %d", getChecksum(thischr2, 23)); unsigned char thischr3 [] = "$PMTK314,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0*28\r\n"; printf("Sentences %d", getChecksum(thischr3, 49)); /*printf("Message 2\n"); gpsSeparate(msg2, outBuffer); printf("\n"); printf(outBuffer); printf("\nValid: %d Type:%d", outBuffer[MSIZE-1], outBuffer[0]); printf("\n"); printf(msg2); printf("First Call to GPS Separate\n"); gpsSeparate(msg3, outBuffer); printf("============================\n"); printf("Second Call to GPS Separate\n"); gpsSeparate(msg4, outBuffer); printf("============================\n"); printf(outBuffer); printf("\nValid: %d Type:%d", outBuffer[MSIZE-1], outBuffer[0]); printf("\n"); printf(msg3); printf(msg4); printf("============================\n"); printf("============================\n"); printf("============================\n"); printf("============================\n"); printf("Char: %d, Short: %d, Int: %d, Float: %d, Long:%d", sizeof(char), sizeof(short), sizeof(int), sizeof(float), sizeof(long)); printf("\n"); */ return(0); }
/* * Function: Send a packet from one XBee to another XBee in API mode * * Parameters: * packet : A struct of packetXBee type * * Returns: Integer that determines if there has been any error * error=2 --> The command has not been executed * error=1 --> There has been an error while executing the command * error=0 --> The command has been executed with no errors * * --> DIGI's XBee Packet inner structure: * * StartDelimiter(1B) + Length(2B) + Frame Data(variable) + Checksum(1B) * ______________ ___________ __________________ __________ * | | | | | | | | | * | 0x7E | + | MSB | LSB | + | Frame Data | + | 1 Byte | * |______________| |_____|_____| |__________________| |__________| * * Remarks: * It is necessary to set the MY address to 0xFFFF when sending in * order to insert the source mac address within the packet. Thus, the * receiver will be able to know the source's mac address */ uint8_t WaspXBee802::sendXBeePriv(struct packetXBee* packet) { // Local variables uint8_t TX[120]; uint8_t counter=0; unsigned long previous=0; uint8_t protegido=0; uint8_t tipo=0; uint8_t estado=1; int8_t error=2; uint8_t old_netAddress[2]; uint8_t net_Address_changed = 0; error_TX = 2; // clear TX variable where the frame is going to be filled memset(TX,0x00,120); // Create the XBee frame TX[0] = 0x7E; TX[1] = 0x00; // set frame ID as 0x01, so response message will be sent TX[4] = 0x01; // init variables it = 0; error_AT = 2; // NOTE: It is necessary to set the MY address to 0xFFFF when sending in // order to insert the source mac address within the packet. Thus, the // receiver will be able to know the source's mac address // Initialize variable old_netAddress[0] = 0x00; old_netAddress[1] = 0x00; // BROADCAST MODE if( packet->mode == BROADCAST ) { tipo = 15; // set packet length TX[2] = 11+packet->data_length; // set TX request frame (0x00) TX[3] = 0x00; // get the backup MY address previous = millis(); error_AT = 2; while( ((error_AT == 1) || (error_AT == 2)) && (millis()-previous<500) ) { estado = getOwnNetAddress(); //avoid millis overflow problem if( millis() < previous ) previous=millis(); } old_netAddress[0] = sourceNA[0]; old_netAddress[1] = sourceNA[1]; // disable the MY address to include the MAC address as source address previous = millis(); error_AT = 2; while( ((error_AT == 1) || (error_AT == 2)) && (millis()-previous<500) ) { estado=setOwnNetAddress(0xFF,0xFF); net_Address_changed = 1; //avoid millis overflow problem if( millis() < previous ) previous=millis(); } error = 2; // set BROADCAST address TX[5] = 0x00; TX[6] = 0x00; TX[7] = 0x00; TX[8] = 0x00; TX[9] = 0x00; TX[10] = 0x00; TX[11] = 0xFF; TX[12] = 0xFF; // set Options enabling ACK TX[13] = 0x00; it = 0; // generate RF Data payload which is composed by [Api header]+[Data] genDataPayload(packet,TX,14); // set checksum TX[packet->data_length+14] = getChecksum(TX); } else if(packet->mode == UNICAST) { // 64-bit Destination Address if( packet->address_type == _64B ) { tipo = 15; // set fragment length TX[2] = 11+packet->data_length; // set TX Request Frame Type (64-bit address) TX[3] = 0x00; // set chosen address in setDestinationParams function TX[5] = packet->macDH[0]; TX[6] = packet->macDH[1]; TX[7] = packet->macDH[2]; TX[8] = packet->macDH[3]; TX[9] = packet->macDL[0]; TX[10] = packet->macDL[1]; TX[11] = packet->macDL[2]; TX[12] = packet->macDL[3]; // get the backup MY address previous = millis(); error_AT = 2; while( ((error_AT == 1) || (error_AT == 2)) && (millis()-previous<500) ) { estado = getOwnNetAddress(); // avoid millis overflow problem if( millis() < previous ) previous=millis(); } old_netAddress[0] = sourceNA[0]; old_netAddress[1] = sourceNA[1]; // disable the MY address to include the MAC address as source address previous=millis(); error_AT = 2; while( ((error_AT == 1) || (error_AT == 2)) && (millis()-previous<500) ) { estado=setOwnNetAddress(0xFF,0xFF); net_Address_changed = 1; // avoid millis overflow problem if( millis() < previous ) previous=millis(); } error = 2; TX[13] = 0x00; it = 0; // generate RF Data payload which is composed by [Api header]+[Data] genDataPayload(packet,TX,14); // setting checksum TX[packet->data_length+14] = getChecksum(TX); } // 16-Bit Destination Address else if( packet->address_type == _16B) { tipo = 9; // set TX Request frame Type (16-bit address) TX[3] = 0x01; // set Destination Address TX[5] = packet->naD[0]; TX[6] = packet->naD[1]; // Set Options enabling ACK TX[7] = 0x00; it=0; // generate RF Data payload which is composed by [Api header]+[Data] genDataPayload(packet,TX,8); // fragment length TX[2] = 5+packet->data_length; // set checksum TX[packet->data_length+8] = getChecksum(TX); } } else { // no mode selected, exit with error return 2; } // Generate the escaped API frame (it is necessary because AP=2) gen_frame_ap2(packet,TX,protegido,tipo); counter = 0; // send frame through correspondent UART while( counter < (packet->data_length+tipo+protegido) ) { // switch MUX in case SOCKET1 is used if( uart == SOCKET1 ) { Utils.setMuxSocket1(); } // print byte through correspondent UART printByte(TX[counter], uart); counter++; } counter = 0; // read XBee response to TX request error_TX = txStatusResponse(); error = error_TX; // set delivery status packet->deliv_status = delivery_status; // reset the backup MY address if( net_Address_changed == 1 ) { error_AT = 2; previous = millis(); while( ((error_AT == 1) || (error_AT == 2)) && (millis()-previous<500) ) { estado = setOwnNetAddress(old_netAddress[0],old_netAddress[1]); //avoid millis overflow problem if( millis() < previous ) previous=millis(); } } return error; }
// TODO: Include a messaging Mechanism for immediate or once in time messages // TODO: Include a File option for Archiving checksum fails for debuging float protParseDecode (unsigned char* fromSPI, FILE* outFile, unsigned char prevException){ #else void protParseDecode (unsigned char* fromSPI){ #endif // Static variables CAREFUL static unsigned char prevBuffer[2*MAXLOGLEN]; static unsigned char previousComplete =1; static unsigned char indexLast = 0; #ifdef _IN_PC_ static long long checkSumFail = 0; static long long totalPackets = 0; static float test = 0.0; float alpha = 0.3; #endif // local variables unsigned char i; unsigned char tmpChksum = 0, headerFound=0, noMoreBytes = 1; unsigned char trailerFound = 0; //unsigned char logSize = 0; // Add the received bytes to the protocol parsing circular buffer for(i = 1; i <= fromSPI[0]; i += 1 ) //for(i = 0; i <= 95; i += 1 ) { writeBack(ppBuffer, fromSPI[i]); } // update the noMoreBytes flag accordingly noMoreBytes = (fromSPI[0]>0)?0:1; // noMoreBytes = 0; while (!noMoreBytes){ // if the previous message was complete then read from the circular buffer // and make sure that you are into the begining of a message if(previousComplete){ while (!headerFound && !noMoreBytes) { // move along until you find a dollar sign or run out of bytes while (getLength(ppBuffer)>1 && peak(ppBuffer)!=DOLLAR){ readFront(ppBuffer); } // if you found a dollar then make sure the next one is an AT if(getLength(ppBuffer)>1 && peak(ppBuffer) == DOLLAR){ // read it prevBuffer[indexLast++] = readFront(ppBuffer); // if next is a at sign if (peak(ppBuffer) == AT){ // read it prevBuffer[indexLast++] = readFront(ppBuffer); // and signal you found a header headerFound = 1; // and set as incomplete the sentece previousComplete = 0; } } else { noMoreBytes = 1; } // else no dollar } // while we found header && no more bytes }// if previous complete // At this point either you found a header from a previous complete // or you are reading from a message that was incomplete the last time // in any of those two cases, keep reading until you run out of bytes // or find a STAR and an AT while (!trailerFound && !noMoreBytes){ while (getLength(ppBuffer)>2 && peak(ppBuffer)!=STAR){ prevBuffer[indexLast++] = readFront(ppBuffer); } // if you found a STAR (42) and stil have bytes if (getLength(ppBuffer)>2 && peak(ppBuffer)==STAR){ // read it prevBuffer[indexLast++] = readFront(ppBuffer); // if you still have 2 bytes if (getLength(ppBuffer)>1){ // and the next byte is an AT sign if (peak(ppBuffer)==AT){ // then you found a trailer trailerFound =1; } } else { noMoreBytes =1; } } else { // no more bytes noMoreBytes =1; } } // if you found a trailer, then the message is done if(trailerFound){ // read the AT and the checksum prevBuffer[indexLast++] = readFront(ppBuffer); prevBuffer[indexLast] = readFront(ppBuffer); // Compute the checksum tmpChksum= getChecksum(prevBuffer, indexLast-1); #ifdef _IN_PC_ totalPackets++; #endif // if the checksum is valid if (tmpChksum ==prevBuffer[indexLast]){ // update the states depending on the message updateStates(&prevBuffer[0]); // increment the log size //logSize += (indexLast+1); #ifdef _IN_PC_ // if in PC and loggin is enabled if ((outFile != NULL)){ printState(outFile, prevException); } //test = alpha*test; #endif } else{ #ifdef _IN_PC_ checkSumFail++; //test = (1.0-alpha) + alpha*test; #endif } // get everything ready to start all-over previousComplete =1; indexLast = 0; headerFound = 0; trailerFound = 0; memset(prevBuffer, 0, sizeof(prevBuffer)); }else { // you ran out of bytes // No More Bytes noMoreBytes = 1; }// else no star } // big outer while (no more bytes) #ifdef _IN_PC_ if (totalPackets>0){ //test = ((float)checkSumFail/(float)totalPackets); test = (float)checkSumFail; } else { test = 0.0; } return test; #endif } unsigned char getFilterOnOff (void){ return filterControlData; } // ================================ // hardware in the loop methods // ================================ void hil_getRawRead(short * rawData){ rawData[0] = rawControlData.gyroX.shData; rawData[1] = rawControlData.gyroY.shData; rawData[2] = rawControlData.gyroZ.shData; rawData[3] = rawControlData.accelX.shData; rawData[4] = rawControlData.accelY.shData; rawData[5] = rawControlData.accelZ.shData; rawData[6] = rawControlData.magX.shData; rawData[7] = rawControlData.magY.shData; rawData[8] = rawControlData.magZ.shData; rawData[9] = rawControlData.baro.shData; rawData[10] = rawControlData.pito.shData; rawData[11] = rawControlData.powr.shData; rawData[12] = rawControlData.ther.shData; }
void ChecksumUpdater::update(boost::shared_ptr<workflow::Node> node) { while(!nodesStack.empty()) nodesStack.pop(); boost::shared_ptr<workflow::Workflow> workflow = boost::dynamic_pointer_cast<workflow::Workflow>(node); if (workflow) { std::vector<boost::weak_ptr<workflow::Node> >& interfaceNodes = workflow->getInterfaceNodes(); for (unsigned i = 0; i < interfaceNodes.size(); ++i) { if (workflow->isOutputNode(interfaceNodes[i].lock())) buildStack(interfaceNodes[i].lock()); } } else { buildStack(node); } while (!nodesStack.empty()) { boost::shared_ptr<workflow::Node> currentNode = nodesStack.top(); nodesStack.pop(); // Update checksum + checksum from dependent stuff boost::crc_optimal<32, 0x04C11DB7> valueSum; boost::shared_ptr<workflow::Workflow> subworkflow = boost::dynamic_pointer_cast<workflow::Workflow>(currentNode); if (subworkflow) { ChecksumUpdater updater; updater.update(subworkflow); } else { assert(currentNode->getModule()); checksum_t dependentSum = 0; checksum_t selfSum = getChecksum(currentNode->getModule().get(), currentNode.get()); valueSum.process_bytes(&selfSum, sizeof(selfSum)); // std::cout << "Class name: " << currentNode->getModule()->getClassName() << std::endl; // if (currentNode->getModule()->getClassName() == "gml::convrbm4d::StackTensors") // std::cout << " Checksum: " << valueSum.checksum() << std::endl; std::vector<boost::shared_ptr<workflow::Node> > dependentNodes; currentNode->getDependentNodes(dependentNodes, true); // if (currentNode->getModule()->getClassName() == "gml::convrbm4d::StackTensors") // std::cout << " Dependent nodes: " << dependentNodes.size() << std::endl; for (unsigned i = 0; i < dependentNodes.size(); ++i) { // if (currentNode->getModule()->getClassName() == "gml::convrbm4d::StackTensors") { // std::cout << " " << dependentNodes[i]->getUuid() << std::endl; // std::cout << " In: " << dependentNodes[i]->getInputChecksum() << std::endl; // std::cout << " Out: " << dependentNodes[i]->getOutputChecksum() << std::endl; // } dependentSum = dependentNodes[i]->getInputChecksum(); valueSum.process_bytes(&dependentSum, sizeof(dependentSum)); // if (currentNode->getModule()->getClassName() == "gml::convrbm4d::StackTensors") { // std::cout << " Checksum: " << valueSum.checksum() << std::endl; // } } // if (currentNode->getModule()->getClassName() == "gml::convrbm4d::StackTensors") // std::cout << " Checksum: " << valueSum.checksum() << std::endl; currentNode->setInputChecksum(valueSum.checksum()); // if (currentNode->getModule()->getClassName() == "gml::convrbm4d::StackTensors") { // std::cout << " In: " << currentNode->getInputChecksum() << std::endl; // std::cout << " Out: " << currentNode->getOutputChecksum() << std::endl; // if (currentNode->getInputChecksum() != currentNode->getOutputChecksum()) // std::cout << currentNode->getUuid() << " changed!" << std::endl; // } } } if (workflow) { // accumulate checksums of output nodes // boost::crc_32_type valueSum; boost::crc_optimal<32, 0x04C11DB7> valueSum; std::vector<boost::weak_ptr<workflow::Node> >& interfaceNodes = workflow->getInterfaceNodes(); for (unsigned i = 0; i < interfaceNodes.size(); ++i) { if (workflow->isOutputNode(interfaceNodes[i].lock())) { checksum_t cs = interfaceNodes[i].lock()->getInputChecksum(); valueSum.process_bytes(&cs, sizeof(cs)); } } workflow->setInputChecksum(valueSum.checksum()); //if (workflow->getInputChecksum() != workflow->getOutputChecksum()) // std::cout << "checksum changed!" << std::endl; } }