Beispiel #1
0
        /// <summary>
        /// Mark sure client is initialized.
        /// </summary>
        /// <param name="component"></param>
        private void CheckClientAndValues(SmartComponent component)
        {
            if (client == null)
            {
                client = new S7Client();
                Disconnect(component);
            }

            int diCount = (int)component.Properties["DI_Number"].Value;

            if (diCount != bDI_AddressIsValid.Length)            // When just loaded array is not initialized
            {
                UpdateDICount(component, diCount);
            }
            int doCount = (int)component.Properties["DO_Number"].Value;

            if (doCount != bDO_AddressIsValid.Length)            // When just loaded array is not initialized
            {
                UpdateDOCount(component, doCount);
            }

            for (int i = 0; i < component.Properties.Count; ++i)
            {
                component.Properties[i].ValidateValue(component.Properties[i].Value);
            }
        }
Beispiel #2
0
        private ValueValidationInfo DIValidationInfo(SmartComponent smartComponent, DynamicProperty property, object newValue)
        {
            int diNumber = -1;

            int.TryParse(Right(property.Name, property.Name.Length - 11), out diNumber);
            if ((diNumber >= 0) && (diNumber < bDIO_AddressIsValid[(int)IO.Input].Length))
            {
                bDIO_AddressIsValid[(int)IO.Input][diNumber] = false;
                S7Client.S7DataItem item = new S7Client.S7DataItem();
                if (!GetS7DataItem((string)newValue, ref item))
                {
                    return(new ValueValidationInfo(ValueValidationResult.InvalidSyntax));
                }
                if (item.WordLen != S7Consts.S7WLBit)
                {
                    return(new ValueValidationInfo(ValueValidationResult.InvalidSyntax));
                }
                if ((item.Area != S7Consts.S7AreaPA) &&
                    (item.Area != S7Consts.S7AreaMK) &&
                    (item.Area != S7Consts.S7AreaDB)
                    )
                {
                    return(new ValueValidationInfo(ValueValidationResult.InvalidSyntax));
                }

                bDIO_AddressIsValid[(int)IO.Input][diNumber] = true;
                return(ValueValidationInfo.Valid);
            }
            else
            {
                return(new ValueValidationInfo(ValueValidationResult.InvalidProject));
            }
        }
        private void ChangeComp(SmartComponent component, int Choise)
        {
            int    NextAct  = 0;
            string Selected = "SourceSelector" + Choise.ToString();

            if (component.IOSignals[Selected].Value.Equals(1))
            {
                //Record if we want to turn this one ON
                NextAct = Choise;
            }
            else
            { //We want to turn it OFF, and select the next highest
                for (int i = 6; i >= 0; i--)
                {
                    Selected = "SourceSelector" + i.ToString();
                    if (NextAct == 0)
                    {
                        if (component.IOSignals[Selected].Value.Equals(1))
                        {
                            NextAct = i;
                        }
                    }
                }
            }
            component.Properties["SourceSelectNumber"].Value = NextAct;
            Selected = "Component" + NextAct.ToString();
            component.Properties["ResultingComponent"].Value = component.Properties[Selected].Value;
        }
        /// <summary>
        /// Called when the value of an I/O signal value has changed.
        /// </summary>
        /// <param name="component"> Component that owns the changed signal. </param>
        /// <param name="changedSignal"> Changed signal. </param>
        public override void OnIOSignalValueChanged(SmartComponent component, IOSignal changedSignal)
        {
            switch (changedSignal.Name)
            {
            case "GroupInputMSB":
                UpdateOutProp(component);
                break;

            case "GroupInputB3":
                UpdateOutProp(component);
                break;

            case "GroupInputB2":
                UpdateOutProp(component);
                break;

            case "GroupInputLSB":
                UpdateOutProp(component);
                break;

            default:
                Logger.AddMessage(new LogMessage("not recognised IO signal change"));
                break;
            }
            Logger.AddMessage(new LogMessage("finished OnIOSignalValueChanged"));
        }
