Esempio n. 1
0
        /// <summary>
        /// To Gcode CommandFrame
        /// </summary>
        /// <returns></returns>
        private static GcodeCommandFrame ToGcodeCommandFrame(IEnumerable <KeyValuePair <string, string> > frameSegments)
        {
            var gcodeCommandFrame = new GcodeCommandFrame();

            foreach (var frameSegment in frameSegments)
            {
                //команда
                var key = frameSegment.Key;
                //значение
                var value = frameSegment.Value;
                //получить свойство кадра
                var fieldInfo = gcodeCommandFrame.GetType().GetProperty(key);
                //свойство есть
                if (fieldInfo != null)
                {
                    //получить информацию свойства поля кадра
                    var fileldInfoType = fieldInfo.PropertyType;
                    // тип универсален, и универсальный тип - Nullable
                    if (fileldInfoType.IsGenericType && fileldInfoType.GetGenericTypeDefinition() == typeof(Nullable <>))
                    {
                        //объект назначения
                        var obj = gcodeCommandFrame;
                        //значение поля
                        var fieldValue = value;
                        //свойства поля кадра
                        fileldInfoType = fileldInfoType.GetGenericArguments()[0];
                        //указание значения сегмента кадра
                        fieldInfo.SetValue(obj, Convert.ChangeType(fieldValue, fileldInfoType, Culture));
                    }
                }
            }
            return(gcodeCommandFrame);
        }
Esempio n. 2
0
        public static List <byte[]> ParseG(GcodeCommandFrame gcodeFrame)
        {
            List <byte[]> listOfTXbuffs = new List <byte[]>();

            if (gcodeFrame.G.HasValue)
            {
                if (gcodeFrame.X.HasValue)
                {
                    //some how got speed and steps from planner
                    float    v     = 100f;
                    uint     x     = 123;
                    MovCmd_t cmdTX = new MovCmd_t
                    {
                        cw = new controlWord_t()
                        {
                            opcode = OpcodeEnum.g
                        },
                        drv1 = new axes_t()
                        {
                            freq = v, steps = x
                        }
                    };
                    listOfTXbuffs.Add(PackIntoByteArr(cmdTX));
                }
            }
            return(listOfTXbuffs);
        }
Esempio n. 3
0
        public void FrameSetTest4()
        {
            var frameset = new GcodeCommandSet();
            var frame    = new GcodeCommandFrame();

            frameset.GCodeCommandFrameSet.Add(frame);
            var c = frameset.GCodeCommandFrameSet;

            Assert.IsTrue(c.Count == 1);
        }
Esempio n. 4
0
 public void GcodeCommandFrameTest3()
 {
     for (var i = 0; i < 500; i++)
     {
         var frame = new GcodeCommandFrame {
             N = i
         };
         Assert.AreEqual(i, frame.N);
     }
 }
Esempio n. 5
0
 public void GcodeCommandFrameTest2()
 {
     for (var i = 0; i < 500; i++)
     {
         var frame = new GcodeCommandFrame {
             N = i
         };
         Assert.IsInstanceOfType(frame, typeof(GcodeCommandFrame));
     }
 }
Esempio n. 6
0
        public void ToJsonTest2()
        {
            var cmd = new GcodeCommandFrame {
                G       = 1,
                X       = 626.713,
                Y       = 251.523,
                E       = 12.01248,
                Comment = "Haha"
            };
            var          res      = cmd.ToJson();
            const string expected = "{\"G\":\"1\",\"X\":\"626.713\",\"Y\":\"251.523\",\"E\":\"12.01248\",\"Comment\":\"Haha\"}";

            Assert.AreEqual(expected, res);
        }
