支持华为Roma平台

This commit is contained in:
iioter 2022-08-10 16:55:44 +08:00
parent 0c3d187405
commit 858ce94bbb
28 changed files with 3129 additions and 1161 deletions

View File

@ -0,0 +1,856 @@
// <auto-generated />
using System;
using IoTGateway.DataAccess;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace IoTGateway.DataAccess.Migrations
{
[DbContext(typeof(DataContext))]
[Migration("20220810063014_mqttClientId")]
partial class mqttClientId
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "6.0.1");
modelBuilder.Entity("IoTGateway.Model.Device", b =>
{
b.Property<Guid>("ID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<bool>("AutoStart")
.HasColumnType("INTEGER");
b.Property<bool>("CgUpload")
.HasColumnType("INTEGER");
b.Property<string>("CreateBy")
.HasColumnType("TEXT");
b.Property<DateTime?>("CreateTime")
.HasColumnType("TEXT");
b.Property<string>("Description")
.HasColumnType("TEXT");
b.Property<string>("DeviceName")
.HasColumnType("TEXT");
b.Property<int>("DeviceTypeEnum")
.HasColumnType("INTEGER");
b.Property<Guid?>("DriverId")
.HasColumnType("TEXT");
b.Property<uint>("EnforcePeriod")
.HasColumnType("INTEGER");
b.Property<uint>("Index")
.HasColumnType("INTEGER");
b.Property<Guid?>("ParentId")
.HasColumnType("TEXT");
b.Property<string>("UpdateBy")
.HasColumnType("TEXT");
b.Property<DateTime?>("UpdateTime")
.HasColumnType("TEXT");
b.HasKey("ID");
b.HasIndex("DriverId");
b.HasIndex("ParentId");
b.ToTable("Devices");
});
modelBuilder.Entity("IoTGateway.Model.DeviceConfig", b =>
{
b.Property<Guid>("ID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("CreateBy")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<DateTime?>("CreateTime")
.HasColumnType("TEXT");
b.Property<int>("DataSide")
.HasColumnType("INTEGER");
b.Property<string>("Description")
.HasColumnType("TEXT");
b.Property<string>("DeviceConfigName")
.HasColumnType("TEXT");
b.Property<Guid?>("DeviceId")
.HasColumnType("TEXT");
b.Property<string>("EnumInfo")
.HasColumnType("TEXT");
b.Property<string>("UpdateBy")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<DateTime?>("UpdateTime")
.HasColumnType("TEXT");
b.Property<string>("Value")
.HasColumnType("TEXT");
b.HasKey("ID");
b.HasIndex("DeviceId");
b.ToTable("DeviceConfigs");
});
modelBuilder.Entity("IoTGateway.Model.DeviceVariable", b =>
{
b.Property<Guid>("ID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<int>("DataType")
.HasColumnType("INTEGER");
b.Property<string>("Description")
.HasColumnType("TEXT");
b.Property<string>("DeviceAddress")
.HasColumnType("TEXT");
b.Property<Guid?>("DeviceId")
.HasColumnType("TEXT");
b.Property<string>("Expressions")
.HasColumnType("TEXT");
b.Property<string>("Method")
.HasColumnType("TEXT");
b.Property<string>("Name")
.HasColumnType("TEXT");
b.Property<int>("ProtectType")
.HasColumnType("INTEGER");
b.HasKey("ID");
b.HasIndex("DeviceId");
b.ToTable("DeviceVariables");
});
modelBuilder.Entity("IoTGateway.Model.Driver", b =>
{
b.Property<Guid>("ID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("AssembleName")
.HasColumnType("TEXT");
b.Property<int>("AuthorizesNum")
.HasColumnType("INTEGER");
b.Property<string>("CreateBy")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<DateTime?>("CreateTime")
.HasColumnType("TEXT");
b.Property<string>("DriverName")
.HasColumnType("TEXT");
b.Property<string>("FileName")
.HasColumnType("TEXT");
b.Property<string>("UpdateBy")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<DateTime?>("UpdateTime")
.HasColumnType("TEXT");
b.HasKey("ID");
b.ToTable("Drivers");
});
modelBuilder.Entity("IoTGateway.Model.RpcLog", b =>
{
b.Property<Guid>("ID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("Description")
.HasColumnType("TEXT");
b.Property<Guid?>("DeviceId")
.HasColumnType("TEXT");
b.Property<DateTime>("EndTime")
.HasColumnType("TEXT");
b.Property<bool>("IsSuccess")
.HasColumnType("INTEGER");
b.Property<string>("Method")
.HasColumnType("TEXT");
b.Property<string>("Params")
.HasColumnType("TEXT");
b.Property<int>("RpcSide")
.HasColumnType("INTEGER");
b.Property<DateTime>("StartTime")
.HasColumnType("TEXT");
b.HasKey("ID");
b.HasIndex("DeviceId");
b.ToTable("RpcLogs");
});
modelBuilder.Entity("IoTGateway.Model.SystemConfig", b =>
{
b.Property<Guid>("ID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("ClientId")
.HasColumnType("TEXT");
b.Property<string>("CreateBy")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<DateTime?>("CreateTime")
.HasColumnType("TEXT");
b.Property<string>("GatewayName")
.HasColumnType("TEXT");
b.Property<int>("IoTPlatformType")
.HasColumnType("INTEGER");
b.Property<string>("MqttIp")
.HasColumnType("TEXT");
b.Property<int>("MqttPort")
.HasColumnType("INTEGER");
b.Property<string>("MqttUName")
.HasColumnType("TEXT");
b.Property<string>("MqttUPwd")
.HasColumnType("TEXT");
b.Property<string>("UpdateBy")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<DateTime?>("UpdateTime")
.HasColumnType("TEXT");
b.HasKey("ID");
b.ToTable("SystemConfig");
});
modelBuilder.Entity("WalkingTec.Mvvm.Core.ActionLog", b =>
{
b.Property<Guid>("ID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("ActionName")
.HasMaxLength(255)
.HasColumnType("TEXT");
b.Property<DateTime>("ActionTime")
.HasColumnType("TEXT");
b.Property<string>("ActionUrl")
.HasMaxLength(250)
.HasColumnType("TEXT");
b.Property<string>("CreateBy")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<DateTime?>("CreateTime")
.HasColumnType("TEXT");
b.Property<double>("Duration")
.HasColumnType("REAL");
b.Property<string>("IP")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<string>("ITCode")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<int>("LogType")
.HasColumnType("INTEGER");
b.Property<string>("ModuleName")
.HasMaxLength(255)
.HasColumnType("TEXT");
b.Property<string>("Remark")
.HasColumnType("TEXT");
b.Property<string>("UpdateBy")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<DateTime?>("UpdateTime")
.HasColumnType("TEXT");
b.HasKey("ID");
b.ToTable("ActionLogs");
});
modelBuilder.Entity("WalkingTec.Mvvm.Core.DataPrivilege", b =>
{
b.Property<Guid>("ID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("CreateBy")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<DateTime?>("CreateTime")
.HasColumnType("TEXT");
b.Property<string>("Domain")
.HasColumnType("TEXT");
b.Property<string>("GroupCode")
.HasColumnType("TEXT");
b.Property<string>("RelateId")
.HasColumnType("TEXT");
b.Property<string>("TableName")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<string>("UpdateBy")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<DateTime?>("UpdateTime")
.HasColumnType("TEXT");
b.Property<string>("UserCode")
.HasColumnType("TEXT");
b.HasKey("ID");
b.ToTable("DataPrivileges");
});
modelBuilder.Entity("WalkingTec.Mvvm.Core.FileAttachment", b =>
{
b.Property<Guid>("ID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("ExtraInfo")
.HasColumnType("TEXT");
b.Property<byte[]>("FileData")
.HasColumnType("BLOB");
b.Property<string>("FileExt")
.IsRequired()
.HasMaxLength(10)
.HasColumnType("TEXT");
b.Property<string>("FileName")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("HandlerInfo")
.HasColumnType("TEXT");
b.Property<long>("Length")
.HasColumnType("INTEGER");
b.Property<string>("Path")
.HasColumnType("TEXT");
b.Property<string>("SaveMode")
.HasColumnType("TEXT");
b.Property<DateTime>("UploadTime")
.HasColumnType("TEXT");
b.HasKey("ID");
b.ToTable("FileAttachments");
});
modelBuilder.Entity("WalkingTec.Mvvm.Core.FrameworkGroup", b =>
{
b.Property<Guid>("ID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("CreateBy")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<DateTime?>("CreateTime")
.HasColumnType("TEXT");
b.Property<string>("GroupCode")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("TEXT");
b.Property<string>("GroupName")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<string>("GroupRemark")
.HasColumnType("TEXT");
b.Property<string>("TenantCode")
.HasColumnType("TEXT");
b.Property<string>("UpdateBy")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<DateTime?>("UpdateTime")
.HasColumnType("TEXT");
b.HasKey("ID");
b.ToTable("FrameworkGroups");
});
modelBuilder.Entity("WalkingTec.Mvvm.Core.FrameworkMenu", b =>
{
b.Property<Guid>("ID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("ActionName")
.HasColumnType("TEXT");
b.Property<string>("ClassName")
.HasColumnType("TEXT");
b.Property<int?>("DisplayOrder")
.IsRequired()
.HasColumnType("INTEGER");
b.Property<string>("Domain")
.HasColumnType("TEXT");
b.Property<bool>("FolderOnly")
.HasColumnType("INTEGER");
b.Property<string>("Icon")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<bool>("IsInherit")
.HasColumnType("INTEGER");
b.Property<bool?>("IsInside")
.IsRequired()
.HasColumnType("INTEGER");
b.Property<bool>("IsPublic")
.HasColumnType("INTEGER");
b.Property<string>("MethodName")
.HasColumnType("TEXT");
b.Property<string>("ModuleName")
.HasColumnType("TEXT");
b.Property<string>("PageName")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<Guid?>("ParentId")
.HasColumnType("TEXT");
b.Property<bool>("ShowOnMenu")
.HasColumnType("INTEGER");
b.Property<string>("Url")
.HasColumnType("TEXT");
b.HasKey("ID");
b.HasIndex("ParentId");
b.ToTable("FrameworkMenus");
});
modelBuilder.Entity("WalkingTec.Mvvm.Core.FrameworkRole", b =>
{
b.Property<Guid>("ID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("CreateBy")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<DateTime?>("CreateTime")
.HasColumnType("TEXT");
b.Property<string>("RoleCode")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("TEXT");
b.Property<string>("RoleName")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<string>("RoleRemark")
.HasColumnType("TEXT");
b.Property<string>("TenantCode")
.HasColumnType("TEXT");
b.Property<string>("UpdateBy")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<DateTime?>("UpdateTime")
.HasColumnType("TEXT");
b.HasKey("ID");
b.ToTable("FrameworkRoles");
});
modelBuilder.Entity("WalkingTec.Mvvm.Core.FrameworkUser", b =>
{
b.Property<Guid>("ID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("Address")
.HasMaxLength(200)
.HasColumnType("TEXT");
b.Property<string>("CellPhone")
.HasColumnType("TEXT");
b.Property<string>("CreateBy")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<DateTime?>("CreateTime")
.HasColumnType("TEXT");
b.Property<string>("Email")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<int?>("Gender")
.HasColumnType("INTEGER");
b.Property<string>("HomePhone")
.HasMaxLength(30)
.HasColumnType("TEXT");
b.Property<string>("ITCode")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<bool>("IsValid")
.HasColumnType("INTEGER");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<string>("Password")
.IsRequired()
.HasMaxLength(32)
.HasColumnType("TEXT");
b.Property<Guid?>("PhotoId")
.HasColumnType("TEXT");
b.Property<string>("TenantCode")
.HasColumnType("TEXT");
b.Property<string>("UpdateBy")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<DateTime?>("UpdateTime")
.HasColumnType("TEXT");
b.Property<string>("ZipCode")
.HasColumnType("TEXT");
b.HasKey("ID");
b.HasIndex("PhotoId");
b.ToTable("FrameworkUsers");
});
modelBuilder.Entity("WalkingTec.Mvvm.Core.FrameworkUserGroup", b =>
{
b.Property<Guid>("ID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("CreateBy")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<DateTime?>("CreateTime")
.HasColumnType("TEXT");
b.Property<string>("GroupCode")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("UpdateBy")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<DateTime?>("UpdateTime")
.HasColumnType("TEXT");
b.Property<string>("UserCode")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("ID");
b.ToTable("FrameworkUserGroups");
});
modelBuilder.Entity("WalkingTec.Mvvm.Core.FrameworkUserRole", b =>
{
b.Property<Guid>("ID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("CreateBy")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<DateTime?>("CreateTime")
.HasColumnType("TEXT");
b.Property<string>("RoleCode")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("UpdateBy")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<DateTime?>("UpdateTime")
.HasColumnType("TEXT");
b.Property<string>("UserCode")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("ID");
b.ToTable("FrameworkUserRoles");
});
modelBuilder.Entity("WalkingTec.Mvvm.Core.FunctionPrivilege", b =>
{
b.Property<Guid>("ID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<bool?>("Allowed")
.IsRequired()
.HasColumnType("INTEGER");
b.Property<string>("CreateBy")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<DateTime?>("CreateTime")
.HasColumnType("TEXT");
b.Property<Guid>("MenuItemId")
.HasColumnType("TEXT");
b.Property<string>("RoleCode")
.HasColumnType("TEXT");
b.Property<string>("UpdateBy")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<DateTime?>("UpdateTime")
.HasColumnType("TEXT");
b.HasKey("ID");
b.HasIndex("MenuItemId");
b.ToTable("FunctionPrivileges");
});
modelBuilder.Entity("WalkingTec.Mvvm.Core.PersistedGrant", b =>
{
b.Property<Guid>("ID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<DateTime>("CreationTime")
.HasColumnType("TEXT");
b.Property<DateTime>("Expiration")
.HasColumnType("TEXT");
b.Property<string>("RefreshToken")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<string>("Type")
.HasMaxLength(50)
.HasColumnType("TEXT");
b.Property<string>("UserCode")
.HasColumnType("TEXT");
b.HasKey("ID");
b.ToTable("PersistedGrants");
});
modelBuilder.Entity("IoTGateway.Model.Device", b =>
{
b.HasOne("IoTGateway.Model.Driver", "Driver")
.WithMany()
.HasForeignKey("DriverId");
b.HasOne("IoTGateway.Model.Device", "Parent")
.WithMany("Children")
.HasForeignKey("ParentId");
b.Navigation("Driver");
b.Navigation("Parent");
});
modelBuilder.Entity("IoTGateway.Model.DeviceConfig", b =>
{
b.HasOne("IoTGateway.Model.Device", "Device")
.WithMany("DeviceConfigs")
.HasForeignKey("DeviceId");
b.Navigation("Device");
});
modelBuilder.Entity("IoTGateway.Model.DeviceVariable", b =>
{
b.HasOne("IoTGateway.Model.Device", "Device")
.WithMany("DeviceVariables")
.HasForeignKey("DeviceId");
b.Navigation("Device");
});
modelBuilder.Entity("IoTGateway.Model.RpcLog", b =>
{
b.HasOne("IoTGateway.Model.Device", "Device")
.WithMany()
.HasForeignKey("DeviceId");
b.Navigation("Device");
});
modelBuilder.Entity("WalkingTec.Mvvm.Core.FrameworkMenu", b =>
{
b.HasOne("WalkingTec.Mvvm.Core.FrameworkMenu", "Parent")
.WithMany("Children")
.HasForeignKey("ParentId");
b.Navigation("Parent");
});
modelBuilder.Entity("WalkingTec.Mvvm.Core.FrameworkUser", b =>
{
b.HasOne("WalkingTec.Mvvm.Core.FileAttachment", "Photo")
.WithMany()
.HasForeignKey("PhotoId")
.OnDelete(DeleteBehavior.Restrict);
b.Navigation("Photo");
});
modelBuilder.Entity("WalkingTec.Mvvm.Core.FunctionPrivilege", b =>
{
b.HasOne("WalkingTec.Mvvm.Core.FrameworkMenu", "MenuItem")
.WithMany("Privileges")
.HasForeignKey("MenuItemId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("MenuItem");
});
modelBuilder.Entity("IoTGateway.Model.Device", b =>
{
b.Navigation("Children");
b.Navigation("DeviceConfigs");
b.Navigation("DeviceVariables");
});
modelBuilder.Entity("WalkingTec.Mvvm.Core.FrameworkMenu", b =>
{
b.Navigation("Children");
b.Navigation("Privileges");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,25 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace IoTGateway.DataAccess.Migrations
{
public partial class mqttClientId : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "ClientId",
table: "SystemConfig",
type: "TEXT",
nullable: true);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "ClientId",
table: "SystemConfig");
}
}
}

View File

@ -233,6 +233,9 @@ namespace IoTGateway.DataAccess.Migrations
.ValueGeneratedOnAdd() .ValueGeneratedOnAdd()
.HasColumnType("TEXT"); .HasColumnType("TEXT");
b.Property<string>("ClientId")
.HasColumnType("TEXT");
b.Property<string>("CreateBy") b.Property<string>("CreateBy")
.HasMaxLength(50) .HasMaxLength(50)
.HasColumnType("TEXT"); .HasColumnType("TEXT");

View File

@ -7,6 +7,8 @@ namespace IoTGateway.Model
{ {
[Display(Name = "网关名称")] [Display(Name = "网关名称")]
public string GatewayName { get; set; } public string GatewayName { get; set; }
[Display(Name = "ClientId")]
public string ClientId { get; set; }
[Display(Name = "Mqtt服务器")] [Display(Name = "Mqtt服务器")]
public string MqttIp { get; set; } public string MqttIp { get; set; }
[Display(Name = "Mqtt端口")] [Display(Name = "Mqtt端口")]
@ -34,6 +36,8 @@ namespace IoTGateway.Model
OneNET = 5, OneNET = 5,
[Display(Name = "ThingsCloud")] [Display(Name = "ThingsCloud")]
ThingsCloud = 6, ThingsCloud = 6,
[Display(Name = "华为云")]
HuaWei = 7,
[Display(Name = "IotDB")] [Display(Name = "IotDB")]
IotDB = 99 IotDB = 99
} }

View File

@ -40,9 +40,9 @@ namespace IoTGateway.ViewModel.BasicData.DeviceConfigVMs
{ {
foreach (var item in device.Children) foreach (var item in device.Children)
{ {
var deviceThread = deviceService.DeviceThreads.Where(x => x._device.ID.ToString() == (string)item.Value).FirstOrDefault(); var deviceThread = deviceService.DeviceThreads.Where(x => x.Device.ID.ToString() == (string)item.Value).FirstOrDefault();
if (deviceThread != null) if (deviceThread != null)
item.Icon = deviceThread._device.AutoStart ? (deviceThread._driver.IsConnected ? "layui-icon layui-icon-link" : "layui-icon layui-icon-unlink") : "layui-icon layui-icon-pause"; item.Icon = deviceThread.Device.AutoStart ? (deviceThread.Driver.IsConnected ? "layui-icon layui-icon-link" : "layui-icon layui-icon-unlink") : "layui-icon layui-icon-pause";
item.Text = " "+item.Text; item.Text = " "+item.Text;
item.Expended = true; item.Expended = true;

View File

@ -1,8 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using WalkingTec.Mvvm.Core; using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Core.Extensions; using WalkingTec.Mvvm.Core.Extensions;
using IoTGateway.Model; using IoTGateway.Model;
@ -37,9 +35,12 @@ namespace IoTGateway.ViewModel.BasicData.DeviceVMs
if (this.Entity.DeviceTypeEnum == DeviceTypeEnum.Device) if (this.Entity.DeviceTypeEnum == DeviceTypeEnum.Device)
{ {
var deviceService = Wtm.ServiceProvider.GetService(typeof(DeviceService)) as DeviceService; var deviceService = Wtm.ServiceProvider.GetService(typeof(DeviceService)) as DeviceService;
deviceService._DrvierManager.AddConfigs(this.Entity.ID, this.Entity.DriverId); deviceService.DrvierManager.AddConfigs(this.Entity.ID, this.Entity.DriverId);
var dap = DC.Set<Device>().Where(x => x.ID == Entity.ID).Include(x=>x.Parent).Include(x => x.Driver).SingleOrDefault(); var device = DC.Set<Device>().Where(x => x.ID == Entity.ID).Include(x=>x.Parent).Include(x => x.Driver).SingleOrDefault();
deviceService.CreateDeviceThread(dap); deviceService.CreateDeviceThread(device);
var myMqttClient = Wtm.ServiceProvider.GetService(typeof(MyMqttClient)) as MyMqttClient;
myMqttClient.DeviceAdded(device);
} }
} }
catch (Exception ex) catch (Exception ex)
@ -63,7 +64,14 @@ namespace IoTGateway.ViewModel.BasicData.DeviceVMs
var pluginManager = Wtm.ServiceProvider.GetService(typeof(DeviceService)) as DeviceService; var pluginManager = Wtm.ServiceProvider.GetService(typeof(DeviceService)) as DeviceService;
var ret = DeleteDevices.doDelete(pluginManager, DC, Ids); var ret = DeleteDevices.doDelete(pluginManager, DC, Ids);
if (!ret.IsSuccess) if (!ret.IsSuccess)
{
MSD.AddModelError("", ret.Message); MSD.AddModelError("", ret.Message);
return;
}
var myMqttClient = Wtm.ServiceProvider.GetService(typeof(MyMqttClient)) as MyMqttClient;
myMqttClient.DeviceDeleted(Entity);
} }
public override DuplicatedInfo<Device> SetDuplicatedCheck() public override DuplicatedInfo<Device> SetDuplicatedCheck()
{ {

View File

@ -45,9 +45,9 @@ namespace IoTGateway.ViewModel.BasicData.DeviceVariableVMs
{ {
foreach (var item in device.Children) foreach (var item in device.Children)
{ {
var deviceThread = deviceService.DeviceThreads.Where(x => x._device.ID.ToString() == (string)item.Value).FirstOrDefault(); var deviceThread = deviceService.DeviceThreads.Where(x => x.Device.ID.ToString() == (string)item.Value).FirstOrDefault();
if (deviceThread != null) if (deviceThread != null)
item.Icon = deviceThread._device.AutoStart ? (deviceThread._driver.IsConnected ? "layui-icon layui-icon-link" : "layui-icon layui-icon-unlink") : "layui-icon layui-icon-pause"; item.Icon = deviceThread.Device.AutoStart ? (deviceThread.Driver.IsConnected ? "layui-icon layui-icon-link" : "layui-icon layui-icon-unlink") : "layui-icon layui-icon-pause";
item.Text = " " + item.Text; item.Text = " " + item.Text;
item.Expended = true; item.Expended = true;
@ -95,7 +95,7 @@ namespace IoTGateway.ViewModel.BasicData.DeviceVariableVMs
var deviceService = Wtm.ServiceProvider.GetService(typeof(DeviceService)) as DeviceService; var deviceService = Wtm.ServiceProvider.GetService(typeof(DeviceService)) as DeviceService;
foreach (var item in EntityList) foreach (var item in EntityList)
{ {
var DapThread = deviceService.DeviceThreads.Where(x => x._device.ID == item.DeviceId).FirstOrDefault(); var DapThread = deviceService.DeviceThreads.Where(x => x.Device.ID == item.DeviceId).FirstOrDefault();
if (DapThread?.DeviceValues != null && DapThread.DeviceValues.ContainsKey(item.ID)) if (DapThread?.DeviceValues != null && DapThread.DeviceValues.ContainsKey(item.ID))
{ {
item.Value = DapThread?.DeviceValues[item.ID]?.Value?.ToString(); item.Value = DapThread?.DeviceValues[item.ID]?.Value?.ToString();

View File

@ -31,7 +31,7 @@ namespace IoTGateway.ViewModel.BasicData.DeviceVariableVMs
= variable.DataType.GetEnumDisplayName(); = variable.DataType.GetEnumDisplayName();
var deviceService = Wtm.ServiceProvider.GetService(typeof(DeviceService)) as DeviceService; var deviceService = Wtm.ServiceProvider.GetService(typeof(DeviceService)) as DeviceService;
var dapThread = deviceService.DeviceThreads.Where(x => x._device.ID == variable.DeviceId).FirstOrDefault(); var dapThread = deviceService.DeviceThreads.Where(x => x.Device.ID == variable.DeviceId).FirstOrDefault();
if (dapThread?.DeviceValues != null && dapThread.DeviceValues.ContainsKey(variable.ID)) if (dapThread?.DeviceValues != null && dapThread.DeviceValues.ContainsKey(variable.ID))
{ {
@ -71,7 +71,7 @@ namespace IoTGateway.ViewModel.BasicData.DeviceVariableVMs
= variable.DataType.GetEnumDisplayName(); = variable.DataType.GetEnumDisplayName();
var deviceService = Wtm.ServiceProvider.GetService(typeof(DeviceService)) as DeviceService; var deviceService = Wtm.ServiceProvider.GetService(typeof(DeviceService)) as DeviceService;
var dapThread = deviceService.DeviceThreads.Where(x => x._device.ID == variable.DeviceId).FirstOrDefault(); var dapThread = deviceService.DeviceThreads.Where(x => x.Device.ID == variable.DeviceId).FirstOrDefault();
if (dapThread?.DeviceValues != null && dapThread.DeviceValues.ContainsKey(variable.ID)) if (dapThread?.DeviceValues != null && dapThread.DeviceValues.ContainsKey(variable.ID))
{ {

View File

@ -33,6 +33,7 @@ namespace IoTGateway.ViewModel.Config.SystemConfigVMs
{ {
return new List<GridColumn<SystemConfig_View>>{ return new List<GridColumn<SystemConfig_View>>{
this.MakeGridHeader(x => x.GatewayName), this.MakeGridHeader(x => x.GatewayName),
this.MakeGridHeader(x => x.ClientId),
this.MakeGridHeader(x => x.IoTPlatformType), this.MakeGridHeader(x => x.IoTPlatformType),
this.MakeGridHeader(x => x.MqttIp), this.MakeGridHeader(x => x.MqttIp),
this.MakeGridHeader(x => x.MqttPort), this.MakeGridHeader(x => x.MqttPort),
@ -49,6 +50,7 @@ namespace IoTGateway.ViewModel.Config.SystemConfigVMs
{ {
ID = x.ID, ID = x.ID,
GatewayName = x.GatewayName, GatewayName = x.GatewayName,
ClientId = x.ClientId,
MqttIp = x.MqttIp, MqttIp = x.MqttIp,
MqttPort = x.MqttPort, MqttPort = x.MqttPort,
MqttUName = x.MqttUName, MqttUName = x.MqttUName,

View File

@ -5,6 +5,7 @@
<wt:quote>注意目前实现了iotsharp、thingsboard、thingscloud、iotdb的遥测、属性上传以及RPC功能</wt:quote> <wt:quote>注意目前实现了iotsharp、thingsboard、thingscloud、iotdb的遥测、属性上传以及RPC功能</wt:quote>
<wt:row items-per-row="ItemsPerRowEnum.Two"> <wt:row items-per-row="ItemsPerRowEnum.Two">
<wt:textbox field="Entity.GatewayName" /> <wt:textbox field="Entity.GatewayName" />
<wt:textbox field="Entity.ClientId" />
<wt:combobox field="Entity.IoTPlatformType" /> <wt:combobox field="Entity.IoTPlatformType" />
<wt:textbox field="Entity.MqttIp" /> <wt:textbox field="Entity.MqttIp" />
<wt:textbox field="Entity.MqttPort" /> <wt:textbox field="Entity.MqttPort" />

View File

@ -53,21 +53,21 @@ namespace IoTGateway.Controllers
data.Add(new ChartData data.Add(new ChartData
{ {
Value = _deviceService.DeviceThreads.Where(x => !x._device.AutoStart).Count(), Value = _deviceService.DeviceThreads.Where(x => !x.Device.AutoStart).Count(),
Category = "停止", Category = "停止",
Series = "Device" Series = "Device"
}); });
data.Add(new ChartData data.Add(new ChartData
{ {
Value = _deviceService.DeviceThreads.Where(x => x._device.AutoStart && x._driver.IsConnected).Count(), Value = _deviceService.DeviceThreads.Where(x => x.Device.AutoStart && x.Driver.IsConnected).Count(),
Category = "运行", Category = "运行",
Series = "Device", Series = "Device",
}); });
data.Add(new ChartData data.Add(new ChartData
{ {
Value = _deviceService.DeviceThreads.Where(x => x._device.AutoStart && !x._driver.IsConnected).Count(), Value = _deviceService.DeviceThreads.Where(x => x.Device.AutoStart && !x.Driver.IsConnected).Count(),
Category = "异常", Category = "异常",
Series = "Device" Series = "Device"
}); });
@ -78,18 +78,18 @@ namespace IoTGateway.Controllers
public IActionResult GetDeviceVariableChart() public IActionResult GetDeviceVariableChart()
{ {
var data = new List<ChartData>(); var data = new List<ChartData>();
foreach (var deviceThread in _deviceService.DeviceThreads.OrderBy(x => x._device.DeviceName)) foreach (var deviceThread in _deviceService.DeviceThreads.OrderBy(x => x.Device.DeviceName))
{ {
data.Add(new ChartData data.Add(new ChartData
{ {
Category = deviceThread._device.DeviceName, Category = deviceThread.Device.DeviceName,
Value = deviceThread.DeviceValues.Where(x => x.Value.StatusType != VaribaleStatusTypeEnum.Good).Count(), Value = deviceThread.DeviceValues.Where(x => x.Value.StatusType != VaribaleStatusTypeEnum.Good).Count(),
Series = "Others" Series = "Others"
}); });
data.Add(new ChartData data.Add(new ChartData
{ {
Category = deviceThread._device.DeviceName, Category = deviceThread.Device.DeviceName,
Value = deviceThread.DeviceValues.Where(x => x.Value.StatusType == VaribaleStatusTypeEnum.Good).Count(), Value = deviceThread.DeviceValues.Where(x => x.Value.StatusType == VaribaleStatusTypeEnum.Good).Count(),
Series = "Good" Series = "Good"
}); });

Binary file not shown.

View File

@ -1,15 +1,10 @@
using System; namespace Plugin
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Plugin
{ {
public class ConnnectSettingsModel public class ConnnectSettingsModel
{ {
public string Key { get; set; } public string? Key { get; set; }
public string Value { get; set; } public string? Value { get; set; }
public string DbContext { get; set; } public string? DbContext { get; set; }
public string DBType { get; set; } public string? DbType { get; set; }
} }
} }

View File

@ -3,11 +3,9 @@ using Microsoft.Extensions.Configuration;
using PluginInterface; using PluginInterface;
using System.Net; using System.Net;
using System.Reflection; using System.Reflection;
using System.Runtime.CompilerServices;
using WalkingTec.Mvvm.Core; using WalkingTec.Mvvm.Core;
using IoTGateway.DataAccess; using IoTGateway.DataAccess;
using IoTGateway.Model; using IoTGateway.Model;
using DynamicExpresso;
using MQTTnet.Server; using MQTTnet.Server;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
@ -16,34 +14,40 @@ namespace Plugin
public class DeviceService : IDisposable public class DeviceService : IDisposable
{ {
private readonly ILogger<DeviceService> _logger; private readonly ILogger<DeviceService> _logger;
public DriverService _DrvierManager; public DriverService DrvierManager;
public List<DeviceThread> DeviceThreads = new List<DeviceThread>(); public List<DeviceThread> DeviceThreads = new List<DeviceThread>();
private MyMqttClient _MyMqttClient; private readonly MyMqttClient _myMqttClient;
private IMqttServer _MqttServer; private readonly UAService _uAService;
private string connnectSetting = IoTBackgroundService.connnectSetting; private readonly IMqttServer _mqttServer;
private DBTypeEnum DBType = IoTBackgroundService.DBType; private readonly string _connnectSetting = IoTBackgroundService.connnectSetting;
public DeviceService(IConfiguration ConfigRoot, DriverService drvierManager, MyMqttClient myMqttClient, UAService uAService, IMqttServer mqttServer, ILogger<DeviceService> logger) private readonly DBTypeEnum _dbType = IoTBackgroundService.DbType;
public DeviceService(IConfiguration configRoot, DriverService drvierManager, MyMqttClient myMqttClient,
UAService uAService, IMqttServer mqttServer, ILogger<DeviceService> logger)
{ {
if (mqttServer == null) throw new ArgumentNullException(nameof(mqttServer));
_logger = logger; _logger = logger;
_DrvierManager = drvierManager; DrvierManager = drvierManager;
_MyMqttClient = myMqttClient; _myMqttClient = myMqttClient;
_MqttServer = mqttServer; _uAService = uAService;
_mqttServer = mqttServer ?? throw new ArgumentNullException(nameof(mqttServer));
try try
{ {
using (var DC = new DataContext(connnectSetting, DBType)) using (var dc = new DataContext(_connnectSetting, _dbType))
{ {
var Devices = DC.Set<Device>().Where(x => x.DeviceTypeEnum == DeviceTypeEnum.Device).Include(x => x.Parent).Include(x => x.Driver).Include(x => x.DeviceConfigs).Include(x => x.DeviceVariables).AsNoTracking().ToList(); var devices = dc.Set<Device>().Where(x => x.DeviceTypeEnum == DeviceTypeEnum.Device)
_logger.LogInformation($"Loaded Devices Count:{Devices.Count()}"); .Include(x => x.Parent).Include(x => x.Driver).Include(x => x.DeviceConfigs)
foreach (var Device in Devices) .Include(x => x.DeviceVariables).AsNoTracking().ToList();
_logger.LogInformation($"Loaded Devices Count:{devices.Count()}");
foreach (var device in devices)
{ {
CreateDeviceThread(Device); CreateDeviceThread(device);
} }
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError($"LoadDevicesError", ex); _logger.LogError($"LoadDevicesError", ex);
} }
} }
@ -61,7 +65,6 @@ namespace Plugin
{ {
_logger.LogError($"UpdateDevice Error:{device.DeviceName}", ex); _logger.LogError($"UpdateDevice Error:{device.DeviceName}", ex);
} }
} }
public void UpdateDevices(List<Device> devices) public void UpdateDevices(List<Device> devices)
@ -70,31 +73,33 @@ namespace Plugin
UpdateDevice(device); UpdateDevice(device);
} }
public void CreateDeviceThread(Device Device) public void CreateDeviceThread(Device device)
{ {
try try
{ {
_logger.LogInformation($"CreateDeviceThread Start:{Device.DeviceName}"); _logger.LogInformation($"CreateDeviceThread Start:{device.DeviceName}");
using (var DC = new DataContext(connnectSetting, DBType)) using (var dc = new DataContext(_connnectSetting, _dbType))
{ {
var systemManage = DC.Set<SystemConfig>().FirstOrDefault(); var systemManage = dc.Set<SystemConfig>().FirstOrDefault();
var driver = _DrvierManager.DriverInfos.Where(x => x.Type.FullName == Device.Driver.AssembleName).SingleOrDefault(); var driver = DrvierManager.DriverInfos
.SingleOrDefault(x => x.Type.FullName == device.Driver.AssembleName);
if (driver == null) if (driver == null)
_logger.LogError($"找不到设备:[{Device.DeviceName}]的驱动:[{Device.Driver.AssembleName}]"); _logger.LogError($"找不到设备:[{device.DeviceName}]的驱动:[{device.Driver.AssembleName}]");
else else
{ {
var settings = DC.Set<DeviceConfig>().Where(x => x.DeviceId == Device.ID).AsNoTracking().ToList(); var settings = dc.Set<DeviceConfig>().Where(x => x.DeviceId == device.ID).AsNoTracking()
.ToList();
Type[] types = new Type[2] { typeof(string) ,typeof(ILogger) }; Type[] types = new Type[] { typeof(string), typeof(ILogger) };
object[] param = new object[2] { Device.DeviceName , _logger }; object[] param = new object[] { device.DeviceName, _logger };
ConstructorInfo constructor = driver.Type.GetConstructor(types); ConstructorInfo? constructor = driver.Type.GetConstructor(types);
var DeviceObj = constructor.Invoke(param) as IDriver; var deviceObj = constructor?.Invoke(param) as IDriver;
foreach (var p in driver.Type.GetProperties()) foreach (var p in driver.Type.GetProperties())
{ {
var config = p.GetCustomAttribute(typeof(ConfigParameterAttribute)); var config = p.GetCustomAttribute(typeof(ConfigParameterAttribute));
var setting = settings.Where(x => x.DeviceConfigName == p.Name).FirstOrDefault(); var setting = settings.FirstOrDefault(x => x.DeviceConfigName == p.Name);
if (config == null || setting == null) if (config == null || setting == null)
continue; continue;
@ -135,24 +140,25 @@ namespace Plugin
else if (p.PropertyType.BaseType == typeof(Enum)) else if (p.PropertyType.BaseType == typeof(Enum))
value = Enum.Parse(p.PropertyType, setting.Value); value = Enum.Parse(p.PropertyType, setting.Value);
p.SetValue(DeviceObj, value); p.SetValue(deviceObj, value);
} }
var deviceThread = new DeviceThread(Device, DeviceObj, systemManage.GatewayName, _MyMqttClient, _MqttServer, _logger); if (deviceObj != null && systemManage != null)
{
var deviceThread = new DeviceThread(device, deviceObj, systemManage.GatewayName,
_myMqttClient,
_mqttServer, _logger);
DeviceThreads.Add(deviceThread); DeviceThreads.Add(deviceThread);
} }
}
} }
_logger.LogInformation($"CreateDeviceThread End:{Device.DeviceName}"); _logger.LogInformation($"CreateDeviceThread End:{device.DeviceName}");
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogInformation($"CreateDeviceThread Error:{Device.DeviceName}", ex); _logger.LogInformation($"CreateDeviceThread Error:{device.DeviceName}", ex);
} }
} }
public void CreateDeviceThreads(List<Device> devices) public void CreateDeviceThreads(List<Device> devices)
@ -163,15 +169,12 @@ namespace Plugin
public void RemoveDeviceThread(Device devices) public void RemoveDeviceThread(Device devices)
{ {
if (devices != null) var deviceThread = DeviceThreads.FirstOrDefault(x => x.Device.ID == devices.ID);
if (deviceThread != null)
{ {
var DeviceThread = DeviceThreads.Where(x => x._device.ID == devices.ID).FirstOrDefault(); deviceThread.StopThread();
if (DeviceThread != null) deviceThread.Dispose();
{ DeviceThreads.Remove(deviceThread);
DeviceThread.StopThread();
DeviceThread.Dispose();
DeviceThreads.Remove(DeviceThread);
}
} }
} }
@ -187,9 +190,11 @@ namespace Plugin
try try
{ {
_logger.LogInformation($"GetDriverMethods Start:{deviceId}"); _logger.LogInformation($"GetDriverMethods Start:{deviceId}");
foreach (var method in DeviceThreads.Where(x => x._device.ID == deviceId).FirstOrDefault()?.Methods) var methodInfos = DeviceThreads.FirstOrDefault(x => x.Device.ID == deviceId)?.Methods;
if (methodInfos != null)
foreach (var method in methodInfos)
{ {
var Attribute = method.CustomAttributes.ToList().FirstOrDefault().ConstructorArguments; var attribute = method.CustomAttributes.ToList().FirstOrDefault()?.ConstructorArguments;
var item = new ComboSelectListItem var item = new ComboSelectListItem
{ {
Text = method.Name, Text = method.Name,
@ -197,16 +202,17 @@ namespace Plugin
}; };
driverFilesComboSelect.Add(item); driverFilesComboSelect.Add(item);
} }
_logger.LogInformation($"GetDriverMethods End:{deviceId}"); _logger.LogInformation($"GetDriverMethods End:{deviceId}");
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError($"GetDriverMethods Error:{deviceId}", ex);
_logger.LogInformation($"GetDriverMethods Error:{deviceId}");
} }
return driverFilesComboSelect; return driverFilesComboSelect;
} }
public void Dispose() public void Dispose()
{ {
_logger.LogInformation("Dispose"); _logger.LogInformation("Dispose");

View File

@ -12,51 +12,55 @@ namespace Plugin
public class DeviceThread : IDisposable public class DeviceThread : IDisposable
{ {
private readonly ILogger _logger; private readonly ILogger _logger;
public readonly Device _device; public readonly Device Device;
public readonly IDriver _driver; public readonly IDriver Driver;
private readonly MyMqttClient _myMqttClient; private readonly string _projectId;
private Interpreter _interpreter ; private readonly MyMqttClient? _myMqttClient;
private Interpreter? _interpreter;
public Dictionary<Guid, DriverReturnValueModel> DeviceValues { get; set; } = new(); public Dictionary<Guid, DriverReturnValueModel> DeviceValues { get; set; } = new();
internal List<MethodInfo> Methods { get; set; } internal List<MethodInfo>? Methods { get; set; }
private Task task { get; set; } = null; private Task? _task;
private DateTime TsStartDt = new DateTime(1970, 1, 1); private readonly DateTime _tsStartDt = new(1970, 1, 1);
private CancellationTokenSource tokenSource = new CancellationTokenSource(); private readonly CancellationTokenSource _tokenSource = new CancellationTokenSource();
private object _lock = new object(); private readonly object _lock = new();
private bool lastConnected = false; private bool _lastConnected;
public DeviceThread(Device device, IDriver driver, string ProjectId, MyMqttClient myMqttClient, IMqttServer mqttServer, ILogger logger)
public DeviceThread(Device device, IDriver driver, string projectId, MyMqttClient myMqttClient,
IMqttServer mqttServer, ILogger logger)
{ {
_myMqttClient = myMqttClient; _myMqttClient = myMqttClient;
_myMqttClient.OnExcRpc += MyMqttClient_OnExcRpc; _myMqttClient.OnExcRpc += MyMqttClient_OnExcRpc;
_device = device; Device = device;
_driver = driver; Driver = driver;
_projectId = projectId;
_interpreter = new Interpreter(); _interpreter = new Interpreter();
_logger = logger; _logger = logger;
Methods = _driver.GetType().GetMethods().Where(x => x.GetCustomAttribute(typeof(MethodAttribute)) != null).ToList(); Methods = Driver.GetType().GetMethods().Where(x => x.GetCustomAttribute(typeof(MethodAttribute)) != null)
if (_device.AutoStart) .ToList();
if (Device.AutoStart)
{ {
_logger.LogInformation($"线程已启动:{_device.DeviceName}"); _logger.LogInformation($"线程已启动:{Device.DeviceName}");
using (var DC = new DataContext(IoTBackgroundService.connnectSetting, IoTBackgroundService.DBType)) if (Device.DeviceVariables != null)
{ {
if (_device.DeviceVariables != null) foreach (var item in Device.DeviceVariables)
{
foreach (var item in _device.DeviceVariables)
{ {
DeviceValues[item.ID] = new() { StatusType = VaribaleStatusTypeEnum.Bad }; DeviceValues[item.ID] = new() { StatusType = VaribaleStatusTypeEnum.Bad };
} }
} }
}
task = Task.Run(() => _task = Task.Run(() =>
{ {
Thread.Sleep(5000); //上传客户端属性 Thread.Sleep(5000); //上传客户端属性
myMqttClient.UploadAttributeAsync(device.DeviceName, device.DeviceConfigs.Where(x => x.DataSide == DataSide.ClientSide).ToDictionary(x => x.DeviceConfigName, x => x.Value)); myMqttClient.UploadAttributeAsync(device.DeviceName,
device.DeviceConfigs.Where(x => x.DataSide == DataSide.ClientSide)
.ToDictionary(x => x.DeviceConfigName, x => x.Value));
while (true) while (true)
{ {
if (tokenSource.IsCancellationRequested) if (_tokenSource.IsCancellationRequested)
{ {
_logger.LogInformation($"停止线程:{_device.DeviceName}"); _logger.LogInformation($"停止线程:{Device.DeviceName}");
return; return;
} }
@ -64,15 +68,15 @@ namespace Plugin
{ {
try try
{ {
Dictionary<string, List<PayLoad>> sendModel = new() { { _device.DeviceName, new() } }; 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 (driver.IsConnected)
{ {
if (_device.DeviceVariables != null) if (Device.DeviceVariables != null)
{ {
foreach (var item in _device.DeviceVariables) foreach (var item in Device.DeviceVariables)
{ {
var ret = new DriverReturnValueModel(); var ret = new DriverReturnValueModel();
var ioarg = new DriverAddressIoArgModel var ioarg = new DriverAddressIoArgModel
@ -85,13 +89,16 @@ namespace Plugin
if (method == null) if (method == null)
ret.StatusType = VaribaleStatusTypeEnum.MethodError; ret.StatusType = VaribaleStatusTypeEnum.MethodError;
else else
ret = (DriverReturnValueModel)method.Invoke(_driver, new object[1] { ioarg }); ret = (DriverReturnValueModel)method.Invoke(Driver,
new object[] { ioarg })!;
if (ret.StatusType == VaribaleStatusTypeEnum.Good && !string.IsNullOrWhiteSpace(item.Expressions?.Trim())) if (ret.StatusType == VaribaleStatusTypeEnum.Good &&
!string.IsNullOrWhiteSpace(item.Expressions?.Trim()))
{ {
try try
{ {
ret.CookedValue = _interpreter.Eval(DealMysqlStr(item.Expressions).Replace("raw", ret.Value?.ToString())); ret.CookedValue = _interpreter.Eval(DealMysqlStr(item.Expressions)
.Replace("raw", ret.Value.ToString()));
} }
catch (Exception) catch (Exception)
{ {
@ -106,18 +113,25 @@ namespace Plugin
ret.VarId = item.ID; ret.VarId = item.ID;
//变化了才推送到mqttserver用于前端展示 //变化了才推送到mqttserver用于前端展示
if (DeviceValues[item.ID].StatusType != ret.StatusType || DeviceValues[item.ID].Value?.ToString() != ret.Value?.ToString() || DeviceValues[item.ID].CookedValue?.ToString() != ret.CookedValue?.ToString()) 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(
$"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.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)) if (DeviceValues.Any(x => x.Value.Value == null))
{ {
@ -127,74 +141,75 @@ namespace Plugin
else else
{ {
payLoad.DeviceStatus = DeviceStatusTypeEnum.Good; payLoad.DeviceStatus = DeviceStatusTypeEnum.Good;
sendModel[_device.DeviceName] = new List<PayLoad> { payLoad }; sendModel[Device.DeviceName] = new List<PayLoad> { payLoad };
myMqttClient.PublishTelemetry(_device, sendModel); myMqttClient.PublishTelemetryAsync(Device, sendModel);
} }
} }
} }
else else
{ {
if (driver.Connect()) if (driver.Connect())
{ {
lastConnected = true; _lastConnected = true;
_myMqttClient.DeviceConnected(_device.DeviceName); _myMqttClient?.DeviceConnected(Device);
} }
else if (lastConnected) else if (_lastConnected)
{ {
lastConnected = false; _lastConnected = false;
_myMqttClient.DeviceDisconnected(_device.DeviceName); _myMqttClient?.DeviceDisconnected(Device);
} }
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError($"线程循环异常,{_device.DeviceName}", ex); _logger.LogError($"线程循环异常,{Device.DeviceName}", ex);
} }
} }
Thread.Sleep((int)_driver.MinPeriod); Thread.Sleep((int)Driver.MinPeriod);
} }
}); });
} }
else else
_myMqttClient.DeviceDisconnected(_device.DeviceName); _myMqttClient?.DeviceDisconnected(Device);
} }
public void MyMqttClient_OnExcRpc(object? sender, RpcRequest e) public void MyMqttClient_OnExcRpc(object? sender, RpcRequest e)
{ {
if (e.DeviceName == _device.DeviceName) if (e.DeviceName == Device.DeviceName)
{ {
RpcLog rpcLog = new RpcLog() RpcLog rpcLog = new RpcLog()
{ {
DeviceId = _device.ID, DeviceId = Device.ID,
StartTime = DateTime.Now, StartTime = DateTime.Now,
Method = e.Method, Method = e.Method,
RpcSide = RpcSide.ServerSide, RpcSide = RpcSide.ServerSide,
Params = JsonConvert.SerializeObject(e.Params) Params = JsonConvert.SerializeObject(e.Params)
}; };
_logger.LogInformation($"{_device.DeviceName}收到RPC,{e}"); _logger.LogInformation($"{Device.DeviceName}收到RPC,{e}");
RpcResponse rpcResponse = new() { DeviceName = e.DeviceName, RequestId = e.RequestId, IsSuccess = false }; RpcResponse rpcResponse = new()
{ DeviceName = e.DeviceName, RequestId = e.RequestId, IsSuccess = false };
//执行写入变量RPC //执行写入变量RPC
if (e.Method.ToLower() == "write") if (e.Method.ToLower() == "write")
{ {
lock (_lock) lock (_lock)
{ {
bool RpcConnected = false; bool rpcConnected = false;
//没连接就连接 //没连接就连接
if (!_driver.IsConnected) if (!Driver.IsConnected)
if (_driver.Connect()) if (Driver.Connect())
RpcConnected = true; rpcConnected = true;
//连接成功就尝试一个一个的写入,注意:目前写入地址和读取地址是相同的对于PLC来说没问题其他的要自己改........ //连接成功就尝试一个一个的写入,注意:目前写入地址和读取地址是相同的对于PLC来说没问题其他的要自己改........
if (_driver.IsConnected) if (Driver.IsConnected)
{ {
foreach (var para in e.Params) foreach (var para in e.Params)
{ {
//先查配置项,要用到配置的地址、数据类型、方法(方法最主要是用于区分写入数据的辅助判断比如modbus不同的功能码) //先查配置项,要用到配置的地址、数据类型、方法(方法最主要是用于区分写入数据的辅助判断比如modbus不同的功能码)
var deviceVariable = _device.DeviceVariables.Where(x => x.Name == para.Key).FirstOrDefault(); var deviceVariable = Device.DeviceVariables.Where(x => x.Name == para.Key)
.FirstOrDefault();
if (deviceVariable != null) if (deviceVariable != null)
{ {
DriverAddressIoArgModel ioArgModel = new() DriverAddressIoArgModel ioArgModel = new()
@ -203,7 +218,8 @@ namespace Plugin
Value = para.Value, Value = para.Value,
ValueType = deviceVariable.DataType ValueType = deviceVariable.DataType
}; };
var writeResponse = _driver.WriteAsync(e.RequestId, deviceVariable.Method, ioArgModel).Result; var writeResponse = Driver
.WriteAsync(e.RequestId, deviceVariable.Method, ioArgModel).Result;
rpcResponse.IsSuccess = writeResponse.IsSuccess; rpcResponse.IsSuccess = writeResponse.IsSuccess;
if (!writeResponse.IsSuccess) if (!writeResponse.IsSuccess)
{ {
@ -218,9 +234,9 @@ namespace Plugin
break; break;
} }
} }
if (RpcConnected)
_driver.Close();
if (rpcConnected)
Driver.Close();
} }
else //连接失败 else //连接失败
{ {
@ -228,7 +244,6 @@ namespace Plugin
rpcResponse.Description = $"{e.DeviceName} 连接失败"; rpcResponse.Description = $"{e.DeviceName} 连接失败";
} }
} }
} }
//其他RPC TODO //其他RPC TODO
else else
@ -238,47 +253,46 @@ namespace Plugin
} }
//反馈RPC //反馈RPC
_myMqttClient.ResponseRpc(rpcResponse); _myMqttClient.ResponseRpcAsync(rpcResponse);
//纪录入库 //纪录入库
rpcLog.IsSuccess = rpcResponse.IsSuccess; rpcLog.IsSuccess = rpcResponse.IsSuccess;
rpcLog.Description = rpcResponse.Description; rpcLog.Description = rpcResponse.Description;
rpcLog.EndTime = DateTime.Now; rpcLog.EndTime = DateTime.Now;
using (var DC = new DataContext(IoTBackgroundService.connnectSetting, IoTBackgroundService.DBType)) using (var dc = new DataContext(IoTBackgroundService.connnectSetting, IoTBackgroundService.DbType))
{ {
DC.Set<RpcLog>().Add(rpcLog); dc.Set<RpcLog>().Add(rpcLog);
DC.SaveChanges(); dc.SaveChanges();
} }
} }
} }
public void StopThread() public void StopThread()
{ {
_logger.LogInformation($"线程停止:{_device.DeviceName}"); _logger.LogInformation($"线程停止:{Device.DeviceName}");
_myMqttClient.DeviceDisconnected(_device.DeviceName); _myMqttClient?.DeviceDisconnected(Device);
if (task != null) if (_task != null)
{ {
_myMqttClient.OnExcRpc -= MyMqttClient_OnExcRpc; if (_myMqttClient != null) _myMqttClient.OnExcRpc -= MyMqttClient_OnExcRpc;
tokenSource.Cancel(); _tokenSource.Cancel();
_driver.Close(); Driver.Close();
} }
} }
public void Dispose() public void Dispose()
{ {
_driver.Dispose(); Driver.Dispose();
_interpreter = null; _interpreter = null;
DeviceValues = null; DeviceValues = null;
Methods = null; Methods = null;
_logger.LogInformation($"线程释放,{_device.DeviceName}"); _logger.LogInformation($"线程释放,{Device.DeviceName}");
} }
//mysql会把一些符号转义没找到原因先临时处理下 //mysql会把一些符号转义没找到原因先临时处理下
private string DealMysqlStr(string Expression) private string DealMysqlStr(string expression)
{ {
return Expression.Replace("&lt;", "<").Replace("&gt;", ">").Replace("&amp;", "&").Replace("&quot;", "\""); return expression.Replace("&lt;", "<").Replace("&gt;", ">").Replace("&amp;", "&").Replace("&quot;", "\"");
} }
} }
} }

View File

@ -1,13 +1,8 @@
using System; namespace Plugin
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Plugin
{ {
public class DriverInfo public class DriverInfo
{ {
public string FileName; public string? FileName;
public Type Type; public Type? Type;
} }
} }

View File

@ -1,13 +1,8 @@
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using PluginInterface; using PluginInterface;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection; using System.Reflection;
using System.Text.Json; using System.Text.Json;
using System.Threading.Tasks;
using WalkingTec.Mvvm.Core; using WalkingTec.Mvvm.Core;
using IoTGateway.DataAccess; using IoTGateway.DataAccess;
using IoTGateway.Model; using IoTGateway.Model;
@ -15,35 +10,37 @@ using Microsoft.Extensions.Logging;
namespace Plugin namespace Plugin
{ {
public class DriverService//: IDependency public class DriverService
{ {
private readonly ILogger<DriverService> _logger; private readonly ILogger<DriverService> _logger;
string DriverPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"drivers/net6.0"); readonly string _driverPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"drivers/net6.0");
string[] driverFiles; readonly string[] _driverFiles;
public List<DriverInfo> DriverInfos = new List<DriverInfo>(); public List<DriverInfo> DriverInfos = new();
public DriverService(IConfiguration ConfigRoot, ILogger<DriverService> logger)
public DriverService(IConfiguration configRoot, ILogger<DriverService> logger)
{ {
_logger = logger; _logger = logger;
try try
{ {
_logger.LogInformation("LoadDriverFiles Start"); _logger.LogInformation("LoadDriverFiles Start");
driverFiles = Directory.GetFiles(DriverPath).Where(x => Path.GetExtension(x) == ".dll").ToArray(); _driverFiles = Directory.GetFiles(_driverPath).Where(x => Path.GetExtension(x) == ".dll").ToArray();
_logger.LogInformation($"LoadDriverFiles EndCount{driverFiles.Count()}"); _logger.LogInformation($"LoadDriverFiles EndCount{_driverFiles.Count()}");
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError("LoadDriverFiles Error", ex); _logger.LogError("LoadDriverFiles Error", ex);
} }
LoadAllDrivers(); LoadAllDrivers();
} }
public List<ComboSelectListItem> GetAllDrivers() public List<ComboSelectListItem> GetAllDrivers()
{ {
List<ComboSelectListItem> driverFilesComboSelect = new List<ComboSelectListItem>(); List<ComboSelectListItem> driverFilesComboSelect = new List<ComboSelectListItem>();
using (var DC = new DataContext(IoTBackgroundService.connnectSetting, IoTBackgroundService.DBType)) using var dc = new DataContext(IoTBackgroundService.connnectSetting, IoTBackgroundService.DbType);
{ var drivers = dc.Set<Driver>().AsNoTracking().ToList();
var Drivers = DC.Set<Driver>().AsNoTracking().ToList();
foreach (var file in driverFiles) foreach (var file in _driverFiles)
{ {
var dll = Assembly.LoadFrom(file); var dll = Assembly.LoadFrom(file);
if (dll.GetTypes().Where(x => typeof(IDriver).IsAssignableFrom(x) && x.IsClass).Any()) if (dll.GetTypes().Where(x => typeof(IDriver).IsAssignableFrom(x) && x.IsClass).Any())
@ -55,47 +52,45 @@ namespace Plugin
Value = fileName, Value = fileName,
Disabled = false, Disabled = false,
}; };
if (Drivers.Where(x => x.FileName == Path.GetFileName(file)).Any()) if (drivers.Where(x => x.FileName == Path.GetFileName(file)).Any())
item.Disabled = true; item.Disabled = true;
driverFilesComboSelect.Add(item); driverFilesComboSelect.Add(item);
} }
} }
}
return driverFilesComboSelect; return driverFilesComboSelect;
} }
public string GetAssembleNameByFileName(string fileName) public string GetAssembleNameByFileName(string fileName)
{ {
var file = driverFiles.Where(f => Path.GetFileName(f) == fileName).SingleOrDefault(); var file = _driverFiles.SingleOrDefault(f => Path.GetFileName(f) == fileName);
var dll = Assembly.LoadFrom(file); var dll = Assembly.LoadFrom(file);
var type = dll.GetTypes().Where(x => typeof(IDriver).IsAssignableFrom(x) && x.IsClass).FirstOrDefault(); var type = dll.GetTypes().FirstOrDefault(x => typeof(IDriver).IsAssignableFrom(x) && x.IsClass);
return type.FullName; return type?.FullName;
} }
public void AddConfigs(Guid? dapID, Guid? DriverId)
public void AddConfigs(Guid? dapId, Guid? driverId)
{ {
using (var DC = new DataContext(IoTBackgroundService.connnectSetting, IoTBackgroundService.DBType)) using var dc = new DataContext(IoTBackgroundService.connnectSetting, IoTBackgroundService.DbType);
{ var device = dc.Set<Device>().Where(x => x.ID == dapId).AsNoTracking().SingleOrDefault();
var device = DC.Set<Device>().Where(x => x.ID == dapID).AsNoTracking().SingleOrDefault(); var driver = dc.Set<Driver>().Where(x => x.ID == driverId).AsNoTracking().SingleOrDefault();
var driver = DC.Set<Driver>().Where(x => x.ID == DriverId).AsNoTracking().SingleOrDefault(); var type = DriverInfos.SingleOrDefault(x => x.Type.FullName == driver?.AssembleName);
var type = DriverInfos.Where(x => x.Type.FullName == driver.AssembleName).SingleOrDefault();
Type[] types = new Type[2] { typeof(string), typeof(ILogger) }; Type[] types = { typeof(string), typeof(ILogger) };
object[] param = new object[2] { device.DeviceName, _logger }; object[] param = { device?.DeviceName, _logger };
ConstructorInfo constructor = type.Type.GetConstructor(types); ConstructorInfo? constructor = type?.Type.GetConstructor(types);
var iObj = constructor.Invoke(param) as IDriver; var iObj = constructor?.Invoke(param) as IDriver;
foreach (var property in type.Type.GetProperties()) foreach (var property in type?.Type.GetProperties())
{ {
var config = property.GetCustomAttribute(typeof(ConfigParameterAttribute)); var config = property.GetCustomAttribute(typeof(ConfigParameterAttribute));
if (config != null) if (config != null)
{ {
var DapConfig = new DeviceConfig var dapConfig = new DeviceConfig
{ {
ID = Guid.NewGuid(), ID = Guid.NewGuid(),
DeviceId = dapID, DeviceId = dapId,
DeviceConfigName = property.Name, DeviceConfigName = property.Name,
DataSide = DataSide.AnySide, DataSide = DataSide.AnySide,
Description = ((ConfigParameterAttribute)config).Description, Description = ((ConfigParameterAttribute)config).Description,
@ -105,20 +100,21 @@ namespace Plugin
if (property.PropertyType.BaseType == typeof(Enum)) if (property.PropertyType.BaseType == typeof(Enum))
{ {
var fields = property.PropertyType.GetFields(BindingFlags.Static | BindingFlags.Public); var fields = property.PropertyType.GetFields(BindingFlags.Static | BindingFlags.Public);
var EnumInfos = fields.ToDictionary(f => f.Name, f => (int)f.GetValue(null)); var enumInfos = fields.ToDictionary(f => f.Name, f => (int)f.GetValue(null));
DapConfig.EnumInfo = JsonSerializer.Serialize(EnumInfos); dapConfig.EnumInfo = JsonSerializer.Serialize(enumInfos);
} }
DC.Set<DeviceConfig>().Add(DapConfig); dc.Set<DeviceConfig>().Add(dapConfig);
} }
} }
DC.SaveChanges();
} dc.SaveChanges();
} }
public void LoadAllDrivers() public void LoadAllDrivers()
{ {
_logger.LogInformation("LoadAllDrivers Start"); _logger.LogInformation("LoadAllDrivers Start");
foreach (var file in driverFiles) foreach (var file in _driverFiles)
{ {
try try
{ {
@ -138,19 +134,16 @@ namespace Plugin
{ {
_logger.LogDebug($"LoadAllDrivers Error {ex}"); _logger.LogDebug($"LoadAllDrivers Error {ex}");
} }
} }
_logger.LogInformation($"LoadAllDrivers End,Count{DriverInfos.Count}");
_logger.LogInformation($"LoadAllDrivers End,Count{DriverInfos.Count}");
} }
public void LoadRegestedDeviers() public void LoadRegestedDeviers()
{ {
using (var DC = new DataContext(IoTBackgroundService.connnectSetting, IoTBackgroundService.DBType)) using var dc = new DataContext(IoTBackgroundService.connnectSetting, IoTBackgroundService.DbType);
{
var Drivers = DC.Set<Driver>().AsNoTracking().ToList();
var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"drivers/net5.0"); var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"drivers/net6.0");
var files = Directory.GetFiles(path).Where(x => Path.GetExtension(x) == ".dll").ToArray(); var files = Directory.GetFiles(path).Where(x => Path.GetExtension(x) == ".dll").ToArray();
foreach (var file in files) foreach (var file in files)
{ {
@ -168,4 +161,3 @@ namespace Plugin
} }
} }
} }
}

View File

@ -1,44 +1,36 @@
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using WalkingTec.Mvvm.Core; using WalkingTec.Mvvm.Core;
namespace Plugin namespace Plugin
{ {
public class IoTBackgroundService : BackgroundService public class IoTBackgroundService : BackgroundService
{ {
public static DBTypeEnum DBType; public static DBTypeEnum DbType;
public static string connnectSetting; public static string connnectSetting;
public static Guid? VariableSelectDeviceId, ConfigSelectDeviceId; public static Guid? VariableSelectDeviceId, ConfigSelectDeviceId;
public IoTBackgroundService(IConfiguration ConfigRoot) public IoTBackgroundService(IConfiguration configRoot)
{ {
var connnectSettings = new List<ConnnectSettingsModel>(); var connnectSettings = new List<ConnnectSettingsModel>();
ConfigRoot.Bind("Connections", connnectSettings); configRoot.Bind("Connections", connnectSettings);
connnectSetting = connnectSettings[0].Value; connnectSetting = connnectSettings[0].Value;
switch (connnectSettings[0].DBType.Trim().ToLower()) switch (connnectSettings[0].DbType?.Trim().ToLower())
{ {
case "oracle": case "oracle":
DBType = DBTypeEnum.Oracle; DbType = DBTypeEnum.Oracle;
break; break;
case "mysql": case "mysql":
DBType = DBTypeEnum.MySql; DbType = DBTypeEnum.MySql;
break; break;
case "pgsql": case "pgsql":
DBType = DBTypeEnum.PgSql; DbType = DBTypeEnum.PgSql;
break; break;
case "sqlite": case "sqlite":
DBType = DBTypeEnum.SQLite; DbType = DBTypeEnum.SQLite;
break; break;
case "memory": case "memory":
DBType = DBTypeEnum.Memory; DbType = DBTypeEnum.Memory;
break;
default:
break; break;
} }
} }

View File

@ -1,24 +1,19 @@
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Modbus.Data; using Modbus.Data;
using Modbus.Device; using Modbus.Device;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net; using System.Net;
using System.Net.Sockets; using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace Plugin namespace Plugin
{ {
public class ModbusSlaveService : IDisposable public class ModbusSlaveService : IDisposable
{ {
private readonly ILogger<ModbusSlaveService> _logger; private readonly ILogger<ModbusSlaveService> _logger;
TcpListener slaveTcpListener; readonly TcpListener _slaveTcpListener;
private Timer m_simulationTimer; private readonly Timer _mSimulationTimer;
private object Lock=new object(); private readonly object _lock = new();
private ModbusSlave slave; private readonly ModbusSlave _slave;
private Task task { get; set; } = null; private Task _task;
public ModbusSlaveService(ILogger<ModbusSlaveService> logger) public ModbusSlaveService(ILogger<ModbusSlaveService> logger)
{ {
_logger = logger; _logger = logger;
@ -27,12 +22,12 @@ namespace Plugin
IPAddress address = IPAddress.Any; IPAddress address = IPAddress.Any;
// create and start the TCP slave // create and start the TCP slave
slaveTcpListener = new TcpListener(address, port); _slaveTcpListener = new TcpListener(address, port);
slaveTcpListener.Start(); _slaveTcpListener.Start();
slave = ModbusTcpSlave.CreateTcp(slaveId, slaveTcpListener); _slave = ModbusTcpSlave.CreateTcp(slaveId, _slaveTcpListener);
slave.DataStore = DataStoreFactory.CreateDefaultDataStore(); _slave.DataStore = DataStoreFactory.CreateDefaultDataStore();
slave.ListenAsync(); _slave.ListenAsync();
m_simulationTimer = new Timer(DoSimulation, null, 1000, 1000); _mSimulationTimer = new Timer(DoSimulation, null, 1000, 1000);
_logger.LogInformation($"Modbus Server Started"); _logger.LogInformation($"Modbus Server Started");
} }
@ -40,19 +35,19 @@ namespace Plugin
{ {
try try
{ {
lock (Lock) lock (_lock)
{ {
for (int i = 1; i <= 20; i++) for (int i = 1; i <= 20; i++)
{ {
if (i != 1 || i != 2 || i != 7) if (i != 1 || i != 2 || i != 7)
slave.DataStore.HoldingRegisters[i] = (ushort)new Random().Next(0, short.MaxValue); _slave.DataStore.HoldingRegisters[i] = (ushort)new Random().Next(0, short.MaxValue);
slave.DataStore.InputRegisters[i] = (ushort)new Random().Next(0, short.MaxValue); _slave.DataStore.InputRegisters[i] = (ushort)new Random().Next(0, short.MaxValue);
slave.DataStore.CoilDiscretes[i] = new Random().Next() % 2 == 0; _slave.DataStore.CoilDiscretes[i] = new Random().Next() % 2 == 0;
slave.DataStore.InputDiscretes[i] = new Random().Next() % 2 == 0; _slave.DataStore.InputDiscretes[i] = new Random().Next() % 2 == 0;
} }
slave.DataStore.HoldingRegisters[1] = (ushort)new Random().Next(2000,3000); //前端要用的温度 _slave.DataStore.HoldingRegisters[1] = (ushort)new Random().Next(2000, 3000); //前端要用的温度
slave.DataStore.HoldingRegisters[2] = (ushort)new Random().Next(4000, 7000);//湿度 _slave.DataStore.HoldingRegisters[2] = (ushort)new Random().Next(4000, 7000);//湿度
slave.DataStore.HoldingRegisters[7] = (ushort)new Random().Next(0, 10000);//随机值 _slave.DataStore.HoldingRegisters[7] = (ushort)new Random().Next(0, 10000);//随机值
} }
} }
catch (Exception ex) catch (Exception ex)
@ -63,8 +58,8 @@ namespace Plugin
public void Dispose() public void Dispose()
{ {
_logger.LogError($"Modbus Server Dispose"); _logger.LogError($"Modbus Server Dispose");
m_simulationTimer.Dispose(); _mSimulationTimer.Dispose();
slaveTcpListener.Stop(); _slaveTcpListener.Stop();
} }
} }
} }

View File

@ -10,6 +10,7 @@ using MQTTnet.Client.Receiving;
using MQTTnet.Protocol; using MQTTnet.Protocol;
using Newtonsoft.Json; using Newtonsoft.Json;
using PluginInterface; using PluginInterface;
using PluginInterface.HuaWeiRoma;
using PluginInterface.IotDB; using PluginInterface.IotDB;
using PluginInterface.IoTSharp; using PluginInterface.IoTSharp;
using PluginInterface.ThingsBoard; using PluginInterface.ThingsBoard;
@ -20,14 +21,15 @@ namespace Plugin
public class MyMqttClient public class MyMqttClient
{ {
private readonly ILogger<MyMqttClient> _logger; private readonly ILogger<MyMqttClient> _logger;
private readonly ReferenceNodeManager _uaNodeManager = null; private readonly ReferenceNodeManager? _uaNodeManager;
private SystemConfig? _systemConfig; private SystemConfig? _systemConfig;
private IMqttClientOptions clientOptions; private IMqttClientOptions _clientOptions;
public bool IsConnected => (Client?.IsConnected).GetValueOrDefault(); public bool IsConnected => (Client.IsConnected);
private IMqttClient Client { get; set; } private IMqttClient Client { get; set; }
public event EventHandler<RpcRequest> OnExcRpc; public event EventHandler<RpcRequest> OnExcRpc;
public event EventHandler<ISAttributeResponse> OnReceiveAttributes; public event EventHandler<ISAttributeResponse> OnReceiveAttributes;
public MyMqttClient(UAService uaService, ILogger<MyMqttClient> logger) public MyMqttClient(UAService uaService, ILogger<MyMqttClient> logger)
{ {
_logger = logger; _logger = logger;
@ -35,81 +37,82 @@ namespace Plugin
ConnectAsync(); ConnectAsync();
} }
public async Task<bool> ConnectAsync() public async Task ConnectAsync()
{ {
bool initok = false;
try try
{ {
using (var DC = new DataContext(IoTBackgroundService.connnectSetting, IoTBackgroundService.DBType)) await using var dc = new DataContext(IoTBackgroundService.connnectSetting, IoTBackgroundService.DbType);
{ _systemConfig = dc.Set<SystemConfig>().FirstOrDefault();
_systemConfig = DC.Set<SystemConfig>().FirstOrDefault();
if (_systemConfig == null) if (_systemConfig == null)
{ {
_systemConfig = new SystemConfig() _systemConfig = new SystemConfig()
{ {
ID = Guid.NewGuid(), ID = Guid.NewGuid(),
GatewayName = "iotgateway", GatewayName = "iotgateway",
ClientId = Guid.NewGuid().ToString(),
MqttIp = "localhost", MqttIp = "localhost",
MqttPort = 1888, MqttPort = 1888,
MqttUName = "user", MqttUName = "user",
MqttUPwd = "pwd", MqttUPwd = "pwd",
IoTPlatformType = IoTPlatformType.IoTSharp IoTPlatformType = IoTPlatformType.IoTSharp
}; };
DC.Set<SystemConfig>().Add(_systemConfig); dc.Set<SystemConfig>().Add(_systemConfig);
DC.SaveChanges(); await dc.SaveChangesAsync();
} }
var factory = new MqttFactory(); var factory = new MqttFactory();
Client = (MqttClient)factory.CreateMqttClient(); Client = (MqttClient)factory.CreateMqttClient();
clientOptions = new MqttClientOptionsBuilder() _clientOptions = new MqttClientOptionsBuilder()
.WithClientId(_systemConfig.GatewayName + Guid.NewGuid().ToString()) .WithClientId(_systemConfig.ClientId ?? Guid.NewGuid().ToString())
.WithTcpServer(_systemConfig.MqttIp, _systemConfig.MqttPort) .WithTcpServer(_systemConfig.MqttIp, _systemConfig.MqttPort)
.WithCredentials(_systemConfig.MqttUName, _systemConfig.MqttUPwd) .WithCredentials(_systemConfig.MqttUName, _systemConfig.MqttUPwd)
.WithCommunicationTimeout(TimeSpan.FromSeconds(30)) .WithCommunicationTimeout(TimeSpan.FromSeconds(30))
.WithKeepAlivePeriod(TimeSpan.FromSeconds(20)) .WithKeepAlivePeriod(TimeSpan.FromSeconds(20))
.Build(); .Build();
Client.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(Client_ApplicationMessageReceived); Client.ApplicationMessageReceivedHandler =
Client.ConnectedHandler = new MqttClientConnectedHandlerDelegate(x => OnConnected()); new MqttApplicationMessageReceivedHandlerDelegate(Client_ApplicationMessageReceived);
Client.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(x => OnDisconnectedAsync()); Client.ConnectedHandler = new MqttClientConnectedHandlerDelegate(_ => OnConnected());
Client.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(_ => OnDisconnectedAsync());
try try
{ {
Client.ConnectAsync(clientOptions); await Client.ConnectAsync(_clientOptions);
initok = true;
} }
catch (Exception exception) catch (Exception ex)
{ {
_logger.LogError("MQTT CONNECTING FAILED", exception); _logger.LogError("MQTT CONNECTING FAILED", ex);
} }
_logger.LogInformation("MQTT WAITING FOR APPLICATION MESSAGES"); _logger.LogInformation("MQTT WAITING FOR APPLICATION MESSAGES");
} }
} catch (Exception ex)
catch (Exception exception)
{ {
_logger.LogError("MQTT CONNECTING FAILED", exception); _logger.LogError("MQTT CONNECTING FAILED", ex);
} }
return initok;
} }
private async Task OnDisconnectedAsync() private async Task OnDisconnectedAsync()
{ {
try try
{ {
await Client.ConnectAsync(clientOptions); await Client.ConnectAsync(_clientOptions);
} }
catch (Exception exception) catch (Exception ex)
{ {
_logger.LogError("MQTT CONNECTING FAILED", exception); _logger.LogError("MQTT CONNECTING FAILED", ex);
} }
} }
private readonly string tbRpcTopic = "v1/gateway/rpc"; private readonly string _tbRpcTopic = "v1/gateway/rpc";
private void OnConnected() private void OnConnected()
{ {
if (_systemConfig != null)
switch (_systemConfig.IoTPlatformType) switch (_systemConfig.IoTPlatformType)
{ {
case IoTPlatformType.ThingsBoard: case IoTPlatformType.ThingsBoard:
//{"device": "Device A", "data": {"id": $request_id, "method": "toggle_gpio", "params": {"pin":1}}} //{"device": "Device A", "data": {"id": $request_id, "method": "toggle_gpio", "params": {"pin":1}}}
Client.SubscribeAsync(tbRpcTopic, MqttQualityOfServiceLevel.ExactlyOnce); Client.SubscribeAsync(_tbRpcTopic, MqttQualityOfServiceLevel.ExactlyOnce);
//Message: {"id": $request_id, "device": "Device A", "value": "value1"} //Message: {"id": $request_id, "device": "Device A", "value": "value1"}
Client.SubscribeAsync("v1/gateway/attributes/response", MqttQualityOfServiceLevel.ExactlyOnce); Client.SubscribeAsync("v1/gateway/attributes/response", MqttQualityOfServiceLevel.ExactlyOnce);
//Message: {"device": "Device A", "data": {"attribute1": "value1", "attribute2": 42}} //Message: {"device": "Device A", "data": {"attribute1": "value1", "attribute2": 42}}
@ -136,25 +139,27 @@ namespace Plugin
break; break;
case IoTPlatformType.OneNET: case IoTPlatformType.OneNET:
break; break;
default:
break;
} }
_logger.LogInformation($"MQTT CONNECTED WITH SERVER "); _logger.LogInformation($"MQTT CONNECTED WITH SERVER ");
} }
private Task Client_ApplicationMessageReceived(MqttApplicationMessageReceivedEventArgs e) private Task Client_ApplicationMessageReceived(MqttApplicationMessageReceivedEventArgs e)
{ {
_logger.LogDebug($"ApplicationMessageReceived Topic {e.ApplicationMessage.Topic} QualityOfServiceLevel:{e.ApplicationMessage.QualityOfServiceLevel} Retain:{e.ApplicationMessage.Retain} "); _logger.LogDebug(
$"ApplicationMessageReceived Topic {e.ApplicationMessage.Topic} QualityOfServiceLevel:{e.ApplicationMessage.QualityOfServiceLevel} Retain:{e.ApplicationMessage.Retain} ");
try try
{ {
if (e.ApplicationMessage.Topic == tbRpcTopic) if (e.ApplicationMessage.Topic == _tbRpcTopic)
ReceiveTbRpc(e); ReceiveTbRpc(e);
else if (e.ApplicationMessage.Topic.StartsWith($"devices/") && e.ApplicationMessage.Topic.Contains("/response/")) else if (e.ApplicationMessage.Topic.StartsWith($"devices/") &&
e.ApplicationMessage.Topic.Contains("/response/"))
{ {
ReceiveAttributes(e); ReceiveAttributes(e);
} }
else if (e.ApplicationMessage.Topic.StartsWith($"devices/") && e.ApplicationMessage.Topic.Contains("/rpc/request/")) else if (e.ApplicationMessage.Topic.StartsWith($"devices/") &&
e.ApplicationMessage.Topic.Contains("/rpc/request/"))
{ {
ReceiveIsRpc(e); ReceiveIsRpc(e);
} }
@ -165,8 +170,11 @@ namespace Plugin
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError($"ClientId:{e.ClientId} Topic:{e.ApplicationMessage.Topic},Payload:{e.ApplicationMessage.ConvertPayloadToString()}", ex); _logger.LogError(
$"ClientId:{e.ClientId} Topic:{e.ApplicationMessage.Topic},Payload:{e.ApplicationMessage.ConvertPayloadToString()}",
ex);
} }
return Task.CompletedTask; return Task.CompletedTask;
} }
@ -176,13 +184,13 @@ namespace Plugin
/// <param name="e"></param> /// <param name="e"></param>
private void ReceiveTbRpc(MqttApplicationMessageReceivedEventArgs e) private void ReceiveTbRpc(MqttApplicationMessageReceivedEventArgs e)
{ {
TBRpcRequest tBRpcRequest;
try try
{ {
tBRpcRequest = JsonConvert.DeserializeObject<TBRpcRequest>(e.ApplicationMessage.ConvertPayloadToString()); var tBRpcRequest =
if (!string.IsNullOrWhiteSpace(tBRpcRequest.RequestData.Method)) JsonConvert.DeserializeObject<TBRpcRequest>(e.ApplicationMessage.ConvertPayloadToString());
if (tBRpcRequest != null && !string.IsNullOrWhiteSpace(tBRpcRequest.RequestData.Method))
{ {
OnExcRpc?.Invoke(Client, new RpcRequest() OnExcRpc(Client, new RpcRequest()
{ {
Method = tBRpcRequest.RequestData.Method, Method = tBRpcRequest.RequestData.Method,
DeviceName = tBRpcRequest.DeviceName, DeviceName = tBRpcRequest.DeviceName,
@ -193,9 +201,10 @@ namespace Plugin
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError($"ReceiveTbRpc:Topic:{e.ApplicationMessage.Topic},Payload:{e.ApplicationMessage.ConvertPayloadToString()}", ex); _logger.LogError(
$"ReceiveTbRpc:Topic:{e.ApplicationMessage.Topic},Payload:{e.ApplicationMessage.ConvertPayloadToString()}",
ex);
} }
} }
/// <summary> /// <summary>
@ -204,11 +213,12 @@ namespace Plugin
/// <param name="e"></param> /// <param name="e"></param>
private void ReceiveTcRpc(MqttApplicationMessageReceivedEventArgs e) private void ReceiveTcRpc(MqttApplicationMessageReceivedEventArgs e)
{ {
TCRpcRequest tCRpcRequest;
try try
{ {
tCRpcRequest = JsonConvert.DeserializeObject<TCRpcRequest>(e.ApplicationMessage.ConvertPayloadToString()); var tCRpcRequest =
OnExcRpc?.Invoke(Client, new RpcRequest() JsonConvert.DeserializeObject<TCRpcRequest>(e.ApplicationMessage.ConvertPayloadToString());
if (tCRpcRequest != null)
OnExcRpc.Invoke(Client, new RpcRequest()
{ {
Method = tCRpcRequest.RequestData.Method, Method = tCRpcRequest.RequestData.Method,
DeviceName = tCRpcRequest.DeviceName, DeviceName = tCRpcRequest.DeviceName,
@ -218,62 +228,66 @@ namespace Plugin
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError($"ReceiveTbRpc:Topic:{e.ApplicationMessage.Topic},Payload:{e.ApplicationMessage.ConvertPayloadToString()}", ex); _logger.LogError(
$"ReceiveTbRpc:Topic:{e.ApplicationMessage.Topic},Payload:{e.ApplicationMessage.ConvertPayloadToString()}",
ex);
}
} }
}
private void ReceiveIsRpc(MqttApplicationMessageReceivedEventArgs e) private void ReceiveIsRpc(MqttApplicationMessageReceivedEventArgs e)
{ {
try try
{ {
var tps = e.ApplicationMessage.Topic.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries); var tps = e.ApplicationMessage.Topic.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
var rpcmethodname = tps[4]; var rpcMethodName = tps[4];
var rpcdevicename = tps[1]; var rpcDeviceName = tps[1];
var rpcrequestid = tps[5]; var rpcRequestId = tps[5];
_logger.LogInformation($"rpcmethodname={rpcmethodname} "); _logger.LogInformation($"rpcMethodName={rpcMethodName} ");
_logger.LogInformation($"rpcdevicename={rpcdevicename } "); _logger.LogInformation($"rpcDeviceName={rpcDeviceName} ");
_logger.LogInformation($"rpcrequestid={rpcrequestid} "); _logger.LogInformation($"rpcRequestId={rpcRequestId} ");
if (!string.IsNullOrEmpty(rpcmethodname) && !string.IsNullOrEmpty(rpcdevicename) && !string.IsNullOrEmpty(rpcrequestid)) if (!string.IsNullOrEmpty(rpcMethodName) && !string.IsNullOrEmpty(rpcDeviceName) &&
!string.IsNullOrEmpty(rpcRequestId))
{ {
OnExcRpc?.Invoke(Client, new RpcRequest() OnExcRpc(Client, new RpcRequest()
{ {
Method = rpcmethodname, Method = rpcMethodName,
DeviceName = rpcdevicename, DeviceName = rpcDeviceName,
RequestId = rpcrequestid, RequestId = rpcRequestId,
Params = JsonConvert.DeserializeObject<Dictionary<string, object>>(e.ApplicationMessage.ConvertPayloadToString()) Params = JsonConvert.DeserializeObject<Dictionary<string, object>>(e.ApplicationMessage
.ConvertPayloadToString())
}); });
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError($"ReceiveIsRpc:Topic:{e.ApplicationMessage.Topic},Payload:{e.ApplicationMessage.ConvertPayloadToString()}", ex); _logger.LogError(
$"ReceiveIsRpc:Topic:{e.ApplicationMessage.Topic},Payload:{e.ApplicationMessage.ConvertPayloadToString()}",
ex);
}
} }
} private async Task ResponseTbRpcAsync(TBRpcResponse tBRpcResponse)
private Task ResponseTBRpc(TBRpcResponse tBRpcResponse)
{ {
return Client.PublishAsync(new MqttApplicationMessageBuilder() await Client.PublishAsync(new MqttApplicationMessageBuilder()
.WithTopic(tbRpcTopic) .WithTopic(_tbRpcTopic)
.WithPayload(JsonConvert.SerializeObject(tBRpcResponse)) .WithPayload(JsonConvert.SerializeObject(tBRpcResponse))
.WithQualityOfServiceLevel(MqttQualityOfServiceLevel.ExactlyOnce).Build()); .WithQualityOfServiceLevel(MqttQualityOfServiceLevel.ExactlyOnce).Build());
} }
private Task ResponseTCRpc(TCRpcRequest tCRpcResponse) private async Task ResponseTcRpcAsync(TCRpcRequest tCRpcResponse)
{ {
string topic = $"command/reply/{tCRpcResponse.RequestData.RequestId}"; var topic = $"command/reply/{tCRpcResponse.RequestData.RequestId}";
return Client.PublishAsync(new MqttApplicationMessageBuilder() await Client.PublishAsync(new MqttApplicationMessageBuilder()
.WithTopic(topic) .WithTopic(topic)
.WithPayload(JsonConvert.SerializeObject(tCRpcResponse)) .WithPayload(JsonConvert.SerializeObject(tCRpcResponse))
.WithQualityOfServiceLevel(MqttQualityOfServiceLevel.ExactlyOnce).Build()); .WithQualityOfServiceLevel(MqttQualityOfServiceLevel.ExactlyOnce).Build());
} }
private Task ResponseISRpc(ISRpcResponse rpcResult) private async Task ResponseIsRpcAsync(ISRpcResponse rpcResult)
{ {
///IoTSharp/Clients/RpcClient.cs#L65 var responseTopic = $"/devices/{deviceid}/rpc/response/{methodName}/{rpcid}"; //var responseTopic = $"/devices/{deviceid}/rpc/response/{methodName}/{rpcid}";
string topic = $"devices/{rpcResult.DeviceId}/rpc/response/{rpcResult.Method}/{rpcResult.ResponseId}"; var topic = $"devices/{rpcResult.DeviceId}/rpc/response/{rpcResult.Method}/{rpcResult.ResponseId}";
return Client.PublishAsync(new MqttApplicationMessageBuilder() await Client.PublishAsync(new MqttApplicationMessageBuilder()
.WithTopic(topic) .WithTopic(topic)
.WithPayload(JsonConvert.SerializeObject(rpcResult)) .WithPayload(JsonConvert.SerializeObject(rpcResult))
.WithQualityOfServiceLevel(MqttQualityOfServiceLevel.ExactlyOnce).Build()); .WithQualityOfServiceLevel(MqttQualityOfServiceLevel.ExactlyOnce).Build());
@ -281,61 +295,96 @@ namespace Plugin
private void ReceiveAttributes(MqttApplicationMessageReceivedEventArgs e) private void ReceiveAttributes(MqttApplicationMessageReceivedEventArgs e)
{ {
var tps = e.ApplicationMessage.Topic.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries); var tps = e.ApplicationMessage.Topic.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
var rpcmethodname = tps[2]; var rpcMethodName = tps[2];
var rpcdevicename = tps[1]; var rpcDeviceName = tps[1];
var rpcrequestid = tps[4]; var rpcRequestId = tps[4];
_logger.LogInformation($"rpcmethodname={rpcmethodname} "); _logger.LogInformation($"rpcMethodName={rpcMethodName}");
_logger.LogInformation($"rpcdevicename={rpcdevicename } "); _logger.LogInformation($"rpcDeviceName={rpcDeviceName}");
_logger.LogInformation($"rpcrequestid={rpcrequestid} "); _logger.LogInformation($"rpcRequestId={rpcRequestId}");
if (!string.IsNullOrEmpty(rpcmethodname) && !string.IsNullOrEmpty(rpcdevicename) && !string.IsNullOrEmpty(rpcrequestid)) if (!string.IsNullOrEmpty(rpcMethodName) && !string.IsNullOrEmpty(rpcDeviceName) &&
!string.IsNullOrEmpty(rpcRequestId))
{ {
if (e.ApplicationMessage.Topic.Contains("/attributes/")) if (e.ApplicationMessage.Topic.Contains("/attributes/"))
{ {
OnReceiveAttributes?.Invoke(Client, new ISAttributeResponse() OnReceiveAttributes.Invoke(Client, new ISAttributeResponse()
{ {
KeyName = rpcmethodname, KeyName = rpcMethodName,
DeviceName = rpcdevicename, DeviceName = rpcDeviceName,
Id = rpcrequestid, Id = rpcRequestId,
Data = e.ApplicationMessage.ConvertPayloadToString() Data = e.ApplicationMessage.ConvertPayloadToString()
}); });
} }
} }
} }
public Task UploadAttributeAsync(string _devicename, object obj) public Task UploadAttributeAsync(string deviceName, object obj)
{ {
//Topic: v1/gateway/attributes //Topic: v1/gateway/attributes
//Message: {"Device A":{"attribute1":"value1", "attribute2": 42}, "Device B":{"attribute1":"value1", "attribute2": 42} //Message: {"Device A":{"attribute1":"value1", "attribute2": 42}, "Device B":{"attribute1":"value1", "attribute2": 42}
try try
{ {
if (Client.IsConnected) if (Client.IsConnected)
return Client.PublishAsync(new MqttApplicationMessageBuilder().WithTopic($"devices/{_devicename}/attributes").WithPayload(Newtonsoft.Json.JsonConvert.SerializeObject(obj)).Build()); return Client.PublishAsync(new MqttApplicationMessageBuilder()
.WithTopic($"devices/{deviceName}/attributes").WithPayload(JsonConvert.SerializeObject(obj))
.Build());
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError($"Device:{_devicename} UploadAttributeAsync Failed,{ex}"); _logger.LogError($"Device:{deviceName} UploadAttributeAsync Failed,{ex}");
} }
return Task.CompletedTask; return Task.CompletedTask;
} }
public Task UploadISTelemetryDataAsync(string _devicename, object obj) public async Task UploadIsTelemetryDataAsync(string deviceName, object obj)
{ {
return Client.PublishAsync(new MqttApplicationMessageBuilder().WithTopic($"devices/{_devicename}/telemetry").WithPayload(Newtonsoft.Json.JsonConvert.SerializeObject(obj)).Build()); await Client.PublishAsync(new MqttApplicationMessageBuilder().WithTopic($"devices/{deviceName}/telemetry")
.WithPayload(JsonConvert.SerializeObject(obj)).Build());
} }
public Task UploadTCTelemetryDataAsync(string _devicename, object obj) public async Task UploadTcTelemetryDataAsync(string deviceName, object obj)
{ {
var toSend = new Dictionary<string, object> { { _devicename, obj } }; var toSend = new Dictionary<string, object> { { deviceName, obj } };
return Client.PublishAsync("gateway/attributes", JsonConvert.SerializeObject(toSend)); await Client.PublishAsync("gateway/attributes", JsonConvert.SerializeObject(toSend));
} }
public void ResponseRpc(RpcResponse rpcResponse) public async Task UploadHwTelemetryDataAsync(Device device, object obj)
{
var hwTelemetry = new List<HwTelemetry>()
{
new HwTelemetry()
{
DeviceId = device.DeviceConfigs.FirstOrDefault(x => x.DeviceConfigName == "DeviceId")?.Value,
Services = new()
{
new Service()
{
ServiceId = "serviceId",
EventTime = DateTime.Now.ToString("yyyyMMddTHHmmssZ"),
Data = new Dictionary<string, object>()
{
{ "data", obj }
}
}
}
}
};
var hwTelemetrys = new HwTelemetrys()
{
Devices = hwTelemetry
};
await Client.PublishAsync($"/v1/devices/{_systemConfig?.GatewayName}/datas",
JsonConvert.SerializeObject(hwTelemetrys));
}
public async Task ResponseRpcAsync(RpcResponse rpcResponse)
{ {
try try
{ {
if (_systemConfig != null)
switch (_systemConfig.IoTPlatformType) switch (_systemConfig.IoTPlatformType)
{ {
case IoTPlatformType.ThingsBoard: case IoTPlatformType.ThingsBoard:
@ -343,17 +392,21 @@ namespace Plugin
{ {
DeviceName = rpcResponse.DeviceName, DeviceName = rpcResponse.DeviceName,
RequestId = rpcResponse.RequestId, RequestId = rpcResponse.RequestId,
ResponseData = new Dictionary<string, object> { { "success", rpcResponse.IsSuccess }, { "description", rpcResponse.Description } } ResponseData = new Dictionary<string, object>
{ { "success", rpcResponse.IsSuccess }, { "description", rpcResponse.Description } }
}; };
ResponseTBRpc(tRpcResponse); await ResponseTbRpcAsync(tRpcResponse);
break; break;
case IoTPlatformType.IoTSharp: case IoTPlatformType.IoTSharp:
ResponseISRpc(new ISRpcResponse await ResponseIsRpcAsync(new ISRpcResponse
{ {
DeviceId = rpcResponse.DeviceName, DeviceId = rpcResponse.DeviceName,
Method = "Method", Method = "Method",
ResponseId = rpcResponse.RequestId, ResponseId = rpcResponse.RequestId,
Data = JsonConvert.SerializeObject(new Dictionary<string, object> { { "success", rpcResponse.IsSuccess }, { "description", rpcResponse.Description } }) Data = JsonConvert.SerializeObject(new Dictionary<string, object>
{
{ "success", rpcResponse.IsSuccess }, { "description", rpcResponse.Description }
})
}); });
break; break;
case IoTPlatformType.ThingsCloud: case IoTPlatformType.ThingsCloud:
@ -367,22 +420,20 @@ namespace Plugin
break; break;
case IoTPlatformType.OneNET: case IoTPlatformType.OneNET:
break; break;
default:
break;
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError($"ResponseRpc Error,{rpcResponse}", ex); _logger.LogError($"ResponseRpc Error,{rpcResponse}", ex);
} }
} }
public Task RequestAttributes(string _devicename, bool anySide, params string[] args) public async Task RequestAttributes(string deviceName, bool anySide, params string[] args)
{ {
try try
{ {
string id = Guid.NewGuid().ToString(); string id = Guid.NewGuid().ToString();
if (_systemConfig != null)
switch (_systemConfig.IoTPlatformType) switch (_systemConfig.IoTPlatformType)
{ {
case IoTPlatformType.ThingsBoard: case IoTPlatformType.ThingsBoard:
@ -390,17 +441,22 @@ namespace Plugin
Dictionary<string, object> tbRequestData = new Dictionary<string, object> Dictionary<string, object> tbRequestData = new Dictionary<string, object>
{ {
{ "id", id }, { "id", id },
{ "device",_devicename}, { "device", deviceName },
{ "client", true }, { "client", true },
{ "key", args[0] } { "key", args[0] }
}; };
return Client.PublishAsync("v1/gateway/attributes/request", JsonConvert.SerializeObject(tbRequestData), MqttQualityOfServiceLevel.ExactlyOnce); await Client.PublishAsync("v1/gateway/attributes/request",
JsonConvert.SerializeObject(tbRequestData), MqttQualityOfServiceLevel.ExactlyOnce);
break;
case IoTPlatformType.IoTSharp: case IoTPlatformType.IoTSharp:
string topic = $"devices/{_devicename}/attributes/request/{id}"; string topic = $"devices/{deviceName}/attributes/request/{id}";
Dictionary<string, string> keys = new Dictionary<string, string>(); Dictionary<string, string> keys = new Dictionary<string, string>();
keys.Add(anySide ? "anySide" : "server", string.Join(",", args)); keys.Add(anySide ? "anySide" : "server", string.Join(",", args));
Client.SubscribeAsync($"devices/{_devicename}/attributes/response/{id}", MqttQualityOfServiceLevel.ExactlyOnce); await Client.SubscribeAsync($"devices/{deviceName}/attributes/response/{id}",
return Client.PublishAsync(topic, JsonConvert.SerializeObject(keys), MqttQualityOfServiceLevel.ExactlyOnce); MqttQualityOfServiceLevel.ExactlyOnce);
await Client.PublishAsync(topic, JsonConvert.SerializeObject(keys),
MqttQualityOfServiceLevel.ExactlyOnce);
break;
case IoTPlatformType.AliCloudIoT: case IoTPlatformType.AliCloudIoT:
break; break;
case IoTPlatformType.TencentIoTHub: case IoTPlatformType.TencentIoTHub:
@ -409,33 +465,29 @@ namespace Plugin
break; break;
case IoTPlatformType.OneNET: case IoTPlatformType.OneNET:
break; break;
default:
break;
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError($"RequestAttributes:{deviceName}", ex);
_logger.LogError($"RequestAttributes:{_devicename}", ex);
} }
return Task.CompletedTask;
} }
private Dictionary<string, List<PayLoad>> LastTelemetrys = new(0); private Dictionary<string, List<PayLoad>> _lastTelemetrys = new(0);
/// <summary> /// <summary>
/// 判断是否推送遥测数据 /// 判断是否推送遥测数据
/// </summary> /// </summary>
/// <param name="device">设备</param> /// <param name="device">设备</param>
/// <param name="SendModel">遥测</param> /// <param name="sendModel">遥测</param>
/// <returns></returns> /// <returns></returns>
private bool CanPubTelemetry(Device device, Dictionary<string, List<PayLoad>> SendModel) private bool CanPubTelemetry(Device device, Dictionary<string, List<PayLoad>> sendModel)
{ {
bool canPub = false; bool canPub = false;
try try
{ {
//第一次上传 //第一次上传
if (!LastTelemetrys.ContainsKey(device.DeviceName)) if (!_lastTelemetrys.ContainsKey(device.DeviceName))
canPub = true; canPub = true;
else else
{ {
@ -443,14 +495,15 @@ namespace Plugin
if (device.CgUpload) if (device.CgUpload)
{ {
//是否超过归档周期 //是否超过归档周期
if (SendModel[device.DeviceName][0].TS - LastTelemetrys[device.DeviceName][0].TS > device.EnforcePeriod) if (sendModel[device.DeviceName][0].TS - _lastTelemetrys[device.DeviceName][0].TS >
device.EnforcePeriod)
canPub = true; canPub = true;
//是否变化 //是否变化
else else
{ {
if (JsonConvert.SerializeObject(SendModel[device.DeviceName][0].Values) != JsonConvert.SerializeObject(LastTelemetrys[device.DeviceName][0].Values)) if (JsonConvert.SerializeObject(sendModel[device.DeviceName][0].Values) !=
JsonConvert.SerializeObject(_lastTelemetrys[device.DeviceName][0].Values))
canPub = true; canPub = true;
} }
} }
//非变化上传 //非变化上传
@ -463,36 +516,42 @@ namespace Plugin
canPub = true; canPub = true;
Console.WriteLine(e); Console.WriteLine(e);
} }
if (canPub) if (canPub)
LastTelemetrys[device.DeviceName] = SendModel[device.DeviceName]; _lastTelemetrys[device.DeviceName] = sendModel[device.DeviceName];
return canPub; return canPub;
} }
public void PublishTelemetry(Device device, Dictionary<string, List<PayLoad>> SendModel)
public async Task PublishTelemetryAsync(Device device, Dictionary<string, List<PayLoad>> sendModel)
{ {
try try
{ {
if (CanPubTelemetry(device, SendModel)) if (CanPubTelemetry(device, sendModel))
{ {
if (_systemConfig != null)
switch (_systemConfig.IoTPlatformType) switch (_systemConfig.IoTPlatformType)
{ {
case IoTPlatformType.ThingsBoard: case IoTPlatformType.ThingsBoard:
Client.PublishAsync("v1/gateway/telemetry", JsonConvert.SerializeObject(SendModel)); await Client.PublishAsync("v1/gateway/telemetry",
JsonConvert.SerializeObject(sendModel));
break; break;
case IoTPlatformType.IoTSharp: case IoTPlatformType.IoTSharp:
foreach (var payload in SendModel[device.DeviceName]) foreach (var payload in sendModel[device.DeviceName])
{ {
UploadISTelemetryDataAsync(device.DeviceName, payload.Values); await UploadIsTelemetryDataAsync(device.DeviceName, payload.Values);
} }
break; break;
case IoTPlatformType.ThingsCloud: case IoTPlatformType.ThingsCloud:
foreach (var payload in SendModel[device.DeviceName]) foreach (var payload in sendModel[device.DeviceName])
{ {
UploadTCTelemetryDataAsync(device.DeviceName, payload.Values); await UploadTcTelemetryDataAsync(device.DeviceName, payload.Values);
} }
break; break;
case IoTPlatformType.IotDB: case IoTPlatformType.IotDB:
{ {
foreach (var payload in SendModel[device.DeviceName]) foreach (var payload in sendModel[device.DeviceName])
{ {
if (payload.DeviceStatus != DeviceStatusTypeEnum.Good) if (payload.DeviceStatus != DeviceStatusTypeEnum.Good)
continue; continue;
@ -504,11 +563,19 @@ namespace Plugin
measurements = payload.Values.Keys.ToList(), measurements = payload.Values.Keys.ToList(),
values = payload.Values.Values.ToList() values = payload.Values.Values.ToList()
}; };
Client.PublishAsync(device.DeviceName, JsonConvert.SerializeObject(tsData)); await Client.PublishAsync(device.DeviceName, JsonConvert.SerializeObject(tsData));
} }
break; break;
} }
case IoTPlatformType.HuaWei:
foreach (var payload in sendModel[device.DeviceName])
{
await UploadHwTelemetryDataAsync(device, payload.Values);
}
break;
case IoTPlatformType.AliCloudIoT: case IoTPlatformType.AliCloudIoT:
case IoTPlatformType.TencentIoTHub: case IoTPlatformType.TencentIoTHub:
case IoTPlatformType.BaiduIoTCore: case IoTPlatformType.BaiduIoTCore:
@ -518,33 +585,34 @@ namespace Plugin
} }
} }
foreach (var payload in SendModel[device.DeviceName]) foreach (var payload in sendModel[device.DeviceName])
{ {
foreach (var kv in payload.Values) foreach (var kv in payload.Values)
{ {
//更新到UAService //更新到UAService
_uaNodeManager.UpdateNode($"{device.Parent.DeviceName}.{device.DeviceName}.{kv.Key}", kv.Value); _uaNodeManager?.UpdateNode($"{device.Parent.DeviceName}.{device.DeviceName}.{kv.Key}",
kv.Value);
} }
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError($"PublishTelemetryAsync Error", ex);
}
} }
} public async Task DeviceConnected(Device device)
public async Task DeviceConnected(string DeviceName)
{ {
try try
{ {
if (_systemConfig != null)
switch (_systemConfig.IoTPlatformType) switch (_systemConfig.IoTPlatformType)
{ {
case IoTPlatformType.ThingsBoard: case IoTPlatformType.ThingsBoard:
case IoTPlatformType.IoTSharp: case IoTPlatformType.IoTSharp:
await Client.PublishAsync("v1/gateway/connect", JsonConvert.SerializeObject(new Dictionary<string, string> { { "device", DeviceName } })); await Client.PublishAsync("v1/gateway/connect",
JsonConvert.SerializeObject(new Dictionary<string, string>
{ { "device", device.DeviceName } }));
break; break;
case IoTPlatformType.AliCloudIoT: case IoTPlatformType.AliCloudIoT:
break; break;
@ -555,27 +623,48 @@ namespace Plugin
case IoTPlatformType.OneNET: case IoTPlatformType.OneNET:
break; break;
case IoTPlatformType.ThingsCloud: case IoTPlatformType.ThingsCloud:
await Client.PublishAsync("gateway/connect", JsonConvert.SerializeObject(new Dictionary<string, string> { { "device", DeviceName } })); await Client.PublishAsync("gateway/connect",
JsonConvert.SerializeObject(new Dictionary<string, string>
{ { "device", device.DeviceName } }));
break; break;
default: case IoTPlatformType.HuaWei:
var deviceOnLine = new HwDeviceOnOffLine()
{
MId = new Random().NextInt64(), //命令ID
DeviceStatuses = new List<DeviceStatus>()
{
new DeviceStatus()
{
DeviceId = device.DeviceConfigs
.FirstOrDefault(x => x.DeviceConfigName == "DeviceId")
?.Value,
Status = "ONLINE"
}
}
};
await Client.PublishAsync($"/v1/devices/{_systemConfig.GatewayName}/topo/update",
JsonConvert.SerializeObject(deviceOnLine));
break; break;
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError($"DeviceConnected:{DeviceName}", ex); _logger.LogError($"DeviceConnected:{device.DeviceName}", ex);
} }
} }
public async Task DeviceDisconnected(string DeviceName) public async Task DeviceDisconnected(Device device)
{ {
try try
{ {
if (_systemConfig != null)
switch (_systemConfig.IoTPlatformType) switch (_systemConfig.IoTPlatformType)
{ {
case IoTPlatformType.ThingsBoard: case IoTPlatformType.ThingsBoard:
case IoTPlatformType.IoTSharp: case IoTPlatformType.IoTSharp:
await Client.PublishAsync("v1/gateway/disconnect", JsonConvert.SerializeObject(new Dictionary<string, string> { { "device", DeviceName } })); await Client.PublishAsync("v1/gateway/disconnect",
JsonConvert.SerializeObject(new Dictionary<string, string>
{ { "device", device.DeviceName } }));
break; break;
case IoTPlatformType.AliCloudIoT: case IoTPlatformType.AliCloudIoT:
break; break;
@ -586,18 +675,107 @@ namespace Plugin
case IoTPlatformType.OneNET: case IoTPlatformType.OneNET:
break; break;
case IoTPlatformType.ThingsCloud: case IoTPlatformType.ThingsCloud:
await Client.PublishAsync("gateway/disconnect", JsonConvert.SerializeObject(new Dictionary<string, string> { { "device", DeviceName } })); await Client.PublishAsync("gateway/disconnect",
JsonConvert.SerializeObject(new Dictionary<string, string>
{ { "device", device.DeviceName } }));
break; break;
default: case IoTPlatformType.HuaWei:
var deviceOnLine = new HwDeviceOnOffLine()
{
MId = new Random().NextInt64(), //命令ID
DeviceStatuses = new List<DeviceStatus>()
{
new DeviceStatus()
{
DeviceId = device.DeviceConfigs
.FirstOrDefault(x => x.DeviceConfigName == "DeviceId")
?.Value,
Status = "OFFLINE"
}
}
};
await Client.PublishAsync($"/v1/devices/{_systemConfig.GatewayName}/topo/update",
JsonConvert.SerializeObject(deviceOnLine));
break; break;
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError($"DeviceDisconnected:{DeviceName}", ex); _logger.LogError($"DeviceDisconnected:{device.DeviceName}", ex);
}
} }
public async Task DeviceAdded(Device device)
{
try
{
if (_systemConfig != null)
switch (_systemConfig.IoTPlatformType)
{
case IoTPlatformType.HuaWei:
var topic = $"/v1/devices/{_systemConfig.GatewayName}/topo/add";
var addDeviceDto = new HwAddDeviceDto
{
MId = new Random().NextInt64() //命令ID
};
addDeviceDto.DeviceInfos.Add(
new DeviceInfo
{
NodeId = device.DeviceName,
Name = device.DeviceName,
Description = device.Description,
ManufacturerId = "Test_n",
ProductType = "A_n"
}
);
await Client.PublishAsync(topic,
JsonConvert.SerializeObject(addDeviceDto));
break;
}
}
catch (Exception ex)
{
_logger.LogError($"DeviceAdded:{device.DeviceName}", ex);
}
} }
public async Task DeviceDeleted(Device device)
{
try
{
if (_systemConfig != null)
switch (_systemConfig.IoTPlatformType)
{
case IoTPlatformType.HuaWei:
var topic = $"/v1/devices/{_systemConfig.GatewayName}/topo/delete";
var deleteDeviceDto = new HwDeleteDeviceDto
{
Id = new Random().NextInt64(), //命令ID
DeviceId = device.DeviceConfigs.FirstOrDefault(x => x.DeviceConfigName == "DeviceId")
?.Value,
RequestTime = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds,
Request = new()
{
ManufacturerId = "Test_n",
ManufacturerName = "Test_n",
ProductType = "A_n"
}
};
await Client.PublishAsync(topic,
JsonConvert.SerializeObject(deleteDeviceDto));
break;
}
}
catch (Exception ex)
{
_logger.LogError($"DeviceAdded:{device.DeviceName}", ex);
}
}
} }
} }

File diff suppressed because it is too large Load Diff

View File

@ -1,13 +1,5 @@
using Microsoft.Extensions.Hosting; using Quickstarts;
using Opc.Ua;
using Quickstarts;
using Quickstarts.ReferenceServer; using Quickstarts.ReferenceServer;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Plugin namespace Plugin
{ {

View File

@ -0,0 +1,49 @@
using Newtonsoft.Json;
namespace PluginInterface.HuaWeiRoma
{
public class HwAddDeviceDto
{
[JsonProperty(PropertyName = "deviceInfos")]
public List<DeviceInfo> DeviceInfos = new();
/// <summary>
/// 命令ID
/// </summary>
[JsonProperty(PropertyName = "mid")]
public long MId { get; set; }
}
public class DeviceInfo
{
/// <summary>
/// 设备标识
/// </summary>
[JsonProperty(PropertyName = "nodeId")]
public string NodeId { get; set; }
/// <summary>
/// 设备名称
/// </summary>
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
/// <summary>
/// 设备描述
/// </summary>
[JsonProperty(PropertyName = "description")]
public string Description { get; set; }
/// <summary>
/// 厂商ID
/// </summary>
[JsonProperty(PropertyName = "manufacturerId")]
public string ManufacturerId { get; set; }
/// <summary>
/// 产品型号
/// </summary>
[JsonProperty(PropertyName = "model")]
public string ProductType { get; set; }
}
}

View File

@ -0,0 +1,52 @@
using Newtonsoft.Json;
namespace PluginInterface.HuaWeiRoma
{
public class HwDeleteDeviceDto
{
/// <summary>
/// 命令ID
/// </summary>
[JsonProperty(PropertyName = "id")]
public long Id { get; set; }
/// <summary>
/// 平台生成的设备唯一标识对应设备客户端ID
/// </summary>
[JsonProperty(PropertyName = "deviceId")]
public string? DeviceId { get; set; }
/// <summary>
/// 请求时间戳
/// </summary>
[JsonProperty(PropertyName = "requestTime")]
public long RequestTime { get; set; }
/// <summary>
/// 子设备信息
/// </summary>
[JsonProperty(PropertyName = "request")]
public Request? Request { get; set; }
}
public class Request
{
/// <summary>
/// 厂商名称
/// </summary>
[JsonProperty(PropertyName = "manufacturerName")]
public string? ManufacturerName { get; set; }
/// <summary>
/// 厂商ID
/// </summary>
[JsonProperty(PropertyName = "manufacturerId")]
public string? ManufacturerId { get; set; }
/// <summary>
/// 产品型号
/// </summary>
[JsonProperty(PropertyName = "model")]
public string? ProductType { get; set; }
}
}

View File

@ -0,0 +1,34 @@
using Newtonsoft.Json;
namespace PluginInterface.HuaWeiRoma
{
public class HwDeviceOnOffLine
{
[JsonProperty(PropertyName = "deviceStatuses")]
public List<DeviceStatus> DeviceStatuses = new();
/// <summary>
/// 命令ID
/// </summary>
[JsonProperty(PropertyName = "mid")]
public long MId { get; set; }
}
public class DeviceStatus
{
/// <summary>
/// 设备标识
/// </summary>
[JsonProperty(PropertyName = "deviceId")]
public string? DeviceId { get; set; }
/// <summary>
/// 子设备状态:
/// OFFLINE设备离线
/// ONLINE 设备上线
/// </summary>
[JsonProperty(PropertyName = "status")]
public string? Status { get; set; }
}
}

View File

@ -0,0 +1,27 @@
using Newtonsoft.Json;
namespace PluginInterface.HuaWeiRoma
{
public class HwTelemetrys
{
[JsonProperty(PropertyName = "devices")]
public List<HwTelemetry>? Devices { get; set; }
}
public class HwTelemetry
{
[JsonProperty(PropertyName = "deviceId")]
public string? DeviceId { get; set; }
[JsonProperty(PropertyName = "services")]
public List<Service>? Services { get; set; }
}
public class Service
{
[JsonProperty(PropertyName = "serviceId")]
public string? ServiceId { get; set; }
[JsonProperty(PropertyName = "data")]
public object? Data { get; set; }
[JsonProperty(PropertyName = "eventTime")]
public string? EventTime { get; set; }
}
}

View File

@ -5,7 +5,7 @@ namespace PluginInterface
{ {
public interface IDriver : IDisposable public interface IDriver : IDisposable
{ {
public Guid DeviceId { get; } public string DeviceId { get; }
public bool IsConnected { get; } public bool IsConnected { get; }
public int Timeout { get; } public int Timeout { get; }
public uint MinPeriod { get; } public uint MinPeriod { get; }

View File

@ -11,7 +11,7 @@ namespace PluginInterface
public string DeviceName { get; set; } public string DeviceName { get; set; }
public string Method { get; set; } public string Method { get; set; }
public string RequestId { get; set; } public string RequestId { get; set; }
public Dictionary<string, object> Params { get; set; } public Dictionary<string, object>? Params { get; set; }
public override string ToString() public override string ToString()
{ {
return $"Method:{Method},RequestId:{RequestId},Params:{Newtonsoft.Json.JsonConvert.SerializeObject(Params)}"; return $"Method:{Method},RequestId:{RequestId},Params:{Newtonsoft.Json.JsonConvert.SerializeObject(Params)}";