Example #1
0
        public ScriptRunner(String base_path, ISerial serial_device, String script_path)
        {
            Script script = new Script();

            XmlSerializer s = new XmlSerializer(typeof(Script));

            try
            {
                using (StreamReader streamReader = new StreamReader(script_path))
                {
                    string fileContent = streamReader.ReadToEnd();
                    using (StringReader reader = new StringReader(fileContent))
                    {
                        script = (Script)s.Deserialize(reader);
                    }
                }


                buildScriptActions(base_path, serial_device, script);
            }

            catch (Exception e)
            {
                throw new MtuLoadException("Error loading Script file");
            }
        }
Example #2
0
        public void ParseScriptAndRun(String base_path, ISerial serial_device, String script_stream, int stream_size)
        {
            // Script file is empty
            if (string.IsNullOrEmpty(script_stream.Trim()))
            {
                Errors.LogErrorNowAndContinue(new ScriptEmptyException());
                this.OnError();

                return;
            }

            Script        script = new Script();
            XmlSerializer s      = new XmlSerializer(typeof(Script));

            try
            {
                using (StringReader reader = new StringReader(script_stream.Substring(0, stream_size)))
                {
                    script = (Script)s.Deserialize(reader);
                }
                buildScriptActions(base_path, serial_device, script);
            }
            catch (Exception e)
            {
                // Script file has invalid format or structure
                Errors.LogErrorNowAndContinue(new ScriptWrongStructureException());
                this.OnError();

                return;
            }

            this.Run();
        }
Example #3
0
        public Service()
        {
            var kernel = new StandardKernel(new YouCNC_Serial.DiModule.DiModule());

            kernel.Load(Assembly.GetExecutingAssembly());
            this.serial = kernel.Get <ISerial>();
        }
Example #4
0
 public TesterContext(Card card, ISerial serialPort)
 {
     this.card       = card;
     this.serialPort = serialPort;
     this.readThread = new ReadThread(serialPort);
     this.command    = new Command(serialPort);
 }
Example #5
0
        public static async Task <Eeprom> ReadEepromAsync(this ISerial serial)
        {
            uint[] values = await serial.GetEpromValuesAsync(SerialExtension.DefaultEpromTimeout);

            if (values != null)
            {
                var ee = new EepromV1 {
                    Values = values
                };

                if (ee.IsValid)
                {
                    File.WriteAllLines(Environment.ExpandEnvironmentVariables(@"%TEMP%\EepromRead.nc"), ee.ToGCode());
                    byte numAxis = ee[EepromV1.EValueOffsets8.NumAxis];

                    var eeprom = Eeprom.Create(ee[EepromV1.EValueOffsets32.Signature], numAxis);
                    eeprom.Values = values;
                    eeprom.ReadFrom(ee);

                    return(eeprom);
                }
            }

            return(null);
        }
Example #6
0
        private SimWorker()
        {
            _serial = new UsbSerial();
            _serial.ReceiveHandler += SerialPort_ReceiveHandler;
            _waitForSendDirectives  = new ConcurrentQueue <CompositeDirective>();

            Init().IgnorCompletion();
        }
        /// <summary>
        /// Send commands stored in a file. Wait until the commands are transferred and we got a reply (no command pending)
        /// </summary>
        /// <param name="serial"></param>
        /// <param name="filename">used for a StreamReader</param>
        /// <param name="waitForMilliseconds"></param>
        public static async Task <IEnumerable <SerialCommand> > SendFileAsync(this ISerial serial, string filename, int waitForMilliseconds = DefaultTimeout)
        {
            var list = await serial.QueueFileAsync(filename);

            await serial.WaitUntilQueueEmptyAsync(waitForMilliseconds);

            return(list);
        }
