/
agontar
/
TOROS
Обзор
Документация
Войти
/
agontar
/
TOROS
Код
Запросы
0
Задачи
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
Webapplication_new/Controllers/StationsController.cs
609 строк
24 KB
gav
add DisplayPositions(ip, 80) in OutputInterpreter.cs
30 сен 2024, 12:03
30 сен 2024, 12:03
0b819fb
Код
Авторство
О чём код?
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Hosting; using Quartz.Util; using WebApplication1.Data; using WebApplication1.Models; using WebApplication1.Services; using IApplicationLifetime = Microsoft.AspNetCore.Hosting.IApplicationLifetime; namespace WebApplication1.Controllers { public class StationsController : Controller { private readonly ApplicationDbContext _context; public StationsController(ApplicationDbContext context) { _context = context; } [HttpGet] public IActionResult SyncDateTime(StationTime time) { return View(time); } [HttpPost] public IActionResult SyncDateTime(StationTime time, string IP) { Console.WriteLine($"{time.hours} {time.mins} {time.secs} {time.date} {time.month} {time.year} {time.Operation}"); Singleton1 s1 = Singleton1.Instance; IP = s1.IP; Console.WriteLine(IP); byte hours, mins, secs, date, month, year; try { OutputInterpreter interpreter = new OutputInterpreter(); Request request = new Request(); if (time.Operation == 0) { if (time.hours.IsNullOrWhiteSpace() || time.mins.IsNullOrWhiteSpace() || time.secs.IsNullOrWhiteSpace() || time.date.IsNullOrWhiteSpace() || time.month.IsNullOrWhiteSpace() || time.year.IsNullOrWhiteSpace()) { Console.WriteLine("Ошибка ввода"); time.Status = "Ошибка ввода"; return View(time); } hours = Convert.ToByte(time.hours); mins = Convert.ToByte(time.mins); secs = Convert.ToByte(time.secs); date = Convert.ToByte(time.date); month = Convert.ToByte(time.month); year = Convert.ToByte(time.year); Console.WriteLine($"{hours} {mins} {secs} {date} {month} {year}"); try { interpreter.StopOp(IP, 80); byte[] result = request.SetDateTime(IP, 80, hours, mins, secs, date, month, year); interpreter.StartOp(IP, 80); for (int i = 0; i < result.Length; i++) { Console.Write(result[i] + " "); } if (result[5] == 254) time.Status = $"Новое время: {time.hours}:{time.mins}:{time.secs}" + $" {time.date}/{time.month}/{time.year}"; else time.Status = "Команда не прошла проверьте ввод"; } catch (Exception ex) { Console.WriteLine(ex.ToString()); return View(time); } } if (time.Operation == 1) { DateTime datetime = new DateTime(); datetime = DateTime.Now; hours = Convert.ToByte(datetime.Hour.ToString()); Console.WriteLine(hours); mins = Convert.ToByte(datetime.Minute.ToString()); Console.WriteLine(mins); secs = Convert.ToByte(datetime.Second.ToString()); Console.WriteLine(secs); date = Convert.ToByte(datetime.Day.ToString()); Console.WriteLine(date); month = Convert.ToByte(datetime.Month.ToString()); Console.WriteLine(month); year = Convert.ToByte((datetime.Year - 2000).ToString()); Console.WriteLine(year); try { interpreter.StopOp(IP, 80); byte[] result = request.SetDateTime(IP, 80, hours, mins, secs, date, month, year); interpreter.StartOp(IP, 80); for (int i = 0; i < result.Length; i++) { Console.Write(result[i] + " "); } if (result[5] == 254) time.Status = $"Новое время: {hours.ToString()}:{mins.ToString()}:{secs.ToString()}" + $" {date.ToString()}/{month.ToString()}/{year.ToString()}"; else time.Status = "Команда не прошла проверьте ввод"; } catch (Exception ex) { Console.WriteLine(ex.ToString()); return View(time); } } return View(time); } catch (Exception ex) { Console.WriteLine(ex.ToString()); time.Status = "Проверьте входные данные"; return View(time); } } [HttpGet] public IActionResult ChangeSensors(SensorsChange change) { Singleton1 s1 = Singleton1.Instance; string ip = s1.IP; //if (s1.MasterType == "БС211") { ViewBag.D2 = "disabled"; } //Request request = new Request(); //byte[] output = request.Command_5_bytes(ip, 80, 0x50); OutputInterpreter interpreter = new OutputInterpreter(); //int sensorsNumber = (int)output[13]; //change.ids = interpreter.DisplayAllSensorIDs(ip, sensorsNumber); /* Console.WriteLine("=========================="); foreach (var item in change.ids) { Console.WriteLine(item); }*/ Console.WriteLine("=========================="); change.ids = interpreter.DisplayAllSensors(ip, 80); //interpreter.DisplayPositions(ip, 80); Console.WriteLine("=========================="); return View(change); } [HttpPost] public IActionResult ChangeSensors(SensorsChange change, string ip, string listbox, string listbox2, string listbox3, string parameter) { // Singleton1 s1 = Singleton1.Instance; listbox2 = "1"; // force delete operation string newIDS1 = "", newIDS2 = "", newIDS3 = "", newIDS4 = ""; Console.WriteLine($"Действие=={listbox2}=="); Console.WriteLine($" Значения=={change.AB}=={change.BC}=={change.CD}=="); change.SetFloatValues(); Console.WriteLine($" Значения float == {change.ab} == {change.bc} == {change.cd} =="); int masterType = 0; byte avs = 0x00; int.TryParse(listbox3, out masterType); byte.TryParse(parameter, out avs); Console.WriteLine($" Тип датчика == {masterType} =="); Console.WriteLine($" Выбранный AVS == {avs} =="); if (listbox2 == "2") { change.Operation = 3; if (change.IDS1.IsNullOrWhiteSpace() || change.IDS2.IsNullOrWhiteSpace() || change.IDS3.IsNullOrWhiteSpace() || change.IDS4.IsNullOrWhiteSpace()) { Console.WriteLine("Ошибка ввода"); change.Status = "Ошибка ввода"; return View(change); } newIDS1 = change.IDS1; newIDS1 = newIDS1.Replace(" ", ""); newIDS1 = newIDS1.ToLower(); newIDS2 = change.IDS2; newIDS2 = newIDS2.Replace(" ", ""); newIDS2 = newIDS2.ToLower(); newIDS3 = change.IDS3; newIDS3 = newIDS3.Replace(" ", ""); newIDS3 = newIDS3.ToLower(); newIDS4 = change.IDS4; newIDS4 = newIDS4.Replace(" ", ""); newIDS4 = newIDS4.ToLower(); } Console.WriteLine($"Датчик=={listbox}=="); string[] idsArray; if (listbox != "Выбрать" && !listbox.IsNullOrWhiteSpace()) { idsArray = listbox.Split(" "); for (int i = 0; i < idsArray.Length; i++) { Console.WriteLine(idsArray[i]); } change.IDS1 = idsArray[0]; change.IDS2 = idsArray[1]; change.IDS3 = idsArray[2]; change.IDS4 = idsArray[3]; } Console.WriteLine($" {change.IDS1}-{change.IDS2}-{change.IDS3}-{change.IDS4} {change.Operation}"); Singleton1 s1 = Singleton1.Instance; //if (s1.MasterType == "БС211") { ViewBag.D2 = "disabled"; } //if () { } ip = s1.IP; Console.WriteLine(ip); if (change.IDS1.IsNullOrWhiteSpace() || change.IDS2.IsNullOrWhiteSpace() || change.IDS3.IsNullOrWhiteSpace() || change.IDS4.IsNullOrWhiteSpace()) { Console.WriteLine("Ошибка ввода"); change.Status = "Ошибка ввода"; return View(change); } // if (!ModelState.IsValid) return BadRequest(ModelState); try { string IDS1 = change.IDS1.Replace(" ", ""); string IDS2 = change.IDS2.Replace(" ", ""); string IDS3 = change.IDS3.Replace(" ", ""); string IDS4 = change.IDS4.Replace(" ", ""); IDS1 = IDS1.ToLower(); IDS2 = IDS2.ToLower(); IDS3 = IDS3.ToLower(); IDS4 = IDS4.ToLower(); byte[] ids = Convert.FromHexString(IDS1 + IDS2 + IDS3 + IDS4); if (ids == null || ids.Length != 4) { Console.WriteLine("Ошибка ввода"); change.Status = "Ошибка ввода"; return View(change); } Console.WriteLine(ids.ToString()); for (int i = 0; i < ids.Length; i++) { Console.WriteLine(ids[i].ToString("X")); Console.WriteLine(ids[i]); /*if (ids[i] == null) { Console.WriteLine("Ошибка ввода"); change.Status = "Ошибка ввода"; return View(change); }*/ } // if sensor type is new type if (ids[0] >= 128) { } try { Request request = new Request(); byte[] result; OutputInterpreter interpreter = new OutputInterpreter(); if (change.Operation == 1) { interpreter.StopOp(ip, 80); if (s1.MasterType == "БС211") { result = request.AddSensor(ip, 80, ids); } else { result = request.AddSensorM(ip, 80, ids, masterType, avs, change.ab, change.bc, change.cd); } interpreter.StartOp(ip, 80); for (int i = 0; i < result.Length; i++) { Console.Write(result[i] + " "); } if (result[5] == 254) { change.Status = "Датчик добавлен"; } else { change.Status = "Операция не прошла, проверьте ввод"; } } if (change.Operation == 0) { interpreter.StopOp(ip, 80); result = request.RemoveSensor(ip, 80, ids); interpreter.StartOp(ip, 80); for (int i = 0; i < result.Length; i++) { Console.Write(result[i] + " "); } if (result[5] == 254) { change.Status = "Датчик удален"; } else { change.Status = "Операция не прошла, проверьте ввод"; } } if (change.Operation == 3) { Console.WriteLine("\nРедактирование"); Console.WriteLine($"Старый: {change.IDS1} {change.IDS2} {change.IDS3} {change.IDS4}"); Console.WriteLine($"Новый: {newIDS1} {newIDS2} {newIDS3} {newIDS4}"); byte[] newids = Convert.FromHexString(newIDS1 + newIDS2 + newIDS3 + newIDS4); if (newids == null || ids.Length != 4) { Console.WriteLine("Ошибка ввода"); change.Status = "Ошибка ввода"; return View(change); } interpreter.StopOp(ip, 80); byte[] result1 = request.RemoveSensor(ip, 80, ids); if (result1[5] == 254) { change.Status = "Старый датчик удален"; byte[] result2 = request.AddSensor(ip, 80, newids); if (result2[5] == 254) { change.Status = "Датчик заменен"; } else { Console.WriteLine($"Датчик не добавлен, код: {result2[5]}"); change.Status = "Новый датчик не добавлен, запись уже существует"; interpreter.StartOp(ip, 80); return View(change); } } else { change.Status = "Старый датчик не удален, проверьте ввод"; interpreter.StartOp(ip, 80); } interpreter.StartOp(ip, 80); } } catch (Exception) { change.Status = "Операция не прошла, проверьте ввод"; return View(change); } return View(change); } catch (Exception ex) { Console.WriteLine(ex.ToString()); change.Status = "Ошибка ввода"; return View(change); } } [HttpGet] public IActionResult SetSensorsReadInterval(MasterStatus status) { return View(status); } [HttpPost] public IActionResult SetSensorsReadInterval(MasterStatus status, string IP) { if (status.mins.IsNullOrWhiteSpace() || status.hours.IsNullOrWhiteSpace()) { Console.WriteLine("Ошибка ввода"); status.Status = "Ошибка ввода"; return View(status); } try { Singleton1 s1 = Singleton1.Instance; IP = s1.IP; byte hours = Convert.ToByte(status.hours); byte mins = Convert.ToByte(status.mins); OutputInterpreter interpreter = new OutputInterpreter(); Request request = new Request(); interpreter.StopOp(IP, 80); byte[] result = request.SetSensorsReadInterval(IP, 80, hours, mins); for (int i = 0; i < result.Length; i++) { Console.Write(result[i] + " "); } interpreter.StartOp(IP, 80); status.Status = "Интервал изменен"; return View(status); } catch (Exception ex) { Console.WriteLine(ex.Message); status.Status = "Ошибка ввода"; return View(status); } } [HttpGet] public IActionResult ChangeIpSettings(IpSettongs settings) { return View(settings); } [HttpPost] public IActionResult ChangeIpSettings(IpSettongs settings, string IP) { if (settings.IP.IsNullOrWhiteSpace() || settings.NewIP.IsNullOrWhiteSpace() || settings.Mask.IsNullOrWhiteSpace() || settings.GW.IsNullOrWhiteSpace()) { Console.WriteLine("Ошибка ввода"); settings.Status = "Ошибка ввода"; return View(settings); } try { IP = settings.IP; settings.IP = settings.IP.Replace(" ", ""); settings.NewIP = settings.NewIP.Replace(" ", ""); settings.Mask = settings.Mask.Replace(" ", ""); settings.GW = settings.GW.Replace(" ", ""); string[] newIpStr = settings.NewIP.Split("."); string[] maskStr = settings.Mask.Split("."); string[] gwStr = settings.GW.Split("."); byte[] ip = new byte[4]; byte[] mask = new byte[4]; byte[] gw = new byte[4]; ip[0] = Convert.ToByte(newIpStr[0]); ip[1] = Convert.ToByte(newIpStr[1]); ip[2] = Convert.ToByte(newIpStr[2]); ip[3] = Convert.ToByte(newIpStr[3]); for (int i = 0; i < ip.Length; i++) { Console.Write(ip[i] + " "); } mask[0] = Convert.ToByte(maskStr[0]); mask[1] = Convert.ToByte(maskStr[1]); mask[2] = Convert.ToByte(maskStr[2]); mask[3] = Convert.ToByte(maskStr[3]); for (int i = 0; i < mask.Length; i++) { Console.Write(mask[i] + " "); } gw[0] = Convert.ToByte(gwStr[0]); gw[1] = Convert.ToByte(gwStr[1]); gw[2] = Convert.ToByte(gwStr[2]); gw[3] = Convert.ToByte(gwStr[3]); for (int i = 0; i < gw.Length; i++) { Console.Write(gw[i] + " "); } Request request = new Request(); byte[] result = request.SetIpSettings(IP, 80, ip, mask, gw); if (result == null) { settings.Status = "Ошибка соединения"; return View(settings); } settings.Status = "Настройки изменены"; return View(settings); } catch (Exception ex) { Console.WriteLine(ex.Message); settings.Status = "Ошибка ввода"; return View(settings); } } // GET: Stations public async Task<IActionResult> Index() { return _context.Station != null ? View(await _context.Station.ToListAsync()) : Problem("Entity set 'ApplicationDbContext.Station' is null."); } // GET: Stations/Details/5 public async Task<IActionResult> Details(int? id) { if (id == null || _context.Station == null) { return NotFound(); } var station = await _context.Station .FirstOrDefaultAsync(m => m.Id == id); if (station == null) { return NotFound(); } return View(station); } // GET: Stations/Create [Authorize] public IActionResult Create() { return View(); } // POST: Stations/Create // To protect from overposting attacks, enable the specific properties you want to bind to. // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create([Bind("Id,Host,Description,Location")] Station station) { if (ModelState.IsValid) { _context.Add(station); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } return View(station); } // GET: Stations/Edit/5 public async Task<IActionResult> Edit(int? id) { if (id == null || _context.Station == null) { return NotFound(); } var station = await _context.Station.FindAsync(id); if (station == null) { return NotFound(); } return View(station); } // POST: Stations/Edit/5 // To protect from overposting attacks, enable the specific properties you want to bind to. // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(int id, [Bind("Id,Host,Description,Location")] Station station) { if (id != station.Id) { return NotFound(); } if (ModelState.IsValid) { try { _context.Update(station); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!StationExists(station.Id)) { return NotFound(); } else { throw; } } return RedirectToAction(nameof(Index)); } return View(station); } // GET: Stations/Delete/5 public async Task<IActionResult> Delete(int? id) { if (id == null || _context.Station == null) { return NotFound(); } var station = await _context.Station .FirstOrDefaultAsync(m => m.Id == id); if (station == null) { return NotFound(); } return View(station); } // POST: Stations/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteConfirmed(int id) { if (_context.Station == null) { return Problem("Entity set 'ApplicationDbContext.Station' is null."); } var station = await _context.Station.FindAsync(id); if (station != null) { _context.Station.Remove(station); } await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } private bool StationExists(int id) { return (_context.Station?.Any(e => e.Id == id)).GetValueOrDefault(); } } }