Quellcode durchsuchen

更新IOT上报日志文件

样式分支
fyf vor 2 Jahren
Ursprung
Commit
83c0bd32c1
9 geänderte Dateien mit 972 neuen und 19 gelöschten Zeilen
  1. +1
    -1
      BPASmartClient.DRCoffee/CoffeeMachine.cs
  2. +1
    -0
      BPASmartClient.IoT/BPASmartClient.IoT.csproj
  3. +34
    -0
      BPASmartClient.IoT/DataVClient.cs
  4. +247
    -0
      BPASmartClient.IoT/Model/CRC.cs
  5. +63
    -13
      BPASmartClient.IoT/Model/DataVReport.cs
  6. +350
    -0
      BPASmartClient.IoT/Model/FileUpload.cs
  7. +269
    -0
      BPASmartClient.IoT/Model/OSS_Helper.cs
  8. +5
    -5
      BPASmartClient/App.config
  9. +2
    -0
      BPASmartClient/MainWindow.xaml.cs

+ 1
- 1
BPASmartClient.DRCoffee/CoffeeMachine.cs Datei anzeigen

@@ -164,7 +164,7 @@ namespace BPASmartClient.DRCoffee
{
status["Status"] = DrCoffeeStatus.Wait;
status["AppStatus"] = DrCoffeeAppStatus.应用无状态;
status["Warning"] = DrCoffeeWarning.冲泡器未安装到位;
status["Warning"] = DrCoffeeWarning.无警告;
status["Fault"] = DrCoffeeFault.无故障;
}



+ 1
- 0
BPASmartClient.IoT/BPASmartClient.IoT.csproj Datei anzeigen

@@ -5,6 +5,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Aliyun.OSS.SDK" Version="2.13.0" />
<PackageReference Include="M2Mqtt" Version="4.3.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="System.Configuration.ConfigurationManager" Version="6.0.0" />


+ 34
- 0
BPASmartClient.IoT/DataVClient.cs Datei anzeigen

@@ -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);
}

/// <summary>
/// 文件上传请求
/// </summary>
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<FileUploadModelResult>(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<FileUploadModelResult>(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<FileUploadModelResult>(message);
}
}

/// <summary>


+ 247
- 0
BPASmartClient.IoT/Model/CRC.cs Datei anzeigen

@@ -0,0 +1,247 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BPASmartClient.IoT.Model
{
/// <summary>
/// CRC校验
/// </summary>
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();
}

/// <summary>
/// 字符串转16进制字符数组
/// </summary>
/// <param name="hex"></param>
/// <returns></returns>
public static byte[] StringToHexByte(string str)
{
return StringToHexByte(str, false);
}

/// <summary>
/// 字符串转16进制字符数组
/// </summary>
/// <param name="str"></param>
/// <param name="isFilterChinese">是否过滤掉中文字符</param>
/// <returns></returns>
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) };
}
}
}

+ 63
- 13
BPASmartClient.IoT/Model/DataVReport.cs Datei anzeigen

@@ -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
/// <summary>
/// 初始化IOT连接
/// </summary>
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);
}

/// <summary>
/// 订阅主题
/// </summary>
@@ -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 私有函数
/// <summary>
/// 设置变量
@@ -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";
}

/// <summary>
/// 创建连接
/// </summary>
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<List<DeviceTable>> jsonMsg = Tools.JsonToObjectTools<JsonMsg<List<DeviceTable>>>(json);
@@ -224,7 +252,7 @@ namespace BPASmartDatavDeviceClient.IoT
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Client_ConnectionClosed(object sender, EventArgs e)
private void Client_ConnectionClosed(object sender, EventArgs e)
{
// 尝试重连
_TryContinueConnect();
@@ -235,7 +263,7 @@ namespace BPASmartDatavDeviceClient.IoT
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
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
/// <summary>
/// 自动重连主体
/// </summary>
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
/// <summary>
/// 设备消息数据回调
/// </summary>
public Action<string,string, string> DataVMessageAction { get; set; }
public Action<string, string, string> DataVMessageAction { get; set; }
/// <summary>
/// 重连事件
/// </summary>
@@ -324,7 +352,7 @@ namespace BPASmartDatavDeviceClient.IoT
/// <summary>
/// 当前设备
/// </summary>
public DeviceTable deviceTable =new DeviceTable();
public DeviceTable deviceTable = new DeviceTable();
#endregion

#region 发布或订阅主题或URL地址
@@ -369,10 +397,30 @@ namespace BPASmartDatavDeviceClient.IoT
/// </summary>
public string BroadcastTopic = "/broadcast/" + "grgpECHSL7q" + "/" + DeviceName + "_SetDevice";
/// <summary>
/// 文件上Topic
/// 文件上传请求Topic
/// </summary>
public string FileUpLoadTopic = $"/sys/{ProductKey}/{DeviceName}/thing/file/upload/mqtt/init";
/// <summary>
/// 文件上传请求响应Topic
/// </summary>
public string FileUpLoadReplyTopic = $"/sys/{ProductKey}/{DeviceName}/thing/file/upload/mqtt/init_reply";
/// <summary>
/// 文件发送Topic
/// </summary>
public string FileUpLoadSendTopic = $"/sys/{ProductKey}/{DeviceName}/thing/file/upload/mqtt/send";
/// <summary>
/// 文件发送响应Topic
/// </summary>
public string FileUpLoadSendReplyTopic = $"/sys/{ProductKey}/{DeviceName}/thing/file/upload/mqtt/send_reply";
/// <summary>
/// 取消文件发送Topic
/// </summary>
public string CancelFileUpLoadSendTopic = $"/sys/{ProductKey}/{DeviceName}/thing/file/upload/mqtt/cancel";
/// <summary>
/// 取消文件发送响应Topic
/// </summary>
public string CancelFileUpLoadSendReplyTopic = $"/sys/{ProductKey}/{DeviceName}/thing/file/upload/mqtt/cancel_reply";
/// <summary>
/// 订阅主题集合
/// </summary>
public static List<string> SubTopicList = new List<string>();
@@ -409,4 +457,6 @@ namespace BPASmartDatavDeviceClient.IoT
return signBuilder.ToString();
}
}


}

+ 350
- 0
BPASmartClient.IoT/Model/FileUpload.cs Datei anzeigen

@@ -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
{
/// <summary>
/// 阿里云文件上传
/// </summary>
public class FileUpload
{
public static Dictionary<string, string> UploadData = new Dictionary<string, string>();
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;
}
/// <summary>
/// 文件请求上传
/// </summary>
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<string, string> { {"Time", DateTime.Now.ToString("yyyy_M_d") },{"Name", "HBL.LogDir" } };
dataV.IOT_Publish(dataV.FileUpLoadTopic,Tools.JsonConvertTools(fileUpload));
}

/// <summary>
/// 文件上传
/// </summary>
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<byte> message = new List<byte>() { HeaderLen_H, HeaderLen_L};
message.AddRange(Header);
message.AddRange(FileBlock);
message.AddRange(CRC16);
dataV.IOT_Publish(dataV.FileUpLoadSendTopic, message.ToArray());
}

/// <summary>
/// 取消文件上传
/// </summary>
public static void FileCancelSend(DataVReport dataV)
{
//CancelSend cancel = new CancelSend();
//dataV.IOT_Publish(dataV.CancelFileUpLoadSendTopic, Tools.JsonConvertTools(cancel));
}

/// <summary>
/// 读取文件字节
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
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 请求上传文件
/// <summary>
/// 请求上传文件
/// </summary>
public class FileUploadModel
{
/// <summary>
/// 消息ID号
/// 0~4294967295
/// </summary>
public string id { get; set; }
/// <summary>
/// 请求业务参数
/// </summary>
public BusinessParameters @params { get; set; }

public FileUploadModel()
{
id = RandomHelper.GenerateRandomCode();
@params = new BusinessParameters();
}
}