Beispiel #5
0
        /// <summary>
        /// Get last Simulation Time from component.
        /// Function called by Lua Script with 0 parameter:
        ///		()
        ///	Returns double component last simulation time, double Simulator current time, double Simulator State
        /// </summary>
        /// <param name="L">Lua State caller</param>
        /// <returns>Number of return parameters</returns>
        static int GetLastSimulationTime(lua_State L)
        {
            //Get component owner
            lua_getglobal(L, "SmartComponent");
            string compID = lua_tostring(L, -1).ToString();

            SmartComponent myComponent = GetComponent(compID);

            if (myComponent != null)
            {
                if (!lastSimulTimes.ContainsKey(myComponent.UniqueId))
                {
                    lastSimulTimes[myComponent.UniqueId] = -1;
                }

                lua_pushnumber(L, lastSimulTimes[myComponent.UniqueId]);
                lua_pushnumber(L, Simulator.CurrentTime);
                lua_pushnumber(L, (int)Simulator.State);
            }
            else
            {
                Logger.AddMessage("RSLuaScript: Lua Script call get_last_simulation_time of unknown component. Closing it.", LogMessageSeverity.Error);
                lua_close(L);
            }

            return(3);            // number of return parameters
        }
Beispiel #6
0
        /// <summary>
        /// Called when the library or station containing the SmartComponent has been loaded
        /// </summary>
        /// <param name="component">Smart Component</param>
        public override void OnLoad(SmartComponent component)
        {
            base.OnLoad(component);
            bOnLoad = true;

            string dllPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
                             + "\\RobotStudio\\Libraries\\KopiLua.dll";

            if (!System.IO.File.Exists(dllPath))
            {
                if (component.Assets.TryGetAsset("KopiLua.dll", out Asset asset))
                {
                    System.IO.File.WriteAllBytes(dllPath, asset.GetData());
                }

                Logger.AddMessage("RSLuaScript: KopiLua Dll copied to your Libraries folder.", LogMessageSeverity.Warning);
            }

            AppDomain CurrentDomain = AppDomain.CurrentDomain;

            CurrentDomain.AssemblyResolve += new ResolveEventHandler(MyResolver);

            isOnPropertyValueChanged = new Dictionary <string, bool>();
            //luaStates = new Dictionary<string, lua_State>();//Can't handle it here else an error occurs with assembly missing.

            component.Properties["Status"].Value = "OnLoad";
            //Here component is not the final component and don't get saved properties.
            //Only called once for all same instance.

            // Survey log message
            Logger.LogMessageAdded -= OnLogMessageAdded;
            Logger.LogMessageAdded += OnLogMessageAdded;

            bOnLoad = false;
        }
Beispiel #7
0
        /// <summary>
        /// Get a signal value from component.
        /// Function called by Lua Script with 1 parameter:
        ///		(string Signal name)
        ///	Returns number Signal Value
        /// </summary>
        /// <param name="L">Lua State caller</param>
        /// <returns>Number of return parameters</returns>
        static int GetSignal(lua_State L)
        {
            //Get component owner
            lua_getglobal(L, "SmartComponent");
            string compID = lua_tostring(L, -1).ToString();

            SmartComponent myComponent = GetComponent(compID);

            if (myComponent != null)
            {
                string signalName = luaL_checklstring(L, 1).ToString();

                if (myComponent.IOSignals.Contains(signalName))
                {
                    IOSignal ios = myComponent.IOSignals[signalName];

                    lua_pushnumber(L, Convert.ToDouble(ios.Value));
                }
                else
                {
                    Logger.AddMessage("RSLuaScript: Lua Script get Signal value of unknown signal named:" + signalName + ". Check your script file.", LogMessageSeverity.Warning);
                }
            }
            else
            {
                Logger.AddMessage("RSLuaScript: Lua Script get Signal value of unknown component. Closing it.", LogMessageSeverity.Error);
                lua_close(L);
            }

            return(1);            // number of return parameters
        }
Beispiel #8
0
        /// <summary>
        /// Ternary operator IIF
        /// Function called by Lua Script with 3 parameters:
        ///		(Bool condition, Any ValueForTrue, Any ValueForFalse)
        ///	Returns ValueForTrue if condition is true else ValueForFalse
        /// </summary>
        /// <param name="L">Lua State caller</param>
        /// <returns>Number of return parameters</returns>
        static int IIf(lua_State L)
        {
            //Get component owner
            lua_getglobal(L, "SmartComponent");
            string compID = lua_tostring(L, -1).ToString();

            SmartComponent myComponent = GetComponent(compID);

            if (myComponent != null)
            {
                if (lua_isboolean(L, 1))
                {
                    lua_pushvalue(L, (lua_toboolean(L, 1) == 1) ? 2 : 3);
                }
                else
                {
                    Logger.AddMessage("RSLuaScript: " + myComponent.Name + " Lua Script call iif with parameters 1 of different type than Boolean. Check your script file.", LogMessageSeverity.Warning);
                }
            }
            else
            {
                Logger.AddMessage("RSLuaScript: Lua Script call iif of unknown component. Closing it.", LogMessageSeverity.Error);
                lua_close(L);
            }

            return(1);            // number of return parameters
        }
