Beispiel #1
0
        public MachinaBridgeWindow()
        {
            InitializeComponent();

            dc = new BoundContent(this);

            DataContext = dc;

            uiContext = SynchronizationContext.Current;

            _maxLogLevel          = Machina.LogLevel.VERBOSE;
            Logger.CustomLogging += Logger_CustomLogging;

            Logger.Info("Machina Bridge: " + Version + "; Core: " + Robot.Version);

            InitializeWebSocketServer();

            // Handle pasting text on the input
            DataObject.AddPastingHandler(InputBlock, InputBlock_Paste);

#if DEBUG
            var item = combo_LogLevel.Items.GetItemAt(5) as ComboBoxItem;
            item.IsSelected = true;
#endif
        }
Beispiel #2
0
        private bool ParseWebSocketURL()
        {
            string url = txtbox_WSServerURL.Text;

            string[] parts = url.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
            // Should be something like {"ws:", "127.0.0.1", "route" [, ...] }
            if (parts.Length < 3)
            {
                Logger.Error("Please add a route to the websocket url, like \"/Bridge\"");
                return(false);
            }
            else if (!parts[0].Equals("ws:", StringComparison.InvariantCultureIgnoreCase))
            {
                Logger.Error("WebSocket URL must start with \"ws:\"");
                return(false);
            }
            else if (!Machina.Net.Net.ValidateIPv4Port(parts[1]))
            {
                Logger.Error("Invalid IP:Port address \"" + parts[1] + "\"");
                return(false);
            }

            wssvURL      = parts[0] + "//" + parts[1];
            wssvBehavior = "/" + String.Join("/", parts, 2, parts.Length - 2);

            Logger.Debug("WebSocket server URL: " + wssvURL);
            Logger.Debug("WebSocket server route: " + wssvBehavior);

            return(true);
        }
 private void cbx_FollowPointer_Unchecked(object sender, RoutedEventArgs e)
 {
     if (dc != null)
     {
         Logger.Debug("Follow program pointer deactivated.");
         dc.queueFollowPointer = false;
     }
 }
Beispiel #4
0
        /// <summary>
        /// Print error when wrong tool is metioned. Function only works for creating of tools atm
        /// line number will automatically change.
        /// </summary>
        /// <param name="tool"></param>
        private void ErrorWithLineNum(string tool)
        {
            StackFrame stackFrame = new StackFrame(1, true);

            int line = stackFrame.GetFileLineNumber();

            Logger.Error($"tool {tool} doesn't exists yet in the source code." +
                         $"source code needs to be edited at MainWindow.xaml.cs line {line} ");
        }
 private void StopWebSocketClient()
 {
     if (wscl != null)
     {
         Logger.Verbose("Stopping WebSocket client on " + wscl.Url);
         wscl.Close();
         wscl = null;
     }
 }
Beispiel #6
0
 private void StopWebSocketServer()
 {
     if (wssv != null)
     {
         Logger.Verbose("Stopping WebSocket service on " + wssv.Address + ":" + wssv.Port + wssv.WebSocketServices.Paths.ElementAt(0));
         wssv.Stop();
         wssv = null;
     }
 }
        private void Wscl_OnMessage(object sender, MessageEventArgs e)
        {
            if (bot == null)
            {
                wscl.Send($"{{\"event\":\"controller-disconnected\"}}");
                return;
            }

            //Logger.Verbose("Action from \"" + _clientName + "\": " + e.Data);
            Logger.Verbose("Instruction/s received from Machina Server: " + e.Data);

            ExecuteInstructionsOnContext(e.Data);
        }
        protected override void OnClose(CloseEventArgs e)
        {
            //base.OnClose(e);
            Logger.Debug($"WS client disconnected: {e.Code} {e.Reason}");
            Logger.Warning("Client \"" + _clientName + "\" disconnected...");
            _parent._connectedClients.Remove(_clientName);
            //_parent.UpdateClientBox();
            _parent.uiContext.Post(x =>
            {
                _parent.UpdateClientBox();
            }, null);

            _parent.wssv.WebSocketServices.Broadcast($"{{\"event\":\"client-disconnected\",\"user\":\"clientname\"}}");
        }
        protected override void OnMessage(MessageEventArgs e)
        {
            //base.OnMessage(e);
            //Console.WriteLine("  BRIDGE: received message: " + e.Data);
            if (_robot == null || _parent.bot == null)
            {
                _parent.wssv.WebSocketServices.Broadcast($"{{\"event\":\"controller-disconnected\"}}");
                return;
            }

            Logger.Verbose("Action from \"" + _clientName + "\": " + e.Data);

            _parent.ExecuteInstructionsOnContext(e.Data);
        }
        protected override void OnOpen()
        {
            //base.OnOpen();
            //Console.WriteLine("  BRIDGE: opening bridge");
            _clientName = Context.QueryString["name"];
            _parent._connectedClients.Add(_clientName);
            //_parent.UpdateClientBox();
            _parent.uiContext.Post(x =>
            {
                _parent.UpdateClientBox();
            }, null);

            Logger.Info("Client \"" + _clientName + "\" connected...");
        }
        // Figures out if auto-scroll, and deactivates follow pointer if not
        private void QueueScroller_ScrollChanged(object sender, ScrollChangedEventArgs e)
        {
            // Figure out if this was related to auto scrolling
            if (e.VerticalChange == 0.0 ||
                e.ExtentHeight == 0 ||
                e.ExtentHeightChange > 0)
            {
                return;
            }

            if (isUserScroll && dc.queueFollowPointer)
            {
                Logger.Debug("Manual scroll detected, deactivating 'Follow Pointer'.");
                dc.queueFollowPointer       = false;
                cbx_FollowPointer.IsChecked = false;
                cbx_FollowPointer_Unchecked(null, null);
            }

            isUserScroll = true;
        }
Beispiel #12
0
        private bool InitializeWebSocketServer()
        {
            if (!ParseWebSocketURL())
            {
                Logger.Error("Invalid WebSocket URL \"" + txtbox_WSServerURL.Text + "\"; try something like \"ws://127.0.0.1/Bridge\"");
                return(false);
            }

            if (wssv != null && wssv.IsListening)
            {
                StopWebSocketServer();
            }

            wssv = new WebSocketServer(wssvURL);
            wssv.AddWebSocketService(wssvBehavior, () => new BridgeBehavior(bot, this));

            // @TODO: add a check here if the port is in use, and try a different port instead
            try
            {
                wssv.Start();
            }
            catch
            {
                Logger.Error("Default websocket server is not available, please enter a new one manually...");
                return(false);
            }

            if (wssv.IsListening)
            {
                //Machina.Logger.Info($"Listening on port {wssv.Port}, and providing WebSocket services:");
                //foreach (var path in wssv.WebSocketServices.Paths) Machina.Logger.Info($"- {path}");
                Logger.Info("Waiting for incoming connections on " + (wssvURL + wssvBehavior));
            }

            return(true);
            //lbl_ServerURL.Content = wssvURL + wssvBehavior;
        }
