/** * Interprets given line and transmit can message * * @param line Line string which contains the transmit command */ unsigned char transmitStd(char *line) { canmsg_t canmsg; unsigned long temp; unsigned char idlen; canmsg.flags.rtr = ((line[0] == 'r') || (line[0] == 'R')); // upper case -> extended identifier if (line[0] < 'Z') { canmsg.flags.extended = 1; idlen = 8; } else { canmsg.flags.extended = 0; idlen = 3; } if (!parseHex(&line[1], idlen, &temp)) return 0; canmsg.id = temp; if (!parseHex(&line[1 + idlen], 1, &temp)) return 0; canmsg.length = temp; if (!canmsg.flags.rtr) { unsigned char i; for (i = 0; i < canmsg.length; i++) { if (!parseHex(&line[idlen + 2 + i*2], 2, &temp)) return 0; canmsg.data[i] = temp; } } return mcp2515_send_message(&canmsg); }
bool CLI_process(CLIContext *context) { while (true) { char *end = strpbrk(context->buffer, "\r\n"); if (end == NULL) return true; *end = 0; if (bufferStartsWith(context, "quit")) { addToOutput(context, "EXIT"); return false; } const char *ptr; if (bufferStartsWith(context, "set uart mode") || bufferStartsWith(context, "set uart tx") || bufferStartsWith(context, "set sys iofunc")) { /* Ignored */ addToOutput(context, "AOK\r\n"); } else if ((ptr=bufferStartsWith(context, "set uart instant ")) != NULL) { uint32_t baud = parseDecimal(ptr); if (baud > 0) { Serial_setBaud(baud); addToOutput(context, "AOK\r\n"); } else { addToOutput(context, "ERROR\r\n"); } } else if ((ptr=bufferStartsWith(context, "set sys mask ")) != NULL) { uint32_t mask = parseHex(ptr, &ptr); if (!(*ptr)) { addToOutput(context, "ERROR\r\n"); } else if (*ptr == '0') { GPIO_setMode(mask, false); addToOutput(context, "AOK\r\n"); } else { GPIO_setMode(mask, true); addToOutput(context, "AOK\r\n"); } } else if ((ptr=bufferStartsWith(context, "set sys output ")) != NULL) { uint32_t output = parseHex(ptr, &ptr); if (!(*ptr)) { addToOutput(context, "ERROR\r\n"); } else { uint32_t mask = parseHex(ptr, &ptr); GPIO_setOutput(mask, output); addToOutput(context, "AOK\r\n"); } } else if (end != &context->buffer[0]) { addToOutput(context, "ERROR\r\n"); } memmove(context->buffer, end+1, strlen(end+1)+1); } }
QByteArray TellStick::readHex(const QString &filename, int maxAddress) { QByteArray data; QFile file(filename); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { return ""; } while( !file.atEnd() ) { QByteArray fileLine = file.readLine(); if (fileLine[0] != ':' || fileLine.length() < 11) { // skip line if not hex line entry,or not minimum length ":BBAAAATTCC" continue; } int byteCount = parseHex(fileLine, 1, 2); int startAddress = parseHex(fileLine, 3, 4); int recordType = parseHex(fileLine, 7, 2); if (recordType == 1) { //End of file, break break; } if (recordType == 2) { //Not implemented yet } else if (recordType == 4) { //Extended Linear Address Record not supported break; } else if (recordType == 0) { //Data record if (fileLine.length() < (11+ (2*byteCount))) { // skip if line isn't long enough for bytecount. continue; } //Protect us from overwriting the bootloader if (startAddress >= maxAddress) { continue; } //Pad with empty data when needed if ((startAddress > data.size())) { while (startAddress > data.size()) { data.append((char)0xFF); } } for (int lineByte = 0; lineByte < byteCount; lineByte++) { unsigned char hex = (unsigned char)parseHex(fileLine, 9 + (2 * lineByte), 2); data.append(hex); } } } for (int i = 0; i < 64; ++i) { //At least 64-bytes extra so the last block will be written to the memory data.append((char)0xff); } return data; }
int URI::parseEntity(int p0, int &result) { int p = p0; int ch = peek(p); if (ch != '&') return p0; p++; if (!match(p, "#x")) { error("parseEntity: expected '#x'"); return -1; } p += 2; int val; p = parseHex(p, val); if (p<0) return -1; ch = peek(p); if (ch != ';') { error("parseEntity: expected ';'"); return -1; } p++; result = val; return p; }
/* Main checks that the number of arguments is correct, then calls the to * the other functions to parse the hexadecimal values to integers * then print them out to stdout. It will quit on incorrect input with * an appro * * Parameters: * argc: the number of arguments (including the original program) * argv: an array of the arguments (including the original program name) * * Exit codes: * 0: Completed successfully * 1: More than 6 values to convert. Failed. * 2: Bad input in one of the hex numbers. Failed. */ int main (int argc, char *argv[]){ if (argc == 1) { /* no arguements, do nothing */ return 0; } if (argc > 7) { printf("Maximum of 6 values accepted. Quitting.\n"); return 1; } int intarray[argc]; int i; for ( i = 1; i < argc; i++ ) { int decimal; /*contains the decimal value of the hex input*/ decimal = parseHex(argv[i]); if (decimal == -1) { printf("Bad input encountered. Quitting.\n"); return 2; } else { intarray[i - 1] = decimal; } } printOutput(intarray, argv ,argc); return 0; }
Frame Parser::Private::parseFrame() { Frame frame; while (notAtEnd()) { blockingReadNext(); if (reader.isEndElement()) break; if (reader.isStartElement()) { const QStringRef name = reader.name(); if (name == QLatin1String("ip")) frame.setInstructionPointer(parseHex(blockingReadElementText(), QLatin1String("error/frame/ip"))); else if (name == QLatin1String("obj")) frame.setObject(blockingReadElementText()); else if (name == QLatin1String("fn")) frame.setFunctionName( blockingReadElementText()); else if (name == QLatin1String("dir")) frame.setDirectory(blockingReadElementText()); else if (name == QLatin1String("file")) frame.setFile( blockingReadElementText()); else if (name == QLatin1String("line")) frame.setLine(parseInt64(blockingReadElementText(), QLatin1String("error/frame/line"))); else if (reader.isStartElement()) reader.skipCurrentElement(); } } return frame; }
void Parser::Private::parseErrorCounts() { while (notAtEnd()) { blockingReadNext(); if (reader.isEndElement()) break; if (reader.isStartElement()) { if (reader.name() == QLatin1String("pair")) { qint64 unique = 0; qint64 count = 0; while (notAtEnd()) { blockingReadNext(); if (reader.isEndElement()) break; if (reader.isStartElement()) { const QStringRef name = reader.name(); if (name == QLatin1String("unique")) unique = parseHex(blockingReadElementText(), QLatin1String("errorcounts/pair/unique")); else if (name == QLatin1String("count")) count = parseInt64(blockingReadElementText(), QLatin1String("errorcounts/pair/count")); else if (reader.isStartElement()) reader.skipCurrentElement(); } } emit q->errorCount(unique, count); } else if (reader.isStartElement()) reader.skipCurrentElement(); } } }
boolean GPS::checksum(){ uint8_t sum = 0; uint8_t runningSum = 0; int i = 1; while(incomingNMEAString[i] != '*' && i < (MAXSIZE - 3)){ runningSum ^= incomingNMEAString[i++]; } i++; //advance past '*' sum = (parseHex(incomingNMEAString[i++]) * 16); sum += parseHex(incomingNMEAString[i]); if(sum == runningSum) return true; else return false; }
static bool parseRemap(const char *psz, UInt16 &scanFrom, UInt16& scanTo) { // psz is of the form: "scanfrom=scanto", examples: // non-extended: "1d=3a" // extended: "e077=e017" // of course, extended can be mapped to non-extended or non-extended to extended unsigned n; psz = parseHex(psz, '=', 0, n); if (NULL == psz || *psz != '=' || n > 0xFFFF) return false; scanFrom = n; psz = parseHex(psz+1, '\n', ';', n); if (NULL == psz || n > 0xFFFF) return false; scanTo = n; return true; }
static int parseIntelHex(char *hexfile, char* buffer, int *startAddr, int *endAddr) { int address, base, d, segment, i, lineLen, sum; FILE *input; input = strcmp(hexfile, "-") == 0 ? stdin : fopen(hexfile, "r"); if (input == NULL) { printf("> Error opening %s: %s\n", hexfile, strerror(errno)); return 1; } while (parseUntilColon(input) == ':') { sum = 0; sum += lineLen = parseHex(input, 2); base = address = parseHex(input, 4); sum += address >> 8; sum += address; sum += segment = parseHex(input, 2); /* segment value? */ if (segment != 0) { /* ignore lines where this byte is not 0 */ continue; } for (i = 0; i < lineLen; i++) { d = parseHex(input, 2); buffer[address++] = d; sum += d; } sum += parseHex(input, 2); if ((sum & 0xff) != 0) { printf("> Warning: Checksum error between address 0x%x and 0x%x\n", base, address); } if(*startAddr > base) { *startAddr = base; } if(*endAddr < address) { *endAddr = address; } } fclose(input); return 0; }
bool parseType (const char * _pValue, const char * _pEnd, const char ** _ppEnd, __int64 & _ulType) { const char * p = _pValue; // Omit spaces. while (p < _pEnd && * p == ' ') ++ p; if (p + 1 < _pEnd && p [0] == '0' && p [1] == 'x') return parseHex (p + 2, _pEnd, _ppEnd, _ulType); else return parseDecU (p, _pEnd, _ppEnd, _ulType); }
/* * Frontend of STM programmer */ void Stm32p::startProgram() { vddStateSet(false); QThread::msleep(300); gpioDirection(GPIO_OUT); /* GPIO low when reset released enters bootloader */ gpioStateSet(false); vddStateSet(true); /* The voltagesupervisor keeps reset active for max 300ms */ QThread::msleep(400); QByteArray bootloaderVersion = STM32->cmdGetBootloaderVersion(); if (bootloaderVersion == QByteArray()) qCritical() << "Get Version Failed"; else printf("Bootloader version v%s.%s\n", qPrintable(bootloaderVersion.toHex().at(0)), qPrintable(bootloaderVersion.toHex().at(1))); QByteArray chipId = STM32->cmdGetId(); if (chipId == QByteArray()) qCritical() << "Get ID Failed"; else printf("Device id is 0x%s\n", qPrintable(chipId.toHex())); if (!hexFile.open(QIODevice::ReadOnly | QIODevice::Text)) { qCritical() << "Error opening file"; return; } QByteArray data; unsigned long address = 0; QTextStream infile(&hexFile); while (parseHex(&infile, &address, &data)) { for (int i=0; i<sectorErased.size(); ++i) if (address >= sectorStartAddress.at(i) && address <= sectorEndAddress.at(i) && !sectorErased.at(i)) { printf("Erasing sector %d (0x%08lx...%08lx)\n", i, sectorStartAddress.at(i), sectorEndAddress.at(i)); STM32->cmdEraseMemory(i); sectorErased.replace(i, true); } printf("Programming 0x%08lx\r", address); STM32->cmdWriteMemory(address, data); } printf("\n"); doneProgramming = true; }
static void recordLabel(char *p) { ulongest_t address; ulongest_t *stringIdP; Res res; address = parseHex(&p); if (address > (Word)-1) { printf("label address too large!"); return; } stringIdP = malloc(sizeof(ulongest_t)); if (stringIdP == NULL) everror("Can't allocate space for a string's ID"); *stringIdP = parseHex(&p); res = TableDefine(labelTable, (Word)address, (void *)stringIdP); if (res != ResOK) everror("Couldn't create an intern mapping."); }
int URI::parseAsciiEntity(int p0, int &result) { int p = p0; int ch = peek(p); if (ch != '%') return p0; p++; int val; p = parseHex(p, val); if (p<0) return -1; result = val; return p; }
charVec Programming::parseIntelHex(char *hexFile, int fileSize) { int address, d, recordType, lineLen, sum, j, checkSum; charVec data; data.reserve(5000); for(int i = 0; i < fileSize + 1; i++) { if(hexFile[i] == ':') { sum = 0; sum += lineLen = parseHex(hexFile, i + 1, 2); address = parseHex(hexFile, i + 3, 4); sum += (address >> 8); sum += address; sum += recordType = parseHex(hexFile, i + 7, 2); if(recordType != 0) // ignore lines where this byte is not 0 continue; for(j = 0; j < lineLen; j++) { d = parseHex(hexFile, i + 9 + (j * 2), 2); data.push_back(d); sum += d; } checkSum = parseHex(hexFile, i + 11 + (j * 2), 2); } }
Erc Strpack::unpack(float* pf) { int i; Erc erc; union { uint8_t b[4]; uint32_t ui32; float f; } reg; for (i = 3; i >= 0; i--) { erc = parseHex(®.b[i]); if (erc) return erc; } *pf = reg.f; return E_OK; }
static void recordIntern(char *p) { ulongest_t stringId; char *string; char *copy; size_t len; Res res; stringId = parseHex(&p); string = parseString(&p); len = strlen(string); copy = malloc(len+1); if (copy == NULL) everror("Couldn't allocate space for a string."); (void)strcpy(copy, string); res = TableDefine(internTable, (Word)stringId, (void *)copy); if (res != ResOK) everror("Couldn't create an intern mapping."); }
void Shell::pushInt(const char *str) { bool opposite = false; if(str[0]=='-') { opposite=true; str++; } int v = 0; if(str[0] == '0') { //Could be octal or hexa if(str[1] == 'x') v = parseHex(str+2); else v = parseOct(str+1); } else { v = parseDec(str); } if(opposite) v = -v; s.push(v); }
CMString WCPattern::parseEscape(bool & inv, bool & quo) { wchar_t ch = pattern[curInd++]; CMString classes; if (curInd > pattern.GetLength()) { raiseError(); return ""; } quo = 0; inv = 0; switch (ch) { case 'p': classes = parsePosix(); break; case 'P': classes = L"!!"; classes += parsePosix(); break; case 'd': classes = L"0123456789"; break; case 'D': classes = L"!!0123456789"; break; case 's': classes = L" \t\r\n\f"; break; case 'S': classes = L"!! \t\r\n\f"; break; case 'w': classes = L"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_"; break; case 'W': classes = L"!!abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_"; break; case '0': classes = parseOctal(); break; case 'x': classes = parseHex(); break; case 'Q': quo = 1; break; case 't': classes = L"\t"; break; case 'r': classes = L"\r"; break; case 'n': classes = L"\n"; break; case 'f': classes = L"\f"; break; case 'a': classes = L"\a"; break; case 'e': classes = L"\r"; break; default: classes.AppendChar(ch); break; } if (classes.Mid(0, 2) == L"!!") { classes = classes.Mid(2); inv = 1; } return classes; }
UUID UUID::fromString(const NPT_String& s) { const char *cc = s.GetChars(); if (s.GetLength() == 36 && cc[8] == '-' && cc[13] == '-' && cc[18] == '-' && cc[23] == '-') { UUID uuid; if (!parseHex(*reinterpret_cast<NPT_UInt32*>(uuid.m_data + 0), cc, 8)) return UUID(); if (!parseHex(*reinterpret_cast<NPT_UInt16*>(uuid.m_data + 4), cc + 9, 4)) return UUID(); if (!parseHex(*reinterpret_cast<NPT_UInt16*>(uuid.m_data + 6), cc + 14, 4)) return UUID(); if (!parseHex(*reinterpret_cast<NPT_UInt8*>(uuid.m_data + 8), cc + 19, 2)) return UUID(); if (!parseHex(*reinterpret_cast<NPT_UInt8*>(uuid.m_data + 9), cc + 21, 2)) return UUID(); for (int i = 0; i < 6; i++) { if (!parseHex(*reinterpret_cast<NPT_UInt8*>(uuid.m_data + 10 + i), cc + 24 + i * 2, 2)) return UUID(); } return uuid; } return UUID(); }
boolean Adafruit_GPS::parse(char *nmea) { // do checksum check // first look if we even have one if (nmea[strlen(nmea)-4] == '*') { uint16_t sum = parseHex(nmea[strlen(nmea)-3]) * 16; sum += parseHex(nmea[strlen(nmea)-2]); // check checksum for (uint8_t i=2; i < (strlen(nmea)-4); i++) { sum ^= nmea[i]; } if (sum != 0) { // bad checksum :( return false; } } int32_t degree; long minutes; char degreebuff[10]; // look for a few common sentences if (strstr(nmea, "$GPGGA")) { // found GGA char *p = nmea; // get time p = strchr(p, ',')+1; float timef = atof(p); uint32_t time = timef; hour = time / 10000; minute = (time % 10000) / 100; seconds = (time % 100); milliseconds = fmod(timef, 1.0) * 1000; // parse out latitude p = strchr(p, ',')+1; if (',' != *p) { strncpy(degreebuff, p, 2); p += 2; degreebuff[2] = '\0'; degree = atol(degreebuff) * 10000000; strncpy(degreebuff, p, 2); // minutes p += 3; // skip decimal point strncpy(degreebuff + 2, p, 4); degreebuff[6] = '\0'; minutes = 50 * atol(degreebuff) / 3; latitude_fixed = degree + minutes; latitude = degree / 100000 + minutes * 0.000006F; latitudeDegrees = (latitude-100*int(latitude/100))/60.0; latitudeDegrees += int(latitude/100); } p = strchr(p, ',')+1; if (',' != *p) { if (p[0] == 'S') latitudeDegrees *= -1.0; if (p[0] == 'N') lat = 'N'; else if (p[0] == 'S') lat = 'S'; else if (p[0] == ',') lat = 0; else return false; } // parse out longitude p = strchr(p, ',')+1; if (',' != *p) { strncpy(degreebuff, p, 3); p += 3; degreebuff[3] = '\0'; degree = atol(degreebuff) * 10000000; strncpy(degreebuff, p, 2); // minutes p += 3; // skip decimal point strncpy(degreebuff + 2, p, 4); degreebuff[6] = '\0'; minutes = 50 * atol(degreebuff) / 3; longitude_fixed = degree + minutes; longitude = degree / 100000 + minutes * 0.000006F; longitudeDegrees = (longitude-100*int(longitude/100))/60.0; longitudeDegrees += int(longitude/100); } p = strchr(p, ',')+1; if (',' != *p) { if (p[0] == 'W') longitudeDegrees *= -1.0; if (p[0] == 'W') lon = 'W'; else if (p[0] == 'E') lon = 'E'; else if (p[0] == ',') lon = 0; else return false; } p = strchr(p, ',')+1; if (',' != *p) { fixquality = atoi(p); } p = strchr(p, ',')+1; if (',' != *p) { satellites = atoi(p); } p = strchr(p, ',')+1; if (',' != *p) { HDOP = atof(p); } p = strchr(p, ',')+1; if (',' != *p) { altitude = atof(p); } p = strchr(p, ',')+1; p = strchr(p, ',')+1; if (',' != *p) { geoidheight = atof(p); } return true; } if (strstr(nmea, "$GPRMC")) { // found RMC char *p = nmea; // get time p = strchr(p, ',')+1; float timef = atof(p); uint32_t time = timef; hour = time / 10000; minute = (time % 10000) / 100; seconds = (time % 100); milliseconds = fmod(timef, 1.0) * 1000; p = strchr(p, ',')+1; // Serial.println(p); if (p[0] == 'A') fix = true; else if (p[0] == 'V') fix = false; else return false; // parse out latitude p = strchr(p, ',')+1; if (',' != *p) { strncpy(degreebuff, p, 2); p += 2; degreebuff[2] = '\0'; long degree = atol(degreebuff) * 10000000; strncpy(degreebuff, p, 2); // minutes p += 3; // skip decimal point strncpy(degreebuff + 2, p, 4); degreebuff[6] = '\0'; long minutes = 50 * atol(degreebuff) / 3; latitude_fixed = degree + minutes; latitude = degree / 100000 + minutes * 0.000006F; latitudeDegrees = (latitude-100*int(latitude/100))/60.0; latitudeDegrees += int(latitude/100); } p = strchr(p, ',')+1; if (',' != *p) { if (p[0] == 'S') latitudeDegrees *= -1.0; if (p[0] == 'N') lat = 'N'; else if (p[0] == 'S') lat = 'S'; else if (p[0] == ',') lat = 0; else return false; } // parse out longitude p = strchr(p, ',')+1; if (',' != *p) { strncpy(degreebuff, p, 3); p += 3; degreebuff[3] = '\0'; degree = atol(degreebuff) * 10000000; strncpy(degreebuff, p, 2); // minutes p += 3; // skip decimal point strncpy(degreebuff + 2, p, 4); degreebuff[6] = '\0'; minutes = 50 * atol(degreebuff) / 3; longitude_fixed = degree + minutes; longitude = degree / 100000 + minutes * 0.000006F; longitudeDegrees = (longitude-100*int(longitude/100))/60.0; longitudeDegrees += int(longitude/100); } p = strchr(p, ',')+1; if (',' != *p) { if (p[0] == 'W') longitudeDegrees *= -1.0; if (p[0] == 'W') lon = 'W'; else if (p[0] == 'E') lon = 'E'; else if (p[0] == ',') lon = 0; else return false; } // speed p = strchr(p, ',')+1; if (',' != *p) { speed = atof(p); } // angle p = strchr(p, ',')+1; if (',' != *p) { angle = atof(p); } p = strchr(p, ',')+1; if (',' != *p) { uint32_t fulldate = atof(p); day = fulldate / 10000; month = (fulldate % 10000) / 100; year = (fulldate % 100); } // we dont parse the remaining, yet! return true; } return false; }
void Parser::Private::parseError() { Error e; QVector<QVector<Frame> > frames; XauxWhat currentAux; QVector<XauxWhat> auxs; int lastAuxWhat = -1; while (notAtEnd()) { blockingReadNext(); if (reader.isEndElement()) break; if (reader.isStartElement()) lastAuxWhat++; const QStringRef name = reader.name(); if (name == QLatin1String("unique")) { e.setUnique(parseHex(blockingReadElementText(), QLatin1String("unique"))); } else if (name == QLatin1String("tid")) { e.setTid(parseInt64(blockingReadElementText(), QLatin1String("error/tid"))); } else if (name == QLatin1String("kind")) { //TODO this is memcheck-specific: e.setKind(parseErrorKind(blockingReadElementText())); } else if (name == QLatin1String("suppression")) { e.setSuppression(parseSuppression()); } else if (name == QLatin1String("xwhat")) { const XWhat xw = parseXWhat(); e.setWhat(xw.text); e.setLeakedBlocks(xw.leakedblocks); e.setLeakedBytes(xw.leakedbytes); e.setHelgrindThreadId(xw.hthreadid); } else if (name == QLatin1String("what")) { e.setWhat(blockingReadElementText()); } else if (name == QLatin1String("xauxwhat")) { if (!currentAux.text.isEmpty()) auxs.push_back(currentAux); currentAux = parseXauxWhat(); } else if (name == QLatin1String("auxwhat")) { const QString aux = blockingReadElementText(); //concatenate multiple consecutive <auxwhat> tags if (lastAuxWhat > 1) { if (!currentAux.text.isEmpty()) auxs.push_back(currentAux); currentAux.clear(); currentAux.text = aux; } else { if (!currentAux.text.isEmpty()) currentAux.text.append(QLatin1Char(' ')); currentAux.text.append(aux); } lastAuxWhat = 0; } else if (name == QLatin1String("stack")) { frames.push_back(parseStack()); } else if (reader.isStartElement()) { reader.skipCurrentElement(); } } if (!currentAux.text.isEmpty()) auxs.push_back(currentAux); //if we have less xaux/auxwhats than stacks, prepend empty xauxwhats //(the first frame usually has not xauxwhat in helgrind and memcheck) while (auxs.size() < frames.size()) auxs.prepend(XauxWhat()); QVector<Stack> stacks; for (int i = 0; i < auxs.size(); ++i) stacks.append(makeStack(auxs[i], frames[i])); e.setStacks(stacks); emit q->error(e); }
// testConfData - Check each data item from the Unicode confusables.txt file, // verify that it transforms correctly in a skeleton. // void IntlTestSpoof::testConfData() { UErrorCode status = U_ZERO_ERROR; const char *testDataDir = IntlTest::getSourceTestData(status); TEST_ASSERT_SUCCESS(status); char buffer[2000]; uprv_strcpy(buffer, testDataDir); uprv_strcat(buffer, "confusables.txt"); LocalStdioFilePointer f(fopen(buffer, "rb")); if (f.isNull()) { errln("Skipping test spoof/testConfData. File confusables.txt not accessible."); return; } fseek(f.getAlias(), 0, SEEK_END); int32_t fileSize = ftell(f.getAlias()); LocalArray<char> fileBuf(new char[fileSize]); fseek(f.getAlias(), 0, SEEK_SET); int32_t amt_read = fread(fileBuf.getAlias(), 1, fileSize, f.getAlias()); TEST_ASSERT_EQ(amt_read, fileSize); TEST_ASSERT(fileSize>0); if (amt_read != fileSize || fileSize <=0) { return; } UnicodeString confusablesTxt = UnicodeString::fromUTF8(StringPiece(fileBuf.getAlias(), fileSize)); LocalUSpoofCheckerPointer sc(uspoof_open(&status)); TEST_ASSERT_SUCCESS(status); // Parse lines from the confusables.txt file. Example Line: // FF44 ; 0064 ; SL # ( d -> d ) FULLWIDTH .... // Three fields. The hex fields can contain more than one character, // and each character may be more than 4 digits (for supplemntals) // This regular expression matches lines and splits the fields into capture groups. RegexMatcher parseLine("(?m)^([0-9A-F]{4}[^#;]*?);([^#;]*?);([^#]*)", confusablesTxt, 0, status); TEST_ASSERT_SUCCESS(status); while (parseLine.find()) { UnicodeString from = parseHex(parseLine.group(1, status)); if (!Normalizer::isNormalized(from, UNORM_NFD, status)) { // The source character was not NFD. // Skip this case; the first step in obtaining a skeleton is to NFD the input, // so the mapping in this line of confusables.txt will never be applied. continue; } UnicodeString rawExpected = parseHex(parseLine.group(2, status)); UnicodeString expected; Normalizer::decompose(rawExpected, FALSE /*NFD*/, 0, expected, status); TEST_ASSERT_SUCCESS(status); int32_t skeletonType = 0; UnicodeString tableType = parseLine.group(3, status); TEST_ASSERT_SUCCESS(status); if (tableType.indexOf("SL") >= 0) { skeletonType = USPOOF_SINGLE_SCRIPT_CONFUSABLE; } else if (tableType.indexOf("SA") >= 0) { skeletonType = USPOOF_SINGLE_SCRIPT_CONFUSABLE | USPOOF_ANY_CASE; } else if (tableType.indexOf("ML") >= 0) { skeletonType = 0; } else if (tableType.indexOf("MA") >= 0) { skeletonType = USPOOF_ANY_CASE; } UnicodeString actual; uspoof_getSkeletonUnicodeString(sc.getAlias(), skeletonType, from, actual, &status); TEST_ASSERT_SUCCESS(status); TEST_ASSERT(actual == expected); if (actual != expected) { errln(parseLine.group(0, status)); UnicodeString line = "Actual: "; int i = 0; while (i < actual.length()) { appendHexUChar(line, actual.char32At(i)); i = actual.moveIndex32(i, 1); } errln(line); } if (U_FAILURE(status)) { break; } } }
static void readLog(FILE *input) { int i; for (i=0; i <= EventCodeMAX; ++i) eventName[i] = NULL; EVENT_LIST(EVENT_SET_NAME, X); while (TRUE) { /* loop for each event */ char line[MAX_LOG_LINE_LENGTH]; char *p, *q; ulongest_t clock; int code; ulongest_t val_hex; double val_float; const char *val_string; p = fgets(line, MAX_LOG_LINE_LENGTH, input); if (!p) { if (feof(input)) break; else everror("Couldn't read line from input."); } clock = parseHex(&p); code = (int)parseHex(&p); if (eventName[code]) printf("%0*" PRIXLONGEST " %04X %-19s ", hexWordWidth, clock, code, eventName[code]); else printf("%0*" PRIXLONGEST " %04X %-19s ", hexWordWidth, clock, code, "[Unknown]"); q = p; /* for a few particular codes, we do local processing. */ if (code == EventInternCode) { recordIntern(q); } else if (code == EventLabelCode) { recordLabel(q); } else if (code == EventEventInitCode) { ulongest_t major, median, minor, maxCode, maxNameLen, wordWidth, clocksPerSec; major = parseHex(&q); /* EVENT_VERSION_MAJOR */ median = parseHex(&q); /* EVENT_VERSION_MEDIAN */ minor = parseHex(&q); /* EVENT_VERSION_MINOR */ maxCode = parseHex(&q); /* EventCodeMAX */ maxNameLen = parseHex(&q); /* EventNameMAX */ wordWidth = parseHex(&q); /* MPS_WORD_WIDTH */ clocksPerSec = parseHex(&q); /* mps_clocks_per_sec() */ UNUSED(clocksPerSec); UNUSED(maxNameLen); if ((major != EVENT_VERSION_MAJOR) || (median != EVENT_VERSION_MEDIAN) || (minor != EVENT_VERSION_MINOR)) { fprintf(stderr, "Event log version does not match: %d.%d.%d vs %d.%d.%d\n", (int)major, (int)median, (int)minor, EVENT_VERSION_MAJOR, EVENT_VERSION_MEDIAN, EVENT_VERSION_MINOR); } if (maxCode > EventCodeMAX) { fprintf(stderr, "Event log may contain unknown events with codes from %d to %d\n", EventCodeMAX+1, (int)maxCode); } if (wordWidth > MPS_WORD_WIDTH) { int newHexWordWidth = (int)((wordWidth + 3) / 4); if (newHexWordWidth > hexWordWidth) { fprintf(stderr, "Event log word width is greater than on current platform;" "previous values may be printed too narrowly.\n"); } hexWordWidth = newHexWordWidth; } if (wordWidth > sizeof(ulongest_t) * CHAR_BIT) { everror("Event log word width %d is too wide for the current platform.", (int)wordWidth); } } switch(code) { EVENT_LIST(EVENT_PROCESS, X); default: printf("Unknown event."); } putchar('\n'); } }
BOOL CDisasm::DlgProc(UINT message, WPARAM wParam, LPARAM lParam) { //if (!m_hDlg) return FALSE; switch(message) { case WM_INITDIALOG: { return TRUE; } break; case WM_TIMER: { int iPage = TabCtrl_GetCurSel (GetDlgItem(m_hDlg, IDC_LEFTTABS)); ShowWindow(GetDlgItem(m_hDlg, IDC_FUNCTIONLIST), iPage?SW_NORMAL:SW_HIDE); ShowWindow(GetDlgItem(m_hDlg, IDC_REGLIST), iPage?SW_HIDE:SW_NORMAL); } break; case WM_NOTIFY: { HWND tabs = GetDlgItem(m_hDlg, IDC_LEFTTABS); NMHDR* pNotifyMessage = NULL; pNotifyMessage = (LPNMHDR)lParam; if (pNotifyMessage->hwndFrom == tabs) { int iPage = TabCtrl_GetCurSel (tabs); ShowWindow(GetDlgItem(m_hDlg, IDC_FUNCTIONLIST), iPage?SW_NORMAL:SW_HIDE); ShowWindow(GetDlgItem(m_hDlg, IDC_REGLIST), iPage?SW_HIDE:SW_NORMAL); } break; } case WM_COMMAND: { CtrlDisAsmView *ptr = CtrlDisAsmView::getFrom(GetDlgItem(m_hDlg,IDC_DISASMVIEW)); CtrlRegisterList *reglist = CtrlRegisterList::getFrom(GetDlgItem(m_hDlg,IDC_REGLIST)); switch(LOWORD(wParam)) { case IDC_SHOWVFPU: vfpudlg->Show(true); break; case IDC_FUNCTIONLIST: switch (HIWORD(wParam)) { case CBN_DBLCLK: case CBN_SELCHANGE: { HWND lb = GetDlgItem(m_hDlg,LOWORD(wParam)); int n = ListBox_GetCurSel(lb); if (n!=-1) { unsigned int addr = (unsigned int)ListBox_GetItemData(lb,n); ptr->gotoAddr(addr); } } break; }; break; case IDC_GOTOINT: switch (HIWORD(wParam)) { case LBN_SELCHANGE: { HWND lb =GetDlgItem(m_hDlg,LOWORD(wParam)); int n = ComboBox_GetCurSel(lb); unsigned int addr = (unsigned int)ComboBox_GetItemData(lb,n); if (addr != 0xFFFFFFFF) ptr->gotoAddr(addr); } break; }; break; case IDC_GO: { SetDebugMode(false); Core_EnableStepping(false); } break; case IDC_STEP: { Core_DoSingleStep(); Sleep(1); _dbg_update_(); ptr->gotoPC(); UpdateDialog(); vfpudlg->Update(); } break; case IDC_STEPOVER: { SetDebugMode(false); CBreakPoints::AddBreakPoint(cpu->GetPC()+cpu->getInstructionSize(0),true); _dbg_update_(); Core_EnableStepping(false); Sleep(1); ptr->gotoPC(); UpdateDialog(); } break; case IDC_STEPHLE: { hleDebugBreak(); SetDebugMode(false); _dbg_update_(); Core_EnableStepping(false); } break; case IDC_STOP: { SetDebugMode(true); Core_EnableStepping(true); _dbg_update_(); Sleep(1); //let cpu catch up ptr->gotoPC(); UpdateDialog(); vfpudlg->Update(); } break; case IDC_SKIP: { cpu->SetPC(cpu->GetPC() + cpu->getInstructionSize(0)); Sleep(1); ptr->gotoPC(); UpdateDialog(); } break; case IDC_MEMCHECK: { bool isRunning = !Core_IsInactive(); if (isRunning) { SetDebugMode(true); Core_EnableStepping(true); Core_WaitInactive(200); } MemCheck check; if (InputBox_GetHex(GetModuleHandle(NULL), m_hDlg, "JIT (and not HLE) only for now, no delete", 0, check.iStartAddress)) { check.bBreak = true; check.bLog = true; check.bOnRead = true; check.bOnWrite = true; check.bRange = false; CBreakPoints::MemChecks.push_back(check); CBreakPoints::InvalidateJit(); } if (isRunning) { SetDebugMode(false); Core_EnableStepping(false); } } break; case IDC_ADDRESS: { if (HIWORD(wParam) == EN_CHANGE ) { char szBuffer[32]; GetWindowText ((HWND)lParam, szBuffer, 32); ptr->gotoAddr(parseHex(szBuffer)); UpdateDialog(); } } break; case IDC_UPDATECALLSTACK: { HWND hDlg = m_hDlg; HWND list = GetDlgItem(hDlg,IDC_CALLSTACK); ComboBox_ResetContent(list); u32 pc = currentMIPS->pc; u32 ra = currentMIPS->r[MIPS_REG_RA]; DWORD addr = Memory::ReadUnchecked_U32(pc); int count=1; ComboBox_SetItemData(list,ComboBox_AddString(list,symbolMap.GetDescription(pc)),pc); if (symbolMap.GetDescription(pc) != symbolMap.GetDescription(ra)) { ComboBox_SetItemData(list,ComboBox_AddString(list,symbolMap.GetDescription(ra)),ra); count++; } //walk the stack chain while (addr != 0xFFFFFFFF && addr!=0 && count++<20) { DWORD fun = Memory::ReadUnchecked_U32(addr+4); char *str = symbolMap.GetDescription(fun); if (strlen(str)==0) str = "(unknown)"; ComboBox_SetItemData(list, ComboBox_AddString(list,str), fun); addr = Memory::ReadUnchecked_U32(addr); } ComboBox_SetCurSel(list,0); } break; case IDC_GOTOPC: { ptr->gotoPC(); UpdateDialog(); } break; case IDC_GOTOLR: { ptr->gotoAddr(cpu->GetLR()); } break; case IDC_BACKWARDLINKS: { HWND box = GetDlgItem(m_hDlg, IDC_FUNCTIONLIST); int funcnum = symbolMap.GetSymbolNum(ListBox_GetItemData(box,ListBox_GetCurSel(box))); if (funcnum!=-1) symbolMap.FillListBoxBLinks(box,funcnum); break; } case IDC_ALLFUNCTIONS: { symbolMap.FillSymbolListBox(GetDlgItem(m_hDlg, IDC_FUNCTIONLIST),ST_FUNCTION); break; } default: return FALSE; } return TRUE; } case WM_USER+1: NotifyMapLoaded(); break; case WM_SIZE: { HWND disasm = GetDlgItem(m_hDlg, IDC_DISASMVIEW); HWND funclist = GetDlgItem(m_hDlg, IDC_FUNCTIONLIST); HWND regList = GetDlgItem(m_hDlg, IDC_REGLIST); int wf = regRect.right-regRect.left; int top = 138; MoveWindow(regList,8,top,wf,HIWORD(lParam)-top-8,TRUE); MoveWindow(funclist,8,top,wf,HIWORD(lParam)-top-8,TRUE); int w = LOWORD(lParam)-wf; top = 25; MoveWindow(disasm,wf+15,top, w-20,HIWORD(lParam)-top-8,TRUE); return TRUE; } case WM_GETMINMAXINFO: { MINMAXINFO *m = (MINMAXINFO *)lParam; m->ptMinTrackSize.x=minRect.right-minRect.left; //m->ptMaxTrackSize.x=m->ptMinTrackSize.x; m->ptMinTrackSize.y=minRect.bottom-minRect.top; } return TRUE; case WM_CLOSE: Show(false); return TRUE; } return FALSE; }
// Private Methods ////////////////////////////////////////////////////////////// void GPS_NMEA_Class::parse_nmea_gps(void) { byte NMEA_check; long aux_deg; long aux_min; char *parseptr; if (strncmp(buffer,"$GPGGA",6)==0){ // Check if sentence begins with $GPGGA if (buffer[bufferidx-4]=='*'){ // Check for the "*" character NMEA_check = parseHex(buffer[bufferidx-3])*16 + parseHex(buffer[bufferidx-2]); // Read the checksums characters if (GPS_checksum == NMEA_check){ // Checksum validation //Serial.println("buffer"); NewData = 1; // New GPS Data parseptr = strchr(buffer, ',')+1; //parseptr = strchr(parseptr, ',')+1; Time = parsenumber(parseptr,2); // GPS UTC time hhmmss.ss parseptr = strchr(parseptr, ',')+1; // aux_deg = parsedecimal(parseptr,2); // degrees aux_min = parsenumber(parseptr+2,4); // minutes (sexagesimal) => Convert to decimal Lattitude = aux_deg*10000000 + (aux_min*50)/3; // degrees + minutes/0.6 (*10000000) (0.6 = 3/5) parseptr = strchr(parseptr, ',')+1; // if (*parseptr=='S') Lattitude = -1*Lattitude; // South Lattitudes are negative // parseptr = strchr(parseptr, ',')+1; // W Longitudes are Negative aux_deg = parsedecimal(parseptr,3); // degrees aux_min = parsenumber(parseptr+3,4); // minutes (sexagesimal) Longitude = aux_deg*10000000 + (aux_min*50)/3; // degrees + minutes/0.6 (*10000000) //Longitude = -1*Longitude; // This Assumes that we are in W longitudes... parseptr = strchr(parseptr, ',')+1; // if (*parseptr=='W') Longitude = -1*Longitude; // West Longitudes are negative // parseptr = strchr(parseptr, ',')+1; Fix = parsedecimal(parseptr,1); parseptr = strchr(parseptr, ',')+1; NumSats = parsedecimal(parseptr,2); parseptr = strchr(parseptr, ',')+1; HDOP = parsenumber(parseptr,1); // HDOP * 10 parseptr = strchr(parseptr, ',')+1; Altitude = parsenumber(parseptr,1)*100; // Altitude in decimeters*100 = milimeters if (Fix < 1) Quality = 0; // No FIX else if(NumSats<5) Quality = 1; // Bad (Num sats < 5) else if(HDOP>30) Quality = 2; // Poor (HDOP > 30) else if(HDOP>25) Quality = 3; // Medium (HDOP > 25) else Quality = 4; // Good (HDOP < 25) } else { if (PrintErrors) Serial.println("GPSERR: Checksum error!!"); } } } else if (strncmp(buffer,"$GPVTG",6)==0){ // Check if sentence begins with $GPVTG //Serial.println(buffer); if (buffer[bufferidx-4]=='*'){ // Check for the "*" character NMEA_check = parseHex(buffer[bufferidx-3])*16 + parseHex(buffer[bufferidx-2]); // Read the checksums characters if (GPS_checksum == NMEA_check){ // Checksum validation parseptr = strchr(buffer, ',')+1; Ground_Course = parsenumber(parseptr,2); // Ground course in degrees * 100 parseptr = strchr(parseptr, ',')+1; parseptr = strchr(parseptr, ',')+1; parseptr = strchr(parseptr, ',')+1; parseptr = strchr(parseptr, ',')+1; parseptr = strchr(parseptr, ',')+1; parseptr = strchr(parseptr, ',')+1; Ground_Speed = parsenumber(parseptr,2)*10/36; // Convert Km/h to m/s (*100) //GPS_line = true; } else { if (PrintErrors) Serial.println("GPSERR: Checksum error!!"); } } } else { bufferidx = 0; if (PrintErrors) Serial.println("GPSERR: Bad sentence!!"); } }
/** * Parse data for the given GPS and store values. * This will find longitude, latitude, altitude, fix and more. * Values are used to calculate height and range differences and direction. */ boolean GPS::parse(char *nmea) { // first look if we even have one if (nmea[strlen(nmea)-4] == '*') { uint16_t sum = parseHex(nmea[strlen(nmea)-3]) * 16; sum += parseHex(nmea[strlen(nmea)-2]); // Calculate checksum diff for (uint8_t i=1; i < (strlen(nmea)-4); i++) sum ^= nmea[i]; // Check for bad checksum if (sum != 0) return false; } // Look for known keyword -> GGA if (strstr(nmea, "$GPGGA")) { char *p = nmea; // Get time p = strchr(p, ',')+1; // Parse out latitude p = strchr(p, ',')+1; latitude = atof(p); p = strchr(p, ',')+1; latitude = latitude*compassDirection(p[0]); // Parse out longitude p = strchr(p, ',')+1; longitude = atof(p); p = strchr(p, ',')+1; longitude = longitude*compassDirection(p[0]); // Parse rest of the stored information p = strchr(p, ',')+1; fixquality = atoi(p); p = strchr(p, ',')+1; satellites = atoi(p); p = strchr(p, ',')+1; HDOP = atof(p); p = strchr(p, ',')+1; altitude = atof(p); p = strchr(p, ',')+1; p = strchr(p, ',')+1; geoidheight = atof(p); return true; } // Look for known keyword -> RMC if (strstr(nmea, "$GPRMC")) { char *p = nmea; // Get time p = strchr(p, ',')+1; float timef = atof(p); uint32_t time = timef; hour = time / 10000; minute = (time % 10000) / 100; seconds = (time % 100); milliseconds = fmod(timef, 1.0) * 1000; p = strchr(p, ',')+1; if (p[0] == 'A') fix = true; else if (p[0] == 'V') fix = false; else return false; // Parse latitude p = strchr(p, ',')+1; latitude = atof(p); p = strchr(p, ',')+1; if (p[0] == 'N') lat = 'N'; else if (p[0] == 'S') lat = 'S'; else if (p[0] == ',') lat = 0; else return false; // parse out longitude p = strchr(p, ',')+1; longitude = atof(p); p = strchr(p, ',')+1; if (p[0] == 'W') lon = 'W'; else if (p[0] == 'E') lon = 'E'; else if (p[0] == ',') lon = 0; else return false; // Velocity p = strchr(p, ',')+1; speed = atof(p); // Angle p = strchr(p, ',')+1; angle = atof(p); p = strchr(p, ',')+1; uint32_t fulldate = atof(p); day = fulldate / 10000; month = (fulldate % 10000) / 100; year = (fulldate % 100); // There is still some information left, // but this is currently not relevant. return true; } return false; }
/** * Parse given command line * * @param line Line string to parse */ void parseLine(char * line) { unsigned char result = BELL; switch (line[0]) { case 'S': // Setup with standard CAN bitrates if (state == STATE_CONFIG) { switch (line[1]) { case '0': mcp2515_set_bittiming(MCP2515_TIMINGS_10K); result = CR; break; case '1': mcp2515_set_bittiming(MCP2515_TIMINGS_20K); result = CR; break; case '2': mcp2515_set_bittiming(MCP2515_TIMINGS_50K); result = CR; break; case '3': mcp2515_set_bittiming(MCP2515_TIMINGS_100K); result = CR; break; case '4': mcp2515_set_bittiming(MCP2515_TIMINGS_125K); result = CR; break; case '5': mcp2515_set_bittiming(MCP2515_TIMINGS_250K); result = CR; break; case '6': mcp2515_set_bittiming(MCP2515_TIMINGS_500K); result = CR; break; case '7': mcp2515_set_bittiming(MCP2515_TIMINGS_800K); result = CR; break; case '8': mcp2515_set_bittiming(MCP2515_TIMINGS_1M); result = CR; break; } } break; case 's': // Setup with user defined timing settings for CNF1/CNF2/CNF3 if (state == STATE_CONFIG) { unsigned long cnf1, cnf2, cnf3; if (parseHex(&line[1], 2, &cnf1) && parseHex(&line[3], 2, &cnf2) && parseHex(&line[5], 2, &cnf3)) { mcp2515_set_bittiming(cnf1, cnf2, cnf3); result = CR; } } break; case 'G': // Read given MCP2515 register { unsigned long address; if (parseHex(&line[1], 2, &address)) { unsigned char value = mcp2515_read_register(address); sendByteHex(value); result = CR; } } break; case 'W': // Write given MCP2515 register { unsigned long address, data; if (parseHex(&line[1], 2, &address) && parseHex(&line[3], 2, &data)) { mcp2515_write_register(address, data); result = CR; } } break; case 'V': // Get versions { usb_putch('V'); sendByteHex(VERSION_HARDWARE); sendByteHex(VERSION_FIRMWARE_MAJOR); result = CR; } break; case 'v': // Get firmware version { usb_putch('v'); sendByteHex(VERSION_FIRMWARE_MAJOR); sendByteHex(VERSION_FIRMWARE_MINOR); result = CR; } break; case 'N': // Get serial number { usb_putch('N'); sendHex(0xFFFF, 4); result = CR; } break; case 'O': // Open CAN channel if (state == STATE_CONFIG) { mcp2515_bit_modify(MCP2515_REG_CANCTRL, 0xE0, 0x00); // set normal operating mode clock_reset(); state = STATE_OPEN; result = CR; } break; case 'l': // Loop-back mode if (state == STATE_CONFIG) { mcp2515_bit_modify(MCP2515_REG_CANCTRL, 0xE0, 0x40); // set loop-back state = STATE_OPEN; result = CR; } break; case 'L': // Open CAN channel in listen-only mode if (state == STATE_CONFIG) { mcp2515_bit_modify(MCP2515_REG_CANCTRL, 0xE0, 0x60); // set listen-only mode state = STATE_LISTEN; result = CR; } break; case 'C': // Close CAN channel if (state != STATE_CONFIG) { mcp2515_bit_modify(MCP2515_REG_CANCTRL, 0xE0, 0x80); // set configuration mode state = STATE_CONFIG; result = CR; } break; case 'r': // Transmit standard RTR (11 bit) frame case 'R': // Transmit extended RTR (29 bit) frame case 't': // Transmit standard (11 bit) frame case 'T': // Transmit extended (29 bit) frame if (state == STATE_OPEN) { if (transmitStd(line)) { if (line[0] < 'Z') usb_putch('Z'); else usb_putch('z'); result = CR; } } break; case 'F': // Read status flags { unsigned char flags = mcp2515_read_register(MCP2515_REG_EFLG); unsigned char status = 0; if (flags & 0x01) status |= 0x04; // error warning if (flags & 0xC0) status |= 0x08; // data overrun if (flags & 0x18) status |= 0x20; // passive error if (flags & 0x20) status |= 0x80; // bus error usb_putch('F'); sendByteHex(status); result = CR; } break; case 'Z': // Set time stamping { unsigned long stamping; if (parseHex(&line[1], 1, &stamping)) { timestamping = (stamping != 0); result = CR; } } break; case 'm': // Set accpetance filter mask if (state == STATE_CONFIG) { unsigned long am0, am1, am2, am3; if (parseHex(&line[1], 2, &am0) && parseHex(&line[3], 2, &am1) && parseHex(&line[5], 2, &am2) && parseHex(&line[7], 2, &am3)) { mcp2515_set_SJA1000_filter_mask(am0, am1, am2, am3); result = CR; } } break; case 'M': // Set accpetance filter code if (state == STATE_CONFIG) { unsigned long ac0, ac1, ac2, ac3; if (parseHex(&line[1], 2, &ac0) && parseHex(&line[3], 2, &ac1) && parseHex(&line[5], 2, &ac2) && parseHex(&line[7], 2, &ac3)) { mcp2515_set_SJA1000_filter_code(ac0, ac1, ac2, ac3); result = CR; } } break; } usb_putch(result); }
boolean Adafruit_GPS::parse(char *nmea) { // do checksum check // first look if we even have one if (nmea[strlen(nmea)-4] == '*') { uint16_t sum = parseHex(nmea[strlen(nmea)-3]) * 16; sum += parseHex(nmea[strlen(nmea)-2]); // check checksum for (uint8_t i=1; i < (strlen(nmea)-4); i++) { sum ^= nmea[i]; } if (sum != 0) { // bad checksum :( //return false; } } // look for a few common sentences if (strstr(nmea, "$GPGGA")) { // found GGA char *p = nmea; // get time p = strchr(p, ',')+1; float timef = atof(p); uint32_t time = timef; hour = time / 10000; minute = (time % 10000) / 100; seconds = (time % 100); milliseconds = fmod(timef, 1.0) * 1000; // parse out latitude p = strchr(p, ',')+1; latitude = atof(p); p = strchr(p, ',')+1; if (p[0] == 'N') lat = 'N'; else if (p[0] == 'S') lat = 'S'; else if (p[0] == ',') lat = 0; else return false; // parse out longitude p = strchr(p, ',')+1; longitude = atof(p); p = strchr(p, ',')+1; if (p[0] == 'W') lon = 'W'; else if (p[0] == 'E') lon = 'E'; else if (p[0] == ',') lon = 0; else return false; p = strchr(p, ',')+1; fixquality = atoi(p); p = strchr(p, ',')+1; satellites = atoi(p); p = strchr(p, ',')+1; HDOP = atof(p); p = strchr(p, ',')+1; altitude = atof(p); p = strchr(p, ',')+1; p = strchr(p, ',')+1; geoidheight = atof(p); return true; } if (strstr(nmea, "$GPRMC")) { // found RMC char *p = nmea; // get time p = strchr(p, ',')+1; float timef = atof(p); uint32_t time = timef; hour = time / 10000; minute = (time % 10000) / 100; seconds = (time % 100); milliseconds = fmod(timef, 1.0) * 1000; p = strchr(p, ',')+1; // Serial.println(p); if (p[0] == 'A') fix = true; else if (p[0] == 'V') fix = false; else return false; // parse out latitude p = strchr(p, ',')+1; latitude = atof(p); p = strchr(p, ',')+1; if (p[0] == 'N') lat = 'N'; else if (p[0] == 'S') lat = 'S'; else if (p[0] == ',') lat = 0; else return false; // parse out longitude p = strchr(p, ',')+1; longitude = atof(p); p = strchr(p, ',')+1; if (p[0] == 'W') lon = 'W'; else if (p[0] == 'E') lon = 'E'; else if (p[0] == ',') lon = 0; else return false; // speed p = strchr(p, ',')+1; speed = atof(p); // angle p = strchr(p, ',')+1; angle = atof(p); p = strchr(p, ',')+1; uint32_t fulldate = atof(p); day = fulldate / 10000; month = (fulldate % 10000) / 100; year = (fulldate % 100); // we dont parse the remaining, yet! return true; } return false; }
static int parseIntelHex(char *hexfile, char buffer[131072 + 256]) { int address, base, d, segment, i, lineLen, sum, extSegAddr; FILE *input; extSegAddr = 0; input = fopen(hexfile, "r"); if(input == NULL){ fprintf(stderr, "error opening %s: %s\n", hexfile, strerror(errno)); return 1; } while(parseUntilColon(input) == ':'){ sum = 0; sum += lineLen = parseHex(input, 2); base = address = parseHex(input, 4); sum += address >> 8; sum += address; address += extSegAddr; base += extSegAddr; if(address >= 0x7000) break; sum += segment = parseHex(input, 2); /* segment value? */ if(segment == 0x02) /* Extended Segment Address Records (HEX86)*/ { extSegAddr = parseHex(input, 4); extSegAddr = (extSegAddr << 4) & 0xFFFF0; continue; }else if(segment != 0) /* ignore lines where this byte is not 0 */ { continue; } for(i = 0; i < lineLen ; i++){ d = parseHex(input, 2); buffer[address++] = d; sum += d; } sum += parseHex(input, 2); if((sum & 0xff) != 0){ fprintf(stderr, "Warning: Checksum error between address 0x%x and 0x%x\n", base, address); } if(start) { startAddress[addressIndex] = base; endAddress[addressIndex] = address; start = 0; // fprintf(stderr, "s[%d]=%x, e[%d]=%x \n", addressIndex, startAddress[addressIndex], addressIndex, endAddress[addressIndex]); } if ((base - endAddress[addressIndex]) >= 32 || (endAddress[addressIndex] - base) >= 32) { addressIndex++; startAddress[addressIndex] = base; // fprintf(stderr, "s[%d]=%x, e[%d]=%x \n", addressIndex, startAddress[addressIndex], addressIndex, endAddress[addressIndex]); } endAddress[addressIndex] = address; // fprintf(stderr, "s[%d]=%x, e[%d]=%x \n", addressIndex, startAddress[addressIndex], addressIndex, endAddress[addressIndex]); } #ifdef DEBUG for(i = 0; i <= addressIndex; i++) { fprintf(stderr, "s[%d]=%x, e[%d]=%x \n", i, startAddress[i], i, endAddress[i]); } #endif fclose(input); return 0; }