Commit ff29bf86 by hanfei

反编译修复

parents
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Confluent.Kafka" Version="2.11.1" />
<PackageReference Include="CSRedisCore" Version="3.8.805" />
<PackageReference Include="EasyShardingCore" Version="1.0.1" />
<PackageReference Include="Flurl.Http" Version="3.2.4" />
<PackageReference Include="IdGen" Version="3.0.1" />
<PackageReference Include="Mapster" Version="7.3.0" />
<PackageReference Include="Masa.Contrib.Service.MinimalAPIs" Version="1.0.0" />
<PackageReference Include="Microsoft.AspNetCore" Version="2.3.0" />
<PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.3.0" />
<PackageReference Include="Microsoft.CodeAnalysis" Version="4.14.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.19" />
<PackageReference Include="NLog" Version="5.0.0" />
<PackageReference Include="NLog.Web.AspNetCore" Version="5.0.0" />
<PackageReference Include="Snowflake.Core" Version="2.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerGen" Version="6.5.0" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="6.5.0" />
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
</Project>
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<ActiveDebugProfile>https</ActiveDebugProfile>
</PropertyGroup>
</Project>
\ No newline at end of file
using Microsoft.AspNetCore.Mvc.ApplicationParts;
using System.Reflection;
//[assembly: AssemblyCompany("Amd.KafkaConsumer")]
//[assembly: AssemblyConfiguration("Release")]
//[assembly: AssemblyFileVersion("1.0.0.0")]
//[assembly: AssemblyInformationalVersion("1.0.0")]
//[assembly: AssemblyProduct("Amd.KafkaConsumer")]
//[assembly: AssemblyTitle("Amd.KafkaConsumer")]
//[assembly: ApplicationPart("Masa.Contrib.Service.MinimalAPIs")]
//[assembly: ApplicationPart("Masa.Utils.Exceptions")]
//[assembly: ApplicationPart("Microsoft.AspNetCore.OpenApi")]
//[assembly: ApplicationPart("Swashbuckle.AspNetCore.SwaggerGen")]
//[assembly: AssemblyVersion("1.0.0.0")]
// Decompiled with JetBrains decompiler
// Type: Amd.KafkaConsumer.BlockQueue`1
// Assembly: Amd.KafkaConsumer, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: 84842E10-777A-4595-89D9-B43B8D2CDA96
// Assembly location: D:\项目\上海斯凯孚整合项目\kafka\KafkaConsumer\KafkaConsumer\Amd.KafkaConsumer.dll
// XML documentation location: D:\项目\上海斯凯孚整合项目\kafka\KafkaConsumer\KafkaConsumer\Amd.KafkaConsumer.xml
using System.Collections.Concurrent;
#nullable enable
namespace Amd.KafkaConsumer
{
public class BlockQueue<T> where T : class
{
private static BlockingCollection<T> colls = new BlockingCollection<T>();
public static bool IsComleted() => BlockQueue<T>.colls.IsCompleted;
public static bool HasEle() => BlockQueue<T>.colls.Count > 0;
public static void Add(T msg) => BlockQueue<T>.colls.Add(msg);
public static T Take()
{
T obj;
BlockQueue<T>.colls.TryTake(out obj);
return obj;
}
public static T[] ToList() => BlockQueue<T>.colls.ToArray();
}
}
// Decompiled with JetBrains decompiler
// Type: Amd.KafkaConsumer.Entities.BaseEntity
// Assembly: Amd.KafkaConsumer, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: 84842E10-777A-4595-89D9-B43B8D2CDA96
// Assembly location: D:\项目\上海斯凯孚整合项目\kafka\KafkaConsumer\KafkaConsumer\Amd.KafkaConsumer.dll
// XML documentation location: D:\项目\上海斯凯孚整合项目\kafka\KafkaConsumer\KafkaConsumer\Amd.KafkaConsumer.xml
namespace Amd.KafkaConsumer.Entities
{
public class BaseEntity
{
}
}
// Decompiled with JetBrains decompiler
// Type: Amd.KafkaConsumer.Entities.MachineData
// Assembly: Amd.KafkaConsumer, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: 84842E10-777A-4595-89D9-B43B8D2CDA96
// Assembly location: D:\项目\上海斯凯孚整合项目\kafka\KafkaConsumer\KafkaConsumer\Amd.KafkaConsumer.dll
// XML documentation location: D:\项目\上海斯凯孚整合项目\kafka\KafkaConsumer\KafkaConsumer\Amd.KafkaConsumer.xml
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Snowflake.Core;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
#nullable enable
namespace Amd.KafkaConsumer.Entities
{
[Table("kafka_machine_data")]
public class MachineData : BaseEntity
{
public MachineData()
{
}
/// <summary>主键</summary>
[Key]
[Column("id")]
public long Id { get; set; }
/// <summary>设备ID</summary>
[Column("machine_id")]
public int MachineId { get; set; }
/// <summary>原始采集信息</summary>
[Column("read_data")]
public string ReadData { get; set; }
/// <summary>转换结果</summary>
[Column("create_time")]
public DateTime CreateTime { get; set; }
/// <summary>结果</summary>
[Column("result")]
public bool Result { get; set; }
/// <summary>转换值</summary>
[Column("receive_val", TypeName = "decimal(18,6)")]
public Decimal ReceiveVal { get; set; }
[NotMapped]
public MachineDataAtc MachineDataAtc { get; set; }
[NotMapped]
public Dictionary<string, string> Dicts { get; set; }
/// <summary>采集值转换</summary>
/// <param name="str"></param>
public MachineData(string str)
{
DateTime now = DateTime.Now;
try
{
this.Id = new IdWorker(1L, 1L).NextId();
JObject jobject = JObject.Parse(str);
jobject.Add("ReceiveTime", (JToken) now);
this.ReadData = str;
this.CreateTime = now;
int result;
this.MachineId = int.TryParse(jobject["mn"]?.ToString(), out result) ? result : 0;
this.ReceiveVal = 0M;
this.Result = true;
this.MachineDataAtc = JsonConvert.DeserializeObject<MachineDataAtc>(str);
}
catch (Exception ex)
{
Console.WriteLine("============================================================");
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
Console.WriteLine(ex.InnerException?.Message ?? "");
Console.WriteLine("============================================================");
}
}
public MachineData(MachineDataAtc tempData)
{
try
{
this.Id = new IdWorker(2L, 1L).NextId();
this.ReadData = JsonConvert.SerializeObject((object) tempData);
this.CreateTime = DateTime.Now;
this.MachineId = tempData.mn;
this.ReceiveVal = 0M;
this.Result = true;
this.MachineDataAtc = tempData;
this.Dicts = JsonConvert.DeserializeObject<Dictionary<string, string>>(JsonConvert.SerializeObject((object) tempData));
}
catch (Exception ex)
{
Console.WriteLine("============================================================");
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
Console.WriteLine(ex.InnerException?.Message ?? "");
Console.WriteLine("============================================================");
}
}
public MachineData(MachineDataTemp tempData, string json)
{
try
{
if (tempData.ReleaseState.HasValue)
{
this.Id = new IdWorker(5L, 1L).NextId();
this.ReadData = json;
this.CreateTime = DateTime.Now;
int result;
this.MachineId = int.TryParse(tempData.mn, out result) ? result : 0;
this.ReceiveVal = -999999M;
this.Result = tempData.ReleaseState.Value;
}
else if (tempData.gas == null || tempData.gas.value == null)
{
this.Id = new IdWorker(3L, 1L).NextId();
this.ReadData = json;
this.CreateTime = DateTime.Now;
int result;
this.MachineId = int.TryParse(tempData.mn, out result) ? result : 0;
this.ReceiveVal = -999999M;
this.Result = false;
}
else
{
this.Id = new IdWorker(4L, 1L).NextId();
this.ReadData = JsonConvert.SerializeObject((object) tempData);
this.CreateTime = DateTime.Now;
int result1;
this.MachineId = int.TryParse(tempData.mn, out result1) ? result1 : 0;
Decimal result2;
this.ReceiveVal = Decimal.TryParse(tempData.gas?.value ?? "0", out result2) ? result2 : 0M;
this.Result = tempData.gas?.result == "OK";
}
}
catch (Exception ex)
{
Console.WriteLine("============================================================");
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
Console.WriteLine(ex.InnerException?.Message ?? "");
Console.WriteLine("============================================================");
}
}
}
}
// Decompiled with JetBrains decompiler
// Type: Amd.KafkaConsumer.Entities.MachineDataAlarm
// Assembly: Amd.KafkaConsumer, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: 84842E10-777A-4595-89D9-B43B8D2CDA96
// Assembly location: D:\项目\上海斯凯孚整合项目\kafka\KafkaConsumer\KafkaConsumer\Amd.KafkaConsumer.dll
// XML documentation location: D:\项目\上海斯凯孚整合项目\kafka\KafkaConsumer\KafkaConsumer\Amd.KafkaConsumer.xml
using IdGen;
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
#nullable enable
namespace Amd.KafkaConsumer.Entities
{
/// <summary>设备报警信息</summary>
[Table("machine_data_alarm")]
public class MachineDataAlarm : BaseEntity
{
public MachineDataAlarm()
{
}
public MachineDataAlarm(MachineDataAtc atc)
{
this.Id = new IdGenerator(11).CreateId();
this.MachineId = atc.mn;
this.CreateTime = atc.t;
this.Fault = atc.Alarm_Fault;
this.Warning = atc.Alarm_Warning;
this.MaintenceDoorOpen = atc.Alarm_MaintenceDoorOpen;
this.SafeDoorOpen = atc.Alarm_SafeDoorOpen;
this.MaterialLowWarning = atc.Alarm_MaterialLowWarning;
this.FaultMsgID = atc.Alarm_FaultMsgID;
this.WarningMsgID = atc.Alarm_WarningMsgID;
this.SafeDoorOpenID = atc.Alarm_SafeDoorOpenID;
}
/// <summary>主键</summary>
[Key]
[Column("id")]
public long Id { get; set; }
/// <summary>设备ID</summary>
[Column("machine_id")]
public int MachineId { get; set; }
/// <summary>创建时间</summary>
[Column("create_time")]
public DateTime CreateTime { get; set; }
/// <summary>设备故障标记位</summary>
[Column("fault")]
public bool Fault { get; set; }
/// <summary>设备预警标记位</summary>
[Column("waring")]
public bool Warning { get; set; }
/// <summary>维修门打开</summary>
[Column("maintence_door_open")]
public bool MaintenceDoorOpen { get; set; }
/// <summary>安全门开</summary>
[Column("safe_door_open")]
public bool SafeDoorOpen { get; set; }
/// <summary>物料低报警</summary>
[Column("material_low_warning")]
public bool MaterialLowWarning { get; set; }
/// <summary>故障信息ID</summary>
[Column("fault_msg_id")]
public string FaultMsgID { get; set; }
/// <summary>报警信息ID</summary>
[Column("warning_msg_id")]
public string WarningMsgID { get; set; }
/// <summary>安全门开启ID代码</summary>
[Column("safe_door_open_id")]
public string SafeDoorOpenID { get; set; }
}
}
// Decompiled with JetBrains decompiler
// Type: Amd.KafkaConsumer.Entities.MachineDataAtc
// Assembly: Amd.KafkaConsumer, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: 84842E10-777A-4595-89D9-B43B8D2CDA96
// Assembly location: D:\项目\上海斯凯孚整合项目\kafka\KafkaConsumer\KafkaConsumer\Amd.KafkaConsumer.dll
// XML documentation location: D:\项目\上海斯凯孚整合项目\kafka\KafkaConsumer\KafkaConsumer\Amd.KafkaConsumer.xml
using IdGen;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Reflection;
#nullable enable
namespace Amd.KafkaConsumer.Entities
{
/// <summary>OPCUA</summary>
[Table("machine_data_atc")]
public class MachineDataAtc : BaseEntity
{
public MachineDataAtc() => this.Id = new IdGenerator(1).CreateId();
[Key]
[Column("id")]
public long Id { get; set; }
[Column("t")]
public DateTime t { get; set; }
[Column("mn")]
public int mn { get; set; }
[Column("State_AutoRun")]
public bool State_AutoRun { get; set; }
[Column("State_EffectiveRun")]
public bool State_EffectiveRun { get; set; }
[Column("State_ManualRun")]
public bool State_ManualRun { get; set; }
[Column("State_SingleStepRun")]
public bool State_SingleStepRun { get; set; }
[Column("State_ByPassRun")]
public bool State_ByPassRun { get; set; }
[Column("State_DryRun")]
public bool State_DryRun { get; set; }
[Column("State_RunOut")]
public bool State_RunOut { get; set; }
[Column("State_EnergySave")]
public bool State_EnergySave { get; set; }
[Column("State_FaultStop")]
public bool State_FaultStop { get; set; }
[Column("State_OperateStop")]
public bool State_OperateStop { get; set; }
[Column("State_EStop")]
public bool State_EStop { get; set; }
[Column("State_ByPassCode")]
public bool State_ByPassCode { get; set; }
[Column("Alarm_Fault")]
public bool Alarm_Fault { get; set; }
[Column("Alarm_Warning")]
public bool Alarm_Warning { get; set; }
[Column("Alarm_MaintenceDoorOpen")]
public bool Alarm_MaintenceDoorOpen { get; set; }
[Column("Alarm_SafeDoorOpen")]
public bool Alarm_SafeDoorOpen { get; set; }
[Column("Alarm_MaterialLowWarning")]
public bool Alarm_MaterialLowWarning { get; set; }
[Column("Alarm_FaultMsgID")]
public string Alarm_FaultMsgID { get; set; }
[Column("Alarm_WarningMsgID")]
public string Alarm_WarningMsgID { get; set; }
[Column("Alarm_SafeDoorOpenID")]
public string Alarm_SafeDoorOpenID { get; set; }
[Column("Process_Data_V1_ID")]
public string Process_Data_V1_ID { get; set; }
[Column("Process_Data_V1_SensorNo")]
public string Process_Data_V1_SensorNo { get; set; }
[Column("Process_Data_V1_SetPoint")]
public float Process_Data_V1_SetPoint { get; set; }
[Column("Process_Data_V1_USL")]
public float Process_Data_V1_USL { get; set; }
[Column("Process_Data_V1_Act")]
public float Process_Data_V1_Act { get; set; }
[Column("Process_Data_V1_LSL")]
public float Process_Data_V1_LSL { get; set; }
[Column("Tool_T1_ToolNo")]
public string Tool_T1_ToolNo { get; set; }
[Column("Tool_T1_FixtureNo")]
public string Tool_T1_FixtureNo { get; set; }
[Column("Tool_T1_LifeMax")]
public int Tool_T1_LifeMax { get; set; }
[Column("Tool_T1_LifeUsed")]
public int Tool_T1_LifeUsed { get; set; }
[Column("Tool_T1_ChangeWarning")]
public bool Tool_T1_ChangeWarning { get; set; }
[Column("Tool_T1_ChangeAck")]
public bool Tool_T1_ChangeAck { get; set; }
[Column("Tool_T1_Fault")]
public bool Tool_T1_Fault { get; set; }
[Column("Tool_T1_OnChange")]
public bool Tool_T1_OnChange { get; set; }
[Column("Tool_T1_OnUsed")]
public bool Tool_T1_OnUsed { get; set; }
[Column("Process_Data_V2_ID")]
public string Process_Data_V2_ID { get; set; }
[Column("Process_Data_V2_SensorNo")]
public string Process_Data_V2_SensorNo { get; set; }
[Column("Process_Data_V2_SetPoint")]
public float Process_Data_V2_SetPoint { get; set; }
[Column("Process_Data_V2_USL")]
public float Process_Data_V2_USL { get; set; }
[Column("Process_Data_V2_Act")]
public float Process_Data_V2_Act { get; set; }
[Column("Process_Data_V2_LSL")]
public float Process_Data_V2_LSL { get; set; }
public MachineDataAlarm GetAlarm() => new MachineDataAlarm(this);
public MachineDataState GetState() => new MachineDataState(this);
public List<MachineDataProcess> GetProcess()
{
List<MachineDataProcess> result = new List<MachineDataProcess>();
PropertyInfo[] processV1Properties = ((IEnumerable<PropertyInfo>) typeof (MachineDataAtc).GetProperties()).Where<PropertyInfo>((Func<PropertyInfo, bool>) (x => x.Name.StartsWith("Process_Data"))).ToArray<PropertyInfo>();
List<string> list1 = ((IEnumerable<PropertyInfo>) processV1Properties).Select<PropertyInfo, string>((Func<PropertyInfo, string>) (x => x.Name)).GroupBy<string, string>((Func<string, string>) (x => ((IEnumerable<string>) x.Split(new char[1]
{
'_'
}, StringSplitOptions.RemoveEmptyEntries)).Skip<string>(2).Take<string>(1).FirstOrDefault<string>())).Select<IGrouping<string, string>, string>((Func<IGrouping<string, string>, string>) (x => x.Key)).ToList<string>();
long[] ids = new IdGenerator(15).Take<long>(list1.Count).ToArray<long>();
int i = 0;
list1.ForEach((Action<string>) (t =>
{
List<PropertyInfo> list2 = ((IEnumerable<PropertyInfo>) processV1Properties).Where<PropertyInfo>((Func<PropertyInfo, bool>) (x => x.Name.Contains(t))).ToList<PropertyInfo>();
string dataId = list2.FirstOrDefault<PropertyInfo>((Func<PropertyInfo, bool>) (x => x.Name.EndsWith("_ID"))).GetValue((object) this).ToString();
string sensorNo = list2.FirstOrDefault<PropertyInfo>((Func<PropertyInfo, bool>) (x => x.Name.EndsWith("_SensorNo"))).GetValue((object) this).ToString();
float setPoint = (float) list2.FirstOrDefault<PropertyInfo>((Func<PropertyInfo, bool>) (x => x.Name.EndsWith("_SetPoint"))).GetValue((object) this);
float uSL = (float) list2.FirstOrDefault<PropertyInfo>((Func<PropertyInfo, bool>) (x => x.Name.EndsWith("_USL"))).GetValue((object) this);
float act = (float) list2.FirstOrDefault<PropertyInfo>((Func<PropertyInfo, bool>) (x => x.Name.EndsWith("_Act"))).GetValue((object) this);
float lSL = (float) list2.FirstOrDefault<PropertyInfo>((Func<PropertyInfo, bool>) (x => x.Name.EndsWith("_LSL"))).GetValue((object) this);
result.Add(new MachineDataProcess(ids[i], this.mn, this.t, t, dataId, sensorNo, setPoint, uSL, act, lSL));
++i;
}));
return result;
}
public List<MachineDataTool> GetTools()
{
List<MachineDataTool> result = new List<MachineDataTool>();
PropertyInfo[] processV1Properties = ((IEnumerable<PropertyInfo>) typeof (MachineDataAtc).GetProperties()).Where<PropertyInfo>((Func<PropertyInfo, bool>) (x => x.Name.StartsWith("Tool_T"))).ToArray<PropertyInfo>();
List<string> list1 = ((IEnumerable<PropertyInfo>) processV1Properties).Select<PropertyInfo, string>((Func<PropertyInfo, string>) (x => x.Name)).GroupBy<string, string>((Func<string, string>) (x => ((IEnumerable<string>) x.Split(new char[1]
{
'_'
}, StringSplitOptions.RemoveEmptyEntries)).Skip<string>(1).Take<string>(1).FirstOrDefault<string>())).Select<IGrouping<string, string>, string>((Func<IGrouping<string, string>, string>) (x => x.Key)).ToList<string>();
long[] ids = new IdGenerator(15).Take<long>(list1.Count).ToArray<long>();
int i = 0;
list1.ForEach((Action<string>) (t =>
{
List<PropertyInfo> list2 = ((IEnumerable<PropertyInfo>) processV1Properties).Where<PropertyInfo>((Func<PropertyInfo, bool>) (x => x.Name.Contains(t))).ToList<PropertyInfo>();
result.Add(new MachineDataTool(ids[i], this.mn, this.t, list2.FirstOrDefault<PropertyInfo>((Func<PropertyInfo, bool>) (x => x.Name.EndsWith("_ToolNo"))).GetValue((object) this).ToString(), list2.FirstOrDefault<PropertyInfo>((Func<PropertyInfo, bool>) (x => x.Name.EndsWith("_FixtureNo"))).GetValue((object) this).ToString(), (int) list2.FirstOrDefault<PropertyInfo>((Func<PropertyInfo, bool>) (x => x.Name.EndsWith("_LifeMax"))).GetValue((object) this), (int) list2.FirstOrDefault<PropertyInfo>((Func<PropertyInfo, bool>) (x => x.Name.EndsWith("_LifeUsed"))).GetValue((object) this), (bool) list2.FirstOrDefault<PropertyInfo>((Func<PropertyInfo, bool>) (x => x.Name.EndsWith("_ChangeWarning"))).GetValue((object) this), (bool) list2.FirstOrDefault<PropertyInfo>((Func<PropertyInfo, bool>) (x => x.Name.EndsWith("_ChangeAck"))).GetValue((object) this), (bool) list2.FirstOrDefault<PropertyInfo>((Func<PropertyInfo, bool>) (x => x.Name.EndsWith("_Fault"))).GetValue((object) this), (bool) list2.FirstOrDefault<PropertyInfo>((Func<PropertyInfo, bool>) (x => x.Name.EndsWith("_OnChange"))).GetValue((object) this), (bool) list2.FirstOrDefault<PropertyInfo>((Func<PropertyInfo, bool>) (x => x.Name.EndsWith("_OnUsed"))).GetValue((object) this), t));
++i;
}));
return result;
}
}
}
// Decompiled with JetBrains decompiler
// Type: Amd.KafkaConsumer.Entities.MachineDataAtcConfiguration
// Assembly: Amd.KafkaConsumer, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: 84842E10-777A-4595-89D9-B43B8D2CDA96
// Assembly location: D:\项目\上海斯凯孚整合项目\kafka\KafkaConsumer\KafkaConsumer\Amd.KafkaConsumer.dll
// XML documentation location: D:\项目\上海斯凯孚整合项目\kafka\KafkaConsumer\KafkaConsumer\Amd.KafkaConsumer.xml
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System;
using System.Linq.Expressions;
#nullable enable
namespace Amd.KafkaConsumer.Entities
{
public class MachineDataAtcConfiguration : IEntityTypeConfiguration<MachineDataAtc>
{
public void Configure(EntityTypeBuilder<MachineDataAtc> builder)
{
builder.HasIndex((Expression<Func<MachineDataAtc, object>>) (x => (object) x.t));
builder.HasIndex((Expression<Func<MachineDataAtc, object>>) (x => (object) x.mn));
}
}
}
// Decompiled with JetBrains decompiler
// Type: Amd.KafkaConsumer.Entities.MachineDataConfiguration
// Assembly: Amd.KafkaConsumer, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: 84842E10-777A-4595-89D9-B43B8D2CDA96
// Assembly location: D:\项目\上海斯凯孚整合项目\kafka\KafkaConsumer\KafkaConsumer\Amd.KafkaConsumer.dll
// XML documentation location: D:\项目\上海斯凯孚整合项目\kafka\KafkaConsumer\KafkaConsumer\Amd.KafkaConsumer.xml
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System;
using System.Linq.Expressions;
#nullable enable
namespace Amd.KafkaConsumer.Entities
{
public class MachineDataConfiguration : IEntityTypeConfiguration<MachineData>
{
public void Configure(EntityTypeBuilder<MachineData> builder)
{
builder.HasIndex((Expression<Func<MachineData, object>>) (x => (object) x.CreateTime));
builder.HasIndex((Expression<Func<MachineData, object>>) (x => (object) x.MachineId));
}
}
}
// Decompiled with JetBrains decompiler
// Type: Amd.KafkaConsumer.Entities.MachineDataProcess
// Assembly: Amd.KafkaConsumer, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: 84842E10-777A-4595-89D9-B43B8D2CDA96
// Assembly location: D:\项目\上海斯凯孚整合项目\kafka\KafkaConsumer\KafkaConsumer\Amd.KafkaConsumer.dll
// XML documentation location: D:\项目\上海斯凯孚整合项目\kafka\KafkaConsumer\KafkaConsumer\Amd.KafkaConsumer.xml
using IdGen;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
#nullable enable
namespace Amd.KafkaConsumer.Entities
{
/// <summary>设备工艺信息</summary>
[Table("machine_data_process")]
public class MachineDataProcess : BaseEntity
{
public MachineDataProcess()
{
}
public MachineDataProcess(
long id,
int machineId,
DateTime createTime,
string position,
string dataId,
string sensorNo,
float setPoint,
float uSL,
float act,
float lSL)
{
this.Id = id;
this.MachineId = machineId;
this.CreateTime = createTime;
this.Position = position;
this.DataId = dataId;
this.SensorNo = sensorNo;
this.SetPoint = setPoint;
this.USL = uSL;
this.Act = act;
this.LSL = lSL;
}
public List<MachineDataProcess> GetList(MachineData data)
{
List<MachineDataProcess> list1 = new List<MachineDataProcess>();
Dictionary<string, string> dictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(data.ReadData);
List<string> list2 = dictionary.Keys.Where<string>((Func<string, bool>) (x => x.StartsWith("Process_Data"))).Select<string, string>((Func<string, string>) (x => x.Split('_')[2])).Distinct<string>().ToList<string>();
int num = 0;
foreach (string str in list2)
{
++num;
list1.Add(new MachineDataProcess()
{
Id = new IdGenerator(12).CreateId() + (long) num,
MachineId = int.Parse(dictionary["mn"]),
CreateTime = DateTime.Parse(dictionary["t"]),
DataId = dictionary["Process_Data_" + str + "_ID"] ?? "",
SensorNo = dictionary["Process_Data_" + str + "_SensorNo"] ?? "",
SetPoint = float.Parse(dictionary["Process_Data_" + str + "_SetPoint"]),
USL = float.Parse(dictionary["Process_Data_" + str + "_USL"]),
LSL = float.Parse(dictionary["Process_Data_" + str + "_LSL"]),
Act = float.Parse(dictionary["Process_Data_" + str + "_Act"]),
Position = str
});
}
return list1;
}
public MachineDataProcess(MachineDataAtc atc, string position)
{
this.MachineId = atc.mn;
this.CreateTime = atc.t;
this.Position = position;
if (position == "V1")
{
this.Id = new IdGenerator(12).CreateId();
this.DataId = atc.Process_Data_V1_ID;
this.SensorNo = atc.Process_Data_V1_SensorNo;
this.SetPoint = atc.Process_Data_V1_SetPoint;
this.USL = atc.Process_Data_V1_USL;
this.LSL = atc.Process_Data_V1_LSL;
this.Act = atc.Process_Data_V1_Act;
}
else
{
this.Id = new IdGenerator(15).CreateId();
this.DataId = atc.Process_Data_V2_ID;
this.SensorNo = atc.Process_Data_V2_SensorNo;
this.SetPoint = atc.Process_Data_V2_SetPoint;
this.USL = atc.Process_Data_V2_USL;
this.LSL = atc.Process_Data_V2_LSL;
this.Act = atc.Process_Data_V2_Act;
}
}
/// <summary>主键</summary>
[Key]
[Column("id")]
public long Id { get; set; }
/// <summary>设备ID</summary>
[Column("machine_id")]
public int MachineId { get; set; }
/// <summary>创建时间</summary>
[Column("create_time")]
public DateTime CreateTime { get; set; }
/// <summary>位置</summary>
[Column("position")]
[MaxLength(20)]
public string Position { get; set; }
/// <summary>过程数据项编号</summary>
[Column("data_id")]
public string DataId { get; set; }
/// <summary>表具号</summary>
[Column("sensor_no")]
public string SensorNo { get; set; }
/// <summary>Pspec设定值</summary>
[Column("set_point")]
public float SetPoint { get; set; }
/// <summary>上规范围</summary>
[Column("usl")]
public float USL { get; set; }
/// <summary>实际值</summary>
[Column("act")]
public float Act { get; set; }
/// <summary>下规范围</summary>
[Column("lsl")]
public float LSL { get; set; }
}
}
// Decompiled with JetBrains decompiler
// Type: Amd.KafkaConsumer.Entities.MachineDataState
// Assembly: Amd.KafkaConsumer, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: 84842E10-777A-4595-89D9-B43B8D2CDA96
// Assembly location: D:\项目\上海斯凯孚整合项目\kafka\KafkaConsumer\KafkaConsumer\Amd.KafkaConsumer.dll
// XML documentation location: D:\项目\上海斯凯孚整合项目\kafka\KafkaConsumer\KafkaConsumer\Amd.KafkaConsumer.xml
using IdGen;
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
#nullable enable
namespace Amd.KafkaConsumer.Entities
{
/// <summary>设备状态信息</summary>
[Table("machine_data_state")]
public class MachineDataState : BaseEntity
{
public MachineDataState()
{
}
public MachineDataState(MachineDataAtc atc)
{
this.Id = new IdGenerator(13).CreateId();
this.MachineId = atc.mn;
this.CreateTime = atc.t;
this.AutoRun = atc.State_AutoRun;
this.EffectiveRun = atc.State_EffectiveRun;
this.ManualRun = atc.State_ManualRun;
this.SingleStepRun = atc.State_SingleStepRun;
this.ByPassRun = atc.State_ByPassRun;
this.DryRun = atc.State_DryRun;
this.RunOut = atc.State_RunOut;
this.EnergySave = atc.State_EnergySave;
this.FaultStop = atc.State_FaultStop;
this.OperateStop = atc.State_OperateStop;
this.EStop = atc.State_EStop;
this.ByPassCode = atc.State_ByPassCode;
}
/// <summary>主键</summary>
[Key]
[Column("id")]
public long Id { get; set; }
/// <summary>设备ID</summary>
[Column("machine_id")]
public int MachineId { get; set; }
/// <summary>创建时间</summary>
[Column("create_time")]
public DateTime CreateTime { get; set; }
/// <summary>自动运行</summary>
[Column("auto_run")]
public bool AutoRun { get; set; }
/// <summary>有效产出运行状态</summary>
[Column("effective_run")]
public bool EffectiveRun { get; set; }
/// <summary>手动运行</summary>
[Column("manual_run")]
public bool ManualRun { get; set; }
/// <summary>单步运行模式</summary>
[Column("single_step_run")]
public bool SingleStepRun { get; set; }
/// <summary>旁路,强制放行</summary>
[Column("by_pass_run")]
public bool ByPassRun { get; set; }
/// <summary>空运行模式</summary>
[Column("dry_run")]
public bool DryRun { get; set; }
/// <summary>排空模式</summary>
[Column("run_out")]
public bool RunOut { get; set; }
/// <summary>节能模式</summary>
[Column("energy_save")]
public bool EnergySave { get; set; }
/// <summary>设备故障自主停机</summary>
[Column("fault_stop")]
public bool FaultStop { get; set; }
/// <summary>操作工主动停机</summary>
[Column("operate_stop")]
public bool OperateStop { get; set; }
/// <summary>急停停机</summary>
[Column("e_stop")]
public bool EStop { get; set; }
/// <summary>ByPass类别编码</summary>
[Column("by_pass_code")]
public bool ByPassCode { get; set; }
}
}
// Decompiled with JetBrains decompiler
// Type: Amd.KafkaConsumer.Entities.MachineDataTemp
// Assembly: Amd.KafkaConsumer, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: 84842E10-777A-4595-89D9-B43B8D2CDA96
// Assembly location: D:\项目\上海斯凯孚整合项目\kafka\KafkaConsumer\KafkaConsumer\Amd.KafkaConsumer.dll
// XML documentation location: D:\项目\上海斯凯孚整合项目\kafka\KafkaConsumer\KafkaConsumer\Amd.KafkaConsumer.xml
using System;
#nullable enable
namespace Amd.KafkaConsumer.Entities
{
/// <summary>数采原始数据</summary>
public class MachineDataTemp
{
public int pid { get; set; }
public int cid { get; set; }
public int sys { get; set; }
public DateTime t { get; set; }
public string mn { get; set; } = "";
public bool? ReleaseState { get; set; }
public MachineDataTempResult gas { get; set; } = new MachineDataTempResult();
}
}
// Decompiled with JetBrains decompiler
// Type: Amd.KafkaConsumer.Entities.MachineDataTempResult
// Assembly: Amd.KafkaConsumer, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: 84842E10-777A-4595-89D9-B43B8D2CDA96
// Assembly location: D:\项目\上海斯凯孚整合项目\kafka\KafkaConsumer\KafkaConsumer\Amd.KafkaConsumer.dll
// XML documentation location: D:\项目\上海斯凯孚整合项目\kafka\KafkaConsumer\KafkaConsumer\Amd.KafkaConsumer.xml
#nullable enable
namespace Amd.KafkaConsumer.Entities
{
/// <summary>数采原始数据</summary>
public class MachineDataTempResult
{
public string value { get; set; }
public string result { get; set; }
}
}
// Decompiled with JetBrains decompiler
// Type: Amd.KafkaConsumer.Entities.MachineDataTool
// Assembly: Amd.KafkaConsumer, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: 84842E10-777A-4595-89D9-B43B8D2CDA96
// Assembly location: D:\项目\上海斯凯孚整合项目\kafka\KafkaConsumer\KafkaConsumer\Amd.KafkaConsumer.dll
// XML documentation location: D:\项目\上海斯凯孚整合项目\kafka\KafkaConsumer\KafkaConsumer\Amd.KafkaConsumer.xml
using IdGen;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
#nullable enable
namespace Amd.KafkaConsumer.Entities
{
/// <summary>刀具工装信息</summary>
[Table("machine_data_tool")]
public class MachineDataTool : BaseEntity
{
public MachineDataTool()
{
}
public MachineDataTool(
long id,
int machineId,
DateTime createTime,
string toolNo,
string fixtureNo,
int lifeMax,
int lifeUsed,
bool changeWarning,
bool changeAck,
bool fault,
bool onChange,
bool onUsed,
string position)
{
this.Id = id;
this.MachineId = machineId;
this.CreateTime = createTime;
this.ToolNo = toolNo;
this.FixtureNo = fixtureNo;
this.LifeMax = lifeMax;
this.LifeUsed = lifeUsed;
this.ChangeWarning = changeWarning;
this.ChangeAck = changeAck;
this.Fault = fault;
this.OnChange = onChange;
this.OnUsed = onUsed;
this.Position = position;
}
public MachineDataTool(MachineDataAtc atc)
{
this.Id = new IdGenerator(14).CreateId();
this.MachineId = atc.mn;
this.CreateTime = atc.t;
this.ToolNo = atc.Tool_T1_ToolNo;
this.FixtureNo = atc.Tool_T1_FixtureNo;
this.LifeMax = atc.Tool_T1_LifeMax;
this.LifeUsed = atc.Tool_T1_LifeUsed;
this.ChangeWarning = atc.Tool_T1_ChangeWarning;
this.ChangeAck = atc.Tool_T1_ChangeAck;
this.Fault = atc.Tool_T1_Fault;
this.OnChange = atc.Tool_T1_OnChange;
this.OnUsed = atc.Tool_T1_OnUsed;
this.Position = "T1";
}
public List<MachineDataTool> GetList(MachineData data)
{
List<MachineDataTool> list1 = new List<MachineDataTool>();
Dictionary<string, string> dictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(data.ReadData);
List<string> list2 = dictionary.Keys.Where<string>((Func<string, bool>) (x => x.StartsWith("Tool"))).Select<string, string>((Func<string, string>) (x => x.Split('_')[1])).Distinct<string>().ToList<string>();
int num = 0;
foreach (string str in list2)
{
++num;
list1.Add(new MachineDataTool()
{
Id = new IdGenerator(14).CreateId() + (long) num,
MachineId = int.Parse(dictionary["mn"]),
CreateTime = DateTime.Parse(dictionary["t"]),
ToolNo = dictionary["Tool_" + str + "_ToolNo"] ?? "",
FixtureNo = dictionary["Tool_" + str + "_FixtureNo"] ?? "",
LifeMax = int.Parse(dictionary["Tool_" + str + "_LifeMax"]),
LifeUsed = int.Parse(dictionary["Tool_" + str + "_LifeUsed"]),
ChangeWarning = bool.Parse(dictionary["Tool_" + str + "_ChangeWarning"]),
ChangeAck = bool.Parse(dictionary["Tool_" + str + "_ChangeAck"]),
Fault = bool.Parse(dictionary["Tool_" + str + "_Fault"]),
OnChange = bool.Parse(dictionary["Tool_" + str + "_OnChange"]),
OnUsed = bool.Parse(dictionary["Tool_" + str + "_OnUsed"]),
Position = str
});
}
return list1;
}
public MachineDataTool(MachineDataAtc atc, string position)
: this(atc)
{
}
/// <summary>主键</summary>
[Key]
[Column("id")]
public long Id { get; set; }
/// <summary>设备ID</summary>
[Column("machine_id")]
public int MachineId { get; set; }
/// <summary>创建时间</summary>
[Column("create_time")]
public DateTime CreateTime { get; set; }
/// <summary>刀具工装编号</summary>
[Column("tool_no")]
public string ToolNo { get; set; }
/// <summary>刀具工装座编号</summary>
[Column("fixture_no")]
public string FixtureNo { get; set; }
/// <summary>刀具工装最大使用次数</summary>
[Column("life_max")]
public int LifeMax { get; set; }
/// <summary>刀具工装已使用次数</summary>
[Column("life_used")]
public int LifeUsed { get; set; }
/// <summary>刀具工装更换提示</summary>
[Column("change_warning")]
public bool ChangeWarning { get; set; }
/// <summary>刀具工装更换确认</summary>
[Column("change_ack")]
public bool ChangeAck { get; set; }
/// <summary>刀具工装更换故障</summary>
[Column("fault")]
public bool Fault { get; set; }
/// <summary>刀具工装更换中</summary>
[Column("on_change")]
public bool OnChange { get; set; }
/// <summary>刀具工装在使用中</summary>
[Column("on_used")]
public bool OnUsed { get; set; }
[Column("position")]
[MaxLength(20)]
public string Position { get; set; } = "";
}
}
// Decompiled with JetBrains decompiler
// Type: Amd.KafkaConsumer.EventHandler.BaseDbEventDubscriber
// Assembly: Amd.KafkaConsumer, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: 84842E10-777A-4595-89D9-B43B8D2CDA96
// Assembly location: D:\项目\上海斯凯孚整合项目\kafka\KafkaConsumer\KafkaConsumer\Amd.KafkaConsumer.dll
// XML documentation location: D:\项目\上海斯凯孚整合项目\kafka\KafkaConsumer\KafkaConsumer\Amd.KafkaConsumer.xml
using Amd.KafkaConsumer.Entities;
using System.Threading.Tasks;
#nullable enable
namespace Amd.KafkaConsumer.EventHandler
{
/// <summary>保存基础数据到MySql</summary>
public class BaseDbEventDubscriber : EventSubscriber
{
/// <summary>
///
/// </summary>
/// <param name="publisher"></param>
public BaseDbEventDubscriber(EventPublisher publisher)
: base(publisher)
{
}
/// <inheritdoc />
///
/// 数据存储到MySQL数据库
public override Task DoActionAsync(MachineData data)
{
BlockQueue<MachineData>.Add(data);
return Task.CompletedTask;
}
}
}
using Amd.KafkaConsumer.Entities;
using System;
namespace Amd.KafkaConsumer.EventHandler
{
/// <summary>事件发布</summary>
public class EventPublisher
{
public event EventHandler<MachineData> EventOccurred;
public void RaiseEvent(MachineData data)
{
EventOccurred?.Invoke(this, data);
}
}
}
\ No newline at end of file
using Amd.KafkaConsumer.Entities;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Amd.KafkaConsumer.EventHandler
{
/// <summary>事件订阅基类</summary>
public class EventSubscriber
{
private readonly EventPublisher _publisher;
private readonly int _delaySeconds;
public EventSubscriber(EventPublisher publisher)
{
_publisher = publisher;
_publisher.EventOccurred += HandleEventOccurred;
}
public EventSubscriber(EventPublisher publisher, int second)
: this(publisher)
{
_delaySeconds = second;
}
/// <summary>订阅事件</summary>
/// <param name="sender"></param>
/// <param name="data"></param>
private void HandleEventOccurred(object sender, MachineData data)
{
Task.Run(async () =>
{
if (_delaySeconds > 0)
{
await Task.Delay(_delaySeconds * 1000);
}
await DoActionAsync(data);
});
}
/// <summary>数据处理</summary>
/// <param name="data"></param>
/// <returns></returns>
public virtual Task DoActionAsync(MachineData data) => Task.CompletedTask;
/// <summary>取消订阅</summary>
public void Unsubscribe()
{
_publisher.EventOccurred -= HandleEventOccurred;
}
}
}
\ No newline at end of file
// Decompiled with JetBrains decompiler
// Type: Amd.KafkaConsumer.EventHandler.RedisEventDubscriber
// Assembly: Amd.KafkaConsumer, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: 84842E10-777A-4595-89D9-B43B8D2CDA96
// Assembly location: D:\项目\上海斯凯孚整合项目\kafka\KafkaConsumer\KafkaConsumer\Amd.KafkaConsumer.dll
// XML documentation location: D:\项目\上海斯凯孚整合项目\kafka\KafkaConsumer\KafkaConsumer\Amd.KafkaConsumer.xml
using Amd.KafkaConsumer.Entities;
using CSRedis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
#nullable enable
namespace Amd.KafkaConsumer.EventHandler
{
/// <summary>保存最新数据到Redis,查看GlobalCache:KafkaMachineData键</summary>
public class RedisEventDubscriber : EventSubscriber
{
/// <summary>
///
/// </summary>
/// <param name="publisher"></param>
public RedisEventDubscriber(EventPublisher publisher)
: base(publisher)
{
}
/// <inheritdoc />
///
/// 数据存储到Redis 只保留300条数据
// public override async Task DoActionAsync(MachineData data)
// {
// CSRedisClient instance1 = RedisHelper<RedisHelper>.Instance;
// DefaultInterpolatedStringHandler interpolatedStringHandler1 = new DefaultInterpolatedStringHandler(0, 1);
// interpolatedStringHandler1.AppendFormatted<int>(data.MachineId);
// string stringAndClear1 = interpolatedStringHandler1.ToStringAndClear();
// MachineData machineData1 = data;
// int num1 = await instance1.HSetAsync("GlobalCache:KafkaMachineData", stringAndClear1, (object) machineData1) ? 1 : 0;
// CSRedisClient instance2 = RedisHelper<RedisHelper>.Instance;
// DefaultInterpolatedStringHandler interpolatedStringHandler2 = new DefaultInterpolatedStringHandler(29, 1);
// interpolatedStringHandler2.AppendLiteral("GlobalCache:KafkaMachineData:");
// interpolatedStringHandler2.AppendFormatted<int>(data.MachineId);
// string stringAndClear2 = interpolatedStringHandler2.ToStringAndClear();
// string[] source = await instance2.HKeysAsync(stringAndClear2);
// if (source.Length > 29)
// {
// // ISSUE: reference to a compiler-generated field
// // ISSUE: reference to a compiler-generated field
// string[] array = ((IEnumerable<string>) source).Select<string, long>(RedisEventDubscriber.<0>__Parse ?? (RedisEventDubscriber.<0>__Parse = new Func<string, long>(long.Parse))).OrderDescending<long>().Skip<long>(29).Select<long, string>((Func<long, string>) (x => x.ToString())).ToArray<string>();
// CSRedisClient instance3 = RedisHelper<RedisHelper>.Instance;
// DefaultInterpolatedStringHandler interpolatedStringHandler3 = new DefaultInterpolatedStringHandler(29, 1);
// interpolatedStringHandler3.AppendLiteral("GlobalCache:KafkaMachineData:");
// interpolatedStringHandler3.AppendFormatted<int>(data.MachineId);
// string stringAndClear3 = interpolatedStringHandler3.ToStringAndClear();
// string[] strArray = array;
// long num2 = await instance3.HDelAsync(stringAndClear3, strArray);
// }
// CSRedisClient instance4 = RedisHelper<RedisHelper>.Instance;
// DefaultInterpolatedStringHandler interpolatedStringHandler4 = new DefaultInterpolatedStringHandler(29, 1);
// interpolatedStringHandler4.AppendLiteral("GlobalCache:KafkaMachineData:");
// interpolatedStringHandler4.AppendFormatted<int>(data.MachineId);
// string stringAndClear4 = interpolatedStringHandler4.ToStringAndClear();
// interpolatedStringHandler4 = new DefaultInterpolatedStringHandler(0, 1);
// interpolatedStringHandler4.AppendFormatted<long>(data.Id);
// string stringAndClear5 = interpolatedStringHandler4.ToStringAndClear();
// MachineData machineData2 = data;
// int num3 = await instance4.HSetAsync(stringAndClear4, stringAndClear5, (object) machineData2) ? 1 : 0;
// }
//}
public override async Task DoActionAsync(MachineData data)
{
// 1. 存储到全局缓存
var instance1 = RedisHelper<RedisHelper>.Instance;
var globalKey = $"GlobalCache:KafkaMachineData";
var machineKey = data.MachineId.ToString();
int num1 = await instance1.HSetAsync(globalKey, machineKey, data) ? 1 : 0;
// 2. 获取特定机器的缓存键
var instance2 = RedisHelper<RedisHelper>.Instance;
var machineCacheKey = $"GlobalCache:KafkaMachineData:{data.MachineId}";
string[] source = await instance2.HKeysAsync(machineCacheKey);
// 3. 清理过期的缓存(保留最近29个)
if (source.Length > 29)
{
// 修复排序和筛选逻辑
var keysToDelete = source
.Select(key => long.TryParse(key, out long result) ? result : long.MinValue)
.Where(x => x != long.MinValue) // 过滤无效的long值
.OrderByDescending(x => x) // 使用 OrderByDescending
.Skip(29) // 保留最近的29个
.Select(x => x.ToString())
.ToArray();
if (keysToDelete.Length > 0)
{
var instance3 = RedisHelper<RedisHelper>.Instance;
long num2 = await instance3.HDelAsync(machineCacheKey, keysToDelete);
}
}
// 4. 存储到机器特定的缓存
var instance4 = RedisHelper<RedisHelper>.Instance;
var itemKey = data.Id.ToString();
int num3 = await instance4.HSetAsync(machineCacheKey, itemKey, data) ? 1 : 0;
}
}
}
// Decompiled with JetBrains decompiler
// Type: Amd.KafkaConsumer.Helper.LogHelper
// Assembly: Amd.KafkaConsumer, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: 84842E10-777A-4595-89D9-B43B8D2CDA96
// Assembly location: D:\项目\上海斯凯孚整合项目\kafka\KafkaConsumer\KafkaConsumer\Amd.KafkaConsumer.dll
// XML documentation location: D:\项目\上海斯凯孚整合项目\kafka\KafkaConsumer\KafkaConsumer\Amd.KafkaConsumer.xml
using NLog;
#nullable enable
namespace Amd.KafkaConsumer.Helper
{
public class LogHelper
{
public static Logger logger = LogManager.GetCurrentClassLogger();
public static string Keyword { get; set; }
}
}
// Decompiled with JetBrains decompiler
// Type: Amd.KafkaConsumer.Models.CusResult`1
// Assembly: Amd.KafkaConsumer, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: 84842E10-777A-4595-89D9-B43B8D2CDA96
// Assembly location: D:\项目\上海斯凯孚整合项目\kafka\KafkaConsumer\KafkaConsumer\Amd.KafkaConsumer.dll
// XML documentation location: D:\项目\上海斯凯孚整合项目\kafka\KafkaConsumer\KafkaConsumer\Amd.KafkaConsumer.xml
#nullable enable
namespace Amd.KafkaConsumer.Models
{
/// <summary>自定义数据返回格式</summary>
/// <typeparam name="T"></typeparam>
public class CusResult<T>
{
public int ret { get; set; }
public string message { get; set; }
public T data { get; set; }
}
}
// Decompiled with JetBrains decompiler
// Type: Amd.KafkaConsumer.Models.KafkaConfig
// Assembly: Amd.KafkaConsumer, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: 84842E10-777A-4595-89D9-B43B8D2CDA96
// Assembly location: D:\项目\上海斯凯孚整合项目\kafka\KafkaConsumer\KafkaConsumer\Amd.KafkaConsumer.dll
// XML documentation location: D:\项目\上海斯凯孚整合项目\kafka\KafkaConsumer\KafkaConsumer\Amd.KafkaConsumer.xml
using System.Collections.Generic;
#nullable enable
namespace Amd.KafkaConsumer.Models
{
public class KafkaConfig
{
public string Server { get; set; }
public List<TopicInfo> Topics { get; set; }
public string Group { get; set; }
}
}
// Decompiled with JetBrains decompiler
// Type: Amd.KafkaConsumer.Models.TopicInfo
// Assembly: Amd.KafkaConsumer, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: 84842E10-777A-4595-89D9-B43B8D2CDA96
// Assembly location: D:\项目\上海斯凯孚整合项目\kafka\KafkaConsumer\KafkaConsumer\Amd.KafkaConsumer.dll
// XML documentation location: D:\项目\上海斯凯孚整合项目\kafka\KafkaConsumer\KafkaConsumer\Amd.KafkaConsumer.xml
using System.Collections.Generic;
#nullable enable
namespace Amd.KafkaConsumer.Models
{
public class TopicInfo
{
public string Topic { get; set; }
public List<int> MachineIdList { get; set; }
}
}
//// Decompiled with JetBrains decompiler
//// Type: Program
//// Assembly: Amd.KafkaConsumer, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
//// MVID: 84842E10-777A-4595-89D9-B43B8D2CDA96
//// Assembly location: D:\项目\上海斯凯孚整合项目\kafka\KafkaConsumer\KafkaConsumer\Amd.KafkaConsumer.dll
//// XML documentation location: D:\项目\上海斯凯孚整合项目\kafka\KafkaConsumer\KafkaConsumer\Amd.KafkaConsumer.xml
//using Amd.KafkaConsumer.Entities;
//using Amd.KafkaConsumer.EventHandler;
//using Amd.KafkaConsumer.Helper;
//using Amd.KafkaConsumer.Models;
//using Amd.KafkaConsumer.Services;
//using CSRedis;
//using EasyShardingCore;
//using Microsoft.AspNetCore.Builder;
//using Microsoft.AspNetCore.Hosting;
//using Microsoft.Extensions.Configuration;
//using Microsoft.Extensions.DependencyInjection;
//using Microsoft.Extensions.Hosting;
//using NLog;
//using NLog.Layouts;
//using System;
//WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
//LogHelper.Keyword = args == null || args.Length == 0 ? "" : args[0];
//LogManager.Configuration.Variables["module"] = (Layout)"IOT";
//NLog.SetupBuilderExtensions.GetCurrentClassLogger(NLog.Web.SetupBuilderExtensions.LoadConfigurationFromAppSettings(LogManager.Setup()));
//ConfigurationManager configuration = builder.Configuration;
//DateTime result;
//DateTime begin = DateTime.TryParse(configuration["ConnectionStrings:ShardingBegin"], out result) ? result : DateTime.Now;
//EFCoreShardingExtensions.AddEFCoreSharding(builder.Services, (Action<IShardingBuilder>)(config =>
//{
// config.SetEntityAssemblies(typeof(BaseEntity).Assembly);
// config.EnableComments(true);
// config.CreateShardingTableOnStarting(true);
// config.AddDataSource(configuration["ConnectionStrings:MDbConnection"], ReadWriteType.Read | ReadWriteType.Write, DatabaseType.MySql);
// config.SetDateSharding<MachineData>("CreateTime", ExpandByDateMode.PerMonth, begin);
// config.SetDateSharding<MachineDataAtc>("t", ExpandByDateMode.PerMonth, begin);
// config.SetDateSharding<MachineDataState>("CreateTime", ExpandByDateMode.PerMonth, begin);
// config.SetDateSharding<MachineDataAlarm>("CreateTime", ExpandByDateMode.PerMonth, begin);
// config.SetDateSharding<MachineDataProcess>("CreateTime", ExpandByDateMode.PerMonth, begin);
// config.SetDateSharding<MachineDataTool>("CreateTime", ExpandByDateMode.PerMonth, begin);
//}));
//ServiceCollectionServiceExtensions.AddSingleton<EventPublisher>(builder.Services);
//RedisHelper<RedisHelper>.Initialization(new CSRedisClient(configuration["ConnectionStrings:MRedisConnection"]));
//Common.Url = configuration["ConnectionStrings:OPCUA"];
//EndpointMetadataApiExplorerServiceCollectionExtensions.AddEndpointsApiExplorer(builder.Services);
//SwaggerGenServiceCollectionExtensions.AddSwaggerGen(builder.Services);
//KafkaConfig kafkaConfig = new KafkaConfig();
//ConfigurationBinder.Bind(configuration.GetSection("Kafka"), (object)kafkaConfig);
//ServiceCollectionServiceExtensions.AddSingleton<KafkaConfig>(builder.Services, kafkaConfig);
//ServiceCollectionHostedServiceExtensions.AddHostedService<MachineDataActionBackgroundService>(builder.Services);
//ServiceCollectionHostedServiceExtensions.AddHostedService<MachineDataAtcActionBackgroundService>(builder.Services);
//ServiceCollectionHostedServiceExtensions.AddHostedService<MachineDataProcessActionBackgroundService>(builder.Services);
//ServiceCollectionHostedServiceExtensions.AddHostedService<MachineDataAlarmActionBackgroundService>(builder.Services);
//ServiceCollectionHostedServiceExtensions.AddHostedService<MachineDataStateActionBackgroundService>(builder.Services);
//ServiceCollectionHostedServiceExtensions.AddHostedService<MachineDataToolActionBackgroundService>(builder.Services);
//WebApplication app = ServiceCollectionExtensions.AddServices(builder.Services, builder);
//if (HostEnvironmentEnvExtensions.IsDevelopment(app.Environment))
//{
// object SwaggerBuilderExtensions = null;
// SwaggerBuilderExtensions.UseSwagger(app);
// SwaggerUIBuilderExtensions.UseSwaggerUI(app);
//}
//HostingAbstractionsWebHostBuilderExtensions.UseUrls(builder.WebHost, "http://*:19000");
//app.Run();
using Amd.KafkaConsumer.Entities;
using Amd.KafkaConsumer.EventHandler;
using Amd.KafkaConsumer.Helper;
using Amd.KafkaConsumer.Models;
using Amd.KafkaConsumer.Services;
using CSRedis;
using EasyShardingCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using NLog;
using NLog.Layouts;
using System;
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
LogHelper.Keyword = args == null || args.Length == 0 ? "" : args[0];
LogManager.Configuration.Variables["module"] = (Layout)"IOT";
NLog.SetupBuilderExtensions.GetCurrentClassLogger(NLog.Web.SetupBuilderExtensions.LoadConfigurationFromAppSettings(LogManager.Setup()));
ConfigurationManager configuration = builder.Configuration;
DateTime result;
DateTime begin = DateTime.TryParse(configuration["ConnectionStrings:ShardingBegin"], out result) ? result : DateTime.Now;
// 添加分片配置
EFCoreShardingExtensions.AddEFCoreSharding(builder.Services, config =>
{
config.SetEntityAssemblies(typeof(BaseEntity).Assembly);
config.EnableComments(true);
config.CreateShardingTableOnStarting(true);
config.AddDataSource(configuration["ConnectionStrings:MDbConnection"], ReadWriteType.Read | ReadWriteType.Write, DatabaseType.MySql);
config.SetDateSharding<MachineData>("CreateTime", ExpandByDateMode.PerMonth, begin);
config.SetDateSharding<MachineDataAtc>("t", ExpandByDateMode.PerMonth, begin);
config.SetDateSharding<MachineDataState>("CreateTime", ExpandByDateMode.PerMonth, begin);
config.SetDateSharding<MachineDataAlarm>("CreateTime", ExpandByDateMode.PerMonth, begin);
config.SetDateSharding<MachineDataProcess>("CreateTime", ExpandByDateMode.PerMonth, begin);
config.SetDateSharding<MachineDataTool>("CreateTime", ExpandByDateMode.PerMonth, begin);
});
// 添加服务
builder.Services.AddSingleton<EventPublisher>();
RedisHelper<RedisHelper>.Initialization(new CSRedisClient(configuration["ConnectionStrings:MRedisConnection"]));
Common.Url = configuration["ConnectionStrings:OPCUA"];
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
// Kafka配置
KafkaConfig kafkaConfig = new KafkaConfig();
configuration.GetSection("Kafka").Bind(kafkaConfig);
builder.Services.AddSingleton(kafkaConfig);
// 添加后台服务
builder.Services.AddHostedService<MachineDataActionBackgroundService>();
builder.Services.AddHostedService<MachineDataAtcActionBackgroundService>();
builder.Services.AddHostedService<MachineDataProcessActionBackgroundService>();
builder.Services.AddHostedService<MachineDataAlarmActionBackgroundService>();
builder.Services.AddHostedService<MachineDataStateActionBackgroundService>();
builder.Services.AddHostedService<MachineDataToolActionBackgroundService>();
// 构建应用
builder.WebHost.UseUrls("http://*:19000"); // UseUrls 应该在 Build() 之前调用
WebApplication app = builder.Build();
// 配置中间件
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.Run();
\ No newline at end of file
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:56474",
"sslPort": 44379
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:5119",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7135;http://localhost:5119",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
// Decompiled with JetBrains decompiler
// Type: Amd.KafkaConsumer.Services.Common
// Assembly: Amd.KafkaConsumer, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: 84842E10-777A-4595-89D9-B43B8D2CDA96
// Assembly location: D:\项目\上海斯凯孚整合项目\kafka\KafkaConsumer\KafkaConsumer\Amd.KafkaConsumer.dll
// XML documentation location: D:\项目\上海斯凯孚整合项目\kafka\KafkaConsumer\KafkaConsumer\Amd.KafkaConsumer.xml
using EasyShardingCore;
#nullable enable
namespace Amd.KafkaConsumer.Services
{
public static class Common
{
public static IShardingDbAccessor shardingDbAccessor { get; set; }
public static string UrlAlarm => Common.Url + "/Alarm/Create";
public static string UrlState => Common.Url + "/State/Create";
public static string UrlProcess => Common.Url + "/Process/Create";
public static string UrlTool => Common.Url + "/Tool/Create";
public static string Url { get; set; }
}
}
using Amd.KafkaConsumer.Entities;
using Amd.KafkaConsumer.EventHandler;
using Amd.KafkaConsumer.Helper;
using Amd.KafkaConsumer.Models;
using Confluent.Kafka;
using Mapster;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Amd.KafkaConsumer.Services
{
public class CommonService : ServiceBase
{
private readonly EventPublisher _eventPublisher;
private readonly KafkaConfig config;
public CommonService(
EventPublisher eventPublisher,
KafkaConfig _config,
IConfiguration configuration)
{
this.config = _config;
// 配置Kafka
KafkaConfig kafkaConfig = new KafkaConfig();
configuration.GetSection("Kafka").Bind(kafkaConfig);
kafkaConfig.Adapt(this.config);
this.RouteOptions.DisableAutoMapRoute = true;
this._eventPublisher = eventPublisher;
// 注册事件订阅者
BaseDbAtcEventDubscriber atcEventDubscriber = new BaseDbAtcEventDubscriber(this._eventPublisher);
// 注册测试端点
this.App.MapGet("/Common/Test", () =>
{
string testData = "{\"State_AutoRun\":false,\"State_EffectiveRun\":false,\"State_ManualRun\":true,\"State_SingleStepRun\":false,\"State_ByPassRun\":false,\"State_DryRun\":false,\"State_RunOut\":false,\"State_EnergySave\":false,\"State_FaultStop\":false,\"State_OperateStop\":true,\"State_EStop\":false,\"State_ByPassCode\":false,\"Alarm_Fault\":false,\"Alarm_Warning\":false,\"Alarm_MaintenceDoorOpen\":false,\"Alarm_SafeDoorOpen\":false,\"Alarm_MaterialLowWarning\":false,\"Alarm_FaultMsgID\":\"[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]\",\"Alarm_WarningMsgID\":\"[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]\",\"Alarm_SafeDoorOpenID\":\"0\",\"Process_Data_V1_ID\":\"0\",\"Process_Data_V1_SensorNo\":\"0\",\"Process_Data_V1_SetPoint\":0.0,\"Process_Data_V1_USL\":0.0,\"Process_Data_V1_Act\":4.0,\"Process_Data_V1_LSL\":0.0,\"Process_Data_V2_ID\":\"0\",\"Process_Data_V2_SensorNo\":\"0\",\"Process_Data_V2_SetPoint\":0.0,\"Process_Data_V2_USL\":31.0,\"Process_Data_V2_Act\":0.0,\"Process_Data_V2_LSL\":29.0,\"Process_Data_V3_ID\":\"0\",\"Process_Data_V3_SensorNo\":\"0\",\"Process_Data_V3_SetPoint\":0.0,\"Process_Data_V3_USL\":0.0,\"Process_Data_V3_Act\":0.0,\"Process_Data_V3_LSL\":0.0,\"Process_Data_V4_ID\":\"0\",\"Process_Data_V4_SensorNo\":\"0\",\"Process_Data_V4_SetPoint\":0.0,\"Process_Data_V4_USL\":0.0,\"Process_Data_V4_Act\":0.0,\"Process_Data_V4_LSL\":0.0,\"Process_Data_V5_ID\":\"0\",\"Process_Data_V5_SensorNo\":\"0\",\"Process_Data_V5_SetPoint\":0.0,\"Process_Data_V5_USL\":0.0,\"Process_Data_V5_Act\":0.0,\"Process_Data_V5_LSL\":0.0,\"Tool_T1_ToolNo\":\"0\",\"Tool_T1_FixtureNo\":\"0\",\"Tool_T1_LifeMax\":0,\"Tool_T1_LifeUsed\":0,\"Tool_T1_ChangeWarning\":false,\"Tool_T1_ChangeAck\":false,\"Tool_T1_Fault\":false,\"Tool_T1_OnChange\":false,\"Tool_T1_OnUsed\":false,\"mn\":\"947\",\"t\":\"2023-10-25T14:02:39.6024471+08:00\",\"cid\":2005,\"pid\":3116}";
MachineData data = new MachineData(JsonConvert.DeserializeObject<MachineDataAtc>(testData));
data.Dicts = JsonConvert.DeserializeObject<Dictionary<string, string>>(testData);
this._eventPublisher.RaiseEvent(data);
return Results.Ok("OK");
});
Console.WriteLine("Start Kafka Reader");
string brokerList = _config.Server;
List<string> topics = _config.Topics.Select(x => x.Topic).ToList();
// 启动Kafka消费者
Task.Run(() =>
{
CancellationTokenSource cts = new CancellationTokenSource();
Console.CancelKeyPress += (_, e) =>
{
e.Cancel = true;
cts.Cancel();
};
this.Run_Consume(brokerList, topics, cts.Token);
});
}
private void Run_Consume(string brokerList, List<string> topics, CancellationToken cancellationToken)
{
ConsumerConfig config = new ConsumerConfig
{
BootstrapServers = brokerList,
GroupId = this.config.Group,
EnableAutoCommit = false,
StatisticsIntervalMs = 5000,
SessionTimeoutMs = 6000,
AutoOffsetReset = AutoOffsetReset.Latest,
EnablePartitionEof = true,
PartitionAssignmentStrategy = PartitionAssignmentStrategy.CooperativeSticky
};
using (IConsumer<Ignore, string> consumer = new ConsumerBuilder<Ignore, string>(config)
.SetErrorHandler((_, e) => Console.WriteLine("Error: " + e.Reason))
.SetPartitionsAssignedHandler((c, partitions) => { })
.SetPartitionsRevokedHandler((c, partitions) =>
c.Assignment.Where(atp => partitions.Count(rtp => rtp.TopicPartition == atp) == 0))
.SetPartitionsLostHandler((c, partitions) => { })
.Build())
{
consumer.Subscribe(topics);
try
{
while (true)
{
try
{
ConsumeResult<Ignore, string> result = consumer.Consume(cancellationToken);
if (!result.IsPartitionEOF)
{
try
{
if (!result.Message.Value.Contains("offline"))
{
MachineData data = new MachineData(JsonConvert.DeserializeObject<MachineDataAtc>(result.Message.Value));
data.Dicts = JsonConvert.DeserializeObject<Dictionary<string, string>>(result.Message.Value);
if (data != null)
{
if (!string.IsNullOrWhiteSpace(LogHelper.Keyword))
LogHelper.logger.Info(result.Message.Value);
this._eventPublisher.RaiseEvent(data);
}
}
consumer.Commit(result);
}
catch (KafkaException ex)
{
Console.WriteLine(ex.Data);
}
}
}
catch (ConsumeException ex)
{
Console.WriteLine("Consume error: " + ex.Error.Reason);
}
}
}
catch (OperationCanceledException)
{
Console.WriteLine("Closing consumer.");
consumer.Close();
}
}
}
}
}
\ No newline at end of file
using Amd.KafkaConsumer.Entities;
using Amd.KafkaConsumer.Helper;
using EasyShardingCore;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json;
using Snowflake.Core;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace Amd.KafkaConsumer.Services
{
public class MachineDataActionBackgroundService : BackgroundService
{
private readonly IServiceProvider _serviceProvider;
private readonly IShardingDbAccessor _dbAccessor;
public MachineDataActionBackgroundService(
IServiceProvider serviceProvider,
IShardingDbAccessor dbAccessor)
{
_serviceProvider = serviceProvider;
_dbAccessor = dbAccessor;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
await Handle();
await Task.Delay(500, stoppingToken);
}
}
private async Task Handle()
{
if (BlockQueue<MachineData>.IsComleted())
return;
try
{
List<MachineData> machineDataList = new List<MachineData>();
while (BlockQueue<MachineData>.HasEle() && machineDataList.Count < 5)
{
MachineData machineData = BlockQueue<MachineData>.Take();
machineDataList.Add(machineData);
}
if (machineDataList.Count <= 0)
return;
await Save(machineDataList);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private async Task Save(List<MachineData> machineDataList)
{
try
{
int result = await _dbAccessor.InsertAsync<MachineData>(machineDataList);
}
catch (Exception ex)
{
// 如果插入失败,重新将数据加入队列
machineDataList.ForEach(x =>
{
Thread.Sleep(5);
x.Id = new IdWorker(1L, 1L).NextId(); // 生成新的ID
BlockQueue<MachineData>.Add(x);
});
LogHelper.logger.Info(JsonConvert.SerializeObject(ex));
Console.WriteLine(JsonConvert.SerializeObject(ex));
}
}
}
}
\ No newline at end of file
using Amd.KafkaConsumer.Entities;
using Amd.KafkaConsumer.Helper;
using EasyShardingCore;
using Flurl.Http;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json;
using NLog;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace Amd.KafkaConsumer.Services
{
public class MachineDataAlarmActionBackgroundService : BackgroundService
{
private readonly IServiceProvider _serviceProvider;
private readonly IShardingDbAccessor _dbAccessor;
public MachineDataAlarmActionBackgroundService(
IServiceProvider serviceProvider,
IShardingDbAccessor dbAccessor)
{
_serviceProvider = serviceProvider;
_dbAccessor = dbAccessor;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
Thread.Sleep(20);
while (!stoppingToken.IsCancellationRequested)
{
await Handle();
await Task.Delay(500, stoppingToken);
}
}
private async Task Handle()
{
if (BlockQueue<MachineDataAlarm>.IsComleted())
return;
try
{
List<MachineDataAlarm> alarmDataList = new List<MachineDataAlarm>();
while (BlockQueue<MachineDataAlarm>.HasEle() && alarmDataList.Count < 5)
{
MachineDataAlarm alarmData = BlockQueue<MachineDataAlarm>.Take();
alarmDataList.Add(alarmData);
}
if (alarmDataList.Count <= 0)
return;
await Save(alarmDataList);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private async Task Save(List<MachineDataAlarm> alarmDataList)
{
try
{
string response = await (Common.UrlAlarm ?? "").PostJsonAsync(alarmDataList).ReceiveString();
string logMessage = $"{Common.UrlAlarm}: \r\n {JsonConvert.SerializeObject(alarmDataList)} \r\n {response}";
LogHelper.logger.Info(logMessage);
}
catch (Exception ex)
{
string errorMessage = JsonConvert.SerializeObject(ex);
LogHelper.logger.Info(errorMessage);
Console.WriteLine(errorMessage);
}
}
}
}
\ No newline at end of file
using Amd.KafkaConsumer.Entities;
using EasyShardingCore;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace Amd.KafkaConsumer.Services
{
public class MachineDataAtcActionBackgroundService : BackgroundService
{
private readonly IServiceProvider _serviceProvider;
private readonly IShardingDbAccessor _dbAccessor;
public MachineDataAtcActionBackgroundService(
IServiceProvider serviceProvider,
IShardingDbAccessor dbAccessor)
{
_serviceProvider = serviceProvider;
_dbAccessor = dbAccessor;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
await Handle();
await Task.Delay(500, stoppingToken);
}
}
private async Task Handle()
{
if (BlockQueue<MachineDataAtc>.IsComleted())
return;
try
{
List<MachineDataAtc> atcDataList = new List<MachineDataAtc>();
while (BlockQueue<MachineDataAtc>.HasEle() && atcDataList.Count < 5)
{
MachineDataAtc atcData = BlockQueue<MachineDataAtc>.Take();
atcDataList.Add(atcData);
}
if (atcDataList.Count <= 0)
return;
await Save(atcDataList);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private async Task Save(List<MachineDataAtc> atcDataList)
{
try
{
await _dbAccessor.InsertAsync<MachineDataAtc>(atcDataList);
}
catch (Exception ex)
{
Console.WriteLine(JsonConvert.SerializeObject(ex));
}
}
}
}
\ No newline at end of file
using Amd.KafkaConsumer.Entities;
using Amd.KafkaConsumer.Helper;
using EasyShardingCore;
using Flurl.Http;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json;
using NLog;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace Amd.KafkaConsumer.Services
{
public class MachineDataProcessActionBackgroundService : BackgroundService
{
private readonly IServiceProvider _serviceProvider;
private readonly IShardingDbAccessor _dbAccessor;
public MachineDataProcessActionBackgroundService(
IServiceProvider serviceProvider,
IShardingDbAccessor dbAccessor)
{
_serviceProvider = serviceProvider;
_dbAccessor = dbAccessor;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
await Handle();
await Task.Delay(500, stoppingToken);
}
}
private async Task Handle()
{
if (BlockQueue<MachineDataProcess>.IsComleted())
return;
try
{
List<MachineDataProcess> processDataList = new List<MachineDataProcess>();
while (BlockQueue<MachineDataProcess>.HasEle() && processDataList.Count < 5)
{
MachineDataProcess processData = BlockQueue<MachineDataProcess>.Take();
processDataList.Add(processData);
}
if (processDataList.Count <= 0)
return;
await Save(processDataList);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private async Task Save(List<MachineDataProcess> processDataList)
{
try
{
string response = await (Common.UrlProcess ?? "").PostJsonAsync(processDataList).ReceiveString();
string logMessage = $"{Common.UrlProcess}: \r\n {JsonConvert.SerializeObject(processDataList)} \r\n {response}";
LogHelper.logger.Info(logMessage);
}
catch (Exception ex)
{
string errorMessage = JsonConvert.SerializeObject(ex);
LogHelper.logger.Info(errorMessage);
Console.WriteLine(errorMessage);
}
}
}
}
\ No newline at end of file
using Amd.KafkaConsumer.Entities;
using Amd.KafkaConsumer.Models;
using EasyShardingCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Threading.Tasks;
namespace Amd.KafkaConsumer.Services
{
public class MachineDataService : ServiceBase
{
public MachineDataService()
{
this.RouteOptions.DisableAutoMapRoute = true;
this.App.MapGet("/MachineData/GetList/{machineId}/{from}/{to}",
async ([FromServices] IShardingDbAccessor dbAccessor, int machineId, DateTime from, DateTime to) =>
await GetList(dbAccessor, machineId, from, to));
this.App.MapGet("/MachineData/GetTest/{machineId}/{from}/{to}",
async ([FromServices] IShardingDbAccessor dbAccessor, int machineId, DateTime from, DateTime to) =>
await GetTest(dbAccessor, machineId, from, to));
this.App.MapGet("/MachineData/GetCommonTest/{machineId}/{from}/{to}",
async ([FromServices] IShardingDbAccessor dbAccessor, int machineId, DateTime from, DateTime to) =>
await GetCommonList(dbAccessor, machineId, from, to));
}
public async Task<List<MachineData>> GetCommonList(
[FromServices] IShardingDbAccessor dbAccessor,
int machineId,
DateTime from,
DateTime to)
{
return await dbAccessor.GetIShardingQueryable<MachineData>()
.Where(x => x.CreateTime >= from && x.CreateTime <= to && x.MachineId == machineId)
.ToListAsync();
}
public async Task<List<MachineData>> GetList(
[FromServices] IShardingDbAccessor dbAccessor,
int machineId,
DateTime from,
DateTime to)
{
var list = await dbAccessor.GetIShardingQueryable<MachineData>()
.Where(x => x.CreateTime >= from && x.CreateTime <= to && x.MachineId == machineId && x.ReceiveVal > 0M)
.ToListAsync();
list.ForEach(x => x.ReadData = "");
return list;
}
public async Task<CusResult<List<MachineData>>> GetTest(
[FromServices] IShardingDbAccessor dbAccessor,
int machineId,
DateTime from,
DateTime to)
{
var list = await dbAccessor.GetIShardingQueryable<MachineData>()
.Where(x => x.CreateTime >= from && x.CreateTime <= to && x.MachineId == machineId)
.ToListAsync();
list.ForEach(x => x.ReadData = "");
return new CusResult<List<MachineData>> { data = list };
}
public async Task<CusResult<List<MachineDataAtc>>> GetAtcList(
[FromServices] IShardingDbAccessor dbAccessor,
int machineId,
DateTime from,
DateTime to,
int page,
int pagesize)
{
var list = await dbAccessor.GetIShardingQueryable<MachineDataAtc>()
.Where(x => x.t >= from && x.t <= to && x.mn == machineId)
.Skip((page - 1) * pagesize)
.Take(pagesize)
.ToListAsync();
return new CusResult<List<MachineDataAtc>> { data = list };
}
public async Task<CusResult<List<MachineDataAlarm>>> GetAlarmList(
[FromServices] IShardingDbAccessor dbAccessor,
int machineId,
DateTime from,
DateTime to,
int page,
int pagesize)
{
var list = await dbAccessor.GetIShardingQueryable<MachineDataAlarm>()
.Where(x => x.CreateTime >= from && x.CreateTime <= to && x.MachineId == machineId)
.Skip((page - 1) * pagesize)
.Take(pagesize)
.ToListAsync();
return new CusResult<List<MachineDataAlarm>> { data = list };
}
public async Task<CusResult<List<MachineDataState>>> GetStateList(
[FromServices] IShardingDbAccessor dbAccessor,
int machineId,
DateTime from,
DateTime to,
int page,
int pagesize)
{
var list = await dbAccessor.GetIShardingQueryable<MachineDataState>()
.Where(x => x.CreateTime >= from && x.CreateTime <= to && x.MachineId == machineId)
.Skip((page - 1) * pagesize)
.Take(pagesize)
.ToListAsync();
return new CusResult<List<MachineDataState>> { data = list };
}
public async Task<CusResult<List<MachineDataTool>>> GetToolList(
[FromServices] IShardingDbAccessor dbAccessor,
int machineId,
DateTime from,
DateTime to,
int page,
int pagesize)
{
var list = await dbAccessor.GetIShardingQueryable<MachineDataTool>()
.Where(x => x.CreateTime >= from && x.CreateTime <= to && x.MachineId == machineId)
.Skip((page - 1) * pagesize)
.Take(pagesize)
.ToListAsync();
return new CusResult<List<MachineDataTool>> { data = list };
}
public async Task<CusResult<List<MachineDataProcess>>> GetProcessList(
[FromServices] IShardingDbAccessor dbAccessor,
int machineId,
DateTime from,
DateTime to,
int page,
int pagesize)
{
var list = await dbAccessor.GetIShardingQueryable<MachineDataProcess>()
.Where(x => x.CreateTime >= from && x.CreateTime <= to && x.MachineId == machineId)
.Skip((page - 1) * pagesize)
.Take(pagesize)
.ToListAsync();
return new CusResult<List<MachineDataProcess>> { data = list };
}
/// <summary>创建报警</summary>
public async Task<int> AlarmCreate(
[FromServices] IShardingDbAccessor dbAccessor,
List<MachineDataAlarm> datas)
{
return await dbAccessor.InsertAsync<MachineDataAlarm>(datas);
}
/// <summary>创建状态</summary>
public async Task<int> StateCreate(
[FromServices] IShardingDbAccessor dbAccessor,
List<MachineDataState> datas)
{
return await dbAccessor.InsertAsync<MachineDataState>(datas);
}
/// <summary>创建工具</summary>
public async Task<int> ToolCreate(
[FromServices] IShardingDbAccessor dbAccessor,
List<MachineDataTool> datas)
{
return await dbAccessor.InsertAsync<MachineDataTool>(datas);
}
/// <summary>创建加工过程</summary>
public async Task<int> ProcessCreate(
[FromServices] IShardingDbAccessor dbAccessor,
List<MachineDataProcess> datas)
{
return await dbAccessor.InsertAsync<MachineDataProcess>(datas);
}
}
}
\ No newline at end of file
using Amd.KafkaConsumer.Entities;
using Amd.KafkaConsumer.Helper;
using EasyShardingCore;
using Flurl.Http;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json;
using NLog;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace Amd.KafkaConsumer.Services
{
public class MachineDataStateActionBackgroundService : BackgroundService
{
private readonly IServiceProvider _serviceProvider;
private readonly IShardingDbAccessor _dbAccessor;
public MachineDataStateActionBackgroundService(
IServiceProvider serviceProvider,
IShardingDbAccessor dbAccessor)
{
_serviceProvider = serviceProvider;
_dbAccessor = dbAccessor;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
await Handle();
await Task.Delay(500, stoppingToken);
}
}
private async Task Handle()
{
if (BlockQueue<MachineDataState>.IsComleted())
return;
try
{
List<MachineDataState> stateDataList = new List<MachineDataState>();
while (BlockQueue<MachineDataState>.HasEle() && stateDataList.Count < 5)
{
MachineDataState stateData = BlockQueue<MachineDataState>.Take();
stateDataList.Add(stateData);
}
if (stateDataList.Count <= 0)
return;
await Save(stateDataList);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private async Task Save(List<MachineDataState> stateDataList)
{
try
{
string response = await (Common.UrlState ?? "").PostJsonAsync(stateDataList).ReceiveString();
string logMessage = $"{Common.UrlState}: \r\n {JsonConvert.SerializeObject(stateDataList)} \r\n {response}";
LogHelper.logger.Info(logMessage);
}
catch (Exception ex)
{
string errorMessage = JsonConvert.SerializeObject(ex);
LogHelper.logger.Info(errorMessage);
Console.WriteLine(errorMessage);
}
}
}
}
\ No newline at end of file
using Amd.KafkaConsumer.Entities;
using Amd.KafkaConsumer.Helper;
using EasyShardingCore;
using Flurl.Http;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json;
using NLog;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace Amd.KafkaConsumer.Services
{
public class MachineDataToolActionBackgroundService : BackgroundService
{
private readonly IServiceProvider _serviceProvider;
private readonly IShardingDbAccessor _dbAccessor;
public MachineDataToolActionBackgroundService(
IServiceProvider serviceProvider,
IShardingDbAccessor dbAccessor)
{
_serviceProvider = serviceProvider;
_dbAccessor = dbAccessor;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
await Handle();
await Task.Delay(500, stoppingToken);
}
}
private async Task Handle()
{
if (BlockQueue<MachineDataTool>.IsComleted())
return;
try
{
List<MachineDataTool> operateLogInfos = new List<MachineDataTool>();
while (BlockQueue<MachineDataTool>.HasEle() && operateLogInfos.Count < 5)
{
MachineDataTool machineDataTool = BlockQueue<MachineDataTool>.Take();
operateLogInfos.Add(machineDataTool);
}
if (operateLogInfos.Count <= 0)
return;
await Save(operateLogInfos);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private async Task Save(List<MachineDataTool> operateLogInfos)
{
try
{
string str = await (Common.UrlTool ?? "").PostJsonAsync((object)operateLogInfos).ReceiveString();
Logger logger = LogHelper.logger;
string stringAndClear = BuildLogMessage(str, operateLogInfos);
logger.Info(stringAndClear);
}
catch (Exception ex)
{
LogHelper.logger.Info(JsonConvert.SerializeObject(ex));
Console.WriteLine(JsonConvert.SerializeObject(ex));
}
}
private string BuildLogMessage(string str, List<MachineDataTool> operateLogInfos)
{
return $"{Common.UrlState}: \r\n {JsonConvert.SerializeObject(operateLogInfos)} \r\n {str}";
}
}
}
\ No newline at end of file
// Decompiled with JetBrains decompiler
// Type: System.Runtime.CompilerServices.RefSafetyRulesAttribute
// Assembly: Amd.KafkaConsumer, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: 84842E10-777A-4595-89D9-B43B8D2CDA96
// Assembly location: D:\项目\上海斯凯孚整合项目\kafka\KafkaConsumer\KafkaConsumer\Amd.KafkaConsumer.dll
// XML documentation location: D:\项目\上海斯凯孚整合项目\kafka\KafkaConsumer\KafkaConsumer\Amd.KafkaConsumer.xml
using Microsoft.CodeAnalysis;
using System.Runtime.InteropServices;
namespace System.Runtime.CompilerServices
{
[CompilerGenerated]
[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
internal sealed class RefSafetyRulesAttribute : Attribute
{
public readonly int Version;
public RefSafetyRulesAttribute([In] int obj0) => this.Version = obj0;
}
}
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"Kafka": {
"Group": "202309120111",
"Server": "10.178.36.19:6667",
"Topics": [
{
"Topic": "sigerdataMsg",
"MachineIdList": []
}
]
},
"ConnectionStrings": {
"OPCUA": "http://localhost:28105/MTS",
"ShardingBegin": "2023-07-01",
"MDbConnection": "Server=10.178.36.20;port=3306;database=siger_shard_atc;charset=utf8;uid=siger;password=Siger_123;sslMode=None",
"MRedisConnection": "10.178.36.20:6379,password=ky701@YH.com,ssl=false,writeBuffer=10240"
}
}
This source diff could not be displayed because it is too large. You can view the blob instead.
{
"runtimeOptions": {
"tfm": "net7.0",
"frameworks": [
{
"name": "Microsoft.NETCore.App",
"version": "7.0.0"
},
{
"name": "Microsoft.AspNetCore.App",
"version": "7.0.0"
}
],
"configProperties": {
"System.GC.Server": true,
"System.Runtime.Serialization.EnableUnsafeBinaryFormatterSerialization": false
}
}
}
\ No newline at end of file
{"Version":1,"ManifestType":"Build","Endpoints":[]}
\ No newline at end of file
This source diff could not be displayed because it is too large. You can view the blob instead.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This source diff could not be displayed because it is too large. You can view the blob instead.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment