Ejemplo n.º 1
0
 public override string ToString()
 {
     return("[ " + _msgType.ToString() +
            " - " + _priority.ToString() +
            " - ID: " + _msgID +
            " (" + CNCRTools.BytesToHex(this.toSerial()) + ") ]");
 }
Ejemplo n.º 2
0
        /// <summary>
        /// Transfers message data to a byte array for transfer.
        /// </summary>
        /// <returns>
        /// Command Structure:
        /// [Type XYZ P] [SpeedUpper7 P] [SpeedLower7 P] [0000 0 SU1 SL1 P] [Parity]
        /// -  Type: 5
        /// -   XYZ: 110 would set the speed for X and Y, but not Z
        /// - Speed: 16 bit unsigned int, a range of about 64k
        /// </returns>
        public override byte[] toSerial()
        {
            // Build first byte [Type 0 XYZ] --> [0101 0XYZ]
            byte TypeAndAxis = getMsgTypeByte();

            if (_X)
            {
                TypeAndAxis |= 0x08;
            }                                // Set X bit [0000 1000]
            if (_Y)
            {
                TypeAndAxis |= 0x04;
            }                                // Set Y bit [0000 0100]
            if (_Z)
            {
                TypeAndAxis |= 0x02;
            }                                // Set Z bit [0000 0010]

            byte[] speedBytes = CNCRTools.generateThreeBytesFromUInt16(_speed);

            byte[] result = { TypeAndAxis,   speedBytes[0],
                              speedBytes[1], speedBytes[2], 0 };
            CNCRTools.generateParity(ref result);
            return(result);
        }
