Beispiel #1
0
        public async Task OnMoveView(string viewID, bool up)
        {
            lastActivity = Timestamp.Now;

            View?view = model.Views.Find(v => v.ID == viewID);

            if (view == null)
            {
                throw new Exception("Unknown viewID " + viewID);
            }

            int i = model.Views.IndexOf(view);

            if (up && i > 0)
            {
                model.Views[i]     = model.Views[i - 1];
                model.Views[i - 1] = view;
            }
            else if (!up && i < model.Views.Count - 1)
            {
                model.Views[i]     = model.Views[i + 1];
                model.Views[i + 1] = view;
            }

            DataValue   dv     = DataValue.FromObject(model.Views);
            MemberValue member = MemberValue.Make(moduleID, model.ID, nameof(DashboardModel.Views), dv);
            await connection.UpdateConfig(member);
        }
Beispiel #2
0
        public async Task <string> OnDuplicateView(string viewID)
        {
            lastActivity = Timestamp.Now;

            View?view = model.Views.Find(v => v.ID == viewID);

            if (view == null)
            {
                throw new Exception("Unknown viewID " + viewID);
            }

            View newView = new View()
            {
                ID     = GernerateID(6),
                Name   = view.Name,
                Group  = view.Group,
                Config = view.Config,
                Type   = view.Type,
            };

            model.Views.Add(newView);
            DataValue   dv     = DataValue.FromObject(model.Views);
            MemberValue member = MemberValue.Make(moduleID, model.ID, nameof(DashboardModel.Views), dv);
            await connection.UpdateConfig(member);

            await CreateView(newView);

            return(newView.ID);
        }
Beispiel #3
0
        private MemberValue MakeMemberValue(string id, KeyValuePair <string, JToken?> entry)
        {
            JToken?   value     = entry.Value;
            DataValue dataValue = value == null ? DataValue.Empty : DataValue.FromObject(value);

            // Console.WriteLine($"{id}.{entry.Key}: {dataValue.ToString()}");
            return(MemberValue.Make(moduleID, id, entry.Key, dataValue));
        }
Beispiel #4
0
        public async Task OnRenameView(string viewID, string newName)
        {
            lastActivity = Timestamp.Now;

            View?view = model.Views.Find(v => v.ID == viewID);

            if (view == null)
            {
                throw new Exception("Unknown viewID " + viewID);
            }

            view.Name = newName;

            DataValue   dv     = DataValue.FromObject(view.Name);
            MemberValue member = MemberValue.Make(moduleID, view.ID, nameof(View.Name), dv);
            await connection.UpdateConfig(member);
        }
Beispiel #5
0
        async Task ViewContext.SaveViewConfiguration(DataValue newConfig)
        {
            ViewBase?view = currentView;

            if (view == null)
            {
                return;
            }
            var entry = views.FirstOrDefault(p => p.Value == view);

            if (entry.Value != view)
            {
                return;
            }
            string      viewID = entry.Key;
            MemberValue member = MemberValue.Make(moduleID, viewID, nameof(View.Config), newConfig);
            await connection.UpdateConfig(member);

            view.Config = newConfig;
        }
Beispiel #6
0
        public async Task <string> OnDuplicateConvertHistoryPlot(string viewID)
        {
            lastActivity = Timestamp.Now;

            View?view = model.Views.Find(v => v.ID == viewID);

            if (view == null)
            {
                throw new Exception("Unknown viewID " + viewID);
            }

            Identify?identify = typeof(View_HistoryPlots).GetCustomAttribute <Identify>();

            if (identify == null || view.Type != identify.ID)
            {
                throw new Exception("View is not a HistoryPlot!");
            }

            var config    = view.Config.Object <View_HistoryPlots.ViewConfig>();
            var newConfig = Pages.ConfigFromHistoryPlot.Convert(config);

            View newView = new View()
            {
                ID     = GernerateID(6),
                Name   = view.Name,
                Group  = view.Group,
                Config = DataValue.FromObject(newConfig, indented: true),
                Type   = typeof(Pages.View).GetCustomAttribute <Identify>() !.ID,
            };

            model.Views.Add(newView);
            DataValue   dv     = DataValue.FromObject(model.Views);
            MemberValue member = MemberValue.Make(moduleID, model.ID, nameof(DashboardModel.Views), dv);
            await connection.UpdateConfig(member);

            await CreateView(newView);

            return(newView.ID);
        }
