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
class Handler
  def initialize(first_msg)
    @type, @seq, @limit = msg.type, msg.seq, msg.limit
    first_msg.ack!
  end

  def upto(limit)
    if limit > @limit
      raise BadMessage, "Message sequence too short"
    end
    
    loop do
      msg = Message.get

      if msg.type != @type ||
            msg.limit != @limit ||
            msg.seq > limit
        raise BadMessage, "Invalid message continuation"
      end

      yield msg
    end
  end

  def dispatch
    raise NotImplementedError
  end
end

class Protocol
  def initialize(handlers)
    @handlers = handlers
  end

  def dispatch
    loop { dispatch_one }
  end

  def dispatch_one
    msg = Message.get
    return unless msg.seq == 0

    @handlers.find do |handler|
      handler.accept?(msg)
    end.new(msg).dispatch
  rescue e
    # nothing;
    # or: debug_trace(e)
  end
end

class FirmwareFlashHandler
  UNLOCK_KEY = ByteArray("\x00" * 64)

  def initialize(first_msg)
    unless first_msg.payload == UNLOCK_KEY
      raise BadMessage, "Invalid unlock key"
    end

    super
  end

  def dispatch
    flasher = FirmwareFlasher.new

    upto(@limit - 1) do |msg|
      flasher.process(msg.payload)
      msg.ack!
    end

    upto(@limit) do |msg|
      flasher.verify_hash(msg.payload)
      msg.ack!
    end
  end
end

Protocol.new([
  FirmwareFlashHandler
]).dispatch