private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { List <byte> rx = new List <byte>(); try { while (serialPort1.BytesToRead > 0) { rx.Add((byte)serialPort1.ReadByte()); } } catch (Exception ex) { MessageBox.Show("Error reading port " + serialPort1.PortName + ": " + ex.Message); } string outStr1; if (checkBox_hexTerminal.Checked == true) { outStr1 = Accessory.ConvertByteArrayToHex(rx.ToArray()); } else { outStr1 = System.Text.Encoding.GetEncoding(ComPrnControl_.NET2.Properties.Settings.Default.CodePage).GetString(rx.ToArray(), 0, rx.Count); } collectBuffer(outStr1, Port1DataIn); }
private void OpenFileDialog_FileOk(object sender, CancelEventArgs e) { if (openFileDialog.Title == "Open BIN file") //binary data read { SourceFile = openFileDialog.FileName; try { sourceData.Clear(); sourceData.AddRange(File.ReadAllBytes(SourceFile)); } catch (Exception ex) { MessageBox.Show("\r\nError reading file " + SourceFile + ": " + ex.Message); } //Form1.ActiveForm.Text += " " + SourceFile; textBox_code.Text = Accessory.ConvertByteArrayToHex(sourceData.ToArray()); textBox_code.Select(0, 0); //ParseEscPos.Init(textBox_code.Text, CommandDatabase); ParseEscPos.sourceData.Clear(); ParseEscPos.sourceData.AddRange(Accessory.ConvertHexToByteArray(textBox_code.Text)); } else if (openFileDialog.Title == "Open HEX file") //hex text read { SourceFile = openFileDialog.FileName; try { textBox_code.Text = Accessory.CheckHexString(File.ReadAllText(SourceFile)); } catch (Exception ex) { MessageBox.Show("\r\nError reading file " + SourceFile + ": " + ex.Message); } //Form1.ActiveForm.Text += " " + SourceFile; sourceData.Clear(); sourceData.AddRange(Accessory.ConvertHexToByteArray(textBox_code.Text)); textBox_code.Select(0, 0); //ParseEscPos.Init(textBox_code.Text, CommandDatabase); ParseEscPos.sourceData.Clear(); ParseEscPos.sourceData.AddRange(Accessory.ConvertHexToByteArray(textBox_code.Text)); } else if (openFileDialog.Title == "Open command CSV database") //hex text read { CommandDatabase = new DataTable(); ReadCsv(openFileDialog.FileName, CommandDatabase); for (var i = 0; i < CommandDatabase.Rows.Count; i++) { CommandDatabase.Rows[i][0] = Accessory.CheckHexString(CommandDatabase.Rows[i][0].ToString()); } dataGridView_commands.DataSource = CommandDatabase; ParseEscPos.commandDataBase = CommandDatabase; } else if (openFileDialog.Title == "Open errors CSV database") //hex text read { ErrorsDatabase = new DataTable(); ReadCsv(openFileDialog.FileName, ErrorsDatabase); } }
public static string RawToData(byte[] b) { if (Accessory.PrintableByteArray(b)) { return("\"" + Encoding.GetEncoding(Settings.Default.CodePage).GetString(b) + "\""); } return("[" + Accessory.ConvertByteArrayToHex(b) + "]"); }
private void OpenFileDialog_FileOk(object sender, CancelEventArgs e) { if (openFileDialog.Title == "Open BIN file") //binary data read { SourceFile = openFileDialog.FileName; try { sourceData.Clear(); sourceData.AddRange(File.ReadAllBytes(SourceFile)); } catch (Exception ex) { MessageBox.Show("\r\nError reading file " + SourceFile + ": " + ex.Message); } //Form1.ActiveForm.Text += " " + SourceFile; textBox_code.Text = Accessory.ConvertByteArrayToHex(sourceData.ToArray()); textBox_code.Select(0, 0); ParseEscPos.Init(sourceData.ToArray(), CommandDatabase); } else if (openFileDialog.Title == "Open HEX file") //hex text read { SourceFile = openFileDialog.FileName; try { textBox_code.Text = Accessory.CheckHexString(File.ReadAllText(SourceFile)); } catch (Exception ex) { MessageBox.Show("\r\nError reading file " + SourceFile + ": " + ex.Message); } //Form1.ActiveForm.Text += " " + SourceFile; sourceData.Clear(); sourceData.AddRange(Accessory.ConvertHexToByteArray(textBox_code.Text)); textBox_code.Select(0, 0); ParseEscPos.Init(Accessory.ConvertHexToByteArray(textBox_code.Text), CommandDatabase); } else if (openFileDialog.Title == "Open CSV database") //hex text read { ReadCsv(openFileDialog.FileName); ParseEscPos.Init(Accessory.ConvertHexToByteArray(textBox_code.Text), CommandDatabase); } }
// !!! check TLV actual data layout public static string RawToTLVData(byte[] b, int n) { var s = new List <byte>(); s.AddRange(b); if (s.Count < 4) { return(""); } if (s.Count > n + 4) { s = s.GetRange(0, n + 4); } var outStr = ""; var tlvType = (int)RawToNumber(s.GetRange(0, 2).ToArray()); outStr = "[" + tlvType + "]"; var strLength = (int)RawToNumber(s.GetRange(2, 2).ToArray()); outStr += "[" + strLength + "]"; if (s.Count == 4 + strLength) { var b1 = s.GetRange(2, s.Count - 2).ToArray(); if (Accessory.PrintableByteArray(b1)) { outStr += "\"" + Encoding.GetEncoding(Settings.Default.CodePage) .GetString(s.GetRange(4, s.Count - 4).ToArray()) + "\""; } else { outStr += "[" + Accessory.ConvertByteArrayToHex(b1) + "]"; } } else { outStr += "INCORRECT LENGTH"; } return(outStr); }
private void Server_DataReceived(byte[] rx2) { var dataRowRx2 = CSVdataTable.NewRow(); dataRowRx2[GridColumns.Date] = DateTime.Today.ToShortDateString(); dataRowRx2[GridColumns.Time] = DateTime.Now.ToLongTimeString(); dataRowRx2[GridColumns.Milis] = DateTime.Now.Millisecond.ToString("D3"); dataRowRx2[GridColumns.Port] = _clientName; dataRowRx2[GridColumns.Dir] = "RX"; dataRowRx2[GridColumns.Data] = Accessory.ConvertByteArrayToHex(rx2); dataRowRx2[GridColumns.Mark] = checkBox_Mark.Checked; if (logToGridToolStripMenuItem.Checked) { CSVcollectGrid(dataRowRx2); } var outStr2 = ""; if (checkBox_ClientHex.Checked) { outStr2 += dataRowRx2[GridColumns.Data]; } else { outStr2 += Encoding.GetEncoding(Settings.Default.CodePage).GetString(rx2, 0, rx2.Length); } CollectBuffer(outStr2, ClientDataIn, dataRowRx2[GridColumns.Date] + " " + dataRowRx2[GridColumns.Time] + "." + dataRowRx2[GridColumns.Milis]); if (autosaveCSVToolStripMenuItem1.Checked) { CSVcollectBuffer(dataRowRx2[GridColumns.Date] + "," + dataRowRx2[GridColumns.Time] + "," + dataRowRx2[GridColumns.Milis] + "," + dataRowRx2[GridColumns.Port] + "," + dataRowRx2[GridColumns.Dir] + "," + dataRowRx2[GridColumns.Data] + "," + "," + dataRowRx2[GridColumns.Mark] + "\r\n"); } }
//lineNum = -1 - искать во всех командах //lineNum = x - искать в команде на определенной стоке базы public static bool FindCommand(int _pos, int lineNum = -1) { //reset all result values ClearCommand(); if (sourceData.Count < _pos + 2) { return(false); } //check if sequence starts with >ENQ <NAK //check if it's a command or reply if (sourceData[_pos] == enqSign && sourceData[_pos + 1] == nakSign && sourceData[_pos + 2] == stxSign) { CSVColumns.CommandParameterSize = 1; CSVColumns.CommandParameterType = 2; CSVColumns.CommandParameterValue = 3; CSVColumns.CommandDescription = 4; itIsReply = false; _pos += 3; } else if (sourceData[_pos] == ackSign && sourceData[_pos + 1] == stxSign) { itIsReply = true; CSVColumns.CommandParameterSize = 5; CSVColumns.CommandParameterType = 6; CSVColumns.CommandParameterValue = 7; CSVColumns.CommandDescription = 8; _pos += 2; } else { return(false); } //select data frame commandFrameLength = sourceData[_pos]; _pos++; //check if "commandFrameLength" less than "sourcedata". note the last byte of "sourcedata" is CRC. if (sourceData.Count - 1 < _pos + commandFrameLength) { commandFrameLength = sourceData.Count - _pos; lengthIncorrect = true; } //find command if (sourceData.Count < _pos + 1) { return(false); //check if it doesn't go over the last symbol } var i = 0; if (lineNum != -1) { i = lineNum; } for (; i < commandDataBase.Rows.Count; i++) { if (commandDataBase.Rows[i][CSVColumns.CommandName].ToString() != "") { if (sourceData[_pos] == Accessory.ConvertHexToByte(commandDataBase.Rows[i][CSVColumns.CommandName].ToString()) || Accessory.ConvertByteArrayToHex(sourceData.GetRange(_pos, 2).ToArray()) == commandDataBase.Rows[i][CSVColumns.CommandName].ToString()) //if command matches { if (lineNum < 0 || lineNum == i) //if string matches { commandName = commandDataBase.Rows[i][CSVColumns.CommandName].ToString(); commandDbLineNum = i; commandDesc = commandDataBase.Rows[i][CSVColumns.CommandDescription].ToString(); commandFramePosition = _pos; //get CRC of the frame var sentCRC = sourceData[_pos + commandFrameLength]; //check length of sourceData var calculatedCRC = PayOnline_CRC(sourceData.GetRange(_pos - 1, commandFrameLength + 1).ToArray(), commandFrameLength + 1); if (calculatedCRC != sentCRC) { crcFailed = true; } else { crcFailed = false; } //check command height - how many rows are occupated var i1 = 0; while (commandDbLineNum + i1 + 1 < commandDataBase.Rows.Count && commandDataBase.Rows[commandDbLineNum + i1 + 1][CSVColumns.CommandName].ToString() == "") { i1++; } commandDbHeight = i1; return(true); } } } } return(false); }
private void Button_find_Click(object sender, EventArgs e) { if (sender != listBox_commands) { listBox_commands.Items.Clear(); } textBox_commandDesc.Clear(); ResultDatabase.Clear(); //check if cursor position in not last if (textBox_code.SelectionStart < textBox_code.Text.Length) { if (textBox_code.Text.Substring(textBox_code.SelectionStart, 1) == " ") { textBox_code.SelectionStart++; } } //check if cursor position in not first if (textBox_code.SelectionStart != 0) { if (textBox_code.Text.Substring(textBox_code.SelectionStart - 1, 1) != " " && textBox_code.Text.Substring(textBox_code.SelectionStart, 1) != " ") { textBox_code.SelectionStart--; } } label_currentPosition.Text = textBox_code.SelectionStart + "/" + textBox_code.TextLength; if (ParseEscPos.FindCommand(textBox_code.SelectionStart / 3, comboBox_printerType.SelectedItem.ToString())) { //int currentCommand = 0; //temp const to select 1st command found var currentCommand = 0; if (sender == listBox_commands) { currentCommand = listBox_commands.SelectedIndex; } else if (ParseEscPos.commandName.Count > 1) { var _saved_pos = textBox_code.SelectionStart; var err = new bool[ParseEscPos.commandName.Count, 2]; for (var i = 0; i < ParseEscPos.commandName.Count; i++) { //есть ли ошибка в поиске параметров err[i, 0] = ParseEscPos.FindParameter(i); //если мы еще в пределах поля данных if ((ParseEscPos.commandPosition[currentCommand] + ParseEscPos.commandBlockLength) * 3 < textBox_code.Text.Length) { //ищем след. команду и, возможно, параметры //есть ли ошибка в поиске след. команды err[i, 1] = ParseEscPos.FindCommand(_saved_pos / 3 + ParseEscPos.commandBlockLength, comboBox_printerType.SelectedItem.ToString()); //возможно, стоит поискать параметры след. команды и проверить их на ошибки тоже //возвращаем поиск команды в исходное состояние для след. итерации textBox_code.SelectionStart = _saved_pos; ParseEscPos.FindCommand(textBox_code.SelectionStart / 3, comboBox_printerType.SelectedItem.ToString()); } else { err[i, 1] = err[i, 0]; } //обрабатываем результаты проверок //если параметры текущей и след. команда нашлись, то выбираем текущую if (err[i, 1] == err[i, 0] && err[i, 0]) { currentCommand = i; } } } ParseEscPos.FindParameter(currentCommand); if (sender != button_auto) //only update interface if it's no auto-parsing mode { dataGridView_commands.CurrentCell = dataGridView_commands .Rows[ParseEscPos.commandDbLineNum[currentCommand]].Cells[ParseEscPos.CSVColumns.CommandName]; if (sender != listBox_commands) { for (var i = 0; i < ParseEscPos.commandName.Count; i++) { listBox_commands.Items.Add(ParseEscPos.commandName[i] + "[" + ParseEscPos.commandPrinterModel[i] + "]"); } } listBox_commands.SelectedIndexChanged -= ListBox_commands_SelectedIndexChanged; listBox_commands.SelectedIndex = currentCommand; listBox_commands.SelectedIndexChanged += ListBox_commands_SelectedIndexChanged; textBox_commandDesc.Text = ParseEscPos.commandDesc[currentCommand]; for (var i = 0; i < ParseEscPos.paramName.Count; i++) { var row = ResultDatabase.NewRow(); row[ResultColumns.Name] = ParseEscPos.paramName[i]; row[ResultColumns.Value] = ParseEscPos.paramValue[i]; row[ResultColumns.Type] = ParseEscPos.paramType[i]; row[ResultColumns.Raw] = Accessory.ConvertByteArrayToHex(ParseEscPos.paramRAWValue[i].ToArray()); //if (ParseEscPos.paramType[i].ToLower() != ParseEscPos.DataTypes.Bitfield) row[ResultColumns.Desc] = ParseEscPos.paramDesc[i]; row[ResultColumns.Desc] = ParseEscPos.paramDesc[i]; ResultDatabase.Rows.Add(row); if (ParseEscPos.paramType[i].ToLower() == ParseEscPos.DataTypes.Bitfield) //add bitfield display { for (var i1 = 0; i1 < 8; i1++) { row = ResultDatabase.NewRow(); //row[ResultColumns.Name] = ParseEscPos.paramName[i] + "[" + i1.ToString() + "]"; row[ResultColumns.Value] = ParseEscPos.bitValue[i][i1]; row[ResultColumns.Type] = ParseEscPos.bitName[i][i1]; row[ResultColumns.Desc] = ParseEscPos.bitDescription[i][i1]; ResultDatabase.Rows.Add(row); } } } } //textBox_code.Select(textBox_code.SelectionStart, ParseEscPos.commandBlockLength * 3); textBox_code.Select(ParseEscPos.commandPosition[currentCommand] * 3, ParseEscPos.commandBlockLength * 3); } //look for the end of unrecognizable data (consider it text string) else { var i = 3; while (!ParseEscPos.FindCommand((textBox_code.SelectionStart + i) / 3, comboBox_printerType.SelectedItem.ToString()) && textBox_code.SelectionStart + i < textBox_code.TextLength) //looking for a non-parseable part end { i += 3; } if (textBox_code.SelectionStart + i >= textBox_code.TextLength) { i = textBox_code.TextLength - textBox_code.SelectionStart; } textBox_code.Select(textBox_code.SelectionStart, i); ParseEscPos.commandName.Clear(); if (textBox_code.SelectedText.Length > 0) { if (sender != button_auto) { listBox_commands.Items.Add("\"" + textBox_code.SelectedText + "\""); dataGridView_commands.CurrentCell = dataGridView_commands.Rows[0].Cells[0]; if (Accessory.PrintableHex(textBox_code.SelectedText)) { textBox_commandDesc.Text = "\"" + Encoding.GetEncoding(Settings.Default.CodePage) .GetString(Accessory.ConvertHexToByteArray(textBox_code.SelectedText)) + "\""; } } } } textBox_code.ScrollToCaret(); }
private void Button_auto_Click(object sender, EventArgs e) { File.WriteAllText(SourceFile + ".escpos", ""); File.WriteAllText(SourceFile + ".list", ""); textBox_code.Select(0, 0); var asciiString = new StringBuilder(); while (textBox_code.SelectionStart < textBox_code.TextLength) { var saveStr = new StringBuilder(); //run "Find" button event as "Auto" Button_find_Click(button_auto, EventArgs.Empty); if (ParseEscPos.commandName != "") { //ParseEscPos.FindCommandParameter(); //????????????? //Save ASCII string if collected till now if (asciiString.Length != 0) { saveStr.Append("#" + ParseEscPos.commandFramePosition + " RAW data [" + asciiString + "]\r\n"); if (asciiString.ToString() == Accessory.ConvertByteToHex(ParseEscPos.ackSign)) { saveStr.Append("ACK\r\n"); } else if (asciiString.ToString() == Accessory.ConvertByteToHex(ParseEscPos.nakSign)) { saveStr.Append("NAK\r\n"); } else if (asciiString.ToString() == Accessory.ConvertByteToHex(ParseEscPos.enqSign) + Accessory.ConvertByteToHex(ParseEscPos.ackSign)) { saveStr.Append("BUSY\r\n"); } else if (Accessory.PrintableHex(asciiString.ToString())) { saveStr.Append("ASCII string: \"" + Encoding.GetEncoding(Settings.Default.CodePage) .GetString(Accessory.ConvertHexToByteArray(asciiString.ToString())) + "\"\r\n"); } saveStr.Append("\r\n"); File.AppendAllText(SourceFile + ".list", asciiString + "\r\n", Encoding.GetEncoding(Settings.Default.CodePage)); asciiString.Clear(); } //collect command into file /* RAW [12 34] * Command: "12 34" - "Description" * Printer model: "VKP80II-SX" * Parameter: "n" = "1234"[Word] - "Description" * Parameter: ... */ saveStr.Append("#" + ParseEscPos.commandFramePosition + " RAW data [" + textBox_code.SelectedText + "]\r\n"); if (ParseEscPos.itIsReply) { saveStr.Append("Reply: [" + ParseEscPos.commandName + "] - \"" + ParseEscPos.commandDesc + "\"\r\n"); } else { saveStr.Append("Command: [" + ParseEscPos.commandName + "] - \"" + ParseEscPos.commandDesc + "\"\r\n"); } for (var i = 0; i < ParseEscPos.commandParamSize.Count; i++) { saveStr.Append("\tParameter = "); saveStr.Append("\"" + ParseEscPos.commandParamValue[i] + "\""); saveStr.Append("[" + ParseEscPos.commandParamType[i] + "] - \"" + ParseEscPos .commandParamDesc[i].TrimStart('\r').TrimStart('\n').TrimEnd('\n').TrimEnd('\r') .Replace("\n", "\n\t\t\t\t")); if (ParseEscPos.commandParamType[i].ToLower() == ParseEscPos.DataTypes.Error) { saveStr.Append(": " + GetErrorDesc(int.Parse(ParseEscPos.commandParamValue[i]))); } saveStr.Append("\", RAW [" + Accessory.ConvertByteArrayToHex(ParseEscPos.commandParamRAWValue[i].ToArray()) + "]\r\n"); if (ParseEscPos.commandParamType[i].ToLower() == ParseEscPos.DataTypes.Bitfield) { var b = byte.Parse(ParseEscPos.commandParamValue[i]); for (var i1 = 0; i1 < 8; i1++) { saveStr.Append("\t\t[bit" + i1 + "]\" = \""); saveStr.Append((Accessory.GetBit(b, (byte)i1) ? (byte)1 : (byte)0) + "\" - \""); saveStr.Append(dataGridView_commands.Rows[ParseEscPos.commandParamDbLineNum[i] + i1 + 1] .Cells[ParseEscPos.CSVColumns.CommandDescription].Value.ToString() .Replace("\n", "\n\t\t\t\t")); saveStr.Append("\"\r\n"); } } } saveStr.Append("\r\n"); File.AppendAllText(SourceFile + ".list", textBox_code.SelectedText + "\r\n", Encoding.GetEncoding(Settings.Default.CodePage)); File.AppendAllText(SourceFile + ".escpos", saveStr.ToString(), Encoding.GetEncoding(Settings.Default.CodePage)); } else //consider this as a string and collect { asciiString.Append(textBox_code.SelectedText); } textBox_code.SelectionStart = textBox_code.SelectionStart + textBox_code.SelectionLength; } if (asciiString.Length != 0) { var saveStr = new StringBuilder(); saveStr.Append("#" + ParseEscPos.commandFramePosition + " RAW data [" + asciiString + "]\r\n"); if (asciiString.ToString() == Accessory.ConvertByteToHex(ParseEscPos.ackSign)) { saveStr.Append("ACK"); } if (asciiString.ToString() == Accessory.ConvertByteToHex(ParseEscPos.nakSign)) { saveStr.Append("NAK"); } if (asciiString.ToString() == Accessory.ConvertByteToHex(ParseEscPos.enqSign) + Accessory.ConvertByteToHex(ParseEscPos.ackSign)) { saveStr.Append("BUSY"); } else if (Accessory.PrintableHex(asciiString.ToString())) { saveStr.Append("ASCII string: \"" + Encoding.GetEncoding(Settings.Default.CodePage) .GetString(Accessory.ConvertHexToByteArray(asciiString.ToString())) + "\"\r\n"); } saveStr.Append("\r\n"); File.AppendAllText(SourceFile + ".list", asciiString + "\r\n", Encoding.GetEncoding(Settings.Default.CodePage)); File.AppendAllText(SourceFile + ".escpos", saveStr.ToString(), Encoding.GetEncoding(Settings.Default.CodePage)); asciiString.Clear(); } }
private async void button_sendFile_ClickAsync(object sender, EventArgs e) { if (SendComing > 0) { SendComing++; } else if (SendComing == 0) { UInt16 repeat = 1, delay = 1, strDelay = 1; if (textBox_fileName.Text != "" && textBox_sendNum.Text != "" && UInt16.TryParse(textBox_sendNum.Text, out repeat) && UInt16.TryParse(textBox_delay.Text, out delay) && UInt16.TryParse(textBox_strDelay.Text, out strDelay)) { SendComing = 1; button_Send.Enabled = false; button_openFile.Enabled = false; button_sendFile.Text = "Stop"; textBox_fileName.Enabled = false; textBox_sendNum.Enabled = false; textBox_delay.Enabled = false; textBox_strDelay.Enabled = false; for (int n = 0; n < repeat; n++) { string outStr = ""; string outErr = ""; long length = 0; if (repeat > 1) { collectBuffer(" Send cycle " + (n + 1).ToString() + "/" + repeat.ToString() + ">> ", 0); } try { length = new FileInfo(textBox_fileName.Text).Length; } catch (Exception ex) { MessageBox.Show("\r\nError opening file " + textBox_fileName.Text + ": " + ex.Message); } if (comboBox_Printer.Items.Count > 0 && comboBox_Printer.SelectedItem.ToString() != "") { //binary file read if (!checkBox_hexFileOpen.Checked) { //byte-by-byte if (radioButton_byByte.Checked) { byte[] tmpBuffer = new byte[length]; try { tmpBuffer = File.ReadAllBytes(textBox_fileName.Text); } catch (Exception ex) { MessageBox.Show("\r\nError reading file " + textBox_fileName.Text + ": " + ex.Message); } for (int l = 0; l < tmpBuffer.Length; l++) { byte[] outByte = { tmpBuffer[l] }; if (checkBox_hexTerminal.Checked) { outStr = Accessory.ConvertByteArrayToHex(tmpBuffer, tmpBuffer.Length); } else { outStr = Encoding.GetEncoding(RawPrnControl.Properties.Settings.Default.CodePage).GetString(tmpBuffer); } collectBuffer(outStr, Port1DataOut); if (RawPrinterSender.SendRAWToPrinter(comboBox_Printer.SelectedItem.ToString(), outByte)) { progressBar1.Value = (n * tmpBuffer.Length + l) * 100 / (repeat * tmpBuffer.Length); if (strDelay > 0) { await TaskEx.Delay(strDelay); } } else { collectBuffer("Byte " + l.ToString() + ": Write Failure", Port1Error); } if (SendComing > 1) { l = tmpBuffer.Length; } } } //stream else { byte[] tmpBuffer = new byte[length]; try { tmpBuffer = File.ReadAllBytes(textBox_fileName.Text); } catch (Exception ex) { MessageBox.Show("\r\nError reading file " + textBox_fileName.Text + ": " + ex.Message); } int r = 0; while (r < 10 && !RawPrinterSender.SendRAWToPrinter(comboBox_Printer.SelectedItem.ToString(), tmpBuffer)) { collectBuffer("USB write retry " + r.ToString(), Port1Error); await TaskEx.Delay(100); r++; } if (r >= 10) { outErr = "Block write failure"; } if (checkBox_hexTerminal.Checked) { outStr = Accessory.ConvertByteArrayToHex(tmpBuffer, tmpBuffer.Length); } else { outStr = Encoding.GetEncoding(RawPrnControl.Properties.Settings.Default.CodePage).GetString(tmpBuffer); } if (outErr != "") { collectBuffer(outErr + ": start", Port1Error); } collectBuffer(outStr, Port1DataOut); if (outErr != "") { collectBuffer(outErr + ": end", Port1Error); } progressBar1.Value = ((n * tmpBuffer.Length) * 100) / (repeat * tmpBuffer.Length); } } //hex file read else { //String-by-string if (radioButton_byString.Checked) { String[] tmpBuffer = { }; try { tmpBuffer = File.ReadAllText(textBox_fileName.Text).Replace('\n', '\r').Replace("\r\r", "\r").Split('\r'); } catch (Exception ex) { MessageBox.Show("\r\nError reading file " + textBox_fileName.Text + ": " + ex.Message); } for (int l = 0; l < tmpBuffer.Length; l++) { if (tmpBuffer[l] != "") { tmpBuffer[l] = Accessory.CheckHexString(tmpBuffer[l]); collectBuffer(outStr, Port1DataOut); if (RawPrinterSender.SendRAWToPrinter(comboBox_Printer.SelectedItem.ToString(), Accessory.ConvertHexToByteArray(tmpBuffer[l]))) { if (checkBox_hexTerminal.Checked) { outStr = tmpBuffer[l]; } else { outStr = Accessory.ConvertHexToString(tmpBuffer[l]); } if (strDelay > 0) { await TaskEx.Delay(strDelay); } } else //?????????????? { outErr = "String" + l.ToString() + ": Write failure"; } if (SendComing > 1) { l = tmpBuffer.Length; } collectBuffer(outErr, Port1Error); progressBar1.Value = (n * tmpBuffer.Length + l) * 100 / (repeat * tmpBuffer.Length); } } } //byte-by-byte if (radioButton_byByte.Checked) { string tmpStrBuffer = ""; try { tmpStrBuffer = Accessory.CheckHexString(File.ReadAllText(textBox_fileName.Text)); } catch (Exception ex) { MessageBox.Show("Error reading file " + textBox_fileName.Text + ": " + ex.Message); } byte[] tmpBuffer = new byte[tmpStrBuffer.Length / 3]; tmpBuffer = Accessory.ConvertHexToByteArray(tmpStrBuffer); for (int l = 0; l < tmpBuffer.Length; l++) { byte[] outByte = { tmpBuffer[l] }; if (checkBox_hexTerminal.Checked) { outStr = Accessory.ConvertByteArrayToHex(tmpBuffer, tmpBuffer.Length); } else { outStr = Encoding.GetEncoding(RawPrnControl.Properties.Settings.Default.CodePage).GetString(tmpBuffer); } collectBuffer(outStr, Port1DataOut); if (RawPrinterSender.SendRAWToPrinter(comboBox_Printer.SelectedItem.ToString(), outByte)) { progressBar1.Value = (n * tmpBuffer.Length + l) * 100 / (repeat * tmpBuffer.Length); if (strDelay > 0) { await TaskEx.Delay(strDelay); } } else { collectBuffer("Byte " + l.ToString() + ": Write Failure", Port1Error); } if (SendComing > 1) { l = tmpBuffer.Length; } } } //stream else { string tmpStrBuffer = ""; try { tmpStrBuffer = Accessory.CheckHexString(File.ReadAllText(textBox_fileName.Text)); } catch (Exception ex) { MessageBox.Show("Error reading file " + textBox_fileName.Text + ": " + ex.Message); } byte[] tmpBuffer = new byte[tmpStrBuffer.Length / 3]; tmpBuffer = Accessory.ConvertHexToByteArray(tmpStrBuffer); int r = 0; while (r < 10 && !RawPrinterSender.SendRAWToPrinter(comboBox_Printer.SelectedItem.ToString(), tmpBuffer)) { collectBuffer("USB write retry " + r.ToString(), Port1Error); await TaskEx.Delay(100); r++; } if (r >= 10) { outErr = "Block write failure"; } if (checkBox_hexTerminal.Checked) { outStr = Accessory.ConvertByteArrayToHex(tmpBuffer, tmpBuffer.Length); } else { outStr = Encoding.GetEncoding(RawPrnControl.Properties.Settings.Default.CodePage).GetString(tmpBuffer); } if (outErr != "") { collectBuffer(outErr + " start", Port1Error); } collectBuffer(outStr, Port1DataOut); if (outErr != "") { collectBuffer(outErr + " end", Port1Error); } progressBar1.Value = ((n * tmpBuffer.Length) * 100) / (repeat * tmpBuffer.Length); } } } if (repeat > 1) { await TaskEx.Delay(delay); } if (SendComing > 1) { n = repeat; } } button_Send.Enabled = true; button_openFile.Enabled = true; button_sendFile.Text = "Send file"; textBox_fileName.Enabled = true; textBox_sendNum.Enabled = true; textBox_delay.Enabled = true; textBox_strDelay.Enabled = true; } SendComing = 0; } }
private async void Button_sendFile_ClickAsync(object sender, EventArgs e) { if (_sendComing > 0) { _sendComing++; } else if (_sendComing == 0) { int repeat = 1, delay = 1, strDelay = 1; if (textBox_fileName.Text != "" && textBox_sendNum.Text != "" && int.TryParse(textBox_sendNum.Text, out repeat) && int.TryParse(textBox_delay.Text, out delay) && int.TryParse(textBox_strDelay.Text, out strDelay)) { _sendComing = 1; button_Send.Enabled = false; button_closeport.Enabled = false; button_openFile.Enabled = false; button_sendFile.Text = "Stop"; textBox_fileName.Enabled = false; textBox_sendNum.Enabled = false; textBox_delay.Enabled = false; textBox_strDelay.Enabled = false; for (var n = 0; n < repeat; n++) { string outStr; long length = 0; try { length = new FileInfo(textBox_fileName.Text).Length; } catch (Exception ex) { MessageBox.Show("\r\nError opening file " + textBox_fileName.Text + ": " + ex.Message); } if (!checkBox_hexFileOpen.Checked) //binary data read { if (radioButton_byByte.Checked) //byte-by-byte { var tmpBuffer = new byte[length]; try { tmpBuffer = File.ReadAllBytes(textBox_fileName.Text); } catch (Exception ex) { MessageBox.Show("\r\nError reading file " + textBox_fileName.Text + ": " + ex.Message); } LptOpen(comboBox_portname1.SelectedItem.ToString()); if (!_isConnected) { MessageBox.Show("Error opening port " + comboBox_portname1.SelectedItem); comboBox_portname1.Enabled = true; return; } try { for (var m = 0; m < tmpBuffer.Length; m++) { _lptPort.Write(tmpBuffer, m, 1); progressBar1.Value = (n * tmpBuffer.Length + m) * 100 / (repeat * tmpBuffer.Length); if (strDelay > 0) { await TaskEx.Delay(strDelay); } //ReadLPT(); outStr = ">> "; if (checkBox_hexTerminal.Checked) { outStr += Accessory.ConvertByteArrayToHex(tmpBuffer); } else { outStr += Accessory.ConvertHexToString( Accessory.ConvertByteArrayToHex(tmpBuffer)); } outStr += "\r\n"; SetText(outStr); if (_sendComing > 1) { m = tmpBuffer.Length; } } } catch (Exception ex) { MessageBox.Show("Error sending to port " + comboBox_portname1.SelectedItem + ": " + ex.Message); } } else { var tmpBuffer = new byte[length]; try { tmpBuffer = File.ReadAllBytes(textBox_fileName.Text); } catch (Exception ex) { MessageBox.Show("\r\nError reading file " + textBox_fileName.Text + ": " + ex.Message); } LptOpen(comboBox_portname1.SelectedItem.ToString()); if (!_isConnected) { MessageBox.Show("Error opening port " + comboBox_portname1.SelectedItem); comboBox_portname1.Enabled = true; return; } try { _lptPort.Write(tmpBuffer, 0, tmpBuffer.Length); //ReadLPT(); outStr = ">> "; if (checkBox_hexTerminal.Checked) { outStr += Accessory.ConvertByteArrayToHex(tmpBuffer); } else { outStr += Accessory.ConvertHexToString( Accessory.ConvertByteArrayToHex(tmpBuffer)); } outStr += "\r\n"; SetText(outStr); progressBar1.Value = n * 100 / (repeat * tmpBuffer.Length); } catch (Exception ex) { MessageBox.Show("Error sending to port " + comboBox_portname1.SelectedItem + ": " + ex.Message); } } } else //hex text read { if (radioButton_byString.Checked) //String-by-string { string[] tmpBuffer = { }; try { length = new FileInfo(textBox_fileName.Text).Length; tmpBuffer = File.ReadAllText(textBox_fileName.Text).Replace("\n", "").Split('\r'); } catch (Exception ex) { MessageBox.Show("\r\nError reading file " + textBox_fileName.Text + ": " + ex.Message); } LptOpen(comboBox_portname1.SelectedItem.ToString()); if (!_isConnected) { MessageBox.Show("Error opening port " + comboBox_portname1.SelectedItem); comboBox_portname1.Enabled = true; return; } try { for (var m = 0; m < tmpBuffer.Length; m++) { tmpBuffer[m] = Accessory.CheckHexString(tmpBuffer[m]); _lptPort.Write(Accessory.ConvertHexToByteArray(tmpBuffer[m]), 0, tmpBuffer[m].Length / 3); outStr = ">> "; if (checkBox_hexTerminal.Checked) { outStr += tmpBuffer[m]; } else { outStr += Accessory.ConvertHexToString(tmpBuffer[m]); } outStr += "\r\n"; if (strDelay > 0) { await TaskEx.Delay(strDelay); } //ReadLPT(); if (_sendComing > 1) { m = tmpBuffer.Length; } SetText(outStr); progressBar1.Value = (n * tmpBuffer.Length + m) * 100 / (repeat * tmpBuffer.Length); } } catch (Exception ex) { MessageBox.Show("Error sending to port " + comboBox_portname1.SelectedItem + ": " + ex.Message); } if (repeat > 1) { outStr = "\r\nSend cycle " + (n + 1) + "/" + repeat + "\r\n"; } else { outStr = ""; } //if (checkBox_hexTerminal.Checked) outStr += tmpBuffer; //else outStr += ConvertHexToString(tmpBuffer.ToString()); } else if (radioButton_byByte.Checked) //byte-by-byte { var tmpBuffer = ""; try { length = new FileInfo(textBox_fileName.Text).Length; tmpBuffer = File.ReadAllText(textBox_fileName.Text); } catch (Exception ex) { MessageBox.Show("\r\nError reading file " + textBox_fileName.Text + ": " + ex.Message); } tmpBuffer = Accessory.CheckHexString(tmpBuffer); LptOpen(comboBox_portname1.SelectedItem.ToString()); if (!_isConnected) { MessageBox.Show("Error opening port " + comboBox_portname1.SelectedItem); comboBox_portname1.Enabled = true; return; } try { for (var m = 0; m < tmpBuffer.Length; m += 3) { _lptPort.Write(Accessory.ConvertHexToByteArray(tmpBuffer.Substring(m, 3)), 0, 1); outStr = ">> "; if (checkBox_hexTerminal.Checked) { outStr += tmpBuffer.Substring(m, 3); } else { outStr += Accessory.ConvertHexToString(tmpBuffer.Substring(m, 3)); } outStr += "\r\n"; if (strDelay > 0) { await TaskEx.Delay(strDelay); } //ReadLPT(); progressBar1.Value = (n * tmpBuffer.Length + m) * 100 / (repeat * tmpBuffer.Length); if (_sendComing > 1) { m = tmpBuffer.Length; } SetText(outStr); progressBar1.Value = (n * tmpBuffer.Length + m) * 100 / (repeat * tmpBuffer.Length); } } catch (Exception ex) { MessageBox.Show("Error sending to port " + comboBox_portname1.SelectedItem + ": " + ex.Message); } if (repeat > 1) { outStr = " Send cycle " + (n + 1) + "/" + repeat + ">> "; } else { outStr = ""; } } else //raw stream { var tmpBuffer = ""; try { length = new FileInfo(textBox_fileName.Text).Length; tmpBuffer = Accessory.CheckHexString(File.ReadAllText(textBox_fileName.Text)); } catch (Exception ex) { MessageBox.Show("\r\nError reading file " + textBox_fileName.Text + ": " + ex.Message); } LptOpen(comboBox_portname1.SelectedItem.ToString()); if (!_isConnected) { MessageBox.Show("Error opening port " + comboBox_portname1.SelectedItem); comboBox_portname1.Enabled = true; return; } try { _lptPort.Write(Accessory.ConvertHexToByteArray(tmpBuffer), 0, tmpBuffer.Length / 3); //ReadLPT(); } catch (Exception ex) { MessageBox.Show("Error sending to port " + comboBox_portname1.SelectedItem + ": " + ex.Message); } if (repeat > 1) { outStr = " Send cycle " + (n + 1) + "/" + repeat + ">> "; } else { outStr = ">> "; } if (checkBox_hexTerminal.Checked) { outStr += tmpBuffer; } else { outStr += Accessory.ConvertHexToString(tmpBuffer); } outStr += "\r\n"; SetText(outStr); progressBar1.Value = n * 100 / (repeat * tmpBuffer.Length); } } if (repeat > 1) { await TaskEx.Delay(delay); } if (_sendComing > 1) { n = repeat; } } button_Send.Enabled = true; button_closeport.Enabled = true; button_openFile.Enabled = true; button_sendFile.Text = "Send file"; textBox_fileName.Enabled = true; textBox_sendNum.Enabled = true; textBox_delay.Enabled = true; textBox_strDelay.Enabled = true; } _sendComing = 0; } }
private void button_sendFile_Click(object sender, EventArgs e) { if (SendComing > 0) { SendComing++; } else if (SendComing == 0) { UInt16 repeat = 1, delay = 1, strDelay = 1; if (textBox_fileName.Text != "" && textBox_sendNum.Text != "" && UInt16.TryParse(textBox_sendNum.Text, out repeat) && UInt16.TryParse(textBox_delay.Text, out delay) && UInt16.TryParse(textBox_strDelay.Text, out strDelay)) { SendComing = 1; button_Send.Enabled = false; button_closeport.Enabled = false; button_openFile.Enabled = false; button_sendFile.Text = "Stop"; textBox_fileName.Enabled = false; textBox_sendNum.Enabled = false; textBox_delay.Enabled = false; textBox_strDelay.Enabled = false; for (int n = 0; n < repeat; n++) { string outStr; long length = 0; if (repeat > 1) { outStr = "\r\nSend cycle " + (n + 1).ToString() + "/" + repeat.ToString() + "\r\n"; } else { outStr = ""; } try { length = new FileInfo(textBox_fileName.Text).Length; } catch (Exception ex) { MessageBox.Show("\r\nError opening file " + textBox_fileName.Text + ": " + ex.Message); } if (!checkBox_hexFileOpen.Checked) //binary data read { if (radioButton_byByte.Checked) //byte-by-byte { byte[] tmpBuffer = new byte[length]; try { tmpBuffer = File.ReadAllBytes(textBox_fileName.Text); } catch (Exception ex) { MessageBox.Show("\r\nError reading file " + textBox_fileName.Text + ": " + ex.Message); } try { for (int m = 0; m < tmpBuffer.Length; m++) { serialPort1.Write(tmpBuffer, m, 1); progressBar1.Value = (n * tmpBuffer.Length + m) * 100 / (repeat * tmpBuffer.Length); if (strDelay > 0) { Accessory.DelayMs(strDelay); } if (SendComing > 1) { m = tmpBuffer.Length; } } if (checkBox_hexTerminal.Checked) { outStr += Accessory.ConvertByteArrayToHex(tmpBuffer); } else { outStr += Accessory.ConvertHexToString(Accessory.ConvertByteArrayToHex(tmpBuffer)); } collectBuffer(outStr, Port1DataOut); } catch (Exception ex) { MessageBox.Show("Error sending to port " + serialPort1.PortName + ": " + ex.Message); } } else //stream { byte[] tmpBuffer = new byte[length]; try { tmpBuffer = File.ReadAllBytes(textBox_fileName.Text); } catch (Exception ex) { MessageBox.Show("\r\nError reading file " + textBox_fileName.Text + ": " + ex.Message); } try { for (int m = 0; m < tmpBuffer.Length; m++) { serialPort1.Write(tmpBuffer, m, 1); progressBar1.Value = (n * tmpBuffer.Length + m) * 100 / (repeat * tmpBuffer.Length); } } catch (Exception ex) { MessageBox.Show("Error sending to port " + serialPort1.PortName + ": " + ex.Message); } if (checkBox_hexTerminal.Checked) { outStr += Accessory.ConvertByteArrayToHex(tmpBuffer); } else { outStr += Accessory.ConvertHexToString(Accessory.ConvertByteArrayToHex(tmpBuffer)); } collectBuffer(outStr, Port1DataOut); } } else //hex text read { if (radioButton_byString.Checked) //String-by-string { String[] tmpBuffer = { }; try { length = new FileInfo(textBox_fileName.Text).Length; tmpBuffer = File.ReadAllText(textBox_fileName.Text).Replace("\n", "").Split('\r'); } catch (Exception ex) { MessageBox.Show("\r\nError reading file " + textBox_fileName.Text + ": " + ex.Message); } for (int m = 0; m < tmpBuffer.Length; m++) { tmpBuffer[m] = Accessory.CheckHexString(tmpBuffer[m]); } try { for (int m = 0; m < tmpBuffer.Length; m++) { serialPort1.Write(Accessory.ConvertHexToByteArray(tmpBuffer[m]), 0, tmpBuffer[m].Length / 3); if (checkBox_hexTerminal.Checked) { outStr += tmpBuffer[m]; } else { outStr += Accessory.ConvertHexToString(tmpBuffer[m].ToString()); } collectBuffer(outStr, Port1DataOut); progressBar1.Value = (n * tmpBuffer.Length + m) * 100 / (repeat * tmpBuffer.Length); if (strDelay > 0) { Accessory.DelayMs(strDelay); } if (SendComing > 1) { m = tmpBuffer.Length; } } } catch (Exception ex) { MessageBox.Show("Error sending to port " + serialPort1.PortName + ": " + ex.Message); } //if (checkBox_hexTerminal.Checked) outStr += tmpBuffer; //else outStr += ConvertHexToString(tmpBuffer.ToString()); } else if (radioButton_byByte.Checked) //byte-by-byte { String tmpBuffer = ""; try { length = new FileInfo(textBox_fileName.Text).Length; tmpBuffer = File.ReadAllText(textBox_fileName.Text); } catch (Exception ex) { MessageBox.Show("\r\nError reading file " + textBox_fileName.Text + ": " + ex.Message); } tmpBuffer = Accessory.CheckHexString(tmpBuffer); try { for (int m = 0; m < tmpBuffer.Length; m += 3) { serialPort1.Write(Accessory.ConvertHexToByteArray(tmpBuffer.Substring(m, 3)), 0, 1); progressBar1.Value = (n * tmpBuffer.Length + m) * 100 / (repeat * tmpBuffer.Length); if (strDelay > 0) { Accessory.DelayMs(strDelay); } if (SendComing > 1) { m = tmpBuffer.Length; } } if (checkBox_hexTerminal.Checked) { outStr += tmpBuffer; } else { outStr += Accessory.ConvertHexToString(tmpBuffer); } collectBuffer(outStr, Port1DataOut); } catch (Exception ex) { MessageBox.Show("Error sending to port " + serialPort1.PortName + ": " + ex.Message); } } else //raw stream { String tmpBuffer = ""; try { length = new FileInfo(textBox_fileName.Text).Length; tmpBuffer = Accessory.CheckHexString(File.ReadAllText(textBox_fileName.Text)); } catch (Exception ex) { MessageBox.Show("\r\nError reading file " + textBox_fileName.Text + ": " + ex.Message); } try { for (int m = 0; m < tmpBuffer.Length; m += 3) { serialPort1.Write(Accessory.ConvertHexToByteArray(tmpBuffer.Substring(m, 3)), 0, 1); progressBar1.Value = (n * tmpBuffer.Length + m) * 100 / (repeat * tmpBuffer.Length); } } catch (Exception ex) { MessageBox.Show("Error sending to port " + serialPort1.PortName + ": " + ex.Message); } if (checkBox_hexTerminal.Checked) { outStr += tmpBuffer; } else { outStr += Accessory.ConvertHexToString(tmpBuffer); } collectBuffer(outStr, Port1DataOut); } } if (repeat > 1) { Accessory.DelayMs(delay); } if (SendComing > 1) { n = repeat; } } button_Send.Enabled = true; button_closeport.Enabled = true; button_openFile.Enabled = true; button_sendFile.Text = "Send file"; textBox_fileName.Enabled = true; textBox_sendNum.Enabled = true; textBox_delay.Enabled = true; textBox_strDelay.Enabled = true; } SendComing = 0; } }
public static bool FindParameter(int _commandNum) { ClearParameters(); if (_commandNum < 0 || _commandNum >= commandName.Count) { return(false); } //collect parameters var _stopSearch = commandDbLineNum[_commandNum] + 1; while (_stopSearch < _commandDataBase.Rows.Count && _commandDataBase.Rows[_stopSearch][CSVColumns.CommandName].ToString() == "") { _stopSearch++; } for (var i = commandDbLineNum[_commandNum] + 1; i < _stopSearch; i++) { if (_commandDataBase.Rows[i][CSVColumns.ParameterName].ToString() != "") { paramDbLineNum.Add(i); paramName.Add(_commandDataBase.Rows[i][CSVColumns.ParameterName].ToString()); paramDesc.Add(_commandDataBase.Rows[i][CSVColumns.Description].ToString()); paramType.Add(_commandDataBase.Rows[i][CSVColumns.ParameterType].ToString()); } } errors = false; //Error in parameter found //process each parameter for (var parameter = 0; parameter < paramDbLineNum.Count; parameter++) { paramPosition.Add(commandPosition[_commandNum] + ResultLength(_commandNum)); bitName.Add(new List <string>()); bitValue.Add(new List <string>()); bitDescription.Add(new List <string>()); //collect predefined RAW values var predefinedParamsRaw = new List <string>(); var j = paramDbLineNum[parameter] + 1; while (j < _commandDataBase.Rows.Count && _commandDataBase.Rows[j][CSVColumns.ParameterValue].ToString() != "") { predefinedParamsRaw.Add(_commandDataBase.Rows[j][CSVColumns.ParameterValue].ToString()); j++; } //Calculate predefined params var predefinedParamsVal = new List <int>(); foreach (var expresion in predefinedParamsRaw) { var val = 0; //select formula basing on parameter value "?k=1:n+n1 ?k-2:n*n1" if (expresion.StartsWith("?")) { var tmpstr = expresion.Trim().Replace("\r", "").Replace("\n", "").Split('?'); foreach (var str in tmpstr) { if (str != "") { var equation = str.Substring(0, str.IndexOf(':')); //calculate equation if needed for (var i2 = 0; i2 < paramName.Count - 1; i2++) //insert all parameters before current into equation { equation = equation.Replace(paramName[i2], paramValue[i2]); equation = equation.Replace('=', '-'); } if (Accessory.Evaluate(equation) == 0) { var equation2 = str.Substring(str.IndexOf(':') + 1).Trim(); for (var i3 = 0; i3 < paramName.Count - 1; i3++) { equation2 = equation2.Replace(paramName[i3], paramValue[i3]); } try { val = (int)Accessory.Evaluate(equation2); } catch { } } } } } else if (expresion.StartsWith("@")) { var equation = expresion.Substring(1); //insert all parameters before current into equation for (var i2 = 0; i2 < paramName.Count - 1; i2++) { equation = equation.Replace(paramName[i2], paramValue[i2]); } val = (int)Accessory.Evaluate(equation); // = str.Substring(str.IndexOf(':') + 1); } else { if (!int.TryParse(expresion.Trim(), out val)) { val = 0; } } predefinedParamsVal.Add(val); } //get parameter from text var tmpStrLength = 0; var predefinedFound = false; //Matching predefined parameter found and it's number is in "predefinedParameterMatched" var errMessage = ""; byte l = 0, h = 0; var predefinedParameterMatched = 0; var _prmType = _commandDataBase.Rows[paramDbLineNum[parameter]][CSVColumns.ParameterType].ToString() .ToLower(); if (_prmType == DataTypes.Byte) { if (paramPosition[parameter] + 1 <= sourceData.Count) { paramRAWValue.Add(sourceData.GetRange(paramPosition[parameter], 1)); l = paramRAWValue[parameter].ToArray()[0]; } else { errors = true; errMessage = "!!!ERR: Out of data!!!"; paramRAWValue.Add(sourceData.GetRange(paramPosition[parameter], sourceData.Count - paramPosition[parameter])); } paramValue.Add(l.ToString()); } else if (_prmType == DataTypes.Bitfield) { if (paramPosition[parameter] + 1 <= sourceData.Count) { paramRAWValue.Add(sourceData.GetRange(paramPosition[parameter], 1)); l = paramRAWValue[parameter].ToArray()[0]; for (byte i2 = 0; i2 < 8; i2++) { bitName[parameter].Add("bit" + i2); bitValue[parameter].Add(Accessory.GetBit(l, i2).ToString()); bitDescription[parameter] .Add(_commandDataBase.Rows[paramDbLineNum[parameter] + i2 + 1][CSVColumns.Description] .ToString()); } } else { errors = true; errMessage = "!!!ERR: Out of data!!!"; paramRAWValue.Add(sourceData.GetRange(paramPosition[parameter], sourceData.Count - paramPosition[parameter])); } paramValue.Add(l.ToString()); } else if (_prmType == DataTypes.Word) { if (paramPosition[parameter] + 2 <= sourceData.Count) { paramRAWValue.Add(sourceData.GetRange(paramPosition[parameter], 2)); l = paramRAWValue[parameter].GetRange(0, 1)[0]; h = paramRAWValue[parameter].GetRange(1, 1)[0]; } else { errors = true; errMessage = "!!!ERR: Out of data!!!"; paramRAWValue.Add(sourceData.GetRange(paramPosition[parameter], sourceData.Count - paramPosition[parameter])); } paramValue.Add((h * 256 + l).ToString()); } else if (_prmType == DataTypes.Rword) { if (paramPosition[parameter] + 2 <= sourceData.Count) { paramRAWValue.Add(sourceData.GetRange(paramPosition[parameter], 2)); h = paramRAWValue[parameter].GetRange(0, 1)[0]; l = paramRAWValue[parameter].GetRange(1, 1)[0]; } else { errors = true; errMessage = "!!!ERR: Out of data!!!"; paramRAWValue.Add(sourceData.GetRange(paramPosition[parameter], sourceData.Count - paramPosition[parameter])); } paramValue.Add((h * 256 + l).ToString()); } else if (_prmType == DataTypes.Textstring || _prmType == DataTypes.Decstring || _prmType == DataTypes.Hexstring || _prmType == DataTypes.Binarystring) { if (predefinedParamsVal.Count > 0) { //look for the end of the string (predefined byte) while (predefinedFound == false && paramPosition[parameter] + tmpStrLength <= sourceData.Count) { //check for each predefined value for (var i1 = 0; i1 < predefinedParamsVal.Count; i1++) { if (paramPosition[parameter] + tmpStrLength + 1 <= sourceData.Count) { if (sourceData[paramPosition[parameter] + tmpStrLength] == predefinedParamsVal[i1]) { predefinedFound = true; predefinedParameterMatched = i1; paramRAWValue.Add(sourceData.GetRange(paramPosition[parameter], tmpStrLength)); } } else { errors = true; errMessage = "!!!ERR: Out of data!!!"; } } tmpStrLength++; } if (tmpStrLength < 1) { errors = true; errMessage = "!!!ERR: Out of data!!!"; } if (errors) { paramRAWValue.Add(sourceData.GetRange(paramPosition[parameter], sourceData.Count - paramPosition[parameter])); } if (paramRAWValue[parameter].Count != 0) { if ((_prmType == DataTypes.Textstring || _prmType == DataTypes.Decstring || _prmType == DataTypes.Hexstring) && Accessory.PrintableByteArray(paramRAWValue[parameter].ToArray())) { paramValue.Add(Encoding.GetEncoding(Settings.Default.CodePage) .GetString(paramRAWValue[parameter].ToArray())); } else { paramValue.Add("[" + Accessory.ConvertByteArrayToHex(paramRAWValue[parameter].ToArray()) + "]"); } } else { paramValue.Add(""); } } else { errors = true; errMessage = "!!!ERR: There must be predefined values!!!"; paramRAWValue.Add(null); paramValue.Add(""); } } else if (_prmType == DataTypes.Textarray || _prmType == DataTypes.Decarray || _prmType == DataTypes.Hexarray || _prmType == DataTypes.Binaryarray) { if (predefinedParamsVal.Count == 1) { predefinedFound = true; predefinedParameterMatched = 0; if (paramPosition[parameter] + predefinedParamsVal[0] <= sourceData.Count) { paramRAWValue.Add(sourceData.GetRange(paramPosition[parameter], (byte)predefinedParamsVal[0])); } else { errors = true; errMessage = "!!!ERR: Out of data bound!!!"; paramRAWValue.Add(sourceData.GetRange(paramPosition[parameter], sourceData.Count - paramPosition[parameter])); } if (paramRAWValue[parameter].Count != 0) { if ((_prmType == DataTypes.Textarray || _prmType == DataTypes.Decarray || _prmType == DataTypes.Hexarray) && Accessory.PrintableByteArray(paramRAWValue[parameter].ToArray())) { paramValue.Add(Encoding.GetEncoding(Settings.Default.CodePage) .GetString(paramRAWValue[parameter].ToArray())); } else { paramValue.Add("[" + Accessory.ConvertByteArrayToHex(paramRAWValue[parameter].ToArray()) + "]"); } } else { paramValue.Add(""); } } else { errors = true; errMessage = "!!!ERR: There must be only one predefined value!!!"; paramRAWValue.Add(null); paramValue.Add(""); } } else { predefinedFound = true; errors = true; errMessage = "!!!ERR: Incorrect parameter type!!!"; paramRAWValue.Add(new List <byte>()); paramValue.Add(""); } if (errors) { paramDesc[parameter] += errMessage + "\r\n"; } //compare parameter value with predefined values to get proper description if (predefinedFound == false && !errors) { for (var i1 = 0; i1 < predefinedParamsVal.Count; i1++) { if (paramValue[parameter] == predefinedParamsVal[i1].ToString()) { predefinedFound = true; predefinedParameterMatched = i1; i1 = predefinedParamsVal.Count; } } if (predefinedParamsVal.Count > 0 && predefinedFound == false) { errors = true; //if no parameters match predefined } } //get description for predefined parameter //if description is within current command parameters group if (paramDbLineNum[parameter] + predefinedParameterMatched + 1 <= commandDbLineNum[_commandNum] + commandDbHeight[_commandNum] && predefinedFound) { paramDesc[parameter] += _commandDataBase.Rows[paramDbLineNum[parameter] + predefinedParameterMatched + 1][ CSVColumns.Description].ToString(); } } ResultLength(_commandNum); return(!errors); }
public static bool FindCommand(int _pos, string _printerModel) { //reset all result values ClearCommand(); //find command var _tempCommandList = new Dictionary <int, string>(); for (var i = 0; i < _commandList.Count; i++) { if (_pos + _commandList.ElementAt(i).Value.Length / 3 <= sourceData.Count ) //check if it doesn't go over the last symbol { if (Accessory.ConvertByteArrayToHex(sourceData .GetRange(_pos, _commandList.ElementAt(i).Value.Length / 3).ToArray()) == _commandList.ElementAt(i).Value) //find command { if (_printerModel == "") { _tempCommandList.Add(_commandList.ElementAt(i).Key, _commandList.ElementAt(i).Value); // check if printer model is correct } else { var tmpstr = _commandDataBase.Rows[_commandList.ElementAt(i).Key][CSVColumns.PrinterModel] .ToString().Split(','); for (var i1 = 0; i1 < tmpstr.Count(); i1++) { if (tmpstr[i1].Trim() == _printerModel) { _tempCommandList.Add(_commandList.ElementAt(i).Key, _commandList.ElementAt(i).Value); } } } } } } //else return false; if (_tempCommandList.Count <= 0) { return(false); } for (var i = 0; i < _tempCommandList.Count; i++) { commandName.Add(_tempCommandList.ElementAt(i).Value); commandDbLineNum.Add(_tempCommandList.ElementAt(i).Key); commandDesc.Add(_commandDataBase.Rows[commandDbLineNum[i]][CSVColumns.Description].ToString()); commandPosition.Add(_pos); commandPrinterModel.Add(_commandDataBase.Rows[commandDbLineNum[i]][CSVColumns.PrinterModel].ToString()); //check command height - how many rows are occupated var i1 = 0; while (commandDbLineNum[i] + i1 + 1 < _commandDataBase.Rows.Count && _commandDataBase.Rows[commandDbLineNum[i] + i1 + 1][CSVColumns.CommandName].ToString() == "") { i1++; } commandDbHeight.Add(i1); } return(true); }
private async void Button_sendFile_ClickAsync(object sender, EventArgs e) { if (SendComing > 0) { SendComing++; } else if (SendComing == 0) { timer1.Enabled = false; if (textBox_fileName.Text != "" && textBox_sendNum.Text != "" && ushort.TryParse(textBox_sendNum.Text, out var repeat) && ushort.TryParse(textBox_delay.Text, out var delay) && ushort.TryParse(textBox_strDelay.Text, out var strDelay)) { SendComing = 1; button_Send.Enabled = false; button_closeport.Enabled = false; button_openFile.Enabled = false; button_sendFile.Text = "Stop"; textBox_fileName.Enabled = false; textBox_sendNum.Enabled = false; textBox_delay.Enabled = false; textBox_strDelay.Enabled = false; for (var n = 0; n < repeat; n++) { var outStr = ""; var outErr = ""; long length = 0; if (repeat > 1) { _logger.AddText(" Send cycle " + (n + 1) + "/" + repeat + ">> ", (byte)DataDirection.Info, DateTime.Now, TextLogger.TextLogger.TextFormat.PlainText); } try { length = new FileInfo(textBox_fileName.Text).Length; } catch (Exception ex) { MessageBox.Show("\r\nError opening file " + textBox_fileName.Text + ": " + ex.Message); } if (!checkBox_hexFileOpen.Checked) //binary data read { if (radioButton_byByte.Checked) //byte-by-byte { var tmpBuffer = new byte[length]; try { tmpBuffer = File.ReadAllBytes(textBox_fileName.Text); } catch (Exception ex) { MessageBox.Show("\r\nError reading file " + textBox_fileName.Text + ": " + ex.Message); } for (var m = 0; m < tmpBuffer.Length; m++) { byte[] outByte = { tmpBuffer[m] }; if (WriteTCP(outByte)) { progressBar1.Value = (n * tmpBuffer.Length + m) * 100 / (repeat * tmpBuffer.Length); if (strDelay > 0) { await TaskEx.Delay(strDelay); } var inStream = ReadTCP(); if (inStream.Length > 0) { if (checkBox_saveInput.Checked) { if (checkBox_hexTerminal.Checked) { File.AppendAllText(textBox_saveTo.Text, Accessory.ConvertByteArrayToHex(inStream, inStream.Length), Encoding.GetEncoding(Settings.Default.CodePage)); } else { File.AppendAllText(textBox_saveTo.Text, Encoding.GetEncoding(Settings.Default.CodePage) .GetString(inStream), Encoding.GetEncoding(Settings.Default.CodePage)); } } _logger.AddText( Encoding.GetEncoding(Settings.Default.CodePage).GetString(inStream), (byte)DataDirection.Received, DateTime.Now); } } else { _logger.AddText("Write Failure", (byte)DataDirection.Error, DateTime.Now, TextLogger.TextLogger.TextFormat.PlainText); } outStr = Encoding.GetEncoding(Settings.Default.CodePage).GetString(tmpBuffer); _logger.AddText(outStr, (byte)DataDirection.Sent, DateTime.Now); if (SendComing > 1) { m = tmpBuffer.Length; } } } else //stream { var tmpBuffer = new byte[length]; try { tmpBuffer = File.ReadAllBytes(textBox_fileName.Text); } catch (Exception ex) { MessageBox.Show("\r\nError reading file " + textBox_fileName.Text + ": " + ex.Message); } if (WriteTCP(tmpBuffer)) { var inStream = ReadTCP(); if (inStream.Length > 0) { if (checkBox_saveInput.Checked) { if (checkBox_hexTerminal.Checked) { File.AppendAllText(textBox_saveTo.Text, Accessory.ConvertByteArrayToHex(inStream, inStream.Length), Encoding.GetEncoding(Settings.Default.CodePage)); } else { File.AppendAllText(textBox_saveTo.Text, Encoding.GetEncoding(Settings.Default.CodePage).GetString(inStream), Encoding.GetEncoding(Settings.Default.CodePage)); } } _logger.AddText( Encoding.GetEncoding(Settings.Default.CodePage).GetString(inStream), (byte)DataDirection.Received, DateTime.Now); } } else { outErr = "Write Failure"; } outStr = Encoding.GetEncoding(Settings.Default.CodePage).GetString(tmpBuffer); _logger.AddText(outStr, (byte)DataDirection.Sent, DateTime.Now); _logger.AddText(outErr, (byte)DataDirection.Error, DateTime.Now, TextLogger.TextLogger.TextFormat.PlainText); progressBar1.Value = n * 100 / (repeat * tmpBuffer.Length); } } else //hex text read { if (radioButton_byString.Checked) //String-by-string { string[] tmpBuffer = { }; try { length = new FileInfo(textBox_fileName.Text).Length; tmpBuffer = File.ReadAllText(textBox_fileName.Text).Replace("\n", "").Split('\r'); } catch (Exception ex) { MessageBox.Show("\r\nError reading file " + textBox_fileName.Text + ": " + ex.Message); } for (var m = 0; m < tmpBuffer.Length; m++) { tmpBuffer[m] = Accessory.CheckHexString(tmpBuffer[m]); if (WriteTCP(Accessory.ConvertHexToByteArray(tmpBuffer[m]))) { if (checkBox_hexTerminal.Checked) { outStr = tmpBuffer[m]; } else { outStr = Accessory.ConvertHexToString(tmpBuffer[m]); } if (strDelay > 0) { await TaskEx.Delay(strDelay); } var inStream = ReadTCP(); if (inStream.Length > 0) { if (checkBox_saveInput.Checked) { if (checkBox_hexTerminal.Checked) { File.AppendAllText(textBox_saveTo.Text, Accessory.ConvertByteArrayToHex(inStream, inStream.Length), Encoding.GetEncoding(Settings.Default.CodePage)); } else { File.AppendAllText(textBox_saveTo.Text, Encoding.GetEncoding(Settings.Default.CodePage) .GetString(inStream), Encoding.GetEncoding(Settings.Default.CodePage)); } } _logger.AddText( Encoding.GetEncoding(Settings.Default.CodePage).GetString(inStream), (byte)DataDirection.Received, DateTime.Now); } } else //?????????????? { outErr = "Write failure"; } if (SendComing > 1) { m = tmpBuffer.Length; } _logger.AddText(outStr, (byte)DataDirection.Sent, DateTime.Now); _logger.AddText(outErr, (byte)DataDirection.Error, DateTime.Now, TextLogger.TextLogger.TextFormat.PlainText); progressBar1.Value = (n * tmpBuffer.Length + m) * 100 / (repeat * tmpBuffer.Length); } } else if (radioButton_byByte.Checked) //byte-by-byte { var tmpBuffer = ""; try { length = new FileInfo(textBox_fileName.Text).Length; tmpBuffer = File.ReadAllText(textBox_fileName.Text); } catch (Exception ex) { MessageBox.Show("\r\nError reading file " + textBox_fileName.Text + ": " + ex.Message); } tmpBuffer = Accessory.CheckHexString(tmpBuffer); for (var m = 0; m < tmpBuffer.Length; m += 3) { if (WriteTCP(Accessory.ConvertHexToByteArray(tmpBuffer.Substring(m, 3)))) { if (checkBox_hexTerminal.Checked) { outStr = tmpBuffer.Substring(m, 3); } else { outStr = Accessory.ConvertHexToString(tmpBuffer.Substring(m, 3)); } if (strDelay > 0) { await TaskEx.Delay(strDelay); } var inStream = ReadTCP(); if (inStream.Length > 0) { if (checkBox_saveInput.Checked) { if (checkBox_hexTerminal.Checked) { File.AppendAllText(textBox_saveTo.Text, Accessory.ConvertByteArrayToHex(inStream, inStream.Length), Encoding.GetEncoding(Settings.Default.CodePage)); } else { File.AppendAllText(textBox_saveTo.Text, Encoding.GetEncoding(Settings.Default.CodePage) .GetString(inStream), Encoding.GetEncoding(Settings.Default.CodePage)); } } _logger.AddText( Encoding.GetEncoding(Settings.Default.CodePage).GetString(inStream), (byte)DataDirection.Received, DateTime.Now); } } else { outErr += "Write Failure\r\n"; } if (SendComing > 1) { m = tmpBuffer.Length; } _logger.AddText(outStr, (byte)DataDirection.Sent, DateTime.Now); _logger.AddText(outErr, (byte)DataDirection.Error, DateTime.Now, TextLogger.TextLogger.TextFormat.PlainText); progressBar1.Value = (n * tmpBuffer.Length + m) * 100 / (repeat * tmpBuffer.Length); } } else //stream { var tmpBuffer = ""; try { length = new FileInfo(textBox_fileName.Text).Length; tmpBuffer = Accessory.CheckHexString(File.ReadAllText(textBox_fileName.Text)); } catch (Exception ex) { MessageBox.Show("\r\nError reading file " + textBox_fileName.Text + ": " + ex.Message); } if (WriteTCP(Accessory.ConvertHexToByteArray(tmpBuffer))) { var inStream = ReadTCP(); if (inStream.Length > 0) { if (checkBox_saveInput.Checked) { if (checkBox_hexTerminal.Checked) { File.AppendAllText(textBox_saveTo.Text, Accessory.ConvertByteArrayToHex(inStream, inStream.Length), Encoding.GetEncoding(Settings.Default.CodePage)); } else { File.AppendAllText(textBox_saveTo.Text, Encoding.GetEncoding(Settings.Default.CodePage).GetString(inStream), Encoding.GetEncoding(Settings.Default.CodePage)); } } _logger.AddText( Encoding.GetEncoding(Settings.Default.CodePage).GetString(inStream), (byte)DataDirection.Received, DateTime.Now); } } else { _logger.AddText("Write Failure\r\n", (byte)DataDirection.Error, DateTime.Now, TextLogger.TextLogger.TextFormat.PlainText); } outStr = Accessory.ConvertHexToString(tmpBuffer); _logger.AddText(outStr, (byte)DataDirection.Sent, DateTime.Now); progressBar1.Value = n * 100 / (repeat * tmpBuffer.Length); } } if (repeat > 1) { await TaskEx.Delay(delay); } if (SendComing > 1) { n = repeat; } } button_Send.Enabled = true; button_closeport.Enabled = true; button_openFile.Enabled = true; button_sendFile.Text = "Send file"; textBox_fileName.Enabled = true; textBox_sendNum.Enabled = true; textBox_delay.Enabled = true; textBox_strDelay.Enabled = true; } SendComing = 0; timer1.Enabled = true; } }
private async void Button_sendFile_ClickAsync(object sender, EventArgs e) { if (SendComing > 0) { SendComing++; } else if (SendComing == 0) { timer1.Enabled = false; if (textBox_fileName.Text != "" && textBox_sendNum.Text != "" && ushort.TryParse(textBox_sendNum.Text, out var repeat) && ushort.TryParse(textBox_delay.Text, out var delay) && ushort.TryParse(textBox_strDelay.Text, out var strDelay)) { timer1.Enabled = false; SendComing = 1; button_Send.Enabled = false; button_closeport.Enabled = false; button_openFile.Enabled = false; button_sendFile.Text = "Stop"; textBox_fileName.Enabled = false; textBox_sendNum.Enabled = false; textBox_delay.Enabled = false; textBox_strDelay.Enabled = false; for (var n = 0; n < repeat; n++) { var outStr = ""; var outErr = ""; long length = 0; if (repeat > 1) { _logger.AddText(" Send cycle " + (n + 1) + "/" + repeat + ">> ", (byte)DataDirection.Info, DateTime.Now, TextLogger.TextLogger.TextFormat.PlainText); } try { length = new FileInfo(textBox_fileName.Text).Length; } catch (Exception ex) { MessageBox.Show("\r\nError opening file " + textBox_fileName.Text + ": " + ex.Message); } //binary file read if (!checkBox_hexFileOpen.Checked) { //byte-by-byte if (radioButton_byByte.Checked) { var tmpBuffer = new byte[length]; try { tmpBuffer = File.ReadAllBytes(textBox_fileName.Text); } catch (Exception ex) { MessageBox.Show("\r\nError reading file " + textBox_fileName.Text + ": " + ex.Message); } for (var l = 0; l < tmpBuffer.Length; l++) { byte[] outByte = { tmpBuffer[l] }; outStr = Encoding.GetEncoding(Settings.Default.CodePage).GetString(tmpBuffer); _logger.AddText(outStr, (byte)DataDirection.Sent, DateTime.Now); if (Selected_Printer.GenericWrite(outByte)) { progressBar1.Value = (n * tmpBuffer.Length + l) * 100 / (repeat * tmpBuffer.Length); if (strDelay > 0) { await TaskEx.Delay(strDelay); } ReadUSB(); } else { _logger.AddText("Byte " + l + ": Write Failure", (byte)DataDirection.Error, DateTime.Now, TextLogger.TextLogger.TextFormat.PlainText); } if (SendComing > 1) { l = tmpBuffer.Length; } } } //stream else { var tmpBuffer = new byte[length]; try { tmpBuffer = File.ReadAllBytes(textBox_fileName.Text); } catch (Exception ex) { MessageBox.Show("\r\nError reading file " + textBox_fileName.Text + ": " + ex.Message); } var l = 0; while (l < tmpBuffer.Length) { var bufsize = tmpBuffer.Length - l; if (bufsize > CePrinter.USB_PACK) { bufsize = CePrinter.USB_PACK; } var buf = new byte[bufsize]; for (var i = 0; i < bufsize; i++) { buf[i] = tmpBuffer[l]; l++; } var r = 0; if (Selected_Printer != null) { while (r < 10 && !Selected_Printer.GenericWrite(buf)) { _logger.AddText("USB write retry " + r, (byte)DataDirection.Error, DateTime.Now, TextLogger.TextLogger.TextFormat.PlainText); await TaskEx.Delay(100); Selected_Printer.CloseDevice(); Selected_Printer.OpenDevice(); r++; } } if (r >= 10) { outErr = "Block write failure"; } ReadUSB(); if (checkBox_hexTerminal.Checked) { outStr = Accessory.ConvertByteArrayToHex(buf, buf.Length); } else { outStr = Encoding.GetEncoding(Settings.Default.CodePage).GetString(buf); } if (outErr != "") { _logger.AddText(outErr + ": start", (byte)DataDirection.Error, DateTime.Now, TextLogger.TextLogger.TextFormat.PlainText); } _logger.AddText(outStr, (byte)DataDirection.Sent, DateTime.Now); if (outErr != "") { _logger.AddText(outErr + ": end", (byte)DataDirection.Error, DateTime.Now, TextLogger.TextLogger.TextFormat.PlainText); } progressBar1.Value = (n * tmpBuffer.Length + l) * 100 / (repeat * tmpBuffer.Length); if (SendComing > 1) { l = tmpBuffer.Length; } } } } //hex file read else { //String-by-string if (radioButton_byString.Checked) { string[] tmpBuffer = { }; try { tmpBuffer = File.ReadAllText(textBox_fileName.Text).Replace('\n', '\r') .Replace("\r\r", "\r").Split('\r'); } catch (Exception ex) { MessageBox.Show("\r\nError reading file " + textBox_fileName.Text + ": " + ex.Message); } for (var l = 0; l < tmpBuffer.Length; l++) { if (tmpBuffer[l] != "") { tmpBuffer[l] = Accessory.CheckHexString(tmpBuffer[l]); _logger.AddText(outStr, (byte)DataDirection.Sent, DateTime.Now); if (Selected_Printer.GenericWrite(Accessory.ConvertHexToByteArray(tmpBuffer[l])) ) { if (checkBox_hexTerminal.Checked) { outStr = tmpBuffer[l]; } else { outStr = Accessory.ConvertHexToString(tmpBuffer[l]); } if (strDelay > 0) { await TaskEx.Delay(strDelay); } ReadUSB(); } else //?????????????? { outErr = "String" + l + ": Write failure"; } if (SendComing > 1) { l = tmpBuffer.Length; } if (outErr != "") { _logger.AddText(outErr, (byte)DataDirection.Error, DateTime.Now, TextLogger.TextLogger.TextFormat.PlainText); } progressBar1.Value = (n * tmpBuffer.Length + l) * 100 / (repeat * tmpBuffer.Length); } } } //byte-by-byte if (radioButton_byByte.Checked) { var tmpStrBuffer = ""; try { tmpStrBuffer = Accessory.CheckHexString(File.ReadAllText(textBox_fileName.Text)); } catch (Exception ex) { MessageBox.Show("Error reading file " + textBox_fileName.Text + ": " + ex.Message); } var tmpBuffer = new byte[tmpStrBuffer.Length / 3]; tmpBuffer = Accessory.ConvertHexToByteArray(tmpStrBuffer); for (var l = 0; l < tmpBuffer.Length; l++) { byte[] outByte = { tmpBuffer[l] }; outStr = Encoding.GetEncoding(Settings.Default.CodePage).GetString(tmpBuffer); _logger.AddText(outStr, (byte)DataDirection.Sent, DateTime.Now); if (Selected_Printer.GenericWrite(outByte)) { progressBar1.Value = (n * tmpBuffer.Length + l) * 100 / (repeat * tmpBuffer.Length); if (strDelay > 0) { await TaskEx.Delay(strDelay); } ReadUSB(); } else { _logger.AddText("Byte " + l + ": Write Failure", (byte)DataDirection.Error, DateTime.Now, TextLogger.TextLogger.TextFormat.PlainText); } if (SendComing > 1) { l = tmpBuffer.Length; } } } //stream else { var tmpStrBuffer = ""; try { tmpStrBuffer = Accessory.CheckHexString(File.ReadAllText(textBox_fileName.Text)); } catch (Exception ex) { MessageBox.Show("Error reading file " + textBox_fileName.Text + ": " + ex.Message); } var tmpBuffer = new byte[tmpStrBuffer.Length / 3]; tmpBuffer = Accessory.ConvertHexToByteArray(tmpStrBuffer); var l = 0; while (l < tmpBuffer.Length) { var bufsize = tmpBuffer.Length - l; if (bufsize > CePrinter.USB_PACK) { bufsize = CePrinter.USB_PACK; } var buf = new byte[bufsize]; for (var i = 0; i < bufsize; i++) { buf[i] = tmpBuffer[l]; l++; } var r = 0; if (Selected_Printer != null) { while (r < 10 && !Selected_Printer.GenericWrite(buf)) { _logger.AddText("USB write retry " + r, (byte)DataDirection.Error, DateTime.Now, TextLogger.TextLogger.TextFormat.PlainText); await TaskEx.Delay(100); Selected_Printer.CloseDevice(); Selected_Printer.OpenDevice(); r++; } } if (r >= 10) { outErr = "Block write failure"; } ReadUSB(); outStr = Encoding.GetEncoding(Settings.Default.CodePage).GetString(buf); if (outErr != "") { _logger.AddText(outErr + " start", (byte)DataDirection.Error, DateTime.Now, TextLogger.TextLogger.TextFormat.PlainText); } _logger.AddText(outStr, (byte)DataDirection.Sent, DateTime.Now); if (outErr != "") { _logger.AddText(outErr + " end", (byte)DataDirection.Error, DateTime.Now, TextLogger.TextLogger.TextFormat.PlainText); } progressBar1.Value = (n * tmpBuffer.Length + l) * 100 / (repeat * tmpBuffer.Length); if (SendComing > 1) { l = tmpBuffer.Length; } } } } if (repeat > 1) { await TaskEx.Delay(delay); } if (SendComing > 1) { n = repeat; } } button_Send.Enabled = true; button_closeport.Enabled = true; button_openFile.Enabled = true; button_sendFile.Text = "Send file"; textBox_fileName.Enabled = true; textBox_sendNum.Enabled = true; textBox_delay.Enabled = true; textBox_strDelay.Enabled = true; } SendComing = 0; timer1.Enabled = true; } }
private void Button_find_Click(object sender, EventArgs e) { textBox_command.Text = ""; textBox_commandDesc.Clear(); ResultDatabase.Clear(); if (textBox_code.SelectionStart != textBox_code.Text.Length) //check if cursor position in not last { if (textBox_code.Text.Substring(textBox_code.SelectionStart, 1) == " ") { textBox_code.SelectionStart++; } } if (textBox_code.SelectionStart != 0) //check if cursor position in not first { if (textBox_code.Text.Substring(textBox_code.SelectionStart - 1, 1) != " " && textBox_code.Text.Substring(textBox_code.SelectionStart, 1) != " ") { textBox_code.SelectionStart--; } } /*if (sender != button_find) * { * textBox_code.SelectionStart = textBox_code.SelectionStart + textBox_code.SelectionLength; * }*/ label_currentPosition.Text = textBox_code.SelectionStart + "/" + textBox_code.TextLength; if (ParseEscPos.FindCommand(textBox_code.SelectionStart / 3)) { ParseEscPos.FindCommandParameter(); if (sender != button_auto) //update interface only if it's no auto-parsing mode { dataGridView_commands.CurrentCell = dataGridView_commands.Rows[ParseEscPos.commandDbLineNum] .Cells[ParseEscPos.CSVColumns.CommandName]; if (ParseEscPos.itIsReply) { textBox_command.Text = "[REPLY] " + ParseEscPos.commandName; } else { textBox_command.Text = "[COMMAND] " + ParseEscPos.commandName; } if (ParseEscPos.crcFailed) { textBox_commandDesc.Text += "!!!CRC FAILED!!! "; } if (ParseEscPos.lengthIncorrect) { textBox_commandDesc.Text += "!!!FRAME LENGTH INCORRECT!!! "; } textBox_commandDesc.Text = ParseEscPos.commandDesc; for (var i = 0; i < ParseEscPos.commandParamSize.Count; i++) { var row = ResultDatabase.NewRow(); row[ResultColumns.Value] = ParseEscPos.commandParamValue[i]; row[ResultColumns.Type] = ParseEscPos.commandParamType[i]; row[ResultColumns.Raw] = Accessory.ConvertByteArrayToHex(ParseEscPos.commandParamRAWValue[i].ToArray()); row[ResultColumns.Description] = ParseEscPos.commandParamDesc[i]; if (ParseEscPos.commandParamType[i].ToLower() == ParseEscPos.DataTypes.Error) { row[ResultColumns.Description] += ": " + GetErrorDesc(int.Parse(ParseEscPos.commandParamValue[i])); } ResultDatabase.Rows.Add(row); if (ParseEscPos.commandParamType[i].ToLower() == ParseEscPos.DataTypes.Bitfield ) //add bitfield display { var b = byte.Parse(ParseEscPos.commandParamValue[i]); for (var i1 = 0; i1 < 8; i1++) { row = ResultDatabase.NewRow(); row[ResultColumns.Value] = (Accessory.GetBit(b, (byte)i1) ? (byte)1 : (byte)0).ToString(); row[ResultColumns.Type] = "bit" + i1; row[ResultColumns.Description] = dataGridView_commands .Rows[ParseEscPos.commandParamDbLineNum[i] + i1 + 1] .Cells[ParseEscPos.CSVColumns.CommandDescription].Value; ResultDatabase.Rows.Add(row); } } } } if (ParseEscPos.itIsReply && textBox_code.Text.Substring(textBox_code.SelectionStart + (ParseEscPos.commandBlockLength + 1) * 3, 3) == Accessory.ConvertByteToHex(ParseEscPos.ackSign)) { textBox_code.Select(textBox_code.SelectionStart, (ParseEscPos.commandBlockLength + 2) * 3); } else { textBox_code.Select(textBox_code.SelectionStart, (ParseEscPos.commandBlockLength + 1) * 3); } } else //no command found. consider it's a string { var i = 3; while (!ParseEscPos.FindCommand((textBox_code.SelectionStart + i) / 3) && textBox_code.SelectionStart + i < textBox_code.TextLength) //looking for a non-parseable part end { i += 3; } ParseEscPos.commandName = ""; textBox_code.Select(textBox_code.SelectionStart, i); if (sender != button_auto) { //textBox_command.Text += ""; //textBox_commandDesc.Text = "\"" + (String)textBox_code.SelectedText + "\""; if (textBox_code.SelectedText == Accessory.ConvertByteToHex(ParseEscPos.ackSign)) { textBox_command.Text = "ACK"; } else if (textBox_code.SelectedText == Accessory.ConvertByteToHex(ParseEscPos.nakSign)) { textBox_command.Text = "NAK"; } else if (textBox_code.SelectedText == Accessory.ConvertByteToHex(ParseEscPos.enqSign) + Accessory.ConvertByteToHex(ParseEscPos.ackSign)) { textBox_command.Text = "BUSY"; } else { textBox_command.Text = "\"" + textBox_code.SelectedText + "\""; } dataGridView_commands.CurrentCell = dataGridView_commands.Rows[0].Cells[0]; if (Accessory.PrintableHex(textBox_code.SelectedText)) { textBox_commandDesc.Text = "\"" + Encoding.GetEncoding(Settings.Default.CodePage) .GetString(Accessory.ConvertHexToByteArray(textBox_code.SelectedText)) + "\""; } } } textBox_code.ScrollToCaret(); }