/// <summary>
/// 业务参数
/// </summary>
public class BusinessParameters
{
/// <summary>
/// 设备上传文件的名称
/// </summary>
public string fileName { get; set; }
/// <summary>
/// 上传文件大小,单位字节。单个文件大小不超过16 MB。
/// 取值为-1时,表示文件大小未知。文件上传完成时,需在上传文件分片的消息中,指定参数isComplete
/// </summary>
public long fileSize { get; set; }
/// <summary>
/// 物联网平台对设备上传同名文件的处理策略,默认为overwrite
/// overwrite:覆盖模式 append:文件追加模式 reject:拒绝模式
/// </summary>
public string conflictStrategy { get; set; } = "overwrite";
/// <summary>
/// 文件的完整性校验模式,目前可取值crc64
/// 若不传入,在文件上传完成后不校验文件完整性
/// </summary>
public string ficMode { get; set; }
/// <summary>
/// 文件的完整性校验值,是16位的Hex格式编码的字符串
/// </summary>
public string ficValue { get; set; }
/// <summary>
/// 自定义的设备请求上传文件的任务唯一ID,同一上传任务请求必须对应相同的唯一ID
/// 不传入:物联网平台的云端识别当前请求为新的文件上传请求
/// </summary>
public string initUid { get; set; }
/// <summary>
/// 设备上传文件至OSS存储空间的配置参数
/// </summary>
public ConfigureParameters extraParams { get; set; }=new ConfigureParameters();
}
/// <summary>
/// 配置参数
/// </summary>
public class ConfigureParameters
{
/// <summary>
/// 设备上传文件的目标OSS所有者类型
/// iot-platform:表示上传到阿里云物联网平台的OSS存储空间中
/// device-user:表示上传到设备所属用户自己的OSS存储空间中
/// </summary>
public string ossOwnerType { get; set; } = "device-user";
/// <summary>
/// 文件上传相关的业务ID
/// </summary>
public string serviceId { get; set; }
/// <summary>
/// 标签
/// </summary>
public Dictionary<string, string> fileTag { get; set; }
public ConfigureParameters()
{
}
}
#endregion

#region 请求上传文件响应
/// <summary>
/// 请求响应
/// </summary>
public class FileUploadModelResult
{
/// <summary>
/// 消息ID号
/// 0~4294967295
/// </summary>
public string id { get; set; }
/// <summary>
/// 结果码。返回200表示成功
/// </summary>
public int code { get; set; }
/// <summary>
/// 请求失败时,返回的错误信息
/// </summary>
public string message { get; set; }
/// <summary>
/// 返回设备端的数据。
/// </summary>
public ResultData data { get; set; }
}
/// <summary>
/// 请求响应数据
/// </summary>
public class ResultData
{
/// <summary>
/// 设备上传文件的名称
/// </summary>
public string fileName { get; set; }
/// <summary>
/// 本次上传文件任务的标识ID。后续上传文件分片时,需要传递该文件标识ID。
/// </summary>
public string uploadId { get; set; }
/// <summary>
/// 仅当请求参数conflictStrategy为append,且物联网平台云端存在未完成上传的文件时,返回的已上传文件的大小,单位为字节。
/// </summary>
public long offset { get; set; }
/// <summary>
/// 当前上传文件分片的大小
/// </summary>
public long bSize { get; set; }
/// <summary>
/// 当上传了最后一个分片数据后,文件上传完成
/// </summary>
public bool complete { get; set; }
/// <summary>
/// 文件的完整性校验模式。若请求上传文件时传入了该参数,对应的值仅支持为crc64
/// </summary>
public string ficMode { get; set; }
/// <summary>
/// 文件上传完成,返回设备请求上传文件时的
/// </summary>
public string ficValueClient { get; set; }
/// <summary>
/// 文件上传完成,返回物联网平台云端计算的文件完整性校验值。该值与ficValueClient值相同,表示文件上传完整。
/// </summary>
public string ficValueServer { get; set; }
}
#endregion

#region 上传文件
public class FileSendModel
{
/// <summary>
/// 消息ID号
/// 0~4294967295
/// </summary>
public string id { get; set; }
/// <summary>
/// 上传业务参数
/// </summary>
public SendBusinessParameters @params { get; set; } = new SendBusinessParameters();
public FileSendModel()
{
id = RandomHelper.GenerateRandomCode();
}
}
/// <summary>
/// 上传业务参数
/// </summary>
public class SendBusinessParameters
{
/// <summary>
/// 设备请求上传文件时返回的文件上传任务标识ID。
/// </summary>
public string uploadId { get; set; }
/// <summary>
/// 已上传文件分片的总大小,单位为字节。
/// </summary>
public long offset { get; set; }
/// <summary>
/// 当前上传文件分片的大小,单位为字节
/// </summary>
public long bSize { get; set; }
/// <summary>
/// 仅当设备请求上传文件中fileSize为-1,即文件大小未知时,该参数有效,表示当前分片是否是文件的最后一个分片
/// </summary>
public bool isComplete { get; set; } = true;
}
#endregion

