Пример #1
0
        public static void CommunicationsProtocol(PrinterControl simCtl, byte[] commandPkt)
        {
            var complete = false;
            var header   = new byte[4];

            do
            {
                Buffer.BlockCopy(commandPkt, 0, header, 0, 4);
                var paramDataLen = commandPkt[1];
                var commandParam = new byte[paramDataLen];
                Buffer.BlockCopy(commandPkt, 4, commandParam, 0, paramDataLen);
                var checksumBytes = CalculateChecksum(header, commandParam);
                header[2] = checksumBytes[0];
                header[3] = checksumBytes[1];
                var rcvHeader = SendHeaderAndReceive(simCtl, header);
                if (ByteArraysEquals(header, rcvHeader))
                {
                    //Console.WriteLine("Sending ACK");
                    var ackParam = CombineBytes(ACK, commandParam);
                    //simCtl.WriteSerialToFirmware(ACK, 1);
                    //simCtl.WriteSerialToFirmware(commandParam, commandParam.Length);
                    simCtl.WriteSerialToFirmware(ackParam, ackParam.Length);
                    complete = WaitForResponse(simCtl);
                }
                else
                {
                    //Console.WriteLine("Sending NACK");
                    simCtl.WriteSerialToFirmware(NACK, 1);
                }
            } while (complete == false);
        }
        public void execute(Command cmd, List <Object> param)
        {
            switch (cmd)
            {
            case Command.GetFirmwareVersion:
                var byteMessage = new byte[4] {
                    0x00, 0x00, 0x00, 0x00
                };
                break;

            case Command.ResetStepper:
                byteMessage = new byte[4] {
                    0x01, 0x00, 0x00, 0x00
                };
                printer.WriteSerialToFirmware(byteMessage, 4);    // send command
                handleResponse(cmd, byteMessage, param);
                break;

            case Command.StepStepper:
                byteMessage = new byte[4] {
                    0x02, 0x00, 0x00, 0x00
                };
                // send command with param[0] (up or down)
                break;

            case Command.SetLaser:
                byteMessage = new byte[4] {
                    0x03, 0x00, 0x00, 0x00
                };
                // send command param[0] (on or off)
                break;

            case Command.MoveGalvonometer:
                byteMessage = new byte[4] {
                    0x04, 0x00, 0x00, 0x00
                };
                // send commandwith param[0] x and param[1] y
                break;

            default:
                break;
            }
        }
Пример #3
0
        static byte[] SendHeaderAndReceive(PrinterControl printer, byte[] header)
        {
            //Console.WriteLine("SendingHeader");
            var fooRcvd   = new byte[4];
            int bytesRead = 0;

            printer.WriteSerialToFirmware(header, 4);
            do
            {
                bytesRead = printer.ReadSerialFromFirmware(fooRcvd, 4);
            } while (bytesRead < 1);
            return(fooRcvd);
        }
