コード例 #1
0
ファイル: TrainProgram.cs プロジェクト: tomjcook/BAP
        internal void StartSequence(TrainProgramEvent trainEvent)
        {
            if (hubs == null)
            {
                MainBoard.WriteLine($"You need at least 1 registered hub to start a program. '{Name}' cannot be started.", Color.Red);
                return;
            }

            // Make sure to execute code and nothing else
            trainEvent.Action = TrainProgramEvent.ActionType.Execute_Code;

            // Let's roll!
            ActivateAction(trainEvent);
        }
コード例 #2
0
ファイル: TrainProgram.cs プロジェクト: tomjcook/BAP
        public bool Init(TrainProject project)
        {
            sections = project.Sections;
            hubs     = project.RegisteredTrains;
            if (hubs == null || hubs.Count == 0)
            {
                return(false);
            }

            foreach (Hub t in hubs)
            {
                t.State = (t.State == null) ? new int[100] : t.State;
            }

            // Make sure GlobalStates exist
            Global = (Global == null) ? new int[100] : Global;

            // Make sure GlobalCode exist
            GlobalCode = (project.GlobalCode == null) ? new TrainProgramEvent(TrainProgramEvent.EventType.Global_Code) : project.GlobalCode;

            return(true);
        }
コード例 #3
0
ファイル: FormCodeEditor.cs プロジェクト: tomjcook/BAP
        public FormCodeEditor(TrainProgramEvent codeEvent, TrainProject project, bool editGlobalCode)
        {
            // Init code to edit and global code
            CodeEvent  = codeEvent;
            GlobalCode = (editGlobalCode) ? null : project.GlobalCode;

            // Attach Hubs without launching sensors.
            this.hubs     = project.RegisteredTrains;
            this.sections = project.Sections;
            foreach (Hub h in hubs)
            {
                h.State = h.State ?? (new int[100]);
            }

            // Init Components
            InitializeComponent();

            if (codeEvent.Name != null)
            {
                textBoxName.Text = codeEvent.Name;
            }

            fastColoredTextBox1.Text         = codeEvent.CodeToRun;
            fastColoredTextBox1.TextChanged += fastColoredTextBox1_TextChanged;

            fastColoredTextBox1.SelectAll();
            fastColoredTextBox1.Selection.SetStyle(GreenStyle, @"//.*$", RegexOptions.Multiline);
            fastColoredTextBox1.Selection.SetStyle(BrownStyle, @"""""|@""""|''|@"".*?""|(?<!@)(?<range>"".*?[^\\]"")|'.*?[^\\]'");
            fastColoredTextBox1.Selection.SetStyle(MagentaStyle, @"\b\d+[\.]?\d*([eE]\-?\d+)?[lLdDfF]?\b|\b0x[a-fA-F\d]+\b");

            fastColoredTextBox1.Selection = new Range(fastColoredTextBox1, 0);

            // if Globa Code is null, it means we are editing the global code itself
            buttonTestCode.Text = (GlobalCode == null) ? "Compile Code" : "Run Code";

            InitLabel();
            InitAutocomplete();
        }
コード例 #4
0
ファイル: TrainProgram.cs プロジェクト: tomjcook/BAP
        public void ActivateAction(TrainProgramEvent e)
        {
            Hub target = GetTrain(e.TargetDeviceID);

            if (target == null && e.Action != TrainProgramEvent.ActionType.Execute_Code && e.Action != TrainProgramEvent.ActionType.Play_Sound)
            {
                MainBoard.WriteLine($"Target train '{ e.TargetDeviceID}' is not connected");
                return;
            }

            switch (e.Action)
            {
            case TrainProgramEvent.ActionType.Stop_Motor:
            {
                MainBoard.WriteLine("Action Tiggered => Stop Port " + e.TargetPort + " of " + target.Name);
                target.Stop(e.TargetPort, true);
                break;
            }

            case TrainProgramEvent.ActionType.Set_Speed:
            {
                MainBoard.WriteLine($"{target.Name} Action Tiggered => Set Motor Speed of Port {e.TargetPort} to {e.Param[0]} for {target.Name}");
                target.SetMotorSpeed(e.TargetPort, e.Param[0]);
                break;
            }

            case TrainProgramEvent.ActionType.Invert_Speed:
            {
                Port targetPort = target.GetPortFromPortId(e.TargetPort);

                MainBoard.WriteLine($"{target.Name} Action Tiggered => Invert Speed of Port {e.TargetPort} to {-targetPort.Speed} for {target.Name}");
                target.SetMotorSpeed(e.TargetPort, -targetPort.Speed);
                break;
            }

            case TrainProgramEvent.ActionType.Accelerate_Motor_Over_X_Ms:
            {
                Port targetPort = target.GetPortFromPortId(e.TargetPort);

                MainBoard.WriteLine($"{target.Name} Action Tiggered => Accelerate Port {e.TargetPort} to {e.Param[0]} over {e.Param[1]}ms");
                target.RampMotorSpeed(e.TargetPort, e.Param[0], e.Param[1]);
                break;
            }

            case TrainProgramEvent.ActionType.Decelerate_Motor_Over_X_Ms:
            {
                Port targetPort = target.GetPortFromPortId(e.TargetPort);

                MainBoard.WriteLine($"{target.Name} Action Tiggered => Decelerate Port {e.TargetPort} to 0 over {e.Param[0]}ms");
                target.RampMotorSpeed(e.TargetPort, 0, e.Param[0]);
                break;
            }

            case TrainProgramEvent.ActionType.Wait_X_Ms_And_Set_Speed:
            {
                MainBoard.WriteLine($"{target.Name} Action Tiggered => Wait {e.Param[0]}ms and Set Speed of Port {e.TargetPort} to {e.Param[1]}");
                target.Stop();
                System.Timers.Timer t = new System.Timers.Timer();
                t.Interval = e.Param[0];
                t.Elapsed += (object sender, ElapsedEventArgs ev) =>
                {
                    target.SetMotorSpeed(e.TargetPort, e.Param[1]);
                    t.Stop();
                    t.Dispose();
                };
                t.Start();
                break;
            }

            case TrainProgramEvent.ActionType.Set_Speed_For_X_Ms_And_Stop:
            {
                MainBoard.WriteLine($"{target.Name} Action Tiggered => Set Speed on Port {e.TargetPort} to {e.Param[0]} And Stop after {e.Param[1]}ms");
                target.SetMotorSpeed(e.TargetPort, e.Param[1]);
                System.Timers.Timer t = new System.Timers.Timer(e.Param[0]);
                t.Elapsed += (object sender, ElapsedEventArgs ev) =>
                {
                    target.Stop(e.TargetPort);
                    t.Stop();
                    t.Dispose();
                };
                t.Start();
                break;
            }

            case TrainProgramEvent.ActionType.Activate_Switch_Left:
            case TrainProgramEvent.ActionType.Activate_Switch_Right:
            {
                Port targetPort = target.GetPortFromPortId(e.TargetPort);

                targetPort.TargetSpeed = (e.Action == TrainProgramEvent.ActionType.Activate_Switch_Left) ? -100 : 100;
                MainBoard.WriteLine($"{target.Name} Action Tiggered => Activate Switch to the " + ((targetPort.TargetSpeed == -100) ? "Left" : "Right"));

                // Then trigger the motor
                if (e.Action == TrainProgramEvent.ActionType.Activate_Switch_Left)
                {
                    target.ActivateSwitchToLeft(e.TargetPort);
                }
                else
                {
                    target.ActivateSwitchToRight(e.TargetPort);
                }
                break;
            }

            case TrainProgramEvent.ActionType.PFx_Light_Fx:
            {
                PFxHub hub = (PFxHub)target;
                MainBoard.WriteLine($"{target.Name} Action Tiggered => Activate PFx Light FX " + e.PFxLightParam.ToString() + " on lights " + e.Lights);

                hub.LightFx(e.Lights, (byte)e.PFxLightParam, new byte[0]);
                break;
            }

            case TrainProgramEvent.ActionType.PFx_Play_Sound_With_File_Id:
            {
                PFxHub hub = (PFxHub)target;
                MainBoard.WriteLine($"{target.Name} Action Tiggered => Play PFx Sound from file Id " + e.Param[0]);

                hub.PlayAudioFile((byte)e.Param[0]);
                break;
            }

            case TrainProgramEvent.ActionType.Play_Sound:
            {
                MainBoard.WriteLine($"{target.Name} Action Tiggered => Play Sound " + e.Path);
                try
                {
                    System.Media.SoundPlayer player = new System.Media.SoundPlayer(e.Path);
                    player.Play();
                }
                catch (Exception ex)
                {
                    MainBoard.WriteLine("Error while trying to play a sound: " + ex.Message, Color.Red);
                }

                break;
            }

            case TrainProgramEvent.ActionType.Execute_Code:
            {
                // If we have an internal event code, we execute and stop
                if (e.OnEventIsTriggered())
                {
                    return;
                }

                Hub source            = GetTrain(e.TrainDeviceID);
                int currentTrainIndex = hubs.IndexOf(source);

                string code = TrainProgramEvent.Code.Replace("%Code%", e.CodeToRun.Replace("Wait(", "await Task.Delay("));
                code = code.Replace("/*%GlobalCode%*/", GlobalCode.CodeToRun.Replace("Wait(", "await Task.Delay("));
                code = code.Replace("%CurrentTrainIndex%", currentTrainIndex.ToString());

                CSharpCodeProvider provider   = new CSharpCodeProvider();
                CompilerParameters parameters = new CompilerParameters();

                // Reference to System.Drawing library
                parameters.ReferencedAssemblies.Add("System.dll");
                parameters.ReferencedAssemblies.Add("LegoTrainProject.exe");
                parameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");
                parameters.ReferencedAssemblies.Add("System.Drawing.dll");
                // True - memory generation, false - external file generation
                parameters.GenerateInMemory = true;
                // True - exe file generation, false - dll file generation
                parameters.GenerateExecutable = false;

                // Run the code!
                CompilerResults results = provider.CompileAssemblyFromSource(parameters, code);

                if (results.Errors.HasErrors)
                {
                    StringBuilder sb = new StringBuilder();

                    foreach (CompilerError error in results.Errors)
                    {
                        MainBoard.WriteLine(String.Format("Compilation Error ({0}): {1}", error.ErrorNumber, error.ErrorText), Color.Red);
                    }
                }
                else
                {
                    Assembly   assembly = results.CompiledAssembly;
                    Type       program  = assembly.GetType("LegoTrainProject.DynamicCode");
                    MethodInfo main     = program.GetMethod("ExecuteCode");

                    try
                    {
                        ThreadStart threadMain = delegate() { main.Invoke(null, new object[] { e, this.hubs, sections }); };
                        new System.Threading.Thread(threadMain).Start();
                    }
                    catch (Exception ex)
                    {
                        MainBoard.WriteLine("Exception while executing your sequence: " + ex.InnerException);
                    }
                }

                break;
            }

            //added by Tom Cook to add change speed function
            case TrainProgramEvent.ActionType.Change_Speed:
            {
                MainBoard.WriteLine($"{target.Name} Action Tiggered =>Change Motor Speed of Port {e.TargetPort} by {e.Param[0]}  for {target.Name}");
                //tb.Value = (p.Speed == 127) ? -1 : (p.Speed < -100) ? -100 : (p.Speed > 100) ? 100 : p.Speed;

                int newspeed = (target.GetMotorSpeed(e.TargetPort) + e.Param[0] < -100) ? -100 :
                               (target.GetMotorSpeed(e.TargetPort) + e.Param[0] > 100) ? 100 :
                               target.GetMotorSpeed(e.TargetPort) + e.Param[0];

                target.SetMotorSpeed(e.TargetPort, newspeed);
                break;
            }
            }
        }