Example #8
0
 public void disconnect()
 {
     if (connected != null) {
         ISerial tmp = connected;
         connected = null;
         tmp.disconnect();
     }
 }
 /// <summary>
 /// write all pending (command with no reply) to file
 /// Intended to be used if user abort queue because of an error
 /// </summary>
 /// <param name="serial"></param>
 /// <param name="filename"></param>
 public static void WritePendingCommandsToFile(this ISerial serial, string filename)
 {
     using (var sw = new StreamWriter(Environment.ExpandEnvironmentVariables(filename)))
     {
         foreach (SerialCommand cmd in serial.PendingCommands)
         {
             sw.WriteLine(cmd.CommandText);
         }
     }
 }
Example #10
0
        public static async Task <uint[]> GetEpromValuesAsync(this ISerial serial, int waitForMilliseconds)
        {
            var cmd = (await serial.SendCommandAsync("$?", waitForMilliseconds)).FirstOrDefault();

            if (cmd != null && string.IsNullOrEmpty(cmd.ResultText) == false)
            {
                string[] separators = { "\n", "\r" };
                string[] lines      = cmd.ResultText.Split(separators, StringSplitOptions.RemoveEmptyEntries);
                var      intValues  = new Dictionary <int, uint>();
                int      maxSlot    = -1;
                foreach (var line in lines)
                {
                    // e.g. $1=65535(ffff)
                    string[] assign = line.Split('=');

                    int slot;
                    if (assign.Length == 2 && assign[0].StartsWith("$") && int.TryParse(assign[0].TrimStart('$'), out slot))
                    {
                        uint   slotValue;
                        string valueStr = assign[1];
                        int    idx1     = valueStr.IndexOf('(');
                        if (idx1 > 0)
                        {
                            valueStr = valueStr.Substring(0, idx1);
                        }

                        if (uint.TryParse(valueStr, out slotValue))
                        {
                            intValues[slot] = slotValue;
                            if (maxSlot < slot)
                            {
                                maxSlot = slot;
                            }
                        }
                    }
                }

                if (maxSlot > 0)
                {
                    var ret = new uint[maxSlot + 1];
                    for (int i = 0; i <= maxSlot; i++)
                    {
                        if (intValues.ContainsKey(i))
                        {
                            ret[i] = intValues[i];
                        }
                    }

                    return(ret);
                }
            }

            return(null);
        }
Example #11
0
        public void GetLastLogQueryResult(ISerial serial, int timeout)
        {
            List <byte> list = new List <byte>(5);

            list.Add(37);
            list.Add(254);
            list.Add(21);
            list.Add(0);
            list.Add(GetChecksum(list));

            byte[] stream = list.ToArray();

            serial.Write(stream, 0, stream.Length);

            byte[] rawBuffer       = new byte[10];
            int    response_offest = 0;

            if (serial.isEcho())
            {
                response_offest = stream.Length;
            }
            Array.Resize(ref rawBuffer, (int)(response_offest + 5));

            long timeout_limit = DateTimeOffset.Now.ToUnixTimeMilliseconds() + (timeout);

            while (serial.BytesToRead() < rawBuffer.Length)
            {
                if (DateTimeOffset.Now.ToUnixTimeMilliseconds() > timeout_limit)
                {
                    //if even no data response no puck error..

                    if (serial.BytesToRead() <= response_offest)
                    {
                        throw new IOException();
                    }
                    else
                    {
                        throw new TimeoutException();
                    }
                }
                Thread.Sleep(10);
            }

            serial.Read(rawBuffer, 0, rawBuffer.Length);

            byte[] response = new byte[5];
            Array.Copy(rawBuffer, response.Length, response, 0, response.Length);

            if (response[0] != 0x06)
            {
                throw new LexiWriteException(response);
            }
        }
Example #12
0
        public Action(Configuration config, ISerial serial, ActionType type, String user = "", String outputfile = "")
        {
            // outputfile = new FileInfo ( outputfile ).Name; // NO
            // System.IO.Path.GetFileName(outputfile)); // NO

            configuration = config;
            logger        = new Logger(config, outputfile.Substring(outputfile.LastIndexOf('\\') + 1));
            comm          = new MTUComm(serial, config);
            this.type     = type;
            this.user     = user;
            comm.OnError += Comm_OnError;
        }