Beispiel #13
0
        public bool ExecuteInstruction(string instruction)
        {
            string[] args = Machina.Utilities.Parsing.ParseStatement(instruction);
            if (args == null || args.Length == 0)
            {
                Machina.Logger.Error($"I don't understand \"{instruction}\"...");
                return(false);
            }

            // This is horrible, but oh well...
            if (args[0].Equals("MotionMode", StringComparison.CurrentCultureIgnoreCase))
            {
                try
                {
                    return(bot.MotionMode(args[1]));
                }
                catch (Exception ex)
                {
                    BadFormatInstruction(instruction, ex);
                    return(false);
                }
            }
            else if (args[0].Equals("Speed", StringComparison.CurrentCultureIgnoreCase))
            {
                try
                {
                    return(bot.Speed(Convert.ToDouble(args[1])));
                }
                catch (Exception ex)
                {
                    BadFormatInstruction(instruction, ex);
                    return(false);
                }
            }
            else if (args[0].Equals("SpeedTo", StringComparison.CurrentCultureIgnoreCase))
            {
                try
                {
                    return(bot.SpeedTo(Convert.ToDouble(args[1])));
                }
                catch (Exception ex)
                {
                    BadFormatInstruction(instruction, ex);
                    return(false);
                }
            }
            else if (args[0].Equals("Acceleration", StringComparison.CurrentCultureIgnoreCase))
            {
                try
                {
                    return(bot.Acceleration(Convert.ToDouble(args[1])));
                }
                catch (Exception ex)
                {
                    BadFormatInstruction(instruction, ex);
                    return(false);
                }
            }
            else if (args[0].Equals("AccelerationTo", StringComparison.CurrentCultureIgnoreCase))
            {
                try
                {
                    return(bot.AccelerationTo(Convert.ToDouble(args[1])));
                }
                catch (Exception ex)
                {
                    BadFormatInstruction(instruction, ex);
                    return(false);
                }
            }
            else if (args[0].Equals("Precision", StringComparison.CurrentCultureIgnoreCase))
            {
                try
                {
                    return(bot.Precision(Convert.ToDouble(args[1])));
                }
                catch (Exception ex)
                {
                    BadFormatInstruction(instruction, ex);
                    return(false);
                }
            }
            else if (args[0].Equals("PrecisionTo", StringComparison.CurrentCultureIgnoreCase))
            {
                try
                {
                    return(bot.PrecisionTo(Convert.ToDouble(args[1])));
                }
                catch (Exception ex)
                {
                    BadFormatInstruction(instruction, ex);
                    return(false);
                }
            }
            else if (args[0].Equals("Coordinates", StringComparison.CurrentCultureIgnoreCase))
            {
                bot.Logger.Error($"\"{args[0]}\" is still not implemented.");
                return(false);
            }
            else if (args[0].Equals("Temperature", StringComparison.CurrentCultureIgnoreCase) || args[0].Equals("TemperatureTo", StringComparison.CurrentCultureIgnoreCase))
            {
                bot.Logger.Error($"\"{args[0]}\" is still not implemented.");
                return(false);
            }
            else if (args[0].Equals("ExtrusionRate", StringComparison.CurrentCultureIgnoreCase) || args[0].Equals("ExtrusionRateTo", StringComparison.CurrentCultureIgnoreCase))
            {
                bot.Logger.Error($"\"{args[0]}\" is still not implemented.");
                return(false);
            }
            else if (args[0].Equals("PushSettings", StringComparison.CurrentCultureIgnoreCase))
            {
                bot.PushSettings();
                return(true);
            }
            else if (args[0].Equals("PopSettings", StringComparison.CurrentCultureIgnoreCase))
            {
                bot.PopSettings();
                return(true);
            }
            else if (args[0].Equals("Move", StringComparison.CurrentCultureIgnoreCase))
            {
                try
                {
                    return(bot.Move(Convert.ToDouble(args[1]), Convert.ToDouble(args[2]), Convert.ToDouble(args[3])));
                }
                catch (Exception ex)
                {
                    BadFormatInstruction(instruction, ex);
                    return(false);
                }
            }
            else if (args[0].Equals("MoveTo", StringComparison.CurrentCultureIgnoreCase))
            {
                try
                {
                    return(bot.MoveTo(Convert.ToDouble(args[1]), Convert.ToDouble(args[2]), Convert.ToDouble(args[3])));
                }
                catch (Exception ex)
                {
                    BadFormatInstruction(instruction, ex);
                    return(false);
                }
            }
            else if (args[0].Equals("Rotate", StringComparison.CurrentCultureIgnoreCase))
            {
                try
                {
                    return(bot.Rotate(Convert.ToDouble(args[1]), Convert.ToDouble(args[2]), Convert.ToDouble(args[3]), Convert.ToDouble(args[4])));
                }
                catch (Exception ex)
                {
                    BadFormatInstruction(instruction, ex);
                    return(false);
                }
            }
            else if (args[0].Equals("RotateTo", StringComparison.CurrentCultureIgnoreCase))
            {
                try
                {
                    return(bot.RotateTo(Convert.ToDouble(args[1]), Convert.ToDouble(args[2]), Convert.ToDouble(args[3]),
                                        Convert.ToDouble(args[4]), Convert.ToDouble(args[5]), Convert.ToDouble(args[6])));
                }
                catch (Exception ex)
                {
                    BadFormatInstruction(instruction, ex);
                    return(false);
                }
            }
            else if (args[0].Equals("Transform", StringComparison.CurrentCultureIgnoreCase))
            {
                bot.Logger.Error($"\"{args[0]}\" is still not implemented.");
                return(false);
            }
            else if (args[0].Equals("TransformTo", StringComparison.CurrentCultureIgnoreCase))
            {
                try
                {
                    return(bot.TransformTo(Convert.ToDouble(args[1]), Convert.ToDouble(args[2]), Convert.ToDouble(args[3]),
                                           Convert.ToDouble(args[4]), Convert.ToDouble(args[5]), Convert.ToDouble(args[6]),
                                           Convert.ToDouble(args[7]), Convert.ToDouble(args[8]), Convert.ToDouble(args[9])));
                }
                catch (Exception ex)
                {
                    BadFormatInstruction(instruction, ex);
                    return(false);
                }
            }
            else if (args[0].Equals("Axes", StringComparison.CurrentCultureIgnoreCase))
            {
                try
                {
                    return(bot.Axes(Convert.ToDouble(args[1]), Convert.ToDouble(args[2]), Convert.ToDouble(args[3]),
                                    Convert.ToDouble(args[4]), Convert.ToDouble(args[5]), Convert.ToDouble(args[6])));
                }
                catch (Exception ex)
                {
                    BadFormatInstruction(instruction, ex);
                    return(false);
                }
            }
            else if (args[0].Equals("AxesTo", StringComparison.CurrentCultureIgnoreCase))
            {
                try
                {
                    return(bot.AxesTo(Convert.ToDouble(args[1]), Convert.ToDouble(args[2]), Convert.ToDouble(args[3]),
                                      Convert.ToDouble(args[4]), Convert.ToDouble(args[5]), Convert.ToDouble(args[6])));
                }
                catch (Exception ex)
                {
                    BadFormatInstruction(instruction, ex);
                    return(false);
                }
            }
            else if (args[0].Equals("ExternalAxis", StringComparison.CurrentCultureIgnoreCase))
            {
                try
                {
                    int    axisNumber;
                    double increment;
                    if (!Int32.TryParse(args[1], out axisNumber) || axisNumber < 1 || axisNumber > 6)
                    {
                        Logger.Error($"Invalid axis number");
                        return(false);
                    }

                    if (!Double.TryParse(args[2], out increment))
                    {
                        Logger.Error($"Invalid increment value");
                        return(false);
                    }

                    string target = "All";
                    if (args.Length > 3)
                    {
                        target = args[3];
                    }

                    return(bot.ExternalAxis(axisNumber, increment, target));
                }
                catch (Exception ex)
                {
                    BadFormatInstruction(instruction, ex);
                    return(false);
                }
            }
            else if (args[0].Equals("ExternalAxisTo", StringComparison.CurrentCultureIgnoreCase))
            {
                try
                {
                    int    axisNumber;
                    double val;
                    if (!Int32.TryParse(args[1], out axisNumber) || axisNumber < 1 || axisNumber > 6)
                    {
                        Logger.Error($"Invalid axis number");
                        return(false);
                    }

                    if (!Double.TryParse(args[2], out val))
                    {
                        Logger.Error($"Invalid value " + args[2]);
                        return(false);
                    }

                    string target = "All";
                    if (args.Length > 3)
                    {
                        target = args[3];
                    }

                    return(bot.ExternalAxisTo(axisNumber, val, target));
                }
                catch (Exception ex)
                {
                    BadFormatInstruction(instruction, ex);
                    return(false);
                }
            }
            else if (args[0].Equals("ArmAngle", StringComparison.CurrentCultureIgnoreCase))
            {
                Logger.Warning(
                    "Relative `ArmAngle` is temporarily disabled, please use the absolute `ArmAngleTo` version instead.");
                //try
                //{
                //    double val;

                //    if (!Double.TryParse(args[1], out val))
                //    {
                //        Console.WriteLine($"ERROR: Invalid value " + args[1]);
                //        return false;
                //    }

                //    return bot.ArmAngle(val);
                //}
                //catch (Exception ex)
                //{
                //    BadFormatInstruction(instruction, ex);
                //    return false;
                //}
            }
            else if (args[0].Equals("ArmAngleTo", StringComparison.CurrentCultureIgnoreCase))
            {
                try
                {
                    double val;

                    if (!Double.TryParse(args[1], out val))
                    {
                        Logger.Error($"Invalid value " + args[1]);
                        return(false);
                    }

                    return(bot.ArmAngleTo(val));
                }
                catch (Exception ex)
                {
                    BadFormatInstruction(instruction, ex);
                    return(false);
                }
            }
            else if (args[0].Equals("Wait", StringComparison.CurrentCultureIgnoreCase))
            {
                try
                {
                    return(bot.Wait(Convert.ToInt32(args[1])));
                }
                catch (Exception ex)
                {
                    BadFormatInstruction(instruction, ex);
                    return(false);
                }
            }
            else if (args[0].Equals("Message", StringComparison.CurrentCultureIgnoreCase))
            {
                try
                {
                    return(bot.Message(args[1]));
                }
                catch (Exception ex)
                {
                    BadFormatInstruction(instruction, ex);
                    return(false);
                }
            }
            else if (args[0].Equals("Comment", StringComparison.CurrentCultureIgnoreCase))
            {
                // Do noLightg here, just go through with it.
                return(true);
            }
            else if (args[0].Equals("CustomCode", StringComparison.CurrentCultureIgnoreCase))
            {
                bot.Logger.Warning("\"CustomCode\" can lead to unexpected results, use with caution and only if you know what you are doing.");

                try
                {
                    string statement = args[1];
                    bool   dec       = false;
                    if (args.Length > 2)
                    {
                        dec = bool.Parse(args[2]);  // if not good, throw and explain
                    }

                    return(bot.CustomCode(statement, dec));
                }
                catch (Exception ex)
                {
                    BadFormatInstruction(instruction, ex);
                }

                return(false);
            }
            else if (args[0].Equals("new Tool", StringComparison.CurrentCultureIgnoreCase) ||
                     args[0].Equals("Tool.Create", StringComparison.CurrentCultureIgnoreCase))
            {
                bot.Logger.Error($"\"{args[0]}\" is deprecated, please update your client and use \"DefineTool\" instead. Action will have no effect.");
                return(false);
            }
            else if (args[0].Equals("DefineTool", StringComparison.CurrentCultureIgnoreCase))
            {
                try
                {
                    return(bot.DefineTool(args[1],
                                          Convert.ToDouble(args[2]), Convert.ToDouble(args[3]), Convert.ToDouble(args[4]),
                                          Convert.ToDouble(args[5]), Convert.ToDouble(args[6]), Convert.ToDouble(args[7]),
                                          Convert.ToDouble(args[8]), Convert.ToDouble(args[9]), Convert.ToDouble(args[10]),
                                          Convert.ToDouble(args[11]),
                                          Convert.ToDouble(args[12]), Convert.ToDouble(args[13]), Convert.ToDouble(args[14])));
                }
                catch (Exception ex)
                {
                    BadFormatInstruction(instruction, ex);
                    return(false);
                }
            }
            else if (args[0].Equals("Attach", StringComparison.CurrentCultureIgnoreCase))
            {
                bot.Logger.Error($"\"{args[0]}\" is deprecated, please update your client and use \"AttachTool\" instead. Action will have no effect.");
                return(false);
            }
            else if (args[0].Equals("AttachTool", StringComparison.CurrentCultureIgnoreCase))
            {
                try
                {
                    return(bot.AttachTool(args[1]));
                }
                catch (Exception ex)
                {
                    BadFormatInstruction(instruction, ex);
                    return(false);
                }
            }
            else if (args[0].Equals("Detach", StringComparison.CurrentCultureIgnoreCase))
            {
                bot.Logger.Warning($"\"{args[0]}\" is deprecated, please update your client and use \"DetachTool\" instead.");
                return(bot.DetachTool());
            }
            else if (args[0].Equals("DetachTool", StringComparison.CurrentCultureIgnoreCase))
            {
                return(bot.DetachTool());
            }
            else if (args[0].Equals("WriteDigital", StringComparison.CurrentCultureIgnoreCase))
            {
                try
                {
                    int  count      = args.Length;
                    int  pin        = 0;
                    bool digitalPin = Int32.TryParse(args[1], out pin);

                    // Numeric pins
                    if (digitalPin)
                    {
                        switch (count)
                        {
                        case 3: return(bot.WriteDigital(pin, Convert.ToBoolean(args[2])));

                        case 4: return(bot.WriteDigital(pin, Convert.ToBoolean(args[2]), Convert.ToBoolean(args[3])));
                        }
                    }
                    // Named pins (ABB)
                    else
                    {
                        switch (count)
                        {
                        case 3: return(bot.WriteDigital(args[1], Convert.ToBoolean(args[2])));

                        case 4: return(bot.WriteDigital(args[1], Convert.ToBoolean(args[2]), Convert.ToBoolean(args[3])));
                        }
                    }

                    // If here, something went wrong...
                    Machina.Logger.Error($"Badly formatted instruction: \"{instruction}\"");
                    return(false);
                }
                catch (Exception ex)
                {
                    BadFormatInstruction(instruction, ex);
                    return(false);
                }
            }
            else if (args[0].Equals("WriteAnalog", StringComparison.CurrentCultureIgnoreCase))
            {
                try
                {
                    int  count      = args.Length;
                    int  pin        = 0;
                    bool digitalPin = Int32.TryParse(args[1], out pin);

                    if (digitalPin)
                    {
                        switch (count)
                        {
                        case 3: return(bot.WriteAnalog(pin, Convert.ToDouble(args[2])));

                        case 4: return(bot.WriteAnalog(pin, Convert.ToDouble(args[2]), Convert.ToBoolean(args[3])));
                        }
                    }
                    else
                    {
                        switch (count)
                        {
                        case 3: return(bot.WriteAnalog(args[1], Convert.ToDouble(args[2])));

                        case 4: return(bot.WriteAnalog(args[1], Convert.ToDouble(args[2]), Convert.ToBoolean(args[3])));
                        }
                    }

                    // If here, something went wrong...
                    Machina.Logger.Error($"Badly formatted instruction: \"{instruction}\"");
                    return(false);
                }
                catch (Exception ex)
                {
                    BadFormatInstruction(instruction, ex);
                    return(false);
                }
            }
            else if (args[0].Equals("Extrude", StringComparison.CurrentCultureIgnoreCase))
            {
                return(bot.Extrude());
            }

            // If here, instruction is not available or something went wrong...
            Machina.Logger.Error($"I don't understand \"{instruction}\"...");
            return(false);
        }