Beispiel #9
0
        /// <summary>
        /// Call on_simulation_step on Lua Script
        /// </summary>
        /// <param name="component">Component owner</param>
        private void UpdateScriptSim(SmartComponent component)
        {
            if (luaStates == null)
            {
                luaStates = new Dictionary <string, lua_State>();
            }

            if (!luaStates.ContainsKey(component.UniqueId))
            {
                LoadFile(component);
            }
            lua_State _luaState = luaStates[component.UniqueId];

            if (_luaState != null)
            {
                // load the function from global
                lua_getglobal(_luaState, "on_simulation_step");
                if (lua_isfunction(_luaState, -1))
                {
                    lua_pcall(_luaState, 0, 1, 0);
                    if (!lua_isnil(_luaState, -1))
                    {
                        Logger.AddMessage("RSLuaScript: " + component.Name + ": on_simulation_step returns: " + lua_tostring(_luaState, -1)?.ToString() + ".", LogMessageSeverity.Error);
                    }
                }
            }
        }
Beispiel #10
0
        /// <summary>
        /// Clear all signals of component.
        /// Function called by Lua Script with 0 parameter:
        ///		()
        ///	Returns Nothing
        /// </summary>
        /// <param name="L">Lua State caller</param>
        /// <returns>Number of return parameters</returns>
        static int ClearSignals(lua_State L)
        {
            //Get component owner
            lua_getglobal(L, "SmartComponent");
            string compID = lua_tostring(L, -1).ToString();

            SmartComponent myComponent = GetComponent(compID);

            if (myComponent != null)
            {
                int curs = 0;
                while (myComponent.IOSignals.Count > 1)
                {
                    string signalName = myComponent.IOSignals[curs].Name;
                    if (signalName != "LoadFile")
                    {
                        myComponent.IOSignals.Remove(signalName);
                    }
                    else
                    {
                        ++curs;
                    }
                }
                Logger.AddMessage("RSLuaScript: Lua Script clear all Signals of " + myComponent.Name, LogMessageSeverity.Information);

                myComponent.Properties["Status"].Value = "Cleared";
            }
            else
            {
                Logger.AddMessage("RSLuaScript: Lua Script clear all Signals of unknown component. Closing it.", LogMessageSeverity.Error);
                lua_close(L);
            }

            return(0);            // number of return parameters
        }
Beispiel #11
0
        /// <summary>
        /// Call on_io_signal_value_changed on Lua Script
        /// </summary>
        /// <param name="component">Component owner</param>
        private void UpdateScriptIOSignals(SmartComponent component, string signalName = "", double signalNewValue = 0)
        {
            if (luaStates == null)
            {
                luaStates = new Dictionary <string, lua_State>();
            }

            if (!luaStates.ContainsKey(component.UniqueId))
            {
                LoadFile(component);
            }
            lua_State _luaState = luaStates[component.UniqueId];

            if (_luaState != null)
            {
                // load the function from global
                lua_getglobal(_luaState, "on_io_signal_value_changed");
                if (lua_isfunction(_luaState, -1))
                {
                    lua_pushstring(_luaState, signalName);
                    lua_pushnumber(_luaState, signalNewValue);
                    lua_pcall(_luaState, 2, 1, 0);
                    if (!lua_isnil(_luaState, -1))
                    {
                        Logger.AddMessage("RSLuaScript: " + component.Name + ": on_io_signal_value_changed returns: " + lua_tostring(_luaState, -1)?.ToString() + ".", LogMessageSeverity.Error);
                    }
                }
            }
        }
