提交 b357d62d 编写于 作者: 麦壳饼's avatar 麦壳饼

add gateway

上级 41814620
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using System;
......@@ -45,6 +44,10 @@ namespace IoTSharp.Data
modelBuilder.Entity<TelemetryData>().HasDiscriminator<DataCatalog>(nameof(Data.DataStorage.Catalog));
modelBuilder.Entity<TelemetryLatest>().HasDiscriminator<DataCatalog>(nameof(Data.DataStorage.Catalog));
modelBuilder.Entity<Device>().HasDiscriminator<DeviceType>(nameof(Data.Device.DeviceType)).HasValue<Gateway>(DeviceType.Gateway).HasValue<Device>(DeviceType.Device);
modelBuilder.Entity<Gateway>().HasDiscriminator<DeviceType>(nameof(Data.Device.DeviceType));
switch (DatabaseType)
{
case DatabaseType.mssql:
......@@ -104,8 +107,6 @@ namespace IoTSharp.Data
modelBuilder.Entity<AuditLog>()
.Property(b => b.ActionResult)
.HasColumnType("jsonb");
}
private void ForSqlServer(ModelBuilder modelBuilder)
......@@ -131,6 +132,7 @@ namespace IoTSharp.Data
public DbSet<Customer> Customer { get; set; }
public DbSet<Relationship> Relationship { get; set; }
public DbSet<Device> Device { get; set; }
public DbSet<Gateway> Gateway { get; set; }
public DbSet<TelemetryData> TelemetryData { get; set; }
public DbSet<AttributeLatest> AttributeLatest { get; set; }
public DbSet<DataStorage> DataStorage { get; set; }
......
......@@ -9,9 +9,8 @@ namespace IoTSharp.Data
{
public Guid Id { get; set; } = Guid.NewGuid();
public string Name { get; set; }
public string Type { get; set; }
public DeviceType DeviceType { get; set; }
public Gateway Owner { get; set; }
public Tenant Tenant { get; set; }
public Customer Customer { get; set; }
......
......@@ -93,4 +93,9 @@ namespace IoTSharp.Data
MQTTClient
}
public enum DeviceType
{
Device =0,
Gateway =1
}
}
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace IoTSharp.Data
{
public class Gateway: Device
{
[Newtonsoft.Json.JsonIgnore]
public List<Device> Children { get; set; }
}
}
// <auto-generated />
using System;
using IoTSharp.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
namespace IoTSharp.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("20190518035335_Gateway")]
partial class Gateway
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn)
.HasAnnotation("ProductVersion", "2.2.4-servicing-10062")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
modelBuilder.Entity("IoTSharp.Data.AuditLog", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ActionData")
.HasColumnType("jsonb");
b.Property<string>("ActionName");
b.Property<string>("ActionResult")
.HasColumnType("jsonb");
b.Property<DateTime>("ActiveDateTime");
b.Property<Guid?>("CustomerId");
b.Property<Guid>("ObjectID");
b.Property<string>("ObjectName");
b.Property<int>("ObjectType");
b.Property<Guid?>("TenantId");
b.Property<string>("UserId");
b.Property<string>("UserName");
b.HasKey("Id");
b.HasIndex("CustomerId");
b.HasIndex("TenantId");
b.ToTable("AuditLog");
});
modelBuilder.Entity("IoTSharp.Data.Customer", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Address");
b.Property<string>("City");
b.Property<string>("Country");
b.Property<string>("Email");
b.Property<string>("Name");
b.Property<string>("Phone");
b.Property<string>("Province");
b.Property<string>("Street");
b.Property<Guid?>("TenantId");
b.Property<int>("ZipCode");
b.HasKey("Id");
b.HasIndex("TenantId");
b.ToTable("Customer");
});
modelBuilder.Entity("IoTSharp.Data.DataStorage", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("Catalog");
b.Property<int>("DataSide");
b.Property<DateTime>("DateTime");
b.Property<string>("KeyName")
.IsRequired();
b.Property<int>("Type");
b.Property<byte[]>("Value_Binary");
b.Property<bool>("Value_Boolean");
b.Property<DateTime>("Value_DateTime");
b.Property<double>("Value_Double");
b.Property<string>("Value_Json")
.HasColumnType("jsonb");
b.Property<long>("Value_Long");
b.Property<string>("Value_String");
b.Property<string>("Value_XML")
.HasColumnType("xml");
b.HasKey("Id");
b.ToTable("DataStorage");
b.HasDiscriminator<int>("Catalog").HasValue(0);
});
modelBuilder.Entity("IoTSharp.Data.Device", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd();
b.Property<Guid?>("CustomerId");
b.Property<int>("DeviceType");
b.Property<Guid?>("GatewayId");
b.Property<string>("Name");
b.Property<Guid?>("TenantId");
b.HasKey("Id");
b.HasIndex("CustomerId");
b.HasIndex("GatewayId");
b.HasIndex("TenantId");
b.ToTable("Device");
b.HasDiscriminator<int>("DeviceType").HasValue(0);
});
modelBuilder.Entity("IoTSharp.Data.DeviceIdentity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd();
b.Property<Guid>("DeviceId");
b.Property<string>("IdentityId")
.IsRequired();
b.Property<int>("IdentityType");
b.Property<string>("IdentityValue");
b.HasKey("Id");
b.HasIndex("DeviceId");
b.ToTable("DeviceIdentities");
});
modelBuilder.Entity("IoTSharp.Data.Relationship", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd();
b.Property<Guid?>("CustomerId");
b.Property<string>("IdentityUserId");
b.Property<Guid?>("TenantId");
b.HasKey("Id");
b.HasIndex("CustomerId");
b.HasIndex("IdentityUserId");
b.HasIndex("TenantId");
b.ToTable("Relationship");
});
modelBuilder.Entity("IoTSharp.Data.Tenant", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Address");
b.Property<string>("City");
b.Property<string>("Country");
b.Property<string>("EMail");
b.Property<string>("Name");
b.Property<string>("Phone");
b.Property<string>("Province");
b.Property<string>("Street");
b.Property<int>("ZipCode");
b.HasKey("Id");
b.ToTable("Tenant");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b =>
{
b.Property<string>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Name")
.HasMaxLength(256);
b.Property<string>("NormalizedName")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasName("RoleNameIndex");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("RoleId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b =>
{
b.Property<string>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("AccessFailedCount");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Email")
.HasMaxLength(256);
b.Property<bool>("EmailConfirmed");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("NormalizedEmail")
.HasMaxLength(256);
b.Property<string>("NormalizedUserName")
.HasMaxLength(256);
b.Property<string>("PasswordHash");
b.Property<string>("PhoneNumber");
b.Property<bool>("PhoneNumberConfirmed");
b.Property<string>("SecurityStamp");
b.Property<bool>("TwoFactorEnabled");
b.Property<string>("UserName")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasName("UserNameIndex");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider");
b.Property<string>("ProviderKey");
b.Property<string>("ProviderDisplayName");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("RoleId");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("LoginProvider");
b.Property<string>("Name");
b.Property<string>("Value");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("IoTSharp.Data.AttributeData", b =>
{
b.HasBaseType("IoTSharp.Data.DataStorage");
b.Property<Guid>("DeviceId");
b.HasIndex("DeviceId");
b.HasDiscriminator().HasValue(1);
});
modelBuilder.Entity("IoTSharp.Data.AttributeLatest", b =>
{
b.HasBaseType("IoTSharp.Data.DataStorage");
b.Property<Guid>("DeviceId")
.HasColumnName("AttributeLatest_DeviceId");
b.HasIndex("DeviceId");
b.HasDiscriminator().HasValue(2);
});
modelBuilder.Entity("IoTSharp.Data.TelemetryData", b =>
{
b.HasBaseType("IoTSharp.Data.DataStorage");
b.Property<Guid>("DeviceId")
.HasColumnName("TelemetryData_DeviceId");
b.HasIndex("DeviceId");
b.HasDiscriminator().HasValue(3);
});
modelBuilder.Entity("IoTSharp.Data.TelemetryLatest", b =>
{
b.HasBaseType("IoTSharp.Data.DataStorage");
b.Property<Guid>("DeviceId")
.HasColumnName("TelemetryLatest_DeviceId");
b.HasIndex("DeviceId");
b.HasDiscriminator().HasValue(4);
});
modelBuilder.Entity("IoTSharp.Data.Gateway", b =>
{
b.HasBaseType("IoTSharp.Data.Device");
b.HasDiscriminator().HasValue(1);
});
modelBuilder.Entity("IoTSharp.Data.AuditLog", b =>
{
b.HasOne("IoTSharp.Data.Customer", "Customer")
.WithMany()
.HasForeignKey("CustomerId");
b.HasOne("IoTSharp.Data.Tenant", "Tenant")
.WithMany()
.HasForeignKey("TenantId");
});
modelBuilder.Entity("IoTSharp.Data.Customer", b =>
{
b.HasOne("IoTSharp.Data.Tenant", "Tenant")
.WithMany("Customers")
.HasForeignKey("TenantId");
});
modelBuilder.Entity("IoTSharp.Data.Device", b =>
{
b.HasOne("IoTSharp.Data.Customer", "Customer")
.WithMany("Devices")
.HasForeignKey("CustomerId");
b.HasOne("IoTSharp.Data.Gateway")
.WithMany("Children")
.HasForeignKey("GatewayId");
b.HasOne("IoTSharp.Data.Tenant", "Tenant")
.WithMany("Devices")
.HasForeignKey("TenantId");
});
modelBuilder.Entity("IoTSharp.Data.DeviceIdentity", b =>
{
b.HasOne("IoTSharp.Data.Device", "Device")
.WithMany()
.HasForeignKey("DeviceId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("IoTSharp.Data.Relationship", b =>
{
b.HasOne("IoTSharp.Data.Customer", "Customer")
.WithMany()
.HasForeignKey("CustomerId");
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", "IdentityUser")
.WithMany()
.HasForeignKey("IdentityUserId");
b.HasOne("IoTSharp.Data.Tenant", "Tenant")
.WithMany()
.HasForeignKey("TenantId");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole")
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole")
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("IoTSharp.Data.AttributeData", b =>
{
b.HasOne("IoTSharp.Data.Device", "Device")
.WithMany("AttributeData")
.HasForeignKey("DeviceId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("IoTSharp.Data.AttributeLatest", b =>
{
b.HasOne("IoTSharp.Data.Device", "Device")
.WithMany("AttributeLatest")
.HasForeignKey("DeviceId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("IoTSharp.Data.TelemetryData", b =>
{
b.HasOne("IoTSharp.Data.Device", "Device")
.WithMany("TelemetryData")
.HasForeignKey("DeviceId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("IoTSharp.Data.TelemetryLatest", b =>
{
b.HasOne("IoTSharp.Data.Device", "Device")
.WithMany("TelemetryLatest")
.HasForeignKey("DeviceId")
.OnDelete(DeleteBehavior.Cascade);
});
#pragma warning restore 612, 618
}
}
}
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace IoTSharp.Migrations
{
public partial class Gateway : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Type",
table: "Device");
migrationBuilder.AddColumn<int>(
name: "DeviceType",
table: "Device",
nullable: false,
defaultValue: 0);
migrationBuilder.AddColumn<Guid>(
name: "GatewayId",
table: "Device",
nullable: true);
migrationBuilder.CreateIndex(
name: "IX_Device_GatewayId",
table: "Device",
column: "GatewayId");
migrationBuilder.AddForeignKey(
name: "FK_Device_Device_GatewayId",
table: "Device",
column: "GatewayId",
principalTable: "Device",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Device_Device_GatewayId",
table: "Device");
migrationBuilder.DropIndex(
name: "IX_Device_GatewayId",
table: "Device");
migrationBuilder.DropColumn(
name: "DeviceType",
table: "Device");
migrationBuilder.DropColumn(
name: "GatewayId",
table: "Device");
migrationBuilder.AddColumn<string>(
name: "Type",
table: "Device",
nullable: true);
}
}
}
......@@ -16,7 +16,7 @@ namespace IoTSharp.Migrations
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn)
.HasAnnotation("ProductVersion", "2.2.1-servicing-10028")
.HasAnnotation("ProductVersion", "2.2.4-servicing-10062")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
modelBuilder.Entity("IoTSharp.Data.AuditLog", b =>
......@@ -137,19 +137,25 @@ namespace IoTSharp.Migrations
b.Property<Guid?>("CustomerId");
b.Property<int>("DeviceType");
b.Property<Guid?>("GatewayId");
b.Property<string>("Name");
b.Property<Guid?>("TenantId");
b.Property<string>("Type");
b.HasKey("Id");
b.HasIndex("CustomerId");
b.HasIndex("GatewayId");
b.HasIndex("TenantId");
b.ToTable("Device");
b.HasDiscriminator<int>("DeviceType").HasValue(0);
});
modelBuilder.Entity("IoTSharp.Data.DeviceIdentity", b =>
......@@ -427,6 +433,13 @@ namespace IoTSharp.Migrations
b.HasDiscriminator().HasValue(4);
});
modelBuilder.Entity("IoTSharp.Data.Gateway", b =>
{
b.HasBaseType("IoTSharp.Data.Device");
b.HasDiscriminator().HasValue(1);
});
modelBuilder.Entity("IoTSharp.Data.AuditLog", b =>
{
b.HasOne("IoTSharp.Data.Customer", "Customer")
......@@ -451,6 +464,10 @@ namespace IoTSharp.Migrations
.WithMany("Devices")
.HasForeignKey("CustomerId");
b.HasOne("IoTSharp.Data.Gateway")
.WithMany("Children")
.HasForeignKey("GatewayId");
b.HasOne("IoTSharp.Data.Tenant", "Tenant")
.WithMany("Devices")
.HasForeignKey("TenantId");
......
......@@ -101,7 +101,7 @@ namespace IoTSharp
.WithClientId("buind-in")
.WithTcpServer((setting.MqttBroker == "built-in" || string.IsNullOrEmpty(setting.MqttBroker)) ? "127.0.0.1" : setting.MqttBroker, setting.Port)
.WithCredentials(setting.UserName, setting.Password)
.WithCleanSession()
.WithCleanSession()//.WithProtocolVersion (MQTTnet.Formatter.MqttProtocolVersion.V500)
.Build());
services.AddHostedService <MqttClientService>();
}
......
using IoTSharp.Data;
using IoTSharp.Extensions;
using IoTSharp.X509Extensions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using MQTTnet;
using MQTTnet.AspNetCoreEx;
......@@ -17,10 +18,10 @@ namespace IoTSharp.Handlers
{
public class MqttEventsHandler
{
readonly ILogger<MqttEventsHandler> _logger ;
readonly ApplicationDbContext _dbContext;
readonly ILogger<MqttEventsHandler> _logger;
readonly ApplicationDbContext _dbContext;
readonly IMqttServerEx _serverEx;
public MqttEventsHandler(ILogger<MqttEventsHandler> logger, ApplicationDbContext dbContext,IMqttServerEx serverEx )
public MqttEventsHandler(ILogger<MqttEventsHandler> logger, ApplicationDbContext dbContext, IMqttServerEx serverEx)
{
_logger = logger;
_dbContext = dbContext;
......@@ -47,6 +48,7 @@ namespace IoTSharp.Handlers
}
Dictionary<string, int> lstTopics = new Dictionary<string, int>();
long received = 0;
internal void Server_ApplicationMessageReceived(object sender, MqttApplicationMessageReceivedEventArgs e)
{
_logger.LogInformation($"Server received {e.ClientId}'s message: Topic=[{e.ApplicationMessage.Topic }],Retain=[{e.ApplicationMessage.Retain}],QualityOfServiceLevel=[{e.ApplicationMessage.QualityOfServiceLevel}]");
......@@ -59,11 +61,71 @@ namespace IoTSharp.Handlers
{
lstTopics[e.ApplicationMessage.Topic]++;
}
received += e.ApplicationMessage.Payload.Length;
if (e.ApplicationMessage.Payload != null)
{
received += e.ApplicationMessage.Payload.Length;
}
string topic = e.ApplicationMessage.Topic;
var tpary = topic.Split('/');
if (tpary.Length >= 3 && tpary[0] == "devices" && Devices.ContainsKey(e.ClientId))
{
Device device = JudgeDevice(tpary, Devices[e.ClientId]);
if (device != null)
{
if (tpary[2] == "telemetry")
{
Task.Run(async () =>
{
try
{
var telemetrys = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, object>>(e.ApplicationMessage.ConvertPayloadToString());
var result = await _dbContext.SaveAsync<TelemetryLatest, TelemetryData>(telemetrys, device, DataSide.ClientSide);
}
catch (Exception ex)
{
_logger.LogError(ex, $"Can't upload telemetry to device {device.Name}({device.Id}).the payload is {e.ApplicationMessage.ConvertPayloadToString()}");
}
});
}
else if (tpary[2] == "attributes")
{
Task.Run(async () =>
{
try
{
var attributes = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, object>>(e.ApplicationMessage.ConvertPayloadToString());
var result = await _dbContext.SaveAsync<AttributeLatest, AttributeData>(attributes, device, DataSide.ClientSide);
}
catch (Exception ex)
{
_logger.LogError(ex, $"Can't upload attributes to device {device.Name}({device.Id}).the payload is \"{e.ApplicationMessage.ConvertPayloadToString()}\"");
}
});
}
}
}
}
private Device JudgeDevice(string[] tpary, Device device)
{
Device devicedatato = device;
if (tpary[1] != "me" && device.DeviceType == DeviceType.Gateway)
{
//var ch = from g in _dbContext.Gateway.Include(c => c.Children) where g.Id == device.Id select g.Children;
//if (ch.Any)
//var subdev = from cd in ().FirstOrDefault() where cd.Name == tpary[1] select cd ;
//devicedatato = subdev.FirstOrDefault();
}
return devicedatato;
}
long Subscribed;
internal void Server_ClientSubscribedTopic(object sender, MqttServerClientSubscribedTopicEventArgs e)
internal void Server_ClientSubscribedTopic(object sender, MqttServerClientSubscribedTopicEventArgs e)
{
_logger.LogInformation($"Client [{e.ClientId}] subscribed [{e.TopicFilter}]");
if (e.TopicFilter.Topic.StartsWith("$SYS/"))
......@@ -79,13 +141,10 @@ namespace IoTSharp.Handlers
Task.Run(() => _serverEx.PublishAsync("$SYS/broker/uptime", uptime.ToString()));
}
}
if (e.TopicFilter.Topic.ToLower().StartsWith("/Telemetry/"))
if (e.TopicFilter.Topic.ToLower().StartsWith("/devices/telemetry"))///devices/attributes
{
if (Devices.ContainsKey(e.ClientId))
{
}
}
else
{
......@@ -96,7 +155,7 @@ namespace IoTSharp.Handlers
}
internal void Server_ClientUnsubscribedTopic(object sender, MqttServerClientUnsubscribedTopicEventArgs e)
internal void Server_ClientUnsubscribedTopic(object sender, MqttServerClientUnsubscribedTopicEventArgs e)
{
_logger.LogInformation($"Client [{e.ClientId}] unsubscribed[{e.TopicFilter}]");
if (!e.TopicFilter.StartsWith("$SYS/"))
......@@ -105,9 +164,9 @@ namespace IoTSharp.Handlers
Task.Run(() => _serverEx.PublishAsync("$SYS/broker/subscriptions/count", Subscribed.ToString()));
}
}
internal static Dictionary<string, Device> Devices = new Dictionary<string, Device>();
internal static Dictionary<string, Device> Devices = new Dictionary<string, Device>();
public static string MD5Sum(string text) => BitConverter.ToString(MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(text))).Replace("-", "");
internal void Server_ClientConnectionValidator(object sender, MqttServerClientConnectionValidatorEventArgs e)
internal void Server_ClientConnectionValidator(object sender, MqttServerClientConnectionValidatorEventArgs e)
{
MqttConnectionValidatorContext obj = e.Context;
Uri uri = new Uri("mqtt://" + obj.Endpoint);
......@@ -119,8 +178,8 @@ namespace IoTSharp.Handlers
else
{
_logger.LogInformation($"ClientId={obj.ClientId},Endpoint={obj.Endpoint},Username={obj.Username},Password={obj.Password},WillMessage={obj.WillMessage?.ConvertPayloadToString()}");
var mcr = _dbContext.DeviceIdentities.FirstOrDefault(mc => (mc.IdentityType == IdentityType.AccessToken && mc.IdentityId == obj.Username)
|| (mc.IdentityType== IdentityType.DevicePassword && mc.IdentityId==obj.Username && mc.IdentityValue==obj.Password));
var mcr = _dbContext.DeviceIdentities.FirstOrDefault(mc => (mc.IdentityType == IdentityType.AccessToken && mc.IdentityId == obj.Username)
|| (mc.IdentityType == IdentityType.DevicePassword && mc.IdentityId == obj.Username && mc.IdentityValue == obj.Password));
if (mcr != null)
{
try
......
using IoTSharp.Data;
using IoTSharp.Extensions;
using IoTSharp.Handlers;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Client.Connecting;
using MQTTnet.Client.Disconnecting;
using MQTTnet.Client.Options;
using MQTTnet.Client.Receiving;
using MQTTnet.Server;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
......@@ -24,25 +18,26 @@ namespace IoTSharp.Services
public class MqttClientService : IHostedService
{
private readonly ILogger _logger;
readonly IMqttClient _mqtt;
private readonly IMqttClient _mqtt;
private readonly IMqttClientOptions _clientOptions;
private ApplicationDbContext _dbContext;
private IServiceScope _serviceScope;
public MqttClientService(ILogger<MqttClientService> logger, IServiceScopeFactory scopeFactor, IMqttClient mqtt, IMqttClientOptions clientOptions)
{
_logger = logger;
_mqtt = mqtt;
_clientOptions = clientOptions;
mqtt.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(args => Mqtt_ApplicationMessageReceived(mqtt, args));
mqtt.ConnectedHandler =new MqttClientConnectedHandlerDelegate (args=> Mqtt_ConnectedAsync(mqtt,args));
mqtt.DisconnectedHandler =new MqttClientDisconnectedHandlerDelegate (args=> Mqtt_DisconnectedAsync(mqtt,args));
mqtt.ConnectedHandler = new MqttClientConnectedHandlerDelegate(args => Mqtt_ConnectedAsync(mqtt, args));
mqtt.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(args => Mqtt_DisconnectedAsync(mqtt, args));
_serviceScope = scopeFactor.CreateScope();
_dbContext = _serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
}
private async void Mqtt_DisconnectedAsync(object sender, MqttClientDisconnectedEventArgs e)
{
_logger.LogInformation($"DISCONNECTED FROM SERVER ClientWasConnected:{e.ClientWasConnected}, Exception={ e.Exception.Message}");
_logger.LogInformation($"DISCONNECTED FROM SERVER ClientWasConnected:{e.ClientWasConnected}, Exception={ e.Exception?.Message}");
try
{
await _mqtt.ConnectAsync(_clientOptions);
......@@ -54,61 +49,18 @@ namespace IoTSharp.Services
}
}
private async void Mqtt_ConnectedAsync(object sender, MqttClientConnectedEventArgs e)
private void Mqtt_ConnectedAsync(object sender, MqttClientConnectedEventArgs e)
{
_logger.LogInformation($"CONNECTED IsSessionPresent: {e.AuthenticateResult.IsSessionPresent } ResultCode: { e.AuthenticateResult.ResultCode}");
var subresult1=await _mqtt.SubscribeAsync("/devices/telemetry/#");
var subresult2= await _mqtt.SubscribeAsync("/devices/attributes/#");
}
Dictionary<string, Device> Devices => MqttEventsHandler.Devices;
private void Mqtt_ApplicationMessageReceived(object sender, MQTTnet.MqttApplicationMessageReceivedEventArgs e)
{
_logger.LogInformation($"Received : {e.ApplicationMessage.Topic}");
if (e.ApplicationMessage.Topic.ToLower().StartsWith("/devices/telemetry"))
{
if (Devices.ContainsKey(e.ClientId))
{
var device = Devices[e.ClientId];
Task.Run(async () =>
{
try
{
var telemetrys = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, object>>(e.ApplicationMessage.ConvertPayloadToString());
var result = await _dbContext.SaveAsync<TelemetryLatest, TelemetryData>(telemetrys, device, DataSide.ClientSide);
}
catch (Exception ex)
{
_logger.LogError(ex, $"Can't upload telemetry to device {device.Name}({device.Id}).the payload is {e.ApplicationMessage.ConvertPayloadToString()}");
}
});
}
}
else if (e.ApplicationMessage.Topic.ToLower().StartsWith("/devices/attributes"))
{
if (Devices.ContainsKey(e.ClientId))
{
var device = Devices[e.ClientId];
Task.Run(async () =>
{
try
{
var attributes = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, object>>(e.ApplicationMessage.ConvertPayloadToString());
var result = await _dbContext.SaveAsync<AttributeLatest, AttributeData>(attributes, device, DataSide.ClientSide);
}
catch (Exception ex)
{
_logger.LogError(ex, $"Can't upload attributes to device {device.Name}({device.Id}).the payload is \"{e.ApplicationMessage.ConvertPayloadToString()}\"");
}
});
}
}
}
public Task StartAsync(CancellationToken cancellationToken)
{
return Task.Run(() =>
......@@ -131,4 +83,4 @@ namespace IoTSharp.Services
return _mqtt.DisconnectAsync();
}
}
}
}
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册