iotgateway/Plugins/Plugin/DeviceThread.cs

313 lines
15 KiB
C#
Raw Normal View History

using PluginInterface;
2021-12-12 06:55:48 +00:00
using System.Reflection;
2022-08-23 08:29:29 +00:00
using System.Text;
2021-12-12 06:55:48 +00:00
using IoTGateway.DataAccess;
using IoTGateway.Model;
using DynamicExpresso;
using MQTTnet.Server;
using Newtonsoft.Json;
2022-03-24 13:38:11 +00:00
using Microsoft.Extensions.Logging;
2022-08-23 08:29:29 +00:00
using MQTTnet;
2021-12-12 06:55:48 +00:00
namespace Plugin
{
public class DeviceThread : IDisposable
{
2022-03-24 13:38:11 +00:00
private readonly ILogger _logger;
2022-08-10 08:55:44 +00:00
public readonly Device Device;
public readonly IDriver Driver;
private readonly string _projectId;
private readonly MyMqttClient? _myMqttClient;
private Interpreter? _interpreter;
2021-12-12 06:55:48 +00:00
public Dictionary<Guid, DriverReturnValueModel> DeviceValues { get; set; } = new();
2022-08-10 08:55:44 +00:00
internal List<MethodInfo>? Methods { get; set; }
private Task? _task;
private readonly DateTime _tsStartDt = new(1970, 1, 1);
private readonly CancellationTokenSource _tokenSource = new CancellationTokenSource();
private readonly object _lock = new();
public DeviceThread(Device device, IDriver driver, string projectId, MyMqttClient myMqttClient,
2022-08-23 08:29:29 +00:00
MqttServer mqttServer, ILogger logger)
2021-12-12 06:55:48 +00:00
{
2022-04-13 09:01:24 +00:00
_myMqttClient = myMqttClient;
_myMqttClient.OnExcRpc += MyMqttClient_OnExcRpc;
2022-08-10 08:55:44 +00:00
Device = device;
Driver = driver;
_projectId = projectId;
_interpreter = new Interpreter();
2022-03-24 13:38:11 +00:00
_logger = logger;
2022-08-10 08:55:44 +00:00
Methods = Driver.GetType().GetMethods().Where(x => x.GetCustomAttribute(typeof(MethodAttribute)) != null)
.ToList();
if (Device.AutoStart)
2021-12-12 06:55:48 +00:00
{
2022-08-10 08:55:44 +00:00
_logger.LogInformation($"线程已启动:{Device.DeviceName}");
2021-12-12 06:55:48 +00:00
2022-08-10 08:55:44 +00:00
if (Device.DeviceVariables != null)
2021-12-12 06:55:48 +00:00
{
2022-08-10 08:55:44 +00:00
foreach (var item in Device.DeviceVariables)
2021-12-12 06:55:48 +00:00
{
2022-08-10 08:55:44 +00:00
DeviceValues[item.ID] = new() { StatusType = VaribaleStatusTypeEnum.Bad };
2021-12-12 06:55:48 +00:00
}
}
2022-05-09 15:57:46 +00:00
2022-08-10 08:55:44 +00:00
_task = Task.Run(() =>
{
2022-08-25 07:58:29 +00:00
//上传客户端属性
2022-08-10 08:55:44 +00:00
myMqttClient.UploadAttributeAsync(device.DeviceName,
device.DeviceConfigs.Where(x => x.DataSide == DataSide.ClientSide)
.ToDictionary(x => x.DeviceConfigName, x => x.Value));
2022-05-06 07:56:05 +00:00
while (true)
2022-05-09 15:57:46 +00:00
{
2022-08-10 08:55:44 +00:00
if (_tokenSource.IsCancellationRequested)
2022-05-09 15:57:46 +00:00
{
2022-08-10 08:55:44 +00:00
_logger.LogInformation($"停止线程:{Device.DeviceName}");
2022-05-09 15:57:46 +00:00
return;
}
lock (_lock)
{
try
{
2022-08-10 08:55:44 +00:00
Dictionary<string, List<PayLoad>> sendModel = new() { { Device.DeviceName, new() } };
2022-05-09 15:57:46 +00:00
var payLoad = new PayLoad() { Values = new() };
if (driver.IsConnected)
{
2022-08-10 08:55:44 +00:00
if (Device.DeviceVariables != null)
2022-05-09 15:57:46 +00:00
{
2022-08-25 00:59:49 +00:00
foreach (var item in Device.DeviceVariables.OrderBy(x=>x.Index))
2022-05-09 15:57:46 +00:00
{
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
2022-08-10 08:55:44 +00:00
ret = (DriverReturnValueModel)method.Invoke(Driver,
new object[] { ioarg })!;
2022-05-09 15:57:46 +00:00
2022-08-10 08:55:44 +00:00
if (ret.StatusType == VaribaleStatusTypeEnum.Good &&
!string.IsNullOrWhiteSpace(item.Expressions?.Trim()))
2022-05-09 15:57:46 +00:00
{
try
{
2022-08-10 08:55:44 +00:00
ret.CookedValue = _interpreter.Eval(DealMysqlStr(item.Expressions)
2022-08-10 16:07:02 +00:00
.Replace("raw", ret.Value?.ToString()));
2022-05-09 15:57:46 +00:00
}
catch (Exception)
{
ret.StatusType = VaribaleStatusTypeEnum.ExpressionError;
}
}
else
ret.CookedValue = ret.Value;
payLoad.Values[item.Name] = ret.CookedValue;
ret.VarId = item.ID;
//变化了才推送到mqttserver用于前端展示
2022-08-10 08:55:44 +00:00
if (DeviceValues[item.ID].StatusType != ret.StatusType ||
2022-08-10 16:07:02 +00:00
DeviceValues[item.ID].Value?.ToString() != ret.Value?.ToString() ||
DeviceValues[item.ID].CookedValue?.ToString() !=
ret.CookedValue?.ToString())
2022-05-09 15:57:46 +00:00
{
//这是设备变量列表要用的
2022-09-05 07:32:55 +00:00
var msgInternal = new InjectedMqttApplicationMessage(
2022-08-23 08:29:29 +00:00
new MqttApplicationMessage()
{
Topic =
$"internal/v1/gateway/telemetry/{Device.DeviceName}/{item.Name}",
Payload = Encoding.UTF8.GetBytes(
JsonConvert.SerializeObject(ret))
});
2022-09-05 07:32:55 +00:00
mqttServer.InjectApplicationMessage(msgInternal);
2022-05-09 15:57:46 +00:00
//这是在线组态要用的
2022-09-05 07:32:55 +00:00
var msgConfigure = new InjectedMqttApplicationMessage(
2022-08-23 08:29:29 +00:00
new MqttApplicationMessage()
{
Topic =
$"v1/gateway/telemetry/{Device.DeviceName}/{item.Name}",
Payload = Encoding.UTF8.GetBytes(
JsonConvert.SerializeObject(ret.CookedValue))
});
2022-09-05 07:32:55 +00:00
mqttServer.InjectApplicationMessage(msgConfigure);
2022-05-09 15:57:46 +00:00
}
DeviceValues[item.ID] = ret;
}
2022-08-10 08:55:44 +00:00
payLoad.TS = (long)(DateTime.UtcNow - _tsStartDt).TotalMilliseconds;
2022-05-09 15:57:46 +00:00
if (DeviceValues.Any(x => x.Value.Value == null))
{
payLoad.Values = null;
payLoad.DeviceStatus = DeviceStatusTypeEnum.Bad;
}
2022-08-29 07:00:25 +00:00
else if (DeviceValues.Any(x => x.Value.StatusType == VaribaleStatusTypeEnum.Bad))
{
if (driver.IsConnected)
{
driver.Close();
driver.Dispose();
}
_myMqttClient?.DeviceDisconnected(Device);
}
2022-05-09 15:57:46 +00:00
else
{
payLoad.DeviceStatus = DeviceStatusTypeEnum.Good;
2022-08-10 08:55:44 +00:00
sendModel[Device.DeviceName] = new List<PayLoad> { payLoad };
myMqttClient.PublishTelemetryAsync(Device, sendModel);
2022-05-09 15:57:46 +00:00
}
}
}
else
{
2022-08-30 13:54:18 +00:00
_myMqttClient?.DeviceDisconnected(Device);
2022-05-09 15:57:46 +00:00
if (driver.Connect())
2022-08-10 08:55:44 +00:00
_myMqttClient?.DeviceConnected(Device);
2022-05-09 15:57:46 +00:00
}
}
catch (Exception ex)
{
2022-08-10 08:55:44 +00:00
_logger.LogError($"线程循环异常,{Device.DeviceName}", ex);
2022-05-09 15:57:46 +00:00
}
}
2022-08-10 08:55:44 +00:00
Thread.Sleep((int)Driver.MinPeriod);
2022-05-09 15:57:46 +00:00
}
});
2021-12-12 06:55:48 +00:00
}
else
2022-08-10 08:55:44 +00:00
_myMqttClient?.DeviceDisconnected(Device);
2021-12-12 06:55:48 +00:00
}
2022-05-09 15:57:46 +00:00
public void MyMqttClient_OnExcRpc(object? sender, RpcRequest e)
2022-04-13 09:01:24 +00:00
{
2022-08-10 08:55:44 +00:00
if (e.DeviceName == Device.DeviceName)
2022-04-13 09:01:24 +00:00
{
RpcLog rpcLog = new RpcLog()
{
2022-08-10 08:55:44 +00:00
DeviceId = Device.ID,
2022-04-13 09:01:24 +00:00
StartTime = DateTime.Now,
Method = e.Method,
RpcSide = RpcSide.ServerSide,
Params = JsonConvert.SerializeObject(e.Params)
};
2022-08-10 08:55:44 +00:00
_logger.LogInformation($"{Device.DeviceName}收到RPC,{e}");
RpcResponse rpcResponse = new()
{ DeviceName = e.DeviceName, RequestId = e.RequestId, IsSuccess = false };
2022-04-13 09:01:24 +00:00
//执行写入变量RPC
if (e.Method.ToLower() == "write")
{
lock (_lock)
2022-04-13 09:01:24 +00:00
{
2022-08-10 08:55:44 +00:00
bool rpcConnected = false;
//没连接就连接
2022-08-10 08:55:44 +00:00
if (!Driver.IsConnected)
if (Driver.Connect())
rpcConnected = true;
//连接成功就尝试一个一个的写入,注意:目前写入地址和读取地址是相同的对于PLC来说没问题其他的要自己改........
2022-08-10 08:55:44 +00:00
if (Driver.IsConnected)
2022-04-13 09:01:24 +00:00
{
foreach (var para in e.Params)
2022-04-13 09:01:24 +00:00
{
//先查配置项,要用到配置的地址、数据类型、方法(方法最主要是用于区分写入数据的辅助判断比如modbus不同的功能码)
2022-08-10 08:55:44 +00:00
var deviceVariable = Device.DeviceVariables.Where(x => x.Name == para.Key)
.FirstOrDefault();
if (deviceVariable != null)
2022-04-13 09:01:24 +00:00
{
DriverAddressIoArgModel ioArgModel = new()
{
Address = deviceVariable.DeviceAddress,
Value = para.Value,
ValueType = deviceVariable.DataType
};
2022-08-10 08:55:44 +00:00
var writeResponse = Driver
.WriteAsync(e.RequestId, deviceVariable.Method, ioArgModel).Result;
rpcResponse.IsSuccess = writeResponse.IsSuccess;
if (!writeResponse.IsSuccess)
{
rpcResponse.Description = writeResponse.Description;
2022-08-23 08:29:29 +00:00
continue;
}
}
else
2022-04-13 09:01:24 +00:00
{
rpcResponse.IsSuccess = false;
rpcResponse.Description = $"未能找到变量:{para.Key}";
2022-04-13 09:01:24 +00:00
break;
}
}
2022-08-10 08:55:44 +00:00
if (rpcConnected)
Driver.Close();
}
2022-08-10 08:55:44 +00:00
else //连接失败
{
rpcResponse.IsSuccess = false;
rpcResponse.Description = $"{e.DeviceName} 连接失败";
}
2022-04-13 09:01:24 +00:00
}
}
//其他RPC TODO
else
{
rpcResponse.IsSuccess = false;
rpcResponse.Description = $"方法:{e.Method}暂未实现";
}
//反馈RPC
2022-08-10 08:55:44 +00:00
_myMqttClient.ResponseRpcAsync(rpcResponse);
2022-04-13 09:01:24 +00:00
//纪录入库
rpcLog.IsSuccess = rpcResponse.IsSuccess;
rpcLog.Description = rpcResponse.Description;
rpcLog.EndTime = DateTime.Now;
2022-04-13 09:01:24 +00:00
2022-08-10 08:55:44 +00:00
using (var dc = new DataContext(IoTBackgroundService.connnectSetting, IoTBackgroundService.DbType))
2022-04-13 09:01:24 +00:00
{
2022-08-10 08:55:44 +00:00
dc.Set<RpcLog>().Add(rpcLog);
dc.SaveChanges();
2022-04-13 09:01:24 +00:00
}
}
}
2021-12-12 06:55:48 +00:00
public void StopThread()
{
2022-08-10 08:55:44 +00:00
_logger.LogInformation($"线程停止:{Device.DeviceName}");
_myMqttClient?.DeviceDisconnected(Device);
if (_task != null)
2021-12-12 06:55:48 +00:00
{
2022-08-10 08:55:44 +00:00
if (_myMqttClient != null) _myMqttClient.OnExcRpc -= MyMqttClient_OnExcRpc;
_tokenSource.Cancel();
Driver.Close();
2021-12-12 06:55:48 +00:00
}
}
public void Dispose()
{
2022-08-10 08:55:44 +00:00
Driver.Dispose();
_interpreter = null;
DeviceValues = null;
Methods = null;
2022-08-10 08:55:44 +00:00
_logger.LogInformation($"线程释放,{Device.DeviceName}");
2021-12-12 06:55:48 +00:00
}
//mysql会把一些符号转义没找到原因先临时处理下
2022-08-10 08:55:44 +00:00
private string DealMysqlStr(string expression)
{
2022-08-10 08:55:44 +00:00
return expression.Replace("&lt;", "<").Replace("&gt;", ">").Replace("&amp;", "&").Replace("&quot;", "\"");
}
2021-12-12 06:55:48 +00:00
}
2022-08-10 08:55:44 +00:00
}