Beispiel #12
0
        /// <summary>
        ///  Raised when a message is added.
        /// </summary>
        /// <param name="sender">Sender</param>
        /// <param name="e">The event argument.</param>
        private void OnLogMessageAdded(object sender, LogMessageAddedEventArgs e)
        {
            if (e.Message.Text.StartsWith("RSLuaScript"))
            {
                return;
            }

            if ((e.Message.Text.Contains("Update RSLuaScript"))
                )
            {
                if (DateTime.Compare(DateTime.UtcNow, lastUpdate.AddSeconds(1)) > 0)
                {
                    //Can't use foreach as collection is updated inside
                    for (int i = 0; i < myComponents.Count; ++i)
                    {
                        SmartComponent myComponent = myComponents[i];
                        //Test if component exists as no OnUnLoad event exists.
                        if ((myComponent.ContainingProject == null) ||
                            (myComponent.ContainingProject.GetObjectFromUniqueId(myComponent.UniqueId) == null) ||
                            (myComponent.ContainingProject.Name == ""))
                        {
                            Logger.AddMessage("RSLuaScript: Remove old Component " + myComponent.Name + " from cache. This component works only with named station.", LogMessageSeverity.Information);
                            myComponents.Remove(myComponent);
                            --i;
                            continue;
                        }

                        UpdateScriptIOSignals(myComponent);
                        Logger.AddMessage("RSLuaScript: Updating Component " + myComponent.Name, LogMessageSeverity.Information);
                    }
                    lastUpdate = DateTime.UtcNow;
                }
            }
        }
Beispiel #13
0
        /// <summary>
        /// Get component from current components cache and clean removed ones.
        /// </summary>
        /// <param name="compID">The component UniqueId</param>
        /// <returns>Found Component, null else.</returns>
        static private SmartComponent GetComponent(string compID)
        {
            SmartComponent retComponent = null;

            //Can't use foreach as collection is updated inside
            for (int i = 0; i < myComponents.Count; ++i)
            {
                SmartComponent foundComponent = myComponents[i];
                //Test if component exists as no OnUnLoad event exists.
                if ((foundComponent.ContainingProject == null) ||
                    (foundComponent.ContainingProject.GetObjectFromUniqueId(foundComponent.UniqueId) == null) ||
                    (foundComponent.ContainingProject.Name == ""))
                {
                    Logger.AddMessage("RSLuaScript: Remove old Component " + foundComponent.Name + " from cache. This component works only with named station.", LogMessageSeverity.Information);
                    myComponents.Remove(foundComponent);
                    --i;
                    continue;
                }

                if (foundComponent.UniqueId == compID)
                {
                    retComponent = foundComponent;
                }
            }
            return(retComponent);
        }
Beispiel #14
0
        /// <summary>
        /// Mark sure client is initialized.
        /// </summary>
        /// <param name="smartComponent"></param>
        private void CheckClientAndValues(SmartComponent smartComponent)
        {
            if (client == null)
            {
                client = new S7Client();
                Disconnect(smartComponent);
            }

            int diCount = (int)smartComponent.Properties["DI_Number"].Value;

            if (diCount != bDIO_AddressIsValid[(int)IO.Input].Length)// When just loaded array is not initialized
            {
                UpdateIOCount(smartComponent, diCount, IO.Input);
            }
            int doCount = (int)smartComponent.Properties["DO_Number"].Value;

            if (doCount != bDIO_AddressIsValid[(int)IO.Output].Length)// When just loaded array is not initialized
            {
                UpdateIOCount(smartComponent, diCount, IO.Output);
            }

            for (int i = 0; i < smartComponent.Properties.Count; ++i)
            {
                smartComponent.Properties[i].ValidateValue(smartComponent.Properties[i].Value);
            }
        }
        /// <summary>
        ///   Called when the value of a dynamic property value has changed.
        /// </summary>
        /// <param name="component"> Component that owns the changed property. </param>
        /// <param name="changedProperty"> Changed property. </param>
        /// <param name="oldValue"> Previous value of the changed property. </param>
        public override void OnPropertyValueChanged(SmartComponent component, DynamicProperty changedProperty, Object oldValue)
        {
            PointCloud p       = null;
            Station    station = Project.ActiveProject as Station;

            if (station == null)
            {
                return;
            }

            //Get last cloud
            for (int i = 0; i < station.PointClouds.Count; ++i)
            {
                if (station.PointClouds[i].Name == component.UniqueId)
                {
                    p = station.PointClouds[i];
                }
            }

            if (p == null)
            {
                return;
            }

            if (changedProperty.Name == "Transform")
            {
                p.Transform.GlobalMatrix = (Matrix4)changedProperty.Value;
            }

            if (changedProperty.Name == "Visible")
            {
                p.Visible = (bool)changedProperty.Value;
            }
        }
