PointSource.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. using NModbus.Device;
  2. using NModbus.Unme.Common;
  3. using System;
  4. using System.Diagnostics.CodeAnalysis;
  5. using System.Linq;
  6. namespace NModbus.Data
  7. {
  8. /// <summary>
  9. /// A simple implementation of the point source. Memory for all points is allocated the first time a point is accessed.
  10. /// This is useful for cases where many points are used.
  11. /// </summary>
  12. /// <typeparam name="T"></typeparam>
  13. public class PointSource<T> : IPointSource<T> where T : struct
  14. {
  15. public event EventHandler<PointEventArgs> BeforeRead;
  16. public event EventHandler<PointEventArgs<T>> BeforeWrite;
  17. public event EventHandler<PointEventArgs> AfterWrite;
  18. //Only create this if referenced.
  19. private readonly Lazy<T[]> _points;
  20. private readonly object _syncRoot = new object();
  21. private const int NumberOfPoints = ushort.MaxValue + 1;
  22. public PointSource()
  23. {
  24. _points = new Lazy<T[]>(() => new T[NumberOfPoints]);
  25. }
  26. public T[] ReadPoints(ushort startAddress, ushort numberOfPoints)
  27. {
  28. lock (_syncRoot)
  29. {
  30. return _points.Value
  31. .Slice(startAddress, numberOfPoints)
  32. .ToArray();
  33. }
  34. }
  35. T[] IPointSource<T>.ReadPoints(ushort startAddress, ushort numberOfPoints)
  36. {
  37. BeforeRead?.Invoke(this, new PointEventArgs(startAddress, numberOfPoints));
  38. return ReadPoints(startAddress, numberOfPoints);
  39. }
  40. public void WritePoints(ushort startAddress, T[] points)
  41. {
  42. lock (_syncRoot)
  43. {
  44. for (ushort index = 0; index < points.Length; index++)
  45. {
  46. _points.Value[startAddress + index] = points[index];
  47. }
  48. }
  49. }
  50. void IPointSource<T>.WritePoints(ushort startAddress, T[] points)
  51. {
  52. BeforeWrite?.Invoke(this, new PointEventArgs<T>(startAddress, points));
  53. WritePoints(startAddress, points);
  54. AfterWrite?.Invoke(this, new PointEventArgs(startAddress, (ushort)points.Length));
  55. }
  56. }
  57. }