Example #13
0
 public static void WriteCommandHistory(this ISerial serial, string filename)
 {
     using (var sr = new StreamWriter(Environment.ExpandEnvironmentVariables(filename)))
     {
         foreach (SerialCommand cmds in serial.CommandHistoryCopy)
         {
             sr.Write(cmds.SentTime); sr.Write(":");
             sr.Write(cmds.CommandText); sr.Write(" => ");
             sr.WriteLine(cmds.ResultText);
         }
     }
 }
        public static async Task <bool> SendProbeCommandAsync(this ISerial serial, string axisName, decimal probeSize, decimal probeDist, decimal probeDistUp, decimal probeFeed)
        {
            var result = await serial.SendCommandAsync($"g91 g31 {axisName}-{probeDist.ToString(CultureInfo.InvariantCulture)} F{probeFeed.ToString(CultureInfo.InvariantCulture)} g90", GCodeSerial.DefaultProbeTimeout);

            if (result?.LastOrDefault()?.ReplyType.HasFlag(EReplyType.ReplyError) == false)
            {
                serial.QueueCommand($"g92 {axisName}{(-probeSize).ToString(CultureInfo.InvariantCulture)}");
                serial.QueueCommand($"g91 g0 {axisName}{probeDistUp.ToString(CultureInfo.InvariantCulture)} g90");
                return(true);
            }

            return(false);
        }
Example #15
0
 /// <summary>
 /// Send commands stored in a file. Wait until the commands are transferrd and we got a reply (no command pending)
 /// </summary>
 /// <param name="filename">used for a StreamReader</param>
 public static async Task <IEnumerable <SerialCommand> > QueueFileAsync(this ISerial serial, string filename)
 {
     using (var sr = new StreamReader(filename))
     {
         string line;
         var    lines = new List <string>();
         while ((line = sr.ReadLine()) != null)
         {
             lines.Add(line);
         }
         return(await serial.QueueCommandsAsync(lines.ToArray()));
     }
 }
Example #16
0
        /// <summary>
        /// Send a command to the arduino and wait until a (OK) reply
        /// Queue must be empty
        /// </summary>
        /// <param name="line">command line</param>
        /// <param name="waitForMilliseconds"></param>
        /// <returns>ok result from arduino or empty(if error)</returns>
        public static async Task <string> SendCommandAndReadOKReplyAsync(this ISerial serial, string line, int waitForMilliseconds)
        {
            var ret = await serial.SendCommandAsync(line, waitForMilliseconds);

            if (ret.Any())
            {
                var last = ret.Last();
                if (last.ReplyType.HasFlag(EReplyType.ReplyOK))
                {
                    return(last.ResultText);
                }
            }
            return(null);
        }
Example #17
0
        public static async Task <IEnumerable <IEnumerable <decimal> > > GetPosition(this ISerial serial, string commandPrefix)
        {
            string message = await serial.SendCommandAndReadOKReplyAsync($"{commandPrefix}?", 10 * 1000);

            var ret = new List <IEnumerable <decimal> >();

            if (!string.IsNullOrEmpty(message))
            {
                if (message.Contains("MPos:"))
                {
                    // new or grbl format
                    message = message.Replace("ok", "").Replace("<", "").Replace(">", "").Trim();

                    string[] tags = message.Split('|');

                    var mPos = TryConvert(tags, "MPos:");
                    if (mPos != null)
                    {
                        ret.Add(mPos.ToArray());

                        var wco = TryConvert(tags, "WCO:");
                        if (wco != null)
                        {
                            for (int i = 0; i < wco.Length; i++)
                            {
                                mPos[i] -= wco[i];
                            }
                        }

                        ret.Add(mPos);
                    }
                }
                else
                {
                    decimal[] mPos = Convert(message, "dummy");
                    ret.Add(mPos);

                    message = await serial.SendCommandAndReadOKReplyAsync($"{commandPrefix}m114 s1", 10 * 1000);

                    if (!string.IsNullOrEmpty(message))
                    {
                        decimal[] rPos = Convert(message, "dummy");
                        ret.Add(rPos);
                    }
                }
            }

            return(ret);
        }
