简体   繁体   中英

How to store and pop uint8_t from/to uint32_t asynchronously in C++?

I'm working on a MCU, enhancing the library , making it non-blocking.

It already blocks code using while loop for certain times.

I've tweaked the library to remove all these blockings, sniff out all what should be sent to a std::vector<uint8_t> internalBuffer . and used micros() to asynchronously send bytes through stream output in loop().

I'm Enhancing that by converting std::vector<uint8_t> internalBuffer to std::vector<uint32_t> to take way less space (using ESP8266 with aligned 4 bytes).

I know how to store and extract uint8_t to uint32_t , But when it comes to Asynchronous store and extract, Here comes un-known probabilities to me.

Because storing and extracting uint8_t are asynchronous, storing is anytime, extracting is constrained by time interval.

For what's worth mentioning : I've already done storing, but I don't have a complete extraction code.

void Pos_Printer::storeInBuffer(uint8_t c)
{
    uint32_t longInt = 0UL;
    if (excessBytesInBuffer == 0)
    {
      longInt = c;
    }
    else
    {
      longInt = internalBuffer.back();
      internalBuffer.pop_back();
      longInt = longInt << 8 * excessBytesInBuffer + c;
    }
    excessBytesInBuffer++;
    excessBytesInBuffer %= 4;

    internalBuffer.push_back(longInt);
}

Uncompleted extraction (at CLASS::loop()) :

  if (micros() - resumeTime > 0 && internalBuffer.size())
  {
    uint32_t longInt = 0UL;
    uint8_t byteToSend = 0;

    if(internalBuffer.size() == 1)      
    {                   //Work on excessBytesInBuffer
      longInt = internalBuffer.at(0);
      if(excessBytesInBuffer)
      {                         //What if remained 1 and stored +3 Bytes after this ?
        byteToSend = (longInt >> 8 * excessBytesInBuffer) & 0xFF;

      }
    }
    else
    {    

    }

    stream->write(byteToSend);
    internalBuffer.erase(internalBuffer.begin()); //Uncompleted 
    lastWritingTime = micros();
  }

Another solution : I've thought of another solution, To store 1 of 4 bytes of (uint32_t) to keep track how many bytes stored (from 1 to 3). But that's a big loss if wanted to optimize storing an image to the library (as example).

Just like you keep excessBytesInBuffer in storing, you need something like missingBytesInBuffer in extraction. Then you would only do internalBuffer.erase(internalBuffer.begin()); when missingBytesInBuffer is 4.

You could speed things up if you store four bytes at a time, assuming you have them all on the calling side.

Similarly, you can extract four bytes at a time and keep them in a local buffer (cache).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM