Reuse db context

This commit is contained in:
Martijn Scheepers
2024-11-29 11:31:29 +01:00
parent f8730c580a
commit 834c64ecbf
18 changed files with 206 additions and 184 deletions

View File

@@ -4,6 +4,8 @@ root = true
# C# files
[*.cs]
dotnet_diagnostic.IDE0058.severity = none
#### Core EditorConfig Options ####
# Indentation and spacing
@@ -229,6 +231,7 @@ dotnet_naming_style.begins_with_i.required_prefix = I
dotnet_naming_style.begins_with_i.required_suffix =
dotnet_naming_style.begins_with_i.word_separator =
dotnet_naming_style.begins_with_i.capitalization = pascal_case
csharp_prefer_system_threading_lock = true:suggestion
[*.{cs,vb}]
dotnet_style_operator_placement_when_wrapping = beginning_of_line

View File

@@ -108,7 +108,7 @@ namespace UCS_Status_Monitor.UnitTest
}
[TestMethod]
[SuppressMessage("Interoperability", "CA1416:Validate platform compatibility", Justification = "<Pending>")]
//[SuppressMessage("Interoperability", "CA1416:Validate platform compatibility", Justification = "<Pending>")]
public void LDAPService_GetAllUsers()
{
ILogger<LDAPService> logger = Mock.Of<ILogger<LDAPService>>();
@@ -144,7 +144,7 @@ namespace UCS_Status_Monitor.UnitTest
[DataRow("Users", 0)]
[DataRow("Administrators", 1)]
[DataRow("Guests", 1)]
[SuppressMessage("Interoperability", "CA1416:Validate platform compatibility", Justification = "<Pending>")]
//[SuppressMessage("Interoperability", "CA1416:Validate platform compatibility", Justification = "<Pending>")]
public void LDAPService_GetAllUsersForGroup(string group, int count)
{
ILogger<LDAPService> logger = Mock.Of<ILogger<LDAPService>>();
@@ -171,7 +171,7 @@ namespace UCS_Status_Monitor.UnitTest
}
[TestMethod]
[SuppressMessage("Interoperability", "CA1416:Validate platform compatibility", Justification = "<Pending>")]
//[SuppressMessage("Interoperability", "CA1416:Validate platform compatibility", Justification = "<Pending>")]
public void LDAPService_GetAllGroups()
{
ILogger<LDAPService> logger = Mock.Of<ILogger<LDAPService>>();
@@ -193,7 +193,7 @@ namespace UCS_Status_Monitor.UnitTest
}
[TestMethod]
[SuppressMessage("Interoperability", "CA1416:Validate platform compatibility", Justification = "<Pending>")]
//[SuppressMessage("Interoperability", "CA1416:Validate platform compatibility", Justification = "<Pending>")]
public void LDAPService_GetAllGroupsForUser()
{
ILogger<LDAPService> logger = Mock.Of<ILogger<LDAPService>>();

View File

@@ -2,7 +2,6 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -41,7 +40,7 @@ namespace UCS_Status_Monitor.Controllers
[Authorize]
public async Task<JsonResult> GetIndexTable(CancellationToken token)
{
using var db = await _contextFactory.CreateDbContextAsync(token);
using MonitorDbContext db = await _contextFactory.CreateDbContextAsync(token);
List<HomeTableModel> systems = await db.UCSSystems
.Include(d => d.Devices)
.OrderByDescending(o => o.ComputerName)
@@ -68,7 +67,7 @@ namespace UCS_Status_Monitor.Controllers
[Authorize]
public async Task<JsonResult> GetOverviewTable(string sortOrder, CancellationToken token)
{
using var db = await _contextFactory.CreateDbContextAsync(token);
using MonitorDbContext db = await _contextFactory.CreateDbContextAsync(token);
IQueryable<UCSSystem> systems = db.UCSSystems.Include(d => d.Devices).OrderByDescending(o => o.ComputerName);
if (sortOrder != null)
@@ -251,7 +250,7 @@ namespace UCS_Status_Monitor.Controllers
return BadRequest("No id");
}
using var db = await _contextFactory.CreateDbContextAsync(token);
using MonitorDbContext db = await _contextFactory.CreateDbContextAsync(token);
UCSSystem? system = await db.UCSSystems.Where(i => i.UCSSystemId == id)
.Include(d => d.Devices)
.Include(d => d.Errors.OrderByDescending(o => o.TimeGenerated))
@@ -274,7 +273,7 @@ namespace UCS_Status_Monitor.Controllers
return BadRequest("No id to display");
}
using var db = await _contextFactory.CreateDbContextAsync(token);
using MonitorDbContext db = await _contextFactory.CreateDbContextAsync(token);
UCSSystem? system = await db.UCSSystems.Where(i => i.UCSSystemId == id)
.Include(d => d.Devices)
.SingleOrDefaultAsync(token);
@@ -333,7 +332,7 @@ namespace UCS_Status_Monitor.Controllers
return BadRequest("No id to delete");
}
using var db = await _contextFactory.CreateDbContextAsync(token);
using MonitorDbContext db = await _contextFactory.CreateDbContextAsync(token);
UCSSystem? system = await db.UCSSystems.Where(i => i.UCSSystemId == id)
.Include(d => d.Devices)
.Include(d => d.Loggings)
@@ -371,7 +370,7 @@ namespace UCS_Status_Monitor.Controllers
return BadRequest("No id");
}
using var db = await _contextFactory.CreateDbContextAsync(token);
using MonitorDbContext db = await _contextFactory.CreateDbContextAsync(token);
UCSSystem? system = await db.UCSSystems.FindAsync([id], token);
if (system == null)
@@ -409,7 +408,7 @@ namespace UCS_Status_Monitor.Controllers
return BadRequest("No id");
}
using var db = await _contextFactory.CreateDbContextAsync(token);
using MonitorDbContext db = await _contextFactory.CreateDbContextAsync(token);
UCSSystem? system = await db.UCSSystems.Where(i => i.UCSSystemId == id)
.Include(d => d.Errors.OrderByDescending(o => o.TimeGenerated))
.SingleOrDefaultAsync(token);
@@ -425,7 +424,7 @@ namespace UCS_Status_Monitor.Controllers
[Authorize]
public async Task<IActionResult> Sensors(string sortOrder, CancellationToken token)
{
using var db = await _contextFactory.CreateDbContextAsync(token);
using MonitorDbContext db = await _contextFactory.CreateDbContextAsync(token);
IQueryable<Sensor> sensors = db.Sensors.OrderByDescending(x => x.Date).Take(25);
if (sortOrder != null)
@@ -507,7 +506,7 @@ namespace UCS_Status_Monitor.Controllers
[Authorize]
public async Task<JsonResult> GetCamerasTable(CancellationToken token)
{
using var db = await _contextFactory.CreateDbContextAsync(token);
using MonitorDbContext db = await _contextFactory.CreateDbContextAsync(token);
List<CameraTableModel> camsList = await db.AxisCams
.OrderByDescending(o => o.Device)
@@ -539,7 +538,7 @@ namespace UCS_Status_Monitor.Controllers
[Authorize]
public async Task<JsonResult> GetRoutersTable(CancellationToken token)
{
using var db = await _contextFactory.CreateDbContextAsync(token);
using MonitorDbContext db = await _contextFactory.CreateDbContextAsync(token);
List<RouterTableModel> camsList = await db.Routers
.OrderByDescending(o => o.Device)
@@ -560,7 +559,7 @@ namespace UCS_Status_Monitor.Controllers
[Authorize]
public async Task<IActionResult> RoutersOverview(CancellationToken token)
{
using var db = await _contextFactory.CreateDbContextAsync(token);
using MonitorDbContext db = await _contextFactory.CreateDbContextAsync(token);
List<Router> routersList = await db.Routers
.GroupBy(rout => rout.Device)
.Select(x => x.OrderBy(t => t.Timestamp).Last())
@@ -578,7 +577,7 @@ namespace UCS_Status_Monitor.Controllers
return BadRequest("No id");
}
using var db = await _contextFactory.CreateDbContextAsync(token);
using MonitorDbContext db = await _contextFactory.CreateDbContextAsync(token);
//RouterLogViewModel routerLog = new();

View File

@@ -52,7 +52,11 @@ namespace UCS_Status_Monitor.Controllers
_logger.LogInformation("telemetry == null");
return new JsonResult("Failed");
}
if (telemetry.ComputerName == null)
{
_logger.LogInformation("telemetry.ComputerName == null");
return new JsonResult("Failed");
}
if (!_monitorHandler.TryGetDevice(telemetry.ComputerName, out IMonitorObject ucsDevice))
{
@@ -60,9 +64,10 @@ namespace UCS_Status_Monitor.Controllers
ucsDevice = new UCSSystemMonitorDevice(_configuration.GetSection("MonitorWorker").GetValue<int>("UCSTimeOutMinutes"), _contextFactory, _telegramBot);
_monitorHandler.AddDevice(telemetry.ComputerName, ucsDevice);
}
await ucsDevice.Update(telemetry, token);
await ucsDevice.SetConnectionState(true, token);
using MonitorDbContext db = await _contextFactory.CreateDbContextAsync(token);
await ucsDevice.Update(telemetry, db, token);
await ucsDevice.SetConnectionState(true, db, token);
await db.SaveChangesAsync(token);
return new JsonResult("OK");

View File

@@ -1,5 +1,4 @@
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System.Diagnostics;
using System.IO;
using System.Text;
@@ -27,13 +26,16 @@ namespace UCS_Status_Monitor.Controllers
{
//newtonsoft json
string json = await reader.ReadToEndAsync(token);
Update update = JsonConvert.DeserializeObject<Update>(json);
//Update update = JsonConvert.DeserializeObject<Update>(json);
Update? update = JsonSerializer.Deserialize<Update>(json);
//system.text.json
//var data = System.Text.Json.JsonSerializer.Deserialize<Update>(json);
//Debug.WriteLine($"Webhook post type={update.Type} message={update.Message}");
await _telegramBot.HandleUpdateAsync(update, token);
if (update != null)
{
await _telegramBot.HandleUpdateAsync(update, token);
}
}
return Ok();
}

View File

@@ -49,10 +49,10 @@ namespace UCS_Status_Monitor.Controllers
{
//Debug.WriteLine($"WSEN get {devid}");
//Debug.WriteLine($"Content {content}");
if(string.IsNullOrEmpty(devid) || string.IsNullOrEmpty(content))
if (string.IsNullOrEmpty(devid) || string.IsNullOrEmpty(content))
{
return new JsonResult("Go away");
}
}
if (!_monitorHandler.TryGetDevice(devid, out IMonitorObject prtgDevice))
{
@@ -60,8 +60,10 @@ namespace UCS_Status_Monitor.Controllers
prtgDevice = new PRTGMonitorDevice(_configuration.GetSection("MonitorWorker").GetValue<int>("PRTGTimeOutMinutes"), _contextFactory, _telegramBot);
_monitorHandler.AddDevice(devid, prtgDevice);
}
using MonitorDbContext db = await _contextFactory.CreateDbContextAsync(token);
await prtgDevice.Update(devid, token);
await prtgDevice.SetConnectionState(true, token);
await prtgDevice.SetConnectionState(true, db, token);
await db.SaveChangesAsync(token);
return new JsonResult("OK");
}

View File

@@ -203,8 +203,10 @@ namespace UCS_Status_Monitor.Mqtt
router = new RouterMonitorDevice(_configuration.GetSection("MonitorWorker").GetValue<int>("RouterTimeOutMinutes"), _contextFactory, _telegramBot);
_monitorHandler.AddDevice(device, router);
}
await router.Update(teltonikaMessage);
await router.SetConnectionState(true);
using MonitorDbContext db = await _contextFactory.CreateDbContextAsync();
await router.Update(teltonikaMessage, db);
await router.SetConnectionState(true, db);
await db.SaveChangesAsync();
}
else
{
@@ -225,8 +227,10 @@ namespace UCS_Status_Monitor.Mqtt
router = new RouterMonitorDevice(_configuration.GetSection("MonitorWorker").GetValue<int>("RouterTimeOutMinutes"), _contextFactory, _telegramBot);
_monitorHandler.AddDevice(device, router);
}
await router.Update(teltonikaMessage);
await router.SetConnectionState(true);
using MonitorDbContext db = await _contextFactory.CreateDbContextAsync();
await router.Update(teltonikaMessage, db);
await router.SetConnectionState(true, db);
await db.SaveChangesAsync();
}
}
}
@@ -251,8 +255,10 @@ namespace UCS_Status_Monitor.Mqtt
axisCam = new AxisCamMonitorDevice(_contextFactory, _telegramBot);
_monitorHandler.AddDevice(device, axisCam);
}
bool connected = await axisCam.Update(axisCamMessage);
await axisCam.SetConnectionState(connected);
using MonitorDbContext db = await _contextFactory.CreateDbContextAsync();
bool connected = await axisCam.Update(axisCamMessage, db);
await axisCam.SetConnectionState(connected, db);
await db.SaveChangesAsync();
}
else if (args.ApplicationMessage.Topic.EndsWith("/status"))
{
@@ -270,8 +276,10 @@ namespace UCS_Status_Monitor.Mqtt
axisCam = new AxisCamMonitorDevice(_contextFactory, _telegramBot);
_monitorHandler.AddDevice(device, axisCam);
}
await axisCam.Update(axisCamStatusMessage);
await axisCam.SetConnectionState(true);
using MonitorDbContext db = await _contextFactory.CreateDbContextAsync();
await axisCam.Update(axisCamStatusMessage, db);
await axisCam.SetConnectionState(true, db);
await db.SaveChangesAsync();
}
else
{
@@ -304,13 +312,11 @@ namespace UCS_Status_Monitor.Mqtt
axisCam = new AxisCamMonitorDevice(_contextFactory, _telegramBot);
_monitorHandler.AddDevice(device, axisCam);
}
await axisCam.Update(axisCamStatusMessage);
await axisCam.SetConnectionState(true);
using MonitorDbContext db = await _contextFactory.CreateDbContextAsync();
await axisCam.Update(axisCamStatusMessage, db);
await axisCam.SetConnectionState(true, db);
await db.SaveChangesAsync();
}
}
return Task.CompletedTask;
}

View File

@@ -6,13 +6,21 @@ namespace UCS_Status_Monitor.Models.Database
{
public class AxisCam
{
public AxisCam() { }
public AxisCam(AxisCamConnectionMessage message)
{
Update(message);
}
public void Update(AxisCamConnectionMessage message)
{
Location = message.Location;
Device = message.Device;
ArgumentNullException.ThrowIfNull(message);
Location = message.Location ?? "??";
Device = message.Device ?? "??";
SerialNumber = message.SerialNumber ?? "";
Timestamp = message.Timestamp ?? DateTime.MinValue;
Connected = message.Connected;
Connected = message.Connected;
Description = message.Description ?? "";
SystemReady = true;
Temperature = "??";

View File

@@ -8,8 +8,19 @@ namespace UCS_Status_Monitor.Models.Database
{
public Router() { }
public Router(TeltonikaMessage message)
{
Update(message);
}
public Router(TeltonikaMessageV2 message)
{
Update(message);
}
public void Update(TeltonikaMessage message)
{
ArgumentNullException.ThrowIfNull(message);
Location = message.Location;
Device = message.Device;
Temperature = message.TempValue();
@@ -24,8 +35,10 @@ namespace UCS_Status_Monitor.Models.Database
}
public void Update(TeltonikaMessageV2 message)
{
Location = message.Location;
Device = message.Device;
ArgumentNullException.ThrowIfNull(message);
Location = message.Location ?? "??";
Device = message.Device ?? "??";
Temperature = message.GSM.TempValue();
//Uptime = message.Base.UptimeValue();

View File

@@ -3,6 +3,7 @@ using System.ComponentModel.DataAnnotations;
using System;
using Microsoft.EntityFrameworkCore;
using UCS_Status_Monitor.Extensions;
using Telegram.Bot.Types;
namespace UCS_Status_Monitor.Models.Database
{
@@ -18,7 +19,9 @@ namespace UCS_Status_Monitor.Models.Database
public void Update(Telemetry.TelemetryPacket telemetry)
{
ComputerName = telemetry.ComputerName;
ArgumentNullException.ThrowIfNull(telemetry);
ComputerName = telemetry.ComputerName ?? "??";
LastMessageTime = DateTime.Now;
ConnectionState = true;
StartTime = telemetry.StartTime != null ? DateTime.Parse(telemetry.StartTime) : DateTime.MinValue;

View File

@@ -12,55 +12,49 @@ using UCS_Status_Monitor.Telegram;
namespace UCS_Status_Monitor.Monitor
{
public class AxisCamMonitorDevice : BaseMonitorDevice, IMonitorObject
public class AxisCamMonitorDevice(IDbContextFactory<MonitorDbContext> contextFactory, ITelegramBotService telegramBot) : BaseMonitorDevice(0), IMonitorObject
{
private readonly IDbContextFactory<MonitorDbContext> _contextFactory;
private readonly ITelegramBotService _telegramBot;
private readonly IDbContextFactory<MonitorDbContext> _contextFactory = contextFactory;
private readonly ITelegramBotService _telegramBot = telegramBot;
public AxisCamMonitorDevice(IDbContextFactory<MonitorDbContext> contextFactory, ITelegramBotService telegramBot)
: base(0, contextFactory, telegramBot)
public override async Task SetConnectionState(bool isConnected, MonitorDbContext db, CancellationToken token = default)
{
_contextFactory = contextFactory;
_telegramBot = telegramBot;
}
ArgumentNullException.ThrowIfNull(db);
public override async Task SetConnectionState(bool isConnected, CancellationToken token = default)
{
LastData = DateTime.UtcNow;
await base.SetConnectionState(isConnected, db, token);
if (IsConnected != isConnected)
{
IsConnected = isConnected;
using var db = await _contextFactory.CreateDbContextAsync(token);
AxisCam? cam = db.AxisCams.Where(x => x.Device == DeviceName).FirstOrDefault();
if (cam != null)
{
cam.Connected = isConnected;
db.AxisCams.Update(cam);
await db.SaveChangesAsync(token);
}
await _telegramBot.SendConnectionStatus($"{Location} - {DeviceName}", isConnected, token);
}
}
public override async Task<bool> Update(AxisCamConnectionMessage message, CancellationToken token = default)
public override async Task<bool> Update(AxisCamConnectionMessage message, MonitorDbContext db, CancellationToken token = default)
{
DeviceName = message.Device;
Location = message.Location;
ArgumentNullException.ThrowIfNull(message);
ArgumentNullException.ThrowIfNull(db);
DeviceName = message.Device ?? "??";
Location = message.Location ?? "??";
//Debug.WriteLine($"----------- device name = {message.Device} - {message.Connected}");
using var db = await _contextFactory.CreateDbContextAsync(token);
AxisCam? cam = db.AxisCams.Where(x => x.Device == message.Device).FirstOrDefault();
if (cam == null)
{
//new cam
AxisCam newCam = new();
newCam.Update(message);
AxisCam newCam = new(message);
db.AxisCams.Add(newCam);
await _telegramBot.SendDeviceAdded($"{newCam.Location} - {newCam.Device}", token);
if(!message.Connected)
if (!message.Connected)
{
await _telegramBot.SendConnectionStatus($"{Location} - {DeviceName}", message.Connected, token);
}
@@ -75,16 +69,17 @@ namespace UCS_Status_Monitor.Monitor
cam.Update(message);
db.AxisCams.Update(cam);
}
await db.SaveChangesAsync(token);
return message.Connected;
}
public override async Task Update(AxisCamStatusMessage message, CancellationToken token = default)
public override async Task Update(AxisCamStatusMessage message, MonitorDbContext db, CancellationToken token = default)
{
DeviceName = message.Device;
Location = message.Location;
ArgumentNullException.ThrowIfNull(message);
ArgumentNullException.ThrowIfNull(db);
DeviceName = message.Device ?? "??";
Location = message.Location ?? "??";
using var db = await _contextFactory.CreateDbContextAsync(token);
AxisCam? cam = db.AxisCams.Where(x => x.Device == message.Device).FirstOrDefault();
if (cam != null)
{
@@ -135,10 +130,7 @@ namespace UCS_Status_Monitor.Monitor
await _telegramBot.Send($"✅ <b>{cam.Location} - {cam.Device}</b>{Environment.NewLine} Temp. ok", token);
}
db.AxisCams.Update(cam);
await db.SaveChangesAsync(token);
}
}
}

View File

@@ -11,52 +11,54 @@ using System.Diagnostics;
namespace UCS_Status_Monitor.Monitor
{
public class BaseMonitorDevice : IMonitorObject
public class BaseMonitorDevice : IMonitorObject, IDisposable
{
private readonly IDbContextFactory<MonitorDbContext> _contextFactory;
private readonly ITelegramBotService _telegramBot;
//private readonly IDbContextFactory<MonitorDbContext> _contextFactory;
//private readonly ITelegramBotService _telegramBot;
public BaseMonitorDevice(int timeout, IDbContextFactory<MonitorDbContext> contextFactory, ITelegramBotService telegramBot)
//public BaseMonitorDevice(int timeout, IDbContextFactory<MonitorDbContext> contextFactory, ITelegramBotService telegramBot)
public BaseMonitorDevice(int timeout)
{
_contextFactory = contextFactory;
_telegramBot = telegramBot;
//_contextFactory = contextFactory;
//_telegramBot = telegramBot;
_connectionTimeout = timeout;
_connectionTimer = new();
_connectionTimer.Elapsed += ConnectionTimerElapsed;
}
public string DeviceName { get; set; }
public string Location { get; set; }
public string DeviceName { get; set; } = string.Empty;
public string Location { get; set; } = string.Empty;
public bool IsConnected { get; set; }
public virtual Task SetConnectionState(bool isConnected, CancellationToken token = default)
public virtual Task SetConnectionState(bool isConnected, MonitorDbContext db, CancellationToken token = default)
{
LastData = DateTime.UtcNow;
return Task.CompletedTask;
}
public virtual Task<bool> Update(AxisCamConnectionMessage message, MonitorDbContext db, CancellationToken token = default)
{
throw new NotImplementedException();
}
public virtual Task<bool> Update(AxisCamConnectionMessage message, CancellationToken token = default)
public virtual Task Update(AxisCamStatusMessage message, MonitorDbContext db, CancellationToken token = default)
{
throw new NotImplementedException();
}
public virtual Task Update(AxisCamStatusMessage message, CancellationToken token = default)
public virtual Task Update(TeltonikaMessage message, MonitorDbContext db, CancellationToken token = default)
{
throw new NotImplementedException();
}
public virtual Task Update(TeltonikaMessage message, CancellationToken token = default)
public virtual Task Update(TeltonikaMessageV2 message, MonitorDbContext db, CancellationToken token = default)
{
throw new NotImplementedException();
}
public virtual Task Update(TeltonikaMessageV2 message, CancellationToken token = default)
{
throw new NotImplementedException();
}
public virtual Task Update(TelemetryPacket message, CancellationToken token)
public virtual Task Update(TelemetryPacket message, MonitorDbContext db, CancellationToken token)
{
throw new NotImplementedException();
}
@@ -66,26 +68,33 @@ namespace UCS_Status_Monitor.Monitor
throw new NotImplementedException();
}
//public virtual Task Update<T>(T message, CancellationToken token = default)
//{
// throw new NotImplementedException();
//}
//------------ Connection timeout -----------------
private readonly System.Timers.Timer _connectionTimer = new();
private System.Timers.Timer? _connectionTimer;
private readonly int _connectionTimeout;
private DateTime _lastdata;
public DateTime LastData
{
get { return _lastdata; }
get => _lastdata;
set
{
_lastdata = value;
if (_connectionTimeout > 0)
{
_connectionTimer.Stop();
_connectionTimer.AutoReset = false;
_connectionTimer.Interval = _connectionTimeout * 1000 * 60;
_connectionTimer.Start();
if (_connectionTimer != null)
{
_connectionTimer.Stop();
_connectionTimer.AutoReset = false;
_connectionTimer.Interval = _connectionTimeout * 1000 * 60;
_connectionTimer.Start();
}
}
}
}
@@ -103,7 +112,7 @@ namespace UCS_Status_Monitor.Monitor
{
//Debug.WriteLine($"_connectionState = {IsConnected}");
if (IsConnected == true)
if (IsConnected)
{
//Debug.WriteLine("Connection timeout");
new ValueTask(SetConnectionState(false, default)).AsTask();
@@ -111,10 +120,22 @@ namespace UCS_Status_Monitor.Monitor
}
}
public void StopTimer()
public void Dispose()
{
_connectionTimer.Stop();
_connectionTimer.Dispose();
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (_connectionTimer != null)
{
_connectionTimer.Stop();
_connectionTimer.Dispose();
_connectionTimer = null;
}
}
}
}
}

View File

@@ -1,5 +1,6 @@
using System.Threading;
using System.Threading.Tasks;
using UCS_Status_Monitor.Database;
using UCS_Status_Monitor.MQTT.Axis;
using UCS_Status_Monitor.MQTT.Teltonika;
using UCS_Status_Monitor.Telemetry;
@@ -13,18 +14,20 @@ namespace UCS_Status_Monitor.Monitor
public string DeviceName { get; set; }
public string Location { get; set; }
public Task SetConnectionState(bool isConnected, CancellationToken token = default);
public Task SetConnectionState(bool isConnected, MonitorDbContext db, CancellationToken token = default);
public Task<bool> Update(AxisCamConnectionMessage message, CancellationToken token = default);
public Task<bool> Update(AxisCamConnectionMessage message, MonitorDbContext db, CancellationToken token = default);
public Task Update(AxisCamStatusMessage message, CancellationToken token = default);
public Task Update(AxisCamStatusMessage message, MonitorDbContext db, CancellationToken token = default);
public Task Update(TeltonikaMessage message, CancellationToken token = default);
public Task Update(TeltonikaMessage message, MonitorDbContext db, CancellationToken token = default);
public Task Update(TeltonikaMessageV2 message, CancellationToken token = default);
public Task Update(TeltonikaMessageV2 message, MonitorDbContext db, CancellationToken token = default);
public Task Update(TelemetryPacket message, CancellationToken token);
public Task Update(TelemetryPacket message, MonitorDbContext db, CancellationToken token);
public Task Update(string deviceName, CancellationToken token);
//public Task Update<T>(T message, CancellationToken token = default);
}
}

View File

@@ -5,15 +5,11 @@ namespace UCS_Status_Monitor.Monitor
{
public class MonitorHandler
{
private readonly Dictionary<string, IMonitorObject> MonitoredDevices = new();
private readonly Dictionary<string, IMonitorObject> MonitoredDevices = [];
public bool TryGetDevice(string name, out IMonitorObject device)
{
if (MonitoredDevices.TryGetValue(name, out device))
{
return true;
}
return false;
return MonitoredDevices.TryGetValue(name, out device);
}
public void AddDevice(string name, IMonitorObject device)

View File

@@ -7,21 +7,14 @@ using UCS_Status_Monitor.Telegram;
namespace UCS_Status_Monitor.Monitor
{
public class PRTGMonitorDevice : BaseMonitorDevice, IMonitorObject
public class PRTGMonitorDevice(int timeout, IDbContextFactory<MonitorDbContext> contextFactory, ITelegramBotService telegramBot) : BaseMonitorDevice(timeout), IMonitorObject
{
private readonly IDbContextFactory<MonitorDbContext> _contextFactory;
private readonly ITelegramBotService _telegramBot;
private readonly IDbContextFactory<MonitorDbContext> _contextFactory = contextFactory;
private readonly ITelegramBotService _telegramBot = telegramBot;
public PRTGMonitorDevice(int timeout, IDbContextFactory<MonitorDbContext> contextFactory, ITelegramBotService telegramBot)
: base(timeout, contextFactory, telegramBot)
public override async Task SetConnectionState(bool isConnected, MonitorDbContext db, CancellationToken token = default)
{
_contextFactory = contextFactory;
_telegramBot = telegramBot;
}
public override async Task SetConnectionState(bool isConnected, CancellationToken token = default)
{
LastData = DateTime.UtcNow;
await base.SetConnectionState(isConnected, db, token);
if (IsConnected != isConnected)
{
IsConnected = isConnected;

View File

@@ -12,50 +12,42 @@ using System;
namespace UCS_Status_Monitor.Monitor
{
public class RouterMonitorDevice : BaseMonitorDevice, IMonitorObject
public class RouterMonitorDevice(int timeout, IDbContextFactory<MonitorDbContext> contextFactory, ITelegramBotService telegramBot) : BaseMonitorDevice(timeout), IMonitorObject
{
private readonly IDbContextFactory<MonitorDbContext> _contextFactory;
private readonly ITelegramBotService _telegramBot;
private readonly IDbContextFactory<MonitorDbContext> _contextFactory = contextFactory;
private readonly ITelegramBotService _telegramBot = telegramBot;
public RouterMonitorDevice(int timeout, IDbContextFactory<MonitorDbContext> contextFactory, ITelegramBotService telegramBot)
: base(timeout, contextFactory, telegramBot)
public override async Task SetConnectionState(bool isConnected, MonitorDbContext db, CancellationToken token = default)
{
_contextFactory = contextFactory;
_telegramBot = telegramBot;
}
ArgumentNullException.ThrowIfNull(db);
public override async Task SetConnectionState(bool isConnected, CancellationToken token = default)
{
LastData = DateTime.UtcNow;
await base.SetConnectionState(isConnected, db, token);
if (IsConnected != isConnected)
{
IsConnected = isConnected;
using var db = await _contextFactory.CreateDbContextAsync(token);
Router? router = db.Routers.Where(x => x.Device == DeviceName).FirstOrDefault();
if (router != null)
{
router.Connected = isConnected;
db.Routers.Update(router);
await db.SaveChangesAsync(token);
}
await _telegramBot.SendConnectionStatus($"{Location} - {DeviceName}", isConnected, token);
}
}
public override async Task Update(TeltonikaMessage message, CancellationToken token = default)
public override async Task Update(TeltonikaMessage message, MonitorDbContext db, CancellationToken token = default)
{
ArgumentNullException.ThrowIfNull(message);
ArgumentNullException.ThrowIfNull(db);
DeviceName = message.Device;
Location = message.Location;
using var db = await _contextFactory.CreateDbContextAsync(token);
Router? router = db.Routers.Where(x => x.Device == message.Device).FirstOrDefault();
if (router == null)
{
//new router
Router newRouter = new();
newRouter.Update(message);
Router newRouter = new(message);
db.Routers.Add(newRouter);
await _telegramBot.SendDeviceAdded($"{newRouter.Location} - {newRouter.Device}", token);
@@ -67,25 +59,24 @@ namespace UCS_Status_Monitor.Monitor
{
await _telegramBot.Send($"⚠️ <b>{Location} - {DeviceName}</b>{Environment.NewLine} WAN IP changed to {message.WanIp}", token);
}
router.Update(message);
db.Routers.Update(router);
}
await db.SaveChangesAsync(token);
}
public override async Task Update(TeltonikaMessageV2 message, CancellationToken token = default)
public override async Task Update(TeltonikaMessageV2 message, MonitorDbContext db, CancellationToken token = default)
{
DeviceName = message.Device;
Location = message.Location;
ArgumentNullException.ThrowIfNull(message);
ArgumentNullException.ThrowIfNull(db);
DeviceName = message.Device ?? "??";
Location = message.Location ?? "??";
using var db = await _contextFactory.CreateDbContextAsync(token);
Router? router = db.Routers.Where(x => x.Device == message.Device).FirstOrDefault();
if (router == null)
{
//new router
Router newRouter = new();
newRouter.Update(message);
Router newRouter = new(message);
db.Routers.Add(newRouter);
await _telegramBot.SendDeviceAdded($"{newRouter.Location} - {newRouter.Device}", token);
@@ -100,12 +91,9 @@ namespace UCS_Status_Monitor.Monitor
await _telegramBot.Send($"⚠️ <b>{Location} - {DeviceName}</b>{Environment.NewLine} WAN IP changed to {message.GSM.IpV4[0]}", token);
}
}
router.Update(message);
db.Routers.Update(router);
}
await db.SaveChangesAsync(token);
}
}
}

View File

@@ -1,5 +1,4 @@
using System.Diagnostics;
using UCS_Status_Monitor.Database;
using UCS_Status_Monitor.Database;
using UCS_Status_Monitor.Telemetry;
using System.Linq;
using System;
@@ -8,54 +7,45 @@ using UCS_Status_Monitor.Models.Database;
using System.Threading;
using Microsoft.EntityFrameworkCore;
using UCS_Status_Monitor.Telegram;
using System.Collections.Generic;
namespace UCS_Status_Monitor.Monitor
{
public class UCSSystemMonitorDevice : BaseMonitorDevice, IMonitorObject
public class UCSSystemMonitorDevice(int timeout, IDbContextFactory<MonitorDbContext> contextFactory, ITelegramBotService telegramBot) : BaseMonitorDevice(timeout), IMonitorObject
{
private readonly IDbContextFactory<MonitorDbContext> _contextFactory;
private readonly ITelegramBotService _telegramBot;
//private readonly IDbContextFactory<MonitorDbContext> _contextFactory = contextFactory;
private readonly ITelegramBotService _telegramBot = telegramBot;
public UCSSystemMonitorDevice(int timeout, IDbContextFactory<MonitorDbContext> contextFactory, ITelegramBotService telegramBot)
: base(timeout, contextFactory, telegramBot)
public override async Task SetConnectionState(bool isConnected, MonitorDbContext db, CancellationToken token = default)
{
_contextFactory = contextFactory;
_telegramBot = telegramBot;
}
ArgumentNullException.ThrowIfNull(db);
public override async Task SetConnectionState(bool isConnected, CancellationToken token = default)
{
LastData = DateTime.UtcNow;
await base.SetConnectionState(isConnected, db, token);
if (IsConnected != isConnected)
{
IsConnected = isConnected;
using MonitorDbContext db = await _contextFactory.CreateDbContextAsync(token);
UCSSystem? system = await db.UCSSystems.Where(n => n.ComputerName == DeviceName).SingleOrDefaultAsync(token);
if (system != null)
{
system.ConnectionState = isConnected;
db.UCSSystems.Update(system);
await db.SaveChangesAsync(token);
}
await _telegramBot.SendConnectionStatus($"{system.ComputerName} - {system.ConfigFileName}", isConnected, token);
}
}
public override async Task Update(TelemetryPacket message, CancellationToken token)
public override async Task Update(TelemetryPacket message, MonitorDbContext db, CancellationToken token)
{
DeviceName = message.ComputerName;
ArgumentNullException.ThrowIfNull(message);
ArgumentNullException.ThrowIfNull(db);
DeviceName = message.ComputerName ?? "??";
using MonitorDbContext db = await _contextFactory.CreateDbContextAsync(token);
UCSSystem? system = await db.UCSSystems.Where(n => n.ComputerName == message.ComputerName).SingleOrDefaultAsync(token);
if (system == null)
{
//New system
system = new UCSSystem();
system.Update(message);
system = new UCSSystem(message);
db.UCSSystems.Add(system);
db.Loggings.Add(new Logging { Date = DateTime.Now, State = true, UCSSystem = system });
@@ -163,7 +153,6 @@ namespace UCS_Status_Monitor.Monitor
system.Update(message);
db.UCSSystems.Update(system);
}
await db.SaveChangesAsync(token);
}
}
}

View File

@@ -3,7 +3,6 @@ using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using System;
using System.Configuration;
using System.Diagnostics;