93 lines
3.2 KiB
C#
93 lines
3.2 KiB
C#
|
|
using System.Text;
|
|||
|
|
using Microsoft.AspNetCore.Http;
|
|||
|
|
using Microsoft.AspNetCore.Mvc;
|
|||
|
|
using MySQLAccess.PGModels;
|
|||
|
|
using Newtonsoft.Json;
|
|||
|
|
using NLog;
|
|||
|
|
using ViewModels;
|
|||
|
|
|
|||
|
|
namespace IotManager.Controllers
|
|||
|
|
{
|
|||
|
|
[Route("api/[controller]/[action]")]
|
|||
|
|
[ApiController]
|
|||
|
|
public class MQTTReceiveAPIController : ControllerBase
|
|||
|
|
{
|
|||
|
|
private readonly Logger _logger = LogManager.GetCurrentClassLogger();
|
|||
|
|
private readonly IConfiguration? config;
|
|||
|
|
private PostgresContext IotServerContext { get; set; }
|
|||
|
|
|
|||
|
|
public MQTTReceiveAPIController(IConfiguration config, PostgresContext context)
|
|||
|
|
{
|
|||
|
|
this.config = config;
|
|||
|
|
this.IotServerContext = context;
|
|||
|
|
}
|
|||
|
|
[HttpPost()]
|
|||
|
|
public void ReceiveData()
|
|||
|
|
{
|
|||
|
|
try
|
|||
|
|
{
|
|||
|
|
var readResult = Request.BodyReader.ReadAsync().Result;
|
|||
|
|
Request.BodyReader.AdvanceTo(readResult.Buffer.Start, readResult.Buffer.End);
|
|||
|
|
string body = Encoding.UTF8.GetString(readResult.Buffer.FirstSpan);
|
|||
|
|
|
|||
|
|
if (!string.IsNullOrEmpty(body))
|
|||
|
|
{
|
|||
|
|
Task.Factory.StartNew((state) =>
|
|||
|
|
{
|
|||
|
|
string BodyString = state.ToString();
|
|||
|
|
_logger.Error(body);
|
|||
|
|
var QQQ = System.Text.Json.JsonSerializer.Deserialize<RawPayload>(body);
|
|||
|
|
string topic = QQQ.topic;
|
|||
|
|
string payload = QQQ.payload;
|
|||
|
|
|
|||
|
|
//传递过来的数据就是base64的,没有必要再转
|
|||
|
|
byte[] bbb = Convert.FromBase64String(payload);
|
|||
|
|
string bbb1 = Tools.ByteToString(bbb);
|
|||
|
|
|
|||
|
|
this._logger.Info("Topic: " + topic);
|
|||
|
|
this._logger.Info("PayLoad: " + bbb1);
|
|||
|
|
|
|||
|
|
|
|||
|
|
byte[] NNN1 = Tools.HEXString2ByteArray(bbb1.Replace(" ", ""));
|
|||
|
|
//AA 13 00 44 0B 00 FF FF FF FF 61 67 EF 6B E8 2D 2D 0D 0A 2D 2D
|
|||
|
|
|
|||
|
|
byte Header = NNN1[0];
|
|||
|
|
//从1到3之间的元素,不包括3
|
|||
|
|
byte[] Len = NNN1[1..3];
|
|||
|
|
//byte[] Len = NNN1.AsSpan(1,2);
|
|||
|
|
byte[] Pack_SN = NNN1[3..5];
|
|||
|
|
|
|||
|
|
//重发次数
|
|||
|
|
byte RetryCount = NNN1[5];
|
|||
|
|
|
|||
|
|
//设备编号
|
|||
|
|
byte[] DeviceOnlyNo = NNN1[6..10];
|
|||
|
|
|
|||
|
|
//命令字
|
|||
|
|
byte[] Command = NNN1[10..12];
|
|||
|
|
|
|||
|
|
|
|||
|
|
//校验CRC16,小端模式(低地址在前)
|
|||
|
|
//校验内容:Pack_Head + Pack_LEN + Pack_SN + Retry_Num + Client_ID + CMD + PARA
|
|||
|
|
byte[] CRCCode = NNN1[^8..^6];
|
|||
|
|
|
|||
|
|
//结尾标志符
|
|||
|
|
//// 获取从倒数第三个元素到数组末尾的所有元素
|
|||
|
|
byte[] Tail = NNN1[^6..];
|
|||
|
|
|
|||
|
|
}, body);
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
catch (Exception)
|
|||
|
|
{
|
|||
|
|
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
public class RawPayload
|
|||
|
|
{
|
|||
|
|
public string topic { get; set; }
|
|||
|
|
public string payload { get; set; }
|
|||
|
|
}
|
|||
|
|
}
|