Beispiel #16
0
        /// <summary>
        /// Called when the value of a dynamic property value has changed.
        /// </summary>
        /// <param name="component"> Component that owns the changed property. </param>
        /// <param name="changedProperty"> Changed property. </param>
        /// <param name="oldValue"> Previous value of the changed property. </param>
        public override void OnPropertyValueChanged(SmartComponent component, DynamicProperty changedProperty, Object oldValue)
        {
            if (changedProperty.Name == "Status")
            {
                return;
            }

            base.OnPropertyValueChanged(component, changedProperty, oldValue);
            if (bOnLoad)
            {
                UpdateComponentList(component);
                UpdateControllers(component);
                isOnPropertyValueChanged[component.UniqueId] = false;
                return;
            }
            if (!isOnPropertyValueChanged.ContainsKey(component.UniqueId))
            {
                isOnPropertyValueChanged[component.UniqueId] = false;
            }

            bool bIsOnPropertyValueChanged = isOnPropertyValueChanged[component.UniqueId];

            isOnPropertyValueChanged[component.UniqueId] = true;

            if (changedProperty.Name == "Controller")
            {
                if ((string)changedProperty.Value != "Update")
                {
                    if (GetController(component) != null)
                    {
                        Logger.AddMessage("RSMoveMecha: Connecting Component " + component.Name + " to " + (string)changedProperty.Value, LogMessageSeverity.Information);
                        component.Properties["Status"].Value = "Connected";
                    }
                }
            }
            if (changedProperty.Name == "CtrlMechanism")
            {
                GetController(component);
            }
            if (changedProperty.Name == "Mechanism")
            {
                Mechanism mecha = (Mechanism)component.Properties["Mechanism"].Value;
                if (mecha != null)
                {
                    int[] mechaAxes         = mecha.GetActiveJoints();
                    int   iMechNumberOfAxes = mechaAxes.Length;
                    component.Properties["MechSpecAxis"].Attributes["MaxValue"] = iMechNumberOfAxes.ToString();
                }
            }

            if (!bIsOnPropertyValueChanged)
            {
                //Update available controller
                UpdateControllers(component);
                //Save Modified Component for EventHandlers
                UpdateComponentList(component);
            }

            isOnPropertyValueChanged[component.UniqueId] = bIsOnPropertyValueChanged;
        }
Beispiel #17
0
        protected void sendState(SmartComponent component)
        {
            int PORT = (int)component.Properties["PortNumber"].Value;

            using (var sock = new UdpClient())
            {
                LineSensor.Builder sensorData  = LineSensor.CreateBuilder();
                Point.Builder      sensedPoint = new Point.Builder();
                Point.Builder      start       = new Point.Builder();
                Point.Builder      end         = new Point.Builder();

                UInt32  sensorIDProperty    = Convert.ToUInt32(component.Properties["SensorID"].Value);
                Vector3 sensedPointProperty = (Vector3)component.Properties["SensedPoint"].Value;
                String  sensedPartProperty  = Convert.ToString(component.Properties["SensedPart"].Value);
                Vector3 startProperty       = (Vector3)component.Properties["Start"].Value;
                Vector3 endProperty         = (Vector3)component.Properties["End"].Value;
                double  radiusProperty      = (double)component.Properties["Radius"].Value;

                // convert point from m to mm
                sensedPointProperty = sensedPointProperty.Multiply(1000);

                sensedPoint.SetX(sensedPointProperty.x)
                .SetY(sensedPointProperty.y)
                .SetZ(sensedPointProperty.z);

                start.SetX(startProperty.x)
                .SetY(startProperty.y)
                .SetZ(startProperty.z);

                end.SetX(endProperty.x)
                .SetY(endProperty.y)
                .SetZ(endProperty.z);

                sensorData.SetSensedPoint(sensedPoint)
                .SetStart(start)
                .SetEnd(end)
                .SetRadius(radiusProperty)
                .SetSensedPart(sensedPartProperty)
                .SetSensorID(sensorIDProperty);
                //if(sensorData.SensorID == 42)
                //{
                //    Debug.WriteLine($"sensor nbr {sensorData.SensorID} numbers: ({sensorData.SensedPoint.X}, {sensorData.SensedPoint.Y}, {sensorData.SensedPoint.Z})");
                //}
                LineSensor data = sensorData.Build();

                using (MemoryStream memoryStream = new MemoryStream())
                {
                    data.WriteTo(memoryStream);
                    var bytesSent = sock.SendAsync(memoryStream.ToArray(), (int)memoryStream.Length, "localhost", PORT);
                    //int bytesSent = sock.Send(memoryStream.ToArray(), (int)memoryStream.Length, "localhost", PORT);
                    //if (bytesSent < 0)
                    //{
                    //    Console.WriteLine("ERROR");
                    //}
                }

                //byte[] bytes = Encoding.UTF8.GetBytes("hello, world!");
                //sock.Send(bytes, bytes.Length, "localhost", PORT);
            }
        }
