Skip to content

Add simple RLE compression for ArduinoOTA #6609

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
126 changes: 124 additions & 2 deletions libraries/ArduinoOTA/ArduinoOTA.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,114 @@ extern "C" {
#endif
#endif


/* This class is only used in OTA and implements a dumb, low-memory decompression engine */
class RLEDecompressor : public Stream {
public:
RLEDecompressor(WiFiClient client) {
_client = client;
_blockLen = 0;
_blockIdx = 0;
_block = new uint8_t[128];
}

virtual ~RLEDecompressor() {
delete[] _block;
}

virtual int read() {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

add 'override' ?

int ret = -1; // Default to EOF
if (_blockLen == _blockIdx) {
_refill();
}
if (_blockIdx < _blockLen) {
ret = _block[_blockIdx++];
}
return ret;
}

virtual int peek() {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

add 'override' ?

return -1; // Not implemented, not needed for Updater
}

size_t read(uint8_t*a, size_t&b) { return readBytes((char*)a, b); }

virtual size_t readBytes(char *buffer, size_t length) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

add 'override' ?

if (_blockLen == _blockIdx) {
_refill();
}
int toRead = std::min((int)(_blockLen - _blockIdx), (int)length);
memcpy(buffer, _block + _blockIdx, toRead);
_blockIdx += toRead;
return toRead;
}

virtual size_t write(uint8_t b) { return _client.write(b); }

virtual int available() {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

add 'override' ?

if (_blockLen == _blockIdx) {
_refill();
}
return _blockLen - _blockIdx;
}


private:
bool _refill() {
int c = -1;
while (_client.connected() && (c < 0)) {
c = _client.read();
yield();
}
if (c < 0) {
return false;
}
if (c < 128) {
int l = -1;
while (_client.connected() && (l < 0)) {
l = _client.read();
yield();
}
if (l < 0) {
return false;
}
memset(_block, l, c);
_blockLen = c;
_blockIdx = 0;
return true;
} else {
c = c - 128;
_blockLen = c;
_blockIdx = 0;
while (_client.connected() && c) {
int ret = _client.readBytes(_block + _blockIdx, c);
if (ret > 0) {
c -= ret;
_blockIdx += ret;
} else {
_blockIdx = _blockLen = 0;
return false;
}
}
_blockIdx = 0;
return true;
}
}

private:
WiFiClient _client;
int _blockLeft;
int _blockIdx;
int _blockLen;
uint8_t *_block;
};


