-
Notifications
You must be signed in to change notification settings - Fork 33
/
intel_hex.rb
65 lines (47 loc) · 1.51 KB
/
intel_hex.rb
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
require "wo_oo/electronics/intel_hex_grammar"
require "wo_oo/util/hex"
require "pp"
class HexFile
def self.read(path)
file_content = File.read(path)
parser = WOoo::Electronics::IntelHexParser.new
result = parser.parse(file_content)
unless result.nil?
hex_data = result.eval
WOoo::Util::HexUtil.to_i(hex_data.scan(/../))
else
# TO FIX
puts "PARSING ERROR!"
puts parser.terminal_failures.join("\n")
puts "----"
end
end
# ----------------------------------------------------------------
def self.write(path, data, start_address = 0)
next_address = start_address
File.open(path, "w") do |file|
while (line_data = data.slice!(0..15)).size > 0
line_size = line_data.size
file.print ":"
line = WOoo::Util::HexUtil.to_hex8(line_size)
line += WOoo::Util::HexUtil.to_hex16(next_address)
line += "00"
line += WOoo::Util::HexUtil.to_hex8(line_data).join("")
file.print line
file.print WOoo::Util::HexUtil.to_hex8(checksum(line))
file.print "\n"
next_address += line_size
end
file.print ":00000001FF"
end
end
# ----------------------------------------------------------------
def self.checksum(data)
checksum = 0
data.scan(/../).each do |value|
checksum += WOoo::Util::HexUtil.to_i(value)
end
checksum = ((checksum & 255) ^ 255) + 1
checksum % 256
end
end