Beispiel #18
0
 //START HERE: IO SIGNAL VALUE CHANGED -> UPDATE SENSOR (COMPONENT)
 public override void OnIOSignalValueChanged(SmartComponent component, IOSignal signal)
 {
     if (signal.Name == "Active")
     {
         UpdateSensor(component);
     }
 }
Beispiel #19
0
        /// <summary>
        /// Called during simulation.
        /// </summary>
        /// <param name="component"> Simulated component. </param>
        /// <param name="simulationTime"> Time (in ms) for the current simulation step. </param>
        /// <param name="previousTime"> Time (in ms) for the previous simulation step. </param>
        /// <remarks>
        /// For this method to be called, the component must be marked with
        /// simulate="true" in the xml file.
        /// </remarks>
        public override void OnSimulationStep(SmartComponent component, double simulationTime, double previousTime)
        {
            // if activated
            if (component.IOSignals["Activate"].Value.Equals(1))
            {
                // if there is data to be read
                if (commSocket.Available > 0)
                {
                    commSocket.Receive(msgBuffer, msgSize, SocketFlags.None);

                    var matrix = "";
                    for (int i = 0; i < 4; i++)
                    {
                        for (int j = 0; j < 4; j++)
                        {
                            matrix += (String.Format("{0:0.00}", BitConverter.ToSingle(msgBuffer, 4 * i + j))).PadRight(12);
                        }
                        if (i < 3)
                        {
                            matrix += "\r\n";
                        }
                    }
                    component.Properties["Matrix"].Value = matrix;

                    commSocket.Send(msgBuffer);
                }
            }
        }
Beispiel #20
0
 /// <summary>
 /// Called when the value of an I/O signal value has changed.
 /// </summary>
 /// <param name="component"> Component that owns the changed signal. </param>
 /// <param name="changedSignal"> Changed signal. </param>
 public override void OnIOSignalValueChanged(SmartComponent component, IOSignal changedSignal)
 {
     if (changedSignal.Name.Equals("Activate"))
     {
         if (changedSignal.Value.Equals(1))
         {
             try
             {
                 InitializeSocket((String)component.Properties["IP"].Value, (int)component.Properties["port"].Value);
             }
             catch (SocketException)
             {
                 component.IOSignals["Activate"].Value = false;
             }
             catch (Exception)
             {
                 throw;
             }
         }
         else
         {
             CloseSocket();
         }
     }
 }
Beispiel #21
0
        /// <summary>
        /// Called when the library or station containing the SmartComponent has been loaded
        /// </summary>
        /// <param name="component">Smart Component</param>
        public override void OnLoad(SmartComponent component)
        {
            base.OnLoad(component);
            bOnLoad = true;
            isOnPropertyValueChanged             = new Dictionary <string, bool>();
            isUpdatingControllers                = new Dictionary <string, bool>();
            component.Properties["Status"].Value = "OnLoad";
            //Here component is not the final component and don't get saved properties.
            //Only called once for all same instance.
            //Connect Controller eventHandler
            //ABB.Robotics.RobotStudio.Controllers.ControllerReferenceChangedEventHandler
            ControllerManager.ControllerAdded   -= OnControllerAdded;
            ControllerManager.ControllerAdded   += OnControllerAdded;
            ControllerManager.ControllerRemoved -= OnControllerRemoved;
            ControllerManager.ControllerRemoved += OnControllerRemoved;
            //ActiveStation is null here at startup
            component.ContainingProject.Saving -= OnSaving;
            component.ContainingProject.Saving += OnSaving;

            // Survey log message for checked programs at end of apply.
            Logger.LogMessageAdded -= OnLogMessageAdded;
            Logger.LogMessageAdded += OnLogMessageAdded;

            bOnLoad = false;
        }
