从前端调用rpc修改变量值

This commit is contained in:
iioter 2022-05-09 23:57:46 +08:00
parent 21dfb6f737
commit 9fede82d4e
14 changed files with 249 additions and 110 deletions

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -20,7 +20,7 @@ namespace IoTGateway.ViewModel.BasicData.DeviceVMs
{
try
{
var device = DC.Set<Device>().Where(x => x.ID == Guid.Parse(FC["id"].ToString())).Include(x => x.Parent).Include(x=>x.DeviceConfigs).Include(x => x.Driver).FirstOrDefault();
var device = DC.Set<Device>().Where(x => x.ID == Guid.Parse(FC["id"].ToString())).Include(x => x.Parent).Include(x => x.DeviceVariables).Include(x => x.DeviceConfigs).Include(x => x.Driver).FirstOrDefault();
if (device == null)
= "复制失败,找不到设备";

View File

@ -46,7 +46,8 @@ namespace IoTGateway.ViewModel.BasicData.DeviceVMs
if(a.DeviceTypeEnum== DeviceTypeEnum.Device)
return "true";
return "false";
}),this.MakeGridHeader(x=>"attribute").SetHide().SetFormat((a,b)=>{
}),
this.MakeGridHeader(x=>"attribute").SetHide().SetFormat((a,b)=>{
if(a.DeviceTypeEnum== DeviceTypeEnum.Device)
return "true";
return "false";

View File

@ -21,6 +21,7 @@ namespace IoTGateway.ViewModel.BasicData.DeviceVariableVMs
{
return new List<GridAction>
{
this.MakeAction("DeviceVariable","SetValue","写入值","写入值", GridActionParameterTypesEnum.SingleId,"BasicData",600).SetIconCls("_wtmicon _wtmicon-xiayibu").SetHideOnToolBar(false).SetShowInRow(false).SetBindVisiableColName("setValue"),
this.MakeStandardAction("DeviceVariable", GridActionStandardTypesEnum.Create, Localizer["Sys.Create"],"BasicData", dialogWidth: 800),
this.MakeStandardAction("DeviceVariable", GridActionStandardTypesEnum.Edit, Localizer["Sys.Edit"], "BasicData", dialogWidth: 800),
this.MakeStandardAction("DeviceVariable", GridActionStandardTypesEnum.Delete, Localizer["Sys.Delete"], "BasicData", dialogWidth: 800),
@ -79,6 +80,11 @@ namespace IoTGateway.ViewModel.BasicData.DeviceVariableVMs
this.MakeGridHeader(x=> "detail").SetHide().SetFormat((a,b)=>{
return "false";
}),
this.MakeGridHeader(x=>"setValue").SetHide().SetFormat((a,b)=>{
if(a.Device.AutoStart== true)
return "true";
return "false";
}),
this.MakeGridHeaderAction(width: 115)
};
}
@ -103,7 +109,7 @@ namespace IoTGateway.ViewModel.BasicData.DeviceVariableVMs
if (Searcher.DeviceId != null)
IoTBackgroundService.VariableSelectDeviceId = Searcher.DeviceId;
var query = DC.Set<DeviceVariable>()
var query = DC.Set<DeviceVariable>().Include(x => x.Device)
.CheckContain(Searcher.Name, x => x.Name)
.CheckContain(Searcher.Method, x => x.Method)
.CheckContain(Searcher.DeviceAddress, x => x.DeviceAddress)
@ -121,6 +127,7 @@ namespace IoTGateway.ViewModel.BasicData.DeviceVariableVMs
Expressions = x.Expressions,
ProtectType = x.ProtectType,
DeviceName_view = x.Device.DeviceName,
Device = x.Device
})
.OrderBy(x => x.DeviceName_view).ThenBy(x => x.DeviceAddress);
return query;

View File

