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 _stocks = new ConcurrentDictionary(); private readonly Subject _subject = new Subject(); private readonly TimeSpan _updateInterval = TimeSpan.FromSeconds(10); private Timer _timer; private volatile bool _updatingStock; private SiemensClient client; public StockTicker(IHubContext hub) { Hub = hub; client = new SiemensClient( SiemensVersion.S7_1500, "127.0.0.1", 102 ); LoadDefaultStocks(); } private IHubContext Hub { get; set; } public IEnumerable GetAllStocks() { return _stocks.Values; } public IObservable 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 { 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(); } } } }