Beispiel #22
0
        /// <summary>
        /// Update GO list depends GO_ByteNumber
        /// </summary>
        /// <param name="component">Component that owns signals. </param>
        /// <param name="oldCount">Old GO count</param>
        private void UpdateGOCount(SmartComponent component, int oldCount)
        {
            int newGOCount = (int)component.Properties["GO_ByteNumber"].Value;

            component.Properties["GO_FirstByteAddress"].UIVisible = (newGOCount > 0);
            if (newGOCount > oldCount)
            {
                for (int i = oldCount; i < newGOCount; i++)
                {
                    string goName = "GO_" + i.ToString();
                    if (!component.IOSignals.Contains(goName))
                    {
                        IOSignal ios = new IOSignal(goName, IOSignalType.DigitalGroupInput);
                        ios.ReadOnly  = true;
                        ios.UIVisible = false;
                        component.IOSignals.Add(ios);
                    }
                }
            }
            else
            {
                for (int i = oldCount - 1; i >= newGOCount; i--)
                {
                    string goName = "GO_" + i.ToString();
                    if (component.IOSignals.Contains(goName))
                    {
                        component.IOSignals.Remove(goName);
                    }
                }
            }
        }
Beispiel #23
0
        /// <summary>
        /// Raised when a controller reference is removed.
        /// </summary>
        /// <param name="sender">Sender</param>
        /// <param name="e">The event argument.</param>
        public void OnControllerRemoved(object sender, ControllerReferenceChangedEventArgs e)
        {
            //Can't use foreach as collection is updated inside
            for (int i = 0; i < myComponents.Count; ++i)
            {
                SmartComponent myComponent = myComponents[i];
                //Test if component exists as no OnUnLoad event exists.
                if ((myComponent.ContainingProject == null) ||
                    (myComponent.ContainingProject.GetObjectFromUniqueId(myComponent.UniqueId) == null) ||
                    (myComponent.ContainingProject.Name == ""))
                {
                    Logger.AddMessage("RSMoveMecha: Remove old Component " + myComponent.Name + " from cache.", LogMessageSeverity.Information);
                    myComponents.Remove(myComponent);
                    --i;
                    continue;
                }

                string guid = ((string)myComponent.Properties["Controller"].Value).Split(' ')[0];
                if (guid != "")
                {
                    Guid systemId = new Guid(guid);
                    if (e.Controller.SystemId == systemId)
                    {
                        Logger.AddMessage("RSMoveMecha: Disconnecting Component " + myComponent.Name, LogMessageSeverity.Information);
                        myComponent.Properties["Status"].Value = "Disconnected";
                    }
                }
            }
        }
Beispiel #24
0
        //*********************************************************************************************
        /// <summary>
        /// Update internal component list to get them in EventHandler
        /// </summary>
        /// <param name="component">Component to update.</param>
        protected void UpdateComponentList(SmartComponent component)
        {
            bool bFound = false;

            for (int i = 0; i < myComponents.Count; ++i)
            {
                SmartComponent myComponent = myComponents[i];
                //Test if component exists as no OnUnLoad event exists.
                if ((myComponent.ContainingProject == null) ||
                    (myComponent.ContainingProject.GetObjectFromUniqueId(myComponents[i].UniqueId) == null) ||
                    (myComponent.ContainingProject.Name == "") ||
                    (bFound && (myComponent.UniqueId == component.UniqueId)))
                {
                    Logger.AddMessage("RSMoveMecha: Remove old Component " + myComponents[i].Name + " from cache.", LogMessageSeverity.Information);
                    myComponents.Remove(myComponent);
                    --i;
                    continue;
                }
                if (myComponents[i].UniqueId == component.UniqueId)
                {
                    myComponents[i] = component;
                    bFound          = true;
                }
            }
            if (!bFound)
            {
                myComponents.Add(component);
            }
        }