Example #18
0
        public static async Task <decimal?> GetParameterValueAsync(this ISerial serial, int parameter, string commandPrefix)
        {
            string message = await serial.SendCommandAndReadOKReplyAsync($"{commandPrefix}(print, #{parameter})", 10 * 1000);

            if (!string.IsNullOrEmpty(message))
            {
                // expected response : 0\nok
                string pos = message.Split('\n').FirstOrDefault();
                if (decimal.TryParse(pos, NumberStyles.Any, CultureInfo.InvariantCulture, out decimal val))
                {
                    return(val);
                }
            }

            return(null);
        }
Example #19
0
        private EventCalls SubscribeForEventCall(ISerial serial)
        {
            var eventcounts = new EventCalls();

            serial.WaitForSend         += (sender, e) => eventcounts.EventWaitForSend++;
            serial.CommandSending      += (sender, e) => eventcounts.EventCommandSending++;
            serial.CommandSent         += (sender, e) => eventcounts.EventCommandSent++;
            serial.WaitCommandSent     += (sender, e) => eventcounts.EventWaitCommandSent++;
            serial.ReplyReceived       += (sender, e) => eventcounts.EventReplyReceived++;
            serial.ReplyOK             += (sender, e) => eventcounts.EventReplyOK++;
            serial.ReplyError          += (sender, e) => eventcounts.EventReplyError++;
            serial.ReplyInfo           += (sender, e) => eventcounts.EventReplyInfo++;
            serial.ReplyUnknown        += (sender, e) => eventcounts.EventReplyUnknown++;
            serial.CommandQueueChanged += (sender, e) => eventcounts.EventCommandQueueChanged++;
            serial.CommandQueueEmpty   += (sender, e) => eventcounts.EventCommandQueueEmpty++;
            return(eventcounts);
        }
Example #20
0
        private ISerialPort CreateSerialPortMock(ISerial serial, string[] responsstrings)
        {
            var serialport = Substitute.For <ISerialPort>();
            var basestream = Substitute.For <MemoryStream>();

            serialport.BaseStream.ReturnsForAnyArgs(basestream);
            Encoding encoding = Encoding.GetEncoding(1200);

            serialport.Encoding.ReturnsForAnyArgs(encoding);

            Tools.Dependency.Dependency.Container.ResetContainer();
            Tools.Dependency.Dependency.Container.RegisterInstance(serialport);

            int  resultidx = 0;
            bool sendReply = false;

            basestream.WriteAsync(Arg.Any <byte[]>(), Arg.Any <int>(), Arg.Any <int>(), Arg.Any <System.Threading.CancellationToken>()).
            ReturnsForAnyArgs(async x =>
            {
                sendReply = true;
                await Task.FromResult(0);
            });


            basestream.ReadAsync(Arg.Any <byte[]>(), Arg.Any <int>(), Arg.Any <int>(), Arg.Any <System.Threading.CancellationToken>()).
            ReturnsForAnyArgs(async x =>
            {
                if (sendReply)
                {
                    await Task.Delay(10);
                    sendReply         = false;
                    byte[] encodedStr = encoding.GetBytes(responsstrings[resultidx++]);
                    for (int i = 0; i < encodedStr.Length; i++)
                    {
                        ((byte[])x[0])[i] = encodedStr[i];
                    }

                    return(encodedStr.Length);
                }

                await Task.Delay(10);
                return(0);
            });

            return(serialport);
        }
Example #21
0
        public void ParseScriptAndRun(ISerial serial_device, String script_stream, int stream_size)
        {
            XmlSerializer s = null;

            try
            {
                // Script file is empty
                if (string.IsNullOrEmpty(script_stream.Trim()))
                {
                    throw new ScriptEmptyException();
                }

                Script script = new Script();
                s = new XmlSerializer(typeof(Script));

                // Register unknown elements ( not present in Script class ) as additional parameters
                s.UnknownElement += this.UnknownElementEvent;

                using (StringReader reader = new StringReader(script_stream.Substring(0, stream_size)))
                {
                    script = ( Script )s.Deserialize(reader);
                }
                BuildScriptActions(serial_device, script);
            }
            catch (Exception e)
            {
                if (!Errors.IsOwnException(e))
                {
                    Errors.LogErrorNowAndContinue(new ScriptWrongStructureException());      // Script file has invalid format or structure
                }
                else
                {
                    Errors.LogErrorNowAndContinue(e);     // ScriptLogfileInvalidException, ScriptActionTypeInvalidException
                }
                this.OnError();

                return;
            }
            finally
            {
                s.UnknownElement -= this.UnknownElementEvent;
            }

            this.Run();
        }