ArduinoOTAClass::ArduinoOTAClass()
: _port(0)
, _udp_ota(0)
, _initialized(false)
, _useCompression(false)
, _rebootOnSuccess(true)
, _useMDNS(true)
, _state(OTA_IDLE)
Expand Down Expand Up @@ -199,6 +303,15 @@ void ArduinoOTAClass::_onRx(){
if(_md5.length() != 32)
return;

String compress = readStringUntil('\n');
compress.trim();
if (compress == "COMPRESSRLE") {
_useCompression = true;
#ifdef OTA_DEBUG
OTA_DEBUG.println("Compressed upload requested");
#endif
}

ota_ip = _ota_ip;

if (_password.length()){
Expand Down Expand Up @@ -273,7 +386,11 @@ void ArduinoOTAClass::_runUpdate() {
_state = OTA_IDLE;
return;
}
_udp_ota->append("OK", 2);
if (_useCompression) {
_udp_ota->append("COMPOK", 6);
} else {
_udp_ota->append("OK", 2);
}
_udp_ota->send(ota_ip, _ota_udp_port);
delay(100);

Expand Down Expand Up @@ -317,7 +434,12 @@ void ArduinoOTAClass::_runUpdate() {
}
_state = OTA_IDLE;
}
written = Update.write(client);
if (_useCompression) {
RLEDecompressor decomp(client);
written = Update.write(decomp);
} else {
written = Update.write(client);
}
if (written > 0) {
client.print(written, DEC);
total += written;
Expand Down
1 change: 1 addition & 0 deletions libraries/ArduinoOTA/ArduinoOTA.h
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ class ArduinoOTAClass
String _nonce;
UdpContext *_udp_ota;
bool _initialized;
bool _useCompression;
bool _rebootOnSuccess;
bool _useMDNS;
ota_state_t _state;
Expand Down
124 changes: 88 additions & 36 deletions tools/espota.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,43 @@ def update_progress(progress):
sys.stderr.write('.')
sys.stderr.flush()

def rle(data):
"RLE compress the input bitstream and return it as a list"
buf = [0] * 128
ret = []
src = 0
runlen = 0
repeat = False
while src < len(data):
buf[runlen] = data[src]
runlen = runlen + 1
src = src + 1
if runlen < 2:
continue
if repeat:
if buf[runlen - 1] != buf[runlen - 2]:
repeat = False
if (not repeat) or (runlen == 128):
ret += [runlen - 1] + [buf[0]]
buf[0] = buf[runlen - 1]
runlen = 1
else:
if buf[runlen - 1] == buf[runlen - 2]:
repeat = True
if runlen > 2:
ret += [128 + runlen - 2] + buf[0:runlen - 2]
buf[0] = buf[runlen - 1]
buf[1] = buf[runlen - 1]
runlen = 2
continue
if runlen == 128:
ret += [128 + runlen - 1] + buf[0:runlen]
runlen = 0
if runlen:
ret += [128 + runlen] + buf[0:runlen]
return ret


def serve(remoteAddr, localAddr, remotePort, localPort, password, filename, command = FLASH):
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Expand All @@ -89,12 +126,18 @@ def serve(remoteAddr, localAddr, remotePort, localPort, password, filename, comm
sys.stderr.flush()
logging.info(file_check_msg)

content_size = os.path.getsize(filename)
f = open(filename,'rb')
file_md5 = hashlib.md5(f.read()).hexdigest()
f.close()
with open(filename, "rb") as f:
content = f.read()
content_size = len(content)
content_rle = rle(content)
request_rle = len(content_rle) < content_size
# request_rle = True
file_md5 = hashlib.md5(content).hexdigest()
logging.info('Upload size: %d', content_size)
message = '%d %d %d %s\n' % (command, localPort, content_size, file_md5)
if request_rle:
# Add a request for compression, ignored on earlier ArduinoOTAs
message += 'COMPRESSRLE\n'

# Wait for a connection
logging.info('Sending invitation to: %s', remoteAddr)
Expand All @@ -103,42 +146,50 @@ def serve(remoteAddr, localAddr, remotePort, localPort, password, filename, comm
sent = sock2.sendto(message.encode(), remote_address)
sock2.settimeout(10)
try:
data = sock2.recv(128).decode()
data = sock2.recv(256).decode()
except:
logging.error('No Answer')
sock2.close()
return 1
if (data != "OK"):
if(data.startswith('AUTH')):
nonce = data.split()[1]
cnonce_text = '%s%u%s%s' % (filename, content_size, file_md5, remoteAddr)
cnonce = hashlib.md5(cnonce_text.encode()).hexdigest()
passmd5 = hashlib.md5(password.encode()).hexdigest()
result_text = '%s:%s:%s' % (passmd5 ,nonce, cnonce)
result = hashlib.md5(result_text.encode()).hexdigest()
sys.stderr.write('Authenticating...')
sys.stderr.flush()
message = '%d %s %s\n' % (AUTH, cnonce, result)
sock2.sendto(message.encode(), remote_address)
sock2.settimeout(10)
try:
data = sock2.recv(32).decode()
except:
sys.stderr.write('FAIL\n')
logging.error('No Answer to our Authentication')
sock2.close()
return 1
if (data != "OK"):
sys.stderr.write('FAIL\n')
logging.error('%s', data)
sock2.close()
sys.exit(1);
return 1
sys.stderr.write('OK\n')

if data == "COMPOK":
compress = True
elif data == "OK":
compress = False
elif data.startswith('AUTH'):
nonce = data.split()[1]
cnonce_text = '%s%u%s%s' % (filename, content_size, file_md5, remoteAddr)
cnonce = hashlib.md5(cnonce_text.encode()).hexdigest()
passmd5 = hashlib.md5(password.encode()).hexdigest()
result_text = '%s:%s:%s' % (passmd5 ,nonce, cnonce)
result = hashlib.md5(result_text.encode()).hexdigest()
sys.stderr.write('Authenticating...')
sys.stderr.flush()
message = '%d %s %s\n' % (AUTH, cnonce, result)
sock2.sendto(message.encode(), remote_address)
sock2.settimeout(10)
try:
data = sock2.recv(32).decode()
except:
sys.stderr.write('FAIL\n')
logging.error('No Answer to our Authentication')
sock2.close()
return 1
if data == "OK":
compress = False
elif data == "COMPOK":
compress = True
else:
logging.error('Bad Answer: %s', data)
sys.stderr.write('FAIL\n')
logging.error('%s', data)
sock2.close()
sys.exit(1);
return 1
sys.stderr.write('OK\n')
else:
logging.error('Bad Answer: %s', data)
sock2.close()
return 1
sock2.close()

logging.info('Waiting for device...')
Expand All @@ -155,16 +206,17 @@ def serve(remoteAddr, localAddr, remotePort, localPort, password, filename, comm
received_ok = False

try:
f = open(filename, "rb")
if (PROGRESS):
update_progress(0)
else:
sys.stderr.write('Uploading')
sys.stderr.flush()
offset = 0
chunk_size = 1460 # MTU-safe
while True:
chunk = f.read(1460)
if not chunk: break
if offset >= content_size:
break
chunk = content[offset:min(content_size, offset + chunk_size)]
offset += len(chunk)
update_progress(offset/float(content_size))
connection.settimeout(10)
Expand Down