支持华为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()
.HasColumnType("TEXT");
b.Property<string>("ClientId")
.HasColumnType("TEXT");
b.Property<string>("CreateBy")
.HasMaxLength(50)
.HasColumnType("TEXT");

View File

@ -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
}

View File

@ -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;

View File

@ -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<Device>().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<Device>().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<Device> SetDuplicatedCheck()
{

View File

@ -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();

View File

@ -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))
{

View File

@ -33,6 +33,7 @@ namespace IoTGateway.ViewModel.Config.SystemConfigVMs
{
return new List<GridColumn<SystemConfig_View>>{
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,

View File

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

View File

@ -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<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
{
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"
});

Binary file not shown.

View File

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

View File

@ -3,11 +3,9 @@ using Microsoft.Extensions.Configuration;
using PluginInterface;
using System.Net;
using System.Reflection;
using System.Runtime.CompilerServices;
using WalkingTec.Mvvm.Core;
using IoTGateway.DataAccess;
using IoTGateway.Model;
using DynamicExpresso;
using MQTTnet.Server;
using Microsoft.Extensions.Logging;
@ -16,34 +14,40 @@ namespace Plugin
public class DeviceService : IDisposable
{
private readonly ILogger<DeviceService> _logger;
public DriverService _DrvierManager;
public DriverService DrvierManager;
public List<DeviceThread> DeviceThreads = new List<DeviceThread>();
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<DeviceService> 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<DeviceService> 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<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();
_logger.LogInformation($"Loaded Devices Count:{Devices.Count()}");
foreach (var Device in Devices)
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();
_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<Device> 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<SystemConfig>().FirstOrDefault();
var driver = _DrvierManager.DriverInfos.Where(x => x.Type.FullName == Device.Driver.AssembleName).SingleOrDefault();
var systemManage = dc.Set<SystemConfig>().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<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) };
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);
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<Device> 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,9 +190,11 @@ namespace Plugin
try
{
_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
{
Text = method.Name,
@ -197,16 +202,17 @@ namespace Plugin
};
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");

View File

@ -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<Guid, DriverReturnValueModel> DeviceValues { get; set; } = new();
internal List<MethodInfo> 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<MethodInfo>? Methods { get; set; }
private Task? _task;
private readonly DateTime _tsStartDt = new(1970, 1, 1);
private readonly CancellationTokenSource _tokenSource = new CancellationTokenSource();
private readonly object _lock = new();
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 };
}
}
}
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<string, List<PayLoad>> sendModel = new() { { _device.DeviceName, new() } };
Dictionary<string, List<PayLoad>> 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> { payLoad };
myMqttClient.PublishTelemetry(_device, sendModel);
sendModel[Device.DeviceName] = new List<PayLoad> { 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<RpcLog>().Add(rpcLog);
DC.SaveChanges();
dc.Set<RpcLog>().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("&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;
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;
}
}

View File

