106 lines
2.9 KiB
C#
106 lines
2.9 KiB
C#
using System;
|
|
using System.Collections.Concurrent;
|
|
using System.Collections.Generic;
|
|
using System.Reactive.Linq;
|
|
using System.Reactive.Subjects;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
using IoTClient.Clients.PLC;
|
|
using IoTClient.Common.Enums;
|
|
using IoTClient.Enums;
|
|
using Microsoft.AspNetCore.SignalR;
|
|
|
|
namespace HHWMS.Web
|
|
{
|
|
public class StockTicker
|
|
{
|
|
private readonly SemaphoreSlim _stateLock = new SemaphoreSlim(1, 1);
|
|
private readonly SemaphoreSlim _updateLock = new SemaphoreSlim(1, 1);
|
|
|
|
private readonly ConcurrentDictionary<string, Stock> _stocks =
|
|
new ConcurrentDictionary<string, Stock>();
|
|
|
|
private readonly Subject<Stock> _subject = new Subject<Stock>();
|
|
|
|
private readonly TimeSpan _updateInterval = TimeSpan.FromSeconds(10);
|
|
|
|
private Timer _timer;
|
|
private volatile bool _updatingStock;
|
|
private SiemensClient client;
|
|
|
|
public StockTicker(IHubContext<StockTickerHub> hub)
|
|
{
|
|
Hub = hub;
|
|
client = new SiemensClient(
|
|
SiemensVersion.S7_1500,
|
|
"127.0.0.1",
|
|
102
|
|
);
|
|
LoadDefaultStocks();
|
|
}
|
|
|
|
private IHubContext<StockTickerHub> Hub { get; set; }
|
|
|
|
public IEnumerable<Stock> GetAllStocks()
|
|
{
|
|
return _stocks.Values;
|
|
}
|
|
|
|
public IObservable<Stock> StreamStocks()
|
|
{
|
|
return _subject;
|
|
}
|
|
|
|
public async Task OpenMarket()
|
|
{
|
|
await _stateLock.WaitAsync();
|
|
try
|
|
{
|
|
_timer = new Timer(UpdateStockPrices, null, _updateInterval, _updateInterval);
|
|
}
|
|
finally
|
|
{
|
|
_stateLock.Release();
|
|
}
|
|
}
|
|
|
|
private void LoadDefaultStocks()
|
|
{
|
|
_stocks.Clear();
|
|
|
|
var stocks = new List<Stock>
|
|
{
|
|
new Stock { DbName = "V2207", DbValue = 1.0 },
|
|
new Stock { DbName = "V2307", DbValue = 2.0 },
|
|
new Stock { DbName = "V2407", DbValue = 3.0 }
|
|
};
|
|
stocks.ForEach(stock => _stocks.TryAdd(stock.DbName, stock));
|
|
}
|
|
|
|
private async void UpdateStockPrices(object state)
|
|
{
|
|
// This function must be re-entrant as it's running as a timer interval handler
|
|
await _updateLock.WaitAsync();
|
|
try
|
|
{
|
|
if (!_updatingStock)
|
|
{
|
|
_updatingStock = true;
|
|
|
|
foreach (var stock in _stocks.Values)
|
|
{
|
|
stock.DbValue = client.ReadFloat(stock.DbName).Value;
|
|
|
|
_subject.OnNext(stock);
|
|
}
|
|
_updatingStock = false;
|
|
}
|
|
}
|
|
finally
|
|
{
|
|
_updateLock.Release();
|
|
}
|
|
}
|
|
}
|
|
}
|