signalr test
This commit is contained in:
parent
a87e5e5ff9
commit
d250bca681
@ -5,6 +5,9 @@ using IoTClient.Clients.PLC;
|
||||
using IoTClient.Common.Enums;
|
||||
using IoTClient.Enums;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore.Metadata.Internal;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Query.Expressions.Internal;
|
||||
using NPOI.XSSF.Streaming.Values;
|
||||
using WalkingTec.Mvvm.Core;
|
||||
using WalkingTec.Mvvm.Mvc;
|
||||
|
||||
@ -26,24 +29,30 @@ namespace HHWMS.Web.Controllers
|
||||
[ActionDescription("Sys.Search")]
|
||||
public ActionResult Index()
|
||||
{
|
||||
SiemensClient client = new SiemensClient(SiemensVersion.S7_1500, "127.0.0.1", 102);
|
||||
client.Write("V2209", 33);
|
||||
|
||||
Dictionary<string, DataTypeEnum> addresses = new Dictionary<string, DataTypeEnum>();
|
||||
addresses.Add("DB4.24", DataTypeEnum.Float);
|
||||
addresses.Add("DB1.434.0", DataTypeEnum.Bool);
|
||||
addresses.Add("V4109", DataTypeEnum.Byte);
|
||||
var result = client.BatchRead(addresses);
|
||||
var tt = result.Value.First(x => x.Key.Equals("DB1.434.0")).Value;
|
||||
|
||||
var inv = _unitWork
|
||||
.Find<Inventory>(x => x.TaskStatus != InventoryTaskStatus.任务中)
|
||||
.ToList()
|
||||
.GroupBy(x => x.ContainerCode);
|
||||
var vm = Wtm.CreateVM<ContainerListVM>();
|
||||
return PartialView(vm);
|
||||
}
|
||||
|
||||
#endregion Search
|
||||
|
||||
[HttpPost]
|
||||
public ActionResult Test()
|
||||
{
|
||||
SiemensClient client = new SiemensClient(SiemensVersion.S7_1500, "127.0.0.1", 102);
|
||||
|
||||
// 声明设备列表
|
||||
Dictionary<string, DataTypeEnum> addresses = new Dictionary<string, DataTypeEnum>();
|
||||
addresses.Add("V2207", DataTypeEnum.Float);
|
||||
addresses.Add("V2307", DataTypeEnum.Float);
|
||||
addresses.Add("V2407", DataTypeEnum.Float);
|
||||
var result = client.BatchRead(addresses);
|
||||
if(result.IsSucceed)
|
||||
{
|
||||
var re = result.Value.ToList();
|
||||
return JsonMore(re);
|
||||
}
|
||||
return JsonMore(null);
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,56 +1,106 @@
|
||||
<div id="app">
|
||||
<a-button @@click="handleClick">
|
||||
<template #icon>
|
||||
@* <template #icon>
|
||||
<icon-plus />
|
||||
</template>
|
||||
</template> *@
|
||||
{{ message }}
|
||||
</a-button>
|
||||
{{ result }}
|
||||
|
||||
<a-form :model="form" :style="{ width: '600px' }" @@submit="handleSubmit">
|
||||
<a-form-item field="name" tooltip="Please enter username" label="Username">
|
||||
<a-input v-model="form.name"
|
||||
placeholder="please enter your username..." />
|
||||
</a-form-item>
|
||||
<a-form-item field="post" label="Post">
|
||||
<a-input v-model="form.post" placeholder="please enter your post..." />
|
||||
</a-form-item>
|
||||
<a-form-item field="isRead">
|
||||
<a-checkbox v-model="form.isRead"> I have read the manual </a-checkbox>
|
||||
</a-form-item>
|
||||
<a-form-item>
|
||||
<a-button html-type="submit">Submit</a-button>
|
||||
</a-form-item>
|
||||
</a-form>
|
||||
{{ form }}
|
||||
<a-table :columns="columns" :data="datat" />
|
||||
</div>
|
||||
|
||||
<script src="/front/signalr.min.js"></script>
|
||||
<script>
|
||||
const { createApp } = Vue
|
||||
|
||||
createApp({
|
||||
const { createApp, reactive } = Vue
|
||||
|
||||
const app = createApp({
|
||||
data() {
|
||||
return {
|
||||
message: 'Hello Vue!',
|
||||
form: {
|
||||
name: '',
|
||||
post: '',
|
||||
isRead: false,
|
||||
}
|
||||
result: 'Hello Vue!',
|
||||
columns: [
|
||||
{
|
||||
title: '地址',
|
||||
dataIndex: 'Key',
|
||||
},
|
||||
{
|
||||
title: '值',
|
||||
dataIndex: 'Value',
|
||||
}
|
||||
],
|
||||
datat: reactive([])
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
handleClick() {
|
||||
console.log(1);
|
||||
this.$message.info('This is an info message')
|
||||
var _this = this;
|
||||
axios.post("/configs/Print/Test", {})
|
||||
.then(function (json) {
|
||||
_this.result = json.data.Data;
|
||||
_this.datat = [];
|
||||
_this.result.forEach((item) => {
|
||||
_this.datat.push(item);
|
||||
})
|
||||
|
||||
// _this.datat.forEach((item,index) => {
|
||||
// if (item.Key == "DB4.24") {
|
||||
// _this.datat[index].Value = "3";
|
||||
// }
|
||||
// })
|
||||
})
|
||||
.catch(function (error) {
|
||||
console.log(error);
|
||||
});
|
||||
},
|
||||
handleSubmit(data) {
|
||||
handleSubmit(data) {
|
||||
console.log(data);
|
||||
this.$message.info('This is an info message')
|
||||
}
|
||||
}
|
||||
})
|
||||
.use(ArcoVue)
|
||||
.use(ArcoVueIcon)
|
||||
.mount('#app')
|
||||
});
|
||||
app
|
||||
.use(ArcoVue)
|
||||
.use(ArcoVueIcon)
|
||||
.mount('#app');
|
||||
|
||||
console.log(app._instance.data);
|
||||
|
||||
let connection = new signalR.HubConnectionBuilder()
|
||||
.withAutomaticReconnect()
|
||||
.withUrl("/stocks")
|
||||
.build();
|
||||
connection.start().then(function () {
|
||||
connection.invoke("GetAllStocks").then(function (stocks) {
|
||||
for (let i = 0; i < stocks.length; i++) {
|
||||
app._instance.data.datat.push({ Key: stocks[i].dbName, Value: stocks[i].dbValue });
|
||||
}
|
||||
});
|
||||
|
||||
connection.invoke("GetMarketState").then(function (state) {
|
||||
console.log(state);
|
||||
// if (state === 'Open') {
|
||||
startStreaming();
|
||||
// }
|
||||
});
|
||||
|
||||
connection.invoke("OpenMarket");
|
||||
});
|
||||
|
||||
function startStreaming() {
|
||||
connection.stream("StreamStocks").subscribe({
|
||||
close: false,
|
||||
next: displayStock,
|
||||
error: function (err) {
|
||||
logger.log(err);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function displayStock(stock) {
|
||||
app._instance.data.datat.forEach((item,index) => {
|
||||
if (item.Key == stock.dbName) {
|
||||
app._instance.data.datat[index].Value = stock.dbValue;
|
||||
}
|
||||
})
|
||||
}
|
||||
</script>
|
||||
|
||||
10
HHWMS.Web/Areas/Hub/Stock.cs
Normal file
10
HHWMS.Web/Areas/Hub/Stock.cs
Normal file
@ -0,0 +1,10 @@
|
||||
using System;
|
||||
|
||||
namespace HHWMS.Web
|
||||
{
|
||||
public class Stock
|
||||
{
|
||||
public string DbName { get; set; }
|
||||
public object DbValue { get; set; }
|
||||
}
|
||||
}
|
||||
191
HHWMS.Web/Areas/Hub/StockTicker.cs
Normal file
191
HHWMS.Web/Areas/Hub/StockTicker.cs
Normal file
@ -0,0 +1,191 @@
|
||||
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 _marketStateLock = new SemaphoreSlim(1, 1);
|
||||
private readonly SemaphoreSlim _updateStockPricesLock = new SemaphoreSlim(1, 1);
|
||||
|
||||
private readonly ConcurrentDictionary<string, Stock> _stocks = new ConcurrentDictionary<string, Stock>();
|
||||
|
||||
private readonly Subject<Stock> _subject = new Subject<Stock>();
|
||||
|
||||
// Stock can go up or down by a percentage of this factor on each change
|
||||
private readonly double _rangePercent = 0.002;
|
||||
|
||||
private readonly TimeSpan _updateInterval = TimeSpan.FromSeconds(10);
|
||||
private readonly Random _updateOrNotRandom = new Random();
|
||||
|
||||
private Timer _timer;
|
||||
private volatile bool _updatingStockPrices;
|
||||
private volatile MarketState _marketState;
|
||||
|
||||
public StockTicker(IHubContext<StockTickerHub> hub)
|
||||
{
|
||||
Hub = hub;
|
||||
LoadDefaultStocks();
|
||||
}
|
||||
|
||||
private IHubContext<StockTickerHub> Hub
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
|
||||
public MarketState MarketState
|
||||
{
|
||||
get { return _marketState; }
|
||||
private set { _marketState = value; }
|
||||
}
|
||||
|
||||
public IEnumerable<Stock> GetAllStocks()
|
||||
{
|
||||
return _stocks.Values;
|
||||
}
|
||||
|
||||
public IObservable<Stock> StreamStocks()
|
||||
{
|
||||
return _subject;
|
||||
}
|
||||
|
||||
public async Task OpenMarket()
|
||||
{
|
||||
await _marketStateLock.WaitAsync();
|
||||
try
|
||||
{
|
||||
//if (MarketState != MarketState.Open)
|
||||
//{
|
||||
_timer = new Timer(UpdateStockPrices, null, _updateInterval, _updateInterval);
|
||||
|
||||
MarketState = MarketState.Open;
|
||||
|
||||
await BroadcastMarketStateChange(MarketState.Open);
|
||||
//}
|
||||
}
|
||||
finally
|
||||
{
|
||||
_marketStateLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task CloseMarket()
|
||||
{
|
||||
await _marketStateLock.WaitAsync();
|
||||
try
|
||||
{
|
||||
if (MarketState == MarketState.Open)
|
||||
{
|
||||
if (_timer != null)
|
||||
{
|
||||
_timer.Dispose();
|
||||
}
|
||||
|
||||
MarketState = MarketState.Closed;
|
||||
|
||||
await BroadcastMarketStateChange(MarketState.Closed);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
_marketStateLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task Reset()
|
||||
{
|
||||
await _marketStateLock.WaitAsync();
|
||||
try
|
||||
{
|
||||
if (MarketState != MarketState.Closed)
|
||||
{
|
||||
throw new InvalidOperationException("Market must be closed before it can be reset.");
|
||||
}
|
||||
|
||||
LoadDefaultStocks();
|
||||
await BroadcastMarketReset();
|
||||
}
|
||||
finally
|
||||
{
|
||||
_marketStateLock.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 _updateStockPricesLock.WaitAsync();
|
||||
try
|
||||
{
|
||||
if (!_updatingStockPrices)
|
||||
{
|
||||
_updatingStockPrices = true;
|
||||
|
||||
foreach (var stock in _stocks.Values)
|
||||
{
|
||||
SiemensClient client = new SiemensClient(SiemensVersion.S7_1500, "127.0.0.1", 102);
|
||||
|
||||
stock.DbValue = client.ReadFloat(stock.DbName).Value;
|
||||
|
||||
_subject.OnNext(stock);
|
||||
}
|
||||
|
||||
_updatingStockPrices = false;
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
_updateStockPricesLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task BroadcastMarketStateChange(MarketState marketState)
|
||||
{
|
||||
switch (marketState)
|
||||
{
|
||||
case MarketState.Open:
|
||||
await Hub.Clients.All.SendAsync("marketOpened");
|
||||
break;
|
||||
case MarketState.Closed:
|
||||
await Hub.Clients.All.SendAsync("marketClosed");
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task BroadcastMarketReset()
|
||||
{
|
||||
await Hub.Clients.All.SendAsync("marketReset");
|
||||
}
|
||||
}
|
||||
|
||||
public enum MarketState
|
||||
{
|
||||
Closed,
|
||||
Open
|
||||
}
|
||||
}
|
||||
48
HHWMS.Web/Areas/Hub/StockTickerHub.cs
Normal file
48
HHWMS.Web/Areas/Hub/StockTickerHub.cs
Normal file
@ -0,0 +1,48 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Channels;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNetCore.SignalR;
|
||||
|
||||
namespace HHWMS.Web
|
||||
{
|
||||
public class StockTickerHub : Hub
|
||||
{
|
||||
private readonly StockTicker _stockTicker;
|
||||
|
||||
public StockTickerHub(StockTicker stockTicker)
|
||||
{
|
||||
_stockTicker = stockTicker;
|
||||
}
|
||||
|
||||
public IEnumerable<Stock> GetAllStocks()
|
||||
{
|
||||
return _stockTicker.GetAllStocks();
|
||||
}
|
||||
|
||||
public ChannelReader<Stock> StreamStocks()
|
||||
{
|
||||
return _stockTicker.StreamStocks().AsChannelReader(10);
|
||||
}
|
||||
|
||||
public string GetMarketState()
|
||||
{
|
||||
return _stockTicker.MarketState.ToString();
|
||||
}
|
||||
|
||||
public async Task OpenMarket()
|
||||
{
|
||||
await _stockTicker.OpenMarket();
|
||||
}
|
||||
|
||||
public async Task CloseMarket()
|
||||
{
|
||||
await _stockTicker.CloseMarket();
|
||||
}
|
||||
|
||||
public async Task Reset()
|
||||
{
|
||||
await _stockTicker.Reset();
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,10 +1,8 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using HHWMS.Web.Models;
|
||||
using Quartz;
|
||||
using WalkingTec.Mvvm.Core;
|
||||
using WalkingTec.Mvvm.Core.Extensions;
|
||||
using WalkingTec.Mvvm.Core.Support.Quartz;
|
||||
|
||||
namespace HHWMS.Web
|
||||
@ -19,26 +17,26 @@ namespace HHWMS.Web
|
||||
try
|
||||
{
|
||||
var _unitwork = new UnitWork(Wtm);
|
||||
if (_unitwork.IsExit<ReceiptHeader>(x => x.FirstStatus == ReceiptStatusEnum.收完))
|
||||
{
|
||||
_unitwork.BatchDelete<ReceiptHeader>(x => x.FirstStatus == ReceiptStatusEnum.收完);
|
||||
}
|
||||
|
||||
if (_unitwork.IsExit<ShipmentHeader>(x => x.FirstStatus == ShipStatusEnum.拣货完成))
|
||||
{
|
||||
_unitwork.BatchDelete<ShipmentHeader>(x => x.FirstStatus == ShipStatusEnum.拣货完成);
|
||||
}
|
||||
Wtm.DoLog("清理过期单据", ActionLogTypesEnum.Job, "TestJob");
|
||||
Wtm.DoLog("测试", ActionLogTypesEnum.Job, "TestJob");
|
||||
|
||||
#region 更新时间
|
||||
var job = _unitwork.FindSingle<SysJob>(x => x.JobName == context.JobDetail.Key.Name);
|
||||
var job = _unitwork.FindSingle<SysJob>(x =>
|
||||
x.JobName == context.JobDetail.Key.Name
|
||||
);
|
||||
if (job != null)
|
||||
{
|
||||
job.LastFireTime = TimeZoneInfo.ConvertTimeFromUtc(context.FireTimeUtc.DateTime, TimeZoneInfo.Local);
|
||||
job.LastFireTime = TimeZoneInfo.ConvertTimeFromUtc(
|
||||
context.FireTimeUtc.DateTime,
|
||||
TimeZoneInfo.Local
|
||||
);
|
||||
// 只执行一次 没有下次执行时间
|
||||
if (context.NextFireTimeUtc != null)
|
||||
{
|
||||
job.NextFireTime = TimeZoneInfo.ConvertTimeFromUtc(context.NextFireTimeUtc.Value.DateTime, TimeZoneInfo.Local);
|
||||
job.NextFireTime = TimeZoneInfo.ConvertTimeFromUtc(
|
||||
context.NextFireTimeUtc.Value.DateTime,
|
||||
TimeZoneInfo.Local
|
||||
);
|
||||
}
|
||||
_unitwork.Update<SysJob>(job);
|
||||
}
|
||||
|
||||
@ -34,12 +34,14 @@
|
||||
<PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="12.0.0" />
|
||||
<PackageReference Include="EfCore.SchemaCompare" Version="6.0.0" />
|
||||
<PackageReference Include="IoTClient" Version="1.0.40" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.SignalR.Protocols.MessagePack" Version="6.0.27" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="6.0.11">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="SoapCore" Version="1.1.0.38" />
|
||||
<PackageReference Include="SqlSugarCore" Version="5.1.4.143" />
|
||||
<PackageReference Include="System.Reactive.Linq" Version="6.0.0" />
|
||||
<PackageReference Include="System.ServiceModel.Duplex" Version="4.10.*" />
|
||||
<PackageReference Include="System.ServiceModel.Federation" Version="4.10.*" />
|
||||
<PackageReference Include="System.ServiceModel.Http" Version="4.10.*" />
|
||||
|
||||
@ -59,6 +59,12 @@ builder.Services.AddSoapCore();
|
||||
builder.Services.AddScoped(typeof(IUnitWork), typeof(UnitWork));
|
||||
builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
|
||||
|
||||
builder.Services.AddSignalR()
|
||||
.AddMessagePackProtocol();
|
||||
|
||||
builder.Services.AddSingleton<StockTicker>();
|
||||
|
||||
|
||||
var app = builder.Build();
|
||||
IOptionsMonitor<Configs> config = app.Services.GetRequiredService<IOptionsMonitor<Configs>>();
|
||||
|
||||
@ -90,6 +96,7 @@ app.UseEndpoints(endpoints =>
|
||||
endpoints.MapControllerRoute(
|
||||
name: "default",
|
||||
pattern: "{controller=Home}/{action=Index}/{id?}");
|
||||
endpoints.MapHub<StockTickerHub>("/stocks");
|
||||
});
|
||||
|
||||
app.UseWtmContext();
|
||||
|
||||
32
HHWMS.Web/Support/ObservableExtensions.cs
Normal file
32
HHWMS.Web/Support/ObservableExtensions.cs
Normal file
@ -0,0 +1,32 @@
|
||||
using System;
|
||||
using System.Threading.Channels;
|
||||
|
||||
namespace System
|
||||
{
|
||||
public static class ObservableExtensions
|
||||
{
|
||||
public static ChannelReader<T> AsChannelReader<T>(this IObservable<T> observable, int? maxBufferSize = null)
|
||||
{
|
||||
// This sample shows adapting an observable to a ChannelReader without
|
||||
// back pressure, if the connection is slower than the producer, memory will
|
||||
// start to increase.
|
||||
|
||||
// If the channel is bounded, TryWrite will return false and effectively
|
||||
// drop items.
|
||||
|
||||
// The other alternative is to use a bounded channel, and when the limit is reached
|
||||
// block on WaitToWriteAsync. This will block a thread pool thread and isn't recommended and isn't shown here.
|
||||
var channel = maxBufferSize != null ? Channel.CreateBounded<T>(maxBufferSize.Value) : Channel.CreateUnbounded<T>();
|
||||
|
||||
var disposable = observable.Subscribe(
|
||||
value => channel.Writer.TryWrite(value),
|
||||
error => channel.Writer.TryComplete(error),
|
||||
() => channel.Writer.TryComplete());
|
||||
|
||||
// Complete the subscription on the reader completing
|
||||
channel.Reader.Completion.ContinueWith(task => disposable.Dispose());
|
||||
|
||||
return channel.Reader;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -13,6 +13,7 @@
|
||||
<link rel="stylesheet" href="/font/iconfont.css">
|
||||
<link rel="shortcut icon" href="/favicon.ico" />
|
||||
|
||||
<script src="/axios/axios.min.js"></script>
|
||||
<script src="/front/vue.global.js"></script>
|
||||
<script src="/front/arco-vue.js"></script>
|
||||
<script src="/front/arco-vue-icon.js"></script>
|
||||
|
||||
3422
HHWMS.Web/wwwroot/axios/axios.js
Normal file
3422
HHWMS.Web/wwwroot/axios/axios.js
Normal file
File diff suppressed because it is too large
Load Diff
1
HHWMS.Web/wwwroot/axios/axios.js.map
Normal file
1
HHWMS.Web/wwwroot/axios/axios.js.map
Normal file
File diff suppressed because one or more lines are too long
2
HHWMS.Web/wwwroot/axios/axios.min.js
vendored
Normal file
2
HHWMS.Web/wwwroot/axios/axios.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
1
HHWMS.Web/wwwroot/axios/axios.min.js.map
Normal file
1
HHWMS.Web/wwwroot/axios/axios.min.js.map
Normal file
File diff suppressed because one or more lines are too long
4920
HHWMS.Web/wwwroot/front/signalr.js
Normal file
4920
HHWMS.Web/wwwroot/front/signalr.js
Normal file
File diff suppressed because it is too large
Load Diff
23
HHWMS.Web/wwwroot/front/signalr.min.js
vendored
Normal file
23
HHWMS.Web/wwwroot/front/signalr.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
Loading…
x
Reference in New Issue
Block a user