Первый коммит

This commit is contained in:
2025-11-27 14:02:00 +03:00
commit 5ff0384def
28 changed files with 4606 additions and 0 deletions
@@ -0,0 +1,6 @@
namespace GSS2.Core.Analysis.AmineContent;
public class AmineContentAnalyzerService
{
}
@@ -0,0 +1,6 @@
namespace GSS2.Core.Analysis.AmineContent;
public class AmineContentCalibrationDataService
{
}
@@ -0,0 +1,6 @@
namespace GSS2.Core.Analysis.AmineContent;
public class AmineContentCalibrationService
{
}
@@ -0,0 +1,184 @@
// <auto-generated />
using System;
using GSS2.Core.Analysis.AmineContent.Database;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace GSS2.Core.Analysis.AmineContent.Database
{
[DbContext(typeof(AmineContentCalibrationContext))]
[Migration("20251125054200_Initial")]
partial class Initial
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "10.0.0");
modelBuilder.Entity("GSS2.Core.Analysis.AmineContent.Database.AmineContentCalibrationContext+ImageData", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER")
.HasComment("Уникальный идентификатор");
b.Property<string>("ImagePath")
.IsRequired()
.HasColumnType("TEXT")
.HasComment("Путь к файлу изображения");
b.Property<string>("ImageType")
.IsRequired()
.HasColumnType("TEXT")
.HasComment("Тип изображения (sample - проба или separator - сепаратор)");
b.Property<double>("Uv254Intensity")
.HasColumnType("REAL")
.HasComment("Интенсивность УФ излучения 254 нм (0..1)");
b.Property<double>("Uv365Intensity")
.HasColumnType("REAL")
.HasComment("Интенсивность УФ излучения 365 нм (0..1)");
b.Property<double>("VisibleIntensity")
.HasColumnType("REAL")
.HasComment("Интенсивность видимого света (0..1)");
b.HasKey("Id");
b.ToTable("Images");
});
modelBuilder.Entity("GSS2.Core.Analysis.AmineContent.Database.AmineContentCalibrationContext+Record", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER")
.HasComment("Уникальный идентификатор");
b.Property<double>("AirHumidity")
.HasColumnType("REAL")
.HasComment("Относительная влажность воздуха (%)");
b.Property<double>("AirTemperature")
.HasColumnType("REAL")
.HasComment("Температура воздуха (℃)");
b.Property<double>("MixtureActualRate")
.HasColumnType("REAL")
.HasComment("Истинный расход кондиционирующей смеси (кг/т)");
b.Property<double>("MixtureAmineContent")
.HasColumnType("REAL")
.HasComment("Содержание аминов в кондиционирующей смеси (%)");
b.Property<string>("MixtureName")
.IsRequired()
.HasColumnType("TEXT")
.HasComment("Название используемой кондиционирующей смеси");
b.Property<double>("MixtureNormalRate")
.HasColumnType("REAL")
.HasComment("Норма расхода кондиционирующей смеси (кг/т)");
b.Property<string>("SampleBrand")
.IsRequired()
.HasColumnType("TEXT")
.HasComment("Марка пробы");
b.Property<string>("SampleComment")
.IsRequired()
.HasColumnType("TEXT")
.HasComment("Дополнительная информация о пробе");
b.Property<double>("SampleMass")
.HasColumnType("REAL")
.HasComment("Масса пробы (кг)");
b.Property<string>("SampleName")
.IsRequired()
.HasColumnType("TEXT")
.HasComment("Название пробы");
b.Property<DateTime>("SamplingDateTime")
.HasColumnType("TEXT")
.HasComment("Дата и время отбора пробы");
b.Property<string>("SamplingPlace")
.IsRequired()
.HasColumnType("TEXT")
.HasComment("Место отбора пробы");
b.HasKey("Id");
b.ToTable("Records");
});
modelBuilder.Entity("ImageDataRecord", b =>
{
b.Property<int>("SampleImagesId")
.HasColumnType("INTEGER");
b.Property<int>("SampleRecordsId")
.HasColumnType("INTEGER");
b.HasKey("SampleImagesId", "SampleRecordsId");
b.HasIndex("SampleRecordsId");
b.ToTable("SampleImages", (string)null);
});
modelBuilder.Entity("ImageDataRecord1", b =>
{
b.Property<int>("SeparatorImagesId")
.HasColumnType("INTEGER");
b.Property<int>("SeparatorRecordsId")
.HasColumnType("INTEGER");
b.HasKey("SeparatorImagesId", "SeparatorRecordsId");
b.HasIndex("SeparatorRecordsId");
b.ToTable("SeparatorImages", (string)null);
});
modelBuilder.Entity("ImageDataRecord", b =>
{
b.HasOne("GSS2.Core.Analysis.AmineContent.Database.AmineContentCalibrationContext+ImageData", null)
.WithMany()
.HasForeignKey("SampleImagesId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("GSS2.Core.Analysis.AmineContent.Database.AmineContentCalibrationContext+Record", null)
.WithMany()
.HasForeignKey("SampleRecordsId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("ImageDataRecord1", b =>
{
b.HasOne("GSS2.Core.Analysis.AmineContent.Database.AmineContentCalibrationContext+ImageData", null)
.WithMany()
.HasForeignKey("SeparatorImagesId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("GSS2.Core.Analysis.AmineContent.Database.AmineContentCalibrationContext+Record", null)
.WithMany()
.HasForeignKey("SeparatorRecordsId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,130 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace GSS2.Core.Analysis.AmineContent.Database
{
/// <inheritdoc />
public partial class Initial : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Images",
columns: table => new
{
Id = table.Column<int>(type: "INTEGER", nullable: false, comment: "Уникальный идентификатор")
.Annotation("Sqlite:Autoincrement", true),
VisibleIntensity = table.Column<double>(type: "REAL", nullable: false, comment: "Интенсивность видимого света (0..1)"),
Uv365Intensity = table.Column<double>(type: "REAL", nullable: false, comment: "Интенсивность УФ излучения 365 нм (0..1)"),
Uv254Intensity = table.Column<double>(type: "REAL", nullable: false, comment: "Интенсивность УФ излучения 254 нм (0..1)"),
ImageType = table.Column<string>(type: "TEXT", nullable: false, comment: "Тип изображения (sample - проба или separator - сепаратор)"),
ImagePath = table.Column<string>(type: "TEXT", nullable: false, comment: "Путь к файлу изображения")
},
constraints: table =>
{
table.PrimaryKey("PK_Images", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Records",
columns: table => new
{
Id = table.Column<int>(type: "INTEGER", nullable: false, comment: "Уникальный идентификатор")
.Annotation("Sqlite:Autoincrement", true),
SampleName = table.Column<string>(type: "TEXT", nullable: false, comment: "Название пробы"),
SampleComment = table.Column<string>(type: "TEXT", nullable: false, comment: "Дополнительная информация о пробе"),
SampleBrand = table.Column<string>(type: "TEXT", nullable: false, comment: "Марка пробы"),
SampleMass = table.Column<double>(type: "REAL", nullable: false, comment: "Масса пробы (кг)"),
SamplingDateTime = table.Column<DateTime>(type: "TEXT", nullable: false, comment: "Дата и время отбора пробы"),
SamplingPlace = table.Column<string>(type: "TEXT", nullable: false, comment: "Место отбора пробы"),
MixtureName = table.Column<string>(type: "TEXT", nullable: false, comment: "Название используемой кондиционирующей смеси"),
MixtureAmineContent = table.Column<double>(type: "REAL", nullable: false, comment: "Содержание аминов в кондиционирующей смеси (%)"),
MixtureNormalRate = table.Column<double>(type: "REAL", nullable: false, comment: "Норма расхода кондиционирующей смеси (кг/т)"),
MixtureActualRate = table.Column<double>(type: "REAL", nullable: false, comment: "Истинный расход кондиционирующей смеси (кг/т)"),
AirTemperature = table.Column<double>(type: "REAL", nullable: false, comment: "Температура воздуха (℃)"),
AirHumidity = table.Column<double>(type: "REAL", nullable: false, comment: "Относительная влажность воздуха (%)")
},
constraints: table =>
{
table.PrimaryKey("PK_Records", x => x.Id);
});
migrationBuilder.CreateTable(
name: "SampleImages",
columns: table => new
{
SampleImagesId = table.Column<int>(type: "INTEGER", nullable: false),
SampleRecordsId = table.Column<int>(type: "INTEGER", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_SampleImages", x => new { x.SampleImagesId, x.SampleRecordsId });
table.ForeignKey(
name: "FK_SampleImages_Images_SampleImagesId",
column: x => x.SampleImagesId,
principalTable: "Images",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_SampleImages_Records_SampleRecordsId",
column: x => x.SampleRecordsId,
principalTable: "Records",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "SeparatorImages",
columns: table => new
{
SeparatorImagesId = table.Column<int>(type: "INTEGER", nullable: false),
SeparatorRecordsId = table.Column<int>(type: "INTEGER", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_SeparatorImages", x => new { x.SeparatorImagesId, x.SeparatorRecordsId });
table.ForeignKey(
name: "FK_SeparatorImages_Images_SeparatorImagesId",
column: x => x.SeparatorImagesId,
principalTable: "Images",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_SeparatorImages_Records_SeparatorRecordsId",
column: x => x.SeparatorRecordsId,
principalTable: "Records",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_SampleImages_SampleRecordsId",
table: "SampleImages",
column: "SampleRecordsId");
migrationBuilder.CreateIndex(
name: "IX_SeparatorImages_SeparatorRecordsId",
table: "SeparatorImages",
column: "SeparatorRecordsId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "SampleImages");
migrationBuilder.DropTable(
name: "SeparatorImages");
migrationBuilder.DropTable(
name: "Images");
migrationBuilder.DropTable(
name: "Records");
}
}
}
@@ -0,0 +1,78 @@
using Microsoft.EntityFrameworkCore;
namespace GSS2.Core.Analysis.AmineContent.Database;
public class AmineContentCalibrationContext : DbContext
{
public class Record
{
[Comment("Уникальный идентификатор")]
public int Id { get; set; }
[Comment("Название пробы")]
public string SampleName { get; set; } = string.Empty;
[Comment("Дополнительная информация о пробе")]
public string SampleComment { get; set; } = string.Empty;
[Comment("Марка пробы")]
public string SampleBrand { get; set; } = string.Empty;
[Comment("Масса пробы (кг)")]
public double SampleMass { get; set; } = double.NaN;
[Comment("Дата и время отбора пробы")]
public DateTime SamplingDateTime { get; set; } = DateTime.Now;
[Comment("Место отбора пробы")]
public string SamplingPlace { get; set; } = string.Empty;
[Comment("Название используемой кондиционирующей смеси")]
public string MixtureName { get; set; } = string.Empty;
[Comment("Содержание аминов в кондиционирующей смеси (%)")]
public double MixtureAmineContent { get; set; } = double.NaN;
[Comment("Норма расхода кондиционирующей смеси (кг/т)")]
public double MixtureNormalRate { get; set; } = double.NaN;
[Comment("Истинный расход кондиционирующей смеси (кг/т)")]
public double MixtureActualRate { get; set; } = double.NaN;
[Comment("Изображения пробы")]
public List<ImageData> SampleImages { get; set; } = new();
[Comment("Изображения пустого сепаратора")]
public List<ImageData> SeparatorImages { get; set; } = new();
[Comment("Температура воздуха (℃)")]
public double AirTemperature { get; set; } = new();
[Comment("Относительная влажность воздуха (%)")]
public double AirHumidity { get; set; } = new();
}
public class ImageData
{
[Comment("Уникальный идентификатор")]
public int Id { get; set; }
[Comment("Интенсивность видимого света (0..1)")]
public double VisibleIntensity { get; set; } = double.NaN;
[Comment("Интенсивность УФ излучения 365 нм (0..1)")]
public double Uv365Intensity { get; set; } = double.NaN;
[Comment("Интенсивность УФ излучения 254 нм (0..1)")]
public double Uv254Intensity { get; set; } = double.NaN;
[Comment("Тип изображения (sample - проба или separator - сепаратор)")]
public string ImageType { get; set; } = string.Empty;
[Comment("Путь к файлу изображения")]
public string ImagePath { get; set; } = string.Empty;
[Comment("Записи в которых это изображение используется как изображение пробы")]
public List<Record> SampleRecords { get; set; } = new();
[Comment("Записи в которых это изображение используется как изображение сепаратора")]
public List<Record> SeparatorRecords { get; set; } = new();
}
public DbSet<Record> Records => Set<Record>();
public DbSet<ImageData> Images => Set<ImageData>();
public AmineContentCalibrationContext(DbContextOptions<AmineContentCalibrationContext> options) : base(options) { }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Record>()
.HasMany(r => r.SampleImages)
.WithMany(i => i.SampleRecords)
.UsingEntity(j => j.ToTable("SampleImages"));
modelBuilder.Entity<Record>()
.HasMany(r => r.SeparatorImages)
.WithMany(i => i.SeparatorRecords)
.UsingEntity(j => j.ToTable("SeparatorImages"));
}
}
@@ -0,0 +1,17 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
namespace GSS2.Core.Analysis.AmineContent.Database;
public class AmineContentCalibrationContextFactory : IDesignTimeDbContextFactory<AmineContentCalibrationContext>
{
public AmineContentCalibrationContext CreateDbContext(string[] args)
{
var optionsBuilder = new DbContextOptionsBuilder<AmineContentCalibrationContext>();
// строка подключения для миграций (в design-time)
optionsBuilder.UseSqlite("Data Source=AmineContentCalibration.db");
return new AmineContentCalibrationContext(optionsBuilder.Options);
}
}
@@ -0,0 +1,181 @@
// <auto-generated />
using System;
using GSS2.Core.Analysis.AmineContent.Database;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace GSS2.Core.Analysis.AmineContent.Database
{
[DbContext(typeof(AmineContentCalibrationContext))]
partial class AmineContentCalibrationContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "10.0.0");
modelBuilder.Entity("GSS2.Core.Analysis.AmineContent.Database.AmineContentCalibrationContext+ImageData", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER")
.HasComment("Уникальный идентификатор");
b.Property<string>("ImagePath")
.IsRequired()
.HasColumnType("TEXT")
.HasComment("Путь к файлу изображения");
b.Property<string>("ImageType")
.IsRequired()
.HasColumnType("TEXT")
.HasComment("Тип изображения (sample - проба или separator - сепаратор)");
b.Property<double>("Uv254Intensity")
.HasColumnType("REAL")
.HasComment("Интенсивность УФ излучения 254 нм (0..1)");
b.Property<double>("Uv365Intensity")
.HasColumnType("REAL")
.HasComment("Интенсивность УФ излучения 365 нм (0..1)");
b.Property<double>("VisibleIntensity")
.HasColumnType("REAL")
.HasComment("Интенсивность видимого света (0..1)");
b.HasKey("Id");
b.ToTable("Images");
});
modelBuilder.Entity("GSS2.Core.Analysis.AmineContent.Database.AmineContentCalibrationContext+Record", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER")
.HasComment("Уникальный идентификатор");
b.Property<double>("AirHumidity")
.HasColumnType("REAL")
.HasComment("Относительная влажность воздуха (%)");
b.Property<double>("AirTemperature")
.HasColumnType("REAL")
.HasComment("Температура воздуха (℃)");
b.Property<double>("MixtureActualRate")
.HasColumnType("REAL")
.HasComment("Истинный расход кондиционирующей смеси (кг/т)");
b.Property<double>("MixtureAmineContent")
.HasColumnType("REAL")
.HasComment("Содержание аминов в кондиционирующей смеси (%)");
b.Property<string>("MixtureName")
.IsRequired()
.HasColumnType("TEXT")
.HasComment("Название используемой кондиционирующей смеси");
b.Property<double>("MixtureNormalRate")
.HasColumnType("REAL")
.HasComment("Норма расхода кондиционирующей смеси (кг/т)");
b.Property<string>("SampleBrand")
.IsRequired()
.HasColumnType("TEXT")
.HasComment("Марка пробы");
b.Property<string>("SampleComment")
.IsRequired()
.HasColumnType("TEXT")
.HasComment("Дополнительная информация о пробе");
b.Property<double>("SampleMass")
.HasColumnType("REAL")
.HasComment("Масса пробы (кг)");
b.Property<string>("SampleName")
.IsRequired()
.HasColumnType("TEXT")
.HasComment("Название пробы");
b.Property<DateTime>("SamplingDateTime")
.HasColumnType("TEXT")
.HasComment("Дата и время отбора пробы");
b.Property<string>("SamplingPlace")
.IsRequired()
.HasColumnType("TEXT")
.HasComment("Место отбора пробы");
b.HasKey("Id");
b.ToTable("Records");
});
modelBuilder.Entity("ImageDataRecord", b =>
{
b.Property<int>("SampleImagesId")
.HasColumnType("INTEGER");
b.Property<int>("SampleRecordsId")
.HasColumnType("INTEGER");
b.HasKey("SampleImagesId", "SampleRecordsId");
b.HasIndex("SampleRecordsId");
b.ToTable("SampleImages", (string)null);
});
modelBuilder.Entity("ImageDataRecord1", b =>
{
b.Property<int>("SeparatorImagesId")
.HasColumnType("INTEGER");
b.Property<int>("SeparatorRecordsId")
.HasColumnType("INTEGER");
b.HasKey("SeparatorImagesId", "SeparatorRecordsId");
b.HasIndex("SeparatorRecordsId");
b.ToTable("SeparatorImages", (string)null);
});
modelBuilder.Entity("ImageDataRecord", b =>
{
b.HasOne("GSS2.Core.Analysis.AmineContent.Database.AmineContentCalibrationContext+ImageData", null)
.WithMany()
.HasForeignKey("SampleImagesId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("GSS2.Core.Analysis.AmineContent.Database.AmineContentCalibrationContext+Record", null)
.WithMany()
.HasForeignKey("SampleRecordsId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("ImageDataRecord1", b =>
{
b.HasOne("GSS2.Core.Analysis.AmineContent.Database.AmineContentCalibrationContext+ImageData", null)
.WithMany()
.HasForeignKey("SeparatorImagesId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("GSS2.Core.Analysis.AmineContent.Database.AmineContentCalibrationContext+Record", null)
.WithMany()
.HasForeignKey("SeparatorRecordsId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}
+26
View File
@@ -0,0 +1,26 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Data.SqlClient" Version="6.1.3" />
<PackageReference Include="Microsoft.Data.Sqlite" Version="10.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="10.0.0" />
<PackageReference Include="System.Device.Gpio" Version="4.0.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\GSS2.LightsControl\CSharpClient\GSS2.LightsControl.CSharpClient.csproj" />
</ItemGroup>
</Project>
View File
+221
View File
@@ -0,0 +1,221 @@
using System;
using System.Device.Gpio;
using System.Device.Pwm;
using System.Device.Pwm.Drivers;
using System.IO;
using System.Threading;
using Microsoft.Extensions.Logging;
namespace GSS2.Core.Hardware;
public class IlluminatorService : IDisposable
{
public class IlluminatorServiceConfiguration
{
public static IlluminatorServiceConfiguration Default => new IlluminatorServiceConfiguration
{
WhitePwmPin = 13,
Uv254PwmPin = 18,
Uv365PwmPin = 12,
WhiteRelayPin = 16,
Uv254RelayPin = 15,
Uv365RelayPin = 20,
FanPin = 21,
PwmFrequency = 200,
MaxWhitePwmDuty = 1.0,
MaxUv254PwmDuty = 1.0,
MaxUv365PwmDuty = 1.0
};
public int WhitePwmPin { get; set; }
public int Uv254PwmPin { get; set; }
public int Uv365PwmPin { get; set; }
public int WhiteRelayPin { get; set; }
public int Uv254RelayPin { get; set; }
public int Uv365RelayPin { get; set; }
public int FanPin { get; set; }
public int PwmFrequency { get; set; }
public double MaxWhitePwmDuty { get; set; }
public double MaxUv254PwmDuty { get; set; }
public double MaxUv365PwmDuty { get; set; }
}
private static readonly Dictionary<int, int> PinPwmChips = new()
{
{ 12, 0 },
{ 13, 0 },
{ 14, 0 },
{ 15, 0 },
{ 18, 0 },
{ 19, 0 },
};
private static readonly Dictionary<int, int> PinPwmChannels = new()
{
{ 12, 0 },
{ 13, 1 },
{ 14, 2 },
{ 15, 3 },
{ 18, 2 },
{ 19, 3 }
};
private bool _disposedValue;
private readonly ILogger<IlluminatorService> _logger;
private readonly IlluminatorServiceConfiguration _configuration;
private readonly GpioController _gpio;
private readonly PwmChannel _whitePwm;
private readonly PwmChannel _uv254Pwm;
private readonly PwmChannel _uv365Pwm;
private readonly GpioPin _whiteRelay;
private readonly GpioPin _uv254Relay;
private readonly GpioPin _uv365Relay;
private readonly GpioPin _fanRelay;
public IlluminatorService(ILogger<IlluminatorService> logger, IlluminatorServiceConfiguration? configuration = null)
{
_logger = logger;
_logger.LogInformation("Illuminator initialization");
if (configuration is null)
{
_logger.LogWarning("Illuminator configuration not set. Using default configuration.");
_configuration = IlluminatorServiceConfiguration.Default;
}
else
{
_configuration = configuration;
}
_logger.LogDebug(@$"Illuminator use following configuration:
WhitePwmPin: {_configuration.WhitePwmPin}
Uv254PwmPin: {_configuration.Uv254PwmPin}
Uv365PwmPin: {_configuration.Uv365PwmPin}
WhiteRelayPin: {_configuration.WhiteRelayPin}
Uv254RelayPin: {_configuration.Uv254RelayPin}
Uv365RelayPin: {_configuration.Uv365RelayPin}
FanPin: {_configuration.FanPin}
PwmFrequency: {_configuration.PwmFrequency}
MaxWhitePwmDuty: {_configuration.MaxWhitePwmDuty}
MaxUv254PwmDuty: {_configuration.MaxUv254PwmDuty}
MaxUv365PwmDuty: {_configuration.MaxUv365PwmDuty}
");
CheckPwmPin(_configuration.WhitePwmPin);
CheckPwmPin(_configuration.Uv254PwmPin);
CheckPwmPin(_configuration.Uv365PwmPin);
try
{
_gpio = new GpioController();
_whitePwm = PwmChannel.Create(PinPwmChips[_configuration.WhitePwmPin], PinPwmChannels[_configuration.WhitePwmPin], _configuration.PwmFrequency, CalculateDuty(0, _configuration.MaxWhitePwmDuty));
_uv254Pwm = PwmChannel.Create(PinPwmChips[_configuration.Uv254PwmPin], PinPwmChannels[_configuration.Uv254PwmPin], _configuration.PwmFrequency, CalculateDuty(0, _configuration.MaxUv254PwmDuty));
_uv365Pwm = PwmChannel.Create(PinPwmChips[_configuration.Uv365PwmPin], PinPwmChannels[_configuration.Uv365PwmPin], _configuration.PwmFrequency, CalculateDuty(0, _configuration.MaxUv365PwmDuty));
_whiteRelay = _gpio.OpenPin(_configuration.WhiteRelayPin, PinMode.Output, PinValue.Low);
_uv254Relay = _gpio.OpenPin(_configuration.Uv254RelayPin, PinMode.Output, PinValue.Low);
_uv365Relay = _gpio.OpenPin(_configuration.Uv365RelayPin, PinMode.Output, PinValue.Low);
_fanRelay = _gpio.OpenPin(_configuration.FanPin, PinMode.Output, PinValue.Low);
}
catch (Exception e)
{
_logger.LogCritical(e, "An exception occurred while illuminator initialization");
throw;
}
}
public void SetIntensity(double? white = null, double? uv365 = null, double? uv254 = null)
{
try
{
if (white is not null) _whitePwm.DutyCycle = CalculateDuty(white.Value, _configuration.MaxWhitePwmDuty);
if (uv365 is not null) _uv365Pwm.DutyCycle = CalculateDuty(uv365.Value, _configuration.MaxUv365PwmDuty);
if (uv254 is not null) _uv254Pwm.DutyCycle = CalculateDuty(uv254.Value, _configuration.MaxUv254PwmDuty);
}
catch (Exception e)
{
_logger.LogError(e, "An exception occurred while setting illuminator intensity");
}
}
public void TurnOn()
{
try
{
_fanRelay.Write(PinValue.High);
_whitePwm.Start();
_uv254Pwm.Start();
_uv365Pwm.Start();
_whiteRelay.Write(PinValue.High);
_uv254Relay.Write(PinValue.High);
_uv365Relay.Write(PinValue.High);
}
catch (Exception e)
{
_logger.LogError(e, "An exception occurred while turning on illuminator");
}
}
public void TurnOff()
{
try
{
_whitePwm.Stop();
_uv254Pwm.Stop();
_uv365Pwm.Stop();
_whiteRelay.Write(PinValue.Low);
_uv254Relay.Write(PinValue.Low);
_uv365Relay.Write(PinValue.Low);
_fanRelay.Write(PinValue.Low);
}
catch (Exception e)
{
_logger.LogError(e, "An exception occurred while turning off illuminator");
}
}
protected virtual void Dispose(bool disposing)
{
if (!_disposedValue)
{
if (disposing)
{
try
{
TurnOff();
}
catch { }
_whiteRelay?.Dispose();
_uv254Relay?.Dispose();
_uv365Relay?.Dispose();
_fanRelay?.Dispose();
_whitePwm?.Dispose();
_uv254Pwm?.Dispose();
_uv365Pwm?.Dispose();
_gpio?.Dispose();
}
_disposedValue = true;
}
}
void IDisposable.Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
private static void CheckPwmPin(int pin)
{
if (!PinPwmChips.TryGetValue(pin, out var _) || !PinPwmChannels.TryGetValue(pin, out var _))
throw new ArgumentException($"Unsupported PWM pin {pin}");
}
private static double CalculateDuty(double intensity, double maxDuty) => Math.Clamp(intensity, 0.0, 1.0) * Math.Clamp(maxDuty, 0.0, 1.0);
}
+445
View File
@@ -0,0 +1,445 @@
using System.Drawing;
using System.Runtime.CompilerServices;
using Grpc.Core;
using Grpc.Net.Client;
using GSS2.LightsControl.CSharpClient;
using Microsoft.Extensions.Logging;
namespace GSS2.Core.Hardware;
public class LightsService
{
public class LightsServiceConfiguration()
{
public static LightsServiceConfiguration Default => new LightsServiceConfiguration
{
ServerAddress = "localhost:50051"
};
public string ServerAddress { get; set; } = string.Empty;
}
private readonly ILogger<LightsService> _logger;
private readonly LightsServiceConfiguration _configuration;
private readonly Lights.LightsClient _client;
public LightsService(ILogger<LightsService> logger, LightsServiceConfiguration? configuration = null)
{
_logger = logger;
_logger.LogInformation("Lights initialization");
if (configuration is null)
{
_logger.LogWarning("Lights configuration not set. Using default configuration.");
_configuration = LightsServiceConfiguration.Default;
}
else
{
_configuration = configuration;
}
_logger.LogDebug(@$"Lights use following configuration:
ServerAddress: {_configuration.ServerAddress}
");
_client = new Lights.LightsClient(GrpcChannel.ForAddress(_configuration.ServerAddress));
}
public async Task Run(CancellationToken cancellationToken)
{
_logger.LogInformation("LightsService started");
while (!cancellationToken.IsCancellationRequested)
{
await PingAsync(cancellationToken);
try
{
await Task.Delay(TimeSpan.FromMinutes(1), cancellationToken);
}
catch (TaskCanceledException)
{
break;
}
}
_logger.LogInformation("LightsService stopped");
}
private void SendRequest<T>(Func<T, Metadata, DateTime?, CancellationToken, Empty> method, T request, CancellationToken cancellationToken = default, [CallerMemberName] string sender = "")
{
try
{
#pragma warning disable CS8625
method.Invoke(request, null, null, cancellationToken); ;
#pragma warning restore CS8625
_logger.LogTrace("Request \"{}\" sent", sender);
}
catch (RpcException ex)
{
_logger.LogWarning(ex, "Request \"{}\" RPC error", sender);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Request \"{}\" Unexpected error", method);
}
}
private async Task SendRequestAsync<T>(Func<T, Metadata, DateTime?, CancellationToken, AsyncUnaryCall<Empty>> method, T request, CancellationToken cancellationToken = default, [CallerMemberName] string sender = "")
{
try
{
#pragma warning disable CS8625
await method.Invoke(request, null, null, cancellationToken); ;
#pragma warning restore CS8625
_logger.LogTrace("Request \"{}\" sent", sender);
}
catch (RpcException ex)
{
_logger.LogWarning(ex, "Request \"{}\" RPC error", sender);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Request \"{}\" Unexpected error", method);
}
}
public void Ping(CancellationToken cancellationToken = default) => SendRequest(_client.Ping, new Empty(), cancellationToken);
public void Off(CancellationToken cancellationToken = default) => SendRequest(_client.SetOff, new Empty(), cancellationToken);
public void StaticColor(double brightness, Color color, CancellationToken cancellationToken = default) => SendRequest(_client.SetStaticColor, new StaticColorRequest
{
Brightness = brightness,
R = color.R,
G = color.G,
B = color.B
}, cancellationToken);
public void StaticGradient2(double brightness, Color leftColor, Color rightColor, CancellationToken cancellationToken = default) => SendRequest(_client.SetStaticGradient2, new StaticGradient2Request
{
Brightness = brightness,
LeftR = leftColor.R,
LeftG = leftColor.G,
LeftB = leftColor.B,
RightR = rightColor.R,
RightG = rightColor.G,
RightB = rightColor.B
}, cancellationToken);
public void StaticGradient3(double brightness, Color leftColor, Color middleColor, Color rightColor, CancellationToken cancellationToken = default) => SendRequest(_client.SetStaticGradient3, new StaticGradient3Request
{
Brightness = brightness,
LeftR = leftColor.R,
LeftG = leftColor.G,
LeftB = leftColor.B,
MiddleR = middleColor.R,
MiddleG = middleColor.G,
MiddleB = middleColor.B,
RightR = rightColor.R,
RightG = rightColor.G,
RightB = rightColor.B
}, cancellationToken);
public void StaticRainbow(double brightness, CancellationToken cancellationToken = default) => SendRequest(_client.SetStaticRainbow, new StaticRainbowRequest
{
Brightness = brightness
}, cancellationToken);
public void BreathingColor(double brightness, double speed, Color color, CancellationToken cancellationToken = default) => SendRequest(_client.SetBreathingColor, new BreathingColorRequest
{
Brightness = brightness,
Speed = speed,
R = color.R,
G = color.G,
B = color.B
}, cancellationToken);
public void BreathingGradient2(double brightness, double speed, Color leftColor, Color rightColor, CancellationToken cancellationToken = default) => SendRequest(_client.SetBreathingGradient2, new BreathingGradient2Request
{
Brightness = brightness,
Speed = speed,
LeftR = leftColor.R,
LeftG = leftColor.G,
LeftB = leftColor.B,
RightR = rightColor.R,
RightG = rightColor.G,
RightB = rightColor.B
}, cancellationToken);
public void BreathingGradient3(double brightness, double speed, Color leftColor, Color middleColor, Color rightColor, CancellationToken cancellationToken = default) => SendRequest(_client.SetBreathingGradient3, new BreathingGradient3Request
{
Brightness = brightness,
Speed = speed,
LeftR = leftColor.R,
LeftG = leftColor.G,
LeftB = leftColor.B,
MiddleR = middleColor.R,
MiddleG = middleColor.G,
MiddleB = middleColor.B,
RightR = rightColor.R,
RightG = rightColor.G,
RightB = rightColor.B
}, cancellationToken);
public void BreathingRainbow(double brightness, double speed, CancellationToken cancellationToken = default) => SendRequest(_client.SetBreathingRainbow, new BreathingRainbowRequest
{
Brightness = brightness,
Speed = speed
}, cancellationToken);
public void RunningColor(double brightness, double speed, int length, int fade, Color color, CancellationToken cancellationToken = default) => SendRequest(_client.SetRunningColor, new RunningColorRequest
{
Brightness = brightness,
Speed = speed,
Length = length,
Fade = fade,
R = color.R,
G = color.G,
B = color.B
}, cancellationToken);
public void RunningGradient2(double brightness, double speed, Color leftColor, Color rightColor, CancellationToken cancellationToken = default) => SendRequest(_client.SetRunningGradient2, new RunningGradient2Request
{
Brightness = brightness,
Speed = speed,
LeftR = leftColor.R,
LeftG = leftColor.G,
LeftB = leftColor.B,
RightR = rightColor.R,
RightG = rightColor.G,
RightB = rightColor.B
}, cancellationToken);
public void RunningGradient3(double brightness, double speed, Color leftColor, Color middleColor, Color rightColor, CancellationToken cancellationToken = default) => SendRequest(_client.SetRunningGradient3, new RunningGradient3Request
{
Brightness = brightness,
Speed = speed,
LeftR = leftColor.R,
LeftG = leftColor.G,
LeftB = leftColor.B,
MiddleR = middleColor.R,
MiddleG = middleColor.G,
MiddleB = middleColor.B,
RightR = rightColor.R,
RightG = rightColor.G,
RightB = rightColor.B
}, cancellationToken);
public void RunningRainbow(double brightness, double speed, CancellationToken cancellationToken = default) => SendRequest(_client.SetRunningRainbow, new RunningRainbowRequest
{
Brightness = brightness,
Speed = speed
}, cancellationToken);
public void Snake(double brightness, double speed, int headLength, int tailLength, Color headColor, Color tailColor, CancellationToken cancellationToken = default) => SendRequest(_client.SetSnake, new SnakeRequest
{
Brightness = brightness,
Speed = speed,
HeadLength = headLength,
TailLength = tailLength,
HeadR = headColor.R,
HeadG = headColor.G,
HeadB = headColor.B,
TailR = tailColor.R,
TailG = tailColor.G,
TailB = tailColor.B
}, cancellationToken);
public void Fire(double brightness, double speed, Color color, CancellationToken cancellationToken = default) => SendRequest(_client.SetFire, new FireRequest
{
Brightness = brightness,
Speed = speed,
R = color.R,
G = color.G,
B = color.B
}, cancellationToken);
public void Snowfall(double brightness, double speed, Color color, CancellationToken cancellationToken = default) => SendRequest(_client.SetSnowfall, new SnowfallRequest
{
Brightness = brightness,
Speed = speed,
R = color.R,
G = color.G,
B = color.B
}, cancellationToken);
public void Flash(double brightness, double speed, Color color, CancellationToken cancellationToken = default) => SendRequest(_client.SetFlash, new FlashRequest
{
Brightness = brightness,
Speed = speed,
R = color.R,
G = color.G,
B = color.B
}, cancellationToken);
public void Load(double brightness, double speed, double percent, double lastPercent, Color color, CancellationToken cancellationToken = default) => SendRequest(_client.SetLoad, new LoadRequest
{
Brightness = brightness,
Speed = speed,
Percent = percent,
LastPercent = lastPercent,
R = color.R,
G = color.G,
B = color.B,
}, cancellationToken);
public void CpuLoad(double brightness, double speed, Color color, CancellationToken cancellationToken = default) => SendRequest(_client.SetCpuLoad, new CpuLoadRequest
{
Brightness = brightness,
Speed = speed,
R = color.R,
G = color.G,
B = color.B
}, cancellationToken);
public async Task PingAsync(CancellationToken cancellationToken = default) => await SendRequestAsync(_client.PingAsync, new Empty(), cancellationToken);
public async Task OffAsync(CancellationToken cancellationToken = default) => await SendRequestAsync(_client.SetOffAsync, new Empty(), cancellationToken);
public async Task StaticColorAsync(double brightness, Color color, CancellationToken cancellationToken = default) => await SendRequestAsync(_client.SetStaticColorAsync, new StaticColorRequest
{
Brightness = brightness,
R = color.R,
G = color.G,
B = color.B
}, cancellationToken);
public async Task StaticGradient2Async(double brightness, Color leftColor, Color rightColor, CancellationToken cancellationToken = default) => await SendRequestAsync(_client.SetStaticGradient2Async, new StaticGradient2Request
{
Brightness = brightness,
LeftR = leftColor.R,
LeftG = leftColor.G,
LeftB = leftColor.B,
RightR = rightColor.R,
RightG = rightColor.G,
RightB = rightColor.B
}, cancellationToken);
public async Task StaticGradient3Async(double brightness, Color leftColor, Color middleColor, Color rightColor, CancellationToken cancellationToken = default) => await SendRequestAsync(_client.SetStaticGradient3Async, new StaticGradient3Request
{
Brightness = brightness,
LeftR = leftColor.R,
LeftG = leftColor.G,
LeftB = leftColor.B,
MiddleR = middleColor.R,
MiddleG = middleColor.G,
MiddleB = middleColor.B,
RightR = rightColor.R,
RightG = rightColor.G,
RightB = rightColor.B
}, cancellationToken);
public async Task StaticRainbowAsync(double brightness, CancellationToken cancellationToken = default) => await SendRequestAsync(_client.SetStaticRainbowAsync, new StaticRainbowRequest
{
Brightness = brightness
}, cancellationToken);
public async Task BreathingColorAsync(double brightness, double speed, Color color, CancellationToken cancellationToken = default) => await SendRequestAsync(_client.SetBreathingColorAsync, new BreathingColorRequest
{
Brightness = brightness,
Speed = speed,
R = color.R,
G = color.G,
B = color.B
}, cancellationToken);
public async Task BreathingGradient2Async(double brightness, double speed, Color leftColor, Color rightColor, CancellationToken cancellationToken = default) => await SendRequestAsync(_client.SetBreathingGradient2Async, new BreathingGradient2Request
{
Brightness = brightness,
Speed = speed,
LeftR = leftColor.R,
LeftG = leftColor.G,
LeftB = leftColor.B,
RightR = rightColor.R,
RightG = rightColor.G,
RightB = rightColor.B
}, cancellationToken);
public async Task BreathingGradient3Async(double brightness, double speed, Color leftColor, Color middleColor, Color rightColor, CancellationToken cancellationToken = default) => await SendRequestAsync(_client.SetBreathingGradient3Async, new BreathingGradient3Request
{
Brightness = brightness,
Speed = speed,
LeftR = leftColor.R,
LeftG = leftColor.G,
LeftB = leftColor.B,
MiddleR = middleColor.R,
MiddleG = middleColor.G,
MiddleB = middleColor.B,
RightR = rightColor.R,
RightG = rightColor.G,
RightB = rightColor.B
}, cancellationToken);
public async Task BreathingRainbowAsync(double brightness, double speed, CancellationToken cancellationToken = default) => await SendRequestAsync(_client.SetBreathingRainbowAsync, new BreathingRainbowRequest
{
Brightness = brightness,
Speed = speed
}, cancellationToken);
public async Task RunningColorAsync(double brightness, double speed, int length, int fade, Color color, CancellationToken cancellationToken = default) => await SendRequestAsync(_client.SetRunningColorAsync, new RunningColorRequest
{
Brightness = brightness,
Speed = speed,
Length = length,
Fade = fade,
R = color.R,
G = color.G,
B = color.B
}, cancellationToken);
public async Task RunningGradient2Async(double brightness, double speed, Color leftColor, Color rightColor, CancellationToken cancellationToken = default) => await SendRequestAsync(_client.SetRunningGradient2Async, new RunningGradient2Request
{
Brightness = brightness,
Speed = speed,
LeftR = leftColor.R,
LeftG = leftColor.G,
LeftB = leftColor.B,
RightR = rightColor.R,
RightG = rightColor.G,
RightB = rightColor.B
}, cancellationToken);
public async Task RunningGradient3Async(double brightness, double speed, Color leftColor, Color middleColor, Color rightColor, CancellationToken cancellationToken = default) => await SendRequestAsync(_client.SetRunningGradient3Async, new RunningGradient3Request
{
Brightness = brightness,
Speed = speed,
LeftR = leftColor.R,
LeftG = leftColor.G,
LeftB = leftColor.B,
MiddleR = middleColor.R,
MiddleG = middleColor.G,
MiddleB = middleColor.B,
RightR = rightColor.R,
RightG = rightColor.G,
RightB = rightColor.B
}, cancellationToken);
public async Task RunningRainbowAsync(double brightness, double speed, CancellationToken cancellationToken = default) => await SendRequestAsync(_client.SetRunningRainbowAsync, new RunningRainbowRequest
{
Brightness = brightness,
Speed = speed
}, cancellationToken);
public async Task SnakeAsync(double brightness, double speed, int headLength, int tailLength, Color headColor, Color tailColor, CancellationToken cancellationToken = default) => await SendRequestAsync(_client.SetSnakeAsync, new SnakeRequest
{
Brightness = brightness,
Speed = speed,
HeadLength = headLength,
TailLength = tailLength,
HeadR = headColor.R,
HeadG = headColor.G,
HeadB = headColor.B,
TailR = tailColor.R,
TailG = tailColor.G,
TailB = tailColor.B
}, cancellationToken);
public async Task FireAsync(double brightness, double speed, Color color, CancellationToken cancellationToken = default) => await SendRequestAsync(_client.SetFireAsync, new FireRequest
{
Brightness = brightness,
Speed = speed,
R = color.R,
G = color.G,
B = color.B
}, cancellationToken);
public async Task SnowfallAsync(double brightness, double speed, Color color, CancellationToken cancellationToken = default) => await SendRequestAsync(_client.SetSnowfallAsync, new SnowfallRequest
{
Brightness = brightness,
Speed = speed,
R = color.R,
G = color.G,
B = color.B
}, cancellationToken);
public async Task FlashAsync(double brightness, double speed, Color color, CancellationToken cancellationToken = default) => await SendRequestAsync(_client.SetFlashAsync, new FlashRequest
{
Brightness = brightness,
Speed = speed,
R = color.R,
G = color.G,
B = color.B
}, cancellationToken);
public async Task LoadAsync(double brightness, double speed, double percent, double lastPercent, Color color, CancellationToken cancellationToken = default) => await SendRequestAsync(_client.SetLoadAsync, new LoadRequest
{
Brightness = brightness,
Speed = speed,
Percent = percent,
LastPercent = lastPercent,
R = color.R,
G = color.G,
B = color.B,
}, cancellationToken);
public async Task CpuLoadAsync(double brightness, double speed, Color color, CancellationToken cancellationToken = default) => await SendRequestAsync(_client.SetCpuLoadAsync, new CpuLoadRequest
{
Brightness = brightness,
Speed = speed,
R = color.R,
G = color.G,
B = color.B
}, cancellationToken);
}
@@ -0,0 +1,174 @@
using System.Device.I2c;
using Microsoft.Extensions.Logging;
namespace GSS2.Core.Hardware;
public class TemperatureHumidityService : IDisposable
{
public class TemperatureHumidityServiceConfiguration
{
public static TemperatureHumidityServiceConfiguration Default => new TemperatureHumidityServiceConfiguration
{
Bus = 0,
Address = 0x44
};
public int Bus { get; set; }
public int Address { get; set; }
}
private bool _disposedValue;
private readonly ILogger<TemperatureHumidityService> _logger;
private readonly TemperatureHumidityServiceConfiguration _configuration;
private readonly I2cDevice _sensor;
public TemperatureHumidityService(ILogger<TemperatureHumidityService> logger, TemperatureHumidityServiceConfiguration? configuration = null)
{
_logger = logger;
_logger.LogInformation("Temperature and humidity sensor initialization");
if (configuration is null)
{
_logger.LogWarning("Temperature and humidity sensor configuration not set. Using default configuration.");
_configuration = TemperatureHumidityServiceConfiguration.Default;
}
else
{
_configuration = configuration;
}
_logger.LogDebug(@$"Temperature and humidity sensor use following configuration:
Bus: {_configuration.Bus}
Address: {_configuration.Address}
");
try
{
_sensor = I2cDevice.Create(new I2cConnectionSettings(_configuration.Bus, _configuration.Address));
}
catch (Exception e)
{
_logger.LogCritical(e, "An exception occurred while temperature and humidity sensor initialization");
throw;
}
}
public async Task<(double temperature, double relativeHumidity)> MeasureAsync(int measurementsCount = 1, CancellationToken cancellationToken = default)
{
// В соответствии с даташитом на SHT45-AD1B-R2 псевдокод измерения с высокой точностью следующий:
// i2c_write(i2c_addr=0x44, tx_bytes=[0xFD])
// wait_seconds(0.01)
// rx_bytes = i2c_read(i2c_addr=0x44, number_of_bytes=6)
// t_ticks = rx_bytes[0] * 256 + rx_bytes[1]
// checksum_t = rx_bytes[2]
// rh_ticks = rx_bytes[3] * 256 + rx_bytes[4]
// checksum_rh = rx_bytes[5]
// t_degC = -45 + 175 * t_ticks/65535
// rh_pRH = -6 + 125 * rh_ticks/65535
// if (rh_pRH > 100):
// rh_pRH = 100
// if (rh_pRH < 0):
// rh_pRH = 0
if (measurementsCount <= 0)
throw new ArgumentOutOfRangeException(nameof(measurementsCount));
double sumTemperature = 0;
double sumRelativeHumidity = 0;
int successMeasurementsCount = 0;
Span<byte> command = stackalloc byte[] { 0xFD };
Span<byte> data = stackalloc byte[6];
for (int i = 0; i < measurementsCount; i++)
{
cancellationToken.ThrowIfCancellationRequested();
try
{
// Отправляем команду
_sensor.Write(command);
// 10 мс ожидания
await Task.Delay(10, cancellationToken);
// Читаем данные
_sensor.Read(data);
// Распаковываем данные [2 * 8-bit T-data; 8-bit CRC; 2 * 8-bit RH-data; 8-bit CRC]
ushort temperatureTicks = BitConverter.ToUInt16(data.ToArray(), 0);
byte temperatureChecksum = data[2];
int relativeHumidityTicks = BitConverter.ToUInt16(data.ToArray(), 3);
byte relativeHumidityChecksum = data[5];
// Проверка по CRC
if (!CheckCrc(data.Slice(0, 2), temperatureChecksum) ||
!CheckCrc(data.Slice(3, 2), relativeHumidityChecksum))
{
_logger.LogWarning("Temperature and humidity sensor CRC error");
continue;
}
// Пересчёт
double temperature = -45 + 175 * (temperatureTicks / 65535.0);
double relativeHumidity = -6 + 125 * (relativeHumidityTicks / 65535.0);
relativeHumidity = Math.Clamp(relativeHumidity, 0, 100);
// Сумма для усреднения
sumTemperature += temperature;
sumRelativeHumidity += relativeHumidity;
successMeasurementsCount++;
}
catch (Exception e)
{
_logger.LogWarning(e, "Temperature and humidity sensor not available on I2C bus");
}
}
if (successMeasurementsCount == 0)
{
_logger.LogError("Temperature and humidity sensor: no successful measurements");
return (double.NaN, double.NaN);
}
return (sumTemperature / successMeasurementsCount, sumRelativeHumidity / successMeasurementsCount);
}
private static bool CheckCrc(Span<byte> data, byte expectedCrc)
{
byte crc = 0xFF;
foreach (var b in data)
{
crc ^= b;
for (int i = 0; i < 8; i++)
{
if ((crc & 0x80) != 0)
crc = (byte)((crc << 1) ^ 0x31);
else
crc <<= 1;
}
}
return crc == expectedCrc;
}
protected virtual void Dispose(bool disposing)
{
if (!_disposedValue)
{
if (disposing)
{
try
{
_sensor?.Dispose();
}
catch { }
}
_disposedValue = true;
}
}
void IDisposable.Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
}