module Sapos module Print class Printer def initialize(config) @config = config end def print(args = {}) raw_message = args[:document] log_text = "id=#{args[:id]},doc=#{args[:document_number]},control=#{args[:print_control] ? "SI" : "NO"},cache=0\t" filename = "#{args[:document_number]}.print" if args[:document_number] filename = SecureRandom.hex if filename.nil? result = false raw = raw_message.force_encoding("UTF-8") msgid = args[:id] if @config.duplicate_control? && @config.cache.include?(msgid) log_text += " => DUPLICADO (DC)" log_text.gsub!("cache=0", "cache=#{@config.cache.size}") puts log_text return true end begin if args[:print_control] && args[:document_number] print_dir = File.join(Sapos::Print.app_directory, 'print') FileUtils.mkdir_p print_dir unless File.exists?(print_dir) filename = File.join(print_dir, filename) if !File.exists?(filename) printable = data(raw_message) File.open(filename, 'w'){|f| f.write(printable)} result = send_to_printer({file: filename}) #puts "Result: #{result}" log_text += " => OK" else result = true log_text += " => DUPLICADO" end else printable = data(raw_message) File.open(filename, 'w'){|f| f.write(printable)} result = send_to_printer({file: filename}) File.delete(filename) if File.exists?(filename) #puts "Result: #{result}" log_text += " => OK" end if @config.duplicate_control? @config.cache << msgid @config.cache.shift if @config.cache.size > 30 log_text.gsub!("cache=0", "cache=#{@config.cache.size}") end puts log_text rescue => e puts "#{e.message}" self.errors = e.message result = false ensure #File.delete(filename) if File.exists?(filename) return result end end def data(raw_message) case @config.interface when 'text' return raw_message when 'escp' esc = "\x1B" #ESC byte in hex notation newLine = "\x0A" #LF byte in hex notation cmds = esc + "@" cmds += esc + "!"+"\00" cmds += raw_message cmds += newLine + newLine cmds += "\x1D\x56\x42\x03" # Cut Paper cmds += "\x1B\x70\x00\x19\xFA" # Open drawer return cmds else raise "Unknown interface: #{@config.interface}" end end def send_to_printer(opts = {}) case @config.adapter when 'console' puts "=> CONSOLE: file: #{opts[:file]}<=\n\n" puts File.read(opts[:file]) puts "\n=> END CONSOLE =<" return true when 'cups' file = opts.delete(:file) command_options = [] command_options << "-d #{@printer_name}" command_options << "-o raw" if opts[:raw].present? command = "lp #{command_options.join(" ")} #{file}" puts "CMD => #{command}" if @config.verbose if !system(command) puts "Not executed" return false end return true when 'windows' #command = "copy" + ' "' + filename + '" ' + '"\\\\%COMPUTERNAME%\\'+"TM" filename = opts[:file].to_s.gsub("/","\\") command = "COPY " + '"' + filename + '" ' + '"\\\\%COMPUTERNAME%\\' + @config.printer #command = "copy #{opts[:file]} "+'"\\\\%COMPUTERNAME%\\'+@config.printer if !system(command) puts "Not executed" return false end return true end end end end end