Skip to content

Commit

Permalink
snackbar support
Browse files Browse the repository at this point in the history
  • Loading branch information
mlapaglia committed Nov 8, 2023
1 parent 39817fc commit 7150832
Show file tree
Hide file tree
Showing 9 changed files with 74 additions and 25 deletions.
4 changes: 4 additions & 0 deletions OpenAlprWebhookProcessor/ProcessorHub/IProcessorHub.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ public interface IProcessorHub

Task ProcessInformationLogged(string log);

Task OpenAlprAgentConnected(string agentId, string ipAddress);

Task OpenAlprAgentDisconnected(string agentId, string ipAddress);

Task ScrapeFinished();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
using System.Collections.Concurrent;
using System.Text.RegularExpressions;
using System.Text.Json;
using static System.Runtime.InteropServices.JavaScript.JSType;
using Microsoft.Extensions.Logging;

namespace OpenAlprWebhookProcessor.WebhookProcessor.OpenAlprWebsocket
{
Expand All @@ -19,10 +19,14 @@ public partial class OpenAlprWebsocketClient

private readonly string _agentId;

private readonly ILogger _logger;

public OpenAlprWebsocketClient(
ILogger logger,
string agentId,
WebSocket webSocket)
{
_logger = logger;
_agentId = agentId;
_webSocket = webSocket;
_availableResponses = new ConcurrentDictionary<Guid, string>();
Expand Down Expand Up @@ -89,6 +93,7 @@ public bool TryGetAgentStatusResponse(
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to deserialize AgentStatusResponse");
agentStatusResponse = null;
return false;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,7 @@
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;

Expand All @@ -16,13 +11,8 @@ public class WebsocketClientOrganizer : BackgroundService
{
private readonly ConcurrentDictionary<string, OpenAlprWebsocketClient> _connectedClients;

private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();

private readonly ILogger<WebsocketClientOrganizer> _logger;

public WebsocketClientOrganizer(ILogger<WebsocketClientOrganizer> logger)
public WebsocketClientOrganizer()
{
_logger = logger;
_connectedClients = new ConcurrentDictionary<string, OpenAlprWebsocketClient>();
}

Expand All @@ -35,9 +25,17 @@ public bool AddAgent(
string agentId,
OpenAlprWebsocketClient webSocketClient)
{
return _connectedClients.TryAdd(
var wasUpdated = false;

_connectedClients.AddOrUpdate(
agentId,
webSocketClient);
webSocketClient, (key, oldValue) =>
{
wasUpdated = true;
return webSocketClient;
});

return wasUpdated;
}

public async Task RemoveAgentAsync(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
using Microsoft.AspNetCore.Http;
using System;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using OpenAlprWebhookProcessor.Data;
using System.Threading.Tasks;
using System.Threading;
using System.Text.Json;
using Microsoft.AspNetCore.SignalR;
using System.Linq;

namespace OpenAlprWebhookProcessor.WebhookProcessor.OpenAlprWebsocket
{
Expand All @@ -20,14 +23,18 @@ public class WebsocketController : ControllerBase

private readonly WebsocketClientOrganizer _websocketClientOrganizer;

private readonly IHubContext<ProcessorHub.ProcessorHub, ProcessorHub.IProcessorHub> _processorHub;

public WebsocketController(
ILogger<WebsocketController> logger,
IHubContext<ProcessorHub.ProcessorHub, ProcessorHub.IProcessorHub> processorHub,
ProcessorContext processorContext,
WebsocketClientOrganizer websocketClientOrganizer)
{
_logger = logger;
_processorContext = processorContext;
_websocketClientOrganizer = websocketClientOrganizer;
_processorHub = processorHub;
}

[HttpPost("/api/accountinfo")]
Expand All @@ -50,30 +57,43 @@ public async Task GetWebsocket(CancellationToken cancellationToken)
{
if (HttpContext.WebSockets.IsWebSocketRequest)
{
_logger.LogInformation("websocket connection received.");
_logger.LogInformation("Websocket connection received.");

var agent = await _processorContext.Agents
.AsNoTracking()
.FirstOrDefaultAsync(cancellationToken);

var webSocket = await HttpContext.WebSockets.AcceptWebSocketAsync();

var webSocketClient = new OpenAlprWebsocketClient(agent.Uid, webSocket);
var webSocketClient = new OpenAlprWebsocketClient(
_logger,
agent.Uid,
webSocket);

if (_websocketClientOrganizer.AddAgent(agent.Uid, webSocketClient))
{
_logger.LogError("Multiple websocket connections for the same agent, overwriting old connection: {agentId}.", agent.Uid);
}

await _processorHub.Clients.All.OpenAlprAgentConnected(agent.Uid, HttpContext.Connection.RemoteIpAddress.ToString());

try
{
await webSocketClient.ConsumeMessagesAsync(cancellationToken);

await _websocketClientOrganizer.RemoveAgentAsync(agent.Uid, cancellationToken);
}
else
catch (Exception ex)
{
_logger.LogError("Unable to add websocket connection for agent: {agentId}.", agent.Uid);
_logger.LogError(ex, "Websocket connection closed ungracefully.");

await _websocketClientOrganizer.RemoveAgentAsync(agent.Uid, cancellationToken);
await _processorHub.Clients.All.OpenAlprAgentDisconnected(agent.Uid, HttpContext.Connection.RemoteIpAddress.ToString());
}
}
else
{
_logger.LogInformation("non websocket connection received.");
_logger.LogInformation("Non websocket connection received.");
HttpContext.Response.StatusCode = StatusCodes.Status400BadRequest;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,9 @@ export class OpenalprAgentComponent implements OnInit {
key: "Version",
value: this.agentStatus.version,
});
},
(error) => {
this.agentStatus.isConnected = false;
});
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ export class SystemLogsComponent implements OnInit, AfterViewInit, OnDestroy {
this.subscribeForLogs();
})
}

public subscribeForLogs() {
this.subscriptions.add(this.signalRHub.processInformationLogged.subscribe(logInformation => {
this.logMessages.unshift(logInformation);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export class SignalrService {
public licensePlateReceived = new Subject<string>();
public licensePlateAlerted = new Subject<string>();
public processInformationLogged = new Subject<string>();
public openAlprAgentConnected = new Subject<string>();
public isConnected: boolean;
public connectionStatusChanged: Subject<boolean> = new Subject<boolean>();

Expand Down Expand Up @@ -43,6 +44,17 @@ export class SignalrService {
this.processInformationLogged.next(logMessage);
});

this.hubConnection.on('OpenAlprAgentConnected', (agentId, ipAddress) => {
this.snackbarService.create(`OpenALPR Agent Connected: ${agentId}`, SnackBarType.Connected, `IP Address: ${ipAddress}`);
});

this.hubConnection.on('OpenAlprAgentDisconnected', (agentId, ipAddress) => {
this.snackbarService.create(
`OpenALPR Agent Disconnected: ${agentId}`,
SnackBarType.Disconnected,
"IP Address: " + ipAddress);
});

this.hubConnection.on('LicensePlateRecorded', (plateNumber) => {
this.licensePlateReceived.next(plateNumber);
});
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
<div style="display: flex;" class="snack-container">
<div style="margin-right:15px; padding-top:5px;">
<div style="margin-right:15px; padding-top:15px;">
<mat-icon>{{getIcon}}</mat-icon>
</div>
<div style="padding-top:10px;">
<span >{{data.message}}</span>
<div style="display: flex; flex-direction:column;">
<div style="padding-top:10px;">
<span>{{data.message}}</span>
</div>
<div>
<span>{{data.message2}}</span>
</div>
</div>
</div>
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,16 @@ import { SnackBarType } from './snackbartype';
export class SnackbarService {
constructor(private snackBar: MatSnackBar) { }

create(message: string, snackBarType: SnackBarType) {
create(message: string, snackBarType: SnackBarType, message2?: string) {
this.snackBar.openFromComponent(
SnackbarComponent,
{
horizontalPosition: 'right',
verticalPosition: 'bottom',
duration: 1500,
duration: 3000,
data: {
message: message,
message2: message2,
snackType: snackBarType
},
});
Expand Down

0 comments on commit 7150832

Please sign in to comment.