@ -28,20 +28,23 @@ namespace IoTGateway.ViewModel.BasicData.DeviceVariableVMs
.OrderBy(x => x.Parent.Index).ThenBy(x => x.Parent.DeviceName)
.OrderBy(x => x.Index).ThenBy(x => x.DeviceName)
.GetSelectListItems(Wtm, y => y.DeviceName);
var deviceService = Wtm.ServiceProvider.GetService(typeof(DeviceService)) as DeviceService;
if (Entity.DeviceId != null)
{
var deviceService = Wtm.ServiceProvider.GetService(typeof(DeviceService)) as DeviceService;
AllMethods = deviceService.GetDriverMethods(Entity.DeviceId);
var DapThread = deviceService.DeviceThreads.Where(x => x._device.ID == Entity.DeviceId).FirstOrDefault();
}
else if (IoTBackgroundService.ConfigSelectDeviceId != null)
else if (IoTBackgroundService.VariableSelectDeviceId != null)
{
Entity.DeviceId = IoTBackgroundService.ConfigSelectDeviceId;
Entity.DeviceId = IoTBackgroundService.VariableSelectDeviceId;
AllMethods = deviceService.GetDriverMethods(Entity.DeviceId);
}
if (AllMethods.Count() > 0)
AllMethods[0].Selected = true;
}
public override void DoAdd()
{
{
base.DoAdd();
UpdateVaribale();
}
@ -55,9 +58,9 @@ namespace IoTGateway.ViewModel.BasicData.DeviceVariableVMs
public override void DoDelete()
{
//先获取id
var id= UpdateDevices.FC2Guids(FC);
var deviceId = DC.Set<DeviceVariable>().Where(x => id.Contains(x.ID)).Select(x=>x.DeviceId).FirstOrDefault();
FC["Entity.DeviceId"] =(StringValues)deviceId.ToString();
var id = UpdateDevices.FC2Guids(FC);
var deviceId = DC.Set<DeviceVariable>().Where(x => id.Contains(x.ID)).Select(x => x.DeviceId).FirstOrDefault();
FC["Entity.DeviceId"] = (StringValues)deviceId.ToString();
base.DoDelete();
UpdateVaribale();
}

View File

@ -0,0 +1,86 @@
using Microsoft.EntityFrameworkCore;
using Plugin;
using System;
using System.Collections.Generic;
using System.Linq;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Core.Extensions;
using IoTGateway.Model;
using System.ComponentModel.DataAnnotations;
namespace IoTGateway.ViewModel.BasicData.DeviceVariableVMs
{
public class SetValueVM : BaseVM
{
public string { get; set; }
public string { get; set; }
public string { get; set; }
public string { get; set; }
public string { get; set; }
public string { get; set; }
public string { get; set; }
public string { get; set; }
public void Set()
{
try
{
var variable = DC.Set<DeviceVariable>().Where(x => x.ID == Guid.Parse(FC["id"].ToString())).AsNoTracking().Include(x => x.Device).FirstOrDefault();
= variable.Device.DeviceName;
= variable.Name;
= variable.DataType.GetEnumDisplayName();
var deviceService = Wtm.ServiceProvider.GetService(typeof(DeviceService)) as DeviceService;
var dapThread = deviceService.DeviceThreads.Where(x => x._device.ID == variable.DeviceId).FirstOrDefault();
if (dapThread?.DeviceValues != null && dapThread.DeviceValues.ContainsKey(variable.ID))
{
= dapThread.DeviceValues[variable.ID].Value?.ToString();
= dapThread.DeviceValues[variable.ID].CookedValue?.ToString();
= dapThread.DeviceValues[variable.ID].StatusType.ToString();
}
if (variable == null || variable.Device == null || dapThread == null)
= "设置失败,找不到设备(变量)";
else
{
PluginInterface.RpcRequest request = new PluginInterface.RpcRequest()
{
RequestId = Guid.NewGuid().ToString(),
DeviceName = variable.Device.DeviceName,
Method = "write",
Params = new Dictionary<string, object>() { { variable.Name, } }
};
dapThread.MyMqttClient_OnExcRpc(this, request);
= "设置成功";
}
}
catch (Exception ex)
{
= $"设置失败,{ex}";
}
}
protected override void InitVM()
{
var variable = DC.Set<DeviceVariable>().Where(x => x.ID == Guid.Parse(FC["id"].ToString())).AsNoTracking().Include(x => x.Device).FirstOrDefault();
= variable.Device.DeviceName;
= variable.Name;
= variable.DataType.GetEnumDisplayName();
var deviceService = Wtm.ServiceProvider.GetService(typeof(DeviceService)) as DeviceService;
var dapThread = deviceService.DeviceThreads.Where(x => x._device.ID == variable.DeviceId).FirstOrDefault();
if (dapThread?.DeviceValues != null && dapThread.DeviceValues.ContainsKey(variable.ID))
{
= dapThread.DeviceValues[variable.ID].Value?.ToString();
= dapThread.DeviceValues[variable.ID].CookedValue?.ToString();
= dapThread.DeviceValues[variable.ID].StatusType.ToString();
}
base.InitVM();
}
}
}

View File

@ -214,6 +214,28 @@ namespace IoTGateway.Controllers
{
return vm.GetExportData();
}
#region
[ActionDescription("下发写入")]
public ActionResult SetValue()
{
var vm = Wtm.CreateVM<SetValueVM>();
return PartialView(vm);
}
[HttpPost]
[ActionDescription("下发写入")]
public ActionResult SetValue(SetValueVM vm)
{
if (!ModelState.IsValid)
{
return PartialView(vm);
}
else
{
vm.Set();
return FFResult().CloseDialog().RefreshGrid().Alert($"{vm.设置结果}");
}
}
#endregion
}
}

View File

@ -0,0 +1,17 @@
@model IoTGateway.ViewModel.BasicData.DeviceVariableVMs.SetValueVM
@inject IStringLocalizer<Program> Localizer;
<wt:form vm="@Model">
<wt:row items-per-row="ItemsPerRowEnum.One">
<wt:quote>@Model.设备名/@Model.变量名</wt:quote>
<wt:quote>当前原始值:@Model.当前原始值======>当前计算值:@Model.当前计算值</wt:quote>
<wt:quote>类型:@Model.类型======状态:@Model.状态</wt:quote>
<wt:textbox field=设定原始值 />
</wt:row>
<wt:row align="AlignEnum.Right">
<wt:submitbutton text="下发" />
<wt:closebutton text="取消" />
</wt:row>
</wt:form>

Binary file not shown.

View File

@ -46,123 +46,123 @@ namespace Plugin
}
}
}
task = Task.Run(() =>
{
Thread.Sleep(5000);//上传客户端属性
myMqttClient.UploadAttributeAsync(device.DeviceName, device.DeviceConfigs.Where(x => x.DataSide == DataSide.ClientSide).ToDictionary(x => x.DeviceConfigName, x => x.Value));
while (true)
{
if (tokenSource.IsCancellationRequested)
{
_logger.LogInformation($"停止线程:{_device.DeviceName}");
return;
}
{
if (tokenSource.IsCancellationRequested)
{
_logger.LogInformation($"停止线程:{_device.DeviceName}");
return;
}
lock (_lock)
{
try
{
Dictionary<string, List<PayLoad>> sendModel = new() { { _device.DeviceName, new() } };
lock (_lock)
{
try
{
Dictionary<string, List<PayLoad>> sendModel = new() { { _device.DeviceName, new() } };
var payLoad = new PayLoad() { Values = new() };
var payLoad = new PayLoad() { Values = new() };
if (driver.IsConnected)
{
if (_device.DeviceVariables != null)
{
foreach (var item in _device.DeviceVariables)
{
var ret = new DriverReturnValueModel();
var ioarg = new DriverAddressIoArgModel
{
ID = item.ID,
Address = item.DeviceAddress,
ValueType = item.DataType
};
var method = Methods.Where(x => x.Name == item.Method).FirstOrDefault();
if (method == null)
ret.StatusType = VaribaleStatusTypeEnum.MethodError;
else
ret = (DriverReturnValueModel)method.Invoke(_driver, new object[1] { ioarg });
if (driver.IsConnected)
{
if (_device.DeviceVariables != null)
{
foreach (var item in _device.DeviceVariables)
{
var ret = new DriverReturnValueModel();
var ioarg = new DriverAddressIoArgModel
{
ID = item.ID,
Address = item.DeviceAddress,
ValueType = item.DataType
};
var method = Methods.Where(x => x.Name == item.Method).FirstOrDefault();
if (method == null)
ret.StatusType = VaribaleStatusTypeEnum.MethodError;
else
ret = (DriverReturnValueModel)method.Invoke(_driver, new object[1] { ioarg });
if (ret.StatusType == VaribaleStatusTypeEnum.Good && !string.IsNullOrWhiteSpace(item.Expressions?.Trim()))
{
try
{
ret.CookedValue = interpreter.Eval(DealMysqlStr(item.Expressions).Replace("raw", ret.Value?.ToString()));
}
catch (Exception)
{
ret.StatusType = VaribaleStatusTypeEnum.ExpressionError;
}
}
else
ret.CookedValue = ret.Value;
if (ret.StatusType == VaribaleStatusTypeEnum.Good && !string.IsNullOrWhiteSpace(item.Expressions?.Trim()))
{
try
{
ret.CookedValue = interpreter.Eval(DealMysqlStr(item.Expressions).Replace("raw", ret.Value?.ToString()));
}
catch (Exception)
{
ret.StatusType = VaribaleStatusTypeEnum.ExpressionError;
}
}
else
ret.CookedValue = ret.Value;
payLoad.Values[item.Name] = ret.CookedValue;
payLoad.Values[item.Name] = ret.CookedValue;
ret.VarId = item.ID;
ret.VarId = item.ID;
//变化了才推送到mqttserver用于前端展示
if (DeviceValues[item.ID].StatusType != ret.StatusType || DeviceValues[item.ID].Value?.ToString() != ret.Value?.ToString() || DeviceValues[item.ID].CookedValue?.ToString() != ret.CookedValue?.ToString())
{
//这是设备变量列表要用的
mqttServer.PublishAsync($"internal/v1/gateway/telemetry/{_device.DeviceName}/{item.Name}", JsonConvert.SerializeObject(ret));
//这是在线组态要用的
mqttServer.PublishAsync($"v1/gateway/telemetry/{_device.DeviceName}/{item.Name}", JsonConvert.SerializeObject(ret.CookedValue));
}
//变化了才推送到mqttserver用于前端展示
if (DeviceValues[item.ID].StatusType != ret.StatusType || DeviceValues[item.ID].Value?.ToString() != ret.Value?.ToString() || DeviceValues[item.ID].CookedValue?.ToString() != ret.CookedValue?.ToString())
{
//这是设备变量列表要用的
mqttServer.PublishAsync($"internal/v1/gateway/telemetry/{_device.DeviceName}/{item.Name}", JsonConvert.SerializeObject(ret));
//这是在线组态要用的
mqttServer.PublishAsync($"v1/gateway/telemetry/{_device.DeviceName}/{item.Name}", JsonConvert.SerializeObject(ret.CookedValue));
}
DeviceValues[item.ID] = ret;
DeviceValues[item.ID] = ret;
}
payLoad.TS = (long)(DateTime.UtcNow - TsStartDt).TotalMilliseconds;
}
payLoad.TS = (long)(DateTime.UtcNow - TsStartDt).TotalMilliseconds;
if (DeviceValues.Any(x => x.Value.Value == null))
{
payLoad.Values = null;
payLoad.DeviceStatus = DeviceStatusTypeEnum.Bad;
}
else
{
payLoad.DeviceStatus = DeviceStatusTypeEnum.Good;
sendModel[_device.DeviceName] = new List<PayLoad> { payLoad };
myMqttClient.PublishTelemetry(_device, sendModel);
}
}
if (DeviceValues.Any(x => x.Value.Value == null))
{
payLoad.Values = null;
payLoad.DeviceStatus = DeviceStatusTypeEnum.Bad;
}
else
{
payLoad.DeviceStatus = DeviceStatusTypeEnum.Good;
sendModel[_device.DeviceName] = new List<PayLoad> { payLoad };
myMqttClient.PublishTelemetry(_device, sendModel);
}
}
}
else
{
if (driver.Connect())
{
lastConnected = true;
_myMqttClient.DeviceConnected(_device.DeviceName);
}
else if (lastConnected)
{
lastConnected = false;
_myMqttClient.DeviceDisconnected(_device.DeviceName);
}
}
}
catch (Exception ex)
{
_logger.LogError($"线程循环异常,{_device.DeviceName}", ex);
}
}
}
else
{
if (driver.Connect())
{
lastConnected = true;
_myMqttClient.DeviceConnected(_device.DeviceName);
}
else if (lastConnected)
{
lastConnected = false;
_myMqttClient.DeviceDisconnected(_device.DeviceName);
}
}
}
catch (Exception ex)
{
_logger.LogError($"线程循环异常,{_device.DeviceName}", ex);
}
}
Thread.Sleep((int)_driver.MinPeriod);
}
});
Thread.Sleep((int)_driver.MinPeriod);
}
});
}
else
_myMqttClient.DeviceDisconnected(_device.DeviceName);
}
private void MyMqttClient_OnExcRpc(object? sender, RpcRequest e)
public void MyMqttClient_OnExcRpc(object? sender, RpcRequest e)
{
if (e.DeviceName == _device.DeviceName)
{

View File

@ -178,13 +178,16 @@ namespace Plugin
try
{
tBRpcRequest = JsonConvert.DeserializeObject<TBRpcRequest>(e.ApplicationMessage.ConvertPayloadToString());
OnExcRpc?.Invoke(Client, new RpcRequest()
if(!string.IsNullOrWhiteSpace(tBRpcRequest.RequestData.Method))
{
Method = tBRpcRequest.RequestData.Method,
DeviceName = tBRpcRequest.DeviceName,
RequestId = tBRpcRequest.RequestData.RequestId,
Params = tBRpcRequest.RequestData.Params
});
OnExcRpc?.Invoke(Client, new RpcRequest()
{
Method = tBRpcRequest.RequestData.Method,
DeviceName = tBRpcRequest.DeviceName,
RequestId = tBRpcRequest.RequestData.RequestId,
Params = tBRpcRequest.RequestData.Params
});
}
}
catch (Exception ex)
{