From 858ce94bbb9cb6f44ab7504c875763bd2b95eb54 Mon Sep 17 00:00:00 2001
From: iioter <535915157@qq.com>
Date: Wed, 10 Aug 2022 16:55:44 +0800
Subject: [PATCH] =?UTF-8?q?=E6=94=AF=E6=8C=81=E5=8D=8E=E4=B8=BARoma?=
=?UTF-8?q?=E5=B9=B3=E5=8F=B0?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.../20220810063014_mqttClientId.Designer.cs | 856 ++++++++
.../Migrations/20220810063014_mqttClientId.cs | 25 +
.../Migrations/DataContextModelSnapshot.cs | 3 +
IoTGateway.Model/SystemConfig.cs | 4 +
.../DeviceConfigVMs/DeviceConfigListVM.cs | 4 +-
.../BasicData/DeviceVMs/DeviceVM.cs | 18 +-
.../DeviceVariableVMs/DeviceVariableListVM.cs | 6 +-
.../BasicData/DeviceVariableVMs/SetValueVM.cs | 4 +-
.../SystemConfigVMs/SystemConfigListVM.cs | 2 +
.../Config/Views/SystemConfig/Edit.cshtml | 1 +
IoTGateway/Controllers/HomeController.cs | 12 +-
IoTGateway/iotgateway.db | Bin 311296 -> 311296 bytes
Plugins/Plugin/ConnnectSettingsMode.cs | 17 +-
Plugins/Plugin/DeviceService.cs | 124 +-
Plugins/Plugin/DeviceThread.cs | 174 +-
Plugins/Plugin/DriverInfo.cs | 11 +-
Plugins/Plugin/DrvierService.cs | 164 +-
Plugins/Plugin/IoTBackgroundService.cs | 26 +-
Plugins/Plugin/ModbusSlaveService.cs | 49 +-
Plugins/Plugin/MyMqttClient.cs | 828 +++++---
.../Plugin/UA.Server/ReferenceNodeManager.cs | 1786 ++++++++++++-----
Plugins/Plugin/UAService.cs | 10 +-
.../HuaWeiRoma/HwAddDeviceDto.cs | 49 +
.../HuaWeiRoma/HwDeleteDeviceDto.cs | 52 +
.../HuaWeiRoma/HwDeviceOnOffLine.cs | 34 +
.../PluginInterface/HuaWeiRoma/HwTelemetry.cs | 27 +
Plugins/PluginInterface/IDriver.cs | 2 +-
Plugins/PluginInterface/RpcRequest.cs | 2 +-
28 files changed, 3129 insertions(+), 1161 deletions(-)
create mode 100644 IoTGateway.DataAccess/Migrations/20220810063014_mqttClientId.Designer.cs
create mode 100644 IoTGateway.DataAccess/Migrations/20220810063014_mqttClientId.cs
create mode 100644 Plugins/PluginInterface/HuaWeiRoma/HwAddDeviceDto.cs
create mode 100644 Plugins/PluginInterface/HuaWeiRoma/HwDeleteDeviceDto.cs
create mode 100644 Plugins/PluginInterface/HuaWeiRoma/HwDeviceOnOffLine.cs
create mode 100644 Plugins/PluginInterface/HuaWeiRoma/HwTelemetry.cs
diff --git a/IoTGateway.DataAccess/Migrations/20220810063014_mqttClientId.Designer.cs b/IoTGateway.DataAccess/Migrations/20220810063014_mqttClientId.Designer.cs
new file mode 100644
index 0000000..3296825
--- /dev/null
+++ b/IoTGateway.DataAccess/Migrations/20220810063014_mqttClientId.Designer.cs
@@ -0,0 +1,856 @@
+//
+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("ID")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("TEXT");
+
+ b.Property("AutoStart")
+ .HasColumnType("INTEGER");
+
+ b.Property("CgUpload")
+ .HasColumnType("INTEGER");
+
+ b.Property("CreateBy")
+ .HasColumnType("TEXT");
+
+ b.Property("CreateTime")
+ .HasColumnType("TEXT");
+
+ b.Property("Description")
+ .HasColumnType("TEXT");
+
+ b.Property("DeviceName")
+ .HasColumnType("TEXT");
+
+ b.Property("DeviceTypeEnum")
+ .HasColumnType("INTEGER");
+
+ b.Property("DriverId")
+ .HasColumnType("TEXT");
+
+ b.Property("EnforcePeriod")
+ .HasColumnType("INTEGER");
+
+ b.Property("Index")
+ .HasColumnType("INTEGER");
+
+ b.Property("ParentId")
+ .HasColumnType("TEXT");
+
+ b.Property("UpdateBy")
+ .HasColumnType("TEXT");
+
+ b.Property("UpdateTime")
+ .HasColumnType("TEXT");
+
+ b.HasKey("ID");
+
+ b.HasIndex("DriverId");
+
+ b.HasIndex("ParentId");
+
+ b.ToTable("Devices");
+ });
+
+ modelBuilder.Entity("IoTGateway.Model.DeviceConfig", b =>
+ {
+ b.Property("ID")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("TEXT");
+
+ b.Property("CreateBy")
+ .HasMaxLength(50)
+ .HasColumnType("TEXT");
+
+ b.Property("CreateTime")
+ .HasColumnType("TEXT");
+
+ b.Property("DataSide")
+ .HasColumnType("INTEGER");
+
+ b.Property("Description")
+ .HasColumnType("TEXT");
+
+ b.Property("DeviceConfigName")
+ .HasColumnType("TEXT");
+
+ b.Property("DeviceId")
+ .HasColumnType("TEXT");
+
+ b.Property("EnumInfo")
+ .HasColumnType("TEXT");
+
+ b.Property("UpdateBy")
+ .HasMaxLength(50)
+ .HasColumnType("TEXT");
+
+ b.Property("UpdateTime")
+ .HasColumnType("TEXT");
+
+ b.Property("Value")
+ .HasColumnType("TEXT");
+
+ b.HasKey("ID");
+
+ b.HasIndex("DeviceId");
+
+ b.ToTable("DeviceConfigs");
+ });
+
+ modelBuilder.Entity("IoTGateway.Model.DeviceVariable", b =>
+ {
+ b.Property("ID")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("TEXT");
+
+ b.Property("DataType")
+ .HasColumnType("INTEGER");
+
+ b.Property("Description")
+ .HasColumnType("TEXT");
+
+ b.Property("DeviceAddress")
+ .HasColumnType("TEXT");
+
+ b.Property("DeviceId")
+ .HasColumnType("TEXT");
+
+ b.Property("Expressions")
+ .HasColumnType("TEXT");
+
+ b.Property("Method")
+ .HasColumnType("TEXT");
+
+ b.Property("Name")
+ .HasColumnType("TEXT");
+
+ b.Property("ProtectType")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("ID");
+
+ b.HasIndex("DeviceId");
+
+ b.ToTable("DeviceVariables");
+ });
+
+ modelBuilder.Entity("IoTGateway.Model.Driver", b =>
+ {
+ b.Property("ID")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("TEXT");
+
+ b.Property("AssembleName")
+ .HasColumnType("TEXT");
+
+ b.Property("AuthorizesNum")
+ .HasColumnType("INTEGER");
+
+ b.Property("CreateBy")
+ .HasMaxLength(50)
+ .HasColumnType("TEXT");
+
+ b.Property("CreateTime")
+ .HasColumnType("TEXT");
+
+ b.Property("DriverName")
+ .HasColumnType("TEXT");
+
+ b.Property("FileName")
+ .HasColumnType("TEXT");
+
+ b.Property("UpdateBy")
+ .HasMaxLength(50)
+ .HasColumnType("TEXT");
+
+ b.Property("UpdateTime")
+ .HasColumnType("TEXT");
+
+ b.HasKey("ID");
+
+ b.ToTable("Drivers");
+ });
+
+ modelBuilder.Entity("IoTGateway.Model.RpcLog", b =>
+ {
+ b.Property("ID")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("TEXT");
+
+ b.Property("Description")
+ .HasColumnType("TEXT");
+
+ b.Property("DeviceId")
+ .HasColumnType("TEXT");
+
+ b.Property("EndTime")
+ .HasColumnType("TEXT");
+
+ b.Property("IsSuccess")
+ .HasColumnType("INTEGER");
+
+ b.Property("Method")
+ .HasColumnType("TEXT");
+
+ b.Property("Params")
+ .HasColumnType("TEXT");
+
+ b.Property("RpcSide")
+ .HasColumnType("INTEGER");
+
+ b.Property("StartTime")
+ .HasColumnType("TEXT");
+
+ b.HasKey("ID");
+
+ b.HasIndex("DeviceId");
+
+ b.ToTable("RpcLogs");
+ });
+
+ modelBuilder.Entity("IoTGateway.Model.SystemConfig", b =>
+ {
+ b.Property("ID")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("TEXT");
+
+ b.Property("ClientId")
+ .HasColumnType("TEXT");
+
+ b.Property("CreateBy")
+ .HasMaxLength(50)
+ .HasColumnType("TEXT");
+
+ b.Property("CreateTime")
+ .HasColumnType("TEXT");
+
+ b.Property("GatewayName")
+ .HasColumnType("TEXT");
+
+ b.Property("IoTPlatformType")
+ .HasColumnType("INTEGER");
+
+ b.Property("MqttIp")
+ .HasColumnType("TEXT");
+
+ b.Property("MqttPort")
+ .HasColumnType("INTEGER");
+
+ b.Property("MqttUName")
+ .HasColumnType("TEXT");
+
+ b.Property("MqttUPwd")
+ .HasColumnType("TEXT");
+
+ b.Property("UpdateBy")
+ .HasMaxLength(50)
+ .HasColumnType("TEXT");
+
+ b.Property("UpdateTime")
+ .HasColumnType("TEXT");
+
+ b.HasKey("ID");
+
+ b.ToTable("SystemConfig");
+ });
+
+ modelBuilder.Entity("WalkingTec.Mvvm.Core.ActionLog", b =>
+ {
+ b.Property("ID")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("TEXT");
+
+ b.Property("ActionName")
+ .HasMaxLength(255)
+ .HasColumnType("TEXT");
+
+ b.Property("ActionTime")
+ .HasColumnType("TEXT");
+
+ b.Property("ActionUrl")
+ .HasMaxLength(250)
+ .HasColumnType("TEXT");
+
+ b.Property("CreateBy")
+ .HasMaxLength(50)
+ .HasColumnType("TEXT");
+
+ b.Property("CreateTime")
+ .HasColumnType("TEXT");
+
+ b.Property("Duration")
+ .HasColumnType("REAL");
+
+ b.Property("IP")
+ .HasMaxLength(50)
+ .HasColumnType("TEXT");
+
+ b.Property("ITCode")
+ .HasMaxLength(50)
+ .HasColumnType("TEXT");
+
+ b.Property("LogType")
+ .HasColumnType("INTEGER");
+
+ b.Property("ModuleName")
+ .HasMaxLength(255)
+ .HasColumnType("TEXT");
+
+ b.Property("Remark")
+ .HasColumnType("TEXT");
+
+ b.Property("UpdateBy")
+ .HasMaxLength(50)
+ .HasColumnType("TEXT");
+
+ b.Property("UpdateTime")
+ .HasColumnType("TEXT");
+
+ b.HasKey("ID");
+
+ b.ToTable("ActionLogs");
+ });
+
+ modelBuilder.Entity("WalkingTec.Mvvm.Core.DataPrivilege", b =>
+ {
+ b.Property("ID")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("TEXT");
+
+ b.Property("CreateBy")
+ .HasMaxLength(50)
+ .HasColumnType("TEXT");
+
+ b.Property("CreateTime")
+ .HasColumnType("TEXT");
+
+ b.Property("Domain")
+ .HasColumnType("TEXT");
+
+ b.Property("GroupCode")
+ .HasColumnType("TEXT");
+
+ b.Property("RelateId")
+ .HasColumnType("TEXT");
+
+ b.Property("TableName")
+ .IsRequired()
+ .HasMaxLength(50)
+ .HasColumnType("TEXT");
+
+ b.Property("UpdateBy")
+ .HasMaxLength(50)
+ .HasColumnType("TEXT");
+
+ b.Property("UpdateTime")
+ .HasColumnType("TEXT");
+
+ b.Property("UserCode")
+ .HasColumnType("TEXT");
+
+ b.HasKey("ID");
+
+ b.ToTable("DataPrivileges");
+ });
+
+ modelBuilder.Entity("WalkingTec.Mvvm.Core.FileAttachment", b =>
+ {
+ b.Property("ID")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("TEXT");
+
+ b.Property("ExtraInfo")
+ .HasColumnType("TEXT");
+
+ b.Property("FileData")
+ .HasColumnType("BLOB");
+
+ b.Property("FileExt")
+ .IsRequired()
+ .HasMaxLength(10)
+ .HasColumnType("TEXT");
+
+ b.Property("FileName")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.Property("HandlerInfo")
+ .HasColumnType("TEXT");
+
+ b.Property("Length")
+ .HasColumnType("INTEGER");
+
+ b.Property("Path")
+ .HasColumnType("TEXT");
+
+ b.Property("SaveMode")
+ .HasColumnType("TEXT");
+
+ b.Property("UploadTime")
+ .HasColumnType("TEXT");
+
+ b.HasKey("ID");
+
+ b.ToTable("FileAttachments");
+ });
+
+ modelBuilder.Entity("WalkingTec.Mvvm.Core.FrameworkGroup", b =>
+ {
+ b.Property("ID")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("TEXT");
+
+ b.Property("CreateBy")
+ .HasMaxLength(50)
+ .HasColumnType("TEXT");
+
+ b.Property("CreateTime")
+ .HasColumnType("TEXT");
+
+ b.Property("GroupCode")
+ .IsRequired()
+ .HasMaxLength(100)
+ .HasColumnType("TEXT");
+
+ b.Property("GroupName")
+ .IsRequired()
+ .HasMaxLength(50)
+ .HasColumnType("TEXT");
+
+ b.Property("GroupRemark")
+ .HasColumnType("TEXT");
+
+ b.Property("TenantCode")
+ .HasColumnType("TEXT");
+
+ b.Property("UpdateBy")
+ .HasMaxLength(50)
+ .HasColumnType("TEXT");
+
+ b.Property("UpdateTime")
+ .HasColumnType("TEXT");
+
+ b.HasKey("ID");
+
+ b.ToTable("FrameworkGroups");
+ });
+
+ modelBuilder.Entity("WalkingTec.Mvvm.Core.FrameworkMenu", b =>
+ {
+ b.Property("ID")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("TEXT");
+
+ b.Property("ActionName")
+ .HasColumnType("TEXT");
+
+ b.Property("ClassName")
+ .HasColumnType("TEXT");
+
+ b.Property("DisplayOrder")
+ .IsRequired()
+ .HasColumnType("INTEGER");
+
+ b.Property("Domain")
+ .HasColumnType("TEXT");
+
+ b.Property("FolderOnly")
+ .HasColumnType("INTEGER");
+
+ b.Property("Icon")
+ .HasMaxLength(50)
+ .HasColumnType("TEXT");
+
+ b.Property("IsInherit")
+ .HasColumnType("INTEGER");
+
+ b.Property("IsInside")
+ .IsRequired()
+ .HasColumnType("INTEGER");
+
+ b.Property("IsPublic")
+ .HasColumnType("INTEGER");
+
+ b.Property("MethodName")
+ .HasColumnType("TEXT");
+
+ b.Property("ModuleName")
+ .HasColumnType("TEXT");
+
+ b.Property("PageName")
+ .IsRequired()
+ .HasMaxLength(50)
+ .HasColumnType("TEXT");
+
+ b.Property("ParentId")
+ .HasColumnType("TEXT");
+
+ b.Property("ShowOnMenu")
+ .HasColumnType("INTEGER");
+
+ b.Property("Url")
+ .HasColumnType("TEXT");
+
+ b.HasKey("ID");
+
+ b.HasIndex("ParentId");
+
+ b.ToTable("FrameworkMenus");
+ });
+
+ modelBuilder.Entity("WalkingTec.Mvvm.Core.FrameworkRole", b =>
+ {
+ b.Property("ID")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("TEXT");
+
+ b.Property("CreateBy")
+ .HasMaxLength(50)
+ .HasColumnType("TEXT");
+
+ b.Property("CreateTime")
+ .HasColumnType("TEXT");
+
+ b.Property("RoleCode")
+ .IsRequired()
+ .HasMaxLength(100)
+ .HasColumnType("TEXT");
+
+ b.Property("RoleName")
+ .IsRequired()
+ .HasMaxLength(50)
+ .HasColumnType("TEXT");
+
+ b.Property("RoleRemark")
+ .HasColumnType("TEXT");
+
+ b.Property("TenantCode")
+ .HasColumnType("TEXT");
+
+ b.Property("UpdateBy")
+ .HasMaxLength(50)
+ .HasColumnType("TEXT");
+
+ b.Property("UpdateTime")
+ .HasColumnType("TEXT");
+
+ b.HasKey("ID");
+
+ b.ToTable("FrameworkRoles");
+ });
+
+ modelBuilder.Entity("WalkingTec.Mvvm.Core.FrameworkUser", b =>
+ {
+ b.Property("ID")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("TEXT");
+
+ b.Property("Address")
+ .HasMaxLength(200)
+ .HasColumnType("TEXT");
+
+ b.Property("CellPhone")
+ .HasColumnType("TEXT");
+
+ b.Property("CreateBy")
+ .HasMaxLength(50)
+ .HasColumnType("TEXT");
+
+ b.Property("CreateTime")
+ .HasColumnType("TEXT");
+
+ b.Property("Email")
+ .HasMaxLength(50)
+ .HasColumnType("TEXT");
+
+ b.Property("Gender")
+ .HasColumnType("INTEGER");
+
+ b.Property("HomePhone")
+ .HasMaxLength(30)
+ .HasColumnType("TEXT");
+
+ b.Property("ITCode")
+ .IsRequired()
+ .HasMaxLength(50)
+ .HasColumnType("TEXT");
+
+ b.Property("IsValid")
+ .HasColumnType("INTEGER");
+
+ b.Property("Name")
+ .IsRequired()
+ .HasMaxLength(50)
+ .HasColumnType("TEXT");
+
+ b.Property("Password")
+ .IsRequired()
+ .HasMaxLength(32)
+ .HasColumnType("TEXT");
+
+ b.Property("PhotoId")
+ .HasColumnType("TEXT");
+
+ b.Property("TenantCode")
+ .HasColumnType("TEXT");
+
+ b.Property("UpdateBy")
+ .HasMaxLength(50)
+ .HasColumnType("TEXT");
+
+ b.Property("UpdateTime")
+ .HasColumnType("TEXT");
+
+ b.Property("ZipCode")
+ .HasColumnType("TEXT");
+
+ b.HasKey("ID");
+
+ b.HasIndex("PhotoId");
+
+ b.ToTable("FrameworkUsers");
+ });
+
+ modelBuilder.Entity("WalkingTec.Mvvm.Core.FrameworkUserGroup", b =>
+ {
+ b.Property("ID")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("TEXT");
+
+ b.Property("CreateBy")
+ .HasMaxLength(50)
+ .HasColumnType("TEXT");
+
+ b.Property("CreateTime")
+ .HasColumnType("TEXT");
+
+ b.Property("GroupCode")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.Property("UpdateBy")
+ .HasMaxLength(50)
+ .HasColumnType("TEXT");
+
+ b.Property("UpdateTime")
+ .HasColumnType("TEXT");
+
+ b.Property("UserCode")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.HasKey("ID");
+
+ b.ToTable("FrameworkUserGroups");
+ });
+
+ modelBuilder.Entity("WalkingTec.Mvvm.Core.FrameworkUserRole", b =>
+ {
+ b.Property("ID")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("TEXT");
+
+ b.Property("CreateBy")
+ .HasMaxLength(50)
+ .HasColumnType("TEXT");
+
+ b.Property("CreateTime")
+ .HasColumnType("TEXT");
+
+ b.Property("RoleCode")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.Property("UpdateBy")
+ .HasMaxLength(50)
+ .HasColumnType("TEXT");
+
+ b.Property("UpdateTime")
+ .HasColumnType("TEXT");
+
+ b.Property("UserCode")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.HasKey("ID");
+
+ b.ToTable("FrameworkUserRoles");
+ });
+
+ modelBuilder.Entity("WalkingTec.Mvvm.Core.FunctionPrivilege", b =>
+ {
+ b.Property("ID")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("TEXT");
+
+ b.Property("Allowed")
+ .IsRequired()
+ .HasColumnType("INTEGER");
+
+ b.Property("CreateBy")
+ .HasMaxLength(50)
+ .HasColumnType("TEXT");
+
+ b.Property("CreateTime")
+ .HasColumnType("TEXT");
+
+ b.Property("MenuItemId")
+ .HasColumnType("TEXT");
+
+ b.Property("RoleCode")
+ .HasColumnType("TEXT");
+
+ b.Property("UpdateBy")
+ .HasMaxLength(50)
+ .HasColumnType("TEXT");
+
+ b.Property("UpdateTime")
+ .HasColumnType("TEXT");
+
+ b.HasKey("ID");
+
+ b.HasIndex("MenuItemId");
+
+ b.ToTable("FunctionPrivileges");
+ });
+
+ modelBuilder.Entity("WalkingTec.Mvvm.Core.PersistedGrant", b =>
+ {
+ b.Property("ID")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("TEXT");
+
+ b.Property("CreationTime")
+ .HasColumnType("TEXT");
+
+ b.Property("Expiration")
+ .HasColumnType("TEXT");
+
+ b.Property("RefreshToken")
+ .HasMaxLength(50)
+ .HasColumnType("TEXT");
+
+ b.Property("Type")
+ .HasMaxLength(50)
+ .HasColumnType("TEXT");
+
+ b.Property("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
+ }
+ }
+}
diff --git a/IoTGateway.DataAccess/Migrations/20220810063014_mqttClientId.cs b/IoTGateway.DataAccess/Migrations/20220810063014_mqttClientId.cs
new file mode 100644
index 0000000..24cea47
--- /dev/null
+++ b/IoTGateway.DataAccess/Migrations/20220810063014_mqttClientId.cs
@@ -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(
+ name: "ClientId",
+ table: "SystemConfig",
+ type: "TEXT",
+ nullable: true);
+ }
+
+ protected override void Down(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.DropColumn(
+ name: "ClientId",
+ table: "SystemConfig");
+ }
+ }
+}
diff --git a/IoTGateway.DataAccess/Migrations/DataContextModelSnapshot.cs b/IoTGateway.DataAccess/Migrations/DataContextModelSnapshot.cs
index 38d417e..b1a73d3 100644
--- a/IoTGateway.DataAccess/Migrations/DataContextModelSnapshot.cs
+++ b/IoTGateway.DataAccess/Migrations/DataContextModelSnapshot.cs
@@ -233,6 +233,9 @@ namespace IoTGateway.DataAccess.Migrations
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
+ b.Property("ClientId")
+ .HasColumnType("TEXT");
+
b.Property("CreateBy")
.HasMaxLength(50)
.HasColumnType("TEXT");
diff --git a/IoTGateway.Model/SystemConfig.cs b/IoTGateway.Model/SystemConfig.cs
index b6e3dad..bc7b767 100644
--- a/IoTGateway.Model/SystemConfig.cs
+++ b/IoTGateway.Model/SystemConfig.cs
@@ -7,6 +7,8 @@ namespace IoTGateway.Model
{
[Display(Name = "网关名称")]
public string GatewayName { get; set; }
+ [Display(Name = "ClientId")]
+ public string ClientId { get; set; }
[Display(Name = "Mqtt服务器")]
public string MqttIp { get; set; }
[Display(Name = "Mqtt端口")]
@@ -34,6 +36,8 @@ namespace IoTGateway.Model
OneNET = 5,
[Display(Name = "ThingsCloud")]
ThingsCloud = 6,
+ [Display(Name = "华为云")]
+ HuaWei = 7,
[Display(Name = "IotDB")]
IotDB = 99
}
diff --git a/IoTGateway.ViewModel/BasicData/DeviceConfigVMs/DeviceConfigListVM.cs b/IoTGateway.ViewModel/BasicData/DeviceConfigVMs/DeviceConfigListVM.cs
index b273ad5..26aaab9 100644
--- a/IoTGateway.ViewModel/BasicData/DeviceConfigVMs/DeviceConfigListVM.cs
+++ b/IoTGateway.ViewModel/BasicData/DeviceConfigVMs/DeviceConfigListVM.cs
@@ -40,9 +40,9 @@ namespace IoTGateway.ViewModel.BasicData.DeviceConfigVMs
{
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)
- 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.Expended = true;
diff --git a/IoTGateway.ViewModel/BasicData/DeviceVMs/DeviceVM.cs b/IoTGateway.ViewModel/BasicData/DeviceVMs/DeviceVM.cs
index fb7a6dd..80be40c 100644
--- a/IoTGateway.ViewModel/BasicData/DeviceVMs/DeviceVM.cs
+++ b/IoTGateway.ViewModel/BasicData/DeviceVMs/DeviceVM.cs
@@ -1,8 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
-using System.Threading.Tasks;
-using System.ComponentModel.DataAnnotations;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Core.Extensions;
using IoTGateway.Model;
@@ -37,9 +35,12 @@ namespace IoTGateway.ViewModel.BasicData.DeviceVMs
if (this.Entity.DeviceTypeEnum == DeviceTypeEnum.Device)
{
var deviceService = Wtm.ServiceProvider.GetService(typeof(DeviceService)) as DeviceService;
- deviceService._DrvierManager.AddConfigs(this.Entity.ID, this.Entity.DriverId);
- var dap = DC.Set().Where(x => x.ID == Entity.ID).Include(x=>x.Parent).Include(x => x.Driver).SingleOrDefault();
- deviceService.CreateDeviceThread(dap);
+ deviceService.DrvierManager.AddConfigs(this.Entity.ID, this.Entity.DriverId);
+ var device = DC.Set().Where(x => x.ID == Entity.ID).Include(x=>x.Parent).Include(x => x.Driver).SingleOrDefault();
+ deviceService.CreateDeviceThread(device);
+
+ var myMqttClient = Wtm.ServiceProvider.GetService(typeof(MyMqttClient)) as MyMqttClient;
+ myMqttClient.DeviceAdded(device);
}
}
catch (Exception ex)
@@ -63,7 +64,14 @@ namespace IoTGateway.ViewModel.BasicData.DeviceVMs
var pluginManager = Wtm.ServiceProvider.GetService(typeof(DeviceService)) as DeviceService;
var ret = DeleteDevices.doDelete(pluginManager, DC, Ids);
if (!ret.IsSuccess)
+ {
MSD.AddModelError("", ret.Message);
+ return;
+ }
+
+ var myMqttClient = Wtm.ServiceProvider.GetService(typeof(MyMqttClient)) as MyMqttClient;
+ myMqttClient.DeviceDeleted(Entity);
+
}
public override DuplicatedInfo SetDuplicatedCheck()
{
diff --git a/IoTGateway.ViewModel/BasicData/DeviceVariableVMs/DeviceVariableListVM.cs b/IoTGateway.ViewModel/BasicData/DeviceVariableVMs/DeviceVariableListVM.cs
index 73146e9..3d655b9 100644
--- a/IoTGateway.ViewModel/BasicData/DeviceVariableVMs/DeviceVariableListVM.cs
+++ b/IoTGateway.ViewModel/BasicData/DeviceVariableVMs/DeviceVariableListVM.cs
@@ -45,9 +45,9 @@ namespace IoTGateway.ViewModel.BasicData.DeviceVariableVMs
{
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)
- 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.Expended = true;
@@ -95,7 +95,7 @@ namespace IoTGateway.ViewModel.BasicData.DeviceVariableVMs
var deviceService = Wtm.ServiceProvider.GetService(typeof(DeviceService)) as DeviceService;
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))
{
item.Value = DapThread?.DeviceValues[item.ID]?.Value?.ToString();
diff --git a/IoTGateway.ViewModel/BasicData/DeviceVariableVMs/SetValueVM.cs b/IoTGateway.ViewModel/BasicData/DeviceVariableVMs/SetValueVM.cs
index 684d541..4724a0d 100644
--- a/IoTGateway.ViewModel/BasicData/DeviceVariableVMs/SetValueVM.cs
+++ b/IoTGateway.ViewModel/BasicData/DeviceVariableVMs/SetValueVM.cs
@@ -31,7 +31,7 @@ namespace IoTGateway.ViewModel.BasicData.DeviceVariableVMs
类型 = variable.DataType.GetEnumDisplayName();
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))
{
@@ -71,7 +71,7 @@ namespace IoTGateway.ViewModel.BasicData.DeviceVariableVMs
类型 = variable.DataType.GetEnumDisplayName();
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))
{
diff --git a/IoTGateway.ViewModel/Config/SystemConfigVMs/SystemConfigListVM.cs b/IoTGateway.ViewModel/Config/SystemConfigVMs/SystemConfigListVM.cs
index bbdac64..993b32a 100644
--- a/IoTGateway.ViewModel/Config/SystemConfigVMs/SystemConfigListVM.cs
+++ b/IoTGateway.ViewModel/Config/SystemConfigVMs/SystemConfigListVM.cs
@@ -33,6 +33,7 @@ namespace IoTGateway.ViewModel.Config.SystemConfigVMs
{
return new List>{
this.MakeGridHeader(x => x.GatewayName),
+ this.MakeGridHeader(x => x.ClientId),
this.MakeGridHeader(x => x.IoTPlatformType),
this.MakeGridHeader(x => x.MqttIp),
this.MakeGridHeader(x => x.MqttPort),
@@ -49,6 +50,7 @@ namespace IoTGateway.ViewModel.Config.SystemConfigVMs
{
ID = x.ID,
GatewayName = x.GatewayName,
+ ClientId = x.ClientId,
MqttIp = x.MqttIp,
MqttPort = x.MqttPort,
MqttUName = x.MqttUName,
diff --git a/IoTGateway/Areas/Config/Views/SystemConfig/Edit.cshtml b/IoTGateway/Areas/Config/Views/SystemConfig/Edit.cshtml
index 7715405..5d5e37f 100644
--- a/IoTGateway/Areas/Config/Views/SystemConfig/Edit.cshtml
+++ b/IoTGateway/Areas/Config/Views/SystemConfig/Edit.cshtml
@@ -5,6 +5,7 @@
注意:目前实现了iotsharp、thingsboard、thingscloud、iotdb的遥测、属性上传以及RPC功能
+
diff --git a/IoTGateway/Controllers/HomeController.cs b/IoTGateway/Controllers/HomeController.cs
index a916b0d..5d8a025 100644
--- a/IoTGateway/Controllers/HomeController.cs
+++ b/IoTGateway/Controllers/HomeController.cs
@@ -53,21 +53,21 @@ namespace IoTGateway.Controllers
data.Add(new ChartData
{
- Value = _deviceService.DeviceThreads.Where(x => !x._device.AutoStart).Count(),
+ Value = _deviceService.DeviceThreads.Where(x => !x.Device.AutoStart).Count(),
Category = "停止",
Series = "Device"
});
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 = "运行",
Series = "Device",
});
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 = "异常",
Series = "Device"
});
@@ -78,18 +78,18 @@ namespace IoTGateway.Controllers
public IActionResult GetDeviceVariableChart()
{
var data = new List();
- 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
{
- Category = deviceThread._device.DeviceName,
+ Category = deviceThread.Device.DeviceName,
Value = deviceThread.DeviceValues.Where(x => x.Value.StatusType != VaribaleStatusTypeEnum.Good).Count(),
Series = "Others"
});
data.Add(new ChartData
{
- Category = deviceThread._device.DeviceName,
+ Category = deviceThread.Device.DeviceName,
Value = deviceThread.DeviceValues.Where(x => x.Value.StatusType == VaribaleStatusTypeEnum.Good).Count(),
Series = "Good"
});
diff --git a/IoTGateway/iotgateway.db b/IoTGateway/iotgateway.db
index ee2c33f329dcc96d7db6fbe3fac8e4c7ebe1268d..f66e24bd9345e10f51af4782a4e21bf5daace2ae 100644
GIT binary patch
delta 325
zcmZo@5N>D?o**r#!N9=a1H|4y%m&1&6LpMPH5l~#Yd5AW;1}WG`^>=qg#RG_0{%Mw
zSbjTx3BJ#p6%}stX(@9sJBu3`7#SH@7#bLu85oZY$<-ulOl=F8mn~pX002b?SGWKG
delta 224
zcmZo@5N>D?o**r#&cMLn1H|4y%m&0N6LpMP)fx1xKWlO6PBCR@s%2CA}Q;D5z`hJOS9Wd3rXIvb!WHU4HB{p~jT
zjHd*|J~Hqh=F8{P;JL{&g*%H|oB0#hCx(yHWgHmyPc~2x+rGkyk%^hpM4Vk*Rh6+#
zd;3!d#x;!FSGY39d9lPY@W%p;^W>M@0CXP&G%7IigeuE3=_)#lJBxEnkDJdprELLY
P+XAMx1 _logger;
- public DriverService _DrvierManager;
+ public DriverService DrvierManager;
public List DeviceThreads = new List();
- private MyMqttClient _MyMqttClient;
- private IMqttServer _MqttServer;
- private string connnectSetting = IoTBackgroundService.connnectSetting;
- private DBTypeEnum DBType = IoTBackgroundService.DBType;
- public DeviceService(IConfiguration ConfigRoot, DriverService drvierManager, MyMqttClient myMqttClient, UAService uAService, IMqttServer mqttServer, ILogger logger)
+ private readonly MyMqttClient _myMqttClient;
+ private readonly UAService _uAService;
+ private readonly IMqttServer _mqttServer;
+ private readonly string _connnectSetting = IoTBackgroundService.connnectSetting;
+ private readonly DBTypeEnum _dbType = IoTBackgroundService.DbType;
+
+ public DeviceService(IConfiguration configRoot, DriverService drvierManager, MyMqttClient myMqttClient,
+ UAService uAService, IMqttServer mqttServer, ILogger logger)
{
+ if (mqttServer == null) throw new ArgumentNullException(nameof(mqttServer));
_logger = logger;
- _DrvierManager = drvierManager;
- _MyMqttClient = myMqttClient;
- _MqttServer = mqttServer;
+ DrvierManager = drvierManager;
+ _myMqttClient = myMqttClient;
+ _uAService = uAService;
+ _mqttServer = mqttServer ?? throw new ArgumentNullException(nameof(mqttServer));
try
{
- using (var DC = new DataContext(connnectSetting, DBType))
+ using (var dc = new DataContext(_connnectSetting, _dbType))
{
- var Devices = DC.Set().Where(x => x.DeviceTypeEnum == DeviceTypeEnum.Device).Include(x => x.Parent).Include(x => x.Driver).Include(x => x.DeviceConfigs).Include(x => x.DeviceVariables).AsNoTracking().ToList();
- _logger.LogInformation($"Loaded Devices Count:{Devices.Count()}");
- foreach (var Device in Devices)
+ var devices = dc.Set().Where(x => x.DeviceTypeEnum == DeviceTypeEnum.Device)
+ .Include(x => x.Parent).Include(x => x.Driver).Include(x => x.DeviceConfigs)
+ .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)
{
-
_logger.LogError($"LoadDevicesError", ex);
}
}
@@ -61,7 +65,6 @@ namespace Plugin
{
_logger.LogError($"UpdateDevice Error:{device.DeviceName}", ex);
}
-
}
public void UpdateDevices(List devices)
@@ -70,31 +73,33 @@ namespace Plugin
UpdateDevice(device);
}
- public void CreateDeviceThread(Device Device)
+ public void CreateDeviceThread(Device device)
{
try
{
- _logger.LogInformation($"CreateDeviceThread Start:{Device.DeviceName}");
- using (var DC = new DataContext(connnectSetting, DBType))
+ _logger.LogInformation($"CreateDeviceThread Start:{device.DeviceName}");
+ using (var dc = new DataContext(_connnectSetting, _dbType))
{
- var systemManage = DC.Set().FirstOrDefault();
- var driver = _DrvierManager.DriverInfos.Where(x => x.Type.FullName == Device.Driver.AssembleName).SingleOrDefault();
+ var systemManage = dc.Set().FirstOrDefault();
+ var driver = DrvierManager.DriverInfos
+ .SingleOrDefault(x => x.Type.FullName == device.Driver.AssembleName);
if (driver == null)
- _logger.LogError($"找不到设备:[{Device.DeviceName}]的驱动:[{Device.Driver.AssembleName}]");
+ _logger.LogError($"找不到设备:[{device.DeviceName}]的驱动:[{device.Driver.AssembleName}]");
else
{
- var settings = DC.Set().Where(x => x.DeviceId == Device.ID).AsNoTracking().ToList();
+ var settings = dc.Set().Where(x => x.DeviceId == device.ID).AsNoTracking()
+ .ToList();
- Type[] types = new Type[2] { typeof(string) ,typeof(ILogger) };
- object[] param = new object[2] { Device.DeviceName , _logger };
+ Type[] types = new Type[] { typeof(string), typeof(ILogger) };
+ object[] param = new object[] { device.DeviceName, _logger };
- ConstructorInfo constructor = driver.Type.GetConstructor(types);
- var DeviceObj = constructor.Invoke(param) as IDriver;
+ ConstructorInfo? constructor = driver.Type.GetConstructor(types);
+ var deviceObj = constructor?.Invoke(param) as IDriver;
foreach (var p in driver.Type.GetProperties())
{
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)
continue;
@@ -135,24 +140,25 @@ namespace Plugin
else if (p.PropertyType.BaseType == typeof(Enum))
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);
- DeviceThreads.Add(deviceThread);
+ if (deviceObj != null && systemManage != null)
+ {
+ var deviceThread = new DeviceThread(device, deviceObj, systemManage.GatewayName,
+ _myMqttClient,
+ _mqttServer, _logger);
+ DeviceThreads.Add(deviceThread);
+ }
}
-
-
}
- _logger.LogInformation($"CreateDeviceThread End:{Device.DeviceName}");
+ _logger.LogInformation($"CreateDeviceThread End:{device.DeviceName}");
}
catch (Exception ex)
{
- _logger.LogInformation($"CreateDeviceThread Error:{Device.DeviceName}", ex);
-
+ _logger.LogInformation($"CreateDeviceThread Error:{device.DeviceName}", ex);
}
-
}
public void CreateDeviceThreads(List devices)
@@ -163,15 +169,12 @@ namespace Plugin
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();
- if (DeviceThread != null)
- {
- DeviceThread.StopThread();
- DeviceThread.Dispose();
- DeviceThreads.Remove(DeviceThread);
- }
+ deviceThread.StopThread();
+ deviceThread.Dispose();
+ DeviceThreads.Remove(deviceThread);
}
}
@@ -187,26 +190,29 @@ namespace Plugin
try
{
_logger.LogInformation($"GetDriverMethods Start:{deviceId}");
- foreach (var method in DeviceThreads.Where(x => x._device.ID == deviceId).FirstOrDefault()?.Methods)
- {
- var Attribute = method.CustomAttributes.ToList().FirstOrDefault().ConstructorArguments;
- var item = new ComboSelectListItem
+ var methodInfos = DeviceThreads.FirstOrDefault(x => x.Device.ID == deviceId)?.Methods;
+ if (methodInfos != null)
+ foreach (var method in methodInfos)
{
- Text = method.Name,
- Value = method.Name,
- };
- driverFilesComboSelect.Add(item);
- }
+ var attribute = method.CustomAttributes.ToList().FirstOrDefault()?.ConstructorArguments;
+ var item = new ComboSelectListItem
+ {
+ Text = method.Name,
+ Value = method.Name,
+ };
+ driverFilesComboSelect.Add(item);
+ }
+
_logger.LogInformation($"GetDriverMethods End:{deviceId}");
}
catch (Exception ex)
{
-
- _logger.LogInformation($"GetDriverMethods Error:{deviceId}");
+ _logger.LogError($"GetDriverMethods Error:{deviceId}", ex);
}
return driverFilesComboSelect;
}
+
public void Dispose()
{
_logger.LogInformation("Dispose");
@@ -222,4 +228,4 @@ namespace Plugin
return Task.CompletedTask;
}
}
-}
+}
\ No newline at end of file
diff --git a/Plugins/Plugin/DeviceThread.cs b/Plugins/Plugin/DeviceThread.cs
index 7c85252..2c99d72 100644
--- a/Plugins/Plugin/DeviceThread.cs
+++ b/Plugins/Plugin/DeviceThread.cs
@@ -12,51 +12,55 @@ namespace Plugin
public class DeviceThread : IDisposable
{
private readonly ILogger _logger;
- public readonly Device _device;
- public readonly IDriver _driver;
- private readonly MyMqttClient _myMqttClient;
- private Interpreter _interpreter ;
+ public readonly Device Device;
+ public readonly IDriver Driver;
+ private readonly string _projectId;
+ private readonly MyMqttClient? _myMqttClient;
+ private Interpreter? _interpreter;
public Dictionary DeviceValues { get; set; } = new();
- internal List Methods { get; set; }
- private Task task { get; set; } = null;
- private DateTime TsStartDt = new DateTime(1970, 1, 1);
- private CancellationTokenSource tokenSource = new CancellationTokenSource();
- private object _lock = new object();
- private bool lastConnected = false;
- public DeviceThread(Device device, IDriver driver, string ProjectId, MyMqttClient myMqttClient, IMqttServer mqttServer, ILogger logger)
+ internal List? Methods { get; set; }
+ private Task? _task;
+ private readonly DateTime _tsStartDt = new(1970, 1, 1);
+ private readonly CancellationTokenSource _tokenSource = new CancellationTokenSource();
+ private readonly object _lock = new();
+ private bool _lastConnected;
+
+ public DeviceThread(Device device, IDriver driver, string projectId, MyMqttClient myMqttClient,
+ IMqttServer mqttServer, ILogger logger)
{
_myMqttClient = myMqttClient;
_myMqttClient.OnExcRpc += MyMqttClient_OnExcRpc;
- _device = device;
- _driver = driver;
+ Device = device;
+ Driver = driver;
+ _projectId = projectId;
_interpreter = new Interpreter();
_logger = logger;
- Methods = _driver.GetType().GetMethods().Where(x => x.GetCustomAttribute(typeof(MethodAttribute)) != null).ToList();
- if (_device.AutoStart)
+ Methods = Driver.GetType().GetMethods().Where(x => x.GetCustomAttribute(typeof(MethodAttribute)) != null)
+ .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);//上传客户端属性
- myMqttClient.UploadAttributeAsync(device.DeviceName, device.DeviceConfigs.Where(x => x.DataSide == DataSide.ClientSide).ToDictionary(x => x.DeviceConfigName, x => x.Value));
+ Thread.Sleep(5000); //上传客户端属性
+ myMqttClient.UploadAttributeAsync(device.DeviceName,
+ device.DeviceConfigs.Where(x => x.DataSide == DataSide.ClientSide)
+ .ToDictionary(x => x.DeviceConfigName, x => x.Value));
while (true)
{
- if (tokenSource.IsCancellationRequested)
+ if (_tokenSource.IsCancellationRequested)
{
- _logger.LogInformation($"停止线程:{_device.DeviceName}");
+ _logger.LogInformation($"停止线程:{Device.DeviceName}");
return;
}
@@ -64,15 +68,15 @@ namespace Plugin
{
try
{
- Dictionary> sendModel = new() { { _device.DeviceName, new() } };
+ Dictionary> sendModel = new() { { Device.DeviceName, new() } };
var payLoad = new PayLoad() { Values = new() };
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 ioarg = new DriverAddressIoArgModel
@@ -85,13 +89,16 @@ namespace Plugin
if (method == null)
ret.StatusType = VaribaleStatusTypeEnum.MethodError;
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
{
- 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)
{
@@ -106,18 +113,25 @@ namespace Plugin
ret.VarId = item.ID;
//变化了才推送到mqttserver,用于前端展示
- if (DeviceValues[item.ID].StatusType != ret.StatusType || DeviceValues[item.ID].Value?.ToString() != ret.Value?.ToString() || DeviceValues[item.ID].CookedValue?.ToString() != ret.CookedValue?.ToString())
+ 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;
-
}
- payLoad.TS = (long)(DateTime.UtcNow - TsStartDt).TotalMilliseconds;
+
+ payLoad.TS = (long)(DateTime.UtcNow - _tsStartDt).TotalMilliseconds;
if (DeviceValues.Any(x => x.Value.Value == null))
{
@@ -127,74 +141,75 @@ namespace Plugin
else
{
payLoad.DeviceStatus = DeviceStatusTypeEnum.Good;
- sendModel[_device.DeviceName] = new List { payLoad };
- myMqttClient.PublishTelemetry(_device, sendModel);
+ sendModel[Device.DeviceName] = new List { payLoad };
+ myMqttClient.PublishTelemetryAsync(Device, sendModel);
}
}
-
}
else
{
if (driver.Connect())
{
- lastConnected = true;
- _myMqttClient.DeviceConnected(_device.DeviceName);
+ _lastConnected = true;
+ _myMqttClient?.DeviceConnected(Device);
}
- else if (lastConnected)
+ else if (_lastConnected)
{
- lastConnected = false;
- _myMqttClient.DeviceDisconnected(_device.DeviceName);
+ _lastConnected = false;
+ _myMqttClient?.DeviceDisconnected(Device);
}
}
}
catch (Exception ex)
{
- _logger.LogError($"线程循环异常,{_device.DeviceName}", ex);
+ _logger.LogError($"线程循环异常,{Device.DeviceName}", ex);
}
}
- Thread.Sleep((int)_driver.MinPeriod);
+ Thread.Sleep((int)Driver.MinPeriod);
}
});
}
else
- _myMqttClient.DeviceDisconnected(_device.DeviceName);
+ _myMqttClient?.DeviceDisconnected(Device);
}
public void MyMqttClient_OnExcRpc(object? sender, RpcRequest e)
{
- if (e.DeviceName == _device.DeviceName)
+ if (e.DeviceName == Device.DeviceName)
{
RpcLog rpcLog = new RpcLog()
{
- DeviceId = _device.ID,
+ DeviceId = Device.ID,
StartTime = DateTime.Now,
Method = e.Method,
RpcSide = RpcSide.ServerSide,
Params = JsonConvert.SerializeObject(e.Params)
};
- _logger.LogInformation($"{_device.DeviceName}收到RPC,{e}");
- RpcResponse rpcResponse = new() { DeviceName = e.DeviceName, RequestId = e.RequestId, IsSuccess = false };
+ _logger.LogInformation($"{Device.DeviceName}收到RPC,{e}");
+ RpcResponse rpcResponse = new()
+ { DeviceName = e.DeviceName, RequestId = e.RequestId, IsSuccess = false };
//执行写入变量RPC
if (e.Method.ToLower() == "write")
{
lock (_lock)
{
- bool RpcConnected = false;
+ bool rpcConnected = false;
//没连接就连接
- if (!_driver.IsConnected)
- if (_driver.Connect())
- RpcConnected = true;
+ if (!Driver.IsConnected)
+ if (Driver.Connect())
+ rpcConnected = true;
//连接成功就尝试一个一个的写入,注意:目前写入地址和读取地址是相同的,对于PLC来说没问题,其他的要自己改........
- if (_driver.IsConnected)
+ if (Driver.IsConnected)
{
foreach (var para in e.Params)
{
//先查配置项,要用到配置的地址、数据类型、方法(方法最主要是用于区分写入数据的辅助判断,比如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)
{
DriverAddressIoArgModel ioArgModel = new()
@@ -203,7 +218,8 @@ namespace Plugin
Value = para.Value,
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;
if (!writeResponse.IsSuccess)
{
@@ -218,17 +234,16 @@ namespace Plugin
break;
}
}
- if (RpcConnected)
- _driver.Close();
+ if (rpcConnected)
+ Driver.Close();
}
- else//连接失败
+ else //连接失败
{
rpcResponse.IsSuccess = false;
rpcResponse.Description = $"{e.DeviceName} 连接失败";
}
}
-
}
//其他RPC TODO
else
@@ -238,47 +253,46 @@ namespace Plugin
}
//反馈RPC
- _myMqttClient.ResponseRpc(rpcResponse);
+ _myMqttClient.ResponseRpcAsync(rpcResponse);
//纪录入库
rpcLog.IsSuccess = rpcResponse.IsSuccess;
rpcLog.Description = rpcResponse.Description;
rpcLog.EndTime = DateTime.Now;
- using (var DC = new DataContext(IoTBackgroundService.connnectSetting, IoTBackgroundService.DBType))
+ using (var dc = new DataContext(IoTBackgroundService.connnectSetting, IoTBackgroundService.DbType))
{
- DC.Set().Add(rpcLog);
- DC.SaveChanges();
+ dc.Set().Add(rpcLog);
+ dc.SaveChanges();
}
}
}
public void StopThread()
{
- _logger.LogInformation($"线程停止:{_device.DeviceName}");
- _myMqttClient.DeviceDisconnected(_device.DeviceName);
- if (task != null)
+ _logger.LogInformation($"线程停止:{Device.DeviceName}");
+ _myMqttClient?.DeviceDisconnected(Device);
+ if (_task != null)
{
- _myMqttClient.OnExcRpc -= MyMqttClient_OnExcRpc;
- tokenSource.Cancel();
- _driver.Close();
+ if (_myMqttClient != null) _myMqttClient.OnExcRpc -= MyMqttClient_OnExcRpc;
+ _tokenSource.Cancel();
+ Driver.Close();
}
}
public void Dispose()
{
- _driver.Dispose();
+ Driver.Dispose();
_interpreter = null;
DeviceValues = null;
Methods = null;
- _logger.LogInformation($"线程释放,{_device.DeviceName}");
+ _logger.LogInformation($"线程释放,{Device.DeviceName}");
}
//mysql会把一些符号转义,没找到原因,先临时处理下
- private string DealMysqlStr(string Expression)
+ private string DealMysqlStr(string expression)
{
- return Expression.Replace("<", "<").Replace(">", ">").Replace("&", "&").Replace(""", "\"");
+ return expression.Replace("<", "<").Replace(">", ">").Replace("&", "&").Replace(""", "\"");
}
}
-
-}
+}
\ No newline at end of file
diff --git a/Plugins/Plugin/DriverInfo.cs b/Plugins/Plugin/DriverInfo.cs
index e54124e..3088213 100644
--- a/Plugins/Plugin/DriverInfo.cs
+++ b/Plugins/Plugin/DriverInfo.cs
@@ -1,13 +1,8 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading.Tasks;
-
-namespace Plugin
+namespace Plugin
{
public class DriverInfo
{
- public string FileName;
- public Type Type;
+ public string? FileName;
+ public Type? Type;
}
}
diff --git a/Plugins/Plugin/DrvierService.cs b/Plugins/Plugin/DrvierService.cs
index fbbb467..ece892e 100644
--- a/Plugins/Plugin/DrvierService.cs
+++ b/Plugins/Plugin/DrvierService.cs
@@ -1,13 +1,8 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using PluginInterface;
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
using System.Reflection;
using System.Text.Json;
-using System.Threading.Tasks;
using WalkingTec.Mvvm.Core;
using IoTGateway.DataAccess;
using IoTGateway.Model;
@@ -15,110 +10,111 @@ using Microsoft.Extensions.Logging;
namespace Plugin
{
- public class DriverService//: IDependency
+ public class DriverService
{
private readonly ILogger _logger;
- string DriverPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"drivers/net6.0");
- string[] driverFiles;
- public List DriverInfos = new List();
- public DriverService(IConfiguration ConfigRoot, ILogger logger)
+ readonly string _driverPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"drivers/net6.0");
+ readonly string[] _driverFiles;
+ public List DriverInfos = new();
+
+ public DriverService(IConfiguration configRoot, ILogger logger)
{
_logger = logger;
try
{
_logger.LogInformation("LoadDriverFiles Start");
- driverFiles = Directory.GetFiles(DriverPath).Where(x => Path.GetExtension(x) == ".dll").ToArray();
- _logger.LogInformation($"LoadDriverFiles End,Count{driverFiles.Count()}");
+ _driverFiles = Directory.GetFiles(_driverPath).Where(x => Path.GetExtension(x) == ".dll").ToArray();
+ _logger.LogInformation($"LoadDriverFiles End,Count{_driverFiles.Count()}");
}
catch (Exception ex)
{
_logger.LogError("LoadDriverFiles Error", ex);
}
+
LoadAllDrivers();
}
+
public List GetAllDrivers()
{
List driverFilesComboSelect = new List();
- using (var DC = new DataContext(IoTBackgroundService.connnectSetting, IoTBackgroundService.DBType))
- {
- var Drivers = DC.Set().AsNoTracking().ToList();
+ using var dc = new DataContext(IoTBackgroundService.connnectSetting, IoTBackgroundService.DbType);
+ var drivers = dc.Set().AsNoTracking().ToList();
- foreach (var file in driverFiles)
+ foreach (var file in _driverFiles)
+ {
+ var dll = Assembly.LoadFrom(file);
+ if (dll.GetTypes().Where(x => typeof(IDriver).IsAssignableFrom(x) && x.IsClass).Any())
{
- var dll = Assembly.LoadFrom(file);
- if (dll.GetTypes().Where(x => typeof(IDriver).IsAssignableFrom(x) && x.IsClass).Any())
+ var fileName = Path.GetFileName(file);
+ var item = new ComboSelectListItem
{
- var fileName = Path.GetFileName(file);
- var item = new ComboSelectListItem
- {
- Text = fileName,
- Value = fileName,
- Disabled = false,
- };
- if (Drivers.Where(x => x.FileName == Path.GetFileName(file)).Any())
- item.Disabled = true;
- driverFilesComboSelect.Add(item);
- }
+ Text = fileName,
+ Value = fileName,
+ Disabled = false,
+ };
+ if (drivers.Where(x => x.FileName == Path.GetFileName(file)).Any())
+ item.Disabled = true;
+ driverFilesComboSelect.Add(item);
}
}
+
return driverFilesComboSelect;
}
-
-
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 type = dll.GetTypes().Where(x => typeof(IDriver).IsAssignableFrom(x) && x.IsClass).FirstOrDefault();
- return type.FullName;
+ var type = dll.GetTypes().FirstOrDefault(x => typeof(IDriver).IsAssignableFrom(x) && x.IsClass);
+ 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().Where(x => x.ID == dapId).AsNoTracking().SingleOrDefault();
+ var driver = dc.Set().Where(x => x.ID == driverId).AsNoTracking().SingleOrDefault();
+ var type = DriverInfos.SingleOrDefault(x => x.Type.FullName == driver?.AssembleName);
+
+ Type[] types = { typeof(string), typeof(ILogger) };
+ object[] param = { device?.DeviceName, _logger };
+
+ ConstructorInfo? constructor = type?.Type.GetConstructor(types);
+ var iObj = constructor?.Invoke(param) as IDriver;
+
+ foreach (var property in type?.Type.GetProperties())
{
- var device = DC.Set().Where(x => x.ID == dapID).AsNoTracking().SingleOrDefault();
- var driver = DC.Set().Where(x => x.ID == DriverId).AsNoTracking().SingleOrDefault();
- var type = DriverInfos.Where(x => x.Type.FullName == driver.AssembleName).SingleOrDefault();
-
- Type[] types = new Type[2] { typeof(string), typeof(ILogger) };
- object[] param = new object[2] { device.DeviceName, _logger };
-
- ConstructorInfo constructor = type.Type.GetConstructor(types);
- var iObj = constructor.Invoke(param) as IDriver;
-
- foreach (var property in type.Type.GetProperties())
+ var config = property.GetCustomAttribute(typeof(ConfigParameterAttribute));
+ if (config != null)
{
- var config = property.GetCustomAttribute(typeof(ConfigParameterAttribute));
- if (config != null)
+ var dapConfig = new DeviceConfig
{
- var DapConfig = new DeviceConfig
- {
- ID = Guid.NewGuid(),
- DeviceId = dapID,
- DeviceConfigName = property.Name,
- DataSide= DataSide.AnySide,
- Description = ((ConfigParameterAttribute)config).Description,
- Value = property.GetValue(iObj)?.ToString()
- };
+ ID = Guid.NewGuid(),
+ DeviceId = dapId,
+ DeviceConfigName = property.Name,
+ DataSide = DataSide.AnySide,
+ Description = ((ConfigParameterAttribute)config).Description,
+ Value = property.GetValue(iObj)?.ToString()
+ };
- if (property.PropertyType.BaseType == typeof(Enum))
- {
- var fields = property.PropertyType.GetFields(BindingFlags.Static | BindingFlags.Public);
- var EnumInfos = fields.ToDictionary(f => f.Name, f => (int)f.GetValue(null));
- DapConfig.EnumInfo = JsonSerializer.Serialize(EnumInfos);
- }
-
- DC.Set().Add(DapConfig);
+ if (property.PropertyType.BaseType == typeof(Enum))
+ {
+ var fields = property.PropertyType.GetFields(BindingFlags.Static | BindingFlags.Public);
+ var enumInfos = fields.ToDictionary(f => f.Name, f => (int)f.GetValue(null));
+ dapConfig.EnumInfo = JsonSerializer.Serialize(enumInfos);
}
+
+ dc.Set().Add(dapConfig);
}
- DC.SaveChanges();
}
+
+ dc.SaveChanges();
}
+
public void LoadAllDrivers()
{
_logger.LogInformation("LoadAllDrivers Start");
- foreach (var file in driverFiles)
+ foreach (var file in _driverFiles)
{
try
{
@@ -138,34 +134,30 @@ namespace Plugin
{
_logger.LogDebug($"LoadAllDrivers Error {ex}");
}
-
}
- _logger.LogInformation($"LoadAllDrivers End,Count{DriverInfos.Count}");
+ _logger.LogInformation($"LoadAllDrivers End,Count{DriverInfos.Count}");
}
public void LoadRegestedDeviers()
{
- using (var DC = new DataContext(IoTBackgroundService.connnectSetting, IoTBackgroundService.DBType))
- {
- var Drivers = DC.Set().AsNoTracking().ToList();
+ using var dc = new DataContext(IoTBackgroundService.connnectSetting, IoTBackgroundService.DbType);
- var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"drivers/net5.0");
- var files = Directory.GetFiles(path).Where(x => Path.GetExtension(x) == ".dll").ToArray();
- foreach (var file in files)
+ var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"drivers/net6.0");
+ var files = Directory.GetFiles(path).Where(x => Path.GetExtension(x) == ".dll").ToArray();
+ foreach (var file in files)
+ {
+ var dll = Assembly.LoadFrom(file);
+ foreach (var type in dll.GetTypes().Where(x => typeof(IDriver).IsAssignableFrom(x) && x.IsClass))
{
- var dll = Assembly.LoadFrom(file);
- foreach (var type in dll.GetTypes().Where(x => typeof(IDriver).IsAssignableFrom(x) && x.IsClass))
+ DriverInfo driverInfo = new DriverInfo
{
- DriverInfo driverInfo = new DriverInfo
- {
- FileName = Path.GetFileName(file),
- Type = type
- };
- DriverInfos.Add(driverInfo);
- }
+ FileName = Path.GetFileName(file),
+ Type = type
+ };
+ DriverInfos.Add(driverInfo);
}
}
}
}
-}
+}
\ No newline at end of file
diff --git a/Plugins/Plugin/IoTBackgroundService.cs b/Plugins/Plugin/IoTBackgroundService.cs
index 6cc9c58..e3be538 100644
--- a/Plugins/Plugin/IoTBackgroundService.cs
+++ b/Plugins/Plugin/IoTBackgroundService.cs
@@ -1,44 +1,36 @@
using Microsoft.Extensions.Configuration;
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;
namespace Plugin
{
public class IoTBackgroundService : BackgroundService
{
- public static DBTypeEnum DBType;
+ public static DBTypeEnum DbType;
public static string connnectSetting;
public static Guid? VariableSelectDeviceId, ConfigSelectDeviceId;
- public IoTBackgroundService(IConfiguration ConfigRoot)
+ public IoTBackgroundService(IConfiguration configRoot)
{
var connnectSettings = new List();
- ConfigRoot.Bind("Connections", connnectSettings);
+ configRoot.Bind("Connections", connnectSettings);
connnectSetting = connnectSettings[0].Value;
- switch (connnectSettings[0].DBType.Trim().ToLower())
+ switch (connnectSettings[0].DbType?.Trim().ToLower())
{
case "oracle":
- DBType = DBTypeEnum.Oracle;
+ DbType = DBTypeEnum.Oracle;
break;
case "mysql":
- DBType = DBTypeEnum.MySql;
+ DbType = DBTypeEnum.MySql;
break;
case "pgsql":
- DBType = DBTypeEnum.PgSql;
+ DbType = DBTypeEnum.PgSql;
break;
case "sqlite":
- DBType = DBTypeEnum.SQLite;
+ DbType = DBTypeEnum.SQLite;
break;
case "memory":
- DBType = DBTypeEnum.Memory;
- break;
- default:
+ DbType = DBTypeEnum.Memory;
break;
}
}
diff --git a/Plugins/Plugin/ModbusSlaveService.cs b/Plugins/Plugin/ModbusSlaveService.cs
index 8944e62..4a95cb4 100644
--- a/Plugins/Plugin/ModbusSlaveService.cs
+++ b/Plugins/Plugin/ModbusSlaveService.cs
@@ -1,24 +1,19 @@
using Microsoft.Extensions.Logging;
using Modbus.Data;
using Modbus.Device;
-using System;
-using System.Collections.Generic;
-using System.Linq;
using System.Net;
using System.Net.Sockets;
-using System.Text;
-using System.Threading.Tasks;
namespace Plugin
{
public class ModbusSlaveService : IDisposable
{
private readonly ILogger _logger;
- TcpListener slaveTcpListener;
- private Timer m_simulationTimer;
- private object Lock=new object();
- private ModbusSlave slave;
- private Task task { get; set; } = null;
+ readonly TcpListener _slaveTcpListener;
+ private readonly Timer _mSimulationTimer;
+ private readonly object _lock = new();
+ private readonly ModbusSlave _slave;
+ private Task _task;
public ModbusSlaveService(ILogger logger)
{
_logger = logger;
@@ -27,12 +22,12 @@ namespace Plugin
IPAddress address = IPAddress.Any;
// create and start the TCP slave
- slaveTcpListener = new TcpListener(address, port);
- slaveTcpListener.Start();
- slave = ModbusTcpSlave.CreateTcp(slaveId, slaveTcpListener);
- slave.DataStore = DataStoreFactory.CreateDefaultDataStore();
- slave.ListenAsync();
- m_simulationTimer = new Timer(DoSimulation, null, 1000, 1000);
+ _slaveTcpListener = new TcpListener(address, port);
+ _slaveTcpListener.Start();
+ _slave = ModbusTcpSlave.CreateTcp(slaveId, _slaveTcpListener);
+ _slave.DataStore = DataStoreFactory.CreateDefaultDataStore();
+ _slave.ListenAsync();
+ _mSimulationTimer = new Timer(DoSimulation, null, 1000, 1000);
_logger.LogInformation($"Modbus Server Started");
}
@@ -40,19 +35,19 @@ namespace Plugin
{
try
{
- lock (Lock)
+ lock (_lock)
{
for (int i = 1; i <= 20; i++)
{
- if(i != 1|| i != 2|| i != 7)
- slave.DataStore.HoldingRegisters[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.InputDiscretes[i] = new Random().Next() % 2 == 0;
+ if (i != 1 || i != 2 || i != 7)
+ _slave.DataStore.HoldingRegisters[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.InputDiscretes[i] = new Random().Next() % 2 == 0;
}
- slave.DataStore.HoldingRegisters[1] = (ushort)new Random().Next(2000,3000); //前端要用的温度
- slave.DataStore.HoldingRegisters[2] = (ushort)new Random().Next(4000, 7000);//湿度
- slave.DataStore.HoldingRegisters[7] = (ushort)new Random().Next(0, 10000);//随机值
+ _slave.DataStore.HoldingRegisters[1] = (ushort)new Random().Next(2000, 3000); //前端要用的温度
+ _slave.DataStore.HoldingRegisters[2] = (ushort)new Random().Next(4000, 7000);//湿度
+ _slave.DataStore.HoldingRegisters[7] = (ushort)new Random().Next(0, 10000);//随机值
}
}
catch (Exception ex)
@@ -63,8 +58,8 @@ namespace Plugin
public void Dispose()
{
_logger.LogError($"Modbus Server Dispose");
- m_simulationTimer.Dispose();
- slaveTcpListener.Stop();
+ _mSimulationTimer.Dispose();
+ _slaveTcpListener.Stop();
}
}
}
diff --git a/Plugins/Plugin/MyMqttClient.cs b/Plugins/Plugin/MyMqttClient.cs
index 7442550..c3b2d45 100644
--- a/Plugins/Plugin/MyMqttClient.cs
+++ b/Plugins/Plugin/MyMqttClient.cs
@@ -10,6 +10,7 @@ using MQTTnet.Client.Receiving;
using MQTTnet.Protocol;
using Newtonsoft.Json;
using PluginInterface;
+using PluginInterface.HuaWeiRoma;
using PluginInterface.IotDB;
using PluginInterface.IoTSharp;
using PluginInterface.ThingsBoard;
@@ -20,14 +21,15 @@ namespace Plugin
public class MyMqttClient
{
private readonly ILogger _logger;
- private readonly ReferenceNodeManager _uaNodeManager = null;
+ private readonly ReferenceNodeManager? _uaNodeManager;
private SystemConfig? _systemConfig;
- private IMqttClientOptions clientOptions;
- public bool IsConnected => (Client?.IsConnected).GetValueOrDefault();
+ private IMqttClientOptions _clientOptions;
+ public bool IsConnected => (Client.IsConnected);
private IMqttClient Client { get; set; }
public event EventHandler OnExcRpc;
public event EventHandler OnReceiveAttributes;
+
public MyMqttClient(UAService uaService, ILogger logger)
{
_logger = logger;
@@ -35,126 +37,129 @@ namespace Plugin
ConnectAsync();
}
- public async Task ConnectAsync()
+ public async Task ConnectAsync()
{
- bool initok = false;
try
{
- using (var DC = new DataContext(IoTBackgroundService.connnectSetting, IoTBackgroundService.DBType))
+ await using var dc = new DataContext(IoTBackgroundService.connnectSetting, IoTBackgroundService.DbType);
+ _systemConfig = dc.Set().FirstOrDefault();
+ if (_systemConfig == null)
{
- _systemConfig = DC.Set().FirstOrDefault();
- if (_systemConfig == null)
+ _systemConfig = new SystemConfig()
{
- _systemConfig = new SystemConfig()
- {
- ID = Guid.NewGuid(),
- GatewayName = "iotgateway",
- MqttIp = "localhost",
- MqttPort = 1888,
- MqttUName = "user",
- MqttUPwd = "pwd",
- IoTPlatformType = IoTPlatformType.IoTSharp
- };
- DC.Set().Add(_systemConfig);
- DC.SaveChanges();
- }
- var factory = new MqttFactory();
- Client = (MqttClient)factory.CreateMqttClient();
- clientOptions = new MqttClientOptionsBuilder()
- .WithClientId(_systemConfig.GatewayName + Guid.NewGuid().ToString())
- .WithTcpServer(_systemConfig.MqttIp, _systemConfig.MqttPort)
- .WithCredentials(_systemConfig.MqttUName, _systemConfig.MqttUPwd)
- .WithCommunicationTimeout(TimeSpan.FromSeconds(30))
- .WithKeepAlivePeriod(TimeSpan.FromSeconds(20))
- .Build();
-
- Client.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(Client_ApplicationMessageReceived);
- Client.ConnectedHandler = new MqttClientConnectedHandlerDelegate(x => OnConnected());
- Client.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(x => OnDisconnectedAsync());
- try
- {
- Client.ConnectAsync(clientOptions);
- initok = true;
- }
- catch (Exception exception)
- {
- _logger.LogError("MQTT CONNECTING FAILED", exception);
- }
- _logger.LogInformation("MQTT WAITING FOR APPLICATION MESSAGES");
+ ID = Guid.NewGuid(),
+ GatewayName = "iotgateway",
+ ClientId = Guid.NewGuid().ToString(),
+ MqttIp = "localhost",
+ MqttPort = 1888,
+ MqttUName = "user",
+ MqttUPwd = "pwd",
+ IoTPlatformType = IoTPlatformType.IoTSharp
+ };
+ dc.Set().Add(_systemConfig);
+ await dc.SaveChangesAsync();
}
+
+ var factory = new MqttFactory();
+ Client = (MqttClient)factory.CreateMqttClient();
+ _clientOptions = new MqttClientOptionsBuilder()
+ .WithClientId(_systemConfig.ClientId ?? Guid.NewGuid().ToString())
+ .WithTcpServer(_systemConfig.MqttIp, _systemConfig.MqttPort)
+ .WithCredentials(_systemConfig.MqttUName, _systemConfig.MqttUPwd)
+ .WithCommunicationTimeout(TimeSpan.FromSeconds(30))
+ .WithKeepAlivePeriod(TimeSpan.FromSeconds(20))
+ .Build();
+
+ Client.ApplicationMessageReceivedHandler =
+ new MqttApplicationMessageReceivedHandlerDelegate(Client_ApplicationMessageReceived);
+ Client.ConnectedHandler = new MqttClientConnectedHandlerDelegate(_ => OnConnected());
+ Client.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(_ => OnDisconnectedAsync());
+ try
+ {
+ await Client.ConnectAsync(_clientOptions);
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError("MQTT CONNECTING FAILED", ex);
+ }
+
+ _logger.LogInformation("MQTT WAITING FOR APPLICATION MESSAGES");
}
- catch (Exception exception)
+ catch (Exception ex)
{
- _logger.LogError("MQTT CONNECTING FAILED", exception);
+ _logger.LogError("MQTT CONNECTING FAILED", ex);
}
- return initok;
}
private async Task OnDisconnectedAsync()
{
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()
{
- switch (_systemConfig.IoTPlatformType)
- {
- case IoTPlatformType.ThingsBoard:
- //{"device": "Device A", "data": {"id": $request_id, "method": "toggle_gpio", "params": {"pin":1}}}
- Client.SubscribeAsync(tbRpcTopic, MqttQualityOfServiceLevel.ExactlyOnce);
- //Message: {"id": $request_id, "device": "Device A", "value": "value1"}
- Client.SubscribeAsync("v1/gateway/attributes/response", MqttQualityOfServiceLevel.ExactlyOnce);
- //Message: {"device": "Device A", "data": {"attribute1": "value1", "attribute2": 42}}
- Client.SubscribeAsync("v1/gateway/attributes", MqttQualityOfServiceLevel.ExactlyOnce);
- break;
- case IoTPlatformType.IoTSharp:
- Client.SubscribeAsync("devices/+/rpc/request/+/+", MqttQualityOfServiceLevel.ExactlyOnce);
- Client.SubscribeAsync("devices/+/attributes/update", MqttQualityOfServiceLevel.ExactlyOnce);
- //Message: {"device": "Device A", "data": {"attribute1": "value1", "attribute2": 42}}
- Client.SubscribeAsync("devices/+/attributes/response/+", MqttQualityOfServiceLevel.ExactlyOnce);
- break;
- case IoTPlatformType.ThingsCloud:
- Client.SubscribeAsync("gateway/attributes/response", MqttQualityOfServiceLevel.ExactlyOnce);
- Client.SubscribeAsync("gateway/attributes/get/response", MqttQualityOfServiceLevel.ExactlyOnce);
- Client.SubscribeAsync("gateway/attributes/push", MqttQualityOfServiceLevel.ExactlyOnce);
- Client.SubscribeAsync("gateway/event/response", MqttQualityOfServiceLevel.ExactlyOnce);
- Client.SubscribeAsync("gateway/command/send", MqttQualityOfServiceLevel.ExactlyOnce);
- break;
- case IoTPlatformType.AliCloudIoT:
- break;
- case IoTPlatformType.TencentIoTHub:
- break;
- case IoTPlatformType.BaiduIoTCore:
- break;
- case IoTPlatformType.OneNET:
- break;
- default:
- break;
- }
+ if (_systemConfig != null)
+ switch (_systemConfig.IoTPlatformType)
+ {
+ case IoTPlatformType.ThingsBoard:
+ //{"device": "Device A", "data": {"id": $request_id, "method": "toggle_gpio", "params": {"pin":1}}}
+ Client.SubscribeAsync(_tbRpcTopic, MqttQualityOfServiceLevel.ExactlyOnce);
+ //Message: {"id": $request_id, "device": "Device A", "value": "value1"}
+ Client.SubscribeAsync("v1/gateway/attributes/response", MqttQualityOfServiceLevel.ExactlyOnce);
+ //Message: {"device": "Device A", "data": {"attribute1": "value1", "attribute2": 42}}
+ Client.SubscribeAsync("v1/gateway/attributes", MqttQualityOfServiceLevel.ExactlyOnce);
+ break;
+ case IoTPlatformType.IoTSharp:
+ Client.SubscribeAsync("devices/+/rpc/request/+/+", MqttQualityOfServiceLevel.ExactlyOnce);
+ Client.SubscribeAsync("devices/+/attributes/update", MqttQualityOfServiceLevel.ExactlyOnce);
+ //Message: {"device": "Device A", "data": {"attribute1": "value1", "attribute2": 42}}
+ Client.SubscribeAsync("devices/+/attributes/response/+", MqttQualityOfServiceLevel.ExactlyOnce);
+ break;
+ case IoTPlatformType.ThingsCloud:
+ Client.SubscribeAsync("gateway/attributes/response", MqttQualityOfServiceLevel.ExactlyOnce);
+ Client.SubscribeAsync("gateway/attributes/get/response", MqttQualityOfServiceLevel.ExactlyOnce);
+ Client.SubscribeAsync("gateway/attributes/push", MqttQualityOfServiceLevel.ExactlyOnce);
+ Client.SubscribeAsync("gateway/event/response", MqttQualityOfServiceLevel.ExactlyOnce);
+ Client.SubscribeAsync("gateway/command/send", MqttQualityOfServiceLevel.ExactlyOnce);
+ break;
+ case IoTPlatformType.AliCloudIoT:
+ break;
+ case IoTPlatformType.TencentIoTHub:
+ break;
+ case IoTPlatformType.BaiduIoTCore:
+ break;
+ case IoTPlatformType.OneNET:
+ break;
+ }
+
_logger.LogInformation($"MQTT CONNECTED WITH SERVER ");
}
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
{
- if (e.ApplicationMessage.Topic == tbRpcTopic)
+ if (e.ApplicationMessage.Topic == _tbRpcTopic)
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);
}
- 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);
}
@@ -165,8 +170,11 @@ namespace Plugin
}
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;
}
@@ -176,13 +184,13 @@ namespace Plugin
///
private void ReceiveTbRpc(MqttApplicationMessageReceivedEventArgs e)
{
- TBRpcRequest tBRpcRequest;
try
{
- tBRpcRequest = JsonConvert.DeserializeObject(e.ApplicationMessage.ConvertPayloadToString());
- if (!string.IsNullOrWhiteSpace(tBRpcRequest.RequestData.Method))
+ var tBRpcRequest =
+ JsonConvert.DeserializeObject(e.ApplicationMessage.ConvertPayloadToString());
+ if (tBRpcRequest != null && !string.IsNullOrWhiteSpace(tBRpcRequest.RequestData.Method))
{
- OnExcRpc?.Invoke(Client, new RpcRequest()
+ OnExcRpc(Client, new RpcRequest()
{
Method = tBRpcRequest.RequestData.Method,
DeviceName = tBRpcRequest.DeviceName,
@@ -193,9 +201,10 @@ namespace Plugin
}
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);
}
-
}
///
@@ -204,76 +213,81 @@ namespace Plugin
///
private void ReceiveTcRpc(MqttApplicationMessageReceivedEventArgs e)
{
- TCRpcRequest tCRpcRequest;
try
{
- tCRpcRequest = JsonConvert.DeserializeObject(e.ApplicationMessage.ConvertPayloadToString());
- OnExcRpc?.Invoke(Client, new RpcRequest()
- {
- Method = tCRpcRequest.RequestData.Method,
- DeviceName = tCRpcRequest.DeviceName,
- RequestId = tCRpcRequest.RequestData.RequestId,
- Params = tCRpcRequest.RequestData.Params
- });
+ var tCRpcRequest =
+ JsonConvert.DeserializeObject(e.ApplicationMessage.ConvertPayloadToString());
+ if (tCRpcRequest != null)
+ OnExcRpc.Invoke(Client, new RpcRequest()
+ {
+ Method = tCRpcRequest.RequestData.Method,
+ DeviceName = tCRpcRequest.DeviceName,
+ RequestId = tCRpcRequest.RequestData.RequestId,
+ Params = tCRpcRequest.RequestData.Params
+ });
}
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)
{
try
{
- var tps = e.ApplicationMessage.Topic.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
- var rpcmethodname = tps[4];
- var rpcdevicename = tps[1];
- var rpcrequestid = tps[5];
- _logger.LogInformation($"rpcmethodname={rpcmethodname} ");
- _logger.LogInformation($"rpcdevicename={rpcdevicename } ");
- _logger.LogInformation($"rpcrequestid={rpcrequestid} ");
- if (!string.IsNullOrEmpty(rpcmethodname) && !string.IsNullOrEmpty(rpcdevicename) && !string.IsNullOrEmpty(rpcrequestid))
+ var tps = e.ApplicationMessage.Topic.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
+ var rpcMethodName = tps[4];
+ var rpcDeviceName = tps[1];
+ var rpcRequestId = tps[5];
+ _logger.LogInformation($"rpcMethodName={rpcMethodName} ");
+ _logger.LogInformation($"rpcDeviceName={rpcDeviceName} ");
+ _logger.LogInformation($"rpcRequestId={rpcRequestId} ");
+ if (!string.IsNullOrEmpty(rpcMethodName) && !string.IsNullOrEmpty(rpcDeviceName) &&
+ !string.IsNullOrEmpty(rpcRequestId))
{
- OnExcRpc?.Invoke(Client, new RpcRequest()
+ OnExcRpc(Client, new RpcRequest()
{
- Method = rpcmethodname,
- DeviceName = rpcdevicename,
- RequestId = rpcrequestid,
- Params = JsonConvert.DeserializeObject>(e.ApplicationMessage.ConvertPayloadToString())
+ Method = rpcMethodName,
+ DeviceName = rpcDeviceName,
+ RequestId = rpcRequestId,
+ Params = JsonConvert.DeserializeObject>(e.ApplicationMessage
+ .ConvertPayloadToString())
});
}
}
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 Task ResponseTBRpc(TBRpcResponse tBRpcResponse)
+ private async Task ResponseTbRpcAsync(TBRpcResponse tBRpcResponse)
{
- return Client.PublishAsync(new MqttApplicationMessageBuilder()
- .WithTopic(tbRpcTopic)
+ await Client.PublishAsync(new MqttApplicationMessageBuilder()
+ .WithTopic(_tbRpcTopic)
.WithPayload(JsonConvert.SerializeObject(tBRpcResponse))
.WithQualityOfServiceLevel(MqttQualityOfServiceLevel.ExactlyOnce).Build());
}
- private Task ResponseTCRpc(TCRpcRequest tCRpcResponse)
+ private async Task ResponseTcRpcAsync(TCRpcRequest tCRpcResponse)
{
- string topic = $"command/reply/{tCRpcResponse.RequestData.RequestId}";
- return Client.PublishAsync(new MqttApplicationMessageBuilder()
+ var topic = $"command/reply/{tCRpcResponse.RequestData.RequestId}";
+ await Client.PublishAsync(new MqttApplicationMessageBuilder()
.WithTopic(topic)
.WithPayload(JsonConvert.SerializeObject(tCRpcResponse))
.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}";
- string topic = $"devices/{rpcResult.DeviceId}/rpc/response/{rpcResult.Method}/{rpcResult.ResponseId}";
- return Client.PublishAsync(new MqttApplicationMessageBuilder()
+ //var responseTopic = $"/devices/{deviceid}/rpc/response/{methodName}/{rpcid}";
+ var topic = $"devices/{rpcResult.DeviceId}/rpc/response/{rpcResult.Method}/{rpcResult.ResponseId}";
+ await Client.PublishAsync(new MqttApplicationMessageBuilder()
.WithTopic(topic)
.WithPayload(JsonConvert.SerializeObject(rpcResult))
.WithQualityOfServiceLevel(MqttQualityOfServiceLevel.ExactlyOnce).Build());
@@ -281,161 +295,199 @@ namespace Plugin
private void ReceiveAttributes(MqttApplicationMessageReceivedEventArgs e)
{
- var tps = e.ApplicationMessage.Topic.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
- var rpcmethodname = tps[2];
- var rpcdevicename = tps[1];
- var rpcrequestid = tps[4];
- _logger.LogInformation($"rpcmethodname={rpcmethodname} ");
- _logger.LogInformation($"rpcdevicename={rpcdevicename } ");
- _logger.LogInformation($"rpcrequestid={rpcrequestid} ");
+ var tps = e.ApplicationMessage.Topic.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
+ var rpcMethodName = tps[2];
+ var rpcDeviceName = tps[1];
+ var rpcRequestId = tps[4];
+ _logger.LogInformation($"rpcMethodName={rpcMethodName}");
+ _logger.LogInformation($"rpcDeviceName={rpcDeviceName}");
+ _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/"))
{
- OnReceiveAttributes?.Invoke(Client, new ISAttributeResponse()
+ OnReceiveAttributes.Invoke(Client, new ISAttributeResponse()
{
- KeyName = rpcmethodname,
- DeviceName = rpcdevicename,
- Id = rpcrequestid,
+ KeyName = rpcMethodName,
+ DeviceName = rpcDeviceName,
+ Id = rpcRequestId,
Data = e.ApplicationMessage.ConvertPayloadToString()
});
}
}
}
- public Task UploadAttributeAsync(string _devicename, object obj)
+ public Task UploadAttributeAsync(string deviceName, object obj)
{
//Topic: v1/gateway/attributes
//Message: {"Device A":{"attribute1":"value1", "attribute2": 42}, "Device B":{"attribute1":"value1", "attribute2": 42}
try
{
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)
{
- _logger.LogError($"Device:{_devicename} UploadAttributeAsync Failed,{ex}");
+ _logger.LogError($"Device:{deviceName} UploadAttributeAsync Failed,{ex}");
}
+
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 { { _devicename, obj } };
- return Client.PublishAsync("gateway/attributes", JsonConvert.SerializeObject(toSend));
+ var toSend = new Dictionary { { deviceName, obj } };
+ 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()
+ {
+ 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()
+ {
+ { "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
{
- switch (_systemConfig.IoTPlatformType)
- {
- case IoTPlatformType.ThingsBoard:
- var tRpcResponse = new TBRpcResponse
- {
- DeviceName = rpcResponse.DeviceName,
- RequestId = rpcResponse.RequestId,
- ResponseData = new Dictionary { { "success", rpcResponse.IsSuccess }, { "description", rpcResponse.Description } }
- };
- ResponseTBRpc(tRpcResponse);
- break;
- case IoTPlatformType.IoTSharp:
- ResponseISRpc(new ISRpcResponse
- {
- DeviceId = rpcResponse.DeviceName,
- Method = "Method",
- ResponseId = rpcResponse.RequestId,
- Data = JsonConvert.SerializeObject(new Dictionary { { "success", rpcResponse.IsSuccess }, { "description", rpcResponse.Description } })
- });
- break;
- case IoTPlatformType.ThingsCloud:
- //官网API不需要回复的
- break;
- case IoTPlatformType.AliCloudIoT:
- break;
- case IoTPlatformType.TencentIoTHub:
- break;
- case IoTPlatformType.BaiduIoTCore:
- break;
- case IoTPlatformType.OneNET:
- break;
- default:
- break;
- }
+ if (_systemConfig != null)
+ switch (_systemConfig.IoTPlatformType)
+ {
+ case IoTPlatformType.ThingsBoard:
+ var tRpcResponse = new TBRpcResponse
+ {
+ DeviceName = rpcResponse.DeviceName,
+ RequestId = rpcResponse.RequestId,
+ ResponseData = new Dictionary