/* * HostToFirmware * * Returns: true on success, false on failure * Arguments: * packet: Packet to be sent * simCtl: PrinterControl variable that gets passed around to everything * (optional) maxRetries: Maximum number of retries before faliure is returned * (internal) currentRetry: Used internally to track the current retry count */ // MAKE SURE TO CHANGE MAXRETI static bool HostToFirmware(byte[] packet, PrinterControl simCtl, int maxRetries = 10, int currentRetry = 0) // MAKE COPIES OF ALL THE THINGS { if (currentRetry >= maxRetries) { return(false); } //Console.Write("+++++++++++++++NEXT COMMAND++++++++++++++++ \n"); // Host-to-Firmware Communication Procedure const int header_size = 4; // 4 is header size int response_size = 1; // So it reads one byte at a time int ACK_NAK_size = 1; // size of both ACK and NAK bytes byte null_byte = 0x30; // Null byte const int max_size = 20; byte[] ACK = { 0xA5 }; // ACK byte byte[] NAK = { 0xFF }; // ACK byte string success = "SUCCESS"; // Send 4-byte header consisting of command byte, length, and 16-bit checksum byte[] checksummed_packet = Checksum(packet); byte[] header = checksummed_packet.Skip(0).Take(header_size).ToArray(); // array substring from Skip and Take, 0 to 4 var header_copy = header.ToArray(); // making a copy for header to go in so it doesn't change it printByteArray(header_copy, "Host sending header"); int header_bytes_sent = simCtl.WriteSerialToFirmware(header_copy, header_size); // Read header bytes back from firmware to verify correct receipt of command header byte[] possible_header = new byte[header_size]; // int header_bytes_recieved = simCtl.ReadSerialFromFirmware(possible_header, header_size); while (simCtl.ReadSerialFromFirmware(possible_header, header_size) < header_size) // function inside returns header_bytes_recieved { ; // wait for four bytes to be recieved // 4 bytes } int test = 0; printByteArray(possible_header, "Host received header response"); // If header is correct if (header.SequenceEqual(possible_header)) // header == possible_header { // Send ACK(0xA5) to firmware byte[] ACK_to_send = ACK.ToArray(); printByteArray(ACK_to_send, "Host sending ack"); int ACK_send = simCtl.WriteSerialToFirmware(ACK_to_send, ACK_NAK_size); // 1 is the size of the ACK and NAK bytes // Send rest of packet not including the 4-byte header byte[] rest_bytes_send = checksummed_packet.Skip(header_size).Take(checksummed_packet.Length - header_size).ToArray(); // array substring printByteArray(rest_bytes_send, "Host sending remaining bytes"); int rest_bytes_sent = simCtl.WriteSerialToFirmware(rest_bytes_send, packet.Length - header_size); // change last argument to parameter data length in the 4th byte // Wait for first byte of response to be received byte[] response_byte = new byte[response_size]; byte[] response_bytes = new byte[max_size]; int num_received = 0; int i = 0; //int response_bytes_recieved = simCtl.ReadSerialFromFirmware(response_bytes, response_size); // Continue reading rest of response until null byte (0) is received while (true) // might get hung up here { num_received = simCtl.ReadSerialFromFirmware(response_byte, 1); if (num_received == 1) { i++; // ++'s the number of bytes received response_bytes[i] = response_byte[response_byte.Length - 1]; // fills the byte[] with the bytes starting at 1 for some reason num_received = 0; // resets num_received } if (response_bytes[i] == null_byte) // should I use .SequenceEqual()? { break; // exit the wait loop } else if (i >= max_size) { Console.Write("Broke when trying to read response \n"); return(false); } } var new_response = response_bytes.Skip(1).Take(i - 1).ToArray(); // i - 1 to take off the null and skip 1 to get rid of the 0 in first string response_string = System.Text.Encoding.ASCII.GetString(new_response); // converts from byte[] to string printByteArray(response_bytes, "Host received response string " + response_string); // Verify that response string equals “SUCCESS” or “VERSION n.n” (If not, re-send entire command) if (response_string == success) // || response_bytes == "VERSION n.n" { return(true); } else { Console.Write("retry NO SUCCESS \n"); // retry command return(HostToFirmware(packet, simCtl, maxRetries, currentRetry + 1)); // this retries the command and returns the result of that command } } // else if header is not received correctly else { // Send NAK(0xFF) byte[] NAK_to_send = NAK.ToArray(); printByteArray(NAK_to_send, "Host sending nak :("); int NAK_send = simCtl.WriteSerialToFirmware(NAK_to_send, ACK_NAK_size); Console.Write("retry NAK \n"); // Retry command return(HostToFirmware(packet, simCtl, maxRetries, currentRetry + 1)); // this retries the command and returns the result of that command } }
private void OnConfirmarImpresion(object sender, EventArgs e) { //Variables Auxiliares String ConsultaSQL = ""; DataTable SerialesImprimir; String unidad_almacenamiento = ""; String codigoEmp = View.CodigoEmpaque.Text.ToString(); String destino = ""; //Evaluo que haya sido seleccionado un registro if (View.ListadoEquiposAProcesar.SelectedIndex == -1) { Util.ShowMessage("Debe seleccionar al menos un registro"); return; } //Evaluo que haya seleccionado laexport plain text nueva clasificacion if (View.Ubicacion.SelectedIndex == -1) { Util.ShowError("Por favor seleccionar la nueva clasificacion."); return; } else { destino = ((DataRowView)View.Ubicacion.SelectedItem).Row["UbicacionDestino"].ToString(); } if (String.Compare("", codigoEmp) == 0) { Util.ShowError("Por favor generar un código de empaque"); return; } //Creo la base de la consulta para traer los seriales respectivos ConsultaSQL = "SELECT idPallet,Posicion,serial,Mac,Codigo_SAP,ProductoID,fecha_ingreso FROM dbo.EquiposCLARO WHERE serial IN (''"; //Recorro el listado de registros seleccionados para obtener los seriales e imprimirlos foreach (DataRowView Registros in View.ListadoEquiposAProcesar.SelectedItems) { //Util.ShowMessage(Registros.Row["Serial"].ToString()); //Creo la consulta para cambiar la ubicacion de la estiba ConsultaSQL += ",'" + Registros.Row["Serial"] + "'"; } //Completo la consulta ConsultaSQL += ")"; //Elimino la basura en la cadena ConsultaSQL = ConsultaSQL.Replace("'',", ""); //Ejecuto la consulta SerialesImprimir = service.DirectSQLQuery(ConsultaSQL, "", "dbo.EquiposCLARO", Local); if (View.UnidadAlmacenamiento.SelectedIndex != -1) { unidad_almacenamiento = ((ComboBoxItem)View.UnidadAlmacenamiento.SelectedItem).Content.ToString(); } else { Util.ShowError("Selecciona una unidad de empaque"); return; } //Imprimo los registros PrinterControl.PrintMovimientosBodega(this.userName, SerialesImprimir, unidad_almacenamiento, codigoEmp, destino, "CLARO", "CONFIRMACIÓN - DIAGNOSTICO", "DAÑADOS", ""); }
public FirmwareController(PrinterControl printer) { this.printer = printer; }
static void PrintFile(PrinterControl simCtl) { //Console.Clear(); Console.WriteLine("\nDefault file will be used unless alternate file is given"); Console.WriteLine("Press any key to continue"); Console.ReadKey(); OpenFileDialog filePath = new OpenFileDialog(); string path = ""; if (filePath.ShowDialog() == DialogResult.OK) { path = filePath.FileName; } if (path == "") { path = "..\\..\\..\\SampleSTLs\\F-35_Corrected.gcode"; } StreamReader file = new System.IO.StreamReader(path); Stopwatch swTimer = new Stopwatch(); swTimer.Start(); // Parse the GCode file var parser = new GenericGCodeParser(); var instructions = parser.Parse(file); /* * Commands to note: * G28: Home all axes * G28 X0: Home x axis * * */ double currentX = 0; double currentY = 0; double currentZ = 0; bool isLaserOn = false; bool oldIsLaserOn = false; int instructionCount = 0; foreach (var line in instructions.AllLines()) { if (line.parameters != null) { //Console.WriteLine(line.code); if (line.code == 1) { bool containsX = false; bool containsY = false; bool containsZ = false; bool containsE = false; foreach (var parameter in line.parameters) { if (parameter.identifier.ToUpper() == "X") { currentX = parameter.doubleValue; containsX = true; } if (parameter.identifier.ToUpper() == "Y") { currentY = parameter.doubleValue; containsY = true; } if (parameter.identifier.ToUpper() == "Z") { currentZ = parameter.doubleValue; containsZ = true; } if (parameter.identifier.ToUpper() == "E") { isLaserOn = parameter.doubleValue > 0; containsE = true; } } // Command number: 0x00 // Format: X (4 bytes), Y (4 bytes) if (containsX && containsY) { instructionCount++; //continue; var bytesToSend = new byte[12]; bytesToSend[0] = 0x00; // Command number bytesToSend[1] = 0x08; // Data length bytesToSend[2] = 0x00; // Blank (for checksum) bytesToSend[3] = 0x00; // Blank (for checksum) // Convert x position and y position to a byte array var xBytes = BitConverter.GetBytes((float)currentX); var yBytes = BitConverter.GetBytes((float)currentY); // Insert x position for (int i = 0; i < xBytes.Length; i++) { bytesToSend[i + 4] = xBytes[i]; } // Insert y position for (int i = 0; i < yBytes.Length; i++) { bytesToSend[i + 8] = yBytes[i]; } // Send data if (!HostToFirmware(bytesToSend, simCtl)) // NOTE: the first byte here is 8!!!!!!!!!!!!!============= { //Console.Write("retry"); Console.WriteLine("Print failed - command failed to send."); return; } } // Command number: 0x01 // Format: Z (4 bytes) else if (containsZ) { instructionCount++; //continue; var bytesToSend = new byte[8]; bytesToSend[0] = 0x01; // Command number bytesToSend[1] = 0x04; // Data length // changed from 04 bytesToSend[2] = 0x00; // Blank (for checksum) bytesToSend[3] = 0x00; // Blank (for checksum) // Convert z position to a byte array var zBytes = BitConverter.GetBytes((float)currentZ); // Insert z position for (int i = 0; i < zBytes.Length; i++) { bytesToSend[i + 4] = zBytes[i]; } // Send data if (!HostToFirmware(bytesToSend, simCtl)) { Console.WriteLine("Print failed - command failed to send."); return; } } else if (containsX || containsY) { throw new InvalidDataException("Invalid GCode command - command contains one X/Y command without the other."); } // Separately, if it contains an E // Command number: 0x02 // Format: isLaserOn (1 byte) if (containsE && (isLaserOn != oldIsLaserOn)) { oldIsLaserOn = isLaserOn; instructionCount++; //continue; var bytesToSend = new byte[8]; bytesToSend[0] = 0x02; // Command number bytesToSend[1] = 0x01; // Data length bytesToSend[2] = 0x00; // Blank (for checksum) bytesToSend[3] = 0x00; // Blank (for checksum) // Convert z position to a byte array var isLaserOnBytes = BitConverter.GetBytes(isLaserOn); // Insert isLaserOn for (int i = 0; i < isLaserOnBytes.Length; i++) { bytesToSend[i + 4] = isLaserOnBytes[i]; } // Send data if (!HostToFirmware(bytesToSend, simCtl)) { Console.WriteLine("Print failed - command failed to send."); return; } } } } } Console.WriteLine("Host: There were " + instructionCount.ToString() + " instructions sent by the host."); swTimer.Stop(); long elapsedMS = swTimer.ElapsedMilliseconds; Console.WriteLine("Total Print Time: {0}", elapsedMS / 1000.0); Console.WriteLine("Press any key to continue"); Console.ReadKey(); }
public Z_RailFunction(PrinterControl Printer) { printer = Printer; initialized = false; }
public Command(PrinterControl printer) { this.printer = printer; }
public HostHandler(PrinterThread thread) { this.printer = thread.GetPrinterSim(); }
public static void SendPacket(PrinterControl printer, Packet packet) { byte[] header = packet.GetHeader(); byte[] headerCopy = new byte[4]; header.CopyTo(headerCopy, 0); int result = 0; //Console.WriteLine("\nHost sending to firmware: "); //for (int i = 0; i < header.Length; i++) //{ // Console.Write(" "); // Console.Write(header[i]); //} result = printer.WriteSerialToFirmware(headerCopy, header.Length); byte[] responseHeader = ReadPacket(printer, header.Length); if (SameHead(header, responseHeader) == true) { //Console.WriteLine("\nHost sent ACK to firmware: "); printer.WriteSerialToFirmware(new byte[] { 0xA5 }, 1); //Console.WriteLine("\nHost sending packet to firmware: "); //for (int i = 0; i < packet.data.Length; i++) //{ // Console.Write(" "); // Console.Write(packet.data[i]); //} byte[] packetDataCopy = new byte[packet.data.Length]; packet.data.CopyTo(packetDataCopy, 0); printer.WriteSerialToFirmware(packetDataCopy, packet.data.Length); byte[] character = ReadPacket(printer, 1); string response = ""; while (character[0] != 0) { response += Encoding.ASCII.GetString(new byte[] { character[0] }); character = ReadPacket(printer, 1); } //Console.WriteLine("\nResponse: " + response); if (response == "SUCCESS") { return; } else if (response.Contains("VERSION")) { return; } else { SendPacket(printer, packet); } } else { printer.WriteSerialToFirmware(new byte[] { 0xFF }, 1); SendPacket(printer, packet); } return; }
private void OnImprimirEtiqueta_Individual(object sender, EventArgs e) { Boolean validacion = false; List <String> codAuxiliares = new List <String>(); String serial = View.GetMacImpre_Individual.Text; String mac = View.GetSerialImpre_Individual.Text; Int32 cantidadImpresiones = 1; if (serial != "" || mac != "") { if (View.Get_StackCodigosAdicionales.Children.Count > 0) { //Si el stackpanel tiene controles adicionales para codigos aparte de serial y mac // Se recorre todo el stackpanel en busca de Textbox, especificamente del valor que tengan estos foreach (var child in View.Get_StackCodigosAdicionales.Children) { var textBox = child as TextBox; if (textBox == null) { continue; } if (textBox.Text == "") { textBox.BorderBrush = Brushes.Red; textBox.KeyUp += new KeyEventHandler(KeyUp_CodigoAdicional); validacion = true; } else { textBox.BorderBrush = Brushes.AliceBlue; codAuxiliares.Add(textBox.Text); } } } if (validacion) { Util.ShowError("Todos los campo deben estar completos."); return; } else { System.Windows.Forms.PrintDialog pd = new System.Windows.Forms.PrintDialog(); pd.PrinterSettings = new PrinterSettings(); Int32.TryParse(View.GetCantidad_Impresiones.Text, out cantidadImpresiones); //try { if (System.Windows.Forms.DialogResult.OK == pd.ShowDialog()) { PrinterControl.EtiquetadoEquipoIndividual(serial, mac, this.rutaEtiqueta, this.ipservidor, codAuxiliares, cantidadImpresiones, pd.PrinterSettings.PrinterName); } //} // catch(Exception ex){ // Util.ShowError("Error en la impresión, por favor verifique la conexión a la impresora Zebra "+ex.Message); // } } } else { Util.ShowError("Todos los campo deben estar completos."); } }
public FirmwareController(PrinterControl printer) { this.printer = printer; zRailController = new ZRailController(printer); }
private void startHttpThread() { using (HttpListener listerner = new HttpListener()) { listerner.AuthenticationSchemes = AuthenticationSchemes.Anonymous;//指定身份验证 Anonymous匿名访问 listerner.Prefixes.Add("http://127.0.0.1:" + port + "/report/"); listerner.Start(); log.Info("WebServer Start Successed......."); PrinterControl printerControl = new PrinterControl(); var reportTemplate = string.Empty; while (true) { //等待请求连接 //没有请求则GetContext处于阻塞状态 HttpListenerContext ctx = listerner.GetContext(); string callback = string.Empty; try { log.Info("开始处理请求…… "); Uri url = ctx.Request.Url; ctx.Response.StatusCode = 200;//设置返回给客服端http状态代码 ctx.Response.ContentType = "application/json"; Dictionary <string, string> parm = getData(ctx); if (parm.Count > 0) { var printUrl = parm["url"].ToString().Trim(); callback = parm["callback"].ToString().Trim(); log.Info(printUrl + ": " + printUrl); var postData = parm["postData"].ToString().Trim(); log.Info(postData + ": " + postData); var cookieStr = parm["cookieStr"].ToString().Trim(); log.Info(cookieStr + ": " + cookieStr); var printerParams = parm["printerParams"].ToString().Trim(); log.Info(printerParams + ": " + printerParams); var charset = parm["charset"].ToString().Trim(); log.Info(charset + ": " + charset); reportTemplate = parm["_report"].ToString().Trim(); log.Info(reportTemplate + ": " + reportTemplate); SetPrint(sysIniPath, reportTemplate); PrinterSettings settings = new PrinterSettings(); //settings.DefaultPageSettings.PaperSize.Kind= System.Drawing.Printing.PaperKind.Custom; //1.设置打印机名称 settings.PrinterName = INIHepler.INIGetStringValue(sysIniPath, reportTemplate, reportTemplate, null); //2.设置打印机打印方向 settings.DefaultPageSettings.Landscape = Convert.ToBoolean(INIHepler.INIGetStringValue(sysIniPath, reportTemplate, "SetLandscape", null)); //3.设置纸张 //settings.DefaultPageSettings.PaperSize.PaperName = INIHepler.INIGetStringValue(sysIniPath, reportTemplate, "SetPaperName", null); //纸张高度 var SetPaperHeight = INIHepler.INIGetStringValue(sysIniPath, reportTemplate, "SetPaperHeight", 0 + ""); //纸张宽度 var SetPaperWidth = INIHepler.INIGetStringValue(sysIniPath, reportTemplate, "SetPaperWidth", 0 + ""); PaperSize paperSize = new PaperSize(reportTemplate, Convert.ToInt32(SetPaperWidth), Convert.ToInt32(SetPaperHeight)); settings.DefaultPageSettings.PaperSize = paperSize; //4下边距 var SetMarginsBottom = INIHepler.INIGetStringValue(sysIniPath, reportTemplate, "SetMarginsBottom", 0 + ""); //5上边距 var SetMarginsTop = INIHepler.INIGetStringValue(sysIniPath, reportTemplate, "SetMarginsTop", 0 + ""); //6左边距 var SetMarginsLeft = INIHepler.INIGetStringValue(sysIniPath, reportTemplate, "SetMarginsLeft", 0 + ""); //7右边距 var SetMarginsRight = INIHepler.INIGetStringValue(sysIniPath, reportTemplate, "SetMarginsRight", 0 + ""); //8------设置边距 Margins margins = new Margins(); margins.Bottom = Convert.ToInt32(SetMarginsBottom); margins.Top = Convert.ToInt32(SetMarginsTop); margins.Left = Convert.ToInt32(SetMarginsLeft); margins.Right = Convert.ToInt32(SetMarginsRight); settings.DefaultPageSettings.Margins = margins; var result = printerControl.SilentPrint(printUrl, postData, cookieStr, printerParams, charset, settings); log.Info("本地打印服务调用打印操作:" + result); using (StreamWriter writer = new StreamWriter(ctx.Response.OutputStream)) { // writer.WriteLine(result); writeJS(writer, result.ToString(), callback); } } } catch (Exception e) { if (ctx != null) { ctx.Response.StatusCode = 500;//设置返回给客服端http状态代码 using (StreamWriter writer = new StreamWriter(ctx.Response.OutputStream)) { writeJS(writer, "{status:'error',msg:'" + e.StackTrace + "'}", callback); log.Info("调用本地打印服务出现异常" + e.StackTrace + "*******" + e.Message + "*******" + e.InnerException.StackTrace); } } } } } }
static void PrintFile(string fileName, Command command, PrinterControl simCtl) { string Cmd; float X, Y, Z, E; bool fLaserOn = false; command.SendSingleCommand((byte)FWCommands.CMD_RETRACT_PLATE); // Retract plate Stopwatch swTimer = new Stopwatch(); swTimer.Start(); command.SendCommandParam1((byte)FWCommands.CMD_REMOVE_MODEL, 0); // Set Z axis command.SendCommandParam1((byte)FWCommands.CMD_SET_Z, 0); // Set Z axis command.StartCommandBuffer(); GCode coder = new GCode(fileName); Cmd = ""; X = 0; Y = 0; Z = 0; E = 0; while (coder.GetNextLine(ref Cmd, ref X, ref Y, ref Z, ref E)) { #if USE_OPTIMAL_COMMS if (Z != 0) { command.Add((byte)FWCommands.CMD_SET_Z); command.Add(4); command.Add(Z); } if (E != 0) // Turn on laser { if (!fLaserOn) { command.Add((byte)FWCommands.CMD_SET_LASER); command.Add(1); command.Add(1); fLaserOn = true; } } else // Turn OFF laser { if (fLaserOn) { command.Add((byte)FWCommands.CMD_SET_LASER); command.Add(1); command.Add(0); fLaserOn = false; } } if (X != 0 || Y != 0) { command.Add((byte)FWCommands.CMD_MOVE_GALVOS); command.Add(8); command.Add(X * 0.025f); command.Add(Y * 0.025f); } if (command.Count() > CMD_SEND_THRESHOLD) { command.SendCommandBuffer(); command.StartCommandBuffer(); } #else if (Z != 0) { command.SendCommandParam1((byte)FWCommands.CMD_SET_Z, Z); // Set Z axis } if (E != 0) // Set laser { if (!fLaserOn) { command.SendCommandParam1((byte)FWCommands.CMD_SET_LASER, 1); fLaserOn = true; } } else // Turn OFF laser { if (fLaserOn) { command.SendCommandParam1((byte)FWCommands.CMD_SET_LASER, 0); fLaserOn = false; } } if (X != 0 || Y != 0) { command.SendCommandParam2((byte)FWCommands.CMD_MOVE_GALVOS, X * 0.025f, Y * 0.025f); } #endif Cmd = ""; X = 0; Y = 0; Z = 0; E = 0; } command.SendSingleCommand((byte)FWCommands.CMD_RETRACT_PLATE); // Retract plate swTimer.Stop(); long elapsedMS = swTimer.ElapsedMilliseconds; Console.WriteLine("Total Print Time: {0}", elapsedMS / 1000.0); Console.WriteLine("Press any key to continue"); Console.ReadKey(); }
public ZRailController(PrinterControl printer) { positionHistory = new List <double>(); this.printer = printer; }