From bbc5b759bc11b28f487f3c767bb4bc6aef4710c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A6=82=E6=84=8F=20=E5=BD=AD?= <2417589739@qq.com> Date: Thu, 19 May 2022 13:56:02 +0800 Subject: [PATCH 01/11] =?UTF-8?q?=E9=85=8D=E7=BD=AE=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../{MorksMachine.cs => PLCMachine.cs} | 4 +- BPASmartClient/App.config | 5 ++- BPASmartClient/DeviceInfo.xml | 43 +++++++++++++------ 3 files changed, 34 insertions(+), 18 deletions(-) rename BPASmartClient.MORKSM.BK.PLC/{MorksMachine.cs => PLCMachine.cs} (98%) diff --git a/BPASmartClient.MORKSM.BK.PLC/MorksMachine.cs b/BPASmartClient.MORKSM.BK.PLC/PLCMachine.cs similarity index 98% rename from BPASmartClient.MORKSM.BK.PLC/MorksMachine.cs rename to BPASmartClient.MORKSM.BK.PLC/PLCMachine.cs index 809c80b8..d2a997b9 100644 --- a/BPASmartClient.MORKSM.BK.PLC/MorksMachine.cs +++ b/BPASmartClient.MORKSM.BK.PLC/PLCMachine.cs @@ -9,7 +9,7 @@ using BPASmartClient.Model.PLC; namespace BPASmartClient.PLC { - public class MorksMachine : BasePeripheral + public class PLCMachine : BasePeripheral { ModbusTcp modbusTcp = new ModbusTcp(); public string IpAddress { get; set; } @@ -46,7 +46,7 @@ namespace BPASmartClient.PLC } status[par.Address] = readData; } - + Thread.Sleep(500); } Thread.Sleep(1000); diff --git a/BPASmartClient/App.config b/BPASmartClient/App.config index 08824b61..3bf86a0a 100644 --- a/BPASmartClient/App.config +++ b/BPASmartClient/App.config @@ -3,7 +3,7 @@ - + @@ -36,7 +36,8 @@ --> - + - - - - - 192.168.6.1 - 502 - M,M0.1,1;M,M1.0,8;M,M2.0,9;M,M8.0,4;M,M13.5,1;M,M16.0,7; - - - - + + + + + COM5 + 9600 + + + + + + + + From ee8fdc7fd1a1ba2582c3961b8dd6ca707f5d7b49 Mon Sep 17 00:00:00 2001 From: NXX <447201003@qq> Date: Thu, 19 May 2022 13:59:28 +0800 Subject: [PATCH 02/11] =?UTF-8?q?AdminstratorsView=20=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- BPASmartClient/Control/AdminstratorsView.xaml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/BPASmartClient/Control/AdminstratorsView.xaml b/BPASmartClient/Control/AdminstratorsView.xaml index 81251a0d..7170d552 100644 --- a/BPASmartClient/Control/AdminstratorsView.xaml +++ b/BPASmartClient/Control/AdminstratorsView.xaml @@ -41,11 +41,11 @@ VerticalAlignment="Top" HorizontalAlignment="Right" Margin="20" Style="{StaticResource TxLogin}"/> - - Date: Thu, 19 May 2022 14:53:40 +0800 Subject: [PATCH 03/11] =?UTF-8?q?2=E9=A2=9D=E5=A8=81=E5=A8=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- BPASmartClient.IoT/DataVClient.cs | 6 - BPASmartClient.IoT/Model/DataVReport.cs | 4 + BPASmartClient.IoT/Model/IOT/IOTDevModel.cs | 202 ++++++++++---------- 3 files changed, 105 insertions(+), 107 deletions(-) diff --git a/BPASmartClient.IoT/DataVClient.cs b/BPASmartClient.IoT/DataVClient.cs index c690e40f..d08a6a24 100644 --- a/BPASmartClient.IoT/DataVClient.cs +++ b/BPASmartClient.IoT/DataVClient.cs @@ -65,12 +65,6 @@ namespace BPASmartClient.IoT /// 大屏上报Model /// public DataVAPI.Tool.IOT.IOTDevSXModel iOTDevSXModel = new DataVAPI.Tool.IOT.IOTDevSXModel() { }; - /// - /// 广播 - /// - //public string PubTopic = "/broadcast/" + "grgpECHSL7q" + "/" + "Transit_SetDevice"; - //public string PubTopic = "/broadcast/" + "grgpECHSL7q" + "/" + "Transit_Test_SetDevice"; - /// /// key值 /// diff --git a/BPASmartClient.IoT/Model/DataVReport.cs b/BPASmartClient.IoT/Model/DataVReport.cs index 02d6fcf6..83d93806 100644 --- a/BPASmartClient.IoT/Model/DataVReport.cs +++ b/BPASmartClient.IoT/Model/DataVReport.cs @@ -369,6 +369,10 @@ namespace BPASmartDatavDeviceClient.IoT /// public string BroadcastTopic = "/broadcast/" + "grgpECHSL7q" + "/" + DeviceName + "_SetDevice"; /// + /// 文件上床Topic + /// + public string FileUpLoadTopic = $"/sys/{ProductKey}/{DeviceName}/thing/file/upload/mqtt/init"; + /// /// 订阅主题集合 /// public static List SubTopicList = new List(); diff --git a/BPASmartClient.IoT/Model/IOT/IOTDevModel.cs b/BPASmartClient.IoT/Model/IOT/IOTDevModel.cs index 488125f1..7b52318a 100644 --- a/BPASmartClient.IoT/Model/IOT/IOTDevModel.cs +++ b/BPASmartClient.IoT/Model/IOT/IOTDevModel.cs @@ -66,30 +66,30 @@ namespace DataVAPI.Tool.IOT /// public class IOTDevSXModel { - /// - /// 硬件状态 - /// - public string HardwareStatus { get; set; } - /// - /// 扩展属性 - /// - public string KZSX { get; set; } - /// - /// 基本属性 - /// - public string JBSX { get; set; } + ///// + ///// 硬件状态 + ///// + //public string HardwareStatus { get; set; } + ///// + ///// 扩展属性 + ///// + //public string KZSX { get; set; } + ///// + ///// 基本属性 + ///// + //public string JBSX { get; set; } /// /// 节点状态 /// public string NodeStatus { get; set; } - /// - /// 运行日志 - /// - public string SZXX { get; set; } - /// - /// 运行告警 - /// - public string GJXX { get; set; } + ///// + ///// 运行日志 + ///// + //public string SZXX { get; set; } + ///// + ///// 运行告警 + ///// + //public string GJXX { get; set; } /// /// Model /// @@ -114,87 +114,87 @@ namespace DataVAPI.Tool.IOT return string.Empty; } } - /// - /// 设置基本属性 - /// - /// - /// - public void SetJBSX(DevSX devSX) - { - try - { - JBSX = Tools.JsonConvertTools(devSX); - } - catch (Exception ex) - { - JBSX = string.Empty; - } - } - /// - /// 设置基本属性状态 - /// - /// - /// - public void SetJBSXStatus(DevSXBase sXBase, bool Status) - { - try - { - if (sXBase == null) return; - DevSX dev = Tools.JsonToObjectTools(JBSX); - dev.data?.ForEach(x => - { - if (x.SXMC == sXBase.SXMC && x.SXLX == sXBase.SXLX) - { - x.SXStatus = Status; - } - }); - JBSX = Tools.JsonConvertTools(dev); - } - catch (Exception ex) - { - JBSX = string.Empty; - } - } - /// - /// 设置扩展属性 - /// - /// - public void SetKZSX(DevSX devSX) - { - try - { - KZSX = Tools.JsonConvertTools(devSX); - } - catch (Exception ex) - { - KZSX = string.Empty; - } - } - /// - /// 设置扩展属性状态 - /// - /// - /// - public void SetKZSXStatus(DevSXBase sXBase, bool Status) - { - try - { - if (sXBase == null) return; - DevSX dev = Tools.JsonToObjectTools(KZSX); - dev.data?.ForEach(x => - { - if (x.SXMC == sXBase.SXMC && x.SXLX == sXBase.SXLX) - { - x.SXStatus = Status; - } - }); - KZSX = Tools.JsonConvertTools(dev); - } - catch (Exception ex) - { - KZSX = string.Empty; - } - } + ///// + ///// 设置基本属性 + ///// + ///// + ///// + //public void SetJBSX(DevSX devSX) + //{ + // try + // { + // JBSX = Tools.JsonConvertTools(devSX); + // } + // catch (Exception ex) + // { + // JBSX = string.Empty; + // } + //} + ///// + ///// 设置基本属性状态 + ///// + ///// + ///// + //public void SetJBSXStatus(DevSXBase sXBase, bool Status) + //{ + // try + // { + // if (sXBase == null) return; + // DevSX dev = Tools.JsonToObjectTools(JBSX); + // dev.data?.ForEach(x => + // { + // if (x.SXMC == sXBase.SXMC && x.SXLX == sXBase.SXLX) + // { + // x.SXStatus = Status; + // } + // }); + // JBSX = Tools.JsonConvertTools(dev); + // } + // catch (Exception ex) + // { + // JBSX = string.Empty; + // } + //} + ///// + ///// 设置扩展属性 + ///// + ///// + //public void SetKZSX(DevSX devSX) + //{ + // try + // { + // KZSX = Tools.JsonConvertTools(devSX); + // } + // catch (Exception ex) + // { + // KZSX = string.Empty; + // } + //} + ///// + ///// 设置扩展属性状态 + ///// + ///// + ///// + //public void SetKZSXStatus(DevSXBase sXBase, bool Status) + //{ + // try + // { + // if (sXBase == null) return; + // DevSX dev = Tools.JsonToObjectTools(KZSX); + // dev.data?.ForEach(x => + // { + // if (x.SXMC == sXBase.SXMC && x.SXLX == sXBase.SXLX) + // { + // x.SXStatus = Status; + // } + // }); + // KZSX = Tools.JsonConvertTools(dev); + // } + // catch (Exception ex) + // { + // KZSX = string.Empty; + // } + //} } /// /// 告警消息 From 445f77936bb458e2df5f8fe9d620a652dbc1d90a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A6=82=E6=84=8F=20=E5=BD=AD?= <2417589739@qq.com> Date: Thu, 19 May 2022 21:41:24 +0800 Subject: [PATCH 04/11] =?UTF-8?q?=E6=A1=86=E6=9E=B6=E5=AE=8C=E5=96=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- BPASmartClient.Business/Plugin/ConfigMgr.cs | 37 ++ BPASmartClient.Business/Plugin/DeviceMgr.cs | 4 - .../RecDictionarys/DatePickeerDictionary.xaml | 599 ++++++++++++++++++ .../Themes/MyStyle.xaml | 11 +- .../UserControls/UserKeyBoard.xaml | 432 ++++++++++--- BPASmartClient.Device/BaseDevice.cs | 14 +- .../BPASmartClient.Helper.csproj | 3 +- BPASmartClient.Helper/Sqlite.cs | 49 ++ BPASmartClient.Model/Alarm.cs | 58 ++ BPASmartClient.Model/DeviceConfigModelJson.cs | 182 ++++++ BPASmartClient.Model/KeepDataBase.cs | 1 - BPASmartClient.MorkS/Alarm.cs | 36 +- BPASmartClient.MorkS/Control_Morks.cs | 98 ++- BPASmartClient.MorkS/GVL_MORKS.cs | 3 + BPASmartClient.MorkS/OrderLocInfo.cs | 1 + BPASmartClient.ViewModel/AlarmViewModel.cs | 199 ++++++ .../Model/DeviceConfigModel.cs | 372 ++++++----- .../ShopDeviceConfigViewModel.cs | 45 +- .../SystemSetViewModel.cs | 46 ++ BPASmartClient/App.config | 9 +- BPASmartClient/App.xaml | 1 + BPASmartClient/BPASmartClient.csproj | 1 + BPASmartClient/Control/AdminstratorsView.xaml | 178 +++--- BPASmartClient/Control/AlarmView.xaml | 376 +++++++++++ BPASmartClient/Control/AlarmView.xaml.cs | 28 + BPASmartClient/Control/OrderStatusView.xaml | 14 +- .../Control/ShopDeviceConfigView.xaml | 2 +- .../Control/ShopDeviceConfigView.xaml.cs | 4 +- BPASmartClient/Control/SystemSetView.xaml | 152 ++++- BPASmartClient/DeviceInfo.xml | 20 +- BPASmartClient/MainWindow.xaml | 10 +- BPASmartClient/MainWindow.xaml.cs | 66 +- 32 files changed, 2574 insertions(+), 477 deletions(-) create mode 100644 BPASmartClient.CustomResource/RecDictionarys/DatePickeerDictionary.xaml create mode 100644 BPASmartClient.Helper/Sqlite.cs create mode 100644 BPASmartClient.Model/Alarm.cs create mode 100644 BPASmartClient.Model/DeviceConfigModelJson.cs create mode 100644 BPASmartClient.ViewModel/AlarmViewModel.cs create mode 100644 BPASmartClient.ViewModel/SystemSetViewModel.cs create mode 100644 BPASmartClient/Control/AlarmView.xaml create mode 100644 BPASmartClient/Control/AlarmView.xaml.cs diff --git a/BPASmartClient.Business/Plugin/ConfigMgr.cs b/BPASmartClient.Business/Plugin/ConfigMgr.cs index 83be6035..c0d68ab5 100644 --- a/BPASmartClient.Business/Plugin/ConfigMgr.cs +++ b/BPASmartClient.Business/Plugin/ConfigMgr.cs @@ -1,8 +1,11 @@ using BPA.ApolloClient; using BPA.Message; +using BPASmartClient.Helper; using BPASmartClient.Message; using BPASmartClient.Model; using Microsoft.Extensions.Configuration; +using Newtonsoft.Json; +using System.Collections.ObjectModel; using System.Xml.Linq; using System.Xml.XPath; @@ -58,6 +61,40 @@ namespace BPASmartClient.Business /// private void InitDeviceModel() { + //var text = TextHelper.GetInstance.ReadTextInfo("StartShop", "DeviceConfig"); + //string path = $"{LocaPath.GetInstance().GetDeviceConfigPath}{text}.json"; + //deviceConfigs = new List(); + //if (File.Exists(path)) + //{ + // string JsonString = File.ReadAllText(path); + // var result = JsonConvert.DeserializeObject>(JsonString); + // if (result != null) + // { + // foreach (var shop in result) + // { + // foreach (var device in shop.deviceModels) + // { + + // DeviceConfig deviceConfig = new DeviceConfig(); + // deviceConfig.Name = device.DeviceName; + // deviceConfig.Module = device.DeviceNamespace; + // deviceConfig.DeviceId = int.Parse(device.DeviceId); + + // foreach (var comms in device.communicationDevcies) + // { + // BPASmartClient.Model.Peripheral peripheral = new BPASmartClient.Model.Peripheral(); + // peripheral.Module = comms.CommunicationNamespace; + // } + // deviceConfigs.Add(deviceConfig); + // } + // } + // } + //} + + + + + deviceConfigs = new List(); var devicePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DeviceInfo.xml"); var xdoc = XDocument.Load(devicePath); diff --git a/BPASmartClient.Business/Plugin/DeviceMgr.cs b/BPASmartClient.Business/Plugin/DeviceMgr.cs index ec21017d..3cd27e88 100644 --- a/BPASmartClient.Business/Plugin/DeviceMgr.cs +++ b/BPASmartClient.Business/Plugin/DeviceMgr.cs @@ -74,8 +74,6 @@ namespace BPASmartClient.Business } } - - public void StartService() { this.devices.ForEach(device => @@ -129,8 +127,6 @@ namespace BPASmartClient.Business }); } - - public void StopService() { this.devices.ForEach(device => device.Stop()); diff --git a/BPASmartClient.CustomResource/RecDictionarys/DatePickeerDictionary.xaml b/BPASmartClient.CustomResource/RecDictionarys/DatePickeerDictionary.xaml new file mode 100644 index 00000000..355b5f66 --- /dev/null +++ b/BPASmartClient.CustomResource/RecDictionarys/DatePickeerDictionary.xaml @@ -0,0 +1,599 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 14 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + #FFE8EDF9 + #FFC5CBF9 + #FF7381F9 + + #FFE8EDF9 + #FFC5CBF9 + #FF888888 + + #FFC5CBF9 + #FFDDDDDD + + White + #FF7381F9 + #FF211AA9 + + #FF3843C4 + #FF211AA9 + + + #FF444444 + sc#1, 0.004391443, 0.002428215, 0.242281124 + + + + #FFCCCCCC + #FF888888 + #FF444444 + + #FF888888 + #FF444444 + + #FFAAAAAA + #FF888888 + + Black + + + + #FFC5CBF9 + Black + #FFC5CBF9 + + #FF3843C4 + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/BPASmartClient.CustomResource/Themes/MyStyle.xaml b/BPASmartClient.CustomResource/Themes/MyStyle.xaml index 51c8b9ec..a6ed93e7 100644 --- a/BPASmartClient.CustomResource/Themes/MyStyle.xaml +++ b/BPASmartClient.CustomResource/Themes/MyStyle.xaml @@ -957,7 +957,7 @@ - + - + - + - - + - + - + - - - + + + - + - - - - + + + + - - - - - - - - - - + + + + + + + + + + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/BPASmartClient/Control/AlarmView.xaml.cs b/BPASmartClient/Control/AlarmView.xaml.cs new file mode 100644 index 00000000..c812b5c3 --- /dev/null +++ b/BPASmartClient/Control/AlarmView.xaml.cs @@ -0,0 +1,28 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Documents; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Navigation; +using System.Windows.Shapes; + +namespace BPASmartClient.Control +{ + /// + /// AlarmView.xaml 的交互逻辑 + /// + public partial class AlarmView : UserControl + { + public AlarmView() + { + InitializeComponent(); + } + } +} diff --git a/BPASmartClient/Control/OrderStatusView.xaml b/BPASmartClient/Control/OrderStatusView.xaml index 1c6aee37..56e250c4 100644 --- a/BPASmartClient/Control/OrderStatusView.xaml +++ b/BPASmartClient/Control/OrderStatusView.xaml @@ -36,7 +36,7 @@ - + @@ -118,8 +118,8 @@ + HorizontalScrollBarVisibility="Hidden" + VerticalScrollBarVisibility="Hidden"> @@ -206,7 +206,7 @@ - + - + diff --git a/BPASmartClient/Control/ShopDeviceConfigView.xaml b/BPASmartClient/Control/ShopDeviceConfigView.xaml index b114f896..f78305c1 100644 --- a/BPASmartClient/Control/ShopDeviceConfigView.xaml +++ b/BPASmartClient/Control/ShopDeviceConfigView.xaml @@ -7,7 +7,7 @@ xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:pry="clr-namespace:BPASmartClient.CustomResource.UserControls;assembly=BPASmartClient.CustomResource" xmlns:vm="clr-namespace:BPASmartClient.ViewModel;assembly=BPASmartClient.ViewModel" - xmlns:vmm="clr-namespace:BPASmartClient.ViewModel.Model;assembly=BPASmartClient.ViewModel" + xmlns:vmm="clr-namespace:BPASmartClient.Model;assembly=BPASmartClient.Model" d:DesignHeight="900" d:DesignWidth="1200" mc:Ignorable="d"> diff --git a/BPASmartClient/Control/ShopDeviceConfigView.xaml.cs b/BPASmartClient/Control/ShopDeviceConfigView.xaml.cs index a608cd93..cebbda96 100644 --- a/BPASmartClient/Control/ShopDeviceConfigView.xaml.cs +++ b/BPASmartClient/Control/ShopDeviceConfigView.xaml.cs @@ -16,8 +16,8 @@ using System.Windows.Navigation; using System.Windows.Shapes; using BPASmartClient.DialogWindow; using BPASmartClient.Helper; +using BPASmartClient.Model; using BPASmartClient.ViewModel; -using BPASmartClient.ViewModel.Model; using Newtonsoft.Json; namespace BPASmartClient.Control @@ -140,7 +140,7 @@ namespace BPASmartClient.Control if (file != null && File.Exists(file.FullName)) { string JsonString = File.ReadAllText(file.FullName); - var result = JsonConvert.DeserializeObject>(JsonString); + var result = JsonConvert.DeserializeObject>(JsonString); if (result != null) { ShopDeviceConfigViewModel.deviceConfig.Clear(); diff --git a/BPASmartClient/Control/SystemSetView.xaml b/BPASmartClient/Control/SystemSetView.xaml index 6cf92742..7d977a72 100644 --- a/BPASmartClient/Control/SystemSetView.xaml +++ b/BPASmartClient/Control/SystemSetView.xaml @@ -1,12 +1,144 @@ - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/BPASmartClient/DeviceInfo.xml b/BPASmartClient/DeviceInfo.xml index f442fe8d..5da0b472 100644 --- a/BPASmartClient/DeviceInfo.xml +++ b/BPASmartClient/DeviceInfo.xml @@ -26,19 +26,21 @@ --> - + + + - + - 192.168.1.11 - 508 - M,M550.0,16;M,M0.3,3;M,M100.0,16;M,M235.0,1;M,M102.0,7;M,M103.0,6;VW,VW372,1 + 127.0.0.1 + 502 + M,M230.0,24;M,M0.3,3;M,M100.0,16;M,M235.0,1;M,M102.0,7;M,M103.0,6;VW,VW372,1 - --> + diff --git a/BPASmartClient/MainWindow.xaml b/BPASmartClient/MainWindow.xaml index 9776b21e..dc58adf0 100644 --- a/BPASmartClient/MainWindow.xaml +++ b/BPASmartClient/MainWindow.xaml @@ -50,7 +50,7 @@ Margin="20,0,0,0" VerticalAlignment="Center" Style="{DynamicResource imagetop_Title}" /> - + + Cursor="Hand" /> diff --git a/BPASmartClient/MainWindow.xaml.cs b/BPASmartClient/MainWindow.xaml.cs index 9bf20010..cfb9fd7a 100644 --- a/BPASmartClient/MainWindow.xaml.cs +++ b/BPASmartClient/MainWindow.xaml.cs @@ -11,9 +11,11 @@ using BPASmartClient.Message; using BPASmartClient.Model; using BPASmartClient.Model.冰淇淋.Enum; using BPASmartClient.Model.咖啡机.Enum; +using BPASmartClient.Peripheral; using BPASmartClient.ViewModel; using System; using System.Collections.Generic; +using System.IO; using System.Linq; using System.Reflection; using System.Text; @@ -66,6 +68,7 @@ namespace BPASmartClient ThreadManage.GetInstance().Start(new Action(() => { new MainConsole().Start(); + GetDevices(); }), "启动主控制台", false); ThreadManage.GetInstance().Start(new Action(() => @@ -86,6 +89,67 @@ namespace BPASmartClient } #endregion + private void GetDevices() + { + //List IDevices = new List(); + //List IPeripherals = new List(); + + DirectoryInfo directoryInfo = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory); + var files = directoryInfo.GetFiles().Where(p => p.FullName.Contains("BPASmartClient.") && p.FullName.Contains("dll")).ToList(); + List fileList = new List(); + + var assemblies = AppDomain.CurrentDomain.GetAssemblies(); + var dlls = assemblies?.Where(p => p.FullName.Contains("BPASmartClient.")).ToList(); + List dllList = new List(); + + if (files != null) + { + foreach (var item in files) + { + var res = System.IO.Path.GetFileNameWithoutExtension(item.FullName); + if (res != null && res.Length > 0 && res.Contains(".") && !res.Contains("dll")) fileList.Add(res); + } + } + + if (dlls != null) + { + dlls.ForEach((item) => + { + item.GetTypes().ToList().ForEach((type) => + { + if (type.GetInterfaces().Contains(typeof(IDevice))) + { + if (!type.FullName.Contains("BaseDevice")) ShopDeviceConfigViewModel.IDevices.Add(type.FullName); + } + else if (type.GetInterfaces().Contains(typeof(IPeripheral))) + { + if (!type.FullName.Contains("BasePeripheral")) ShopDeviceConfigViewModel.IPeripherals.Add(type.FullName); + } + }); + + dllList.Add(System.IO.Path.GetFileNameWithoutExtension(item.EscapedCodeBase)); + }); + } + + dllList.ForEach((item) => { if (fileList.Contains(item)) fileList.Remove(item); }); + + fileList.ForEach((item) => + { + Assembly.Load(item).GetTypes().ToList().ForEach((type) => + { + if (type.GetInterfaces().Contains(typeof(IDevice))) + { + if (!type.FullName.Contains("BaseDevice")) ShopDeviceConfigViewModel.IDevices.Add(type.FullName); + } + else if (type.GetInterfaces().Contains(typeof(IPeripheral))) + { + if (!type.FullName.Contains("BasePeripheral")) ShopDeviceConfigViewModel.IPeripherals.Add(type.FullName); + } + }); + }); + + } + #region Click /// /// 菜单切换栏 @@ -213,7 +277,7 @@ namespace BPASmartClient MessageLog.GetInstance.ShowEx($"BPASmartClient 中引发错误,MainWindow.xaml.cs 类MenuItem_Click(),描述:[{ex.Message}]"); } - + } private void Button_LogOut(object sender, RoutedEventArgs e) From 83c0bd32c1e7a57f7bfd955137dff638c6650f22 Mon Sep 17 00:00:00 2001 From: fyf Date: Fri, 20 May 2022 13:13:22 +0800 Subject: [PATCH 05/11] =?UTF-8?q?=E6=9B=B4=E6=96=B0IOT=E4=B8=8A=E6=8A=A5?= =?UTF-8?q?=E6=97=A5=E5=BF=97=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- BPASmartClient.DRCoffee/CoffeeMachine.cs | 2 +- BPASmartClient.IoT/BPASmartClient.IoT.csproj | 1 + BPASmartClient.IoT/DataVClient.cs | 34 ++ BPASmartClient.IoT/Model/CRC.cs | 247 +++++++++++++ BPASmartClient.IoT/Model/DataVReport.cs | 76 +++- BPASmartClient.IoT/Model/FileUpload.cs | 350 +++++++++++++++++++ BPASmartClient.IoT/Model/OSS_Helper.cs | 269 ++++++++++++++ BPASmartClient/App.config | 10 +- BPASmartClient/MainWindow.xaml.cs | 2 + 9 files changed, 972 insertions(+), 19 deletions(-) create mode 100644 BPASmartClient.IoT/Model/CRC.cs create mode 100644 BPASmartClient.IoT/Model/FileUpload.cs create mode 100644 BPASmartClient.IoT/Model/OSS_Helper.cs diff --git a/BPASmartClient.DRCoffee/CoffeeMachine.cs b/BPASmartClient.DRCoffee/CoffeeMachine.cs index 614b24b5..d0cd6a9b 100644 --- a/BPASmartClient.DRCoffee/CoffeeMachine.cs +++ b/BPASmartClient.DRCoffee/CoffeeMachine.cs @@ -164,7 +164,7 @@ namespace BPASmartClient.DRCoffee { status["Status"] = DrCoffeeStatus.Wait; status["AppStatus"] = DrCoffeeAppStatus.应用无状态; - status["Warning"] = DrCoffeeWarning.冲泡器未安装到位; + status["Warning"] = DrCoffeeWarning.无警告; status["Fault"] = DrCoffeeFault.无故障; } diff --git a/BPASmartClient.IoT/BPASmartClient.IoT.csproj b/BPASmartClient.IoT/BPASmartClient.IoT.csproj index 8178e791..1f09b04b 100644 --- a/BPASmartClient.IoT/BPASmartClient.IoT.csproj +++ b/BPASmartClient.IoT/BPASmartClient.IoT.csproj @@ -5,6 +5,7 @@ + diff --git a/BPASmartClient.IoT/DataVClient.cs b/BPASmartClient.IoT/DataVClient.cs index d08a6a24..d4412574 100644 --- a/BPASmartClient.IoT/DataVClient.cs +++ b/BPASmartClient.IoT/DataVClient.cs @@ -4,6 +4,7 @@ using BPA.Message.IOT; using BPASmartClient.Business; using BPASmartClient.Device; using BPASmartClient.Helper; +using BPASmartClient.IoT.Model; using BPASmartClient.Message; using BPASmartDatavDeviceClient.IoT; using System; @@ -204,6 +205,14 @@ namespace BPASmartClient.IoT Thread.Sleep(3000); }), "DataV数据上报", true); } + + /// + /// 文件上传请求 + /// + public void UpDataFile() + { + FileUpload.FileRequest(DeviceDataV); + } #endregion #region 私有 @@ -266,6 +275,31 @@ namespace BPASmartClient.IoT if (iOTCommand.deviceName == DeviceDataV.deviceTable.devicename) ActionManage.GetInstance.Send("IotBroadcast", iOTCommand); } + else if (DeviceDataV.FileUpLoadReplyTopic == topic)//文件请求上传响应Topic + { + FileUploadModelResult result = Tools.JsonToObjectTools(message); + if (result.code == 200) + { + string FileName = result.data?.fileName; + string uploadId = result.data?.uploadId; + FileUpload.SetUploadData(result.id,uploadId); + FileUpload.FileSend(DeviceDataV, uploadId); + } + } + else if (DeviceDataV.FileUpLoadSendReplyTopic == topic)//文件上传Topic + { + FileUploadModelResult result = Tools.JsonToObjectTools(message); + if (result.code == 200) + { + bool complete = result.data.complete; + string uploadId = result.data?.uploadId; + } + } + else if (DeviceDataV.CancelFileUpLoadSendReplyTopic == topic)//取消文件上传Topic + { + FileUploadModelResult result = Tools.JsonToObjectTools(message); + } + } /// diff --git a/BPASmartClient.IoT/Model/CRC.cs b/BPASmartClient.IoT/Model/CRC.cs new file mode 100644 index 00000000..cc57d344 --- /dev/null +++ b/BPASmartClient.IoT/Model/CRC.cs @@ -0,0 +1,247 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BPASmartClient.IoT.Model +{ + /// + /// CRC校验 + /// + public class CRC + { + + #region CRC16 + public static byte[] CRC16(byte[] data) + { + int len = data.Length; + if (len > 0) + { + ushort crc = 0xFFFF; + + for (int i = 0; i < len; i++) + { + crc = (ushort)(crc ^ (data[i])); + for (int j = 0; j < 8; j++) + { + crc = (crc & 1) != 0 ? (ushort)((crc >> 1) ^ 0xA001) : (ushort)(crc >> 1); + } + } + byte hi = (byte)((crc & 0xFF00) >> 8); //高位置 + byte lo = (byte)(crc & 0x00FF); //低位置 + + return new byte[] { hi, lo }; + } + return new byte[] { 0, 0 }; + } + + public static byte[] CRC16_L(byte[] data) + { + int len = data.Length; + if (len > 0) + { + ushort crc = 0xFFFF; + + for (int i = 0; i < len; i++) + { + crc = (ushort)(crc ^ (data[i])); + for (int j = 0; j < 8; j++) + { + crc = (crc & 1) != 0 ? (ushort)((crc >> 1) ^ 0xA001) : (ushort)(crc >> 1); + } + } + byte hi = (byte)((crc & 0xFF00) >> 8); //高位置 + byte lo = (byte)(crc & 0x00FF); //低位置 + + return new byte[] { lo,hi }; + } + return new byte[] { 0, 0 }; + } + #endregion + + #region ToCRC16 + public static string ToCRC16(string content) + { + return ToCRC16(content, Encoding.UTF8); + } + + public static string ToCRC16(string content, bool isReverse) + { + return ToCRC16(content, Encoding.UTF8, isReverse); + } + + public static string ToCRC16(string content, Encoding encoding) + { + return ByteToString(CRC16(encoding.GetBytes(content)), true); + } + + public static string ToCRC16(string content, Encoding encoding, bool isReverse) + { + return ByteToString(CRC16(encoding.GetBytes(content)), isReverse); + } + + public static string ToCRC16(byte[] data) + { + return ByteToString(CRC16(data), true); + } + + public static string ToCRC16(byte[] data, bool isReverse) + { + return ByteToString(CRC16(data), isReverse); + } + #endregion + + #region ToModbusCRC16 + public static string ToModbusCRC16(string s) + { + return ToModbusCRC16(s, true); + } + + public static string ToModbusCRC16(string s, bool isReverse) + { + return ByteToString(CRC16(StringToHexByte(s)), isReverse); + } + + public static string ToModbusCRC16(byte[] data) + { + return ToModbusCRC16(data, true); + } + + public static string ToModbusCRC16(byte[] data, bool isReverse) + { + return ByteToString(CRC16(data), isReverse); + } + #endregion + + #region ByteToString + public static string ByteToString(byte[] arr, bool isReverse) + { + try + { + byte hi = arr[0], lo = arr[1]; + return Convert.ToString(isReverse ? hi + lo * 0x100 : hi * 0x100 + lo, 16).ToUpper().PadLeft(4, '0'); + } + catch (Exception ex) { throw (ex); } + } + + public static string ByteToString(byte[] arr) + { + try + { + return ByteToString(arr, true); + } + catch (Exception ex) { throw (ex); } + } + #endregion + + #region StringToHexString + public static string StringToHexString(string str) + { + StringBuilder s = new StringBuilder(); + foreach (short c in str.ToCharArray()) + { + s.Append(c.ToString("X4")); + } + return s.ToString(); + } + #endregion + + #region StringToHexByte + private static string ConvertChinese(string str) + { + StringBuilder s = new StringBuilder(); + foreach (short c in str.ToCharArray()) + { + if (c <= 0 || c >= 127) + { + s.Append(c.ToString("X4")); + } + else + { + s.Append((char)c); + } + } + return s.ToString(); + } + + private static string FilterChinese(string str) + { + StringBuilder s = new StringBuilder(); + foreach (short c in str.ToCharArray()) + { + if (c > 0 && c < 127) + { + s.Append((char)c); + } + } + return s.ToString(); + } + + /// + /// 字符串转16进制字符数组 + /// + /// + /// + public static byte[] StringToHexByte(string str) + { + return StringToHexByte(str, false); + } + + /// + /// 字符串转16进制字符数组 + /// + /// + /// 是否过滤掉中文字符 + /// + public static byte[] StringToHexByte(string str, bool isFilterChinese) + { + string hex = isFilterChinese ? FilterChinese(str) : ConvertChinese(str); + + //清除所有空格 + hex = hex.Replace(" ", ""); + //若字符个数为奇数,补一个0 + hex += hex.Length % 2 != 0 ? "0" : ""; + + byte[] result = new byte[hex.Length / 2]; + for (int i = 0, c = result.Length; i < c; i++) + { + result[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16); + } + return result; + } + #endregion + + } + + class CRC16Standard + { + private static int[] table = { 0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241, 0xC601, 0x06C0, 0x0780, 0xC741, + 0x0500, 0xC5C1, 0xC481, 0x0440, 0xCC01, 0x0CC0, 0x0D80, 0xCD41, 0x0F00, 0xCFC1, 0xCE81, 0x0E40, 0x0A00, 0xCAC1, 0xCB81, 0x0B40, + 0xC901, 0x09C0, 0x0880, 0xC841, 0xD801, 0x18C0, 0x1980, 0xD941, 0x1B00, 0xDBC1, 0xDA81, 0x1A40, 0x1E00, 0xDEC1, 0xDF81, 0x1F40, + 0xDD01, 0x1DC0, 0x1C80, 0xDC41, 0x1400, 0xD4C1, 0xD581, 0x1540, 0xD701, 0x17C0, 0x1680, 0xD641, 0xD201, 0x12C0, 0x1380, 0xD341, + 0x1100, 0xD1C1, 0xD081, 0x1040, 0xF001, 0x30C0, 0x3180, 0xF141, 0x3300, 0xF3C1, 0xF281, 0x3240, 0x3600, 0xF6C1, 0xF781, 0x3740, + 0xF501, 0x35C0, 0x3480, 0xF441, 0x3C00, 0xFCC1, 0xFD81, 0x3D40, 0xFF01, 0x3FC0, 0x3E80, 0xFE41, 0xFA01, 0x3AC0, 0x3B80, 0xFB41, + 0x3900, 0xF9C1, 0xF881, 0x3840, 0x2800, 0xE8C1, 0xE981, 0x2940, 0xEB01, 0x2BC0, 0x2A80, 0xEA41, 0xEE01, 0x2EC0, 0x2F80, 0xEF41, + 0x2D00, 0xEDC1, 0xEC81, 0x2C40, 0xE401, 0x24C0, 0x2580, 0xE541, 0x2700, 0xE7C1, 0xE681, 0x2640, 0x2200, 0xE2C1, 0xE381, 0x2340, + 0xE101, 0x21C0, 0x2080, 0xE041, 0xA001, 0x60C0, 0x6180, 0xA141, 0x6300, 0xA3C1, 0xA281, 0x6240, 0x6600, 0xA6C1, 0xA781, 0x6740, + 0xA501, 0x65C0, 0x6480, 0xA441, 0x6C00, 0xACC1, 0xAD81, 0x6D40, 0xAF01, 0x6FC0, 0x6E80, 0xAE41, 0xAA01, 0x6AC0, 0x6B80, 0xAB41, + 0x6900, 0xA9C1, 0xA881, 0x6840, 0x7800, 0xB8C1, 0xB981, 0x7940, 0xBB01, 0x7BC0, 0x7A80, 0xBA41, 0xBE01, 0x7EC0, 0x7F80, 0xBF41, + 0x7D00, 0xBDC1, 0xBC81, 0x7C40, 0xB401, 0x74C0, 0x7580, 0xB541, 0x7700, 0xB7C1, 0xB681, 0x7640, 0x7200, 0xB2C1, 0xB381, 0x7340, + 0xB101, 0x71C0, 0x7080, 0xB041, 0x5000, 0x90C1, 0x9181, 0x5140, 0x9301, 0x53C0, 0x5280, 0x9241, 0x9601, 0x56C0, 0x5780, 0x9741, + 0x5500, 0x95C1, 0x9481, 0x5440, 0x9C01, 0x5CC0, 0x5D80, 0x9D41, 0x5F00, 0x9FC1, 0x9E81, 0x5E40, 0x5A00, 0x9AC1, 0x9B81, 0x5B40, + 0x9901, 0x59C0, 0x5880, 0x9841, 0x8801, 0x48C0, 0x4980, 0x8941, 0x4B00, 0x8BC1, 0x8A81, 0x4A40, 0x4E00, 0x8EC1, 0x8F81, 0x4F40, + 0x8D01, 0x4DC0, 0x4C80, 0x8C41, 0x4400, 0x84C1, 0x8581, 0x4540, 0x8701, 0x47C0, 0x4680, 0x8641, 0x8201, 0x42C0, 0x4380, 0x8341, + 0x4100, 0x81C1, 0x8081, 0x4040, }; + + public static byte[] getCRCBytes(byte[] data) + { + int crc = 0x0000; + foreach (byte b in data) + { + crc = (crc >> 8) ^ table[(crc ^ b) & 0xff]; + } + return new byte[] { (byte)(0xff & crc), (byte)((0xff00 & crc) >> 8) }; + } + } +} diff --git a/BPASmartClient.IoT/Model/DataVReport.cs b/BPASmartClient.IoT/Model/DataVReport.cs index 83d93806..560343b7 100644 --- a/BPASmartClient.IoT/Model/DataVReport.cs +++ b/BPASmartClient.IoT/Model/DataVReport.cs @@ -1,6 +1,7 @@ using BPA.Message.IOT; using BPASmartClient.Helper; using BPASmartClient.IoT; +using BPASmartClient.IoT.Model; using System; using System.Collections.Generic; using System.Linq; @@ -22,16 +23,20 @@ namespace BPASmartDatavDeviceClient.IoT /// /// 初始化IOT连接 /// - public bool Initialize(string url,string _clientId,string _deviceId,ref string message) + public bool Initialize(string url, string _clientId, string _deviceId, ref string message) { - if(string.IsNullOrEmpty(url))return false; + if (string.IsNullOrEmpty(url)) return false; deviceId = _deviceId; - if (!CreateLinks(url, _clientId,out deviceTable, _deviceId)) + if (!CreateLinks(url, _clientId, out deviceTable, _deviceId)) { message += $"客户端{_clientId}设备{_deviceId}阿里云上没有该设备。"; return false; } IOT_Subscribe(BroadcastTopic);//订阅广播主题 + IOT_Subscribe(FileUpLoadReplyTopic); + IOT_Subscribe(FileUpLoadSendReplyTopic); + IOT_Subscribe(CancelFileUpLoadSendTopic); + if (!DatavDeviceClient.IsConnected) message += $"客户端:【{_clientId}】,设备名称{deviceTable.devicename}阿里云连接失败.不能上报业务信息"; return DatavDeviceClient.IsConnected; } @@ -113,6 +118,11 @@ namespace BPASmartDatavDeviceClient.IoT var id = DatavDeviceClient.Publish(topic, Encoding.UTF8.GetBytes(message)); } + public void IOT_Publish(string topic, byte[] message) + { + var id = DatavDeviceClient.Publish(topic, message); + } + /// /// 订阅主题 /// @@ -125,8 +135,20 @@ namespace BPASmartDatavDeviceClient.IoT } DatavDeviceClient.Subscribe(new string[] { topic }, new byte[] { 0 }); } + + public void Chkin_Up() + { + OSS_Helper ss = new OSS_Helper(); + + string objectName = "Project/aa.bak"; + string downloadFilename = @"\\aa.bak"; + //记录进度的文件路径 + string checkpointDir = @"D:\checkin\"; + //ss.Multipar_tUp(objectName, downloadFilename); + ss.chkin_Up(objectName, downloadFilename, checkpointDir); + } #endregion - + #region 私有函数 /// /// 设置变量 @@ -151,18 +173,24 @@ namespace BPASmartDatavDeviceClient.IoT HeartbeatSubTopic = "/" + ProductKey + "/" + DeviceName + "/user/HeartbeatAndState"; TargetStatusSubTopic = "/" + ProductKey + "/" + DeviceName + "/user/TargetStatus"; ScreenShowPubTopic = "/" + ProductKey + "/" + DeviceName + "/user/ScreenShow"; + FileUpLoadTopic = $"/sys/{ProductKey}/{DeviceName}/thing/file/upload/mqtt/init"; + FileUpLoadReplyTopic = $"/sys/{ProductKey}/{DeviceName}/thing/file/upload/mqtt/init_reply"; + FileUpLoadSendTopic = $"/sys/{ProductKey}/{DeviceName}/thing/file/upload/mqtt/send"; + FileUpLoadSendReplyTopic = $"/sys/{ProductKey}/{DeviceName}/thing/file/upload/mqtt/send_reply"; + CancelFileUpLoadSendTopic = $"/sys/{ProductKey}/{DeviceName}/thing/file/upload/mqtt/cancel"; + CancelFileUpLoadSendReplyTopic = $"/sys/{ProductKey}/{DeviceName}/thing/file/upload/mqtt/cancel_reply"; } /// /// 创建连接 /// - private bool CreateLinks(string url, string clientId, out DeviceTable device ,string deviceId = "") + private bool CreateLinks(string url, string clientId, out DeviceTable device, string deviceId = "") { try { string json = string.Empty; if (string.IsNullOrEmpty(deviceId)) - json = HttpRequestHelper.HttpGetRequest($"{url}/api/Device/Query?clientId={clientId}",1000); + json = HttpRequestHelper.HttpGetRequest($"{url}/api/Device/Query?clientId={clientId}", 1000); else json = HttpRequestHelper.HttpGetRequest($"{url}/api/Device/Query?clientId={clientId}&deviceId={deviceId}"); JsonMsg> jsonMsg = Tools.JsonToObjectTools>>(json); @@ -224,7 +252,7 @@ namespace BPASmartDatavDeviceClient.IoT /// /// /// - private void Client_ConnectionClosed(object sender, EventArgs e) + private void Client_ConnectionClosed(object sender, EventArgs e) { // 尝试重连 _TryContinueConnect(); @@ -235,7 +263,7 @@ namespace BPASmartDatavDeviceClient.IoT /// /// /// - private void Client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e) + private void Client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e) { string topic = e.Topic; string message = Encoding.UTF8.GetString(e.Message); @@ -248,7 +276,7 @@ namespace BPASmartDatavDeviceClient.IoT /// /// 自动重连主体 /// - private void _TryContinueConnect() + private void _TryContinueConnect() { Thread retryThread = new Thread(new ThreadStart(delegate { @@ -265,7 +293,7 @@ namespace BPASmartDatavDeviceClient.IoT DatavDeviceClient.ConnectionClosed += Client_ConnectionClosed; if (DatavDeviceClient.IsConnected) { - SubTopicList?.ForEach(par =>{DatavDeviceClient.Subscribe(new string[] { par }, new byte[] { 0 }); }); + SubTopicList?.ForEach(par => { DatavDeviceClient.Subscribe(new string[] { par }, new byte[] { 0 }); }); } Thread.Sleep(3000); continue; @@ -312,7 +340,7 @@ namespace BPASmartDatavDeviceClient.IoT /// /// 设备消息数据回调 /// - public Action DataVMessageAction { get; set; } + public Action DataVMessageAction { get; set; } /// /// 重连事件 /// @@ -324,7 +352,7 @@ namespace BPASmartDatavDeviceClient.IoT /// /// 当前设备 /// - public DeviceTable deviceTable =new DeviceTable(); + public DeviceTable deviceTable = new DeviceTable(); #endregion #region 发布或订阅主题或URL地址 @@ -369,10 +397,30 @@ namespace BPASmartDatavDeviceClient.IoT /// public string BroadcastTopic = "/broadcast/" + "grgpECHSL7q" + "/" + DeviceName + "_SetDevice"; /// - /// 文件上床Topic + /// 文件上传请求Topic /// public string FileUpLoadTopic = $"/sys/{ProductKey}/{DeviceName}/thing/file/upload/mqtt/init"; /// + /// 文件上传请求响应Topic + /// + public string FileUpLoadReplyTopic = $"/sys/{ProductKey}/{DeviceName}/thing/file/upload/mqtt/init_reply"; + /// + /// 文件发送Topic + /// + public string FileUpLoadSendTopic = $"/sys/{ProductKey}/{DeviceName}/thing/file/upload/mqtt/send"; + /// + /// 文件发送响应Topic + /// + public string FileUpLoadSendReplyTopic = $"/sys/{ProductKey}/{DeviceName}/thing/file/upload/mqtt/send_reply"; + /// + /// 取消文件发送Topic + /// + public string CancelFileUpLoadSendTopic = $"/sys/{ProductKey}/{DeviceName}/thing/file/upload/mqtt/cancel"; + /// + /// 取消文件发送响应Topic + /// + public string CancelFileUpLoadSendReplyTopic = $"/sys/{ProductKey}/{DeviceName}/thing/file/upload/mqtt/cancel_reply"; + /// /// 订阅主题集合 /// public static List SubTopicList = new List(); @@ -409,4 +457,6 @@ namespace BPASmartDatavDeviceClient.IoT return signBuilder.ToString(); } } + + } diff --git a/BPASmartClient.IoT/Model/FileUpload.cs b/BPASmartClient.IoT/Model/FileUpload.cs new file mode 100644 index 00000000..97d14551 --- /dev/null +++ b/BPASmartClient.IoT/Model/FileUpload.cs @@ -0,0 +1,350 @@ +using BPASmartDatavDeviceClient.IoT; +using DataVAPI.Tool.IOT; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BPASmartClient.IoT.Model +{ + /// + /// 阿里云文件上传 + /// + public class FileUpload + { + public static Dictionary UploadData = new Dictionary(); + public static string FileName=$"HBL.LogDir{DateTime.Now.AddDays(-2).ToString("yyyy_M_d")}"; + public static string path = $"{System.AppDomain.CurrentDomain.BaseDirectory}LogDir\\{FileName}.log"; + public static void SetUploadData(string key,string value) + { + UploadData[key] = value; + } + public static string GetUploadData(string key) + { + return UploadData.ContainsKey(key)? UploadData[key]:string.Empty; + } + /// + /// 文件请求上传 + /// + public static void FileRequest(DataVReport dataV) + { + long length= new FileInfo(path).Length; + byte[] FileBlock = File.ReadAllBytes(path); + FileUploadModel fileUpload=new FileUploadModel(); + fileUpload.@params.fileName = FileName; + fileUpload.@params.fileSize = length; + fileUpload.@params.conflictStrategy = "overwrite";//覆盖模式 + //fileUpload.@params.ficMode = "crc64"; + //fileUpload.@params.ficValue = CRC.ToCRC16(FileBlock); + fileUpload.@params.initUid = $"ab{RandomHelper.GenerateRandomCode()}"; + + //上传到阿里云物联网平台的OSS存储空间中 + fileUpload.@params.extraParams.ossOwnerType = "iot-platform"; + + //表示上传到设备所属用户自己的OSS存储空间中 + //{ossbucket}/aliyun-iot-device-file/${instanceId}/${productKey}/${serviceId}/${deviceName}/${fileName} + //fileUpload.@params.extraParams.ossOwnerType = "device-user"; + //fileUpload.@params.extraParams.serviceId = "black"; + //fileUpload.@params.extraParams.fileTag = new Dictionary { {"Time", DateTime.Now.ToString("yyyy_M_d") },{"Name", "HBL.LogDir" } }; + + dataV.IOT_Publish(dataV.FileUpLoadTopic,Tools.JsonConvertTools(fileUpload)); + } + + /// + /// 文件上传 + /// + public static void FileSend(DataVReport dataV,string uploadId) + { + long length = new FileInfo(path).Length; + FileSendModel fileSend=new FileSendModel(); + fileSend.@params.uploadId = uploadId; + fileSend.@params.offset = 0; + fileSend.@params.bSize = length; + //结构如下图 + //Header.length(高 低) + Header(字节数组UTF-8) + 文件分片的字节数组 + "分片校验值CrC16 低 高" + byte[] Header = Encoding.UTF8.GetBytes(Tools.JsonConvertTools(fileSend)); + byte HeaderLen_L = (byte)(Header.Length); + byte HeaderLen_H = (byte)(Header.Length >> 8); + byte[] FileBlock = File.ReadAllBytes(path);// ReadFile(path); + byte[] CRC16 = CRC16Standard.getCRCBytes(FileBlock);//CRC.CRC16(FileBlock); + List message = new List() { HeaderLen_H, HeaderLen_L}; + message.AddRange(Header); + message.AddRange(FileBlock); + message.AddRange(CRC16); + dataV.IOT_Publish(dataV.FileUpLoadSendTopic, message.ToArray()); + } + + /// + /// 取消文件上传 + /// + public static void FileCancelSend(DataVReport dataV) + { + //CancelSend cancel = new CancelSend(); + //dataV.IOT_Publish(dataV.CancelFileUpLoadSendTopic, Tools.JsonConvertTools(cancel)); + } + + /// + /// 读取文件字节 + /// + /// + /// + public static byte[] ReadFile(string path) + { + //创建d:\file.txt的FileStream对象 + FileStream fstream = new FileStream($@"{path}", FileMode.OpenOrCreate); + byte[] bData = new byte[fstream.Length]; + //设置流当前位置为文件开始位置 + fstream.Seek(0, SeekOrigin.Begin); + + //将文件的内容存到字节数组中(缓存) + fstream.Read(bData, 0, bData.Length); + string result = Encoding.UTF8.GetString(bData); + Console.WriteLine(result); + if (fstream != null) + { + //清除此流的缓冲区,使得所有缓冲的数据都写入到文件中 + fstream.Flush(); + fstream.Close(); + } + return bData; + } + } + + #region 请求上传文件 + /// + /// 请求上传文件 + /// + public class FileUploadModel + { + /// + /// 消息ID号 + /// 0~4294967295 + /// + public string id { get; set; } + /// + /// 请求业务参数 + /// + public BusinessParameters @params { get; set; } + + public FileUploadModel() + { + id = RandomHelper.GenerateRandomCode(); + @params = new BusinessParameters(); + } + } + + /// + /// 业务参数 + /// + public class BusinessParameters + { + /// + /// 设备上传文件的名称 + /// + public string fileName { get; set; } + /// + /// 上传文件大小,单位字节。单个文件大小不超过16 MB。 + /// 取值为-1时,表示文件大小未知。文件上传完成时,需在上传文件分片的消息中,指定参数isComplete + /// + public long fileSize { get; set; } + /// + /// 物联网平台对设备上传同名文件的处理策略,默认为overwrite + /// overwrite:覆盖模式 append:文件追加模式 reject:拒绝模式 + /// + public string conflictStrategy { get; set; } = "overwrite"; + /// + /// 文件的完整性校验模式,目前可取值crc64 + /// 若不传入,在文件上传完成后不校验文件完整性 + /// + public string ficMode { get; set; } + /// + /// 文件的完整性校验值,是16位的Hex格式编码的字符串 + /// + public string ficValue { get; set; } + /// + /// 自定义的设备请求上传文件的任务唯一ID,同一上传任务请求必须对应相同的唯一ID + /// 不传入:物联网平台的云端识别当前请求为新的文件上传请求 + /// + public string initUid { get; set; } + /// + /// 设备上传文件至OSS存储空间的配置参数 + /// + public ConfigureParameters extraParams { get; set; }=new ConfigureParameters(); + } + /// + /// 配置参数 + /// + public class ConfigureParameters + { + /// + /// 设备上传文件的目标OSS所有者类型 + /// iot-platform:表示上传到阿里云物联网平台的OSS存储空间中 + /// device-user:表示上传到设备所属用户自己的OSS存储空间中 + /// + public string ossOwnerType { get; set; } = "device-user"; + /// + /// 文件上传相关的业务ID + /// + public string serviceId { get; set; } + /// + /// 标签 + /// + public Dictionary fileTag { get; set; } + public ConfigureParameters() + { + + } + } + #endregion + + #region 请求上传文件响应 + /// + /// 请求响应 + /// + public class FileUploadModelResult + { + /// + /// 消息ID号 + /// 0~4294967295 + /// + public string id { get; set; } + /// + /// 结果码。返回200表示成功 + /// + public int code { get; set; } + /// + /// 请求失败时,返回的错误信息 + /// + public string message { get; set; } + /// + /// 返回设备端的数据。 + /// + public ResultData data { get; set; } + + } + /// + /// 请求响应数据 + /// + public class ResultData + { + /// + /// 设备上传文件的名称 + /// + public string fileName { get; set; } + /// + /// 本次上传文件任务的标识ID。后续上传文件分片时,需要传递该文件标识ID。 + /// + public string uploadId { get; set; } + /// + /// 仅当请求参数conflictStrategy为append,且物联网平台云端存在未完成上传的文件时,返回的已上传文件的大小,单位为字节。 + /// + public long offset { get; set; } + /// + /// 当前上传文件分片的大小 + /// + public long bSize { get; set; } + /// + /// 当上传了最后一个分片数据后,文件上传完成 + /// + public bool complete { get; set; } + /// + /// 文件的完整性校验模式。若请求上传文件时传入了该参数,对应的值仅支持为crc64 + /// + public string ficMode { get; set; } + /// + /// 文件上传完成,返回设备请求上传文件时的 + /// + public string ficValueClient { get; set; } + /// + /// 文件上传完成,返回物联网平台云端计算的文件完整性校验值。该值与ficValueClient值相同,表示文件上传完整。 + /// + public string ficValueServer { get; set; } + } + #endregion + + #region 上传文件 + public class FileSendModel + { + /// + /// 消息ID号 + /// 0~4294967295 + /// + public string id { get; set; } + /// + /// 上传业务参数 + /// + public SendBusinessParameters @params { get; set; } = new SendBusinessParameters(); + public FileSendModel() + { + id = RandomHelper.GenerateRandomCode(); + } + } + /// + /// 上传业务参数 + /// + public class SendBusinessParameters + { + /// + /// 设备请求上传文件时返回的文件上传任务标识ID。 + /// + public string uploadId { get; set; } + /// + /// 已上传文件分片的总大小,单位为字节。 + /// + public long offset { get; set; } + /// + /// 当前上传文件分片的大小,单位为字节 + /// + public long bSize { get; set; } + /// + /// 仅当设备请求上传文件中fileSize为-1,即文件大小未知时,该参数有效,表示当前分片是否是文件的最后一个分片 + /// + public bool isComplete { get; set; } = true; + } + #endregion + + #region 取消文件上传 + /// + /// 取消上传 + /// + public class CancelSend + { + /// + /// 消息ID号 + /// 0~4294967295 + /// + public string id { get; set; } + /// + /// 请求业务参数 + /// + public object @params { get; set; } + + public CancelSend(string uploadId) + { + id= RandomHelper.GenerateRandomCode(); + @params = new { uploadId = uploadId }; + } + } + #endregion + + public class RandomHelper + { + /// + ///生成制定位数的随机码(数字) + /// + /// + /// + public static string GenerateRandomCode(int length=10) + { + var result = new StringBuilder(); + for (var i = 0; i < length; i++) + { + var r = new Random(Guid.NewGuid().GetHashCode()); + result.Append(r.Next(0, 10)); + } + return result.ToString(); + } + } +} diff --git a/BPASmartClient.IoT/Model/OSS_Helper.cs b/BPASmartClient.IoT/Model/OSS_Helper.cs new file mode 100644 index 00000000..2a01a1cf --- /dev/null +++ b/BPASmartClient.IoT/Model/OSS_Helper.cs @@ -0,0 +1,269 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +using Aliyun.OSS; +using Aliyun.OSS.Common; + +namespace BPASmartClient.IoT.Model +{ + public class OSS_Helper + { + const string accessKeyId = "xxx"; + const string accessKeySecret = "xxx"; + const string endpoint = "http://oss-cn-shanghai.aliyuncs.com"; + const string bucketName = "xxx"; + OssClient client = null; + + public OSS_Helper() + { + // 由用户指定的OSS访问地址、阿里云颁发的AccessKeyId/AccessKeySecret构造一个新的OssClient实例。 + client = new OssClient(endpoint, accessKeyId, accessKeySecret); + } + + /*简单上传:文件最大不能超过5GB。 + 追加上传:文件最大不能超过5GB。 + 断点续传上传:支持并发、断点续传、自定义分片大小。大文件上传推荐使用断点续传。最大不能超过48.8TB。 + 分片上传:当文件较大时,可以使用分片上传,最大不能超过48.8TB。*/ + /// + /// + /// + /// + /// + public void Simple_Up(string objectName, string localFilename) + { + + //var objectName = "Project/222.jpg"; + //var localFilename = @"C:\tiger.jpg"; + // 创建OssClient实例。 + try + { + // 上传文件。 + client.PutObject(bucketName, objectName, localFilename); + Console.WriteLine("Put object succeeded"); + } + catch (Exception ex) + { + Console.WriteLine("Put object failed, {0}", ex.Message); + } + } + /// + /// 分片上传 + /// + /// + /// + public void Multipar_tUp(string objectName, string localFilename) + { + var uploadId = ""; + try + { + // 定义上传文件的名字和所属存储空间。在InitiateMultipartUploadRequest中,可以设置ObjectMeta,但不必指定其中的ContentLength。 + var request = new InitiateMultipartUploadRequest(bucketName, objectName); + var result = client.InitiateMultipartUpload(request); + uploadId = result.UploadId; + // 打印UploadId。 + Console.WriteLine("Init multi part upload succeeded"); + Console.WriteLine("Upload Id:{0}", result.UploadId); + } + catch (Exception ex) + { + throw ex; + } + // 计算分片总数。 + var partSize = 1024 * 1024; + var fi = new FileInfo(localFilename); + var fileSize = fi.Length; + var partCount = fileSize / partSize; + if (fileSize % partSize != 0) + { + partCount++; + } + // 开始分片上传。partETags是保存partETag的列表,OSS收到用户提交的分片列表后,会逐一验证每个分片数据的有效性。 当所有的数据分片通过验证后,OSS会将这些分片组合成一个完整的文件。 + var partETags = new List(); + try + { + using (var fs = File.Open(localFilename, FileMode.Open)) + { + for (var i = 0; i < partCount; i++) + { + var skipBytes = (long)partSize * i; + // 定位到本次上传起始位置。 + fs.Seek(skipBytes, 0); + // 计算本次上传的片大小,最后一片为剩余的数据大小。 + var size = (partSize < fileSize - skipBytes) ? partSize : (fileSize - skipBytes); + var request = new UploadPartRequest(bucketName, objectName, uploadId) + { + InputStream = fs, + PartSize = size, + PartNumber = i + 1 + }; + // 调用UploadPart接口执行上传功能,返回结果中包含了这个数据片的ETag值。 + var result = client.UploadPart(request); + partETags.Add(result.PartETag); + Console.WriteLine("finish {0}/{1}", partETags.Count, partCount); + } + Console.WriteLine("Put multi part upload succeeded"); + } + } + catch (Exception ex) + { + throw ex; + } + // 列举已上传的分片。 + try + { + var listPartsRequest = new ListPartsRequest(bucketName, objectName, uploadId); + var listPartsResult = client.ListParts(listPartsRequest); + Console.WriteLine("List parts succeeded"); + // 遍历所有分片。 + var parts = listPartsResult.Parts; + foreach (var part in parts) + { + Console.WriteLine("partNumber: {0}, ETag: {1}, Size: {2}", part.PartNumber, part.ETag, part.Size); + } + } + catch (Exception ex) + { + throw ex; + } + // 完成分片上传。 + try + { + var completeMultipartUploadRequest = new CompleteMultipartUploadRequest(bucketName, objectName, uploadId); + foreach (var partETag in partETags) + { + completeMultipartUploadRequest.PartETags.Add(partETag); + } + var result = client.CompleteMultipartUpload(completeMultipartUploadRequest); + Console.WriteLine("complete multi part succeeded"); + } + catch (Exception ex) + { + throw ex; + } + + } + /// + /// 上传 + /// + /// + /// + /// + public void chkin_Up(string objectName, string localFilename, string checkpointDir) + { + try + { + // 通过UploadFileRequest设置多个参数。 + UploadObjectRequest request = new UploadObjectRequest(bucketName, objectName, localFilename) + { + // 指定上传的分片大小。 + PartSize = 1024 * 1024, + // 指定并发线程数。 + ParallelThreadCount = 10, + // checkpointDir保存断点续传的中间状态,用于失败后继续上传。如果checkpointDir为null,断点续传功能不会生效,每次失败后都会重新上传。 + CheckpointDir = checkpointDir, + }; + // 断点续传上传。 + client.ResumableUploadObject(request); + Console.WriteLine("Resumable upload object:{0} succeeded", objectName); + } + catch (OssException ex) + { + Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}", + ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId); + } + catch (Exception ex) + { + Console.WriteLine("Failed with error info: {0}", ex.Message); + } + + } + /// + /// 下载文件 + /// + /// + /// + public void Stream_Down(string objectName, string downloadFilename) + { + // objectName 表示您在下载文件时需要指定的文件名称,如abc/efg/123.jpg。 + //var objectName = "Project/cc.jpg"; + //var downloadFilename = @"D:\GG.jpg"; + // 创建OssClient实例。 + //var client = new OssClient(endpoint, accessKeyId, accessKeySecret); + try + { + // 下载文件到流。OssObject 包含了文件的各种信息,如文件所在的存储空间、文件名、元信息以及一个输入流。 + var obj = client.GetObject(bucketName, objectName); + using (var requestStream = obj.Content) + { + byte[] buf = new byte[1024]; + var fs = File.Open(downloadFilename, FileMode.OpenOrCreate); + var len = 0; + // 通过输入流将文件的内容读取到文件或者内存中。 + while ((len = requestStream.Read(buf, 0, 1024)) != 0) + { + fs.Write(buf, 0, len); + } + fs.Close(); + } + Console.WriteLine("Get object succeeded"); + } + catch (Exception ex) + { + Console.WriteLine("Get object failed. {0}", ex.Message); + } + } + + public void DownPBar() + { + + } + + public static void GetObjectProgress() + { + var endpoint = ""; + var accessKeyId = ""; + var accessKeySecret = ""; + var bucketName = ""; + var objectName = ""; + // 创建OssClient实例。 + var client = new OssClient(endpoint, accessKeyId, accessKeySecret); + try + { + var getObjectRequest = new GetObjectRequest(bucketName, objectName); + getObjectRequest.StreamTransferProgress += streamProgressCallback; + // 下载文件。 + var ossObject = client.GetObject(getObjectRequest); + using (var stream = ossObject.Content) + { + var buffer = new byte[1024 * 1024]; + var bytesRead = 0; + while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0) + { + // 处理读取的数据(此处代码省略)。 + } + } + Console.WriteLine("Get object:{0} succeeded", objectName); + } + catch (OssException ex) + { + Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}", + ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId); + } + catch (Exception ex) + { + Console.WriteLine("Failed with error info: {0}", ex.Message); + } + } + + private static void streamProgressCallback(object sender, StreamTransferProgressArgs args) + { + System.Console.WriteLine("ProgressCallback - Progress: {0}%, TotalBytes:{1}, TransferredBytes:{2} ", + args.TransferredBytes * 100 / args.TotalBytes, args.TotalBytes, args.TransferredBytes); + } + + } +} diff --git a/BPASmartClient/App.config b/BPASmartClient/App.config index 3bf86a0a..45f48f2b 100644 --- a/BPASmartClient/App.config +++ b/BPASmartClient/App.config @@ -3,7 +3,7 @@ - + @@ -12,7 +12,7 @@ - + @@ -37,7 +37,7 @@ --> - + diff --git a/BPASmartClient/MainWindow.xaml.cs b/BPASmartClient/MainWindow.xaml.cs index 9bf20010..682d7c73 100644 --- a/BPASmartClient/MainWindow.xaml.cs +++ b/BPASmartClient/MainWindow.xaml.cs @@ -155,6 +155,8 @@ namespace BPASmartClient NoticeDemoViewModel.OpenMsg(EnumPromptType.Error, this, "我是标题", "我是消息内容!我是消息内容!我是消息内容!我是消息内容!"); NoticeDemoViewModel.OpenMsg(EnumPromptType.Warn, this, "我是标题", "我是消息内容!我是消息内容!我是消息内容!我是消息内容!"); NoticeDemoViewModel.OpenMsg(EnumPromptType.Success, this, "我是标题", "我是消息内容!我是消息内容!我是消息内容!我是消息内容!"); + + DataVClient.GetInstance().UpDataFile(); } #endregion From bee994361217c84e31b883381b3a4592d14dded4 Mon Sep 17 00:00:00 2001 From: fyf Date: Fri, 20 May 2022 13:49:05 +0800 Subject: [PATCH 06/11] =?UTF-8?q?=E6=9C=AC=E5=9C=B0=E6=97=A5=E5=BF=97?= =?UTF-8?q?=E6=96=87=E4=BB=B6=E4=B8=8A=E6=8A=A5=E9=98=BF=E9=87=8C=E4=BA=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- BPASmartClient.IoT/BPASmartClient.IoT.csproj | 26 +++---- BPASmartClient.IoT/DataVClient.cs | 24 +++++-- BPASmartClient.IoT/Model/FileUpload.cs | 73 +++++++++++++------- BPASmartClient.ViewModel/LogViewModel.cs | 11 +++ BPASmartClient/App.config | 2 +- BPASmartClient/MainWindow.xaml.cs | 2 - 6 files changed, 92 insertions(+), 46 deletions(-) diff --git a/BPASmartClient.IoT/BPASmartClient.IoT.csproj b/BPASmartClient.IoT/BPASmartClient.IoT.csproj index 1f09b04b..0f2a2042 100644 --- a/BPASmartClient.IoT/BPASmartClient.IoT.csproj +++ b/BPASmartClient.IoT/BPASmartClient.IoT.csproj @@ -1,19 +1,19 @@  - - net6.0 - + + net6.0 + - - - - - - + + + + + + - - - - + + + + diff --git a/BPASmartClient.IoT/DataVClient.cs b/BPASmartClient.IoT/DataVClient.cs index d4412574..d16c12f4 100644 --- a/BPASmartClient.IoT/DataVClient.cs +++ b/BPASmartClient.IoT/DataVClient.cs @@ -211,12 +211,21 @@ namespace BPASmartClient.IoT /// public void UpDataFile() { - FileUpload.FileRequest(DeviceDataV); + try + { + if (DeviceDataV != null && DeviceDataV.GetIsConnected() && DeviceDataV.deviceTable != null) + { + FileUpload.FileRequest(DeviceDataV); + } + } + catch (Exception ex) + { + MessageLog.GetInstance.Show(ex.Message); + } } #endregion #region 私有 - /// /// 增加告警 /// @@ -284,16 +293,23 @@ namespace BPASmartClient.IoT string uploadId = result.data?.uploadId; FileUpload.SetUploadData(result.id,uploadId); FileUpload.FileSend(DeviceDataV, uploadId); + MessageLog.GetInstance.Show($"请求上传【阿里云】成功,准备上传日志文件【HBL.LogDir{DateTime.Now.ToString("yyyy_M_d")}.log】"); } + else + MessageLog.GetInstance.Show($"【HBL.LogDir{DateTime.Now.ToString("yyyy_M_d")}.log】请求上传【阿里云】失败,{result.message}"); + } else if (DeviceDataV.FileUpLoadSendReplyTopic == topic)//文件上传Topic { FileUploadModelResult result = Tools.JsonToObjectTools(message); if (result.code == 200) { + MessageLog.GetInstance.Show($"今日日志文件“HBL.LogDir{DateTime.Now.ToString("yyyy_M_d")}.log”更新上传【阿里云】成功"); bool complete = result.data.complete; string uploadId = result.data?.uploadId; - } + }else + MessageLog.GetInstance.Show($"今日日志文件“HBL.LogDir{DateTime.Now.ToString("yyyy_M_d")}.log”更新上传【阿里云】失败,{result.message}"); + } else if (DeviceDataV.CancelFileUpLoadSendReplyTopic == topic)//取消文件上传Topic { @@ -315,8 +331,6 @@ namespace BPASmartClient.IoT return property.First().GetValue(info, null); } #endregion - - } //命令实体类 diff --git a/BPASmartClient.IoT/Model/FileUpload.cs b/BPASmartClient.IoT/Model/FileUpload.cs index 97d14551..8407b5a5 100644 --- a/BPASmartClient.IoT/Model/FileUpload.cs +++ b/BPASmartClient.IoT/Model/FileUpload.cs @@ -1,4 +1,5 @@ -using BPASmartDatavDeviceClient.IoT; +using BPASmartClient.Helper; +using BPASmartDatavDeviceClient.IoT; using DataVAPI.Tool.IOT; using System; using System.Collections.Generic; @@ -14,51 +15,51 @@ namespace BPASmartClient.IoT.Model /// public class FileUpload { - public static Dictionary UploadData = new Dictionary(); - public static string FileName=$"HBL.LogDir{DateTime.Now.AddDays(-2).ToString("yyyy_M_d")}"; + public static Dictionary UploadData = new Dictionary(); + public static string FileName = $"HBL.LogDir{DateTime.Now.ToString("yyyy_M_d")}"; public static string path = $"{System.AppDomain.CurrentDomain.BaseDirectory}LogDir\\{FileName}.log"; - public static void SetUploadData(string key,string value) + public static void SetUploadData(string key, string value) { UploadData[key] = value; } public static string GetUploadData(string key) { - return UploadData.ContainsKey(key)? UploadData[key]:string.Empty; + return UploadData.ContainsKey(key) ? UploadData[key] : string.Empty; } /// /// 文件请求上传 /// public static void FileRequest(DataVReport dataV) { - long length= new FileInfo(path).Length; - byte[] FileBlock = File.ReadAllBytes(path); - FileUploadModel fileUpload=new FileUploadModel(); + long length = new FileInfo(path).Length; + byte[] FileBlock = FileContent(path); + FileUploadModel fileUpload = new FileUploadModel(); fileUpload.@params.fileName = FileName; fileUpload.@params.fileSize = length; fileUpload.@params.conflictStrategy = "overwrite";//覆盖模式 //fileUpload.@params.ficMode = "crc64"; //fileUpload.@params.ficValue = CRC.ToCRC16(FileBlock); fileUpload.@params.initUid = $"ab{RandomHelper.GenerateRandomCode()}"; - + //上传到阿里云物联网平台的OSS存储空间中 fileUpload.@params.extraParams.ossOwnerType = "iot-platform"; - + //表示上传到设备所属用户自己的OSS存储空间中 //{ossbucket}/aliyun-iot-device-file/${instanceId}/${productKey}/${serviceId}/${deviceName}/${fileName} //fileUpload.@params.extraParams.ossOwnerType = "device-user"; //fileUpload.@params.extraParams.serviceId = "black"; //fileUpload.@params.extraParams.fileTag = new Dictionary { {"Time", DateTime.Now.ToString("yyyy_M_d") },{"Name", "HBL.LogDir" } }; - - dataV.IOT_Publish(dataV.FileUpLoadTopic,Tools.JsonConvertTools(fileUpload)); + + dataV.IOT_Publish(dataV.FileUpLoadTopic, Tools.JsonConvertTools(fileUpload)); } /// /// 文件上传 /// - public static void FileSend(DataVReport dataV,string uploadId) + public static void FileSend(DataVReport dataV, string uploadId) { long length = new FileInfo(path).Length; - FileSendModel fileSend=new FileSendModel(); + FileSendModel fileSend = new FileSendModel(); fileSend.@params.uploadId = uploadId; fileSend.@params.offset = 0; fileSend.@params.bSize = length; @@ -67,9 +68,9 @@ namespace BPASmartClient.IoT.Model byte[] Header = Encoding.UTF8.GetBytes(Tools.JsonConvertTools(fileSend)); byte HeaderLen_L = (byte)(Header.Length); byte HeaderLen_H = (byte)(Header.Length >> 8); - byte[] FileBlock = File.ReadAllBytes(path);// ReadFile(path); + byte[] FileBlock = FileContent(path); byte[] CRC16 = CRC16Standard.getCRCBytes(FileBlock);//CRC.CRC16(FileBlock); - List message = new List() { HeaderLen_H, HeaderLen_L}; + List message = new List() { HeaderLen_H, HeaderLen_L }; message.AddRange(Header); message.AddRange(FileBlock); message.AddRange(CRC16); @@ -79,12 +80,34 @@ namespace BPASmartClient.IoT.Model /// /// 取消文件上传 /// - public static void FileCancelSend(DataVReport dataV) + public static void FileCancelSend(DataVReport dataV, string uploadId) { - //CancelSend cancel = new CancelSend(); - //dataV.IOT_Publish(dataV.CancelFileUpLoadSendTopic, Tools.JsonConvertTools(cancel)); + CancelSend cancel = new CancelSend(uploadId); + dataV.IOT_Publish(dataV.CancelFileUpLoadSendTopic, Tools.JsonConvertTools(cancel)); } + + /// + /// 读取文件 + /// + /// + /// + private static byte[] FileContent(string fileName) + { + using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) + { + try + { + byte[] buffur = new byte[fs.Length]; + fs.Read(buffur, 0, (int)fs.Length); + return buffur; + } + catch (Exception ex) + { + return new byte[0]; + } + } + } /// /// 读取文件字节 /// @@ -171,7 +194,7 @@ namespace BPASmartClient.IoT.Model /// /// 设备上传文件至OSS存储空间的配置参数 /// - public ConfigureParameters extraParams { get; set; }=new ConfigureParameters(); + public ConfigureParameters extraParams { get; set; } = new ConfigureParameters(); } /// /// 配置参数 @@ -187,14 +210,14 @@ namespace BPASmartClient.IoT.Model /// /// 文件上传相关的业务ID /// - public string serviceId { get; set; } + public string serviceId { get; set; } /// /// 标签 /// public Dictionary fileTag { get; set; } public ConfigureParameters() { - + } } #endregion @@ -222,7 +245,7 @@ namespace BPASmartClient.IoT.Model /// 返回设备端的数据。 /// public ResultData data { get; set; } - + } /// /// 请求响应数据 @@ -323,7 +346,7 @@ namespace BPASmartClient.IoT.Model public CancelSend(string uploadId) { - id= RandomHelper.GenerateRandomCode(); + id = RandomHelper.GenerateRandomCode(); @params = new { uploadId = uploadId }; } } @@ -336,7 +359,7 @@ namespace BPASmartClient.IoT.Model /// /// /// - public static string GenerateRandomCode(int length=10) + public static string GenerateRandomCode(int length = 10) { var result = new StringBuilder(); for (var i = 0; i < length; i++) diff --git a/BPASmartClient.ViewModel/LogViewModel.cs b/BPASmartClient.ViewModel/LogViewModel.cs index 0d137903..c411a2be 100644 --- a/BPASmartClient.ViewModel/LogViewModel.cs +++ b/BPASmartClient.ViewModel/LogViewModel.cs @@ -26,6 +26,9 @@ namespace BPASmartClient.ViewModel public class LogViewModel : ObservableObject { #region 变量 + //定时上报文件到阿里云 + public DispatcherTimer UpDataFileTimer; + //定时清除界面日志 public DispatcherTimer dispatcherTimer; public string ClientId = System.Configuration.ConfigurationManager.AppSettings["ClientId"].ToString(); public ObservableCollection LogDataGridData { get; set; } @@ -231,6 +234,14 @@ namespace BPASmartClient.ViewModel }; dispatcherTimer.Interval = TimeSpan.FromSeconds(10); dispatcherTimer.Start(); + + UpDataFileTimer = new DispatcherTimer(); + UpDataFileTimer.Tick += delegate + { + DataVClient.GetInstance().UpDataFile(); + }; + UpDataFileTimer.Interval = TimeSpan.FromHours(2); + UpDataFileTimer.Start(); } /// /// 增加日志 diff --git a/BPASmartClient/App.config b/BPASmartClient/App.config index 5de4098d..0004434b 100644 --- a/BPASmartClient/App.config +++ b/BPASmartClient/App.config @@ -3,7 +3,7 @@ - + diff --git a/BPASmartClient/MainWindow.xaml.cs b/BPASmartClient/MainWindow.xaml.cs index 9643449a..cfb9fd7a 100644 --- a/BPASmartClient/MainWindow.xaml.cs +++ b/BPASmartClient/MainWindow.xaml.cs @@ -219,8 +219,6 @@ namespace BPASmartClient NoticeDemoViewModel.OpenMsg(EnumPromptType.Error, this, "我是标题", "我是消息内容!我是消息内容!我是消息内容!我是消息内容!"); NoticeDemoViewModel.OpenMsg(EnumPromptType.Warn, this, "我是标题", "我是消息内容!我是消息内容!我是消息内容!我是消息内容!"); NoticeDemoViewModel.OpenMsg(EnumPromptType.Success, this, "我是标题", "我是消息内容!我是消息内容!我是消息内容!我是消息内容!"); - - DataVClient.GetInstance().UpDataFile(); } #endregion From 662d64d287e314ca590dd6a136f12fb3441b9baa Mon Sep 17 00:00:00 2001 From: fyf Date: Fri, 20 May 2022 14:37:09 +0800 Subject: [PATCH 07/11] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E8=8F=9C=E5=8D=95?= =?UTF-8?q?=E6=A0=8F=E6=8C=89=E9=92=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- BPASmartClient/MainWindow.xaml | 62 ++++++++----------------- BPASmartClient/MainWindow.xaml.cs | 76 +++++++++++-------------------- 2 files changed, 46 insertions(+), 92 deletions(-) diff --git a/BPASmartClient/MainWindow.xaml b/BPASmartClient/MainWindow.xaml index dc58adf0..20dac7db 100644 --- a/BPASmartClient/MainWindow.xaml +++ b/BPASmartClient/MainWindow.xaml @@ -228,50 +228,28 @@ Style="{DynamicResource border左上}" /> -