/
agontar
/
TOROS
Обзор
Документация
Войти
/
agontar
/
TOROS
Код
Запросы
0
Задачи
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
Webapplication_new/Controllers/HomeController.cs
1 146 строк
48 KB
gav
save before changing sensors arg in vs.MapSensorsToNodes(finalPoints, sensors, cz, wwwPath)
30 сен 2024, 16:31
30 сен 2024, 16:31
7ccfe76
Код
Авторство
О чём код?
using Microsoft.AspNetCore.Mvc; using System.Diagnostics; using WebApplication1.Models; using WebApplication1.Services; using EasyModbus; using Newtonsoft.Json; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc.Rendering; using System.Net; using System.IO; using System.Xml.Linq; using Quartz.Util; using static System.Net.WebRequestMethods; using Microsoft.Extensions.Hosting.Internal; using System.Text.RegularExpressions; using System; using System.Data; namespace WebApplication1.Controllers { public class HomeController : Controller { IWebHostEnvironment Environment; private readonly ILogger<HomeController> _logger; public HomeController(ILogger<HomeController> logger, IWebHostEnvironment environment) { _logger = logger; Environment = environment; // var hosting = new HostingEnvironment(); // Environment = hosting as IWebHostEnvironment; } public List<T> ReadJsonFile<T>(string path, List<T>? collection) { //List<T> list = new List<T>(); var rw = new WriteRead(); try { //var webClient = new WebClient(); //var json = webClient.DownloadString(path); var json = rw.ReadText(path); collection = JsonConvert.DeserializeObject<List<T>>(json) as List<T>; if (collection == null) { collection = new List<T>(); } return collection; } catch (Exception ex) { Console.WriteLine(ex.ToString()); return new List<T>(); } } public void WriteJsonFile<T>(string path, List<T> collection) { JsonSerializer serializer = new JsonSerializer(); try { using (StreamWriter sw = new StreamWriter(path)) using (JsonWriter writer = new JsonTextWriter(sw)) { serializer.Serialize(writer, collection); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); return; } } public IActionResult Clear() { Console.WriteLine("Clear static fields!"); Singleton1 s1 = Singleton1.Instance; s1.NodeId = ""; s1.NodeLevel = 0; s1.Name = ""; s1.IP = ""; s1.selectedItems = ""; s1.ImgFileName = ""; s1.DisplInfo = ""; s1.IDS = ""; return RedirectToAction("Index"); } [HttpGet] public ActionResult GetCoordinates(string myData, WriteRead wr) { Console.WriteLine("Get requested! " + myData); //ViewBag.MyData = "Ziggy Rafiq Blog Post"; string wwwPath = this.Environment.WebRootPath; string path = Path.Combine(wwwPath, "TreeData", "coordinates.json"); string fromFile = wr.ReadText(path); var points = JsonConvert.DeserializeObject<Dictionary<string, int>>(fromFile); var newArray = new List<Coordinates>(); //if (newPoints == null) { newPoints = new Dictionary<string, int>(); } if (points != null) { foreach (var item in points) { // Console.WriteLine($"{item.Key} --> {item.Value}"); Coordinates cords = new Coordinates(); cords.key = item.Key; cords.value = item.Value; newArray.Add(cords); } } myData = "[{'key': 'xy'}, {'value' : 0}]"; myData = JsonConvert.SerializeObject(newArray); return Content(myData); } [HttpPost] [Authorize] public void GetCoordinates(string Data, Coordinates coordinates, WriteRead wr) { try { string wwwPath = this.Environment.WebRootPath; string path = Path.Combine(wwwPath, "TreeData", "coordinates.json"); wr = new WriteRead(); string fromFile = wr.ReadText(path); Data = Data.Replace("null", "0"); fromFile = fromFile.Replace("null", "0"); Console.WriteLine("Raw data: " + Data); var points = JsonConvert.DeserializeObject<Dictionary<string, int>>(fromFile); if (points == null) { points = new Dictionary<string, int>(); } var array = JsonConvert.DeserializeObject<List<Coordinates>>(Data); if (array != null) { foreach (var item in array) { //Console.WriteLine($"{item.key} --> {item.value}"); // points.Add(item.key, item.value); if (points.ContainsKey(item.key)) { points[item.key] = item.value; } else { points.Add(item.key, item.value); } } } foreach (var item in points) { // Console.WriteLine($"{item.Key} --> {item.Value}"); } string json = JsonConvert.SerializeObject(points, Formatting.Indented); // Console.WriteLine(json); var newArray = new List<Coordinates>(); var newPoints = JsonConvert.DeserializeObject<Dictionary<string, int>>(json); //if (newPoints == null) { newPoints = new Dictionary<string, int>(); } if (newPoints != null) { foreach (var item in newPoints) { // Console.WriteLine($"{item.Key} --> {item.Value}"); Coordinates cords = new Coordinates(); cords.key = item.Key; cords.value = item.Value; newArray.Add(cords); } } string arrayToSend = JsonConvert.SerializeObject(newArray); //Console.WriteLine(arrayToSend); wr.WriteText(path, json); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } public int GetNextIndex<T>(List<T> table) { if (table == null) return -1; int[] ids = new int[table.Count]; if (typeof(T) == typeof(VehicleType)) { List<VehicleType>? t = table as List<VehicleType>; if (t != null) for (int i = 0; i < table.Count; i++) { ids[i] = t[i].Id; } } if (typeof(T) == typeof(VehicleSubType)) { List<VehicleSubType>? t = table as List<VehicleSubType>; if (t != null) for (int i = 0; i < table.Count; i++) { ids[i] = t[i].Id; } } int nextIndex = ids.Max() + 1; return nextIndex; } [HttpGet] public IActionResult Index(Sensors sensors, BaseStation s) { //sensors.paramNumber = 2; // GetOneSensor(new OutputInterpreter()); //System.IO.Path.GetFileName //IFormFile f; Monitoring.wwwPath = this.Environment.WebRootPath; WriteToDB.wwwPath = this.Environment.WebRootPath; Singleton1 s1 = Singleton1.Instance; ViewBag.Error = s1.Error; Console.WriteLine(s1.Alarms); Console.WriteLine(s1.MasterType); ViewBag.MasterType = s1.MasterType; ViewBag.Alarm = s1.Alarms; sensors.sensor = s1.sensor; // string sss = s1.IP; Console.WriteLine(s1.NodeId); string NID = s1.NodeId; NID = NID.Replace("-", ""); ViewBag.NID = NID; Console.WriteLine(s1.NodeLevel); Console.WriteLine(s1.Name); sensors.sensor.SensorName = s1.Name; Console.WriteLine(s1.IP); sensors.sensor.SensorIP = s1.IP; Console.WriteLine(s1.IDS); sensors.sensor.id = s1.IDS; Console.WriteLine(s1.ImgFileName); Console.WriteLine(sensors.sensor.Voltage); if (sensors.sensor.SensorIP.IsNullOrWhiteSpace()) { sensors.sensor.SensorIP = "192.168.1.150"; s1.IP = "192.168.1.150"; } // s1.IP = "192.168.1.151"; string wwwPath = this.Environment.WebRootPath; string path1 = Path.Combine(wwwPath, "TreeData", "types1.json"); string path2 = Path.Combine(wwwPath, "TreeData", "subtypes1.json"); string path3 = Path.Combine(wwwPath, "TreeData", "points1.json"); string path4 = Path.Combine(wwwPath, "TreeData", "endpoints.json"); string path5 = Path.Combine(wwwPath, "TreeData", "sensors.json"); //Console.WriteLine(path4); string path = Path.Combine(wwwPath, "Bases", "BaseStations.json"); s.BaseStations = ReadJsonFile(path, s.BaseStations); Monitoring.Stations = s.BaseStations; //Task result = Monitoring.Display(); if (s1.Monitor == false) { Monitoring.monitor = true; Monitoring.MonitorLoop(s.BaseStations); // WriteToDB.enableRec = true; // WriteToDB.RecordingDB(s.BaseStations); s1.Monitor = true; } if (WriteToDB.enableRec == false) { WriteToDB.enableRec = true; WriteToDB.RecordingDB(s.BaseStations); } //else { WriteToDB.enableRec = false; } if (s1.Refresh == false) { Monitoring.refresh = true; Monitoring.RefreshLoop(); s1.Refresh = true; } /*var webClient = new WebClient(); var json1 = webClient.DownloadString(path1); var json2 = webClient.DownloadString(path2); var json3 = webClient.DownloadString(path3);*/ List<TreeViewNode> nodes = new List<TreeViewNode>(); List<VehicleType> types = new List<VehicleType>(); List<VehicleSubType> subtypes = new List<VehicleSubType>(); List<MetricPoint> metricPoints = new List<MetricPoint>(); List<FinalPoint> finalpoints = new List<FinalPoint>(); List<Sensor> sensorRecords = new List<Sensor>(); types = ReadJsonFile(path1, types); subtypes = ReadJsonFile(path2, subtypes); metricPoints = ReadJsonFile(path3, metricPoints); finalpoints = ReadJsonFile(path4, finalpoints); sensorRecords = ReadJsonFile(path5, sensorRecords); try { // loook for measure points for machine if (s1.NodeLevel == 3) { Console.WriteLine("Агрегат!!!"); ViewBag.NodeLevel = "3"; string[] nodeString = s1.NodeId.Split("-"); int nodeId = int.Parse(nodeString[2]); Console.WriteLine($"Id Агрегата: {nodeId}"); foreach (var item in finalpoints) { if (item.MetricPointId == nodeId) { Console.WriteLine($"{item.Id} {item.Name} {item.IDS}"); foreach (var sensor in sensorRecords) { if (sensor.id.Replace("-", "") == item.IDS) { sensor.SensorName = item.Name; sensor.PointColor = item.PointColor; Console.WriteLine($" {sensor.SensorName} {sensor.id} {sensor.SensorIP} {sensor.Voltage} {sensor.Temperature}"); sensors.sensors.Add(sensor); } } Console.WriteLine(); } } } /*foreach (var item in finalpoints) { Console.WriteLine($"{item.Id} {item.Name} {item.MetricPointId}"); }*/ foreach (var type in types) { nodes.Add(new TreeViewNode { id = type.Id.ToString(), parent = "#", text = type.Name, icon = "/Images/Plant.png", ImgFileName = type.ImgFileName }); } foreach (VehicleSubType subType in subtypes) { nodes.Add(new TreeViewNode { id = subType.VehicleTypeId.ToString() + "-" + subType.Id.ToString(), parent = subType.VehicleTypeId.ToString(), text = subType.Name, icon = "/Images/workshop.png", ImgFileName = subType.ImgFileName }); } foreach (var point in metricPoints) { nodes.Add(new TreeViewNode { id = subtypes.Find(x => x.Id == point.VehicleId).VehicleTypeId.ToString() + "-" + point.VehicleId.ToString() + "-" + point.Id.ToString(), parent = subtypes.Find(x => x.Id == point.VehicleId).VehicleTypeId.ToString() + "-" + point.VehicleId.ToString(), text = point.Name, IP = point.IP, IDS = point.IDS, icon = "/Images/machine1.png", ImgFileName = point.ImgFileName //localhost:7256/favicon.ico //jstree.com/tree.png }); ; } foreach (var finalpoint in finalpoints) { MetricPoint? metricpoint = metricPoints.Find(x => x.Id == finalpoint.MetricPointId); VehicleSubType? vehicle = subtypes.Find(x => x.Id == metricpoint.VehicleId); VehicleType? vehicletype = types.Find(x => x.Id == vehicle.VehicleTypeId); string this_id = vehicletype.Id.ToString() + "-" + vehicle.Id.ToString() + "-" + metricpoint.Id.ToString() + "-" + finalpoint.Id.ToString(); string this_parent = vehicletype.Id.ToString() + "-" + vehicle.Id.ToString() + "-" + metricpoint.Id.ToString(); // Console.WriteLine(this_id); // Console.WriteLine(this_parent); nodes.Add(new TreeViewNode { id = this_id, parent = this_parent, text = finalpoint.Name, IP = finalpoint.IP, IDS = finalpoint.IDS, icon = "/Images/sensor.png", //li_attr = { style = "color: red; font-weight: bold;" } li_attr = { style = finalpoint.PointStyle.style } //icon = "/Images/tree.png" }); } ViewBag.Json = JsonConvert.SerializeObject(nodes); /* if (s1.DisplInfo == "ВАЗ") { ViewBag.Path = "/Images/mnemo4.jpg"; } else if (s1.DisplInfo == "ГАЗ") { ViewBag.Path = "/Images/mnemo4.jpg"; } else if (s1.DisplInfo == "КАМАЗ") { ViewBag.Path = "/Images/mnemo3.jpg"; } else { ViewBag.Path = "/Images/mnemo5.gif"; }*/ if (s1.ImgFileName.Length > 0) { ViewBag.Path = "/Uploads/" + s1.ImgFileName; ViewBag.ImgFileName = s1.ImgFileName; } else { ViewBag.Path = "/Images/mnemo5.gif"; ViewBag.ImgFileName = "mnemo5.gif"; } if (s1.NodeLevel == 4) { ViewBag.Btn1 = ""; ViewBag.Btn2 = "defaultOpen"; ViewBag.Disable = "disabled"; ViewBag.DisableSens = "disabled"; ViewBag.DisableTab = ""; } else if (s1.NodeLevel == 3) { ViewBag.Btn2 = ""; ViewBag.Btn1 = "defaultOpen"; ViewBag.Disable = ""; ViewBag.DisableTab = "disabled"; ViewBag.DisableSens = ""; } else { ViewBag.Btn2 = ""; ViewBag.Btn1 = "defaultOpen"; ViewBag.Disable = ""; ViewBag.DisableTab = "disabled"; ViewBag.DisableSens = "disabled"; } //Console.WriteLine(ViewBag.Json); s1.TreeNodes = nodes; path1 = Path.Combine(wwwPath, "TreeData", "types1.json"); WriteJsonFile(path1, types); sensors.sensor.DispInfo = s1.DisplInfo; return View(sensors); } catch (Exception ex) { Console.WriteLine(ex.ToString()); return View(sensors); } } [HttpPost] public IActionResult Index(Sensor sensor, string selectedItems, string measure, Sensors sensors) { // sensors.paramNumber = 2; int pNum = 0; Console.WriteLine($"selected parameter -> {measure}"); int.TryParse(measure, out pNum); sensors.paramNumber = pNum; //GetOneSensor(new OutputInterpreter()); List<MetricPoint> metricPoints = new List<MetricPoint>(); List<FinalPoint> finalPoints = new List<FinalPoint>(); string wwwPath = this.Environment.WebRootPath; string path = Path.Combine(wwwPath, "TreeData", "points1.json"); string path_plus = Path.Combine(wwwPath, "TreeData", "endpoints.json"); metricPoints = ReadJsonFile(path, metricPoints); finalPoints = ReadJsonFile(path_plus, finalPoints); Singleton1 s1 = Singleton1.Instance; Console.WriteLine(s1.MasterType); ViewBag.MasterType = s1.MasterType; Console.WriteLine("=== All nodes ==="); Console.WriteLine(JsonConvert.SerializeObject(s1.TreeNodes)); if (selectedItems != null && selectedItems != "[]") { Console.WriteLine("=== Selected nodes ==="); Console.WriteLine(selectedItems); s1.selectedItems = selectedItems; List<TreeViewNode>? items = JsonConvert.DeserializeObject<List<TreeViewNode>>(selectedItems); if (items != null) items.ForEach(x => { Console.WriteLine(x.text); }); Console.WriteLine("---------------------"); string name = items[0].text.ToString(); string nodeId = items[0].id.ToString(); var matches = Regex.Matches(nodeId, "-"); Console.WriteLine(name); Console.WriteLine(nodeId); Console.WriteLine($"Node level is: {matches.Count + 1}"); s1.NodeLevel = matches.Count + 1; s1.DisplInfo = $"{name}"; s1.NodeId = nodeId; Console.WriteLine("---------------------"); // metricPoints.ForEach(x => { Console.WriteLine(x.Name + " " + x.IP); }); /* foreach (var item in metricPoints) { if (item.Name == name) { Console.WriteLine(item.Name + " " + item.IP + " " + item.IDS); s1.Name = item.Name; s1.IP = item.IP; s1.IDS = item.IDS; } } foreach (var item in finalPoints) { if (item.Name == name) { Console.WriteLine(item.Name + " " + item.IP + " " + item.IDS); s1.Name = item.Name; s1.IP = item.IP; s1.IDS = item.IDS; } } */ foreach (var item in s1.TreeNodes) { if (item.id == nodeId) { Console.WriteLine(item.text + " " + item.IP + " " + item.IDS); s1.Name = item.text; s1.IP = item.IP; s1.IDS = item.IDS; s1.ImgFileName = item.ImgFileName; } } //Console.WriteLine(metricPoints.Find(x => x.Name == name).IP); //Console.WriteLine(metricPoints.Find(x => x.Name == name).IDS); } else { s1.Reset(); } if (s1.NodeLevel == 4) s1.sensor = GetOneSensor(); // ViewBag.NID = s1.NodeId; return RedirectToAction("Index", sensors); //return View(); } [HttpGet] public IActionResult About(MasterStatus status, OutputInterpreter interpreter) { try { Request request = new Request(); if (string.IsNullOrWhiteSpace(status.Ip)) status.Ip = "192.168.1.150"; if (string.IsNullOrWhiteSpace(status.Port)) status.Port = "80"; // PgSql sql = new PgSql(); // sql.InsertMetric(); Singleton1 s1 = Singleton1.Instance; string sss = s1.IP; ViewBag.MasterType = s1.MasterType; // s1.IP = status.Ip; Console.WriteLine(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); Console.WriteLine($"{s1.Name} {s1.IP} {s1.IDS}"); status.Ip = s1.IP; // List<TreeViewNode> current = new List<TreeViewNode>(); // current.ForEach(x => { Console.WriteLine(x.text); }); List<string> parameters = new List<string>(); parameters = interpreter.DisplayStatus(status.Ip, 80); if (parameters.Count == 0) status.Device = "На данном IP или порте устройство не найдено"; else status.Device = "Подключение успешно"; // read date and time string h = "", m = "", s = "", d = "", mm = "", yy = ""; byte[] result = request.Command_5_bytes(status.Ip, 80, 0x13); if (result == null) { return View(status); } if (result[5] < 10) h = "0"; if (result[6] < 10) m = "0"; if (result[7] < 10) s = "0"; if (result[8] < 10) d = "0"; if (result[9] < 10) mm = "0"; if (result[10] < 10) yy = "0"; status.Clock = $"{h}{result[5].ToString()}:{m}{result[6].ToString()}:{s}{result[7].ToString()} {d}{result[8].ToString()}/{mm}{result[9].ToString()}/{yy}{result[10].ToString()}"; status.MAC = parameters[0]; status.ReadingsInterval = parameters[1]; status.Sensors = parameters[2]; status.BatteryVoltage = parameters[3]; status.TimeFlag = parameters[4]; status.Card = parameters[5]; status.SdSize = parameters[6]; status.SdFreeSpace = parameters[7]; return View(status); } catch (Exception ex) { Console.WriteLine(ex.ToString()); return View(status); } } [HttpPost] //[Authorize] public IActionResult About(MasterStatus status, OutputInterpreter interpreter, string ip, int port) { try { Singleton1 s1 = Singleton1.Instance; ViewBag.MasterType = s1.MasterType; // status.Ip = s1.IP; Request request = new Request(); if (string.IsNullOrWhiteSpace(status.Ip)) status.Ip = "192.168.1.150"; if (string.IsNullOrWhiteSpace(status.Port)) status.Port = "80"; s1.IP = status.Ip; port = Int32.Parse(status.Port); List<string> parameters = new List<string>(); parameters = interpreter.DisplayStatus(status.Ip, port); if (parameters.Count == 0) status.Device = "На данном IP или порте устройство не найдено"; else status.Device = "Подключение успешно"; // запрос времени и даты string h = "", m = "", s = "", d = "", mm = "", yy = ""; byte[] result = request.Command_5_bytes(status.Ip, 80, 0x13); if (result == null) { return View(status); } if (result[5] < 10) h = "0"; if (result[6] < 10) m = "0"; if (result[7] < 10) s = "0"; if (result[8] < 10) d = "0"; if (result[9] < 10) mm = "0"; if (result[10] < 10) yy = "0"; status.Clock = $"{h}{result[5].ToString()}:{m}{result[6].ToString()}:{s}{result[7].ToString()} {d}{result[8].ToString()}/{mm}{result[9].ToString()}/{yy}{result[10].ToString()}"; status.MAC = parameters[0]; status.ReadingsInterval = parameters[1]; status.Sensors = parameters[2]; status.BatteryVoltage = parameters[3]; status.TimeFlag = parameters[4]; status.Card = parameters[5]; status.SdSize = parameters[6]; status.SdFreeSpace = parameters[7]; return View(status); } catch (Exception ex) { Console.WriteLine(ex.ToString()); status.Device = "На данном IP или порте устройство не найдено"; return View(status); } } public Sensor GetOneSensor() { Singleton1 s1 = Singleton1.Instance; Sensor sensor = new Sensor(); OutputInterpreter interpreter = new OutputInterpreter(); Console.WriteLine("---- one sensor ----- "); List<Sensor> sensors = new List<Sensor>(); sensors = interpreter.DisplaySensorsData(s1.IP, 80); List<string> ids = interpreter.DisplayAllSensorIDs(s1.IP, sensors.Count); for (int i = 0; i < sensors.Count; i++) { sensors[i].id = ids[i]; } Console.WriteLine("========================="); sensors.ForEach(x => { Console.WriteLine(x.id + "---"); }); Console.WriteLine(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); Console.WriteLine($"{s1.Name} {s1.IP} {s1.IDS}"); //string id = "64-6e-87-9b "; string id = s1.IDS; id = id.Replace(" ", ""); id = id.Replace("-", ""); id = id.ToUpper(); foreach (var item in sensors) { string sId = item.id.Replace(" ", ""); sId = sId.Replace("-", ""); sId = sId.ToUpper(); if (sId == id) { sensor = item; Console.WriteLine($" Напряжение батареи: {item.Voltage.ToString()}, Температура: {item.Temperature.ToString()}"); } } return sensor; } [HttpGet] public IActionResult Sensors(OutputInterpreter interpreter, VibroSensors vs, CheckZone cz) { Singleton1 s1 = Singleton1.Instance; vs.ip = s1.IP; if (string.IsNullOrWhiteSpace(vs.ip)) vs.ip = "192.168.1.150"; List<Sensor> sensors = new List<Sensor>(); List<Sensor> displaySensors = new List<Sensor>(); sensors = interpreter.DisplaySensorsData(vs.ip, 80); List<FinalPoint> finalPoints = new List<FinalPoint>(); string wwwPath = this.Environment.WebRootPath; string path_plus = Path.Combine(wwwPath, "TreeData", "endpoints.json"); finalPoints = ReadJsonFile(path_plus, finalPoints); Console.WriteLine("\n\n\n>>>>>>>>>>>>>>>>>"); foreach (var item in sensors) { Console.WriteLine($"{item.Voltage} {item.Temperature}"); } //List<string> ids = interpreter.DisplayAllSensorIDs(vs.ip, sensors.Count); List<string> ids = interpreter.DisplayAllSensors(vs.ip, 80); List<int> positions = interpreter.DisplayPositions(vs.ip, 80); /* for (int i = 0; i < sensors.Count; i++) { sensors[i].id = ids[i]; }*/ for (int i = 0; i < ids.Count; i++) { Sensor sensor = new Sensor(); int pos = positions[i] - 1; if (pos < sensors.Count) { sensor = sensors[pos]; } sensor.id = ids[i]; displaySensors.Add(sensor); } vs.MapSensorsToNodes(finalPoints, sensors, cz, wwwPath); displaySensors.ForEach(x => { Console.Write(x.id+", "); }); Console.WriteLine(); // if (vs.vibroSensors != null) vs.vibroSensors.sensors = sensors; if (vs.vibroSensors != null) vs.vibroSensors.sensors = displaySensors; return View(vs); } [HttpPost] public IActionResult Sensors(OutputInterpreter interpreter, VibroSensors vs, string ip) { List<Sensor> sensors = new List<Sensor>(); //vs = new VibroSensors(); if (string.IsNullOrWhiteSpace(vs.ip)) vs.ip = "192.168.1.150"; sensors = interpreter.DisplaySensorsData(vs.ip, 80); Console.WriteLine("\n\n\n>>>>>>>>>>>>>>>>>"); foreach (var item in sensors) { } List<string> ids = interpreter.DisplayAllSensorIDs(vs.ip, sensors.Count); // List<string> ids = interpreter.DisplayAllSensors(vs.ip, 80); interpreter.DisplayPositions(vs.ip, 80); for (int i = 0; i < sensors.Count; i++) { sensors[i].id = ids[i]; } if (vs.vibroSensors != null) vs.vibroSensors.sensors = sensors; // return Ok(); //return View(vs); return RedirectToAction("Sensors", vs); } //--------------------------------------------------------- [HttpGet] public IActionResult AddNode(AddNode m, string selectedItems, string listbox, OutputInterpreter interpreter) { // create list of uploaded img files string wwwPath = this.Environment.WebRootPath; string path = Path.Combine(wwwPath, "Uploads"); string[] files = Directory.GetFiles(path); for (int i = 0; i < files.Length; i++) { string file = files[i].Replace(wwwPath + "\\Uploads\\", ""); Console.WriteLine(file); m.Files.Add(file); } // create list of available sensors /*path = Path.Combine(wwwPath, "Bases", "BaseStations.json"); List<BaseStation> stations = new List<BaseStation>(); stations = ReadJsonFile(path, stations ); List<Sensor> sensors = new List<Sensor>(); foreach (BaseStation item in stations) { item.SensorsGroup.sensors = interpreter.StationSensors(item.IP); foreach (var sensor in item.SensorsGroup.sensors) { sensor.SensorIP = item.IP; sensors.Add(sensor); } } foreach (var sensor in sensors) { string s = $"{sensor.id}-->{sensor.SensorIP}"; m.Available.Add(s); }*/ Singleton1 s1 = Singleton1.Instance; int Id = -1; Console.WriteLine(s1.selectedItems); selectedItems = s1.selectedItems; List<TreeViewNode>? items = JsonConvert.DeserializeObject<List<TreeViewNode>>(selectedItems); if (items == null) { m.SelectTeaType = TeaType.Завод; ViewBag.Sel = "+"; ViewBag.D1 = "disabled"; return View(m); } if (items != null) items.ForEach(x => { Console.WriteLine(x.text); }); Console.WriteLine("---------------------"); string name = items[0].text.ToString(); string nodeId = items[0].id.ToString(); Console.WriteLine(name); Console.WriteLine(nodeId); int nodeLevel = 0; if (nodeId.IndexOf("-") != -1) { string[] levels = nodeId.Split("-"); nodeLevel = levels.Length - 1; int.TryParse(levels[nodeLevel], out Id); } else { int.TryParse(nodeId, out Id); } Console.WriteLine("New Node level is: " + (nodeLevel + 1)); Console.WriteLine("Parent Id is: " + Id); Console.WriteLine("Parent is: " + name); //Console.WriteLine(m.SelectTeaType); if (nodeLevel == 2) { ViewBag.D1 = ""; path = Path.Combine(wwwPath, "Bases", "BaseStations.json"); List<BaseStation> stations = new List<BaseStation>(); stations = ReadJsonFile(path, stations); List<Sensor> sensors = new List<Sensor>(); foreach (BaseStation item in stations) { item.SensorsGroup.sensors = interpreter.StationSensors(item.IP); foreach (var sensor in item.SensorsGroup.sensors) { sensor.SensorIP = item.IP; sensors.Add(sensor); } } foreach (var sensor in sensors) { string s = $"{sensor.id}-->{sensor.SensorIP}"; m.Available.Add(s); } } else { ViewBag.D1 = "disabled"; } m.SelectTeaType = (TeaType)(nodeLevel + 1); m.Parent = name; m.ParentId = Id; //ViewBag.D1 = "++++++"; //Console.WriteLine(ViewBag.D1); return View(m); } [HttpPost] public IActionResult AddNode(AddNode m, string listbox, string listbox1, string listbox2) { //Console.WriteLine(listbox); //Console.WriteLine(listbox1); Console.WriteLine(listbox2); //------ if nodetype is 3 ------- /*string[] sensorData = listbox1.Split("-->"); if (sensorData.Length == 2) { m.IDS = sensorData[0]; m.IP = sensorData[1]; } foreach (var item in sensorData) { Console.WriteLine(item); }*/ //------------------------------------------ /* Console.WriteLine($"ParentId: {m.ParentId}"); m.TeaList = GetAllTeaTypes(); if (m.SelectedTeaIds != null) { List<SelectListItem> selectedItems = m.TeaList.Where(p => m.SelectedTeaIds.Contains(int.Parse(p.Value))).ToList(); foreach (var Tea in selectedItems) { Tea.Selected = true; ViewBag.Message += Tea.Text + " | "; } }*/ // dropdown var selectedValue = m.Selected; int nodeType = (int)selectedValue; string wwwPath = this.Environment.WebRootPath; if (listbox != "Выбрать" && !listbox.IsNullOrWhiteSpace()) { m.ImgFileName = listbox; } if (m.ImgFileName.IsNullOrWhiteSpace()) { m.ImgFileName = ""; } Console.WriteLine("Node type: " + nodeType); if (nodeType == 0) { string path1 = Path.Combine(wwwPath, "TreeData", "types1.json"); List<VehicleType> types = new List<VehicleType>(); types = ReadJsonFile(path1, types); if (types == null) { return View(m); } else { int[] ids = new int[types.Count]; types.ForEach(x => { Console.WriteLine(x.Id + " " + x.Name); }); if (types.Find(x => x.Name == m.Name) != null) { m.Result = "Такое предприятие уже существует"; return View(m); } if (m.Name.IsNullOrWhiteSpace()) { m.Result = "Неправильное название"; Console.WriteLine(m.Name); return View(m); } for (int i = 0; i < types.Count; i++) { ids[i] = types[i].Id; } int nextId = ids.Max() + 1; Console.WriteLine(nextId); Console.WriteLine(m.Name); Console.WriteLine(m.ImgFileName); VehicleType type = new VehicleType { Id = nextId, Name = m.Name, ImgFileName = m.ImgFileName }; types.Add(type); types.ForEach(x => { Console.WriteLine(x.Id + " " + x.Name + " " + x.ImgFileName); }); path1 = Path.Combine(wwwPath, "TreeData", "types1.json"); WriteJsonFile(path1, types); m.Result = "Успешно добавлено"; } } if (nodeType == 1) { string path1 = Path.Combine(wwwPath, "TreeData", "types1.json"); string path2 = Path.Combine(wwwPath, "TreeData", "subtypes1.json"); List<VehicleType> types = new List<VehicleType>(); List<VehicleSubType> subtypes = new List<VehicleSubType>(); types = ReadJsonFile(path1, types); subtypes = ReadJsonFile(path2, subtypes); if (types == null || subtypes == null) { return View(m); } else { int[] ids = new int[subtypes.Count]; subtypes.ForEach(x => { Console.WriteLine(x.Id + " " + x.Name); }); if (subtypes.Find(x => x.Name == m.Name) != null) { //m.Result = "Такое название уже существует"; // return View(m); } if (m.Name.IsNullOrWhiteSpace()) { m.Result = "Неправильное название"; Console.WriteLine(m.Name); return View(m); } if (types.Find(x => x.Id == m.ParentId) == null) { m.Result = "Такого предприятия нет"; return View(m); } for (int i = 0; i < subtypes.Count; i++) { ids[i] = subtypes[i].Id; } int nextId = ids.Max() + 1; Console.WriteLine("Next Id: " + nextId); // VehicleSubType subtype = new VehicleSubType { Id = nextId, Name = m.Name, VehicleTypeId = types.Find(x => x.Name == m.Parent).Id }; VehicleSubType subtype = new VehicleSubType { Id = nextId, Name = m.Name, VehicleTypeId = m.ParentId, ImgFileName = m.ImgFileName }; subtypes.Add(subtype); subtypes.ForEach(x => { Console.Write(x.Name + " "); }); path2 = Path.Combine(wwwPath, "TreeData", "subtypes1.json"); WriteJsonFile(path2, subtypes); m.Result = "Успешно добавлено"; } } if (nodeType == 2) { string path1 = Path.Combine(wwwPath, "TreeData", "subtypes1.json"); string path2 = Path.Combine(wwwPath, "TreeData", "points1.json"); List<MetricPoint> points = new List<MetricPoint>(); List<VehicleSubType> subtypes = new List<VehicleSubType>(); subtypes = ReadJsonFile(path1, subtypes); points = ReadJsonFile(path2, points); if (points == null || subtypes == null) { Console.WriteLine("Ошибка чтения файла"); return View(m); } else { int[] ids = new int[points.Count]; points.ForEach(x => { Console.WriteLine(x.Id + " " + x.Name); }); if (points.Find(x => x.Name == m.Name) != null) { //m.Result = "Такое название уже существует"; //return View(m); } if (m.Name.IsNullOrWhiteSpace()) { m.Result = "Неправильное название"; Console.WriteLine(m.Name); return View(m); } if (subtypes.Find(x => x.Id == m.ParentId) == null) { m.Result = "Такого цеха нет"; return View(m); } for (int i = 0; i < points.Count; i++) { ids[i] = points[i].Id; } int nextId = ids.Max() + 1; Console.WriteLine("Next Id: " + nextId); // MetricPoint point = new MetricPoint { Id = nextId, Name = m.Name, VehicleId = subtypes.Find(x => x.Name == m.Parent).Id, IP = m.IP, IDS = m.IDS, SensorType = m.SensorType }; MetricPoint point = new MetricPoint { Id = nextId, Name = m.Name, ImgFileName = m.ImgFileName, VehicleId = m.ParentId, IP = m.IP, IDS = m.IDS, SensorType = m.SensorType }; points.Add(point); points.ForEach(x => { Console.WriteLine(x.Name + " " + x.Id + " " + x.IDS + " " + x.IP + " " + x.VehicleId); }); path2 = Path.Combine(wwwPath, "TreeData", "points1.json"); WriteJsonFile(path2, points); m.Result = "Успешно добавлено"; } } if (nodeType == 3) { string[] sensorData = listbox1.Split("-->"); if (sensorData.Length == 2) { m.IDS = sensorData[0]; m.IP = sensorData[1]; } foreach (var item in sensorData) { Console.WriteLine(item); } string path1 = Path.Combine(wwwPath, "TreeData", "points1.json"); string path2 = Path.Combine(wwwPath, "TreeData", "endpoints.json"); List<FinalPoint> finalpoints = new List<FinalPoint>(); List<MetricPoint> points = new List<MetricPoint>(); points = ReadJsonFile(path1, points); finalpoints = ReadJsonFile(path2, finalpoints); if (points == null || finalpoints == null) { Console.WriteLine("Ошибка чтения файла"); return View(m); } else { int[] ids = new int[finalpoints.Count]; finalpoints.ForEach(x => { Console.WriteLine(x.Id + " " + x.Name); }); if (finalpoints.Find(x => x.Name == m.Name) != null) { //m.Result = "Такое название уже существует"; //return View(m); } if (m.Name.IsNullOrWhiteSpace()) { m.Result = "Неправильное название"; Console.WriteLine(m.Name); return View(m); } if (points.Find(x => x.Id == m.ParentId) == null) { m.Result = "Такой установки нет"; return View(m); } for (int i = 0; i < finalpoints.Count; i++) { ids[i] = finalpoints[i].Id; } int nextId = ids.Max() + 1; Console.WriteLine("Next Id: " + nextId); int eqnClass; // equipment vibro class int.TryParse(listbox2, out eqnClass); // set vibro class FinalPoint finalpoint = new FinalPoint { Id = nextId, Name = m.Name, MetricPointId = m.ParentId, IP = m.IP, IDS = m.IDS, SensorType = m.SensorType, EqnClass = eqnClass }; finalpoints.Add(finalpoint); finalpoints.ForEach(x => { Console.WriteLine(x.Name + " " + x.Id + " " + x.IDS + " " + x.IP + " " + x.MetricPointId); }); WriteJsonFile(path2, finalpoints); m.Result = "Успешно добавлено"; } } ViewBag.TeaType = selectedValue.ToString(); ViewBag.DA = "diasbled"; //return View(); return View(m); } public List<SelectListItem> GetAllTeaTypes() { List<SelectListItem> items = new List<SelectListItem>(); items.Add(new SelectListItem { Text = "General Tea", Value = "1" }); items.Add(new SelectListItem { Text = "Coffee", Value = "2" }); items.Add(new SelectListItem { Text = "Green Tea", Value = "3" }); items.Add(new SelectListItem { Text = "Black Tea", Value = "4" }); return items; } //----------------------------------------------------------- [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } } }