LaunchAPPL/Serial: UnreliableStram to simulate bit errors

This commit is contained in:
Wolfgang Thaller 2018-04-22 14:07:52 +02:00
parent c9f125cb22
commit c66bf4c088
4 changed files with 70 additions and 3 deletions

View File

@ -4,6 +4,7 @@ add_library(LaunchAPPLCommon
ReliableStream.h ReliableStream.h
ReliableStream.cc ReliableStream.cc
CRC32.h CRC32.h
UnreliableStream.h
) )
target_include_directories(LaunchAPPLCommon PUBLIC .) target_include_directories(LaunchAPPLCommon PUBLIC .)

View File

@ -35,6 +35,7 @@ ReliableStream::ReliableStream(Stream& stream)
: stream(stream) : stream(stream)
{ {
incomingPacket.reserve(packetSize + 4); incomingPacket.reserve(packetSize + 4);
stream.setListener(this);
} }
ReliableStream::~ReliableStream() ReliableStream::~ReliableStream()
{ {
@ -65,12 +66,12 @@ void ReliableStream::nack()
printf("nack sent\n"); printf("nack sent\n");
} }
void ReliableStream::gotNack(uint8_t id) void ReliableStream::gotAck(uint8_t id)
{ {
printf("got ack\n"); printf("got ack\n");
} }
void ReliableStream::gotAck(uint8_t id) void ReliableStream::gotNack(uint8_t id)
{ {
printf("got nack\n"); printf("got nack\n");
} }

View File

@ -0,0 +1,56 @@
#ifndef UNRELIABLESTREAM_H_
#define UNRELIABLESTREAM_H_
#include "Stream.h"
// A stream filter to simulate bit errors
class UnreliableStream : public Stream, private StreamListener
{
Stream& stream_;
int nextError = 0;
public:
UnreliableStream(Stream& stream)
: stream_(stream)
{
stream_.setListener(this);
setupNextError();
}
virtual void write(const void* p, size_t n) override
{
std::vector<uint8_t> tmp(n);
memcpy(tmp.data(), p, n);
maybeFlipBit(tmp.data(), n);
stream_.write(tmp.data(),n);
}
virtual void flushWrite() override
{
stream_.flushWrite();
}
private:
virtual size_t onReceive(const uint8_t* p, size_t n) override
{
std::vector<uint8_t> tmp(n);
memcpy(tmp.data(), p, n);
maybeFlipBit(tmp.data(), n);
notifyReceive(tmp.data(), n);
return n;
}
void setupNextError()
{
nextError += 8 * 1000 + 3;
}
void maybeFlipBit(uint8_t* p, size_t n)
{
while(nextError < n * 8)
{
p[n / 8] ^= 0x80 >> (n%8);
setupNextError();
}
nextError -= n * 8;
}
};
#endif

View File

@ -9,6 +9,8 @@
#include <ReliableStream.h> #include <ReliableStream.h>
#include <Processes.h> #include <Processes.h>
#include <UnreliableStream.h>
class MacSerialStream : public Stream class MacSerialStream : public Stream
{ {
static const long kInputBufferSize = 4096; static const long kInputBufferSize = 4096;
@ -195,8 +197,15 @@ int main()
{ {
MacSerialStream stream; MacSerialStream stream;
//#define SIMULATE_ERRORS
#ifdef SIMULATE_ERRORS
UnreliableStream uStream(stream);
ReliableStream rStream(uStream);
#else
ReliableStream rStream(stream); ReliableStream rStream(stream);
stream.setListener(&rStream); #endif
Listener listener; Listener listener;
rStream.setListener(&listener); rStream.setListener(&listener);