Example #22
0
        public void Cancel()
        {
            if (_cancelTokenSource != null)
            {
                if (!_cancelTokenSource.IsCancellationRequested)
                {
                    _cancelTokenSource.Cancel();
                }
            }

            if (_serialPort != null)
            {
                _serialPort.ReceiveHandler -= SpHelper_ReceiveHandler;
                _serialPort = null;
            }

            _waitForFeedbackDirectives.Clear();
        }
Example #23
0
        public static async Task <bool> WriteEepromAsync(this ISerial serial, Eeprom eepromValue)
        {
            var ee = new EepromV1 {
                Values = eepromValue.Values
            };

            if (ee.IsValid)
            {
                eepromValue.WriteTo(ee);

                File.WriteAllLines(Environment.ExpandEnvironmentVariables(@"%TEMP%\EepromWrite.nc"), ee.ToGCode());

                await serial.WriteEepromValuesAsync(ee);

                return(true);
            }

            return(false);
        }
Example #24
0
        public static async Task <bool> SendProbeCommandAsync(this ISerial serial, Machine machine, int axisIndex)
        {
            string  axisName  = machine.GetAxisName(axisIndex);
            decimal probeSize = machine.GetProbeSize(axisIndex);

            string probDist   = machine.ProbeDist.ToString(CultureInfo.InvariantCulture);
            string probDistUp = machine.ProbeDistUp.ToString(CultureInfo.InvariantCulture);
            string probFeed   = machine.ProbeFeed.ToString(CultureInfo.InvariantCulture);

            var result = await serial.SendCommandAsync("g91 g31 " + axisName + "-" + probDist + " F" + probFeed + " g90", DefaultProbeTimeout);

            if (result?.LastOrDefault()?.ReplyType.HasFlag(EReplyType.ReplyError) == false)
            {
                serial.QueueCommand("g92 " + axisName + (-probeSize).ToString(CultureInfo.InvariantCulture));
                serial.QueueCommand("g91 g0" + axisName + probDistUp + " g90");
                return(true);
            }

            return(false);
        }
Example #25
0
        public void ParseScriptAndRun(ISerial serial_device, String script_stream, int stream_size)
        {
            // Script file is empty
            if (string.IsNullOrEmpty(script_stream.Trim()))
            {
                Errors.LogErrorNowAndKill(new ScriptEmptyException());
                //this.OnError ();

                return;
            }

            Script        script = new Script();
            XmlSerializer s      = new XmlSerializer(typeof(Script));

            try
            {
                using (StringReader reader = new StringReader(script_stream.Substring(0, stream_size)))
                {
                    script = (Script)s.Deserialize(reader);
                }
                buildScriptActions(serial_device, script);
            }
            catch (Exception e)
            {
                if (!Errors.IsOwnException(e))
                {
                    Errors.LogErrorNowAndKill(new ScriptWrongStructureException());      // Script file has invalid format or structure
                }
                else
                {
                    Errors.LogErrorNowAndKill(e);     // ScriptLogfileInvalidException, ScriptActionTypeInvalidException
                }
                //this.OnError ();

                return;
            }

            this.Run();
        }