Beispiel #14
0
        internal void DownloadDrivers()
        {
            Logger.Info("Downloading Machina Drivers for " + _robotBrand + " robot on " + txtbox_IP.Text + ":" + txtbox_Port.Text);

            // Create a fake robot not to interfere with the main one
            Robot driverBot = Robot.Create(_robotName, _robotBrand);

            driverBot.ControlMode(ControlType.Online);
            var parameters = new Dictionary <string, string>()
            {
                { "HOSTNAME", txtbox_IP.Text },
                { "PORT", txtbox_Port.Text }
            };

            var files = driverBot.GetDeviceDriverModules(parameters);

            // Clear temp folder
            string path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "machina_modules");

            //https://stackoverflow.com/a/1288747/1934487
            System.IO.DirectoryInfo di = new DirectoryInfo(path);
            if (di.Exists)
            {
                Logger.Debug("Clearing " + path);
                foreach (FileInfo file in di.GetFiles())
                {
                    Logger.Debug("Deleting " + file.FullName);
                    file.Delete();
                }
                foreach (DirectoryInfo dir in di.GetDirectories())
                {
                    Logger.Debug("Deleting " + dir.FullName);
                    dir.Delete(true);
                }
            }
            else
            {
                di.Create();
                Logger.Debug("Created " + path);
            }

            // Save temp files
            foreach (var pair in files)
            {
                string filename = pair.Key;
                string content  = pair.Value;


                string filepath = System.IO.Path.Combine(path, filename);
                try
                {
                    System.IO.File.WriteAllText(filepath, content, Encoding.ASCII);
                }
                catch
                {
                    Logger.Error("Could not save " + filename + " to " + filepath);
                    Logger.Error("Could not download drivers");
                    return;
                }

                Logger.Debug("Saved module to " + filepath);
            }

            // Zip the file
            string zipPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "machina_modules.zip");

            System.IO.FileInfo fi = new FileInfo(zipPath);
            if (fi.Exists)
            {
                fi.Delete();
                Logger.Debug("Deleted previous " + zipPath);
            }
            ZipFile.CreateFromDirectory(path, zipPath);
            Logger.Debug("Zipped files to " + zipPath);

            // Prompt file save dialog: https://www.wpf-tutorial.com/dialogs/the-savefiledialog/
            SaveFileDialog saveFileDialog = new SaveFileDialog();

            saveFileDialog.Filter           = "Zip file (*.zip)|*.zip";
            saveFileDialog.DefaultExt       = "zip";
            saveFileDialog.AddExtension     = true;
            saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            saveFileDialog.FileName         = "machina_modules.zip";

            if (saveFileDialog.ShowDialog() == true)
            {
                fi = new FileInfo(saveFileDialog.FileName);
                if (fi.Exists)
                {
                    fi.Delete();
                    Logger.Debug("Deleted previous " + saveFileDialog.FileName);
                }
                File.Copy(zipPath, saveFileDialog.FileName);
                Logger.Debug("Copied " + zipPath + " to " + saveFileDialog.FileName);

                Logger.Info("Drivers saved to " + saveFileDialog.FileName);
            }
        }