Beispiel #25
0
        /// <summary>
        /// Called when the value of an I/O signal value has changed.
        /// </summary>
        /// <param name="component"> Component that owns the changed signal. </param>
        /// <param name="changedSignal"> Changed signal. </param>
        public override void OnIOSignalValueChanged(SmartComponent component, IOSignal changedSignal)
        {
            if (changedSignal.Name == "LoadFile")
            {
                if ((int)changedSignal.Value == 1)
                {
                    string initialDir = component.ContainingProject?.FileInfo?.DirectoryName ?? "";

                    // First look at Example file
                    if (!string.IsNullOrEmpty(initialDir))
                    {
                        if (!System.IO.File.Exists(initialDir + "\\RSLuaScript.lua"))
                        {
                            if (component.Assets.TryGetAsset("RSLuaScript.lua", out Asset asset))
                            {
                                System.IO.File.WriteAllBytes(initialDir + "\\RSLuaScript.lua", asset.GetData());
                            }
                        }
                    }

                    System.Windows.Forms.OpenFileDialog openFileDialog = new System.Windows.Forms.OpenFileDialog
                    {
                        Title            = "Open Lua Script File",
                        InitialDirectory = initialDir,
                        Filter           = "Lua files (*.lua)|*.lua|All files (*.*)|*.*",
                        RestoreDirectory = true,
                        FileName         = (string)component.Properties["LuaFile"].Value
                    };

                    if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        if ((string)component.Properties["LuaFile"].Value == openFileDialog.FileName)
                        {
                            if (System.Windows.Forms.MessageBox.Show("Do you want to reopen this file, then execute main script once more?"
                                                                     , "Same file reopened"
                                                                     , System.Windows.Forms.MessageBoxButtons.YesNo
                                                                     , System.Windows.Forms.MessageBoxIcon.Question
                                                                     ) == System.Windows.Forms.DialogResult.Yes)
                            {
                                component.Properties["LuaFile"].Value = "";                                 //To raise OnPropertyValueChanged
                            }
                        }
                        component.Properties["LuaFile"].Value = openFileDialog.FileName;
                        component.Properties["Status"].Value  = "Lua File Loaded";
                    }
                }
            }
            else
            {
                if (changedSignal.SignalType == IOSignalType.AnalogInput ||
                    changedSignal.SignalType == IOSignalType.DigitalGroupInput ||
                    changedSignal.SignalType == IOSignalType.DigitalInput)
                {
                    UpdateScriptIOSignals(component, changedSignal.Name, Convert.ToDouble(changedSignal.Value));
                }
            }

            UpdateComponentList(component);
        }
Beispiel #26
0
        //STEP 2: UPDATE SENSOR (COMPONENT) -> SENSE (COMPONENT)
        protected void UpdateSensor(SmartComponent component)
        {
            int active = (int)component.IOSignals["Active"].Value;
            // WHAT THE HELL DOES THIS DO? I WAS JUST STARTING TO FEEL AT HOME IN C#
            int result = active != 0 ? Sense(component) : 0;

            component.IOSignals["SensorOut"].Value = result;
        }
Beispiel #27
0
        /// <summary>
        /// Called from [!:SmartComponent.InitializeCodeBehind].
        /// </summary>
        /// <param name="component">Smart Component</param>
        public override void OnInitialize(SmartComponent component)
        {
            base.OnInitialize(component);
            CheckClientAndValues(component);

            UpdateIOCount(component, 0, IO.Input);
            UpdateIOCount(component, 0, IO.Output);
        }
Beispiel #28
0
 /// <summary>
 /// This function returns a textual explaination of the error code
 /// </summary>
 /// <param name="component"></param>
 /// <param name="result"></param>
 private void ShowResult(SmartComponent component, int result)
 {
     if (result != 0)
     {
         Disconnect(component);
         component.Properties["Status"].Value = client.ErrorText(result);
         Logger.AddMessage(new LogMessage("WW: " + component.Name + " error: " + client.ErrorText(result), LogMessageSeverity.Warning));
     }
 }
Beispiel #29
0
        /// <summary>
        /// Called from [!:SmartComponent.InitializeCodeBehind].
        /// </summary>
        /// <param name="component">Smart Component</param>
        public override void OnInitialize(SmartComponent component)
        {
            ///Never Called???
            base.OnInitialize(component);
            CheckClientAndValues(component);

            UpdateGICount(component, 0);
            UpdateGOCount(component, 0);
        }
Beispiel #30
0
        /// <summary>
        /// Called if the library containing the SmartComponent has been replaced
        /// </summary>
        /// <param name="component">Smart Component</param>
        public override void OnLibraryReplaced(SmartComponent component)
        {
            base.OnLibraryReplaced(component);
            component.Properties["Status"].Value = "OnLibraryReplaced";

            //Save Modified Component for EventHandlers
            //OnPropertyValueChanged is not called here
            UpdateComponentList(component);
        }