Beispiel #7
0
        public override async Task <ReqResult> OnUiRequestAsync(string command, DataValue parameters)
        {
            bool hasModuleID = !string.IsNullOrEmpty(configuration.ModuleID);

            moduleID = hasModuleID ? configuration.ModuleID : "CALC";

            switch (command)
            {
            case "GetModel": {
                ObjectInfo root = await Connection.GetRootObject(moduleID);

                RootID = root.ID;

                await Connection.EnableVariableValueChangedEvents(SubOptions.AllUpdates(sendValueWithEvent: true), root.ID);

                return(await GetModelResult());
            }

            case "Save": {
                SaveParams saveParams = parameters.Object <SaveParams>() ?? throw new Exception("SaveParams is null");
                string     objID      = saveParams.ID;
                IDictionary <string, JToken?> dict = saveParams.Obj;
                MemberValue[] members = dict
                                        .Where(kv => kv.Key != "ID")
                                        .Select(entry => MakeMemberValue(objID, entry))
                                        .ToArray();
                await Connection.UpdateConfig(members);

                return(await GetModelResult());
            }

            case "Delete": {
                ObjectRef obj = ObjectRef.Make(moduleID, parameters.GetString() ?? "");
                await Connection.UpdateConfig(ObjectValue.Make(obj, DataValue.Empty));

                return(await GetModelResult());
            }

            case "AddObject": {
                AddObjectParams addParams = parameters.Object <AddObjectParams>() ?? throw new Exception("AddObjectParams is null");
                ObjectRef       objParent = ObjectRef.Make(moduleID, addParams.ParentObjID);
                DataValue       dataValue = DataValue.FromObject(new {
                        ID   = addParams.NewObjID,
                        Name = addParams.NewObjName
                    });
                var element = AddArrayElement.Make(objParent, addParams.ParentMember, dataValue);
                await Connection.UpdateConfig(element);

                return(await GetModelResult());
            }

            case "MoveObject": {
                var  move = parameters.Object <MoveObject_Params>() ?? throw new Exception("MoveObject_Params is null");
                bool up   = move.Up;

                ObjectRef  obj     = ObjectRef.Make(moduleID, move.ObjID);
                ObjectInfo objInfo = await Connection.GetObjectByID(obj);

                MemberRefIdx?parentMember = objInfo.Parent;

                if (parentMember.HasValue)
                {
                    MemberValue value = await Connection.GetMemberValue(parentMember.Value.ToMemberRef());

                    DataValue v = value.Value;
                    if (v.IsArray)
                    {
                        JArray array = (JArray)StdJson.JTokenFromString(v.JSON);
                        int    index = parentMember.Value.Index;
                        if (up && index > 0)
                        {
                            JToken tmp = array[index - 1];
                            array[index - 1] = array[index];
                            array[index]     = tmp;

                            MemberValue mv = MemberValue.Make(parentMember.Value.ToMemberRef(), DataValue.FromObject(array));
                            await Connection.UpdateConfig(mv);
                        }
                        else if (!up && index < array.Count - 1)
                        {
                            JToken tmp = array[index + 1];
                            array[index + 1] = array[index];
                            array[index]     = tmp;

                            MemberValue mv = MemberValue.Make(parentMember.Value.ToMemberRef(), DataValue.FromObject(array));
                            await Connection.UpdateConfig(mv);
                        }
                    }
                }

                return(await GetModelResult());
            }

            case "ReadModuleObjects": {
                var pars = parameters.Object <ReadModuleObjectsParams>() ?? throw new Exception("ReadModuleObjectsParams is null");

                ObjectInfos objects;

                try {
                    objects = await Connection.GetAllObjects(pars.ModuleID);
                }
                catch (Exception) {
                    objects = new ObjectInfos();
                }

                Func <Variable, bool> isMatch = GetMatchPredicate(pars.ForType);

                return(ReqResult.OK(new {
                        Items = objects.Where(o => o.Variables.Any(isMatch)).Select(o => new {
                            Type = o.ClassName,
                            ID = o.ID.ToEncodedString(),
                            Name = o.Name,
                            Variables = o.Variables.Where(isMatch).Select(v => v.Name).ToArray()
                        }).ToArray()
                    }));
            }

            default:
                return(ReqResult.Bad("Unknown command: " + command));
            }
        }
        public override async Task <ReqResult> OnUiRequestAsync(string command, DataValue parameters)
        {
            bool   hasModuleID = !(configuration == null || string.IsNullOrEmpty(configuration.ModuleID));
            string moduleID    = hasModuleID ? configuration !.ModuleID : "IO";

            switch (command)
            {
            case "GetModel": {
                objects = await Connection.GetAllObjects(moduleID);

                mapVariables.Clear();
                ObjectInfo           root      = objects.FirstOrDefault(o => !o.Parent.HasValue);
                List <VariableValue> variables = await Connection.ReadAllVariablesOfObjectTree(root.ID);

                await Connection.EnableVariableValueChangedEvents(SubOptions.AllUpdates(sendValueWithEvent: true), root.ID);

                foreach (VariableValue vv in variables)
                {
                    mapVariables[vv.Variable] = vv.Value;
                }

                TreeNode node = TransformModel(objects);

                MetaInfos types = await Connection.GetMetaInfos(moduleID);

                objTypes.Clear();
                foreach (ClassInfo ci in types.Classes)
                {
                    objTypes[ci.FullName] = ci;
                }
                enumTypes.Clear();
                foreach (EnumInfo en in types.Enums)
                {
                    enumTypes[en.FullName] = en;
                }
                structTypes.Clear();
                foreach (StructInfo sn in types.Structs)
                {
                    structTypes[sn.FullName] = sn;
                }

                JObject typMap = new JObject();
                foreach (ClassInfo ci in types.Classes)
                {
                    var members = ci.ObjectMember
                                  .Where(m => m.Dimension == Dimension.Array)
                                  .Select(m => new {
                            Array = m.Name,
                            Type  = m.ClassName
                        }).ToArray();

                    var entry = new {
                        ObjectMembers = members
                    };

                    typMap[ci.FullName] = new JRaw(StdJson.ObjectToString(entry));
                }

                var locations = await Connection.GetLocations();

                hasLocations = locations.Count > 0;
                rootLocation = hasLocations ? LocationRef.FromLocationID(locations[0].ID) : (LocationRef?)null;

                return(ReqResult.OK(new {
                        ObjectTree = node,
                        TypeInfo = typMap,
                        Locations = locations,
                    }));
            }

            case "GetObject": {
                GetObjectParams pars   = parameters.Object <GetObjectParams>() ?? throw new Exception("GetObjectParams is null");
                var             values = await GetObjectMembers(pars.ID, pars.Type);

                ClassInfo info       = objTypes[pars.Type];
                var       childTypes = info.ObjectMember
                                       .GroupBy(om => om.ClassName)
                                       .Select(g => new ChildType()
                    {
                        TypeName = g.Key,
                        Members  = g.Select(x => x.Name).ToArray()
                    }).ToList();

                var res = new {
                    ObjectValues = values,
                    ChildTypes   = childTypes
                };
                return(ReqResult.OK(res));
            }

            case "Save": {
                SaveParams saveParams = parameters.Object <SaveParams>() ?? throw new Exception("SaveParams is null");

                foreach (var m in saveParams.Members)
                {
                    Console.WriteLine(m.Name + " => " + m.Value);
                }
                ObjectRef     obj = ObjectRef.FromEncodedString(saveParams.ID);
                MemberValue[] mw  = saveParams.Members.Select(m => MemberValue.Make(obj, m.Name, DataValue.FromJSON(m.Value))).ToArray();

                await Connection.UpdateConfig(mw);

                objects = await Connection.GetAllObjects(moduleID);

                TreeNode node = TransformModel(objects);

                var values = await GetObjectMembers(saveParams.ID, saveParams.Type);

                return(ReqResult.OK(new {
                        ObjectValues = values,
                        ObjectTree = node
                    }));
            }

            case "Delete": {
                ObjectRef obj = ObjectRef.FromEncodedString(parameters.GetString() ?? "");
                await Connection.UpdateConfig(ObjectValue.Make(obj, DataValue.Empty));

                objects = await Connection.GetAllObjects(moduleID);

                TreeNode node = TransformModel(objects);
                return(ReqResult.OK(node));
            }

            case "AddObject": {
                AddObjectParams addParams = parameters.Object <AddObjectParams>() ?? throw new Exception("AddObjectParams is null");
                ObjectRef       objParent = ObjectRef.FromEncodedString(addParams.ParentObjID);
                DataValue       dataValue = DataValue.FromObject(new {
                        ID   = addParams.NewObjID,
                        Name = addParams.NewObjName
                    });
                var element = AddArrayElement.Make(objParent, addParams.ParentMember, dataValue);
                await Connection.UpdateConfig(element);

                objects = await Connection.GetAllObjects(moduleID);

                List <VariableValue> newVarVals = await Connection.ReadAllVariablesOfObjectTree(ObjectRef.Make(objParent.ModuleID, addParams.NewObjID));

                foreach (VariableValue vv in newVarVals)
                {
                    mapVariables[vv.Variable] = vv.Value;
                }

                TreeNode node = TransformModel(objects);
                return(ReqResult.OK(new {
                        ObjectID = ObjectRef.Make(moduleID, addParams.NewObjID),
                        Tree = node
                    }));
            }

            case "DragDrop": {
                DragDropParams dropParams = parameters.Object <DragDropParams>() ?? throw new Exception("DragDropParams is null");

                ObjectRef   obj      = ObjectRef.FromEncodedString(dropParams.FromID);
                ObjectValue objValue = await Connection.GetObjectValueByID(obj);

                var deleteObj = ObjectValue.Make(obj, DataValue.Empty);

                ObjectRef objParent = ObjectRef.FromEncodedString(dropParams.ToID);

                var addElement = AddArrayElement.Make(objParent, dropParams.ToArray, objValue.Value);

                await Connection.UpdateConfig(new ObjectValue[] { deleteObj }, new MemberValue[0], new AddArrayElement[] { addElement });

                objects = await Connection.GetAllObjects(moduleID);

                TreeNode node = TransformModel(objects);
                return(ReqResult.OK(node));
            }

            case "WriteVariable": {
                var write = parameters.Object <WriteVariable_Params>() ?? throw new Exception("WriteVariable_Params is null");
                VTQ vtq   = new VTQ(Timestamp.Now, Quality.Good, DataValue.FromJSON(write.V));
                await Connection.WriteVariable(ObjectRef.FromEncodedString(write.ObjID), write.Var, vtq);

                return(ReqResult.OK());
            }

            case "MoveObject": {
                var  move = parameters.Object <MoveObject_Params>() ?? throw new Exception("MoveObject_Params is null");
                bool up   = move.Up;

                ObjectRef  obj     = ObjectRef.FromEncodedString(move.ObjID);
                ObjectInfo objInfo = await Connection.GetObjectByID(obj);

                MemberRefIdx?parentMember = objInfo.Parent;

                if (parentMember.HasValue)
                {
                    MemberValue value = await Connection.GetMemberValue(parentMember.Value.ToMemberRef());

                    DataValue v = value.Value;
                    if (v.IsArray)
                    {
                        JArray array = (JArray)StdJson.JTokenFromString(v.JSON);
                        int    index = parentMember.Value.Index;
                        if (up && index > 0)
                        {
                            JToken tmp = array[index - 1];
                            array[index - 1] = array[index];
                            array[index]     = tmp;

                            MemberValue mv = MemberValue.Make(parentMember.Value.ToMemberRef(), DataValue.FromObject(array));
                            await Connection.UpdateConfig(mv);
                        }
                        else if (!up && index < array.Count - 1)
                        {
                            JToken tmp = array[index + 1];
                            array[index + 1] = array[index];
                            array[index]     = tmp;

                            MemberValue mv = MemberValue.Make(parentMember.Value.ToMemberRef(), DataValue.FromObject(array));
                            await Connection.UpdateConfig(mv);
                        }
                    }
                }

                objects = await Connection.GetAllObjects(moduleID);

                TreeNode node = TransformModel(objects);
                return(ReqResult.OK(node));
            }

            case "Browse": {
                var browse = parameters.Object <Browse_Params>() ?? throw new Exception("Browse_Params is null");

                var          m   = MemberRef.Make(ObjectRef.FromEncodedString(browse.ObjID), browse.Member);
                BrowseResult res = await Connection.BrowseObjectMemberValues(m);

                return(ReqResult.OK(res.Values.Select(d => d.GetString())));
            }

            case "GetNewID": {
                string type = parameters.GetString() ?? throw new Exception("Type parameter is null");
                string id   = GetObjectID(type);
                return(ReqResult.OK(id));
            }

            default:
                return(ReqResult.Bad("Unknown command: " + command));
            }
        }
