float HTU21D::readHumidity(){ Wire.beginTransmission(HTDU21D_ADDRESS); Wire.write(TRIGGER_HUMD_MEASURE_NOHOLD); Wire.endTransmission(); // Wait for the sensor to measure delay(18); // 16ms measure time for 12bit measures Wire.requestFrom(HTDU21D_ADDRESS, 3); //Wait for data to become available int counter = 0; while(!Wire.available()){ counter++; delay(1); if(counter > 100) return HTU21D_I2C_TIMEOUT; //after 100ms consider I2C timeout } uint16_t h = Wire.read(); h <<= 8; h |= Wire.read(); // CRC check uint8_t crc = Wire.read(); if(checkCRC(h, crc) != 0) return(HTU21D_BAD_CRC); h &= 0xFFFC; // zero the status bits float hum = h; hum *= 125; hum /= 65536; hum -= 6; return hum; }
float HTU21D::readTemperature(){ Wire.beginTransmission(HTDU21D_ADDRESS); Wire.write(TRIGGER_TEMP_MEASURE_NOHOLD); Wire.endTransmission(); // Wait for the sensor to measure delay(55); // 50ms measure time for 14bit measures Wire.requestFrom(HTDU21D_ADDRESS, 3); //Wait for data to become available int counter = 0; while(!Wire.available()){ counter++; delay(1); if(counter > 100) return HTU21D_I2C_TIMEOUT; //after 100ms consider I2C timeout } uint16_t t = Wire.read(); t <<= 8; t |= Wire.read(); // CRC check uint8_t crc = Wire.read(); if( checkCRC(t, crc) != 0) return(HTU21D_BAD_CRC); t &= 0xFFFC; // zero the status bits float temp = t; temp *= 175.72; temp /= 65536; temp -= 46.85; return temp; }
void decodeIt(void) { if(received[0] == SlaveAddress){ if(checkCRC()){ if(received[1] == 0x01){ readCoil(); } else if(received[1] == 0x02){ readInputCoil(); } else if(received[1] == 0x03){ readReg(); } else if(received[1] == 0x04){ readInputReg(); } else if(received[1] == 0x05){ writeCoil(); } else if(received[1] == 0x06){ writeReg(); } else if(received[1] == 0x10){ writeMultipleRegs(); } else if(received[1] == 0x0F){ writeMultipleCoils(); } else{ response[0] = 0; //error this does nothing though.. } } } modbusMessage = 0; }
uint8_t RF24BLE::recvPacket(uint8_t *input, uint8_t length,uint8_t channel ){ unsigned long time = millis(); while (_radio.available()<=0 && (millis()-time)<RECV_TIMEOUT){delay(1);} if (_radio.available()>0){ _radio.read(input, length); } else { return RF24BLE_TIMEOUT; } uint8_t i, dataLen = length - 3; #if DEBUG == 1 // Packet length includes crc of 3 bytes for (i = 0; i < length; i++){ Serial.print((char)input[i]); } Serial.println(); #endif //reversing the bits of the complete packet for (i = 0; i < length; i++){ input[i] = reverseBits(input[i]); } //de-whiten the packet using the same polynomial bleWhiten(input, length, bleWhitenStart(RF24BLE::chLe[channel])); //reversing bits of the crc for (i = 0; i < 3; i++, dataLen++){ input[dataLen] = reverseBits(input[dataLen]); } #if DEBUG == 1 for (i = 0; i < length; i++){ Serial.print((char)input[i]); } Serial.println(); #endif return checkCRC(input, length); }
bool decode(void) { validMIRP_rx = 0; if(!PORTBbits.RB5) { if(checkStart()) { /*mirpRx.id_h = decodeByte(); mirpRx.id_l = decodeByte(); mirpRx.spell_id = decodeByte(); mirpRx.str = decodeByte(); mirpRx.uuid = decodeByte(); mirpRx.crc = decodeByte();*/ /*mirp[0] = decodeByte(); //id_h mirp[1] = decodeByte(); //id_l mirp[2] = decodeByte(); //spell mirp[3] = decodeByte(); //str mirp[4] = decodeByte(); //uuid mirp[5] = decodeByte(); //crc*/ IDH = decodeByte(); IDL = decodeByte(); SPELL = decodeByte(); STR = decodeByte(); UID = decodeByte(); CRC = decodeByte(); } validMIRP_rx = checkCRC(); } counter_rx = 0; //move this out here return validMIRP_rx; }
//Given a command, reads a given 2-byte value with CRC from the HTU21D uint16_t HTU21D::readValue(byte cmd) { //Request a humidity reading _i2cPort->beginTransmission(HTU21D_ADDRESS); _i2cPort->write(cmd); //Measure value (prefer no hold!) _i2cPort->endTransmission(); //Hang out while measurement is taken. datasheet says 50ms, practice may call for more bool validResult; byte counter; for (counter = 0, validResult = 0 ; counter < MAX_COUNTER && !validResult ; counter++) { delay(DELAY_INTERVAL); //Comes back in three bytes, data(MSB) / data(LSB) / Checksum validResult = (3 == _i2cPort->requestFrom(HTU21D_ADDRESS, 3)); } if (!validResult) return (ERROR_I2C_TIMEOUT); //Error out byte msb, lsb, checksum; msb = _i2cPort->read(); lsb = _i2cPort->read(); checksum = _i2cPort->read(); uint16_t rawValue = ((uint16_t) msb << 8) | (uint16_t) lsb; if (checkCRC(rawValue, checksum) != 0) return (ERROR_BAD_CRC); //Error out return rawValue & 0xFFFC; // Zero out the status bits }
bool ModBusUART_Impl::readRegisterPool(quint16 id, quint16 regNumber, quint16 regCount,QVector<quint16>& o_list) { if (!m_port.isOpen()) return false; quint16 regNumberBig = qToBigEndian<quint16>(regNumber); quint16 regCountBig = qToBigEndian<quint16>(regCount); QByteArray data = QByteArray::fromRawData((const char*)& regNumberBig, sizeof(quint16)); data += QByteArray::fromRawData((const char*)& regCountBig, sizeof(quint16)); QByteArray req = makeRTUFrame(id, 3, data); QMutexLocker locker(&m_mutex); m_port.write(req); if ( ! m_port.waitForBytesWritten(m_timeOut)) { return false; } int responseLengthMust = 1 + 1 + 1 + 2 * regCount + 2; if ( m_port.waitForReadyRead(m_timeOut)) { QByteArray responseData = m_port.readAll(); while (m_port.waitForReadyRead(50)) responseData += m_port.readAll(); if ( ! checkCRC(responseData)) return false; if (responseData.size() != responseLengthMust || responseData[1] != char(3) || responseData[0] != char(id)) return false; o_list.clear(); const uchar* d = (const uchar *)responseData.data() + 3; for (int i = 0; i < regCount; i++) { quint16 v = qFromBigEndian<quint16>(d + i * 2); o_list.push_back(v); } } else { return false; } return true; }
bool ModBusUART_Impl::writeRegister(quint16 id, quint16 regNumber, quint16 value) { if (!m_port.isOpen()) return false; quint16 regNumberBig = qToBigEndian<quint16>(regNumber); quint16 valueBig = qToBigEndian<quint16>(value); QByteArray data = QByteArray::fromRawData((const char*)& regNumberBig, sizeof(quint16)); data.append(QByteArray::fromRawData((const char*)&valueBig, sizeof(quint16))); data += QByteArray::fromRawData((const char*)& value, sizeof(qint16)); QByteArray req = makeRTUFrame(id, 6, data); QMutexLocker locker(&m_mutex); m_port.write(req); if (!m_port.waitForBytesWritten(m_timeOut)) { return false; } if (m_port.waitForReadyRead(m_timeOut)) { QByteArray responseData = m_port.readAll(); while (m_port.waitForReadyRead(50)) responseData += m_port.readAll(); if ( ! checkCRC(responseData)) return false; if (responseData.size() == 8 && responseData[1] != char(6) || responseData[0] != char(id)) { return true; } } return false; }
/* ---------------------------------------------------------------------------- * @brief читаем значение Length далее читаем данные размером length * AK -> OK(все данные получили ) | ERR (ошибка) */ static void recvVal(struct Param *p) { const int error = -1; int exec = -1; int length = 0; unsigned char len[2] = {0}; unsigned char crcTxt[2] = {0}; exec = bo_recvAllData(p->sock, len, 2, 2); if(exec == -1) goto error; else { length = boCharToInt(len); if(length <= p->bufSize) { memset(p->buf, 0, p->bufSize); exec = bo_recvAllData(p->sock, (unsigned char *)p->buf, p->bufSize, length); if(exec == -1) goto error; exec = bo_recvAllData(p->sock, crcTxt, 2, 2); if(exec == -1) goto error; exec = checkCRC(crcTxt, p->buf, length); if(exec == -1) { bo_log("bo_net_get_route.c recvVal() incorrect CRC"); goto error; } else p->length = length; } else { bo_log("bo_net_get_route.c recvVal() bad length[%d] bufSize=[%d]", length, p->bufSize); goto error; } } status = END; if(error == 1) { error: bo_log("bo_net_get_route.c recvVal() errno[%s]", strerror(errno)); status = ERR; } }
bool ModBusUART_Impl::readDeviceInfo(quint16 id, QString& vendor, QString& product, QString& version) { if (!m_port.isOpen()) return false; const char reqBody[] = { char(0x0E), char(1), char(0) }; QByteArray reqBodyArray(reqBody); reqBodyArray.append(char(0)); QByteArray req = makeRTUFrame(id, 43, reqBodyArray); QMutexLocker locker(&m_mutex); for (int retryCount = 10; retryCount; retryCount--) { m_port.write(req); if (!m_port.waitForBytesWritten(m_timeOut)) { return false; } if (m_port.waitForReadyRead(m_timeOut)) { QByteArray responseData = m_port.readAll(); while (m_port.waitForReadyRead(50)) responseData += m_port.readAll(); if (!checkCRC(responseData)) { m_port.clear(); continue; } if (responseData[1] != char(43) || responseData[0] != char(id) || responseData[2] != char(0x0e) || responseData[3] != char(1)) return false; try { int numberOfObjects = responseData[7]; if (numberOfObjects < 3) return false; for (int i = 0, startIndex = 8; i < numberOfObjects; i++) { if (i != responseData[startIndex]) return false; int len = responseData[startIndex + 1]; std::string a_string(responseData.data() + startIndex + 2, len); QString* target; switch (i) { case 0: target = &vendor; break; case 1: target = &product; break; case 2: target = &version; break; } (*target) = QString::fromStdString(a_string); startIndex += len + 2; } return true; } catch (...) { } } } return false; }
// processData. processData assembles the frames and calls to transitionAction. void EZRoboNetDevice::processData() { int i; uint16_t numBytesToRead = CommPort->available(); // let's see what we 've got... do { if (remainingBytes==0) { // previous frame was fully read if (numBytesToRead>=6) { // nead at least 6 bytes to read frame header // get the first 6 bytes (starter(1)+sender-receiverid(2)+frame type(1)+payload length (2)) // reading first 6 bytes into FrameHead for (i=0; i<6; i++) FrameHead[i] = CommPort->read(); // now cheking for framestarter character mismatch if (FrameHead[0]!=framestarter) { flushSerialBuffer(); } else {// reamaining bytes should be the payload length plus the terminator and two CRC bytes remainingBytes = FrameHead[4] + FrameHead[5] * 256 +3; } } } else if (numBytesToRead >= remainingBytes) { // it's time to get the remaining frame(s) int totalBytes = remainingBytes + 6; // calculate total length byte buffer[totalBytes]; byte remBuffer[remainingBytes]; // now reading remaining bytes as estimated using the frame header // going altogether for (i=0; i<remainingBytes; i++) remBuffer[i] = CommPort->read(); // tailoring bufhead and rembuffer into buffer for (i=0; i<totalBytes; i++) if (i<6) buffer[i] = FrameHead[i]; else buffer[i] = remBuffer[i-6]; // now handling the message... // checking terminator and CRC uint16_t CRC = buffer[totalBytes-2]+256*buffer[totalBytes-1]; if ((buffer[totalBytes-3]==frameterminator)&&(checkCRC(buffer, totalBytes-2, CRC))) { Serial.println("Frame received!"); EZFrame* frame = bytes2Frame(buffer); // assembled the frame if (frame->ReceiverID == NodeID) // frame was addressed to this node transitionAction(frame); // change internal state and act else // frame was not addressed to this node and being disposed of disposeFrame(frame); } else { Serial.print("Error. Frame CRC :"); Serial.println(CRC, DEC); Serial.print("Frame terminator :"); Serial.println(buffer[totalBytes-3], DEC); } // clearing remaining bytes remainingBytes = 0; } numBytesToRead = CommPort->available(); } while ((numBytesToRead >= remainingBytes)&&(remainingBytes>0)); }
void AbstractPidHandler::parse(const QByteArray &packet) { // If the packet is empty return if (packet.isNull()) return; // Build pointer to packet content const quint8 *data = (quint8 *)packet.constData(), *p = 0; // Return if the packet does not start with 0x47 if (data[0] != 0x47) { qWarning() << "Not a TS packet!"; return; } // Check validity of continuity counter quint8 ccc = data[3] & 0x0F; if (d->ecc == INVALID_CC) { // Conintuity counter has not been yet initialized d->ecc = ccc; // Initialize continuity counter with currrent value } else { // Check if packet is duplicate and just ignore it if it the case if (d->ecc == ccc) { qWarning() << "Duplicate TS packet?!?!?!"; return; } // Compute next continuity counter d->ecc = ++d->ecc & 0x0F; // Check if discontinuity if (d->ecc != ccc) { qDebug() << "Discontinuity!\n"; d->ecc = ccc; emit discontinuity(); } } // Return if no payload in the TS packet if (!data[3] & 0x10) return; // Skip the adaptation field if present if (data[3] & 0x20) // Check if "Adaptation field exists" bit is set p = data + 5 + data[4]; // Point after adaptation field else p = data + 4; // Point to first byte after header // Compute Payload Start Unit Indicator quint8 pusi = data[1] & 0x40; // Skip new section begins if present if (pusi) // Check if "Payload unit start" bit is set p = p + *p + 1; // If no section yet started and the current packet contains the start of a new section then build a new one if (!d->section) { if (!pusi) return; d->section = new Section(this); } // Compute availability of data quint8 available = 188 + data - p; while (available) { // Check if there is enough bytes in the current data buffer to complete the need of the section if (available >= d->section->need) { // Add the needed bytes to the data buffer of the section d->section->data += QByteArray((const char *)p, (int)d->section->need); p += d->section->need; available -= d->section->need; // Check if the section's header has been parsed so far if (!d->section->headerComplete) { // Apparently not! So let's do the job d->section->need = d->section->sectionLength = (((quint16)d->section->data[1] & 0x0F) << 8) | ((quint16)d->section->data[2] & 0xFF); // Done! Let's indicate it d->section->headerComplete = true; // We still need to check if the section isn't too long if (d->section->need > sectionMaxSize() - 3) { qWarning() << "Section too long!"; deleteCurrentSection(); return; // What about remaining bytes? What do we do if there is other sections in the packet? // ... } } else { // Apparently the header is parsed already. We can take care of the payload now and we // will start with checking the CRC if there is one if (hasCRC()) { d->section->validCRC = checkCRC(); } d->section->tableID = d->section->data[0]; d->section->sectionSyntaxIndicator = (d->section->data[1] & 0x80) >> 7; d->section->serviceID = (((quint16)d->section->data[3] & 0xFF) << 8) | ((quint16)d->section->data[4] & 0xFF); d->section->versionNumber = (d->section->data[5] & 0x3E) >> 1; d->section->currentNextIndicator = d->section->data[5] & 0x01; d->section->sectionNumber = d->section->data[6]; d->section->lastSectionNumber = d->section->data[7]; d->section->payload = (const quint8 *)&d->section->data.constData()[8]; d->section->payloadSize = d->section->data.size() - 8; tableComplete(); // We can now dispose of the current section deleteCurrentSection(); // A TS packet may contain any number of sections, only the first // new one is flagged by the pointer_field. If the next payload // byte isn't 0xff then a new section starts. if (available && *p != 0xff) { d->section = new Section(this); } else { available = 0; } } } else {
bool ReadingData::checkCRC() { return checkCRC(this->crc); }