Пример #4
0
        /*
         * 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
            }
        }
Пример #5
0
        public string SendCommand()
        {
            byte[] value = new byte[HEADER_SIZE];
            int    bytesRetrieved;
            string retString = "";

            // Calculate checksum
            short checkSum = 0;

            for (int i = 0; i < curCommand.Count(); i++)
            {
                checkSum += curCommand[i];
            }

            curCommand[2] = (byte)checkSum;    // Stuff checksum into buffer at reserved spot
            curCommand[3] = (byte)(checkSum >> 8);

            do
            {
                // Write the header
                printer.WriteSerialToFirmware(curCommand.ToArray(), HEADER_SIZE);
                // Get header back
                while ((bytesRetrieved = printer.ReadSerialFromFirmware(value, HEADER_SIZE)) == 0)
                {
                    ;
                }

                if (value[0] == curCommand[0] && value[1] == curCommand[1] && value[2] == curCommand[2] && value[3] == curCommand[3])
                {
                    // Send ACK
                    value[0] = 0xA5;
                    printer.WriteSerialToFirmware(value, 1);

                    // Send command payload
                    while (printer.WriteSerialToFirmware(curCommand.Skip(HEADER_SIZE).ToArray(), curCommand.Count() - HEADER_SIZE) == 0)
                    {
                        ;
                    }

                    retString = "";
                    // Wait for response byte
                    do
                    {
                        bytesRetrieved = printer.ReadSerialFromFirmware(value, 1);
                    } while (bytesRetrieved == 0);

                    retString += (char)value[0];  // Add returned value to return string

                    // Add rest of response string until null byte read
                    while (value[0] != 0)
                    {
                        bytesRetrieved = printer.ReadSerialFromFirmware(value, 1);
                        if (bytesRetrieved != 0 && value[0] != 0)
                        {
                            retString += (char)value[0];
                        }
                    }

                    if (curCommand[0] == FWCommands.CMD_VERSION)
                    {
                        break;                                          // Return version info
                    }
                    //                    if (retString != "SUCCESS") Console.WriteLine("Error {0}: " + retString, cmdNum);
                }
                else  // error - send NACK
                {
                    // Send NACK
                    value[0] = 0xFF;
                    printer.WriteSerialToFirmware(value, 1);
                    retString = "NAK";
                }
            } while (retString != "SUCCESS");

            Clear();
            cmdNum++;

            return(retString);
        }
        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 handleMessage(Command cmd, byte[] byteMessage, byte[] paramBytes, float[] floatParam)
        {
            var fullMessage = getFullMessage(byteMessage, paramBytes);
            var checksum    = HelperFunctions.ParseCmdPacket(fullMessage);

            byteMessage[2] = checksum[0];
            byteMessage[3] = checksum[1];
            bool done = false;

            while (!done)
            {
                if (byteMessage[1] > 0x08)
                {
                    var breakp = 0;
                }
                Console.WriteLine("Host: Writing command {0} to firmware", cmd);
                Console.Write("Host: Params in command: ");
                foreach (float p in floatParam)
                {
                    Console.Write("{0}, ", p);
                }
                Console.Write("\n");
                Console.WriteLine("Host: Checksum verification returned {0}", HelperFunctions.validateChecksum(byteMessage, paramBytes));
                printer.WriteSerialToFirmware(byteMessage, byteMessage.Length);
                var finalResponse  = "";
                var headerResponse = new byte[4];
                Console.WriteLine("Host: Reading header back from firmware");
                if (!read(headerResponse, 4))
                {
                    continue;
                }
                bool isRight = byteMessage.SequenceEqual(headerResponse);
                if (isRight)
                {
                    Console.WriteLine("Host: Header was correct, sending parameter data");
                    printer.WriteSerialToFirmware(new byte[1] {
                        0xA5
                    }, 1);
                    printer.WriteSerialToFirmware(paramBytes, paramBytes.Length);
                    var ch = new byte[1] {
                        0xFF
                    };
                    Console.WriteLine("Host: Waiting for success string");
                    while (!ch.SequenceEqual(new byte[1] {
                        0x00
                    }))
                    {
                        var readResult = read(ch, 1);
                        if (!readResult)
                        {
                            ch[0] = 0x00;
                        }
                        finalResponse += System.Text.Encoding.UTF8.GetString(ch);
                    }
                    if (finalResponse.Split(':')[0] == "VERSION")
                    {
                        Console.WriteLine("Host: received version confirmation\n");
                        this.firmwareVersion = "FIRMWARE VERSION: " + finalResponse.Split(':')[1].Replace("\0", string.Empty);
                        done = true;
                        return;
                    }
                    else
                    {
                        Console.WriteLine("Host: Did not receive version confirmation\n");
                        continue;
                    }
                }
                else
                {
                    Console.WriteLine("Host: Header was wrong, resending command\n");
                    printer.WriteSerialToFirmware(new byte[1] {
                        0xFF
                    }, 1);
                    continue;
                }
            }
        }