Beispiel #9
0
        private async Task InitAdapter(CalcInstance adapter)
        {
            if (adapter.Instance == null)
            {
                throw new Exception("InitAdapter: instance is null");
            }
            Calculation info = adapter.CalcConfig.ToCalculation();

            try {
                var initParams = new InitParameter()
                {
                    Calculation  = info,
                    LastOutput   = adapter.LastOutputValues,
                    LastState    = adapter.LastStateValues,
                    ConfigFolder = Path.GetDirectoryName(base.modelFileName) ?? "",
                    DataFolder   = initInfo.DataFolder,
                    ModuleConfig = moduleConfig.ToNamedValues()
                };
                adapter.State = State.InitStarted;
                InitResult res = await adapter.Instance.Initialize(initParams, new Wrapper(this, info));

                if (adapter.State == State.InitStarted)
                {
                    Config.Input[]  newInputs  = res.Inputs.Select(ip => MakeInput(ip, adapter.CalcConfig)).ToArray();
                    Config.Output[] newOutputs = res.Outputs.Select(ip => MakeOutput(ip, adapter.CalcConfig)).ToArray();
                    Config.State[]  newStates  = res.States.Select(MakeState).ToArray();

                    bool inputsChanged  = !StdJson.ObjectsDeepEqual(adapter.CalcConfig.Inputs, newInputs);
                    bool outputsChanged = !StdJson.ObjectsDeepEqual(adapter.CalcConfig.Outputs, newOutputs);
                    bool statesChanged  = !StdJson.ObjectsDeepEqual(adapter.CalcConfig.States, newStates);

                    var changedMembers = new List <MemberValue>(2);

                    if (inputsChanged)
                    {
                        changedMembers.Add(MemberValue.Make(moduleID, adapter.CalcConfig.ID, "Inputs", DataValue.FromObject(newInputs)));
                    }

                    if (outputsChanged)
                    {
                        changedMembers.Add(MemberValue.Make(moduleID, adapter.CalcConfig.ID, "Outputs", DataValue.FromObject(newOutputs)));
                    }

                    if (statesChanged)
                    {
                        changedMembers.Add(MemberValue.Make(moduleID, adapter.CalcConfig.ID, "States", DataValue.FromObject(newStates)));
                    }

                    if (changedMembers.Count > 0)
                    {
                        await UpdateConfig(GetModuleOrigin(),
                                           updateOrDeleteObjects : new ObjectValue[0],
                                           updateOrDeleteMembers : changedMembers.ToArray(),
                                           addArrayElements : new AddArrayElement[0]);
                    }

                    adapter.State = State.InitComplete;
                }
            }
            catch (Exception e) {
                Exception exp = e.GetBaseException() ?? e;
                adapter.State     = State.InitError;
                adapter.LastError = exp.Message;
                throw new Exception($"Initialize of calculation {info.Name} failed: " + exp.Message, exp);
            }
        }