public override async Task <ReqResult> OnUiRequestAsync(string command, DataValue parameters) { switch (command) { case "ReadModuleVariables": if (activeModuleID != "") { await Connection.DisableChangeEvents(); } var pars = parameters.Object <ReadModuleVariables_Params>(); string moduleID = string.IsNullOrEmpty(pars.ModuleID) ? modules[0].ID : pars.ModuleID; ObjectInfo rootObjInfo = await Connection.GetRootObject(moduleID); ObjectRef rootObj = rootObjInfo.ID; ObjectInfo[] objects = await Connection.GetAllObjects(moduleID); SetObjectNameMap(objects); VariableValue[] values = await Connection.ReadAllVariablesOfObjectTree(rootObj); await Connection.EnableVariableValueChangedEvents(SubOptions.AllUpdates(sendValueWithEvent: true), rootObj); VarEntry[] entries = values.Select(MapVarValue).ToArray(); activeModuleID = moduleID; var result = new ReadModuleVariables_Result() { Modules = modules, ModuleID = moduleID, ModuleName = modules.FirstOrDefault(m => m.ID == moduleID).Name, Variables = entries }; mapIdx.Clear(); for (int n = 0; n < values.Length; ++n) { mapIdx[values[n].Variable] = n; } return(ReqResult.OK(result)); case "WriteVariable": var write = parameters.Object <WriteVariable_Params>(); 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()); default: return(ReqResult.Bad("Unknown command: " + command)); } }
public override async Task<ReqResult> OnUiRequestAsync(string command, DataValue parameters) { switch (command) { case "Read": Console.Out.WriteLine("Parameters: " + parameters.ToString()); VTQ vtq = await Connection.ReadVariable(Var); return ReqResult.OK(vtq); default: return ReqResult.Bad("Unknown command: " + command); } }
public override async Task <ReqResult> OnUiRequestAsync(string command, DataValue parameters) { switch (command) { case "Init": { var para = parameters.Object <InitParams>(); var(windowLeft, windowRight) = GetTimeWindow(para.TimeRange, new List <VTTQ[]>()); var res = new LoadHistoryResult(); res.Tabs = configuration.Tabs.Select(t => new TabRes() { Name = t.Name, MaxDataPoints = t.PlotConfig.MaxDataPoints, Variables = t.Items.Select(it => it.Variable).ToArray(), Options = MakeGraphOptions(t), Configuration = t }).ToArray(); res.WindowLeft = windowLeft.JavaTicks; res.WindowRight = windowRight.JavaTicks; tabStates = GetInitialTabStates(configuration); ObjectRef[] objects = configuration.Tabs.SelectMany(t => t.Items.Select(it => it.Variable.Object)).Distinct().ToArray(); ObjectInfo[] infos; try { infos = await Connection.GetObjectsByID(objects); } catch (Exception) { infos = new ObjectInfo[objects.Length]; for (int i = 0; i < objects.Length; ++i) { ObjectRef obj = objects[i]; try { infos[i] = await Connection.GetObjectByID(obj); } catch (Exception) { infos[i] = new ObjectInfo(obj, "???", "???"); } } } foreach (ObjectInfo info in infos) { var numericVariables = info.Variables.Where(IsNumeric).Select(v => v.Name).ToArray(); res.ObjectMap[info.ID.ToEncodedString()] = new ObjInfo() { Name = info.Name, Variables = numericVariables }; } var mods = await Connection.GetModules(); res.Modules = mods.Select(m => new ModuleInfo() { ID = m.ID, Name = m.Name }).ToArray(); await EnableEvents(configuration); return(ReqResult.OK(res)); } case "LoadTabData": { var para = parameters.Object <LoadHistoryParams>(); TabState tabState = tabStates.First(ts => ts.TabName == para.TabName); tabState.LastTimeRange = para.TimeRange; Timestamp tStart = para.TimeRange.GetStart(); Timestamp tEnd = para.TimeRange.GetEnd(); var listHistories = new List <VTTQ[]>(); foreach (var variable in para.Variables) { try { VTTQ[] data = await Connection.HistorianReadRaw(variable, tStart, tEnd, para.MaxDataPoints, BoundingMethod.CompressToN); listHistories.Add(data); } catch (Exception) { listHistories.Add(new VTTQ[0]); } } tabState.IsLoaded = true; var(windowLeft, windowRight) = GetTimeWindow(para.TimeRange, listHistories); var res = MemoryManager.GetMemoryStream("LoadHistory"); try { using (var writer = new StreamWriter(res, Encoding.ASCII, 8 * 1024, leaveOpen: true)) { writer.Write("{ \"WindowLeft\": " + windowLeft.JavaTicks); writer.Write(", \"WindowRight\": " + windowRight.JavaTicks); writer.Write(", \"Data\": "); WriteUnifiedData(writer, listHistories); writer.Write('}'); } res.Seek(0, SeekOrigin.Begin); } catch (Exception) { res.Dispose(); throw; } return(new ReqResult(200, res)); } case "SaveItems": { var para = parameters.Object <SaveItemsParams>(); TabState tabState = tabStates.First(ts => ts.TabName == para.TabName); VariableRef[] newVariables = para.Items.Select(it => it.Variable).ToArray(); bool reloadData = !Arrays.Equals(newVariables, tabState.Variables); tabState.Variables = newVariables; TabConfig tabConfig = configuration.Tabs.FirstOrDefault(t => t.Name == para.TabName); tabConfig.Items = para.Items; DataValue newConfig = ConfigToIndentedDataValue(configuration); await Context.SaveViewConfiguration(newConfig); if (reloadData) { await EnableEvents(configuration); } return(ReqResult.OK(new { Options = MakeGraphOptions(tabConfig), Variables = newVariables, Configuration = tabConfig, ReloadData = reloadData })); } case "SavePlot": { var para = parameters.Object <SavePlotParams>(); TabConfig tabConfig = configuration.Tabs.First(t => t.Name == para.TabName); bool reloadData = tabConfig.PlotConfig.MaxDataPoints != para.Plot.MaxDataPoints; tabConfig.PlotConfig = para.Plot; DataValue newConfig = ConfigToIndentedDataValue(configuration); await Context.SaveViewConfiguration(newConfig); return(ReqResult.OK(new { Options = MakeGraphOptions(tabConfig), Configuration = tabConfig, ReloadData = reloadData })); } case "DeleteTab": { var para = parameters.Object <DeleteTabParams>(); configuration.Tabs = configuration.Tabs.Where(t => t.Name != para.TabName).ToArray(); DataValue newConfig = ConfigToIndentedDataValue(configuration); await Context.SaveViewConfiguration(newConfig); return(ReqResult.OK("")); } case "RenameTab": { var para = parameters.Object <RenameTabParams>(); if (para.NewName != para.TabName && configuration.Tabs.Any(t => t.Name == para.NewName)) { throw new Exception("Tab name already exists!"); } TabConfig tabConfig = configuration.Tabs.First(t => t.Name == para.TabName); tabConfig.Name = para.NewName; TabState tabState = tabStates.First(ts => ts.TabName == para.TabName); tabState.TabName = para.NewName; DataValue newConfig = ConfigToIndentedDataValue(configuration); await Context.SaveViewConfiguration(newConfig); return(ReqResult.OK(new { Configuration = tabConfig })); } case "AddTab": { var para = parameters.Object <AddTabParams>(); var(windowLeft, windowRight) = GetTimeWindow(para.TimeRange, new List <VTTQ[]>()); if (configuration.Tabs.Any(t => t.Name == para.NewName)) { throw new Exception("Tab name already exists!"); } TabConfig tabConfig = new TabConfig(); tabConfig.Name = para.NewName; var tabs = configuration.Tabs.ToList(); tabs.Add(tabConfig); configuration.Tabs = tabs.ToArray(); DataValue newConfig = ConfigToIndentedDataValue(configuration); await Context.SaveViewConfiguration(newConfig); var tabState = new TabState() { TabName = para.NewName, LastTimeRange = para.TimeRange }; tabStates.Add(tabState); return(ReqResult.OK(new { NewTab = new TabRes() { Name = tabConfig.Name, MaxDataPoints = tabConfig.PlotConfig.MaxDataPoints, Options = MakeGraphOptions(tabConfig), Configuration = tabConfig }, WindowLeft = windowLeft.JavaTicks, WindowRight = windowRight.JavaTicks })); } case "MoveLeft": { var para = parameters.Object <MoveTabParams>(); int i = configuration.Tabs.ToList().FindIndex(t => t.Name == para.TabName); if (i <= 0) { throw new Exception("Can't move left"); } var tmp = configuration.Tabs[i]; configuration.Tabs[i] = configuration.Tabs[i - 1]; configuration.Tabs[i - 1] = tmp; DataValue newConfig = ConfigToIndentedDataValue(configuration); await Context.SaveViewConfiguration(newConfig); return(ReqResult.OK("")); } case "MoveRight": { var para = parameters.Object <MoveTabParams>(); int i = configuration.Tabs.ToList().FindIndex(t => t.Name == para.TabName); if (i >= configuration.Tabs.Length - 1) { throw new Exception("Can't move right"); } var tmp = configuration.Tabs[i]; configuration.Tabs[i] = configuration.Tabs[i + 1]; configuration.Tabs[i + 1] = tmp; DataValue newConfig = ConfigToIndentedDataValue(configuration); await Context.SaveViewConfiguration(newConfig); return(ReqResult.OK("")); } case "ReadModuleObjects": { var pars = parameters.Object <ReadModuleObjectsParams>(); ObjectInfo[] objects; try { objects = await Connection.GetAllObjects(pars.ModuleID); } catch (Exception) { objects = new ObjectInfo[0]; } return(ReqResult.OK(new { Items = objects.Where(o => o.Variables.Any(IsNumeric)).Select(o => new Obj() { Type = o.ClassName, ID = o.ID.ToEncodedString(), Name = o.Name, Variables = o.Variables.Where(IsNumeric).Select(v => v.Name).ToArray() }) })); } default: return(ReqResult.Bad("Unknown command: " + command)); } }
public override async Task <ReqResult> OnUiRequestAsync(string command, DataValue parameters) { switch (command) { case "Init": { var para = parameters.Object <InitParams>() ?? throw new Exception("InitParams is null"); var(windowLeft, windowRight) = GetTimeWindow(para.TimeRange, new List <VTTQs>()); var res = new LoadHistoryResult(); res.Tabs = configuration.Tabs.Select(t => new TabRes() { Name = t.Name, MaxDataPoints = t.PlotConfig.MaxDataPoints, Variables = t.Items.Select(it => it.Variable).ToArray(), Options = MakeGraphOptions(t), Configuration = t }).ToArray(); res.WindowLeft = windowLeft.JavaTicks; res.WindowRight = windowRight.JavaTicks; tabStates = GetInitialTabStates(configuration); ObjectRef[] objects = configuration.Tabs.SelectMany(t => t.Items.Select(it => it.Variable.Object)).Distinct().ToArray(); ObjectInfos infos; try { infos = await Connection.GetObjectsByID(objects); } catch (Exception) { infos = new ObjectInfos(objects.Length); for (int i = 0; i < objects.Length; ++i) { ObjectRef obj = objects[i]; try { infos.Add(await Connection.GetObjectByID(obj)); } catch (Exception) { infos.Add(new ObjectInfo(obj, "???", "???")); } } } foreach (ObjectInfo info in infos) { var numericVariables = info.Variables.Where(IsNumericOrBool).Select(v => v.Name).ToArray(); res.ObjectMap[info.ID.ToEncodedString()] = new ObjInfo() { Name = info.Name, Variables = numericVariables }; } res.Modules = modules; await EnableEvents(configuration); return(ReqResult.OK(res)); } case "LoadTabData": { var para = parameters.Object <LoadHistoryParams>() ?? throw new Exception("LoadHistoryParams is null"); TabState tabState = tabStates.FirstOrDefault(ts => ts.TabName == para.TabName); if (tabState == null) { throw new Exception($"Failed to load history data: tab '{para.TabName}' not found"); } tabState.LastTimeRange = para.TimeRange; Timestamp tStart = para.TimeRange.GetStart(); Timestamp tEnd = para.TimeRange.GetEnd(); TabConfig tabConfig = configuration.Tabs.First(t => t.Name == para.TabName); QualityFilter filter = tabConfig.PlotConfig.FilterByQuality; var listHistories = new List <VTTQs>(); foreach (var variable in para.Variables) { try { VTTQs data = await Connection.HistorianReadRaw(variable, tStart, tEnd, para.MaxDataPoints, BoundingMethod.CompressToN, filter); listHistories.Add(data); } catch (Exception) { listHistories.Add(new VTTQs()); } } tabState.IsLoaded = true; var(windowLeft, windowRight) = GetTimeWindow(para.TimeRange, listHistories); var res = MemoryManager.GetMemoryStream("LoadHistory"); try { using (var writer = new StreamWriter(res, Encoding.ASCII, 8 * 1024, leaveOpen: true)) { writer.Write("{ \"WindowLeft\": " + windowLeft.JavaTicks); writer.Write(", \"WindowRight\": " + windowRight.JavaTicks); writer.Write(", \"Data\": "); WriteUnifiedData(new JsonDataRecordArrayWriter(writer), listHistories); writer.Write('}'); } res.Seek(0, SeekOrigin.Begin); } catch (Exception) { res.Dispose(); throw; } return(new ReqResult(200, res)); } case "DownloadFile": { var para = parameters.Object <DownloadDataFileParams>() ?? throw new Exception("DownloadDataFileParams is null"); TabConfig tabConfig = configuration.Tabs.First(t => t.Name == para.TabName); QualityFilter filter = tabConfig.PlotConfig.FilterByQuality; Timestamp tStart = para.TimeRange.GetStart(); Timestamp tEnd = para.TimeRange.GetEnd(); var listHistories = new List <VTTQs>(); foreach (var variable in para.Variables) { try { const int ChunckSize = 5000; VTTQs data = await Connection.HistorianReadRaw(variable, tStart, tEnd, ChunckSize, BoundingMethod.TakeFirstN, filter); if (data.Count < ChunckSize) { listHistories.Add(data); } else { var buffer = new VTTQs(data); do { Timestamp t = data[data.Count - 1].T.AddMillis(1); data = await Connection.HistorianReadRaw(variable, t, tEnd, ChunckSize, BoundingMethod.TakeFirstN, filter); buffer.AddRange(data); }while (data.Count == ChunckSize); listHistories.Add(buffer); } } catch (Exception) { listHistories.Add(new VTTQs()); } } var columns = new List <string>(); columns.Add("Time"); columns.AddRange(para.VariableNames); var res = MemoryManager.GetMemoryStream("DownloadFile"); try { string contentType; switch (para.FileType) { case FileType.CSV: contentType = "text/csv"; using (var writer = new StreamWriter(res, Encoding.UTF8, 8 * 1024, leaveOpen: true)) { WriteUnifiedData(new CsvDataRecordArrayWriter(writer, columns, configuration.DataExport.CSV), listHistories); } break; case FileType.Spreadsheet: contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; using (var excel = new ExcelPackage(res)) { ExcelWorksheet sheet = excel.Workbook.Worksheets.Add("Data Export"); WriteUnifiedData(new ExcelDataRecordArrayWriter(sheet, columns, configuration.DataExport.Spreadsheet), listHistories); excel.Save(); } break; default: throw new Exception($"Unknown file type: {para.FileType}"); } res.Seek(0, SeekOrigin.Begin); return(new ReqResult(200, res, contentType)); } catch (Exception) { res.Dispose(); throw; } } case "SaveItems": { var para = parameters.Object <SaveItemsParams>() ?? throw new Exception("SaveItemsParams is null"); TabState tabState = tabStates.First(ts => ts.TabName == para.TabName); VariableRef[] newVariables = para.Items.Select(it => it.Variable).ToArray(); bool reloadData = !Arrays.Equals(newVariables, tabState.Variables); tabState.Variables = newVariables; TabConfig tabConfig = configuration.Tabs.FirstOrDefault(t => t.Name == para.TabName); tabConfig.Items = para.Items; DataValue newConfig = ConfigToIndentedDataValue(configuration); await Context.SaveViewConfiguration(newConfig); if (reloadData) { await EnableEvents(configuration); } return(ReqResult.OK(new { Options = MakeGraphOptions(tabConfig), Variables = newVariables, Configuration = tabConfig, ReloadData = reloadData })); } case "SavePlot": { var para = parameters.Object <SavePlotParams>() ?? throw new Exception("SavePlotParams is null"); TabConfig tabConfig = configuration.Tabs.First(t => t.Name == para.TabName); bool reloadData = tabConfig.PlotConfig.MaxDataPoints != para.Plot.MaxDataPoints || tabConfig.PlotConfig.FilterByQuality != para.Plot.FilterByQuality || tabConfig.PlotConfig.LeftAxisLimitY != para.Plot.LeftAxisLimitY || tabConfig.PlotConfig.RightAxisLimitY != para.Plot.RightAxisLimitY; tabConfig.PlotConfig = para.Plot; DataValue newConfig = ConfigToIndentedDataValue(configuration); await Context.SaveViewConfiguration(newConfig); return(ReqResult.OK(new { Options = MakeGraphOptions(tabConfig), Configuration = tabConfig, ReloadData = reloadData })); } case "DeleteTab": { var para = parameters.Object <DeleteTabParams>() ?? throw new Exception("DeleteTabParams is null"); configuration.Tabs = configuration.Tabs.Where(t => t.Name != para.TabName).ToArray(); DataValue newConfig = ConfigToIndentedDataValue(configuration); await Context.SaveViewConfiguration(newConfig); return(ReqResult.OK("")); } case "RenameTab": { var para = parameters.Object <RenameTabParams>() ?? throw new Exception("RenameTabParams is null"); if (para.NewName != para.TabName && configuration.Tabs.Any(t => t.Name == para.NewName)) { throw new Exception("Tab name already exists!"); } TabConfig tabConfig = configuration.Tabs.First(t => t.Name == para.TabName); tabConfig.Name = para.NewName; TabState tabState = tabStates.First(ts => ts.TabName == para.TabName); tabState.TabName = para.NewName; DataValue newConfig = ConfigToIndentedDataValue(configuration); await Context.SaveViewConfiguration(newConfig); return(ReqResult.OK(new { Configuration = tabConfig })); } case "AddTab": { var para = parameters.Object <AddTabParams>() ?? throw new Exception("AddTabParams is null"); var(windowLeft, windowRight) = GetTimeWindow(para.TimeRange, new List <VTTQs>()); if (configuration.Tabs.Any(t => t.Name == para.NewName)) { throw new Exception("Tab name already exists!"); } TabConfig tabConfig = new TabConfig(); tabConfig.Name = para.NewName; var tabs = configuration.Tabs.ToList(); tabs.Add(tabConfig); configuration.Tabs = tabs.ToArray(); DataValue newConfig = ConfigToIndentedDataValue(configuration); await Context.SaveViewConfiguration(newConfig); var tabState = new TabState() { TabName = para.NewName, LastTimeRange = para.TimeRange }; tabStates.Add(tabState); return(ReqResult.OK(new { NewTab = new TabRes() { Name = tabConfig.Name, MaxDataPoints = tabConfig.PlotConfig.MaxDataPoints, Options = MakeGraphOptions(tabConfig), Configuration = tabConfig }, WindowLeft = windowLeft.JavaTicks, WindowRight = windowRight.JavaTicks })); } case "MoveLeft": { var para = parameters.Object <MoveTabParams>() ?? throw new Exception("MoveTabParams is null"); int i = configuration.Tabs.ToList().FindIndex(t => t.Name == para.TabName); if (i <= 0) { throw new Exception("Can't move left"); } var tmp = configuration.Tabs[i]; configuration.Tabs[i] = configuration.Tabs[i - 1]; configuration.Tabs[i - 1] = tmp; DataValue newConfig = ConfigToIndentedDataValue(configuration); await Context.SaveViewConfiguration(newConfig); return(ReqResult.OK("")); } case "MoveRight": { var para = parameters.Object <MoveTabParams>() ?? throw new Exception("MoveTabParams is null"); int i = configuration.Tabs.ToList().FindIndex(t => t.Name == para.TabName); if (i >= configuration.Tabs.Length - 1) { throw new Exception("Can't move right"); } var tmp = configuration.Tabs[i]; configuration.Tabs[i] = configuration.Tabs[i + 1]; configuration.Tabs[i + 1] = tmp; DataValue newConfig = ConfigToIndentedDataValue(configuration); await Context.SaveViewConfiguration(newConfig); return(ReqResult.OK("")); } 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(); } return(ReqResult.OK(new { Items = objects.Where(o => o.Variables.Any(IsNumericOrBool)).Select(o => new Obj() { Type = o.ClassName, ID = o.ID.ToEncodedString(), Name = o.Name, Variables = o.Variables.Where(IsNumericOrBool).Select(v => v.Name).ToArray() }).ToArray() })); } default: return(ReqResult.Bad("Unknown command: " + command)); } }
private async Task <ReqResult> HandlePost(HttpRequest request, HttpResponse response) { string path = request.Path; try { if (path == Path_Login) { string?user; string?pass; using (var reader = new StreamReader(request.Body, Encoding.UTF8)) { var obj = await StdJson.JObjectFromReaderAsync(reader); user = (string?)obj["user"]; pass = (string?)obj["pass"]; if (user == null || pass == null) { return(ReqResult.Bad("Missing user and password.")); } } var session = new Session(); Connection connection; try { connection = await HttpConnection.ConnectWithUserLogin("localhost", clientPort, user, pass, null, session, timeoutSeconds : 90); } catch (Exception exp) { logWarn(exp.Message); return(ReqResult.Bad(exp.Message)); } await session.SetConnection(connection, model, moduleID, viewTypes); sessions[session.ID] = session; var result = new JObject(); result["sessionID"] = session.ID; string str = StdJson.ObjectToString(uiModel); JRaw raw = new JRaw(str); result["model"] = raw; return(ReqResult.OK(result)); } else if (path.StartsWith(Path_ViewReq)) { string viewRequest = path.Substring(Path_ViewReq.Length); (Session session, string viewID) = GetSessionFromQuery(request.QueryString.ToString()); string content; using (var reader = new StreamReader(request.Body, Encoding.UTF8)) { content = await reader.ReadToEndAsync(); } return(await session.OnViewCommand(viewID, viewRequest, DataValue.FromJSON(content))); } else if (path == Path_ActivateView) { (Session session, string viewID) = GetSessionFromQuery(request.QueryString.ToString()); await session.OnActivateView(viewID); return(ReqResult.OK()); } else if (path == Path_DuplicateView) { (Session session, string viewID) = GetSessionFromQuery(request.QueryString.ToString()); string newViewID = await session.OnDuplicateView(viewID); uiModel = MakeUiModel(model, viewTypes); return(ReqResult.OK(new { newViewID, model = uiModel })); } else if (path == Path_DuplicateConvertView) { (Session session, string viewID) = GetSessionFromQuery(request.QueryString.ToString()); string newViewID = await session.OnDuplicateConvertHistoryPlot(viewID); uiModel = MakeUiModel(model, viewTypes); return(ReqResult.OK(new { newViewID, model = uiModel })); } else if (path == Path_RenameView) { (Session session, string viewID) = GetSessionFromQuery(request.QueryString.ToString()); string?newViewName; using (var reader = new StreamReader(request.Body, Encoding.UTF8)) { var obj = await StdJson.JObjectFromReaderAsync(reader); newViewName = (string?)obj["newViewName"]; if (newViewName == null) { return(ReqResult.Bad("Missing newViewName")); } } await session.OnRenameView(viewID, newViewName); uiModel = MakeUiModel(model, viewTypes); return(ReqResult.OK(new { model = uiModel })); } else if (path == Path_MoveView) { (Session session, string viewID) = GetSessionFromQuery(request.QueryString.ToString()); bool up = false; using (var reader = new StreamReader(request.Body, Encoding.UTF8)) { var obj = await StdJson.JObjectFromReaderAsync(reader); up = (bool)obj["up"] !; } await session.OnMoveView(viewID, up); uiModel = MakeUiModel(model, viewTypes); return(ReqResult.OK(new { model = uiModel })); } else if (path == Path_DeleteView) { (Session session, string viewID) = GetSessionFromQuery(request.QueryString.ToString()); await session.OnDeleteView(viewID); uiModel = MakeUiModel(model, viewTypes); return(ReqResult.OK(new { model = uiModel })); } else if (path == Path_Logout) { string sessionID; using (var reader = new StreamReader(request.Body, Encoding.UTF8)) { sessionID = await reader.ReadToEndAsync(); } if (sessions.ContainsKey(sessionID)) { Session session = sessions[sessionID]; var ignored = session.Close(); sessions.Remove(sessionID); } return(ReqResult.OK()); } else { return(ReqResult.Bad("Invalid path: " + path)); } } catch (InvalidSessionException exp) { logWarn("HandlePost: " + exp.Message); return(ReqResult.Bad(exp.Message)); } catch (Exception exp) { logWarn("HandlePost:", exp); return(ReqResult.Bad(exp.Message)); } }
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)); } }
public override async Task <ReqResult> OnUiRequestAsync(string command, DataValue parameters) { switch (command) { case "ReadModuleVariables": if (activeModuleID != "") { await Connection.DisableChangeEvents(); } var pars = parameters.Object <ReadModuleVariables_Params>() ?? throw new Exception("ReadModuleVariables_Params is null"); string moduleID = string.IsNullOrEmpty(pars.ModuleID) ? modules[0].ID : pars.ModuleID; ObjectInfo?rootObjInfo; while (true) { rootObjInfo = await Connection.GetRootObject(moduleID); if (rootObjInfo != null) { break; } await Task.Delay(500); } ObjectRef rootObj = rootObjInfo.ID; var objects = await Connection.GetAllObjects(moduleID); SetObjectNameMap(objects); List <VariableValue> values = await Connection.ReadAllVariablesOfObjectTree(rootObj); await Connection.EnableVariableValueChangedEvents(SubOptions.AllUpdates(sendValueWithEvent: true), rootObj); VarEntry[] entries = values.Select(MapVarValue).ToArray(); activeModuleID = moduleID; var locations = await Connection.GetLocations(); var result = new ReadModuleVariables_Result() { Modules = modules, ModuleID = moduleID, ModuleName = modules.FirstOrDefault(m => m.ID == moduleID).Name, Variables = entries, Locations = locations.ToArray(), }; mapIdx.Clear(); for (int n = 0; n < values.Count; ++n) { mapIdx[values[n].Variable] = n; } return(ReqResult.OK(result)); 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 "SyncRead": { var sread = parameters.Object <ReadSync_Params>() ?? throw new Exception("ReadSync_Params is null"); ObjectRef obj = ObjectRef.FromEncodedString(sread.ObjID); VariableRef varRef = VariableRef.Make(obj, sread.Var); VTQ vtq = await Connection.ReadVariableSync(varRef); int idx = mapIdx[varRef]; var entry = new ChangeEntry() { N = idx, V = vtq.V, T = Timestamp2Str(vtq.T), Q = vtq.Q }; return(ReqResult.OK(entry)); } default: return(ReqResult.Bad("Unknown command: " + command)); } }