#region 取消文件上传
/// <summary>
/// 取消上传
/// </summary>
public class CancelSend
{
/// <summary>
/// 消息ID号
/// 0~4294967295
/// </summary>
public string id { get; set; }
/// <summary>
/// 请求业务参数
/// </summary>
public object @params { get; set; }

public CancelSend(string uploadId)
{
id= RandomHelper.GenerateRandomCode();
@params = new { uploadId = uploadId };
}
}
#endregion

public class RandomHelper
{
/// <summary>
///生成制定位数的随机码(数字)
/// </summary>
/// <param name="length"></param>
/// <returns></returns>
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();
}
}
}

+ 269
- 0
BPASmartClient.IoT/Model/OSS_Helper.cs Datei anzeigen

@@ -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。*/
/// <summary>
///
/// </summary>
/// <param name="objectName"></param>
/// <param name="localFilename"></param>
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);
}
}
/// <summary>
/// 分片上传
/// </summary>
/// <param name="objectName"></param>
/// <param name="localFilename"></param>
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<PartETag>();
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;
}

}
/// <summary>
/// 上传
/// </summary>
/// <param name="objectName"></param>
/// <param name="localFilename"></param>
/// <param name="checkpointDir"></param>
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);
}

}
/// <summary>
/// 下载文件
/// </summary>
/// <param name="objectName"></param>
/// <param name="downloadFilename"></param>
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 = "<yourEndpoint>";
var accessKeyId = "<yourAccessKeyId>";
var accessKeySecret = "<yourAccessKeySecret>";
var bucketName = "<yourBucketName>";
var objectName = "<yourObjectName>";
// 创建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);
}

}
}

+ 5
- 5
BPASmartClient/App.config Datei anzeigen

@@ -3,7 +3,7 @@
<appSettings>
<!--通用配置-->
<!--1:且时且多冰淇淋咖啡机,2:且时且多煮面机,3:海科煮面机测试店铺-->
<add key="ClientId" value="48"/>
<add key="ClientId" value="250"/>
<!--<add key="ApolloUri" value="http://10.2.1.21:28080"/>
<add key="OrderServiceUri" value="http://10.2.1.26:21527/order/"/>
<add key="StockServiceUri" value="http://10.2.1.26:21527/stock/"/>-->
@@ -12,7 +12,7 @@
<!--<add key="ClientId" value="2"/>-->

<!--开发环境-->
<add key="apollouri" value="http://10.2.1.21:28080"/>
<!--<add key="apollouri" value="http://10.2.1.21:28080"/>
<add key="orderserviceuri" value="https://bpa.black-pa.com:21527/order/"/>
<add key="stockserviceuri" value="https://bpa.black-pa.com:21527/stock/"/>
<add key="datavserviceuri" value="https://bpa.black-pa.com:21527/datav"/>
@@ -20,7 +20,7 @@
<add key="broadcastpubtopic" value="/broadcast/grgpechsl7q/transit_test_setdevice"/>
<add key="AppId" value="dev1_common"/>
<add key ="Namespaces" value="DEV.Config"/>
<add key="IsEnableTest" value="False"/>
<add key="IsEnableTest" value="False"/>-->



@@ -37,7 +37,7 @@
<add key ="Namespaces" value="DEV.test1.Config"/>-->

<!--正式环境-->
<!--
<add key="ApolloUri" value="http://47.108.65.220:28080"/>
<add key="OrderServiceUri" value="https://witt.black-pa.com/order/"/>
<add key="StockServiceUri" value="https://witt.black-pa.com/stock/"/>
@@ -46,7 +46,7 @@
<add key="BroadcastPubTopic" value="/broadcast/grgpECHSL7q/Transit_SetDevice"/>
<add key="AppId" value="order"/>
<add key ="Namespaces" value="TEST1.Config"/>
<add key="IsEnableTest" value="False"/>-->
<add key="IsEnableTest" value="False"/>

<!--阿里云上报启动方式:API 或者 LOCAL-->
<!--API :通过客户端ID,调用接口查询“设备连接信息”-->


+ 2
- 0
BPASmartClient/MainWindow.xaml.cs Datei anzeigen

@@ -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


Laden…
Abbrechen
Speichern