Esempio n. 7
0
        /// <summary>
        /// Команды в каждом кадре выполняются одновременно,
        /// поэтому порядок команд в кадре строго не оговаривается,
        /// но традиционно предполагается,
        /// что первыми указываются подготовительные команды
        /// (например, выбор рабочей плоскости, скоростей перемещений по осям и др.),
        /// затем задание координат перемещения,
        /// затем выбора режимов обработки и технологические команды.
        /// Максимальное число элементарных команд и заданий координат в одном кадре
        /// зависит от конкретного интерпретатора языка управления станками,
        /// но для большинства популярных интерпретаторов (стоек управления) не превышает 6.
        /// </summary>
        /// <param name="gcodeCommandFrame"></param>
        /// <param name="ignoreComments"></param>
        /// <returns></returns>
        public static string ToStringCommand(GcodeCommandFrame gcodeCommandFrame, bool ignoreComments = false)
        {
            var o = gcodeCommandFrame;
            var cmdSegmentStringBuilder = new StringBuilder();
            var objectProperties        = ReflectionUtils.GetProperties(o);
            var commentString           = string.Empty;
            var addedLines = 0;

            foreach (var objProp in objectProperties)
            {
                var commandSeparator = " ";
                var isNotEmpty       = !string.IsNullOrWhiteSpace(objProp.Value?.Trim());

                if (isNotEmpty)
                {
                    if (objProp.Key != "Comment")
                    {
                        var commandKey = objProp.Key;

                        if (addedLines == 0)
                        {
                            commandSeparator = string.Empty;
                        }

                        if (objProp.Key == "CheckSum" && !string.IsNullOrWhiteSpace(objProp.Value))
                        {
                            commandKey = "*";
                        }

                        var cmdFrameSegmentStr = $"{commandSeparator}{commandKey}{objProp.Value}";

                        cmdSegmentStringBuilder.Append(cmdFrameSegmentStr);
                        addedLines++;
                    }
                    else
                    {
                        if (!ignoreComments)
                        {
                            commentString = objProp.Value;
                        }
                    }
                }
            }

            var res = !string.IsNullOrWhiteSpace(commentString) ? $"{cmdSegmentStringBuilder} ;{commentString}" : cmdSegmentStringBuilder.ToString();

            return(res.Trim());
        }
Esempio n. 8
0
        /// <summary>
        /// To GCode
        /// </summary>
        /// <returns></returns>
        public static GcodeCommandFrame ToGCode(string raw)
        {
            _rawFrame = NormalizeRawFrame(raw.TrimString());
            var frameComment = string.Empty;
            //инициализация кадра
            var gcodeCommandFrame = new GcodeCommandFrame();

            //нет информации о кадре
            if (_rawFrame.IsNullOrErrorFrame())
            {
                return(new GcodeCommandFrame());
            }
            //пустой комментарий
            if (_rawFrame.IsEmptyComment())
            {
                gcodeCommandFrame.Comment = string.Empty;
                return(gcodeCommandFrame);
            }
            //является комментарием
            if (_rawFrame.IsComment())
            {
                gcodeCommandFrame.Comment = _rawFrame.ReplaceAtIndex(0, ' ').Trim();
                return(gcodeCommandFrame);
            }

            //содержит комментарий
            if (_rawFrame.ContainsComment())
            {
                var r = _rawFrame.Split(CommentChar);
                if (r.Length == 2)
                {
                    _rawFrame    = r[0].Trim();
                    frameComment = r[1].Trim();
                }
            }

            gcodeCommandFrame = ToGcodeCommandFrame(_rawFrame.HandleSegments());

            if (!string.IsNullOrWhiteSpace(frameComment))
            {
                gcodeCommandFrame.Comment = frameComment;
            }

            return(gcodeCommandFrame);
        }
Esempio n. 9
0
        /// <summary>
        /// Контрольная сумма кадра
        /// http://reprap.org/wiki/G-code#.2A:_Checksum
        /// Example: *71
        /// If present, the checksum should be the last field in a line, but before a comment.
        /// For G-code stored in files on SD cards the checksum is usually omitted.
        /// The firmware compares the checksum against a locally-computed value.
        /// If they differ, it requests a repeat transmission of the line.
        /// Checking Example
        /// N123 [...G Code in here...] *71
        /// The RepRap firmware checks the line number and the checksum.
        /// You can leave both of these out - RepRap will still work, but it won't do checking.
        /// You have to have both or neither though. If only one appears, it produces an error.
        /// </summary>
        /// <param name="gcodeCommandFrame">Кадр</param>
        /// <returns></returns>
        public static int FrameCrc(GcodeCommandFrame gcodeCommandFrame)
        {
            if (gcodeCommandFrame.N == 0)
            {
#pragma warning disable S112 // General exceptions should never be thrown
                throw new Exception("Frame line number expected (>0)");
#pragma warning restore S112 // General exceptions should never be thrown
            }

            var f     = GcodeParser.ToStringCommand(gcodeCommandFrame);
            var check = 0;
            foreach (var ch in f)
            {
                check ^= (ch & 0xff);
            }

            check ^= 32;

            return(check);
        }
Esempio n. 10
0
        public void GcodeCommandFrameTest1()
        {
            var frame = new GcodeCommandFrame();

            Assert.IsInstanceOfType(frame, typeof(GcodeCommandFrame));
        }
Esempio n. 11
0
        /// <summary>
        /// ToJson
        /// </summary>
        /// <param name="gcodeCommandFrame"></param>
        /// <returns></returns>
        public static string ToJson(this GcodeCommandFrame gcodeCommandFrame)
        {
            var resJson = ToStringCommand(gcodeCommandFrame);

            return(ToJson(resJson));
        }