Ejemplo n.º 3
0
        private void button1_Click(object sender, EventArgs e)
        {
            //                      center     start     stop
            //                      (0, 0)    (0, -1)    (0, 1)
            //int[] a180 = new int[] { 0, 0,/**/ 0, -1,/**/ 0, 1 }; // -180 // CCW
            //int[] a180 = new int[] { 0, 0,/**/ 0, -1,/**/ -1, 0 };// -270 // CCW
            //int[] a180 = new int[] { 0, 0,/**/ -1, 0,/**/ 0, -1 };// 270 // CW (360 - 270) = 90
            //int[] a180 = new int[] { 0, 0,/**/ 1, 0,/**/ -1, 0 };// -180
            int[] a180 = new int[] { 0, 0, /**/ 1, 0, /**/ 0, -1 };// -90

            // From (0, -1) to (0, 1) = -180
            double angle = CNCRTools.getAngleFromLines(a180[0], a180[1], a180[2], a180[3], a180[0], a180[1], a180[4], a180[5]);

            label1.Text = angle.ToString();
            //CNCRMessage bob = new CNCRMessage(CNCRMSG_TYPE.E_STOP);

            /* For testing the priority Queue
             * PriorityQueue<CNCRMessage> testQ = new PriorityQueue<CNCRMessage>();
             * testQ.Enqueue(new CNCRMsgSetSpeed(true, true, false, 300));
             * testQ.Enqueue(new CNCRMsgSetSpeed(false, false, true, 100));
             * testQ.Enqueue(new CNCRMsgMove(0, 0, 5));
             * testQ.Enqueue(new CNCRMsgToolCmd(true));
             * testQ.Enqueue(new CNCRMsgMove(0, 0, 0));
             * CNCRMessage testM = new CNCRMsgCmdAck(false, 0);
             * testM.setPriority(CNCRMSG_PRIORITY.MEDIUM);
             * testQ.Enqueue(testM);
             *
             * label1.Text = "";
             * while (testQ.Count > 0)
             * {
             *  label1.Text += testQ.Dequeue().ToString() + "\n";
             * }//*/



            /* For testing queue joining.
             *
             * List<int> bob = new List<int>();
             * bob.Add(1);
             * bob.Add(2);
             * bob.Add(3);
             * bob.Add(4);
             *
             * List<int> bob2 = new List<int>();
             * bob2.Add(5);
             * bob2.Add(6);
             * bob2.Add(7);
             * bob2.Add(8);
             *
             * bob.AddRange(bob2);
             *
             * Queue<int> jim = new Queue<int>(bob);
             *
             * label1.Text = "";
             * while (jim.Count > 0)
             * {
             *  label1.Text += jim.Dequeue().ToString() + "\n";
             * }//*/
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Transfers CNCRMsgEStop to a byte array for transfer.
        /// </summary>
        /// <returns>
        /// Command Structure:
        ///     [Type 000 P] [Parity]
        /// </returns>
        public override byte[] toSerial()
        {
            // [0010 000 P] [Parity]
            byte Type = getMsgTypeByte();

            byte[] result = { Type, 0 };
            CNCRTools.generateParity(ref result);
            return(result);
        }
Ejemplo n.º 5
0
 public CNCRMsgMove(byte[] msgBytes)
     : this()
 {
     //TODO: CNCRMsgMove: Error check the bytes
     //Convert Bytes to X, Y, Z
     this._X = CNCRTools.generateInt16FromThreeBytes(msgBytes, 1);
     this._Y = CNCRTools.generateInt16FromThreeBytes(msgBytes, 4);
     this._Z = CNCRTools.generateInt16FromThreeBytes(msgBytes, 7);
 }
Ejemplo n.º 6
0
 private void DisplayDataQueue()
 {
     _displayLabel.Invoke(new EventHandler(delegate
     {
         _displayLabel.Text = string.Empty;
         byte[] bytesInQ    = _commBufferQueue.ToArray();
         _displayLabel.Text = CNCRTools.BytesToHex(bytesInQ);
     }));
 }
Ejemplo n.º 7
0
        /// <summary>
        /// Converts message data to a byte array for transfer over serial.
        /// </summary>
        /// <returns>
        /// Command Structure:
        /// [Type 000 P] [#Cmds P] [255]
        /// -     Type: 3
        /// -    #Cmds: 7 bits, gives a range of 1 to 128.
        /// </returns>
        public override byte[] toSerial()
        {
            byte Type     = getMsgTypeByte();
            byte CmdCount = Convert.ToByte(_cmdCnt << 1);

            byte[] result = { Type, CmdCount, 0 };   // Build the result array.
            // generate parity
            CNCRTools.generateParity(ref result);
            return(result);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Transfers the message data to a byte array for transfer.
        /// </summary>
        /// <returns>
        /// Command Structure:
        /// [Type 00 isEndQueue P] [Parity]
        /// -        Type: 4
        /// - isStopQueue: Set to 1 to indicate an end of the build process.
        /// </returns>
        public override byte[] toSerial()
        {
            byte typeEndQueue = getMsgTypeByte();

            if (_isEndQueue)
            {
                typeEndQueue |= 0x02; // Set the EndQueue bit.
            }
            byte[] result = { typeEndQueue, 0 };
            CNCRTools.generateParity(ref result);
            return(result);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Transfers the message data to a byte array for transfer.
        /// </summary>
        /// <returns>
        /// [Type 00 OnOff P][Parity]
        /// -  Type: 7
        /// - OnOff: 0 for off, 1 for on
        /// </returns>
        public override byte[] toSerial()
        {
            byte TypeOnOff = getMsgTypeByte();

            if (_toolOn)
            {
                TypeOnOff |= 0x02;
            }                                   // If tool on, set the bit.

            byte[] result = { TypeOnOff, 0 };
            CNCRTools.generateParity(ref result);
            return(result);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Outputs the message in a format that can be sent over the
        /// serial connection.
        /// </summary>
        /// <returns>
        /// Command Structure:
        /// [Type 000] [UpperX] [LowerX] [EndsX]
        ///            [UpperY] [LowerY] [EndsY]
        ///            [UpperZ] [LowerZ] [EndsZ]
        ///            [Parity]
        /// </returns>
        public override byte[] toSerial()
        {
            byte Type = getMsgTypeByte();

            byte[] xBits  = CNCRTools.generateThreeBytesFromInt16(getX());
            byte[] yBits  = CNCRTools.generateThreeBytesFromInt16(getY());
            byte[] zBits  = CNCRTools.generateThreeBytesFromInt16(getZ());
            byte[] result = { Type,
                              xBits[0],xBits[1],  xBits[2],
                              yBits[0],yBits[1],  yBits[2],
                              zBits[0],zBits[1],  zBits[2],
                              0 };
            CNCRTools.generateParity(ref result);
            return(result);
        }
Ejemplo n.º 11
0
 public void SendBytes(byte[] bytes)
 {
     if (!(comPort.IsOpen == true))
     {
         OpenPort();
     }
     if (comPort.IsOpen && (bytes.Length > 0))
     {
         comPort.Write(bytes, 0, bytes.Length);
     }
     else
     {
         DisplayData("Error: Failed to send bytes - [" +
                     CNCRTools.BytesToHex(bytes) + "]\n");
     }
     //comPort.Close();
 }
Ejemplo n.º 12
0
        /// <summary>
        /// Transfers CNCRMsgCmdAck data to a byte array for transfer.
        /// </summary>
        /// <returns>
        /// Structure of result:
        ///     0001 001 0 | 0000 000 0 | Parity
        ///     type err P | firmware P | Parity
        /// </returns>
        public override byte[] toSerial()
        {
            // Set top 4 bits to "0001"
            byte TypeAndErr = getMsgTypeByte();

            // Set the error flag.
            if (_isError)
            {
                TypeAndErr |= 0x02;
            }

            byte[] result = { TypeAndErr, Convert.ToByte(_firmware << 1), 0 };

            // Set the parity bits and byte.
            CNCRTools.generateParity(ref result);
            return(result);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// method that will be called when there is data waiting in the buffer
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void comPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            int bytes = comPort.BytesToRead;

            byte[] comBuffer = new byte[bytes];
            comPort.Read(comBuffer, 0, bytes);

            if (getDiscardingData())
            {
                DisplayData("Discarded: " + CNCRTools.BytesToHex(comBuffer) + "\n");
            }
            else
            {
                DisplayData("Received: " + CNCRTools.BytesToHex(comBuffer) + "\n");
                handleData(comBuffer);
                DisplayDataQueue();
            }
        }
Ejemplo n.º 14
0
 public CNCRMsgSetSpeed(byte[] msgBytes)
     : this()
 {
     //TODO: CNCRMsgSetSpeed: msgBytes constructor needs to validate msgBytes.
     if ((msgBytes[0] & 0x08) == 0x08)
     {
         _X = true;
     }
     if ((msgBytes[0] & 0x04) == 0x04)
     {
         _Y = true;
     }
     if ((msgBytes[0] & 0x02) == 0x02)
     {
         _Z = true;
     }
     _speed = CNCRTools.generateUInt16FromThreeBytes(msgBytes, 1);
 }
Ejemplo n.º 15
0
        public void SendMsg(CNCRMessage msg)
        {
            //TODO: SendMsg: Should this function really be doing this check?  Shouldnt the function errorhandler do this?
            if (getDiscardingData() &&                   // If we are discarding data.
                msg.getMessageType() == CNCRMSG_TYPE.CMD_ACKNOWLEDGE && // and sending an acknowledge
                ((CNCRMsgCmdAck)msg).getError() == true) // and that acknowledge is saying we have an error.
            {
                setDiscardingData(false);                // Then clear the discard data bit so we can see the response.
                byte[] serialStuff = msg.toSerial();
                string toDisplay   = "Ack Sent: " + CNCRTools.BytesToHex(msg.toSerial());
                toDisplay += "\n";

                DisplayData(toDisplay);
            }
            if (msg.getMessageType() != CNCRMSG_TYPE.CMD_ACKNOWLEDGE)
            {
                setWaitingOnAck(true);
            }
            setLastMessage(msg);
            DisplayData("Sending: " + msg.ToString() + "\n");
            SendBytes(msg.toSerial());
        }
Ejemplo n.º 16
0
        private void CNCRouterCommand_Load(object sender, EventArgs e)
        {
#if !DEBUG
            tcInterface.TabPages.Remove(tpGenDebug);
            tcInterface.TabPages.Remove(tpCommDebug);
#endif

            // Setup the debug tab.
            string[] ports = CNCRTools.GetCNCRouterPorts();
            cmbPorts.Items.AddRange(ports);
            if (cmbPorts.Items.Count > 0)
            {
                cmbPorts.SelectedIndex = 0;
            }

            cmbMsgs.SelectedIndex = 0;

            // Setup the Auto Tab
            commCmd._rtbOutputCommDbg = rtbTraffic;
            commCmd._rtbOutputAuto    = rtbRCOutput;

            commCmd._displayLabel = lblQueue;

            // Setup the manual tab.
            for (int i = 0; i < distances.Length; i++)
            {
                cmbMoveDistance.Items.Add(distances[i].ToString() + " mm");
            }
            cmbMoveDistance.SelectedIndex = 0;

            // Setup the Settings tab.
            cmbRouterPort.Items.AddRange(ports);
            if (cmbRouterPort.Items.Count > 0)
            {
                cmbRouterPort.SelectedIndex = 0;
            }
        }
Ejemplo n.º 17
0
        // Events and functions related to the "Auto" tab.
        #region Auto Tab

        private void btnLoadGCode_Click(object sender, EventArgs e)
        {
            string eventLog = "";

            if (ofdGcodeBrowse.ShowDialog() == DialogResult.OK)
            {
                rtbRCOutput.Clear();

                eventLog += "Opening " + ofdGcodeBrowse.SafeFileName + "\n";

                System.IO.StreamReader readFile = new System.IO.StreamReader(ofdGcodeBrowse.OpenFile());
                string gcode = readFile.ReadToEnd();
                CNCRTools.arcRes = Double.Parse(txtArcAccuracy.Text);
                Queue <CNCRMessage> tempQueue = CNCRTools.parseGCode(gcode, ref eventLog);
                commCmd.commCommandQueueSet(tempQueue);
                eventLog += "Finished Loading. Created " + tempQueue.Count().ToString() + " messages.\n";
                rtbRCOutput.AppendText(eventLog);
                rtbRCOutput.ScrollToCaret();
                lblStatusFile.Text = ofdGcodeBrowse.SafeFileName;

                /* Debug output of the commands to a text file.
                 * string outputText = "";
                 *
                 * while (tempQueue.Count() > 0)
                 * {
                 *  CNCRMessage curMsg = tempQueue.Dequeue();
                 *  if (curMsg.getMessageType() == CNCRMSG_TYPE.MOVE)
                 *  {
                 *      outputText += ((CNCRMsgMove)curMsg).getX().ToString() +
                 *          "\t" + ((CNCRMsgMove)curMsg).getY().ToString() + "\n";
                 *  }
                 * }
                 * System.IO.TextWriter tw = new System.IO.StreamWriter("output2.txt");
                 * tw.Write("");
                 * tw.Close();//*/
            }
        }
Ejemplo n.º 18
0
        public void handleData(byte[] commBuffer)
        {
            // Are we currently in the middle of a type?
            if (_commBufferQueue.Count == 0)
            {
                // No, so grab the type in the next byte.
                setCurType((CNCRMSG_TYPE)Enum.ToObject(typeof(CNCRMSG_TYPE), (commBuffer[0] & 0xF0) >> 4));
            }

            // Get the current type, if it is not between MIN and MAX_TYPE
            CNCRMSG_TYPE currentType = getCurType();

            if (CNCRMSG_TYPE.zMIN_TYPE < currentType && currentType < CNCRMSG_TYPE.zMAX_TYPE)
            {
                // Drop all incoming bytes into the queue
                for (int i = 0; i < commBuffer.Length; i++)
                {
                    if (CNCRTools.validateParityBit(commBuffer[i]))
                    {
                        _commBufferQueue.Enqueue(commBuffer[i]);
                    }
                    else
                    {
                        // Bad Parity bit, Discard the data and log an error.
                        handleError("Invalid Parity Bit.");
                        return;
                    }
                }

                // Check how long of a message we are expecting
                int expectedLength = CNCRTools.getMsgLenFromType(getCurType());
                // Uh, Oh, what about expectedLength = 0, AKA, bad type?
                // - At this point, curType should be validated and curType
                //   should not be unknown, throw an error in getMsgLenFromType.
                if (expectedLength > 0)
                {
                    // Process the current Queue
                    while (_commBufferQueue.Count >= expectedLength)
                    {
                        // We have enough bytes, lets get the message for those bytes.
                        byte[] msgBytes = new byte[expectedLength];
                        for (int i = 0; i < msgBytes.Length; i++)
                        {
                            msgBytes[i] = _commBufferQueue.Dequeue();
                        }

                        if (CNCRTools.validateParityByte(msgBytes))
                        {
                            DisplayData("- Valid Parity\n");
                            CNCRMessage CommMsg = CNCRTools.getMsgFromBytes(msgBytes);
                            DisplayData("- Type: " + CommMsg.ToString() + "\n");
                            Thread runActOnMessage = new Thread(new ParameterizedThreadStart(actOnMessage));
                            runActOnMessage.Start(CommMsg);
                        }
                        else
                        {
                            handleError("Invalid Parity Byte.");
                            return;
                        }
                    }
                }
                else
                {
                    handleError("Expected length was 0 or less.");
                    return;
                }
            }
            else
            {
                // Bad type: log an error, discard bytes.
                handleError("Invalid message type.");
                return;
            }
        }
Ejemplo n.º 19
0
 private void btnRefreshPorts_Click(object sender, EventArgs e)
 {
     cmbPorts.Items.Clear();
     cmbPorts.Items.AddRange(CNCRTools.GetCNCRouterPorts());
     cmbPorts.SelectedIndex = 0;
 }
Ejemplo n.º 20
0
        private void btnSndMsg_Click(object sender, EventArgs e)
        {
            /*
             * int discarded = 0;
             * byte[] bytes = CNCRTools.GetBytes(txtHex.Text, out discarded);
             * lblDbgOut.Text = "";
             * for (int i = 0; i < bytes.Length; i++)
             * {
             *  lblDbgOut.Text += bytes[i].ToString() + " ";
             * }//*/

            byte[]      sendBytes = { 0 };
            CNCRMessage sendMsg   = null;

            switch (cmbMsgs.SelectedIndex)
            {
            case 0:
                int discarded = 0;
                sendBytes = CNCRTools.GetBytes(txtHex.Text, out discarded);
                break;

            case 1:
                sendMsg   = new CNCRMsgPing();
                sendBytes = sendMsg.toSerial();
                break;

            case 2:
                sendMsg   = new CNCRMsgCmdAck(false, 127);
                sendBytes = sendMsg.toSerial();
                break;

            case 3:
                sendMsg   = new CNCRMsgEStop();
                sendBytes = sendMsg.toSerial();
                break;

            case 4:
                sendMsg   = new CNCRMsgRequestCommands(128);
                sendBytes = sendMsg.toSerial();
                break;

            case 5:
                sendMsg   = new CNCRMsgStartQueue(false);
                sendBytes = sendMsg.toSerial();
                break;

            case 6:
                sendMsg   = new CNCRMsgSetSpeed(true, true, false, 40000);
                sendBytes = sendMsg.toSerial();
                break;

            case 7:
                sendMsg   = new CNCRMsgMove(Int16.MinValue, Int16.MaxValue, 0);
                sendBytes = sendMsg.toSerial();
                break;

            case 8:
                sendMsg   = new CNCRMsgToolCmd(true);
                sendBytes = sendMsg.toSerial();
                break;
            }
            rtbTraffic.AppendText(CNCRTools.BytesToHex(sendBytes) + "\n");
            if (sendMsg == null)
            {
                commCmd.SendBytes(sendBytes);
            }
            else
            {
                commCmd.SendMsg(sendMsg);
            }
        }
Ejemplo n.º 21
0
 private void button2_Click(object sender, EventArgs e)
 {
     cmbRouterPort.Items.Clear();
     cmbRouterPort.Items.AddRange(CNCRTools.GetCNCRouterPorts());
     cmbRouterPort.SelectedIndex = 0;
 }