Sha256: 6e263de37c6df42cff6c68eac274d0d342e7c44ea3673e49e50b489b3958e28a

Contents?: true

Size: 1.69 KB

Versions: 7

Compression:

Stored size: 1.69 KB

Contents

module Denko
  module Connection
    class HandshakeError < StandardError; end

    class HandshakeAttempt
      attr_reader :acknowledged, :result
      def initialize
        @acknowledged = false
        @result = nil
      end

      def update(line)
        if line.match(/\AACK:/)
          @result = line.split(":", 2)[1]
          @acknowledged = true
        end
      end
    end

    module Handshake
      HANDSHAKE_TRIES = 3
      HANDSHAKE_TIMEOUT = 2

      def handshake
        io_reset
        HANDSHAKE_TRIES.times do |retries|
          begin
            print "Sending handshake to: #{self.to_s}... "
            self.add_observer(attempt = HandshakeAttempt.new)
            write Message.encode(command: 90)

            Timeout.timeout(HANDSHAKE_TIMEOUT) do
              loop do
                sleep 0.001
                if attempt.acknowledged
                  puts "Acknowledged. Hardware ready...\n\n"
                  
                  # Stop the handshake attempt from observing.
                  self.delete_observer(attempt)
                  
                  # We reset the board, so reset the transit mutex.
                  @transit_mutex.synchronize { @transit_bytes = 0 }
                  
                  # Return the data part of the ACK line.
                  return attempt.result
                end
              end
            end
          rescue Timeout::Error
            self.delete_observer(attempt)
            print "No response, "
            puts (retries + 1 < HANDSHAKE_TRIES ? "retrying..." : "exiting...")
            next
          end
        end
        raise HandshakeError, "Connected to wrong device, or device not running denko"
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
denko-0.13.6 lib/denko/connection/handshake.rb
denko-0.13.5 lib/denko/connection/handshake.rb
denko-0.13.4 lib/denko/connection/handshake.rb
denko-0.13.3 lib/denko/connection/handshake.rb
denko-0.13.2 lib/denko/connection/handshake.rb
denko-0.13.1 lib/denko/connection/handshake.rb
denko-0.13.0 lib/denko/connection/handshake.rb