From edb1c8f0d5a7a034880dce90d946a1ce5f077856 Mon Sep 17 00:00:00 2001 From: wenjy Date: Tue, 22 Aug 2023 21:03:16 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E9=A1=B9=E7=9B=AE=E6=96=87?= =?UTF-8?q?=E4=BB=B6=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../FileDataUpload.Common.csproj | 65 +++ FileDataUpload.Common/INIFile.cs | 109 ++++ FileDataUpload.Common/JsonChange.cs | 113 ++++ FileDataUpload.Common/LogHelper.cs | 135 +++++ .../Properties/AssemblyInfo.cs | 37 ++ FileDataUpload.Common/log4net.config | 153 ++++++ FileDataUpload.Common/packages.config | 4 + FileDataUpload.Entity/AppConfig.cs | 120 ++++ FileDataUpload.Entity/DeviceParam.cs | 16 + FileDataUpload.Entity/DeviceParameterInfo.cs | 41 ++ .../DeviceParametersValue.cs | 55 ++ .../FileDataUpload.Entity.csproj | 59 ++ FileDataUpload.Entity/ParamData.cs | 32 ++ .../Properties/AssemblyInfo.cs | 36 ++ FileDataUpload.Entity/PropertyValue.cs | 52 ++ .../FileDataUpload.FileOperate.csproj | 66 +++ FileDataUpload.FileOperate/FileHelper.cs | 421 ++++++++++++++ FileDataUpload.FileOperate/MonitorEngine.cs | 104 ++++ .../Properties/AssemblyInfo.cs | 36 ++ FileDataUpload.FileOperate/packages.config | 4 + .../FileDataUpload.Mqtt.csproj | 54 ++ FileDataUpload.Mqtt/MqttClient.cs | 127 +++++ .../Properties/AssemblyInfo.cs | 36 ++ FileDataUpload.Mqtt/packages.config | 4 + FileDataUpload.sln | 49 ++ FileDataUpload/App.config | 6 + FileDataUpload/App.xaml | 15 + FileDataUpload/App.xaml.cs | 17 + FileDataUpload/FileDataUpload.csproj | 164 ++++++ FileDataUpload/MainWindow.xaml | 103 ++++ FileDataUpload/MainWindow.xaml.cs | 104 ++++ FileDataUpload/Properties/AssemblyInfo.cs | 55 ++ .../Properties/Resources.Designer.cs | 71 +++ FileDataUpload/Properties/Resources.resx | 117 ++++ .../Properties/Settings.Designer.cs | 30 + FileDataUpload/Properties/Settings.settings | 7 + FileDataUpload/SysConfigWindw.xaml | 107 ++++ FileDataUpload/SysConfigWindw.xaml.cs | 32 ++ FileDataUpload/packages.config | 7 + FileDataUpload/templates/icon/fileIcon.ico | Bin 0 -> 165662 bytes FileDataUpload/templates/icon/fileIcon.png | Bin 0 -> 5310 bytes FileDataUpload/templates/style/Button.xaml | 250 +++++++++ .../viewModel/MainWindowViewModel.cs | 517 ++++++++++++++++++ .../viewModel/SystemConfigViewModel.cs | 125 +++++ 44 files changed, 3655 insertions(+) create mode 100644 FileDataUpload.Common/FileDataUpload.Common.csproj create mode 100644 FileDataUpload.Common/INIFile.cs create mode 100644 FileDataUpload.Common/JsonChange.cs create mode 100644 FileDataUpload.Common/LogHelper.cs create mode 100644 FileDataUpload.Common/Properties/AssemblyInfo.cs create mode 100644 FileDataUpload.Common/log4net.config create mode 100644 FileDataUpload.Common/packages.config create mode 100644 FileDataUpload.Entity/AppConfig.cs create mode 100644 FileDataUpload.Entity/DeviceParam.cs create mode 100644 FileDataUpload.Entity/DeviceParameterInfo.cs create mode 100644 FileDataUpload.Entity/DeviceParametersValue.cs create mode 100644 FileDataUpload.Entity/FileDataUpload.Entity.csproj create mode 100644 FileDataUpload.Entity/ParamData.cs create mode 100644 FileDataUpload.Entity/Properties/AssemblyInfo.cs create mode 100644 FileDataUpload.Entity/PropertyValue.cs create mode 100644 FileDataUpload.FileOperate/FileDataUpload.FileOperate.csproj create mode 100644 FileDataUpload.FileOperate/FileHelper.cs create mode 100644 FileDataUpload.FileOperate/MonitorEngine.cs create mode 100644 FileDataUpload.FileOperate/Properties/AssemblyInfo.cs create mode 100644 FileDataUpload.FileOperate/packages.config create mode 100644 FileDataUpload.Mqtt/FileDataUpload.Mqtt.csproj create mode 100644 FileDataUpload.Mqtt/MqttClient.cs create mode 100644 FileDataUpload.Mqtt/Properties/AssemblyInfo.cs create mode 100644 FileDataUpload.Mqtt/packages.config create mode 100644 FileDataUpload.sln create mode 100644 FileDataUpload/App.config create mode 100644 FileDataUpload/App.xaml create mode 100644 FileDataUpload/App.xaml.cs create mode 100644 FileDataUpload/FileDataUpload.csproj create mode 100644 FileDataUpload/MainWindow.xaml create mode 100644 FileDataUpload/MainWindow.xaml.cs create mode 100644 FileDataUpload/Properties/AssemblyInfo.cs create mode 100644 FileDataUpload/Properties/Resources.Designer.cs create mode 100644 FileDataUpload/Properties/Resources.resx create mode 100644 FileDataUpload/Properties/Settings.Designer.cs create mode 100644 FileDataUpload/Properties/Settings.settings create mode 100644 FileDataUpload/SysConfigWindw.xaml create mode 100644 FileDataUpload/SysConfigWindw.xaml.cs create mode 100644 FileDataUpload/packages.config create mode 100644 FileDataUpload/templates/icon/fileIcon.ico create mode 100644 FileDataUpload/templates/icon/fileIcon.png create mode 100644 FileDataUpload/templates/style/Button.xaml create mode 100644 FileDataUpload/viewModel/MainWindowViewModel.cs create mode 100644 FileDataUpload/viewModel/SystemConfigViewModel.cs diff --git a/FileDataUpload.Common/FileDataUpload.Common.csproj b/FileDataUpload.Common/FileDataUpload.Common.csproj new file mode 100644 index 0000000..99e9298 --- /dev/null +++ b/FileDataUpload.Common/FileDataUpload.Common.csproj @@ -0,0 +1,65 @@ + + + + + Debug + AnyCPU + {8E2E1A40-99D9-4488-A4D1-6708B845E555} + Library + Properties + FileDataUpload.Common + FileDataUpload.Common + v4.5.2 + 512 + true + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + ..\packages\log4net.2.0.15\lib\net45\log4net.dll + + + ..\packages\Newtonsoft.Json.13.0.3\lib\net45\Newtonsoft.Json.dll + + + + + + + + + + + + + + + + + + + + + + PreserveNewest + + + + + \ No newline at end of file diff --git a/FileDataUpload.Common/INIFile.cs b/FileDataUpload.Common/INIFile.cs new file mode 100644 index 0000000..65d34eb --- /dev/null +++ b/FileDataUpload.Common/INIFile.cs @@ -0,0 +1,109 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading.Tasks; + +namespace FileDataUpload.Common +{ + /// + /// 配置操作类 + /// + public class INIFile + { + private string skey = "?S?)??[I"; + public string path; + + public INIFile(string INIPath) + { + path = INIPath; + } + + [DllImport("kernel32")] + private static extern long WritePrivateProfileString(string section, string key, string val, string filePath); + + [DllImport("kernel32")] + private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath); + + + [DllImport("kernel32")] + private static extern int GetPrivateProfileString(string section, string key, string defVal, Byte[] retVal, int size, string filePath); + + [DllImport("kernel32", EntryPoint = "GetPrivateProfileString")] + private static extern uint GetPrivateProfileStringA(string section, string key, string def, Byte[] retVal, int size, string filePath); + + /// + /// 写INI文件 + /// + /// + /// + /// + public void IniWriteValue(string Section, string Key, string Value) + { + + WritePrivateProfileString(Section, Key, Value, this.path); + } + + /// + /// 读取INI文件 + /// + /// + /// + /// + public string IniReadValue(string Section, string Key) + { + StringBuilder temp = new StringBuilder(255); + int i = GetPrivateProfileString(Section, Key, "", temp, 255, this.path); + //return temp.ToString(); + + string str = temp.ToString(); + + return str; + } + public byte[] IniReadValues(string section, string key) + { + byte[] temp = new byte[255]; + int i = GetPrivateProfileString(section, key, "", temp, 255, this.path); + return temp; + + } + + + /// + /// 删除ini文件下所有段落 + /// + public void ClearAllSection() + { + IniWriteValue(null, null, null); + } + /// + /// 删除ini文件下personal段落下的所有键 + /// + /// + public void ClearSection(string Section) + { + IniWriteValue(Section, null, null); + } + + public List ReadKeys(String SectionName) + { + return ReadKeys(SectionName, this.path); + } + + public List ReadKeys(string SectionName, string iniFilename) + { + List result = new List(); + Byte[] buf = new Byte[65536]; + uint len = GetPrivateProfileStringA(SectionName, null, null, buf, buf.Length, iniFilename); + int j = 0; + for (int i = 0; i < len; i++) + if (buf[i] == 0) + { + result.Add(Encoding.Default.GetString(buf, j, i - j)); + j = i + 1; + } + return result; + } + } +} \ No newline at end of file diff --git a/FileDataUpload.Common/JsonChange.cs b/FileDataUpload.Common/JsonChange.cs new file mode 100644 index 0000000..fcb8772 --- /dev/null +++ b/FileDataUpload.Common/JsonChange.cs @@ -0,0 +1,113 @@ +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Web.Script.Serialization; +using System.Xml.Linq; + +namespace FileDataUpload.Common +{ + public class JsonChange + { + + private static readonly Lazy lazy = new Lazy(() => new JsonChange()); + + public static JsonChange Instance + { + get + { + return lazy.Value; + } + } + + private JsonChange() { } + + /// + /// Model 实体转json + /// + /// 可以是单个实体,也可是实体集(即:ToList()) + /// + public string ModeToJson(object Model) + { + JavaScriptSerializer serializer = new JavaScriptSerializer(); + try + { + string str = serializer.Serialize(Model); + return str; + } + catch (Exception) + { + return ""; + } + } + + /// + /// json实体转Model + /// + /// + /// + /// + public T JsonToMode(string jsonStr) + { + JavaScriptSerializer serializer = new JavaScriptSerializer(); + try + { + var info = serializer.Deserialize(jsonStr); + return info; + } + catch (Exception) + { + return default(T); + } + } + + /// + /// object转dictionary + /// + /// + /// + public Dictionary objectToDictionary(string jsonData) + { + Dictionary result = new Dictionary(); + + var inf = JsonConvert.DeserializeObject>(jsonData); + + foreach (KeyValuePair item in inf) + { + if (item.Value != null) + { + var type = item.Value.GetType(); + if (type == typeof(JObject)) + { + var info = objectToDictionary(JsonConvert.SerializeObject(item.Value)); + foreach (KeyValuePair ite in info) + { + result.Add(ite.Key, ite.Value); + } + continue; + } + else if (type == typeof(JArray)) + { + JArray array = (JArray)item.Value; + var info = objectToDictionary(JsonConvert.SerializeObject(array[0])); + foreach (KeyValuePair ite in info) + { + result.Add(item.Key + ite.Key, ite.Value); + } + continue; + } + } + + result.Add(item.Key, item.Value); + } + + return result; + } + + + + } +} \ No newline at end of file diff --git a/FileDataUpload.Common/LogHelper.cs b/FileDataUpload.Common/LogHelper.cs new file mode 100644 index 0000000..44946eb --- /dev/null +++ b/FileDataUpload.Common/LogHelper.cs @@ -0,0 +1,135 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace FileDataUpload.Common +{ + public sealed class LogHelper + { + + private readonly log4net.ILog loginfo = log4net.LogManager.GetLogger("loginfo"); + private readonly log4net.ILog logerror = log4net.LogManager.GetLogger("logerror"); + private readonly log4net.ILog logView = log4net.LogManager.GetLogger("viewlog"); + // 日志优化,四个,调用地方注释掉 + private readonly log4net.ILog sqllog = log4net.LogManager.GetLogger("sqllog"); + private readonly log4net.ILog semaphorelog = log4net.LogManager.GetLogger("semaphorelog"); + private readonly log4net.ILog logPlc = log4net.LogManager.GetLogger("plclog"); + private readonly log4net.ILog logRfid = log4net.LogManager.GetLogger("rfidlog"); + + private static readonly Lazy lazy = new Lazy(() => new LogHelper()); + + public static LogHelper Instance + { + get + { + return lazy.Value; + } + } + + private LogHelper() { } + + + /// + /// 记录Info日志 + /// + /// + /// + public void Info(string msg) + { + if (loginfo.IsInfoEnabled) + { + loginfo.Info(msg); + } + } + + /// + /// 记录PLC日志 + /// + /// + public void PlcLog(string msg) + { + if (logPlc.IsInfoEnabled) + { + logPlc.Info(msg); + } + } + + /// + /// 记录Rfid日志 + /// + /// + public void RfidLog(string msg) + { + if (logRfid.IsInfoEnabled) + { + logRfid.Info(msg); + } + } + + /// + /// 界面日志 + /// + /// + public void ViewLog(string msg) + { + if (logView.IsInfoEnabled) + { + logView.Info(msg); + } + } + + public void SqlLog(string msg) + { + if (sqllog.IsInfoEnabled) + { + sqllog.Info(msg); + } + } + + public void SemaphoreLog(string msg) + { + if (semaphorelog.IsInfoEnabled) + { + semaphorelog.Info(msg); + } + } + + /// + /// 记录Error日志 + /// + /// + /// + public void Error(string info, Exception ex = null) + { + if (!string.IsNullOrEmpty(info) && ex == null) + { + logerror.ErrorFormat("【附加信息】 : {0}
", new object[] { info }); + } + else if (!string.IsNullOrEmpty(info) && ex != null) + { + string errorMsg = BeautyErrorMsg(ex); + logerror.ErrorFormat("【附加信息】 : {0}
{1}", new object[] { info, errorMsg }); + } + else if (string.IsNullOrEmpty(info) && ex != null) + { + string errorMsg = BeautyErrorMsg(ex); + logerror.Error(errorMsg); + } + } + + /// + /// 美化错误信息 + /// + /// 异常 + /// 错误信息 + private string BeautyErrorMsg(Exception ex) + { + string errorMsg = string.Format("【异常类型】:{0}
【异常信息】:{1}
【堆栈调用】:{2}", new object[] { ex.GetType().Name, ex.Message, ex.StackTrace }); + errorMsg = errorMsg.Replace("\r\n", "
"); + errorMsg = errorMsg.Replace("位置", "位置"); + return errorMsg; + } + } +} diff --git a/FileDataUpload.Common/Properties/AssemblyInfo.cs b/FileDataUpload.Common/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..3de4b94 --- /dev/null +++ b/FileDataUpload.Common/Properties/AssemblyInfo.cs @@ -0,0 +1,37 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 有关程序集的一般信息由以下 +// 控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("FileDataUpload.Common")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("FileDataUpload.Common")] +[assembly: AssemblyCopyright("Copyright © 2023")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] +[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", ConfigFileExtension = "config", Watch = true)] + +// 将 ComVisible 设置为 false 会使此程序集中的类型 +//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 +//请将此类型的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID +[assembly: Guid("8e2e1a40-99d9-4488-a4d1-6708b845e555")] + +// 程序集的版本信息由下列四个值组成: +// +// 主版本 +// 次版本 +// 生成号 +// 修订号 +// +//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值 +//通过使用 "*",如下所示: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/FileDataUpload.Common/log4net.config b/FileDataUpload.Common/log4net.config new file mode 100644 index 0000000..a9d7efb --- /dev/null +++ b/FileDataUpload.Common/log4net.config @@ -0,0 +1,153 @@ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/FileDataUpload.Common/packages.config b/FileDataUpload.Common/packages.config new file mode 100644 index 0000000..dc798ab --- /dev/null +++ b/FileDataUpload.Common/packages.config @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/FileDataUpload.Entity/AppConfig.cs b/FileDataUpload.Entity/AppConfig.cs new file mode 100644 index 0000000..3edbb6e --- /dev/null +++ b/FileDataUpload.Entity/AppConfig.cs @@ -0,0 +1,120 @@ +using FileDataUpload.Common; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Text; +using System.Threading.Tasks; + +namespace FileDataUpload.Entity +{ + public sealed class AppConfig + { + private static INIFile iNIFile = new INIFile(System.Environment.CurrentDirectory + "/App.InI"); + + private static readonly Lazy lazy = new Lazy(() => new AppConfig()); + + public static AppConfig Instance + { + get + { + return lazy.Value; + } + } + + private AppConfig() { } + + //public int pushFlag_RivetingRing = Convert.ToInt32(iNIFile.IniReadValue("system", "pushFlag_RivetingRing")); + + //public int pushFlag_Stopper = Convert.ToInt32(iNIFile.IniReadValue("system", "pushFlag_Stopper")); + + //public int pushFlag_displacingValve = Convert.ToInt32(iNIFile.IniReadValue("system", "pushFlag_displacingValve")); + + /// + /// 铆压环 推送标志位 + /// + public int pushFlag_RivetingRing + { + get { return Convert.ToInt32(iNIFile.IniReadValue("system", "pushFlag_RivetingRing")); } + set { iNIFile.IniWriteValue("system", "pushFlag_RivetingRing", value.ToString()); } + } + + /// + /// 限位器 推送标志位 + /// + public int pushFlag_Stopper + { + get { return Convert.ToInt32(iNIFile.IniReadValue("system", "pushFlag_Stopper")); } + set { iNIFile.IniWriteValue("system", "pushFlag_Stopper", value.ToString()); } + } + + /// + /// 排气阀片 推送标志位 + /// + public int pushFlag_displacingValve + { + get { return Convert.ToInt32(iNIFile.IniReadValue("system", "pushFlag_displacingValve")); } + set { iNIFile.IniWriteValue("system", "pushFlag_displacingValve", value.ToString()); } + } + + public string filePath + { + get { return iNIFile.IniReadValue("system", "filePath"); } + set { iNIFile.IniWriteValue("system", "filePath", value); } + } + + public string fileType + { + get { return iNIFile.IniReadValue("system", "fileType"); } + } + + public string 产线 + { + get { return iNIFile.IniReadValue("system", "产线"); } + set { iNIFile.IniWriteValue("system", "产线", value); } + } + + public string 物料编号 + { + get { return iNIFile.IniReadValue("system", "物料编号"); } + set { iNIFile.IniWriteValue("system", "物料编号", value); } + } + + public string 生产条码 + { + get { return iNIFile.IniReadValue("system", "生产条码"); } + set { iNIFile.IniWriteValue("system", "生产条码", value); } + } + + public string 设备编码 + { + get { return iNIFile.IniReadValue("system", "设备编码"); } + set { iNIFile.IniWriteValue("system", "设备编码", value); } + } + + public string 测试总结果 + { + get { return iNIFile.IniReadValue("system", "测试总结果"); } + set { iNIFile.IniWriteValue("system", "测试总结果", value); } + } + + public string 当日生产总数 + { + get { return iNIFile.IniReadValue("system", "当日生产总数"); } + set { iNIFile.IniWriteValue("system", "当日生产总数", value); } + } + + public string 当日生产不良数 + { + get { return iNIFile.IniReadValue("system", "当日生产不良数"); } + set { iNIFile.IniWriteValue("system", "当日生产不良数", value); } + } + + public string 班次 + { + get { return iNIFile.IniReadValue("system", "班次"); } + set { iNIFile.IniWriteValue("system", "班次", value); } + } + + } +} diff --git a/FileDataUpload.Entity/DeviceParam.cs b/FileDataUpload.Entity/DeviceParam.cs new file mode 100644 index 0000000..90cbdc0 --- /dev/null +++ b/FileDataUpload.Entity/DeviceParam.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace FileDataUpload.Entity +{ + public class DeviceParam + { + + public string id { get; set; } + + public ParamData data { get; set; } + } +} diff --git a/FileDataUpload.Entity/DeviceParameterInfo.cs b/FileDataUpload.Entity/DeviceParameterInfo.cs new file mode 100644 index 0000000..0ee74bc --- /dev/null +++ b/FileDataUpload.Entity/DeviceParameterInfo.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace FileDataUpload.Entity +{ + /// + /// 参数信息 + /// + public class DeviceParameterInfo + { + /// + /// 公司名称 + /// + public string companyName { get; set; } + + /// + /// 工件名称 + /// + public string partName { get; set; } + + /// + /// 工件编号 + /// + public string partNumber { get; set; } + + /// + /// 操作人员 + /// + public string operatingPersonnel { get; set; } + + /// + /// 参数值 + /// + public List deviceParametersValues { get; set; } + } + + +} diff --git a/FileDataUpload.Entity/DeviceParametersValue.cs b/FileDataUpload.Entity/DeviceParametersValue.cs new file mode 100644 index 0000000..943a905 --- /dev/null +++ b/FileDataUpload.Entity/DeviceParametersValue.cs @@ -0,0 +1,55 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace FileDataUpload.Entity +{ + /// + /// 设备参数值 + /// + public class DeviceParametersValue + { + /// + /// 参数编号 + /// + public string paramNumber { get; set; } + + /// + /// 内容 + /// + public string paramContent { get; set; } + + /// + /// 测量值 + /// + public object observedValue { get; set; } + + /// + /// 名义值 + /// + public object nominalValue { get; set; } + + /// + /// 超差值 + /// + public object overproofValue { get; set; } + + /// + /// 上公差 + /// + public object upperDeviation { get; set; } + + /// + /// 下公差 + /// + public object lowerDeviation { get; set; } + + /// + /// 状态 + /// + public string state { get; set; } + + } +} diff --git a/FileDataUpload.Entity/FileDataUpload.Entity.csproj b/FileDataUpload.Entity/FileDataUpload.Entity.csproj new file mode 100644 index 0000000..b3b2ebe --- /dev/null +++ b/FileDataUpload.Entity/FileDataUpload.Entity.csproj @@ -0,0 +1,59 @@ + + + + + Debug + AnyCPU + {E7158B5C-2C09-432E-83AC-7D2C065E664F} + Library + Properties + FileDataUpload.Entity + FileDataUpload.Entity + v4.5.2 + 512 + true + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + + + {8e2e1a40-99d9-4488-a4d1-6708b845e555} + FileDataUpload.Common + + + + \ No newline at end of file diff --git a/FileDataUpload.Entity/ParamData.cs b/FileDataUpload.Entity/ParamData.cs new file mode 100644 index 0000000..11f0eac --- /dev/null +++ b/FileDataUpload.Entity/ParamData.cs @@ -0,0 +1,32 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace FileDataUpload.Entity +{ + public class ParamData + { + /// + /// + /// + public string deviceCode { get; set; } + /// + /// + /// + public string propertyCode { get; set; } + /// + /// + /// + public int dataType { get; set; } + /// + /// + /// + public object propertyValue { get; set; } + /// + /// + /// + public string time { get; set; } + } +} diff --git a/FileDataUpload.Entity/Properties/AssemblyInfo.cs b/FileDataUpload.Entity/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..7163d47 --- /dev/null +++ b/FileDataUpload.Entity/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 有关程序集的一般信息由以下 +// 控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("FileDataUpload.Entity")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("FileDataUpload.Entity")] +[assembly: AssemblyCopyright("Copyright © 2023")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 将 ComVisible 设置为 false 会使此程序集中的类型 +//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 +//请将此类型的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID +[assembly: Guid("e7158b5c-2c09-432e-83ac-7d2c065e664f")] + +// 程序集的版本信息由下列四个值组成: +// +// 主版本 +// 次版本 +// 生成号 +// 修订号 +// +//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值 +//通过使用 "*",如下所示: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/FileDataUpload.Entity/PropertyValue.cs b/FileDataUpload.Entity/PropertyValue.cs new file mode 100644 index 0000000..c184df4 --- /dev/null +++ b/FileDataUpload.Entity/PropertyValue.cs @@ -0,0 +1,52 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace FileDataUpload.Entity +{ + public class PropertyValue + { + /// + /// + /// + public string DEVICE_NAME { get; set; } + /// + /// + /// + public string CHECK_ITEM { get; set; } + /// + /// + /// + public string ITEM_VALUE { get; set; } + /// + /// + /// + public string ACCURACYVALUE { get; set; } + /// + /// + /// + public string STANDARDVALUE { get; set; } + /// + /// + /// + public string STANDARDMAX { get; set; } + /// + /// + /// + public string STANDARDMIN { get; set; } + /// + /// + /// + public string TEST_STATUS { get; set; } + /// + /// + /// + public string UOM { get; set; } + /// + /// + /// + public string TEST_DETAIL_ID { get; set; } + } +} diff --git a/FileDataUpload.FileOperate/FileDataUpload.FileOperate.csproj b/FileDataUpload.FileOperate/FileDataUpload.FileOperate.csproj new file mode 100644 index 0000000..bbf3215 --- /dev/null +++ b/FileDataUpload.FileOperate/FileDataUpload.FileOperate.csproj @@ -0,0 +1,66 @@ + + + + + Debug + AnyCPU + {000F3ED7-6A2F-44C6-A31A-DA0FD0C66061} + Library + Properties + FileDataUpload.FileOperate + FileDataUpload.FileOperate + v4.5.2 + 512 + true + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + ..\packages\MiniExcel.1.30.2\lib\net45\MiniExcel.dll + + + + + + + + + + + + + + + + + + + + + + {8E2E1A40-99D9-4488-A4D1-6708B845E555} + FileDataUpload.Common + + + {E7158B5C-2C09-432E-83AC-7D2C065E664F} + FileDataUpload.Entity + + + + \ No newline at end of file diff --git a/FileDataUpload.FileOperate/FileHelper.cs b/FileDataUpload.FileOperate/FileHelper.cs new file mode 100644 index 0000000..6fde06f --- /dev/null +++ b/FileDataUpload.FileOperate/FileHelper.cs @@ -0,0 +1,421 @@ +using FileDataUpload.Common; +using FileDataUpload.Entity; +using MiniExcelLibs; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; + +namespace FileDataUpload.FileOperate +{ + public sealed class FileHelper + { + + private int paramBeginRowNumber = 6; + + private readonly JsonChange jsonChange = JsonChange.Instance; + + private readonly LogHelper logHelper = LogHelper.Instance; + + private AppConfig appConfig = AppConfig.Instance; + + private static readonly Lazy lazy = new Lazy(() => new FileHelper()); + + public static FileHelper Instance + { + get + { + return lazy.Value; + } + } + + private FileHelper() { } + + [Obsolete] + public Dictionary> ReadExcelFile_New(string filePath) + { + try + { + Dictionary> keyValues = new Dictionary>(); + + var sheetNames = MiniExcel.GetSheetNames(filePath); + foreach (var sheetName in sheetNames) + { + List deviceParams = new List(); + DeviceParam parameterInfo = new DeviceParam(); + List info = MiniExcel.Query(filePath, sheetName: sheetName).ToList(); + if (info != null && info.Count() > paramBeginRowNumber) + { + for(int i=8; i<16; i++) + { + DeviceParam deviceParam = new DeviceParam(); + deviceParam.id = System.Guid.NewGuid().ToString("N"); + ParamData param = new ParamData(); + param.deviceCode = "EVtest"; + param.propertyCode = info[i].C; + param.dataType = GetDataType(info[16].F == null ? "Text" : info[16].F); + param.propertyValue = info[i].E; + param.time = GetTimeStamp(); + deviceParam.data = param; + deviceParams.Add(deviceParam); + } + + DeviceParam deviceParam_17 = new DeviceParam(); + deviceParam_17.id = System.Guid.NewGuid().ToString("N"); + ParamData param_17 = new ParamData(); + param_17.deviceCode = "EVtest"; + param_17.propertyCode = info[17].C; + param_17.dataType = 5; + + List propertyValues = new List(); + //tag9 监测明细 + for (int i = 17; i < info.Count();) + { + if (string.IsNullOrEmpty((string)info[i].D)) + { + i = i + 6; + continue; + } + else + { + PropertyValue propertyValue = new PropertyValue(); + propertyValue.CHECK_ITEM = MidStrEx_New((string)info[i].D, "-", "-"); + propertyValue.ITEM_VALUE = info[i].E == null ? " " : string.Format("{0}",info[i].E); + propertyValue.TEST_STATUS = info[i + 1].E == null ? " " : string.Format("{0}", info[i + 1].E); + propertyValue.STANDARDVALUE = info[i + 2].E == null ? " " : string.Format("{0}", info[i + 2].E); + propertyValue.STANDARDMAX = info[i + 3].E == null ? " " : string.Format("{0}", info[i + 3].E); + propertyValue.STANDARDMIN = info[i + 4].E == null ? " " : string.Format("{0}", info[i + 4].E); + propertyValue.TEST_DETAIL_ID = System.Guid.NewGuid().ToString("N"); + + //空值处理 + propertyValue.DEVICE_NAME = ""; + propertyValue.ACCURACYVALUE = ""; + propertyValue.UOM = ""; + propertyValues.Add(propertyValue); + i = i + 6; + } + + + } + param_17.propertyValue = jsonChange.ModeToJson(propertyValues); + param_17.time = GetTimeStamp(); + deviceParam_17.data = param_17; + deviceParams.Add(deviceParam_17); + + //推送标志位 + DeviceParam deviceParam_16 = new DeviceParam(); + deviceParam_16.id = System.Guid.NewGuid().ToString("N"); + ParamData param_16 = new ParamData(); + param_16.deviceCode = "EVtest"; + param_16.propertyCode = info[16].C; + param_16.dataType = GetDataType(info[16].F == null ? "Text" : info[16].F); + param_16.propertyValue = info[16].E == null ? "":info[16].E; + param_16.time = GetTimeStamp(); + deviceParam_16.data = param_16; + deviceParams.Add(deviceParam_16); + } + + keyValues.Add(sheetName, deviceParams); + } + + return keyValues; + } + catch (Exception ex) + { + logHelper.Error("文件解析异常", ex); + return null; + } + } + + + [Obsolete] + public Dictionary> ReadExcelFile(string filePath) + { + try + { + List result = new List(); + var sheetNames = MiniExcel.GetSheetNames(filePath); + foreach (var sheetName in sheetNames) + { + DeviceParameterInfo parameterInfo = new DeviceParameterInfo(); + List info = MiniExcel.Query(filePath, sheetName: sheetName).ToList(); + var rows = MiniExcel.Query(filePath, sheetName: sheetName); + //避免读取数据为空的工作表 + if (info != null && info.Count() > paramBeginRowNumber) + { + //获取前两行参数:公司名称B、工件名称E、工件编号B、操作人员E + parameterInfo.companyName = info[0].B; + parameterInfo.partName = info[0].E; + parameterInfo.partNumber = info[1].B; + parameterInfo.operatingPersonnel = info[2].E; + List values = new List(); + + var deviceParams = info.GetRange(paramBeginRowNumber, info.Count() - paramBeginRowNumber); + if (deviceParams == null) continue; + foreach (var item in deviceParams) + { + + DeviceParametersValue parametersValue = new DeviceParametersValue(); + if (item.A as string == null) continue; + parametersValue.paramNumber = item.A as string; + parametersValue.paramContent = item.B as string; + #region 备份修改 将double转为object + /*parametersValue.observedValue = item.C == null ? 0 : item.C; + parametersValue.nominalValue = item.D == null ? 0 : item.D; + parametersValue.overproofValue = item.E == null ? 0 : item.E; + parametersValue.upperDeviation = item.F == null ? 0 : item.F; + parametersValue.lowerDeviation = item.G == null ? 0 : item.G; + parametersValue.state = item.H as string;*/ + #endregion + + parametersValue.observedValue = string.IsNullOrEmpty(item.C) ? 0 : item.C; + parametersValue.nominalValue = string.IsNullOrEmpty(item.D)? 0 : item.D; + parametersValue.overproofValue = string.IsNullOrEmpty(item.E) ? 0 : item.E; + parametersValue.upperDeviation = string.IsNullOrEmpty(item.F) ? 0 : item.F; + parametersValue.lowerDeviation = string.IsNullOrEmpty(item.G) ? 0 : item.G; + parametersValue.state = item.H as string; + + values.Add(parametersValue); + } + parameterInfo.deviceParametersValues = values; + } + else + { + continue; + } + + result.Add(parameterInfo); + } + return formatFileData(result); + } + catch(Exception ex) + { + throw new Exception(ex.Message); + } + } + + /// + /// 格式化文件数据 + /// + /// + private Dictionary> formatFileData(List parameterInfos) + { + Dictionary> keyValues = new Dictionary>(); + + if (parameterInfos.Count == 0) return null; + + foreach (var infos in parameterInfos) + { + + List deviceParams = new List(); + + //add tag1-8、tag10 + for (int i = 1; i < 9; i++) + { + DeviceParam deviceParam2 = new DeviceParam(); + deviceParam2.id = System.Guid.NewGuid().ToString("N"); + ParamData param2 = new ParamData(); + param2.deviceCode = "EVtest"; + param2.propertyCode = $"tag{i}"; + param2.dataType = 5; + param2.propertyValue = getNodeValue(param2.propertyCode); + param2.time = GetTimeStamp(); + deviceParam2.data = param2; + deviceParams.Add(deviceParam2); + } + + DeviceParam deviceParam = new DeviceParam(); + deviceParam.id = System.Guid.NewGuid().ToString("N"); + ParamData param = new ParamData(); + param.propertyCode = "tag9"; + param.dataType = 5; + var ParametersValues = infos.deviceParametersValues; + List propertyValues = new List(); + + //tag9 监测明细 + foreach (var item in ParametersValues) + { + PropertyValue propertyValue = new PropertyValue(); + propertyValue.CHECK_ITEM = string.IsNullOrEmpty(item.paramContent) ? "" : item.paramContent; + propertyValue.ITEM_VALUE = string.IsNullOrEmpty(item.nominalValue.ToString()) ? "" : item.nominalValue.ToString(); + propertyValue.ACCURACYVALUE = string.IsNullOrEmpty(item.observedValue.ToString()) ? "" : item.observedValue.ToString(); + propertyValue.TEST_STATUS = string.IsNullOrEmpty(item.state) ? "" : item.state; + propertyValue.STANDARDVALUE = string.IsNullOrEmpty(item.overproofValue.ToString()) ? "" : item.overproofValue.ToString(); + propertyValue.STANDARDMAX = string.IsNullOrEmpty(item.upperDeviation.ToString()) ? "" : item.upperDeviation.ToString(); + propertyValue.STANDARDMIN = string.IsNullOrEmpty(item.lowerDeviation.ToString()) ? "" : item.lowerDeviation.ToString(); + propertyValue.TEST_DETAIL_ID = System.Guid.NewGuid().ToString("N"); + + //空值处理 + propertyValue.DEVICE_NAME = ""; + propertyValue.UOM = ""; + propertyValues.Add(propertyValue); + + + } + param.propertyValue = jsonChange.ModeToJson(propertyValues); + //param.propertyValue = propertyValues; + param.time = GetTimeStamp(); + deviceParam.data = param; + + deviceParams.Add(deviceParam); + + + + //推送标志位 + DeviceParam deviceParam_16 = new DeviceParam(); + deviceParam_16.id = System.Guid.NewGuid().ToString("N"); + ParamData param_16 = new ParamData(); + param_16.deviceCode = "EVtest"; + param_16.propertyCode = "tag10"; + param_16.dataType = 5; + param_16.propertyValue = ""; + param_16.time = GetTimeStamp(); + deviceParam_16.data = param_16; + deviceParams.Add(deviceParam_16); + + keyValues.Add("排气阀片", deviceParams); + } + + + + return keyValues; + } + + private string getNodeValue(string nodeStr) + { + string info = ""; + switch(nodeStr) + { + case "tag1": + info = appConfig.产线; + break; + case "tag2": + info = appConfig.物料编号; + break; + case "tag3": + info = appConfig.生产条码; + break; + case "tag4": + info = appConfig.设备编码; + break; + case "tag5": + info = appConfig.测试总结果; + break; + case "tag6": + info = appConfig.当日生产总数; + break; + case "tag7": + info = appConfig.当日生产不良数; + break; + case "tag8": + info = appConfig.班次; + break; + } + return info; + } + + private string getNodeName(string nodeStr) + { + string info = ""; + switch (nodeStr) + { + case "tag1": + info = "产线"; + break; + case "tag2": + info = "物料编号"; + break; + case "tag3": + info = "生产条码"; + break; + case "tag4": + info = "设备编码"; + break; + case "tag5": + info = "测试总结果"; + break; + case "tag6": + info = "当日生产总数"; + break; + case "tag7": + info = "当日生产不良数"; + break; + case "tag8": + info = "班次"; + break; + } + return info; + } + + /// + /// 获取时间戳 + /// + /// + private string GetTimeStamp() + { + TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0); + return Convert.ToInt64(ts.TotalMilliseconds).ToString(); + } + + /// + /// 字符串截取 + /// + /// + /// + /// + /// + private string MidStrEx_New(string sourse, string startstr, string endstr) + { + Regex rg = new Regex("(?<=(" + startstr + "))[.\\s\\S]*?(?=(" + endstr + "))", RegexOptions.Multiline | RegexOptions.Singleline); + return rg.Match(sourse).Value; + } + + /// + /// 数据类型 + /// + /// + /// + private int GetDataType(string str) + { + int result = 5; + switch (str) + { + case "Int32": + result = 0; + break; + case "Float": + result = 1; + break; + case "Double": + result = 2; + break; + case "Bool": + result = 3; + break; + case "Enum": + result = 4; + break; + case "Text": + result = 5; + break; + case "Time": + result = 6; + break; + case "Array": + result = 7; + break; + case "Struct": + result = 8; + break; + default: + result = 5; + break; + } + + return result; + } + } +} diff --git a/FileDataUpload.FileOperate/MonitorEngine.cs b/FileDataUpload.FileOperate/MonitorEngine.cs new file mode 100644 index 0000000..8ccf5ca --- /dev/null +++ b/FileDataUpload.FileOperate/MonitorEngine.cs @@ -0,0 +1,104 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace FileDataUpload.FileOperate +{ + public sealed class MonitorEngine + { + public string Path; + public string Filter; + public delegate void FindOneFile(string path); + public event FindOneFile FindOneFileEvent; + private FileSystemWatcher watcher = new FileSystemWatcher(); + + private static readonly Lazy lazy = new Lazy(() => new MonitorEngine()); + + public static MonitorEngine Instance + { + get + { + return lazy.Value; + } + } + + public MonitorEngine() + { + + watcher.Changed += new FileSystemEventHandler(OnProcess); + watcher.Created += new FileSystemEventHandler(OnProcess); + watcher.Deleted += new FileSystemEventHandler(OnProcess); + watcher.Renamed += new RenamedEventHandler(OnRenamed); + + watcher.NotifyFilter = NotifyFilters.Attributes | NotifyFilters.CreationTime | NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.LastAccess + | NotifyFilters.LastWrite | NotifyFilters.Security | NotifyFilters.Size; + + } + + /// + /// 监控文件夹 + /// + /// + /// + public void WatcherStrat() + { + if (!Directory.Exists(Path)) + { + Directory.CreateDirectory(Path); + } + watcher.Path = Path; + watcher.Filter = Filter; + watcher.EnableRaisingEvents = true; + watcher.IncludeSubdirectories = true; + } + + public void WatcherStop() + { + watcher.EnableRaisingEvents = false; + watcher.IncludeSubdirectories = false; + } + + private void OnProcess(object source, FileSystemEventArgs e) + { + if (e.ChangeType == WatcherChangeTypes.Created) + { + OnCreated(source, e); + } + else if (e.ChangeType == WatcherChangeTypes.Changed) + { + OnChanged(source, e); + } + else if (e.ChangeType == WatcherChangeTypes.Deleted) + { + OnDeleted(source, e); + } + + } + private void OnCreated(object source, FileSystemEventArgs e) + { + string TempFilePath = e.FullPath; + if (FindOneFileEvent != null) + { + FindOneFileEvent(TempFilePath); + } + + + //Console.WriteLine("文件新建事件处理逻辑 {0}  {1}  {2}", e.ChangeType, e.FullPath, e.Name); + } + private void OnChanged(object source, FileSystemEventArgs e) + { + Console.WriteLine("文件改变事件处理逻辑{0}  {1}  {2}", e.ChangeType, e.FullPath, e.Name); + } + private void OnDeleted(object source, FileSystemEventArgs e) + { + Console.WriteLine("文件删除事件处理逻辑{0}  {1}   {2}", e.ChangeType, e.FullPath, e.Name); + } + private void OnRenamed(object source, RenamedEventArgs e) + { + Console.WriteLine("文件重命名事件处理逻辑{0}  {1}  {2}", e.ChangeType, e.FullPath, e.Name); + } + } +} diff --git a/FileDataUpload.FileOperate/Properties/AssemblyInfo.cs b/FileDataUpload.FileOperate/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..99f2ec4 --- /dev/null +++ b/FileDataUpload.FileOperate/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 有关程序集的一般信息由以下 +// 控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("FileDataUpload.FileOperate")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("FileDataUpload.FileOperate")] +[assembly: AssemblyCopyright("Copyright © 2023")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 将 ComVisible 设置为 false 会使此程序集中的类型 +//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 +//请将此类型的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID +[assembly: Guid("000f3ed7-6a2f-44c6-a31a-da0fd0c66061")] + +// 程序集的版本信息由下列四个值组成: +// +// 主版本 +// 次版本 +// 生成号 +// 修订号 +// +//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值 +//通过使用 "*",如下所示: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/FileDataUpload.FileOperate/packages.config b/FileDataUpload.FileOperate/packages.config new file mode 100644 index 0000000..7cf35d5 --- /dev/null +++ b/FileDataUpload.FileOperate/packages.config @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/FileDataUpload.Mqtt/FileDataUpload.Mqtt.csproj b/FileDataUpload.Mqtt/FileDataUpload.Mqtt.csproj new file mode 100644 index 0000000..61e7f91 --- /dev/null +++ b/FileDataUpload.Mqtt/FileDataUpload.Mqtt.csproj @@ -0,0 +1,54 @@ + + + + + Debug + AnyCPU + {863E1DDA-4A95-41FB-AFE6-292E9E0E2732} + Library + Properties + FileDataUpload.Mqtt + FileDataUpload.Mqtt + v4.5.2 + 512 + true + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + ..\packages\MQTTnet.4.1.0.247\lib\net452\MQTTnet.dll + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/FileDataUpload.Mqtt/MqttClient.cs b/FileDataUpload.Mqtt/MqttClient.cs new file mode 100644 index 0000000..4862db6 --- /dev/null +++ b/FileDataUpload.Mqtt/MqttClient.cs @@ -0,0 +1,127 @@ +using MQTTnet.Client; +using MQTTnet; +using MQTTnet.Protocol; +using System; +using System.Text; +using System.Threading.Tasks; +using System.Threading; +using System.Security.Authentication; + +namespace FileDataUpload.Mqtt +{ + public sealed class MqttClient + { + + public delegate void PrintMessageReceived(string message); + public event PrintMessageReceived PrintMessageReceivedEvent; + + private IMqttClient client; + + private static readonly Lazy lazy = new Lazy(() => new MqttClient()); + + public static MqttClient Instance + { + get + { + return lazy.Value; + } + } + + private MqttClient() { } + + public async void Connect(string ip,int port,string clientId,string username,string password) + { + try + { + MqttClientOptions options = new MqttClientOptionsBuilder() + .WithTcpServer(ip, port) + .WithClientId(clientId) + .WithCredentials(username, password) + .WithTls(o => + { + o.CertificateValidationHandler = _ => true; + + o.SslProtocol = SslProtocols.Tls12; + }).Build(); + client = new MqttFactory().CreateMqttClient(); + + client.ApplicationMessageReceivedAsync += MqttClient_ApplicationMessageReceived; + + MqttClientConnectResult result = await client.ConnectAsync(options); + + if (result != null) + { + if (result.ResultCode == MQTTnet.Client.MqttClientConnectResultCode.Success) + { + PrintMessageReceivedEvent?.Invoke($"连接服务器成功{ip}:{port}"); + } + else + { + PrintMessageReceivedEvent?.Invoke($"连接服务器失败"); + } + } + }catch(Exception ex) + { + PrintMessageReceivedEvent?.Invoke($"连接服务器异常:{ex.Message}"); + } + } + + public void DisConnect() + { + client.DisconnectAsync(); + PrintMessageReceivedEvent?.Invoke($"断开连接"); + } + + public async void SubscriptionAsync(string topic) + { + try + { + var mqttFactory = new MqttFactory(); + var mqttSubscribeOptions = mqttFactory.CreateSubscribeOptionsBuilder() + .WithTopicFilter( + f => + { + f.WithTopic(topic); + }) + .Build(); + + MqttClientSubscribeResult result = await client.SubscribeAsync(mqttSubscribeOptions, CancellationToken.None); + + PrintMessageReceivedEvent?.Invoke($"订阅主题:{topic}"); + } + catch(Exception ex) + { + PrintMessageReceivedEvent?.Invoke($"订阅主题异常:{ex.Message}"); + } + } + + public void Unsubscribe(string topic) + { + client.UnsubscribeAsync(topic); + PrintMessageReceivedEvent?.Invoke($"取消订阅,主题:{topic}"); + } + + public void Publish(string topic,string message) + { + try + { + var msg = new MqttApplicationMessageBuilder().WithTopic(topic).WithPayload(message) + .Build(); + client.PublishAsync(msg, CancellationToken.None); + PrintMessageReceivedEvent?.Invoke($"向服务端推送成功,主题:{topic};内容:{message}"); + } + catch(Exception ex) + { + PrintMessageReceivedEvent?.Invoke($"向服务端推送消息异常:{ex.Message}"); + } + } + + private async Task MqttClient_ApplicationMessageReceived(MqttApplicationMessageReceivedEventArgs eventArgs) + { + var info = $"接收到主题:{eventArgs.ApplicationMessage.Topic}的消息,内容:{Encoding.UTF8.GetString(eventArgs.ApplicationMessage.Payload)}"; + PrintMessageReceivedEvent?.Invoke(info); + } + + + } +} diff --git a/FileDataUpload.Mqtt/Properties/AssemblyInfo.cs b/FileDataUpload.Mqtt/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..98be9c1 --- /dev/null +++ b/FileDataUpload.Mqtt/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 有关程序集的一般信息由以下 +// 控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("FileDataUpload.Mqtt")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("FileDataUpload.Mqtt")] +[assembly: AssemblyCopyright("Copyright © 2023")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 将 ComVisible 设置为 false 会使此程序集中的类型 +//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 +//请将此类型的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID +[assembly: Guid("863e1dda-4a95-41fb-afe6-292e9e0e2732")] + +// 程序集的版本信息由下列四个值组成: +// +// 主版本 +// 次版本 +// 生成号 +// 修订号 +// +//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值 +//通过使用 "*",如下所示: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/FileDataUpload.Mqtt/packages.config b/FileDataUpload.Mqtt/packages.config new file mode 100644 index 0000000..1573f93 --- /dev/null +++ b/FileDataUpload.Mqtt/packages.config @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/FileDataUpload.sln b/FileDataUpload.sln new file mode 100644 index 0000000..9f6d0d0 --- /dev/null +++ b/FileDataUpload.sln @@ -0,0 +1,49 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.5.33502.453 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FileDataUpload", "FileDataUpload\FileDataUpload.csproj", "{8B936A6B-A96B-4D41-9BA6-BBC9D975ADE7}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FileDataUpload.FileOperate", "FileDataUpload.FileOperate\FileDataUpload.FileOperate.csproj", "{000F3ED7-6A2F-44C6-A31A-DA0FD0C66061}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FileDataUpload.Entity", "FileDataUpload.Entity\FileDataUpload.Entity.csproj", "{E7158B5C-2C09-432E-83AC-7D2C065E664F}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FileDataUpload.Common", "FileDataUpload.Common\FileDataUpload.Common.csproj", "{8E2E1A40-99D9-4488-A4D1-6708B845E555}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FileDataUpload.Mqtt", "FileDataUpload.Mqtt\FileDataUpload.Mqtt.csproj", "{863E1DDA-4A95-41FB-AFE6-292E9E0E2732}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {8B936A6B-A96B-4D41-9BA6-BBC9D975ADE7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8B936A6B-A96B-4D41-9BA6-BBC9D975ADE7}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8B936A6B-A96B-4D41-9BA6-BBC9D975ADE7}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8B936A6B-A96B-4D41-9BA6-BBC9D975ADE7}.Release|Any CPU.Build.0 = Release|Any CPU + {000F3ED7-6A2F-44C6-A31A-DA0FD0C66061}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {000F3ED7-6A2F-44C6-A31A-DA0FD0C66061}.Debug|Any CPU.Build.0 = Debug|Any CPU + {000F3ED7-6A2F-44C6-A31A-DA0FD0C66061}.Release|Any CPU.ActiveCfg = Release|Any CPU + {000F3ED7-6A2F-44C6-A31A-DA0FD0C66061}.Release|Any CPU.Build.0 = Release|Any CPU + {E7158B5C-2C09-432E-83AC-7D2C065E664F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E7158B5C-2C09-432E-83AC-7D2C065E664F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E7158B5C-2C09-432E-83AC-7D2C065E664F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E7158B5C-2C09-432E-83AC-7D2C065E664F}.Release|Any CPU.Build.0 = Release|Any CPU + {8E2E1A40-99D9-4488-A4D1-6708B845E555}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8E2E1A40-99D9-4488-A4D1-6708B845E555}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8E2E1A40-99D9-4488-A4D1-6708B845E555}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8E2E1A40-99D9-4488-A4D1-6708B845E555}.Release|Any CPU.Build.0 = Release|Any CPU + {863E1DDA-4A95-41FB-AFE6-292E9E0E2732}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {863E1DDA-4A95-41FB-AFE6-292E9E0E2732}.Debug|Any CPU.Build.0 = Debug|Any CPU + {863E1DDA-4A95-41FB-AFE6-292E9E0E2732}.Release|Any CPU.ActiveCfg = Release|Any CPU + {863E1DDA-4A95-41FB-AFE6-292E9E0E2732}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {F808DDC2-2CBD-4309-9F8A-CACAF7420F6A} + EndGlobalSection +EndGlobal diff --git a/FileDataUpload/App.config b/FileDataUpload/App.config new file mode 100644 index 0000000..88fa402 --- /dev/null +++ b/FileDataUpload/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/FileDataUpload/App.xaml b/FileDataUpload/App.xaml new file mode 100644 index 0000000..404888d --- /dev/null +++ b/FileDataUpload/App.xaml @@ -0,0 +1,15 @@ + + + + + + + + + + + diff --git a/FileDataUpload/App.xaml.cs b/FileDataUpload/App.xaml.cs new file mode 100644 index 0000000..d643747 --- /dev/null +++ b/FileDataUpload/App.xaml.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Configuration; +using System.Data; +using System.Linq; +using System.Threading.Tasks; +using System.Windows; + +namespace FileDataUpload +{ + /// + /// App.xaml 的交互逻辑 + /// + public partial class App : Application + { + } +} diff --git a/FileDataUpload/FileDataUpload.csproj b/FileDataUpload/FileDataUpload.csproj new file mode 100644 index 0000000..6167e75 --- /dev/null +++ b/FileDataUpload/FileDataUpload.csproj @@ -0,0 +1,164 @@ + + + + + Debug + AnyCPU + {8B936A6B-A96B-4D41-9BA6-BBC9D975ADE7} + WinExe + FileDataUpload + FileDataUpload + v4.5.2 + 512 + {60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + 4 + true + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + ..\packages\CommonServiceLocator.2.0.2\lib\net45\CommonServiceLocator.dll + + + ..\packages\MvvmLightLibs.5.4.1.1\lib\net45\GalaSoft.MvvmLight.dll + + + ..\packages\MvvmLightLibs.5.4.1.1\lib\net45\GalaSoft.MvvmLight.Extras.dll + + + ..\packages\MvvmLightLibs.5.4.1.1\lib\net45\GalaSoft.MvvmLight.Platform.dll + + + ..\packages\log4net.2.0.15\lib\net45\log4net.dll + + + ..\packages\MQTTnet.4.1.0.247\lib\net452\MQTTnet.dll + + + + + + + + + ..\packages\MvvmLightLibs.5.4.1.1\lib\net45\System.Windows.Interactivity.dll + + + + + + + + + 4.0 + + + + + + + + MSBuild:Compile + Designer + + + SysConfigWindw.xaml + + + + + MSBuild:Compile + Designer + + + App.xaml + Code + + + MainWindow.xaml + Code + + + Designer + MSBuild:Compile + + + MSBuild:Compile + Designer + + + + + Code + + + True + True + Resources.resx + + + True + Settings.settings + True + + + ResXFileCodeGenerator + Resources.Designer.cs + + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + + + + + + + + + + + + {8e2e1a40-99d9-4488-a4d1-6708b845e555} + FileDataUpload.Common + + + {E7158B5C-2C09-432E-83AC-7D2C065E664F} + FileDataUpload.Entity + + + {000F3ED7-6A2F-44C6-A31A-DA0FD0C66061} + FileDataUpload.FileOperate + + + {863e1dda-4a95-41fb-afe6-292e9e0e2732} + FileDataUpload.Mqtt + + + + \ No newline at end of file diff --git a/FileDataUpload/MainWindow.xaml b/FileDataUpload/MainWindow.xaml new file mode 100644 index 0000000..27ab0fd --- /dev/null +++ b/FileDataUpload/MainWindow.xaml @@ -0,0 +1,103 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +