using System; using System.Collections.Generic; using System.Linq; using Application.Domain.Entities; using Infrastructure.Data; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Vibrant.InfluxDB.Client; using Vibrant.InfluxDB.Client.Rows; namespace IoTCenter.Controllers { [Authorize] public class DeviceController : Controller { private readonly IConfiguration _configuration; private readonly IRepository _nodeRepo; private readonly IRepository _deviceRepo; public DeviceController(IConfiguration configuration, IRepository nodeRepo, IRepository deviceRepo) { this._configuration = configuration; this._nodeRepo = nodeRepo; this._deviceRepo = deviceRepo; } public IActionResult Index(Guid id) { var model = this._nodeRepo.ReadOnlyTable().FirstOrDefault(o => o.Id == id); return View(model); } public IActionResult Details(Guid id, string time = "10m") { var model = this._deviceRepo.ReadOnlyTable() .Include(o => o.Node) .Include(o => o.Data) .Include(o => o.Apis).ThenInclude(o => o.Parameters) .FirstOrDefault(o => o.Id == id); ViewBag.time = time; return View(model); } public IActionResult Data(Guid id, string time) { var device = this._deviceRepo.ReadOnlyTable().Include(o => o.Node).Include(o => o.Data).FirstOrDefault(o => o.Id == id); var url = this._configuration["influxdb:url"]; var usr = this._configuration["influxdb:usr"]; var pwd = this._configuration["influxdb:pwd"]; var dbName = "iot"; var measurementName = "data"; var list = new List(); using (var client = new InfluxClient(new Uri(url), usr, pwd)) { var fileds = String.Join(',', device.Data.Where(o => o.Type == "Int" || o.Type == "Float").Select(o => o.Key)); var query = $"select {fileds} from {measurementName} where time>now()-{time} and DeviceNumber = '{device.Number}' limit 10000"; var result = client.ReadAsync(dbName, query).Result; var rows = result.Results.FirstOrDefault()? .Series.FirstOrDefault()? .Rows; var labels = rows?.Select(o => o.Timestamp.Value).Select(o => o.ToString("MM-dd HH:mm:ss")).ToList() ?? new List(); foreach (var data in device.Data.Where(o => o.Type == "Int" || o.Type == "Float")) { list.Add(new { id = data.Key, label = data.Name, labels, data = rows?.Select(o => o.GetField(data.Key)).ToList() ?? new List() }); } } return Json(list); } } }