/// <summary>
        /// Sample : Sending commands to printer without check condition.
        /// </summary>
        public static CommunicationResult SendCommandsDoNotCheckCondition(byte[] commands, 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);

                StarPrinterStatus status;

                result = Result.ErrorWritePort;

                status = port.GetParsedStatus();

                uint commandsLength = (uint)commands.Length;

                uint writtenLength = port.WritePort(commands, 0, commandsLength);

                if (writtenLength != commandsLength)
                {
                    throw new PortException("WritePort failed.");
                }

                result = Result.ErrorWritePort;

                status = 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
            });
        }
Exemplo n.º 2
0
        /// <summary>
        /// Sample : Sending commands to printer without check condition.
        /// </summary>
        public static CommunicationResult SendCommandsDoNotCheckCondition(byte[] commands, string portName, string portSettings, int timeout)
        {
            CommunicationResult result = CommunicationResult.ErrorUnknown;

            IPort port = null;

            try
            {
                result = CommunicationResult.ErrorOpenPort;

                port = Factory.I.GetPort(portName, portSettings, timeout);

                StarPrinterStatus status;

                result = CommunicationResult.ErrorWritePort;

                status = port.GetParsedStatus();

                if (status.RawStatus.Length == 0)
                {
                    throw new PortException("Unable to communicate with printer.");
                }

                uint commandsLength = (uint)commands.Length;

                uint writtenLength = port.WritePort(commands, 0, commandsLength);

                if (writtenLength != commandsLength)
                {
                    throw new PortException("WritePort failed.");
                }

                result = CommunicationResult.ErrorWritePort;

                status = port.GetParsedStatus();

                result = CommunicationResult.Success;
            }
            catch (PortException)
            {
            }
            finally
            {
                if (port != null)
                {
                    Factory.I.ReleasePort(port);
                }
            }

            return(result);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Returns the status of the printer.
        /// </summary>
        /// <returns>An object that contains the status of the printer.</returns>
        public override PrinterStatus GetStatus()
        {
            IPort port          = null;
            var   printerStatus = new PrinterStatus();

            try
            {
                port = Factory.I.GetPort(PrinterName, string.Empty, Timeout);
                var status = port.GetParsedStatus();

                if (status == null)
                {
                    throw new PrinterException("The printer status is null.");
                }

                printerStatus.ReceiptPaperNearEmpty = status.ReceiptPaperNearEmptyInner || status.ReceiptPaperNearEmptyOuter;
                printerStatus.CoverOpen             = status.CoverOpen;
                printerStatus.ReceiptPaperEmpty     = status.ReceiptPaperEmpty;
                printerStatus.OverTemp    = status.OverTemp;
                printerStatus.CutterError = status.CutterError;
                printerStatus.IsOffline   = status.Offline;

                return(printerStatus);
            }
            finally
            {
                if (port != null)
                {
                    Factory.I.ReleasePort(port);
                }
            }
        }
Exemplo n.º 4
0
        /// <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);
            }
        }
Exemplo n.º 5
0
        /// <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);
        }
        /// <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);
                }
            }
        }
        /// <summary>
        /// Sample : Sending commands to printer without check condition (already open port).
        /// </summary>
        public static CommunicationResult SendCommandsDoNotCheckCondition(byte[] commands, IPort port)
        {
            Result result = Result.ErrorUnknown;
            int    code;

            try
            {
                result = Result.ErrorOpenPort;

                if (port == null)
                {
                    throw new PortException("port is null.");
                }

                StarPrinterStatus printerStatus;

                result = Result.ErrorWritePort;

                printerStatus = port.GetParsedStatus();

                uint commandsLength = (uint)commands.Length;

                uint writtenLength = port.WritePort(commands, 0, commandsLength);

                if (writtenLength != commandsLength)
                {
                    throw new PortException("WritePort failed.");
                }

                result = Result.ErrorWritePort;

                printerStatus = port.GetParsedStatus();

                result = Result.Success;
                code   = StarResultCode.Succeeded;
            }
            catch (PortException ex)
            {
                code = ex.ErrorCode;
            }

            return(new CommunicationResult()
            {
                Result = result,
                Code = code
            });
        }
