Class: PrintClient::PrintLabels

Inherits:
Object
  • Object
show all
Defined in:
lib/print_client.rb

Instance Method Summary collapse

Constructor Details

#initializePrintLabels

Returns a new instance of PrintLabels.



37
38
39
40
# File 'lib/print_client.rb', line 37

def initialize
  config = YAML::load_file("./virtusprinter.yml")
  @vp_computer = config['virtusprinter']['computer']
end

Instance Method Details

#startObject



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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
# File 'lib/print_client.rb', line 41

def start
  virtus_printer = VirtusPrinter.new
  log = Logger.new('log.txt', shift_age = 5, shift_size = 6048576)
  log.level = Logger::DEBUG
  log.debug 'Started logging'
  while true
    begin
      sleep 1
      result = false
      data = {}
      time = Benchmark.realtime do
        result, data = virtus_printer.get_labels(@vp_computer)
      end
      log.debug "Time spent in virtusprinter: #{time}"
      unless result
        print " #{virtus_printer.error} "
        next
      end
      print '.'

      xml_doc = Nokogiri::XML(data)
      labels = xml_doc.css("labels label")
      next if labels.count == 0

      # Open all required ports
      ports = {}
      labels.each do |l|
        port = l.at_css('port').content
        unless ports.include?(port)
          ports[port] = SerialPort.new(port, 9600, 8, 1)
          # Wait forever to receive printer response
          ports[port].read_timeout = 0
          # Enable error reporting
          ports[port].write "US"
        end
      end

      # Print labels
      labels.each do |l|
        label_id = l.at_css('id').content
        port = l.at_css('port').content
        epl = l.at_css('epl').content
        print 'p'
        if epl.nil? || epl == ''
          next
        else
          epl.encode!('ISO-8859-1')
          ports[port].write(epl)
          while true
            byte = ports[port].getbyte
            # The label was printed successfully
            break if byte == ACK
            # There was an error, read all error bytes
            break if byte == XOFF
          end
        end
      end

      # Update labels
      labels.each do |l|
        label_id = l.at_css('id').content
        print 'u'
        result = virtus_printer.update_label label_id, 'PRINTED'
        puts virtus_printer.error if result == false
      end

      # Close all ports
      ports.each_value{ |port| port.close}

    rescue Interrupt => e
      log.error e
      exit
    rescue SystemCallError => e
      log.error e
      puts e
    rescue SocketError => e
      log.error e
      print ' SocketError '
    rescue Exception => e
      log.error e
      puts e.class
      puts e
    end
  end
end