Example #26
0
        public Action(Configuration config, ISerial serial, ActionType type, String user = "", String outputfile = "")
        {
            // outputfile = new FileInfo ( outputfile ).Name; // NO
            // System.IO.Path.GetFileName(outputfile)); // NO

            configuration = config;
            logger        = new Logger(outputfile.Substring(outputfile.LastIndexOf('\\') + 1));
            comm          = new MTUComm(serial, config);
            this.type     = type;
            this.user     = user;
            comm.OnError += Comm_OnError;

            this.config = Singleton.Get.Configuration;

            // Only save reference for the current action,
            // not for nested or auxiliary actions ( as BasicRead )
            if (this.type != ActionType.BasicRead &&
                !Singleton.Has <Action> ())
            {
                Singleton.Set = this;
            }
        }
Example #27
0
        public static async Task SendMacroCommandAsync(this ISerial serial, Machine machine, string commandString)
        {
            string[] separators = { @"\n" };
            string[] cmds       = commandString.Split(separators, StringSplitOptions.RemoveEmptyEntries);
            foreach (string s in cmds)
            {
                string[] infos = s.Split(':');
                int      axis;

                if (infos.Length > 1 && string.Compare(infos[0], @";probe", true) == 0 && -1 != (axis = GCodeHelper.AxisNameToIndex(infos[1])))
                {
                    if (false == await serial.SendProbeCommandAsync(machine, axis))
                    {
                        break;
                    }
                }
                else if (infos.Length == 1 && string.Compare(infos[0], @";beep", true) == 0)
                {
                    SystemSounds.Beep.Play();
                }
                else
                {
                    if (s.TrimEnd().EndsWith("?"))
                    {
                        var result = await serial.SendCommandAsync(s.TrimEnd().TrimEnd('?'), GCodeSerial.DefaultTimeout);

                        if (result?.LastOrDefault()?.ReplyType.HasFlag(EReplyType.ReplyError) == false)
                        {
                            return;
                        }
                    }
                    else
                    {
                        await serial.SendCommandAsync(s, GCodeSerial.DefaultTimeout);
                    }
                }
            }
        }
Example #28
0
 public Requests(ISerial serial)
 {
     Serial = serial;
     Serial.DataReceived += data =>
     {
         //Очень не уверен, что это заработает. Надо дебажить!
         if (data.Length != 9)
         {
             return;
         }
         if ((data[0] != 0xAA) ||
             (data[1] != 0xAB) ||
             (data[2] != 0xAC) ||
             (data[7] != 0x55) ||
             (data[8] != 0x55))
         {
             return;
         }
         var adc_data = new int[2];
         adc_data[0] = (data[4] << 16) + (data[3] << 8);
         adc_data[1] = (data[6] << 16) + (data[5] << 8);
         MeasureDataHandler?.Invoke(adc_data);
     };
 }
Example #29
0
 /**************************External interaction stuff*****************/
 //connect an interface to a slot
 public void connect(ISerial toConnect, int slot)
 {
     CPU.SerialInterfaces[slot].disconnect();
     CPU.SerialInterfaces[slot].connect(toConnect);
     toConnect.connect(CPU.SerialInterfaces[slot]);
 }
Example #30
0
 public SLIP(ISerial dev)
 {
     this.Device = dev;
 }
Example #31
0
 public void SetCurrent(string portName)
 {
     Current = portName.StartsWith("com") ? LocalCom : RemoteCom;
 }
Example #32
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Lexi.Lexi" /> class.
 /// </summary>
 /// <param name="serial"></param>
 /// <param name="timeout"></param>
 public Lexi(ISerial serial, int timeout)
 {
     m_serial  = serial;
     m_timeout = timeout;
 }
Example #33
0
 public void disconnect()
 {
     connected = null;
 }
Example #34
0
 public void connect(ISerial sBus)
 {
     connected = sBus;
 }
Example #35
0
 //TODO:
 //make interact with memory, sending/receiving bits etc.
 //  0:  flags register
 //      bits:   0:  interrupt enable
 //              1:  output buffer empty
 //              2:  input buffer full
 //              3:  sending
 //              4:  receiving
 //              5:  recipient ready
 //  1:  receive reg
 //  2:  send reg
 //  3:  reserved
 public SerialBus(UInt16 memLocation, Int32[] mem)
 {
     memPointer = memLocation;
     localMemRef = mem;
     connected = null;
 }