Exemplo n.º 8
0
        /// <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);
                }
            }
        }
Exemplo n.º 9
0
        /// <summary>
        /// Sample : Sending commands to printer without check condition (already open port).
        /// </summary>
        public static CommunicationResult SendCommandsDoNotCheckCondition(byte[] commands, IPort port)
        {
            CommunicationResult result = CommunicationResult.ErrorUnknown;

            try
            {
                if (port == null)
                {
                    return(CommunicationResult.ErrorOpenPort);
                }

                StarPrinterStatus status;

                result = CommunicationResult.ErrorWritePort;

                status = port.GetParsedStatus();

                uint commandsLength = (uint)commands.Length;

                uint writtenLength = port.WritePort(commands, 0, commandsLength);

                if (writtenLength != commandsLength)
                {
                    throw new PortException("WritePort failed.");
                }

                result = CommunicationResult.ErrorWritePort;

                status = port.GetParsedStatus();

                result = CommunicationResult.Success;
            }
            catch (PortException)
            {
            }

            return(result);
        }
Exemplo n.º 10
0
        public static void GetDeviceStatus(string portName, string portSettings, int timeout, Action <Result, IPrinterStatus> action)
        {
            Task task = new Task(() =>
            {
                Result result = Result.UnknownError;

                IPort port = null;

                IPrinterStatus printerStatus = null;

                try
                {
                    result = Result.GetPortError;

                    port = Port.GetPort(portName, portSettings, timeout);

                    result = Result.GetParsedStatusError;

                    printerStatus = port.GetParsedStatus();

                    result = Result.Success;
                }
                catch (Exception exception)
                {
                    DebugExt.WriteLine(exception.Message);
                }
                finally
                {
                    if (port != null)
                    {
                        Port.ReleasePort(port);

                        port = null;
                    }
                }

                Device.BeginInvokeOnMainThread(() => {
                    action(result, printerStatus);
                });
            });

            task.Start();
        }
Exemplo n.º 11
0
        /// <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
            });
        }
        /// <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
            });
        }
Exemplo n.º 14
0
        /// <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);
        }
Exemplo n.º 15
0
        /// <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);
        }
Exemplo n.º 16
0
    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
        });
    }
        /// <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
            });
        }
Exemplo n.º 18
0
        public static void SendCommandsDoNotCheckCondition(byte[] commands, string portName, string portSettings, int timeout, Action <Result> action)
        {
            Task task = new Task(() =>
            {
                Result result = Result.UnknownError;

                IPort port = null;

                IPrinterStatus printerStatus;

                try
                {
                    result = Result.GetPortError;

                    port = Port.GetPort(portName, portSettings, timeout);

                    result = Result.GetParsedStatusError;

                    printerStatus = port.GetParsedStatus();

//                  if (printerStatus.Offline)     // Do not check condition.
//                  {
//                      throw new Exception("Printer is offline (GetParsedStatus)");
//                  }

                    result = Result.WritePortError;

                    DateTime startDateTime = DateTime.Now;

                    int total = 0;

                    while (true)
                    {
                        int written = port.WritePort(commands, total, commands.Length - total);

                        total += written;

//                      if (total == commands.Length)
                        if (total >= commands.Length)
                        {
                            break;
                        }

                        TimeSpan timeSpan = DateTime.Now - startDateTime;

                        if (timeSpan.TotalMilliseconds >= 30000)     // 30000mS!!!
                        {
                            throw new Exception("Write port timed out");
                        }
                    }

                    result = Result.GetParsedStatusError;

                    printerStatus = port.GetParsedStatus();

//                  if (printerStatus.Offline)     // Do not check condition.
//                  {
//                      throw new Exception("Printer is offline (GetParsedStatus)");
//                  }

                    result = Result.Success;
                }
                catch (Exception exception)
                {
                    DebugExt.WriteLine(exception.Message);
                }
                finally
                {
                    if (port != null)
                    {
                        Port.ReleasePort(port);

                        port = null;
                    }
                }

                Device.BeginInvokeOnMainThread(() => {
                    action(result);
                });
            });

            task.Start();
        }
        /// <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
            });
        }