@ -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,35 +10,37 @@ using Microsoft.Extensions.Logging;
namespace Plugin
{
public class DriverService//: IDependency
public class DriverService
{
private readonly ILogger<DriverService> _logger;
string DriverPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"drivers/net6.0");
string[] driverFiles;
public List<DriverInfo> DriverInfos = new List<DriverInfo>();
public DriverService(IConfiguration ConfigRoot, ILogger<DriverService> logger)
readonly string _driverPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"drivers/net6.0");
readonly string[] _driverFiles;
public List<DriverInfo> DriverInfos = new();
public DriverService(IConfiguration configRoot, ILogger<DriverService> logger)
{
_logger = logger;
try
{
_logger.LogInformation("LoadDriverFiles Start");
driverFiles = Directory.GetFiles(DriverPath).Where(x => Path.GetExtension(x) == ".dll").ToArray();
_logger.LogInformation($"LoadDriverFiles EndCount{driverFiles.Count()}");
_driverFiles = Directory.GetFiles(_driverPath).Where(x => Path.GetExtension(x) == ".dll").ToArray();
_logger.LogInformation($"LoadDriverFiles EndCount{_driverFiles.Count()}");
}
catch (Exception ex)
{
_logger.LogError("LoadDriverFiles Error", ex);
}
LoadAllDrivers();
}
public List<ComboSelectListItem> GetAllDrivers()
{
List<ComboSelectListItem> driverFilesComboSelect = new List<ComboSelectListItem>();
using (var DC = new DataContext(IoTBackgroundService.connnectSetting, IoTBackgroundService.DBType))
{
var Drivers = DC.Set<Driver>().AsNoTracking().ToList();
using var dc = new DataContext(IoTBackgroundService.connnectSetting, IoTBackgroundService.DbType);
var drivers = dc.Set<Driver>().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())
@ -55,49 +52,47 @@ namespace Plugin
Value = fileName,
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;
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))
{
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 type = DriverInfos.Where(x => x.Type.FullName == driver.AssembleName).SingleOrDefault();
using var dc = new DataContext(IoTBackgroundService.connnectSetting, IoTBackgroundService.DbType);
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 type = DriverInfos.SingleOrDefault(x => x.Type.FullName == driver?.AssembleName);
Type[] types = new Type[2] { typeof(string), typeof(ILogger) };
object[] param = new object[2] { device.DeviceName, _logger };
Type[] types = { typeof(string), typeof(ILogger) };
object[] param = { device?.DeviceName, _logger };
ConstructorInfo constructor = type.Type.GetConstructor(types);
var iObj = constructor.Invoke(param) as IDriver;
ConstructorInfo? constructor = type?.Type.GetConstructor(types);
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));
if (config != null)
{
var DapConfig = new DeviceConfig
var dapConfig = new DeviceConfig
{
ID = Guid.NewGuid(),
DeviceId = dapID,
DeviceId = dapId,
DeviceConfigName = property.Name,
DataSide= DataSide.AnySide,
DataSide = DataSide.AnySide,
Description = ((ConfigParameterAttribute)config).Description,
Value = property.GetValue(iObj)?.ToString()
};
@ -105,20 +100,21 @@ namespace Plugin
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);
var enumInfos = fields.ToDictionary(f => f.Name, f => (int)f.GetValue(null));
dapConfig.EnumInfo = JsonSerializer.Serialize(enumInfos);
}
DC.Set<DeviceConfig>().Add(DapConfig);
dc.Set<DeviceConfig>().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,19 +134,16 @@ 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<Driver>().AsNoTracking().ToList();
using var dc = new DataContext(IoTBackgroundService.connnectSetting, IoTBackgroundService.DbType);
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();
foreach (var file in files)
{
@ -167,5 +160,4 @@ namespace Plugin
}
}
}
}
}

View File

@ -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<ConnnectSettingsModel>();
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;
}
}

View File

@ -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<ModbusSlaveService> _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<ModbusSlaveService> 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();
}
}
}

View File