Beispiel #15
0
 private void Bot_MotionUpdate(object sender, MotionUpdateArgs args)
 {
     Logger.Debug(args.ToString());
 }
 private void Wscl_OnOpen(object sender, EventArgs e)
 {
     Logger.Debug("Opened WS client connection: ");
 }
Beispiel #17
0
        public bool ExecuteInstruction(string instruction)
        {
            string[] args = Machina.Utilities.Parsing.ParseStatement(instruction);
            if (args == null || args.Length == 0)
            {
                Machina.Logger.Error($"I don't understand \"{instruction}\"...");
                return(false);
            }

            //  ███╗   ███╗██╗   ██╗     ██████╗ ██╗    ██╗███╗   ██╗
            //  ████╗ ████║╚██╗ ██╔╝    ██╔═══██╗██║    ██║████╗  ██║
            //  ██╔████╔██║ ╚████╔╝     ██║   ██║██║ █╗ ██║██╔██╗ ██║
            //  ██║╚██╔╝██║  ╚██╔╝      ██║   ██║██║███╗██║██║╚██╗██║
            //  ██║ ╚═╝ ██║   ██║       ╚██████╔╝╚███╔███╔╝██║ ╚████║
            //  ╚═╝     ╚═╝   ╚═╝        ╚═════╝  ╚══╝╚══╝ ╚═╝  ╚═══╝

            if (args[0].Equals("Test1", StringComparison.CurrentCultureIgnoreCase))
            {
                return(bot.Test1());
            }
            else if (args[0].Equals("Test2", StringComparison.CurrentCultureIgnoreCase))
            {
                return(bot.Test2());
            }
            // easy way to define tool
            else if (args[0].Equals("tool", StringComparison.CurrentCultureIgnoreCase))
            {
                if (args[1].Equals("pallet", StringComparison.CurrentCultureIgnoreCase))
                {
                    return(bot.DefineTool("pallet", new Machina.Point(-63, 0, 70), Machina.Orientation.WorldXY));
                }
                if (args[1].Equals("vacuum", StringComparison.CurrentCultureIgnoreCase))
                {
                    return(bot.DefineTool("vacuum", new Machina.Point(83, 0, 50), Machina.Orientation.WorldXY));
                }

                // print error with line number.
                ErrorWithLineNum(args[1]);

                return(false);
            }
            else if (args[0].Equals("MoveToRobTarget", StringComparison.CurrentCultureIgnoreCase))
            {
                // action MoveToRobTarget is only available in ABB robots
                // further testing for UR robots is needed (have no UR Robot)
                if (bot.Brand == RobotType.ABB)
                {
                    try
                    {
                        return(bot.MoveToRobTarget(
                                   Convert.ToDouble(args[1], CultureInfo.InvariantCulture),
                                   Convert.ToDouble(args[2], CultureInfo.InvariantCulture),
                                   Convert.ToDouble(args[3], CultureInfo.InvariantCulture),
                                   Convert.ToDouble(args[4], CultureInfo.InvariantCulture),
                                   Convert.ToDouble(args[5], CultureInfo.InvariantCulture),
                                   Convert.ToDouble(args[6], CultureInfo.InvariantCulture),
                                   Convert.ToDouble(args[7], CultureInfo.InvariantCulture),
                                   Convert.ToDouble(args[8], CultureInfo.InvariantCulture),
                                   Convert.ToDouble(args[9], CultureInfo.InvariantCulture),
                                   Convert.ToDouble(args[10], CultureInfo.InvariantCulture),
                                   Convert.ToDouble(args[11], CultureInfo.InvariantCulture)
                                   ));
                    }
                    catch (Exception ex)
                    {
                        BadFormatInstruction(instruction, ex);
                        return(false);
                    }
                }
            }
            else if (args[0].Equals("MoveCToRobTarget", StringComparison.CurrentCultureIgnoreCase))
            {
                // Action MovecToRobTarget is only available to ABB robots
                // further testing for UR robots is needed (have no UR Robot)
                if (bot.Brand == RobotType.ABB)
                {
                    try
                    {
                        return(bot.MovecToRobTarget(
                                   Convert.ToDouble(args[1], CultureInfo.InvariantCulture),
                                   Convert.ToDouble(args[2], CultureInfo.InvariantCulture),
                                   Convert.ToDouble(args[3], CultureInfo.InvariantCulture),
                                   Convert.ToDouble(args[4], CultureInfo.InvariantCulture),
                                   Convert.ToDouble(args[5], CultureInfo.InvariantCulture),
                                   Convert.ToDouble(args[6], CultureInfo.InvariantCulture),
                                   Convert.ToDouble(args[7], CultureInfo.InvariantCulture),
                                   Convert.ToDouble(args[8], CultureInfo.InvariantCulture),
                                   Convert.ToDouble(args[9], CultureInfo.InvariantCulture),
                                   Convert.ToDouble(args[10], CultureInfo.InvariantCulture),
                                   Convert.ToDouble(args[11], CultureInfo.InvariantCulture),
                                   Convert.ToDouble(args[12], CultureInfo.InvariantCulture),
                                   Convert.ToDouble(args[13], CultureInfo.InvariantCulture),
                                   Convert.ToDouble(args[14], CultureInfo.InvariantCulture),
                                   Convert.ToDouble(args[15], CultureInfo.InvariantCulture),
                                   Convert.ToDouble(args[16], CultureInfo.InvariantCulture),
                                   Convert.ToDouble(args[17], CultureInfo.InvariantCulture),
                                   Convert.ToDouble(args[18], CultureInfo.InvariantCulture),
                                   Convert.ToDouble(args[19], CultureInfo.InvariantCulture),
                                   Convert.ToDouble(args[20], CultureInfo.InvariantCulture),
                                   Convert.ToDouble(args[21], CultureInfo.InvariantCulture),
                                   Convert.ToDouble(args[22], CultureInfo.InvariantCulture)
                                   ));
                    }
                    catch (Exception ex)
                    {
                        BadFormatInstruction(instruction, ex);
                        return(false);
                    }
                }
            }
            else if (args[0].Equals("abbDefineTool", StringComparison.CurrentCultureIgnoreCase))
            {
                if (bot.Brand == RobotType.ABB)
                {
                    try
                    {
                        return(bot.AbbDefineTool(
                                   args[1],
                                   Convert.ToDouble(args[2], CultureInfo.InvariantCulture),
                                   Convert.ToDouble(args[3], CultureInfo.InvariantCulture),
                                   Convert.ToDouble(args[4], CultureInfo.InvariantCulture),
                                   Convert.ToDouble(args[5], CultureInfo.InvariantCulture),
                                   Convert.ToDouble(args[6], CultureInfo.InvariantCulture),
                                   Convert.ToDouble(args[7], CultureInfo.InvariantCulture),
                                   Convert.ToDouble(args[8], CultureInfo.InvariantCulture),
                                   Convert.ToDouble(args[9], CultureInfo.InvariantCulture),
                                   Convert.ToDouble(args[10], CultureInfo.InvariantCulture),
                                   Convert.ToDouble(args[11], CultureInfo.InvariantCulture),
                                   Convert.ToDouble(args[12], CultureInfo.InvariantCulture)
                                   ));
                    }
                    catch (Exception ex)
                    {
                        BadFormatInstruction(instruction, ex);
                        return(false);
                    }
                }
            }
            else if (args[0].Equals("abbAttachTool", StringComparison.CurrentCultureIgnoreCase))
            {
                if (bot.Brand == RobotType.ABB)
                {
                    try
                    {
                        return(bot.AbbAttachTool(args[1]));
                    }
                    catch (Exception ex)
                    {
                        BadFormatInstruction(instruction, ex);
                        return(false);
                    }
                }
            }

            //  ███████╗██╗  ██╗██╗███████╗████████╗██╗███╗   ██╗ ██████╗
            //  ██╔════╝╚██╗██╔╝██║██╔════╝╚══██╔══╝██║████╗  ██║██╔════╝
            //  █████╗   ╚███╔╝ ██║███████╗   ██║   ██║██╔██╗ ██║██║  ███╗
            //  ██╔══╝   ██╔██╗ ██║╚════██║   ██║   ██║██║╚██╗██║██║   ██║
            //  ███████╗██╔╝ ██╗██║███████║   ██║   ██║██║ ╚████║╚██████╔╝
            //  ╚══════╝╚═╝  ╚═╝╚═╝╚══════╝   ╚═╝   ╚═╝╚═╝  ╚═══╝ ╚═════╝

            // This is horrible, but oh well...
            if (args[0].Equals("MotionMode", StringComparison.CurrentCultureIgnoreCase))
            {
                try
                {
                    return(bot.MotionMode(args[1]));
                }
                catch (Exception ex)
                {
                    BadFormatInstruction(instruction, ex);
                    return(false);
                }
            }
            else if (args[0].Equals("Speed", StringComparison.CurrentCultureIgnoreCase))
            {
                try
                {
                    return(bot.Speed(Convert.ToDouble(args[1], CultureInfo.InvariantCulture)));
                }
                catch (Exception ex)
                {
                    BadFormatInstruction(instruction, ex);
                    return(false);
                }
            }
            else if (args[0].Equals("SpeedTo", StringComparison.CurrentCultureIgnoreCase))
            {
                try
                {
                    return(bot.SpeedTo(Convert.ToDouble(args[1], CultureInfo.InvariantCulture)));
                }
                catch (Exception ex)
                {
                    BadFormatInstruction(instruction, ex);
                    return(false);
                }
            }
            else if (args[0].Equals("Acceleration", StringComparison.CurrentCultureIgnoreCase))
            {
                try
                {
                    return(bot.Acceleration(Convert.ToDouble(args[1], CultureInfo.InvariantCulture)));
                }
                catch (Exception ex)
                {
                    BadFormatInstruction(instruction, ex);
                    return(false);
                }
            }
            else if (args[0].Equals("AccelerationTo", StringComparison.CurrentCultureIgnoreCase))
            {
                try
                {
                    return(bot.AccelerationTo(Convert.ToDouble(args[1], CultureInfo.InvariantCulture)));
                }
                catch (Exception ex)
                {
                    BadFormatInstruction(instruction, ex);
                    return(false);
                }
            }
            else if (args[0].Equals("Precision", StringComparison.CurrentCultureIgnoreCase))
            {
                try
                {
                    return(bot.Precision(Convert.ToDouble(args[1], CultureInfo.InvariantCulture)));
                }
                catch (Exception ex)
                {
                    BadFormatInstruction(instruction, ex);
                    return(false);
                }
            }
            else if (args[0].Equals("PrecisionTo", StringComparison.CurrentCultureIgnoreCase))
            {
                try
                {
                    return(bot.PrecisionTo(Convert.ToDouble(args[1], CultureInfo.InvariantCulture)));
                }
                catch (Exception ex)
                {
                    BadFormatInstruction(instruction, ex);
                    return(false);
                }
            }
            else if (args[0].Equals("Coordinates", StringComparison.CurrentCultureIgnoreCase))
            {
                bot.Logger.Error($"\"{args[0]}\" is still not implemented.");
                return(false);
            }
            else if (args[0].Equals("Temperature", StringComparison.CurrentCultureIgnoreCase) || args[0].Equals("TemperatureTo", StringComparison.CurrentCultureIgnoreCase))
            {
                bot.Logger.Error($"\"{args[0]}\" is still not implemented.");
                return(false);
            }
            else if (args[0].Equals("ExtrusionRate", StringComparison.CurrentCultureIgnoreCase) || args[0].Equals("ExtrusionRateTo", StringComparison.CurrentCultureIgnoreCase))
            {
                bot.Logger.Error($"\"{args[0]}\" is still not implemented.");
                return(false);
            }
            else if (args[0].Equals("PushSettings", StringComparison.CurrentCultureIgnoreCase))
            {
                bot.PushSettings();
                return(true);
            }
            else if (args[0].Equals("PopSettings", StringComparison.CurrentCultureIgnoreCase))
            {
                bot.PopSettings();
                return(true);
            }
            else if (args[0].Equals("Move", StringComparison.CurrentCultureIgnoreCase))
            {
                try
                {
                    return(bot.Move(
                               Convert.ToDouble(args[1], CultureInfo.InvariantCulture),
                               Convert.ToDouble(args[2], CultureInfo.InvariantCulture),
                               Convert.ToDouble(args[3], CultureInfo.InvariantCulture)
                               ));
                }
                catch (Exception ex)
                {
                    BadFormatInstruction(instruction, ex);
                    return(false);
                }
            }
            else if (args[0].Equals("MoveTo", StringComparison.CurrentCultureIgnoreCase))
            {
                try
                {
                    return(bot.MoveTo(
                               Convert.ToDouble(args[1], CultureInfo.InvariantCulture),
                               Convert.ToDouble(args[2], CultureInfo.InvariantCulture),
                               Convert.ToDouble(args[3], CultureInfo.InvariantCulture)
                               ));
                }
                catch (Exception ex)
                {
                    BadFormatInstruction(instruction, ex);
                    return(false);
                }
            }
            else if (args[0].Equals("Rotate", StringComparison.CurrentCultureIgnoreCase))
            {
                try
                {
                    return(bot.Rotate(
                               Convert.ToDouble(args[1], CultureInfo.InvariantCulture),
                               Convert.ToDouble(args[2], CultureInfo.InvariantCulture),
                               Convert.ToDouble(args[3], CultureInfo.InvariantCulture),
                               Convert.ToDouble(args[4], CultureInfo.InvariantCulture)
                               ));
                }
                catch (Exception ex)
                {
                    BadFormatInstruction(instruction, ex);
                    return(false);
                }
            }
            else if (args[0].Equals("RotateTo", StringComparison.CurrentCultureIgnoreCase))
            {
                try
                {
                    return(bot.RotateTo(
                               Convert.ToDouble(args[1], CultureInfo.InvariantCulture),
                               Convert.ToDouble(args[2], CultureInfo.InvariantCulture),
                               Convert.ToDouble(args[3], CultureInfo.InvariantCulture),
                               Convert.ToDouble(args[4], CultureInfo.InvariantCulture),
                               Convert.ToDouble(args[5], CultureInfo.InvariantCulture),
                               Convert.ToDouble(args[6], CultureInfo.InvariantCulture)
                               ));
                }
                catch (Exception ex)
                {
                    BadFormatInstruction(instruction, ex);
                    return(false);
                }
            }
            else if (args[0].Equals("Transform", StringComparison.CurrentCultureIgnoreCase))
            {
                bot.Logger.Error($"\"{args[0]}\" is still not implemented.");
                return(false);
            }
            else if (args[0].Equals("TransformTo", StringComparison.CurrentCultureIgnoreCase))
            {
                try
                {
                    return(bot.TransformTo(
                               Convert.ToDouble(args[1], CultureInfo.InvariantCulture),
                               Convert.ToDouble(args[2], CultureInfo.InvariantCulture),
                               Convert.ToDouble(args[3], CultureInfo.InvariantCulture),
                               Convert.ToDouble(args[4], CultureInfo.InvariantCulture),
                               Convert.ToDouble(args[5], CultureInfo.InvariantCulture),
                               Convert.ToDouble(args[6], CultureInfo.InvariantCulture),
                               Convert.ToDouble(args[7], CultureInfo.InvariantCulture),
                               Convert.ToDouble(args[8], CultureInfo.InvariantCulture),
                               Convert.ToDouble(args[9], CultureInfo.InvariantCulture)
                               ));
                }
                catch (Exception ex)
                {
                    BadFormatInstruction(instruction, ex);
                    return(false);
                }
            }
            else if (args[0].Equals("Axes", StringComparison.CurrentCultureIgnoreCase))
            {
                try
                {
                    return(bot.Axes(
                               Convert.ToDouble(args[1], CultureInfo.InvariantCulture),
                               Convert.ToDouble(args[2], CultureInfo.InvariantCulture),
                               Convert.ToDouble(args[3], CultureInfo.InvariantCulture),
                               Convert.ToDouble(args[4], CultureInfo.InvariantCulture),
                               Convert.ToDouble(args[5], CultureInfo.InvariantCulture),
                               Convert.ToDouble(args[6], CultureInfo.InvariantCulture)
                               ));
                }
                catch (Exception ex)
                {
                    BadFormatInstruction(instruction, ex);
                    return(false);
                }
            }
            else if (args[0].Equals("AxesTo", StringComparison.CurrentCultureIgnoreCase))
            {
                try
                {
                    return(bot.AxesTo(
                               Convert.ToDouble(args[1], CultureInfo.InvariantCulture),
                               Convert.ToDouble(args[2], CultureInfo.InvariantCulture),
                               Convert.ToDouble(args[3], CultureInfo.InvariantCulture),
                               Convert.ToDouble(args[4], CultureInfo.InvariantCulture),
                               Convert.ToDouble(args[5], CultureInfo.InvariantCulture),
                               Convert.ToDouble(args[6], CultureInfo.InvariantCulture)
                               ));
                }
                catch (Exception ex)
                {
                    BadFormatInstruction(instruction, ex);
                    return(false);
                }
            }
            else if (args[0].Equals("ExternalAxis", StringComparison.CurrentCultureIgnoreCase))
            {
                try
                {
                    int axisNumber;
                    try
                    {
                        axisNumber = Convert.ToInt32(args[1]);
                        if (axisNumber < 1 || axisNumber > 6)
                        {
                            Logger.Error($"Axis number must be between 1 and 6");
                            return(false);
                        }
                    }
                    catch
                    {
                        Logger.Error($"Axis number must be an integer");
                        return(false);
                    }

                    double increment;
                    try
                    {
                        increment = Convert.ToDouble(args[2], CultureInfo.InvariantCulture);
                    }
                    catch
                    {
                        Logger.Error($"Invalid increment value " + args[2]);
                        return(false);
                    }

                    string target = "All";
                    if (args.Length > 3)
                    {
                        target = args[3];
                    }

                    return(bot.ExternalAxis(axisNumber, increment, target));
                }
                catch (Exception ex)
                {
                    BadFormatInstruction(instruction, ex);
                    return(false);
                }
            }
            else if (args[0].Equals("ExternalAxisTo", StringComparison.CurrentCultureIgnoreCase))
            {
                try
                {
                    int axisNumber;
                    try
                    {
                        axisNumber = Convert.ToInt32(args[1]);
                        if (axisNumber < 1 || axisNumber > 6)
                        {
                            Logger.Error($"Axis number must be between 1 and 6");
                            return(false);
                        }
                    }
                    catch
                    {
                        Logger.Error($"Axis number must be an integer");
                        return(false);
                    }

                    double val;
                    try
                    {
                        val = Convert.ToDouble(args[2], CultureInfo.InvariantCulture);
                    }
                    catch
                    {
                        Logger.Error($"Invalid value " + args[2]);
                        return(false);
                    }

                    string target = "All";
                    if (args.Length > 3)
                    {
                        target = args[3];
                    }

                    return(bot.ExternalAxisTo(axisNumber, val, target));
                }
                catch (Exception ex)
                {
                    BadFormatInstruction(instruction, ex);
                    return(false);
                }
            }
            else if (args[0].Equals("ArmAngle", StringComparison.CurrentCultureIgnoreCase))
            {
                bot.Logger.Error("Relative `ArmAngle` is temporarily disabled, please use the absolute `ArmAngleTo` version instead.");
                return(false);

                //Logger.Warning(
                //"Relative `ArmAngle` is temporarily disabled, please use the absolute `ArmAngleTo` version instead.");
            }
            else if (args[0].Equals("ArmAngleTo", StringComparison.CurrentCultureIgnoreCase))
            {
                try
                {
                    double val;
                    try
                    {
                        val = Convert.ToDouble(args[1], CultureInfo.InvariantCulture);
                    }
                    catch
                    {
                        Logger.Error($"Invalid value " + args[1]);
                        return(false);
                    }

                    //double val;
                    //if (!Double.TryParse(args[1], out val))
                    //{
                    //    Logger.Error($"Invalid value " + args[1]);
                    //    return false;
                    //}

                    return(bot.ArmAngleTo(val));
                }
                catch (Exception ex)
                {
                    BadFormatInstruction(instruction, ex);
                    return(false);
                }
            }
            else if (args[0].Equals("Wait", StringComparison.CurrentCultureIgnoreCase))
            {
                try
                {
                    return(bot.Wait(Convert.ToInt32(args[1])));
                }
                catch (Exception ex)
                {
                    BadFormatInstruction(instruction, ex);
                    return(false);
                }
            }
            else if (args[0].Equals("Message", StringComparison.CurrentCultureIgnoreCase))
            {
                try
                {
                    return(bot.Message(args[1]));
                }
                catch (Exception ex)
                {
                    BadFormatInstruction(instruction, ex);
                    return(false);
                }
            }
            else if (args[0].Equals("Comment", StringComparison.CurrentCultureIgnoreCase))
            {
                // Do nothing here, just go through with it.
                return(true);
            }
            else if (args[0].Equals("CustomCode", StringComparison.CurrentCultureIgnoreCase))
            {
                bot.Logger.Warning("\"CustomCode\" can lead to unexpected results, use with caution and only if you REALLY know what you are doing.");

                try
                {
                    string statement = args[1];
                    bool   dec       = false;
                    if (args.Length > 2)
                    {
                        dec = bool.Parse(args[2]);  // if not good, throw and explain
                    }

                    return(bot.CustomCode(statement, dec));
                }
                catch (Exception ex)
                {
                    BadFormatInstruction(instruction, ex);
                }

                return(false);
            }
            else if (args[0].Equals("new Tool", StringComparison.CurrentCultureIgnoreCase) ||
                     args[0].Equals("Tool.Create", StringComparison.CurrentCultureIgnoreCase))
            {
                bot.Logger.Error($"\"{args[0]}\" is deprecated, please update your client and use \"DefineTool\" instead. Action will have no effect.");
                return(false);
            }
            else if (args[0].Equals("DefineTool", StringComparison.CurrentCultureIgnoreCase))
            {
                try
                {
                    return(bot.DefineTool(
                               args[1],
                               Convert.ToDouble(args[2], CultureInfo.InvariantCulture),
                               Convert.ToDouble(args[3], CultureInfo.InvariantCulture),
                               Convert.ToDouble(args[4], CultureInfo.InvariantCulture),
                               Convert.ToDouble(args[5], CultureInfo.InvariantCulture),
                               Convert.ToDouble(args[6], CultureInfo.InvariantCulture),
                               Convert.ToDouble(args[7], CultureInfo.InvariantCulture),
                               Convert.ToDouble(args[8], CultureInfo.InvariantCulture),
                               Convert.ToDouble(args[9], CultureInfo.InvariantCulture),
                               Convert.ToDouble(args[10], CultureInfo.InvariantCulture),
                               Convert.ToDouble(args[11], CultureInfo.InvariantCulture),
                               Convert.ToDouble(args[12], CultureInfo.InvariantCulture),
                               Convert.ToDouble(args[13], CultureInfo.InvariantCulture),
                               Convert.ToDouble(args[14], CultureInfo.InvariantCulture)
                               ));
                }
                catch (Exception ex)
                {
                    BadFormatInstruction(instruction, ex);
                    return(false);
                }
            }
            else if (args[0].Equals("Attach", StringComparison.CurrentCultureIgnoreCase))
            {
                bot.Logger.Error($"\"{args[0]}\" is deprecated, please update your client and use \"AttachTool\" instead. Action will have no effect.");
                return(false);
            }
            else if (args[0].Equals("AttachTool", StringComparison.CurrentCultureIgnoreCase))
            {
                try
                {
                    return(bot.AttachTool(args[1]));
                }
                catch (Exception ex)
                {
                    BadFormatInstruction(instruction, ex);
                    return(false);
                }
            }
            else if (args[0].Equals("Detach", StringComparison.CurrentCultureIgnoreCase))
            {
                bot.Logger.Warning($"\"{args[0]}\" is deprecated, please update your client and use \"DetachTool\" instead.");
                return(bot.DetachTool());
            }
            else if (args[0].Equals("DetachTool", StringComparison.CurrentCultureIgnoreCase))
            {
                return(bot.DetachTool());
            }
            else if (args[0].Equals("WriteDigital", StringComparison.CurrentCultureIgnoreCase))
            {
                try
                {
                    int  count      = args.Length;
                    int  pin        = 0;
                    bool digitalPin = Int32.TryParse(args[1], out pin);

                    // Numeric pins
                    if (digitalPin)
                    {
                        switch (count)
                        {
                        case 3: return(bot.WriteAnalog(pin, Convert.ToDouble(args[2], CultureInfo.InvariantCulture)));

                        case 4: return(bot.WriteAnalog(pin, Convert.ToDouble(args[2], CultureInfo.InvariantCulture), Convert.ToBoolean(args[3])));
                        }
                    }
                    // Named pins (ABB)
                    else
                    {
                        switch (count)
                        {
                        case 3: return(bot.WriteAnalog(args[1], Convert.ToDouble(args[2], CultureInfo.InvariantCulture)));

                        case 4: return(bot.WriteAnalog(args[1], Convert.ToDouble(args[2], CultureInfo.InvariantCulture), Convert.ToBoolean(args[3])));
                        }
                    }

                    // If here, something went wrong...
                    // why is this hear and not a call to BadFormatInstruction?
                    Machina.Logger.Error($"Badly formatted instruction: \"{instruction}\"");
                    return(false);
                }
                catch (Exception ex)
                {
                    BadFormatInstruction(instruction, ex);
                    return(false);
                }
            }
            else if (args[0].Equals("WriteAnalog", StringComparison.CurrentCultureIgnoreCase))
            {
                try
                {
                    int  count      = args.Length;
                    int  pin        = 0;
                    bool digitalPin = Int32.TryParse(args[1], out pin);

                    if (digitalPin)
                    {
                        switch (count)
                        {
                        case 3: return(bot.WriteAnalog(pin, Convert.ToDouble(args[2])));

                        case 4: return(bot.WriteAnalog(pin, Convert.ToDouble(args[2]), Convert.ToBoolean(args[3])));
                        }
                    }
                    else
                    {
                        switch (count)
                        {
                        case 3: return(bot.WriteAnalog(args[1], Convert.ToDouble(args[2])));

                        case 4: return(bot.WriteAnalog(args[1], Convert.ToDouble(args[2]), Convert.ToBoolean(args[3])));
                        }
                    }

                    // If here, something went wrong...
                    Machina.Logger.Error($"Badly formatted instruction: \"{instruction}\"");
                    return(false);
                }
                catch (Exception ex)
                {
                    BadFormatInstruction(instruction, ex);
                    return(false);
                }
            }
            else if (args[0].Equals("Extrude", StringComparison.CurrentCultureIgnoreCase))
            {
                return(bot.Extrude());
            }

            // If here, instruction is not available or something went wrong...
            Machina.Logger.Error($"I don't understand \"{instruction}\"...");
            return(false);
        }
 private void Wscl_OnError(object sender, WebSocketSharp.ErrorEventArgs e)
 {
     Logger.Error("Error on WS client connection: " + e.Message);
 }
        /// <summary>
        /// Initialize WebSocket communication infrastructure
        /// </summary>
        /// <returns></returns>
        private bool InitializeWebSocketServer()
        {
            // Close previous instances, if applicable
            if (wssv != null && wssv.IsListening)
            {
                StopWebSocketServer();
            }
            if (wscl != null && wscl.IsAlive)
            {
                StopWebSocketClient();
            }

            wsURL    = txtbox_WSServerURL.Text;
            _authkey = psswrdbox_Key.Password;

            // Check if given URL is a valid Machina Server
            try
            {
                Logger.Verbose("Trying connection to Machina Server on " + wsURL);

                // Add relevant auth info as query parameters
                string fullURL = $"{wsURL}?name={_robotName}&client=machina-bridge&authkey={_authkey}";

                // Establish connection
                wscl            = new WebSocket(fullURL);
                wscl.OnOpen    += Wscl_OnOpen;
                wscl.OnMessage += Wscl_OnMessage;
                wscl.OnClose   += Wscl_OnClose;
                wscl.OnError   += Wscl_OnError;
                wscl.Connect();
                //wscl.Send("hello from Bridge");

                if (wscl.IsAlive)
                {
                    Logger.Info("Successful connection to Machina Remote Server on " + wsURL);
                }
                else
                {
                    throw new Exception();
                }
            }
            catch
            {
                Logger.Verbose("Could not connect to existing Machina Server, initializing locally...");

                // Check validity of URL
                if (!ParseWebSocketURL())
                {
                    Logger.Error("Invalid WebSocket URL \"" + txtbox_WSServerURL.Text + "\"; try something like \"ws://127.0.0.1/Bridge\"");
                    return(false);
                }

                wssv = new WebSocketServer(wsURL);
                wssv.AddWebSocketService(wssvBehavior, () => new WSServerBehavior(bot, this));

                // @TODO: add a check here if the port is in use, and try a different port instead
                try
                {
                    wssv.Start();
                }
                catch
                {
                    Logger.Error("Default websocket server is not available, please enter a new one manually...");
                    return(false);
                }

                if (wssv.IsListening)
                {
                    //Machina.Logger.Info($"Listening on port {wssv.Port}, and providing WebSocket services:");
                    //foreach (var path in wssv.WebSocketServices.Paths) Machina.Logger.Info($"- {path}");
                    Logger.Verbose("Successful initialization of Machina Local Server on " + wsURL);
                    Logger.Info("Waiting for incoming connections on Machina Local Server " + (wsURL + wssvBehavior));
                }
            }

            return(true);
            //lbl_ServerURL.Content = wssvURL + wssvBehavior;
        }
 protected override void OnError(WebSocketSharp.ErrorEventArgs e)
 {
     //base.OnError(e);
     //Console.WriteLine("  BRIDGE ERROR: " + e.Message);
     Logger.Error("WS error: " + e.Message);
 }
 private void Wscl_OnClose(object sender, CloseEventArgs e)
 {
     Logger.Debug("Closed WS client connection: " + e.Code + " " + e.Reason);
 }