From 83c0bd32c1e7a57f7bfd955137dff638c6650f22 Mon Sep 17 00:00:00 2001 From: fyf Date: Fri, 20 May 2022 13:13:22 +0800 Subject: [PATCH] =?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