Skip to content

Instantly share code, notes, and snippets.

@aabanaag
Created November 29, 2019 02:39
Show Gist options
  • Save aabanaag/f3d16eac8132bf7c6c1f0261633bc4db to your computer and use it in GitHub Desktop.
Save aabanaag/f3d16eac8132bf7c6c1f0261633bc4db to your computer and use it in GitHub Desktop.
import RxCocoa
import RxSwift
import Foundation
class PrintManager {
private var printer: BRPtouchPrinter!
init(printerObj: Printer, type: PrinterConnectionType = .BLUETOOTH) {
setupPrinter(with: type, using: printerObj)
printer.setPrintInfo(printConfig())
}
// MARK: Get Printer Status
func getPrinterStatus() -> Bool {
if printer == nil {
return false
}
return printer.isPrinterReady()
}
func print(badge: UIImage) -> Single<Bool> {
return Single.create { [weak self] (observer) -> Disposable in
guard let strongSelf = self else { return Disposables.create() }
let isPrinterStarted = strongSelf.printer.startCommunication()
var hasError: Bool = false
if isPrinterStarted {
let response = strongSelf.printer.print(badge.cgImage, copy: 1)
if response != 0 {
strongSelf.printer.cancelPrinting()
hasError = true
}
strongSelf.printer.endCommunication()
if !hasError {
observer(.success(true))
} else {
observer(.error(NSError()))
}
} else {
observer(.success(true))
}
return Disposables.create()
}
}
// MARK: Printer Options
private func printConfig() -> BRPtouchPrintInfo {
let options = BRPtouchPrintInfo()
options.strPaperName = Constants.Printer.label
options.nDensity = 10
options.nHalftone = HALFTONE_ERRDIF
options.scaleValue = 1.0
options.nOrientation = ORI_PORTRATE
options.nPrintMode = PRINT_FIT
options.nAutoCutFlag = 1
options.nLeftMargin = 0
options.nTopMargin = 0
return options
}
private func getConnectionType(_ type: PrinterConnectionType) -> CONNECTION_TYPE {
switch type {
case .BLUETOOTH:
return CONNECTION_TYPE.BLUETOOTH
case .WIFI:
return CONNECTION_TYPE.WLAN
}
}
private func setupPrinter(with type: PrinterConnectionType, using printerObj: Printer) {
if (type == .BLUETOOTH) {
printer = BRPtouchPrinter(printerName: printerObj.model, interface: getConnectionType(type))
printer.setupForBluetoothDevice(withSerialNumber: printerObj.serialNumber)
} else {
printer = BRPtouchPrinter(printerName: printerObj.name, interface: getConnectionType(type))
printer.setIPAddress(printerObj.ipAddress)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment