Skip to content

Commit

Permalink
cache ESP ethernet events until someone listens for them
Browse files Browse the repository at this point in the history
  • Loading branch information
ctacke committed Oct 29, 2024
1 parent 69ecdf0 commit 2195f06
Showing 1 changed file with 46 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using Meadow.Devices.Esp32.MessagePayloads;
using Meadow.Gateways;
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
Expand Down Expand Up @@ -29,9 +30,36 @@ public partial class Esp32Coprocessor : ICoprocessor

internal event EventHandler<(WiFiFunction fn, StatusCodes status, byte[] data)>? WiFiMessageReceived = default!;
internal event EventHandler<(CellFunction fn, StatusCodes status, byte[] data)>? CellMessageReceived = default!;
internal event EventHandler<(EthernetFunction fn, StatusCodes status, byte[] data)>? EthernetMessageReceived = default!;
internal event EventHandler<(SystemFunction fn, StatusCodes status)>? SystemMessageReceived = default!;

private EventHandler<(EthernetFunction fn, StatusCodes status, byte[] data)>? _ethernetMessageHandlers;
private Queue<RawEventData> _queuedEthernetEvents = new();

private record RawEventData
{
public Esp32Interfaces Interface { get; set; }
public uint Function { get; set; }
public uint StatusCode { get; set; }
public byte[]? Payload { get; set; }
}

internal event EventHandler<(EthernetFunction fn, StatusCodes status, byte[] data)>? EthernetMessageReceived
{
add
{
_ethernetMessageHandlers += value;

lock (_queuedEthernetEvents)
{
foreach (var evt in _queuedEthernetEvents)
{
_ethernetMessageHandlers?.Invoke(this, new((EthernetFunction)evt.Function, (StatusCodes)evt.StatusCode, evt.Payload ?? EmptyPayload));
}
_queuedEthernetEvents.Clear();
}
}
remove => _ethernetMessageHandlers -= value;
}

/// <summary>
/// Possible debug levels.
Expand Down Expand Up @@ -274,7 +302,23 @@ private void EventHandlerServiceThread(object o)
switch ((Esp32Interfaces)eventData.Interface)
{
case Esp32Interfaces.WiredEthernet:
EthernetMessageReceived?.Invoke(this, ((EthernetFunction)eventData.Function, (StatusCodes)eventData.StatusCode, payload ?? EmptyPayload));
lock (_queuedEthernetEvents)
{
if (_ethernetMessageHandlers == null)
{
_queuedEthernetEvents.Enqueue(new RawEventData
{
Interface = Esp32Interfaces.WiredEthernet,
Function = eventData.Function,
StatusCode = eventData.StatusCode,
Payload = payload
});
}
else
{
_ethernetMessageHandlers.Invoke(this, ((EthernetFunction)eventData.Function, (StatusCodes)eventData.StatusCode, payload ?? EmptyPayload));
}
}
break;
case Esp32Interfaces.WiFi:
WiFiMessageReceived?.Invoke(this, ((WiFiFunction)eventData.Function, (StatusCodes)eventData.StatusCode, payload ?? EmptyPayload));
Expand Down

0 comments on commit 2195f06

Please sign in to comment.