@ -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<MyMqttClient> _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<RpcRequest> OnExcRpc;
public event EventHandler<ISAttributeResponse> OnReceiveAttributes;
public MyMqttClient(UAService uaService, ILogger<MyMqttClient> logger)
{
_logger = logger;
@ -35,81 +37,82 @@ namespace Plugin
ConnectAsync();
}
public async Task<bool> ConnectAsync()
public async Task ConnectAsync()
{
bool initok = false;
try
{
using (var DC = new DataContext(IoTBackgroundService.connnectSetting, IoTBackgroundService.DBType))
{
_systemConfig = DC.Set<SystemConfig>().FirstOrDefault();
await using var dc = new DataContext(IoTBackgroundService.connnectSetting, IoTBackgroundService.DbType);
_systemConfig = dc.Set<SystemConfig>().FirstOrDefault();
if (_systemConfig == null)
{
_systemConfig = new SystemConfig()
{
ID = Guid.NewGuid(),
GatewayName = "iotgateway",
ClientId = Guid.NewGuid().ToString(),
MqttIp = "localhost",
MqttPort = 1888,
MqttUName = "user",
MqttUPwd = "pwd",
IoTPlatformType = IoTPlatformType.IoTSharp
};
DC.Set<SystemConfig>().Add(_systemConfig);
DC.SaveChanges();
dc.Set<SystemConfig>().Add(_systemConfig);
await dc.SaveChangesAsync();
}
var factory = new MqttFactory();
Client = (MqttClient)factory.CreateMqttClient();
clientOptions = new MqttClientOptionsBuilder()
.WithClientId(_systemConfig.GatewayName + Guid.NewGuid().ToString())
_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(x => OnConnected());
Client.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(x => OnDisconnectedAsync());
Client.ApplicationMessageReceivedHandler =
new MqttApplicationMessageReceivedHandlerDelegate(Client_ApplicationMessageReceived);
Client.ConnectedHandler = new MqttClientConnectedHandlerDelegate(_ => OnConnected());
Client.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(_ => OnDisconnectedAsync());
try
{
Client.ConnectAsync(clientOptions);
initok = true;
await Client.ConnectAsync(_clientOptions);
}
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");
}
}
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()
{
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);
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}}
@ -136,25 +139,27 @@ namespace Plugin
break;
case IoTPlatformType.OneNET:
break;
default:
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
/// <param name="e"></param>
private void ReceiveTbRpc(MqttApplicationMessageReceivedEventArgs e)
{
TBRpcRequest tBRpcRequest;
try
{
tBRpcRequest = JsonConvert.DeserializeObject<TBRpcRequest>(e.ApplicationMessage.ConvertPayloadToString());
if (!string.IsNullOrWhiteSpace(tBRpcRequest.RequestData.Method))
var tBRpcRequest =
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,
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);
}
}
/// <summary>
@ -204,11 +213,12 @@ namespace Plugin
/// <param name="e"></param>
private void ReceiveTcRpc(MqttApplicationMessageReceivedEventArgs e)
{
TCRpcRequest tCRpcRequest;
try
{
tCRpcRequest = JsonConvert.DeserializeObject<TCRpcRequest>(e.ApplicationMessage.ConvertPayloadToString());
OnExcRpc?.Invoke(Client, new RpcRequest()
var tCRpcRequest =
JsonConvert.DeserializeObject<TCRpcRequest>(e.ApplicationMessage.ConvertPayloadToString());
if (tCRpcRequest != null)
OnExcRpc.Invoke(Client, new RpcRequest()
{
Method = tCRpcRequest.RequestData.Method,
DeviceName = tCRpcRequest.DeviceName,
@ -218,62 +228,66 @@ 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);
}
}
}
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<Dictionary<string, object>>(e.ApplicationMessage.ConvertPayloadToString())
Method = rpcMethodName,
DeviceName = rpcDeviceName,
RequestId = rpcRequestId,
Params = JsonConvert.DeserializeObject<Dictionary<string, object>>(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,61 +295,96 @@ 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<string, object> { { _devicename, obj } };
return Client.PublishAsync("gateway/attributes", JsonConvert.SerializeObject(toSend));
var toSend = new Dictionary<string, object> { { 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<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
{
if (_systemConfig != null)
switch (_systemConfig.IoTPlatformType)
{
case IoTPlatformType.ThingsBoard:
@ -343,17 +392,21 @@ namespace Plugin
{
DeviceName = rpcResponse.DeviceName,
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;
case IoTPlatformType.IoTSharp:
ResponseISRpc(new ISRpcResponse
await ResponseIsRpcAsync(new ISRpcResponse
{
DeviceId = rpcResponse.DeviceName,
Method = "Method",
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;
case IoTPlatformType.ThingsCloud:
@ -367,40 +420,43 @@ namespace Plugin
break;
case IoTPlatformType.OneNET:
break;
default:
break;
}
}
catch (Exception 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
{
string id = Guid.NewGuid().ToString();
if (_systemConfig != null)
switch (_systemConfig.IoTPlatformType)
{
case IoTPlatformType.ThingsBoard:
//{"id": $request_id, "device": "Device A", "client": true, "key": "attribute1"}
Dictionary<string, object> tbRequestData = new Dictionary<string, object>
{
{ "id",id},
{ "device",_devicename},
{ "client",true},
{ "key",args[0]}
{ "id", id },
{ "device", deviceName },
{ "client", true },
{ "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:
string topic = $"devices/{_devicename}/attributes/request/{id}";
string topic = $"devices/{deviceName}/attributes/request/{id}";
Dictionary<string, string> keys = new Dictionary<string, string>();
keys.Add(anySide ? "anySide" : "server", string.Join(",", args));
Client.SubscribeAsync($"devices/{_devicename}/attributes/response/{id}", MqttQualityOfServiceLevel.ExactlyOnce);
return Client.PublishAsync(topic, JsonConvert.SerializeObject(keys), MqttQualityOfServiceLevel.ExactlyOnce);
await Client.SubscribeAsync($"devices/{deviceName}/attributes/response/{id}",
MqttQualityOfServiceLevel.ExactlyOnce);
await Client.PublishAsync(topic, JsonConvert.SerializeObject(keys),
MqttQualityOfServiceLevel.ExactlyOnce);
break;
case IoTPlatformType.AliCloudIoT:
break;
case IoTPlatformType.TencentIoTHub:
@ -409,33 +465,29 @@ namespace Plugin
break;
case IoTPlatformType.OneNET:
break;
default:
break;
}
}
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>
/// <param name="device">设备</param>
/// <param name="SendModel">遥测</param>
/// <param name="sendModel">遥测</param>
/// <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;
try
{
//第一次上传
if (!LastTelemetrys.ContainsKey(device.DeviceName))
if (!_lastTelemetrys.ContainsKey(device.DeviceName))
canPub = true;
else
{
@ -443,14 +495,15 @@ namespace Plugin
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;
//是否变化
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;
}
}
//非变化上传
@ -463,36 +516,42 @@ namespace Plugin
canPub = true;
Console.WriteLine(e);
}
if(canPub)
LastTelemetrys[device.DeviceName] = SendModel[device.DeviceName];
if (canPub)
_lastTelemetrys[device.DeviceName] = sendModel[device.DeviceName];
return canPub;
}
public void PublishTelemetry(Device device, Dictionary<string, List<PayLoad>> SendModel)
public async Task PublishTelemetryAsync(Device device, Dictionary<string, List<PayLoad>> sendModel)
{
try
{
if (CanPubTelemetry(device, SendModel))
if (CanPubTelemetry(device, sendModel))
{
if (_systemConfig != null)
switch (_systemConfig.IoTPlatformType)
{
case IoTPlatformType.ThingsBoard:
Client.PublishAsync("v1/gateway/telemetry", JsonConvert.SerializeObject(SendModel));
await Client.PublishAsync("v1/gateway/telemetry",
JsonConvert.SerializeObject(sendModel));
break;
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;
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;
case IoTPlatformType.IotDB:
{
foreach (var payload in SendModel[device.DeviceName])
foreach (var payload in sendModel[device.DeviceName])
{
if (payload.DeviceStatus != DeviceStatusTypeEnum.Good)
continue;
@ -504,11 +563,19 @@ namespace Plugin
measurements = payload.Values.Keys.ToList(),
values = payload.Values.Values.ToList()
};
Client.PublishAsync(device.DeviceName, JsonConvert.SerializeObject(tsData));
await Client.PublishAsync(device.DeviceName, JsonConvert.SerializeObject(tsData));
}
break;
}
case IoTPlatformType.HuaWei:
foreach (var payload in sendModel[device.DeviceName])
{
await UploadHwTelemetryDataAsync(device, payload.Values);
}
break;
case IoTPlatformType.AliCloudIoT:
case IoTPlatformType.TencentIoTHub:
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)
{
//更新到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)
{
_logger.LogError($"PublishTelemetryAsync Error", ex);
}
}
}
public async Task DeviceConnected(string DeviceName)
public async Task DeviceConnected(Device device)
{
try
{
if (_systemConfig != null)
switch (_systemConfig.IoTPlatformType)
{
case IoTPlatformType.ThingsBoard:
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;
case IoTPlatformType.AliCloudIoT:
break;
@ -555,27 +623,48 @@ namespace Plugin
case IoTPlatformType.OneNET:
break;
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;
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;
}
}
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
{
if (_systemConfig != null)
switch (_systemConfig.IoTPlatformType)
{
case IoTPlatformType.ThingsBoard:
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;
case IoTPlatformType.AliCloudIoT:
break;
@ -586,18 +675,107 @@ namespace Plugin
case IoTPlatformType.OneNET:
break;
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;
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;
}
}
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 Opc.Ua;
using Quickstarts;
using Quickstarts;
using Quickstarts.ReferenceServer;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
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 Guid DeviceId { get; }
public string DeviceId { get; }
public bool IsConnected { get; }
public int Timeout { get; }
public uint MinPeriod { get; }

View File

@ -11,7 +11,7 @@ namespace PluginInterface
public string DeviceName { get; set; }
public string Method { 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()
{
return $"Method:{Method},RequestId:{RequestId},Params:{Newtonsoft.Json.JsonConvert.SerializeObject(Params)}";