-
Notifications
You must be signed in to change notification settings - Fork 2
/
SketchSource.cpp
89 lines (77 loc) · 2.7 KB
/
SketchSource.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include "SketchSource.h"
void SketchSource::reset()
{
_state = ParseState::Start;
_address = 0u;
_byteCount = 0u;
}
int SketchSource::readBytes(uint8_t *buf, uint16_t size)
{
uint16_t read = 0u;
while (read < size) {
switch (_state) {
case ParseState::Start: {
for (int c = hexRead(); c != ':'; c = hexRead()) {
if (c < 0) return read;
}
int newByteCount = readHexByte();
if (newByteCount < 0) return -1;
int hadress = readHexByte();
int laddress = readHexByte();
if (hadress < 0 || laddress < 0) return -1;
uint16_t newAddress = ((uint8_t) hadress << 8) + laddress;
int recordType = readHexByte();
if (recordType < 0) return -1;
_state = (recordType == 0) ? ParseState::Data : ParseState::Start;
if (recordType == 0) {
if (_address + _byteCount != newAddress) {
_ui.print(F("Gap in addresses in hex file at byte address "));
_ui.println(newAddress);
return -1;
}
_address = newAddress;
_byteCount = newByteCount;
_bytesLeft = _byteCount;
}
}
break;
case ParseState::Data:
if (_bytesLeft <= 0) {
if (read > 0) {
// we are done reading a line
// if pageAlign is false, return what we have before loading new address
// if true, proceed to next line where we'll check for contiguous addresses
if (_pageAlign) {
_state = ParseState::Start;
}
else {
return read;
}
}
_state = ParseState::Start;
} else {
int b = readHexByte();
if (b < 0) return -1;
*buf++ = (uint8_t) b;
_bytesLeft--;
read++;
}
break;
}
}
return read;
}
int SketchSource::readHexByte()
{
int c1 = hexRead();
int c2 = hexRead();
if (c1 < 0 || c2 < 0) {
return -1;
}
return (uint8_t) (((c1 <= '9' ? (c1 - '0') : 10 + (c1 <= 'F' ? c1 - 'A' : c1 - 'a')) << 4) +
(c2 <= '9' ? (c2 - '0') : 10 + (c2 <= 'F' ? c2 - 'A' : c2 - 'a')));
}
uint16_t SketchSource::getLineAddress()
{
return _address;
}