/// <summary> /// Sample : Monitoring printer process. /// </summary> private void MonitoringPrinter() { while (true) { lock (lockObject) { try { if (port != null) { StarPrinterStatus status = port.GetParsedStatus(); CheckPrinterStatus(status); // Check printer status. CheckPaperStatus(status); // Check paper status. CheckCoverStatus(status); // Check cover status. } } catch (Exception) // Printer impossible { OnPrinterImpossible(); } } Thread.Sleep(1000); } }
/// <summary> /// Sample : Monitoring printer process. /// </summary> private void MonitoringPrinter() { while (true) { lock (lockObject) { try { if (port != null) { StarPrinterStatus status = port.GetParsedStatus(); // Your printer cash drawer open status. bool cashDrawerOpenActiveHigh = SharedInformationManager.GetDrawerOpenStatus(); if (status.CompulsionSwitch == cashDrawerOpenActiveHigh) // Cash drawer open { OnCashDrawerOpen(); } else { OnCashDrawerClose(); // Cash drawer close } } } catch (Exception) // Printer impossible { OnPrinterImpossible(); } Thread.Sleep(1000); } } }
public async void GetStatus(string objectIdentifier, int timeout, IReactPromise <string> promise) { if (!GetObject(objectIdentifier, out StarPrinter nativeObject)) { promise.Reject(new ReactError()); return; } nativeObject.GetStatusTimeout = timeout; try { StarPrinterStatus status = await nativeObject.GetStatusAsync(); StarPrinterStatusWrapper.SetObject(status, out string statusIdentifier); promise.Resolve(statusIdentifier); } catch (StarIO10Exception e) { StarIO10ErrorWrapper.SetObject(e, out string exceptionIdentifier); promise.Reject(new ReactError() { Code = exceptionIdentifier, Exception = e }); } }
public Form1() { InitializeComponent(); PrinterCommands = new List <string>(); ReceiptData = new List <string>(); try { //LogTextBox.Text += "try to start"; // listBox1.Items.Add("Trying to start Monitoring Status"); this.sPort = Factory.I.GetPort(PrinterPortname, Printersetting, 10000); this.sPrinterStatus = this.sPort.GetParsedStatus(); onlineStatus = true; } catch (PortException ex) { //If we could not open the port, lets show the error. MessageBox.Show("Error Opening Port: " + ex.Message, "PORT ERROR", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); Factory.I.ReleasePort(this.sPort); onlineStatus = false; this.sPrinterStatus = null; //LogTextBox.Text += "port error"; //listBox1.Items.Add("Port Error"); //return; } }
private void ReloadDeviceInformationWithProgressBar() { DeviceStatusListBox.ItemsSource = null; FirmwareInformationListBox.ItemsSource = null; StarPrinterStatus status = null; Dictionary <string, string> firmwareInformation = null; ProgressBarWindow progressBarWindow = new ProgressBarWindow("Communicating...", () => { status = GetDeviceStatus(); if (status == null) { return; } firmwareInformation = GetFirmwareInformation(); }); progressBarWindow.ShowDialog(); if (status == null && firmwareInformation == null) // Communication failure. { Util.ShowMessage("Error", "Communication error"); return; } // Parse printer status. ParsePrinterStatus(status, SharedInformationManager.GetDrawerOpenStatus()); // Parse firmware information. ParseFirmwareInformation(firmwareInformation); }
/// <summary> /// Sample : Retrieving printer status. /// </summary> public static CommunicationResult RetrieveStatus(ref StarPrinterStatus printerStatus, string portName, string portSettings, int timeout) { CommunicationResult result = CommunicationResult.ErrorUnknown; IPort port = null; try { result = CommunicationResult.ErrorOpenPort; port = Factory.I.GetPort(portName, portSettings, timeout); result = CommunicationResult.ErrorReadPort; printerStatus = port.GetParsedStatus(); result = CommunicationResult.Success; } catch (PortException) { } finally { if (port != null) { Factory.I.ReleasePort(port); } } return(result); }
public void GetPrinterStatus() { try { //this.sPrinterStatus = this.sPort.GetParsedStatus(); //Status = NULL if (onlineStatus == false) { Factory.I.ReleasePort(this.sPort); this.monitoring = false; return; } else { this.sPrinterStatus = this.sPort.GetParsedStatus(); if (this.sPrinterStatus.ReceiptPaperEmpty == true) //offline == true { tbStatus.BackColor = Color.Red; return; } else if (this.sPrinterStatus.ReceiptPaperNearEmptyInner == true) { tbStatus.BackColor = Color.Yellow; LogMessage("Printer is almost empty"); return; } else { tbStatus.BackColor = Color.Green; LogMessage("Printer is online"); return; } } } //If there was a problem getting status, lets catch the port error catch (PortException err) { } //If during monitoring the printer port goes null, lets reconnect to the printer. if (this.sPort == null) { try { this.sPort = Factory.I.GetPort(PrinterPortname, Printersetting, 10000); } catch { this.sPort = null; } } else { return; } }
/// <summary> /// Sample : Monitoring printer process. /// </summary> private void MonitoringPrinter() { uint tickCount = (uint)Environment.TickCount; while (!cancellationPending) { // Check printer status is changed for update status to Star Cloud Services. isChangeStatus = false; lock (lockObject) { try { if (port != null) { StarPrinterStatus status = port.GetParsedStatus(); // if printer status is changed "isChangeStatus" comes true. CheckPrinterStatus(status); // Check printer status. CheckPaperStatus(status); // Check paper status. CheckCoverStatus(status); // Check cover status. // Your printer cash drawer open status. bool cashDrawerOpenActiveHigh = SharedInformationManager.SelectedDrawerOpenStatus; CheckCashDrawerStatus(status, cashDrawerOpenActiveHigh); // Check cash drawer status. } } catch (Exception) // Printer impossible { OnPrinterImpossible(); } finally { // if printer status is not changed for some times, update status. if ((UInt32)Environment.TickCount - tickCount >= 300000) { isChangeStatus = true; } // if printer status is changed, upload printer status to Star Cloud Services. if (isChangeStatus) { OnStatusUpdated(); } tickCount = (UInt32)Environment.TickCount; } Thread.Sleep(1000); } } }
private void CheckCashDrawerStatus(StarPrinterStatus status, bool cashDrawerOpenActiveHigh) { if (status.CompulsionSwitch == cashDrawerOpenActiveHigh) // Cash drawer open { OnCashDrawerOpen(); } else { OnCashDrawerClose(); // Cash drawer close } }
private void CheckPrinterStatus(StarPrinterStatus status) { if (status.Offline) // Printer offline { OnPrinterOffline(); } else // Printer online { OnPrinterOnline(); } }
private void CheckCoverStatus(StarPrinterStatus status) { if (status.CoverOpen) // Cover open { OnPrinterCoverOpen(); } else // Cover close { OnPrinterCoverClose(); } }
private void CheckCashDrawer(StarPrinterStatus status) { // Your printer cash drawer open status. bool cashDrawerOpenActiveHigh = SharedInformationManager.GetDrawerOpenStatus(); if (status.CompulsionSwitch == cashDrawerOpenActiveHigh) // Cash drawer open { OnCashDrawerOpen(); } else { OnCashDrawerClose(); // Cash drawer close } }
private void CheckPaperStatus(StarPrinterStatus status) { if (status.ReceiptPaperEmpty) // Paper empty { OnPrinterPaperEmpty(); } else if (status.ReceiptPaperNearEmptyInner || // Paper near empty status.ReceiptPaperNearEmptyOuter) { OnPrinterPaperNearEmpty(); } else // Paper ready { OnPrinterPaperReady(); } }
/// <summary> /// Sample : Getting device status. /// </summary> private StarPrinterStatus GetDeviceStatus() { // Your printer PortName and PortSettings. string portName = SharedInformationManager.SelectedPortName; string portSettings = SharedInformationManager.SelectedPortSettings; StarPrinterStatus status = null; CommunicationResult result = Communication.RetrieveStatus(ref status, portName, portSettings, 30000); if (result.Result != Communication.Result.Success) { return(null); } return(status); }
public void Print(List <TicketBase> tickets, int issueingNumber, Action <int> onPrint, Action <Exception, int> onError) { StarPrinterStatus status = port.BeginCheckedBlock(); if (status.Offline) { } ICommandBuilder builder = StarIoExt.CreateCommandBuilder(Emulation.StarGraphic); builder.BeginDocument(); tickets.ForEach((t, i) => { try { int height = 8 * 58 - 85 - 15; // height = 8 * 58 - 25 - 15; Bitmap bmp = t.Bitmap.Clone(new Rectangle((t.Bitmap.Width - 576) / 2, 70, 576, height), t.Bitmap.PixelFormat); builder.AppendBitmapWithAbsolutePosition(bmp, false, 576, false, BitmapConverterRotation.Normal, 0); builder.AppendCutPaper(CutPaperAction.PartialCutWithFeed); bmp.Dispose(); onPrint(i); } catch (Exception ex) { onError(ex, i); } }); builder.EndDocument(); byte[] command = builder.Commands; uint writtenLength = port.WritePort(command, 0, (uint)command.Length); status = port.EndCheckedBlock(); if (status.Offline) { } }
/// <summary> /// Sample : Monitoring printer process. /// </summary> private void MonitoringPrinter() { // Your printer emulation. Emulation emulation = SharedInformationManager.GetSelectedEmulation(); while (true) { lock (lockObject) { try { if (port != null) { StarPrinterStatus status = port.GetParsedStatus(); CheckPrinterStatus(status); // Check printer status. CheckPaperStatus(status); // Check paper status. CheckCoverStatus(status); // Check cover status. CheckCashDrawer(status); // Check cash drawer status. CheckBarcodeReaderStatus(); // Check barcode reader status. (connect or disconnect) if (currentBarcodeReaderStatus == Communication.PeripheralStatus.Connect) // Barcode reader is connected. { ReadBarcodeReaderData(); // Read barcode reader data. } } } catch (PortException) { OnPrinterImpossible(); } } Thread.Sleep(100); } }
/// <summary> /// Sample : Retrieving printer status. /// </summary> public static CommunicationResult RetrieveStatus(ref StarPrinterStatus printerStatus, string portName, string portSettings, int timeout) { Result result = Result.ErrorUnknown; int code = StarResultCode.ErrorFailed; IPort port = null; try { result = Result.ErrorOpenPort; port = Factory.I.GetPort(portName, portSettings, timeout); result = Result.ErrorReadPort; printerStatus = port.GetParsedStatus(); result = Result.Success; code = StarResultCode.Succeeded; } catch (PortException ex) { code = ex.ErrorCode; } finally { if (port != null) { Factory.I.ReleasePort(port); } } return(new CommunicationResult() { Result = result, Code = code }); }
public void GetStatus(string objectIdentifier, IReactPromise <string> promise) { if (!GetObject(objectIdentifier, out StarIO10Exception nativeObject)) { promise.Reject(new ReactError()); return; } StarPrinterStatus status = null; if (nativeObject is StarIO10UnprintableException) { status = (nativeObject as StarIO10UnprintableException).Status; } if (status == null) { promise.Reject(new ReactError()); return; } StarPrinterStatusWrapper.SetObject(status, out string statusIdentifier); promise.Resolve(statusIdentifier); }
/// <summary> /// Sample : Getting printer serial number. /// </summary> public static CommunicationResult GetSerialNumber(ref string serialNumber, IPort port) { CommunicationResult result = CommunicationResult.ErrorUnknown; try { result = CommunicationResult.ErrorOpenPort; if (port == null) { return(CommunicationResult.ErrorOpenPort); } result = CommunicationResult.ErrorWritePort; StarPrinterStatus printerStatus = port.GetParsedStatus(); byte[] getInformationCommands = new byte[] { 0x1b, 0x1d, 0x29, 0x49, 0x01, 0x00, 49 }; // ESC GS ) I pL pH fn (Transmit printer information command) port.WritePort(getInformationCommands, 0, (uint)getInformationCommands.Length); result = CommunicationResult.ErrorReadPort; byte[] readBuffer = new byte[1024]; uint totalReceiveSize = 0; string information = ""; uint startDate = (uint)Environment.TickCount; while (true) { if ((UInt32)Environment.TickCount - startDate >= 3000) // Timeout { throw new PortException("ReadPort timeout."); } uint receiveSize = port.ReadPort(ref readBuffer, totalReceiveSize, (uint)(readBuffer.Length - totalReceiveSize)); if (receiveSize > 0) { totalReceiveSize += receiveSize; } else { continue; } byte[] receiveData = new byte[totalReceiveSize]; Array.Copy(readBuffer, 0, receiveData, 0, totalReceiveSize); bool receiveResponse = false; if (totalReceiveSize >= 2) { for (int i = 0; i < totalReceiveSize; i++) { if (receiveData[i] == 0x0a && // Check the footer of the command. receiveData[i + 1] == 0x00) { for (int j = 0; j < totalReceiveSize - 9; j++) { if (receiveData[j] == 0x1b && receiveData[j + 1] == 0x1d && receiveData[j + 2] == 0x29 && receiveData[j + 3] == 0x49 && receiveData[j + 4] == 0x01 && receiveData[j + 5] == 0x00 && receiveData[j + 6] == 49) { string responseStr = Encoding.ASCII.GetString(receiveData); int infoStartIndex = j + 7; // information start index. int infoEndIndex = (int)(totalReceiveSize - 2); // information end index. information = responseStr.Substring(infoStartIndex, infoEndIndex - infoStartIndex); // Extract information from priinter response. receiveResponse = true; break; } } } } } if (receiveResponse) { break; } } int serialNumberStartIndex = information.IndexOf("PrSrN="); // Check serial number tag. if (serialNumberStartIndex == -1) { throw new PortException("Parse serial number failed."); } serialNumberStartIndex += "PrSrN=".Length; string temp = information.Substring(serialNumberStartIndex); int serialNumberEndIndex = temp.IndexOf(","); // Check comma. if (serialNumberEndIndex == -1) // Not find comma. { serialNumberEndIndex = temp.Length; // End of information. } serialNumber = temp.Substring(0, serialNumberEndIndex); // Parse serial number information. int nullIndex = serialNumber.IndexOf("\0"); // Check null(for clone serial number). if (nullIndex != -1) // Find null. { serialNumber = serialNumber.Substring(0, nullIndex); } result = CommunicationResult.Success; } catch (PortException) { } return(result); }
/// <summary> /// Sample : Sending commands to printer using redirection. /// </summary> public static CommunicationResult[] SendCommandsForRedirection(byte[] commands, string[] portNameArray, string[] portSettingsArray, int[] timeoutMillisArray) { List <CommunicationResult> resultList = new List <CommunicationResult>(); // Loop sending commands process until it is succeeded. for (int i = 0; i < portNameArray.Length; i++) { Result result = Result.ErrorUnknown; int code = StarResultCode.ErrorFailed; IPort port = null; // Set target printer settings. string portName = portNameArray[i]; string portSettings = portSettingsArray[i]; int timeoutMillis = timeoutMillisArray[i]; try { result = Result.ErrorOpenPort; port = Factory.I.GetPort(portName, portSettings, timeoutMillis); result = Result.ErrorBeginCheckedBlock; StarPrinterStatus status = port.BeginCheckedBlock(); if (status.Offline) { string message = "Printer is Offline."; if (status.ReceiptPaperEmpty) { message += "\nPaper is Empty."; } if (status.CoverOpen) { message += "\nCover is Open."; } throw new PortException(message); } result = Result.ErrorWritePort; uint commandsLength = (uint)commands.Length; uint writtenLength = port.WritePort(commands, 0, commandsLength); if (writtenLength != commandsLength) { throw new PortException("WritePort failed."); } result = Result.ErrorEndCheckedBlock; status = port.EndCheckedBlock(); if (status.Offline == true) { string message = "Printer is Offline."; if (status.ReceiptPaperEmpty == true) { message += "\nPaper is Empty."; } if (status.CoverOpen == true) { message += "\nCover is Open."; } throw new PortException(message); } result = Result.Success; code = StarResultCode.Succeeded; } catch (PortException ex) { code = ex.ErrorCode; } finally { if (port != null) { Factory.I.ReleasePort(port); } } resultList.Add(new CommunicationResult() { Result = result, Code = code }); // Finish process if it is succeeded. if (result == Result.Success) { break; } } return(resultList.ToArray()); }
/// <summary> /// Sample : Getting printer information. /// </summary> public static CommunicationResult GetPrinterInformation(ref string receiveInfomation, string tag, IPort port) { Result result = Result.ErrorUnknown; int code; try { result = Result.ErrorOpenPort; if (port == null) { throw new PortException("port is null."); } result = Result.ErrorWritePort; StarPrinterStatus printerStatus = port.GetParsedStatus(); byte[] getInformationCommands = new byte[] { 0x1b, 0x1d, 0x29, 0x49, 0x01, 0x00, 49 }; // ESC GS ) I pL pH fn (Transmit printer information command) port.WritePort(getInformationCommands, 0, (uint)getInformationCommands.Length); result = Result.ErrorReadPort; string information = ""; byte[] readBuffer = new byte[1024]; List <byte> allReceiveData = new List <byte>(); uint startDate = (uint)Environment.TickCount; while (true) { if ((UInt32)Environment.TickCount - startDate >= 3000) // Timeout { throw new PortException("ReadPort timeout."); } uint receiveSize = port.ReadPort(ref readBuffer, 0, (uint)readBuffer.Length); if (receiveSize == 0) { continue; } byte[] receiveData = new byte[receiveSize]; Array.Copy(readBuffer, 0, receiveData, 0, receiveSize); allReceiveData.AddRange(receiveData); bool receiveResponse = false; int totalReceiveSize = allReceiveData.Count; if (totalReceiveSize >= 2) { for (int i = 0; i < totalReceiveSize; i++) { if (allReceiveData[i] == 0x0a && // Check the footer of the command. allReceiveData[i + 1] == 0x00) { for (int j = 0; j < totalReceiveSize - 9; j++) { if (allReceiveData[j] == 0x1b && allReceiveData[j + 1] == 0x1d && allReceiveData[j + 2] == 0x29 && allReceiveData[j + 3] == 0x49 && allReceiveData[j + 4] == 0x01 && allReceiveData[j + 5] == 0x00 && allReceiveData[j + 6] == 49) { string responseStr = Encoding.ASCII.GetString(allReceiveData.ToArray()); int infoStartIndex = j + 7; // information start index. int infoEndIndex = totalReceiveSize - 2; // information end index. information = responseStr.Substring(infoStartIndex, infoEndIndex - infoStartIndex); // Extract information from priinter response. receiveResponse = true; break; } } } } } if (receiveResponse) { break; } } int infomationStartIndex = information.IndexOf(tag); // Check tag. if (infomationStartIndex == -1) { throw new PortException("Parse printer information failed."); } infomationStartIndex += tag.Length; string temp = information.Substring(infomationStartIndex); int informationEndIndex = temp.IndexOf(","); // Check comma. if (informationEndIndex == -1) // Not find comma. { informationEndIndex = temp.Length; // End of information. } receiveInfomation = temp.Substring(0, informationEndIndex); // Parse serial number information. int nullIndex = receiveInfomation.IndexOf("\0"); // Check null(for clone serial number). if (nullIndex != -1) // Find null. { receiveInfomation = receiveInfomation.Substring(0, nullIndex); } result = Result.Success; code = StarResultCode.Succeeded; } catch (PortException ex) { code = ex.ErrorCode; } return(new CommunicationResult() { Result = result, Code = code }); }
/// <summary> /// Sample : Setting USB serial number. /// </summary> public static CommunicationResult SetUSBSerialNumber(byte[] serialNumber, bool isEnabled, IPort port) { Result result = Result.ErrorUnknown; int code; try { result = Result.ErrorOpenPort; if (port == null) { throw new PortException("port is null."); } result = Result.ErrorWritePort; StarPrinterStatus printerStatus = port.GetParsedStatus(); if (printerStatus.Offline) { string message = "Printer is Offline."; if (printerStatus.ReceiptPaperEmpty) { message += "\nPaper is Empty."; } if (printerStatus.CoverOpen) { message += "\nCover is Open."; } throw new PortException(message); } if (serialNumber.Length != 0) { // Send setting USB serial number command. List <byte> setUSBSerialNumberCommandList = new List <byte>(); setUSBSerialNumberCommandList.AddRange(new byte[] { 0x1b, 0x23, 0x23, 0x57 }); int fillCounts = 0; if (serialNumber.Length <= 8) { setUSBSerialNumberCommandList.Add(0x38); fillCounts = 8 - serialNumber.Length; } else if (serialNumber.Length <= 16) { setUSBSerialNumberCommandList.Add(0x10); fillCounts = 16 - serialNumber.Length; } setUSBSerialNumberCommandList.Add(0x2c); for (int i = 0; i < fillCounts; i++) // Fill in the top at '0' to be a total 8 or 16 digit. { setUSBSerialNumberCommandList.Add(0x30); } setUSBSerialNumberCommandList.AddRange(serialNumber); setUSBSerialNumberCommandList.AddRange(new byte[] { 0x0a, 0x00 }); byte[] setUSBSerialNumberCommand = setUSBSerialNumberCommandList.ToArray(); port.WritePort(setUSBSerialNumberCommand, 0, (uint)setUSBSerialNumberCommand.Length); Thread.Sleep(5000); // Wait for 5 seconds until printer recover from software reset. } // Send setting USB serial number is enabled command. byte[] setUSBSerialNumberIsEnabledCommand; if (isEnabled) { setUSBSerialNumberIsEnabledCommand = new byte[] { 0x1b, 0x1d, 0x23, 0x2b, 0x43, 0x30, 0x30, 0x30, 0x32, 0x0a, 0x00, 0x1b, 0x1d, 0x23, 0x57, 0x30, 0x30, 0x30, 0x30, 0x30, 0x0a, 0x00 }; // Enable } else { setUSBSerialNumberIsEnabledCommand = new byte[] { 0x1b, 0x1d, 0x23, 0x2d, 0x43, 0x30, 0x30, 0x30, 0x32, 0x0a, 0x00, 0x1b, 0x1d, 0x23, 0x57, 0x30, 0x30, 0x30, 0x30, 0x30, 0x0a, 0x00 }; // Disable } port.WritePort(setUSBSerialNumberIsEnabledCommand, 0, (uint)setUSBSerialNumberIsEnabledCommand.Length); result = Result.Success; code = StarResultCode.Succeeded; } catch (PortException ex) { code = ex.ErrorCode; } return(new CommunicationResult() { Result = result, Code = code }); }
/// <summary> /// Sample : Initializing USB serial number. /// </summary> public static CommunicationResult InitializeUSBSerialNumber(bool isEnabled, IPort port) { Result result = Result.ErrorUnknown; int code; try { result = Result.ErrorOpenPort; if (port == null) { throw new PortException("port is null."); } result = Result.ErrorWritePort; StarPrinterStatus printerStatus = port.GetParsedStatus(); if (printerStatus.Offline) { string message = "Printer is Offline."; if (printerStatus.ReceiptPaperEmpty) { message += "\nPaper is Empty."; } if (printerStatus.CoverOpen) { message += "\nCover is Open."; } throw new PortException(message); } List <byte> settingCommandList = new List <byte>(); // Send initialize USB serial number command. byte[] initializeUSBSerialNumberCommand = new byte[] { 0x1b, 0x23, 0x23, 0x57, 0x38, 0x2c, (byte)'?', (byte)'?', (byte)'?', (byte)'?', (byte)'?', (byte)'?', (byte)'?', (byte)'?', 0x0a, 0x00 }; port.WritePort(initializeUSBSerialNumberCommand, 0, (uint)initializeUSBSerialNumberCommand.Length); Thread.Sleep(5000); // Wait for 5 seconds until printer recover from software reset. // Send setting USB serial number is enabled command. byte[] setUSBSerialNumberIsEnabledCommand; if (isEnabled) { setUSBSerialNumberIsEnabledCommand = new byte[] { 0x1b, 0x1d, 0x23, 0x2b, 0x43, 0x30, 0x30, 0x30, 0x32, 0x0a, 0x00, 0x1b, 0x1d, 0x23, 0x57, 0x30, 0x30, 0x30, 0x30, 0x30, 0x0a, 0x00 }; // Enable } else { setUSBSerialNumberIsEnabledCommand = new byte[] { 0x1b, 0x1d, 0x23, 0x2d, 0x43, 0x30, 0x30, 0x30, 0x32, 0x0a, 0x00, 0x1b, 0x1d, 0x23, 0x57, 0x30, 0x30, 0x30, 0x30, 0x30, 0x0a, 0x00 }; // Disable } port.WritePort(setUSBSerialNumberIsEnabledCommand, 0, (uint)setUSBSerialNumberIsEnabledCommand.Length); result = Result.Success; code = StarResultCode.Succeeded; } catch (PortException ex) { code = ex.ErrorCode; } return(new CommunicationResult() { Result = result, Code = code }); }
public static CommunicationResult ParseDoNotCheckCondition(IPeripheralCommandParser parser, IPort port) { Result result = Result.ErrorUnknown; int code; try { result = Result.ErrorOpenPort; if (port == null) { throw new PortException("port is null."); } result = Result.ErrorWritePort; StarPrinterStatus printerStatus = port.GetParsedStatus(); byte[] commands = parser.SendCommands; port.WritePort(commands, 0, (uint)commands.Length); result = Result.ErrorReadPort; byte[] readBuffer = new byte[1024]; List <byte> allReceiveData = new List <byte>(); uint startDate = (uint)Environment.TickCount; while (true) { if ((UInt32)Environment.TickCount - startDate >= 1000) // Timeout { throw new PortException("ReadPort timeout."); } Thread.Sleep(10); uint receiveSize = port.ReadPort(ref readBuffer, 0, (uint)readBuffer.Length); if (receiveSize == 0) { continue; } byte[] receiveData = new byte[receiveSize]; Array.Copy(readBuffer, 0, receiveData, 0, receiveSize); allReceiveData.AddRange(receiveData); if (parser.Parse(allReceiveData.ToArray(), allReceiveData.Count) == ParseResult.Success) { result = Result.Success; code = StarResultCode.Succeeded; break; } } } catch (PortException ex) { code = ex.ErrorCode; } return(new CommunicationResult() { Result = result, Code = code }); }
public bool Test() { bool result = false; ERROR = false; ErrMsg = ""; //Try and get status, Catch errors if we could not get status. try { //If during monitoring the printer port goes null, lets reconnect to the printer. if (this.sPort == null) { try { this.sPort = Factory.I.GetPort(com.PortName, "9600,n,8,1,h", 10000); } catch { this.sPort = null; return(false); } } //Use StarIO to get status this.sPrinterStatus = this.sPort.GetParsedStatus(); //Status = NULL if (this.sPrinterStatus == null) { Factory.I.ReleasePort(this.sPort); return(false); } else { result = true; } //Status = Offline if (this.sPrinterStatus.Offline == true) //offline == true { result = !(ERROR = true); ErrMsg = "OFF-LINE|"; } //Status = Cover Open if (this.sPrinterStatus.CoverOpen == true) { result = !(ERROR = true); ErrMsg += "COVER_OPENED|"; } else { ErrMsg += "COVER_CLOSED|"; } //Paper is empty if (this.sPrinterStatus.ReceiptPaperEmpty == true) { result = !(ERROR = true); ErrMsg += "PAPER_END|"; } else { ErrMsg += "PAPER_PRSENT|"; } } catch (PortException p)//If there was a problem getting status, lets catch the port error { Factory.I.ReleasePort(this.sPort); ErrMsg = p.ToString(); return(false); } return(result); }
/// <summary> /// Sample : Parse printer response. /// </summary> public static CommunicationResult ParseDoNotCheckCondition(IPeripheralCommandParser parser, IPort port) { CommunicationResult result = CommunicationResult.ErrorUnknown; try { result = CommunicationResult.ErrorOpenPort; if (port == null) { return(CommunicationResult.ErrorOpenPort); } result = CommunicationResult.ErrorWritePort; StarPrinterStatus printerStatus = port.GetParsedStatus(); byte[] commands = parser.SendCommands; port.WritePort(commands, 0, (uint)commands.Length); result = CommunicationResult.ErrorReadPort; byte[] readBuffer = new byte[1024]; uint totalReceiveSize = 0; uint startDate = (uint)Environment.TickCount; while (true) { Thread.Sleep(10); uint receiveSize = port.ReadPort(ref readBuffer, totalReceiveSize, (uint)(readBuffer.Length - totalReceiveSize)); if (receiveSize > 0) { totalReceiveSize += receiveSize; } byte[] receiveData = new byte[totalReceiveSize]; Array.Copy(readBuffer, 0, receiveData, 0, totalReceiveSize); if (parser.Parse(receiveData, (int)totalReceiveSize) == ParseResult.Success) { result = CommunicationResult.Success; break; } if ((UInt32)Environment.TickCount - startDate >= 1000) // Timeout { throw new PortException("ReadPort timeout."); } } } catch (PortException) { } return(result); }
static void Main(string[] args) { //TEST appPath = AppDomain.CurrentDomain.BaseDirectory; //隱藏式窗 FreeConsole(); string vName; int poi = -1; //分析參數 for (int i = 0; i < args.Length; i++) { vName = args[i].ToLower(); int j; //檢查是否為指令 for (j = 0; j < cmd.Length; j++) { if (cmd[j] == vName) { //當符合指令時,跳出迴圈,此時j=指令索引 break; } } //如果j>=指令索引陣列長度(沒找到),代表不是指令,屬於前一個指令資料的附加字串 //但是也必須在有前一個指令的狀況下 (poi >= 0) if (j == cmd.Length && poi >= 0) { //附加到前一個指令的資料中 if (cmdval[poi] == "") { cmdval[poi] = args[i]; } else { cmdval[poi] = cmdval[poi] + " " + args[i]; } //處理下一個 continue; } //poi指定為指令索引位置 poi = j; } //檢查參數 if (!File.Exists(cmdval[0] + ".xml")) { ErrorLog("資料檔案" + cmdval[0] + ".xml不存在 -- 終止執行"); return; } if (!LoadData(cmdval[0] + ".xml")) { ErrorLog("讀取檔案" + cmdval[0] + ".xml失敗 -- 終止執行"); return; } command = CreateBitmapData(Emulation.StarGraphic); // 判斷是否列印明細 if (dr["detail"] == "1") { //檢查參數 if (!File.Exists(cmdval[0] + "_Detail.xml")) { ErrorLog("資料檔案" + cmdval[0] + "_Detail.xml不存在 -- 終止執行"); return; } if (!LoadData(cmdval[0] + "_Detail.xml")) { ErrorLog("讀取檔案" + cmdval[0] + "_Detail.xml失敗 -- 終止執行"); return; } command = appendBytes(CreateBitmapDataDetail(Emulation.StarGraphic)); } string str = System.Text.Encoding.UTF8.GetString(command, 0, command.Length); IPort port = null; try { port = Factory.I.GetPort("TCP:" + cmdval[1], "", 500); //like => Factory.I.GetPort("TCP:192.168.1.104","stargraphic;l1",0); StarPrinterStatus status = port.BeginCheckedBlock(); if (status.Offline) { Console.WriteLine("OFF1"); } uint writtenLength = port.WritePort(command, 0, (uint)command.Length); if (writtenLength != command.Length) { Console.WriteLine("WritePort failed."); } Console.WriteLine("Successful"); } catch (PortException ex) { Console.WriteLine(ex); } finally { Factory.I.ReleasePort(port); Application.Exit(); } }
/// <summary> /// Sample : Parsing printer status object. /// </summary> private void ParsePrinterStatus(StarPrinterStatus status, bool cashDrawerOpenActiveHigh) { List <ListBoxItemWithDetail> listBoxItemList = new List <ListBoxItemWithDetail>(); if (status == null) { DeviceStatusListBox.ItemsSource = listBoxItemList.ToArray(); return; } ListBoxItemWithDetail onlineListBoxItem = new ListBoxItemWithDetail("Online"); ListBoxItemWithDetail coverListBoxItem = new ListBoxItemWithDetail("Cover"); ListBoxItemWithDetail paperListBoxItem = new ListBoxItemWithDetail("Paper"); ListBoxItemWithDetail cashDrawerListBoxItem = new ListBoxItemWithDetail("Cash Drawer"); ListBoxItemWithDetail headTemperatureListBoxItem = new ListBoxItemWithDetail("Head Temperature"); ListBoxItemWithDetail nonRecoverableErrorListBoxItem = new ListBoxItemWithDetail("Non Recoverable Error"); ListBoxItemWithDetail paperCutterListBoxItem = new ListBoxItemWithDetail("Paper Cutter"); ListBoxItemWithDetail headThermistorListBoxItem = new ListBoxItemWithDetail("Head Thermistor"); ListBoxItemWithDetail voltageListBoxItem = new ListBoxItemWithDetail("Voltage"); ListBoxItemWithDetail etbCounterListBoxItem = new ListBoxItemWithDetail("ETB Counter"); if (status.Offline) { onlineListBoxItem.Detail = "Offline"; onlineListBoxItem.ForeGroundColor = new SolidColorBrush(Colors.Red); } else { onlineListBoxItem.Detail = "Online"; onlineListBoxItem.ForeGroundColor = new SolidColorBrush(Colors.Blue); } listBoxItemList.Add(onlineListBoxItem); if (status.CoverOpen) { coverListBoxItem.Detail = "Open"; coverListBoxItem.ForeGroundColor = new SolidColorBrush(Colors.Red); } else { coverListBoxItem.Detail = "Closed"; coverListBoxItem.ForeGroundColor = new SolidColorBrush(Colors.Blue); } listBoxItemList.Add(coverListBoxItem); if (status.ReceiptPaperEmpty) { paperListBoxItem.Detail = "Empty"; paperListBoxItem.ForeGroundColor = new SolidColorBrush(Colors.Red); } else if (status.ReceiptPaperNearEmptyInner || status.ReceiptPaperNearEmptyOuter) { paperListBoxItem.Detail = "Near Empty"; paperListBoxItem.ForeGroundColor = new SolidColorBrush(Colors.Yellow); } else { paperListBoxItem.Detail = "Ready"; paperListBoxItem.ForeGroundColor = new SolidColorBrush(Colors.Blue); } listBoxItemList.Add(paperListBoxItem); if (cashDrawerOpenActiveHigh) { if (status.CompulsionSwitch) { cashDrawerListBoxItem.Detail = "Open"; cashDrawerListBoxItem.ForeGroundColor = new SolidColorBrush(Colors.Red); } else { cashDrawerListBoxItem.Detail = "Closed"; cashDrawerListBoxItem.ForeGroundColor = new SolidColorBrush(Colors.Blue); } } else { if (status.CompulsionSwitch) { cashDrawerListBoxItem.Detail = "Closed"; cashDrawerListBoxItem.ForeGroundColor = new SolidColorBrush(Colors.Blue); } else { cashDrawerListBoxItem.Detail = "Open"; cashDrawerListBoxItem.ForeGroundColor = new SolidColorBrush(Colors.Red); } } listBoxItemList.Add(cashDrawerListBoxItem); if (status.OverTemp) { headTemperatureListBoxItem.Detail = "High"; headTemperatureListBoxItem.ForeGroundColor = new SolidColorBrush(Colors.Red); } else { headTemperatureListBoxItem.Detail = "Normal"; headTemperatureListBoxItem.ForeGroundColor = new SolidColorBrush(Colors.Blue); } listBoxItemList.Add(headTemperatureListBoxItem); if (status.UnrecoverableError) { nonRecoverableErrorListBoxItem.Detail = "Error"; nonRecoverableErrorListBoxItem.ForeGroundColor = new SolidColorBrush(Colors.Red); } else { nonRecoverableErrorListBoxItem.Detail = "Ready"; nonRecoverableErrorListBoxItem.ForeGroundColor = new SolidColorBrush(Colors.Blue); } listBoxItemList.Add(nonRecoverableErrorListBoxItem); if (status.CutterError) { paperCutterListBoxItem.Detail = "Error"; paperCutterListBoxItem.ForeGroundColor = new SolidColorBrush(Colors.Red); } else { paperCutterListBoxItem.Detail = "Ready"; paperCutterListBoxItem.ForeGroundColor = new SolidColorBrush(Colors.Blue); } listBoxItemList.Add(paperCutterListBoxItem); if (status.HeadThermistorError) { headThermistorListBoxItem.Detail = "Abnormal"; headThermistorListBoxItem.ForeGroundColor = new SolidColorBrush(Colors.Red); } else { headThermistorListBoxItem.Detail = "Normal"; headThermistorListBoxItem.ForeGroundColor = new SolidColorBrush(Colors.Blue); } listBoxItemList.Add(headThermistorListBoxItem); if (status.VoltageError) { voltageListBoxItem.Detail = "Abnormal"; voltageListBoxItem.ForeGroundColor = new SolidColorBrush(Colors.Red); } else { voltageListBoxItem.Detail = "Normal"; voltageListBoxItem.ForeGroundColor = new SolidColorBrush(Colors.Blue); } listBoxItemList.Add(voltageListBoxItem); if (status.ETBAvailable) { etbCounterListBoxItem.Detail = status.ETBCounter.ToString(); etbCounterListBoxItem.ForeGroundColor = new SolidColorBrush(Colors.Blue); listBoxItemList.Add(etbCounterListBoxItem); } DeviceStatusListBox.ItemsSource = listBoxItemList.ToArray(); }