初始化
This commit is contained in:
13
EMQX_HttpAuth/.config/dotnet-tools.json
Normal file
13
EMQX_HttpAuth/.config/dotnet-tools.json
Normal file
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"version": 1,
|
||||
"isRoot": true,
|
||||
"tools": {
|
||||
"dotnet-ef": {
|
||||
"version": "9.0.4",
|
||||
"commands": [
|
||||
"dotnet-ef"
|
||||
],
|
||||
"rollForward": false
|
||||
}
|
||||
}
|
||||
}
|
||||
561
EMQX_HttpAuth/Controllers/SocketTcpController.cs
Normal file
561
EMQX_HttpAuth/Controllers/SocketTcpController.cs
Normal file
@@ -0,0 +1,561 @@
|
||||
using System.Data;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using Common;
|
||||
using CommonEntity;
|
||||
using LogCap.Common;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.Diagnostics;
|
||||
using NLog;
|
||||
using RestSharp;
|
||||
using RestSharp.Authenticators;
|
||||
using ViewModels;
|
||||
|
||||
namespace EMQX_HttpAuth.Controllers
|
||||
{
|
||||
[Route("api/[controller]/[action]")]
|
||||
[ApiController]
|
||||
public class SocketTcpController : ControllerBase
|
||||
{
|
||||
private readonly Logger _logger = LogManager.GetCurrentClassLogger();
|
||||
public static string tcp_server = "http://localhost:8086";
|
||||
public static string mqtt_server = "http://43.138.217.154:18083";
|
||||
public IList<char> HexSet = new List<char>() { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'a', 'b', 'c', 'd', 'e', 'f' };
|
||||
public IConfiguration Configuration { get; set; }
|
||||
public SocketTcpController(IConfiguration config)
|
||||
{
|
||||
this.Configuration = config;
|
||||
}
|
||||
/// <summary>
|
||||
/// 获取所有在线的 下位机 客户端,返回的数据是 IP:端口的形式
|
||||
/// </summary>
|
||||
/// <param name="data"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPost()]
|
||||
async public Task<string> Get_all_TCPClients([FromBody] Data data)
|
||||
{
|
||||
RestClient client1 = new RestClient(tcp_server);
|
||||
//Console.WriteLine("发送MQTT的数据为:" + str);
|
||||
var request1 = new RestRequest("/blw/tcphandle", Method.Post);
|
||||
|
||||
//注意方法是POST
|
||||
//Console.WriteLine("Topic: " + debug_log_report_mqtt_topic);
|
||||
request1.AddParameter("cmd", "get_tcp_info");
|
||||
request1.AddParameter("parameterlist", "");
|
||||
|
||||
var Q = await client1.ExecuteAsync(request1);
|
||||
return Q.Content;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取所有在线的MQTTClient
|
||||
/// </summary>
|
||||
/// <param name="data"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPost()]
|
||||
async public Task<object> Get_all_MQTTClients([FromBody] QueryData data)
|
||||
{
|
||||
string? Key = Configuration["Key"];
|
||||
string? Security = Configuration["Security"];
|
||||
var option = new RestClientOptions()
|
||||
{
|
||||
BaseUrl = new Uri(mqtt_server),
|
||||
Authenticator = new HttpBasicAuthenticator(Key, Security)
|
||||
|
||||
};
|
||||
RestClient client1 = new RestClient(option);
|
||||
|
||||
//Console.WriteLine("发送MQTT的数据为:" + str);
|
||||
var request1 = new RestRequest("/api/v5/clients", Method.Get);
|
||||
|
||||
//注意方法是POST
|
||||
//Console.WriteLine("Topic: " + debug_log_report_mqtt_topic);
|
||||
request1.AddQueryParameter("limit", data.Limit);
|
||||
request1.AddQueryParameter("page", data.Page);
|
||||
request1.AddQueryParameter("isTrusted", true);
|
||||
|
||||
var Q = await client1.ExecuteAsync(request1);
|
||||
|
||||
|
||||
//返回的数据是
|
||||
//{
|
||||
// "data": [
|
||||
// {
|
||||
// "recv_oct": 147525,
|
||||
// "send_msg.dropped.expired": 0,
|
||||
// "recv_msg.qos0": 0,
|
||||
// "inflight_max": 32,
|
||||
// "recv_msg.qos1": 3320,
|
||||
// "send_msg.qos0": 0,
|
||||
// "recv_msg.qos2": 0,
|
||||
// "expiry_interval": 0,
|
||||
// "send_msg.dropped": 0,
|
||||
// "mqueue_len": 0,
|
||||
// "proto_ver": 5,
|
||||
// "keepalive": 60,
|
||||
// "inflight_cnt": 0,
|
||||
// "node": "emqx@127.0.0.1",
|
||||
// "created_at": "2025-06-09T16:08:38.394+08:00",
|
||||
// "send_cnt": 9436,
|
||||
// "ip_address": "43.138.217.154",
|
||||
// "clean_start": true,
|
||||
// "proto_name": "MQTT",
|
||||
// "enable_authn": true,
|
||||
// "mountpoint": null,
|
||||
// "is_persistent": false,
|
||||
// "send_msg.qos1": 6113,
|
||||
// "send_msg.dropped.too_large": 0,
|
||||
// "send_oct": 331649,
|
||||
// "recv_msg": 3320,
|
||||
// "heap_size": 6772,
|
||||
// "username": "admin",
|
||||
// "send_msg.dropped.queue_full": 0,
|
||||
// "send_msg": 6113,
|
||||
// "clientid": "newemqttclient",
|
||||
// "subscriptions_max": "infinity",
|
||||
// "mqueue_max": 1000,
|
||||
// "recv_pkt": 9436,
|
||||
// "user_property": {},
|
||||
// "port": 36036,
|
||||
// "connected_at": "2025-06-09T16:08:38.394+08:00",
|
||||
// "mailbox_len": 0,
|
||||
// "recv_msg.dropped": 0,
|
||||
// "subscriptions_cnt": 1,
|
||||
// "is_bridge": false,
|
||||
// "awaiting_rel_max": 100,
|
||||
// "awaiting_rel_cnt": 0,
|
||||
// "mqueue_dropped": 0,
|
||||
// "send_pkt": 9436,
|
||||
// "send_msg.qos2": 0,
|
||||
// "recv_msg.dropped.await_pubrel_timeout": 0,
|
||||
// "connected": true,
|
||||
// "reductions": 130011309,
|
||||
// "recv_cnt": 9436,
|
||||
// "listener": "tcp:default"
|
||||
// }
|
||||
// ],
|
||||
// "meta": {
|
||||
// "count": 3,
|
||||
// "limit": 20,
|
||||
// "page": 1,
|
||||
// "hasnext": false
|
||||
// }
|
||||
//}
|
||||
|
||||
var DDD = System.Text.Json.JsonSerializer.Deserialize<MQTTData>(Q.Content);
|
||||
|
||||
var DDD1 = DDD.data.Select(A => new NiMingOO
|
||||
{
|
||||
Listener = A["listener"].ToString(),
|
||||
UserName = A["username"].ToString(),
|
||||
WWWWIP = A["ip_address"].ToString(),
|
||||
WWWWPort = A["port"].ToString(),
|
||||
ClientId = A["clientid"].ToString(),
|
||||
Connected = A["connected"].ToString(),
|
||||
connected_DateTime = A["connected_at"].ToString()
|
||||
}).ToList();
|
||||
return DDD1;
|
||||
}
|
||||
|
||||
|
||||
public static string FrameNoKey = "FrameNoKey";
|
||||
|
||||
|
||||
|
||||
[HttpPost()]
|
||||
async public Task<RMsg> send_data_to_target([FromBody] Data data)
|
||||
{
|
||||
RMsg r = new RMsg();
|
||||
try
|
||||
{
|
||||
|
||||
RestClient client1 = new RestClient(tcp_server);
|
||||
var request1 = new RestRequest("/blw/tcphandle", Method.Post);
|
||||
request1.AddParameter("cmd", data.Cmd);
|
||||
|
||||
var VData = data.Parameterlist;
|
||||
string? HHH1 = VData.data;
|
||||
string? HHH2 = HHH1.Replace(" ", "");
|
||||
if (IsIllegalHexadecimal(HHH2) == false)
|
||||
{
|
||||
request1.AddParameter("parameterlist", JsonSerializer.Serialize(VData));
|
||||
var Q = await client1.ExecuteAsync(request1);
|
||||
r.isok = true;
|
||||
r.message = "success";
|
||||
}
|
||||
else
|
||||
{
|
||||
r.isok = false;
|
||||
r.message = "错误,发送的数据必须是 16进制";
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
r.message = ex.Message;
|
||||
r.isok = false;
|
||||
}
|
||||
return r;
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 发送控制数据
|
||||
/// 也可以 发送控制指令通过clientid
|
||||
/// 接口加好了。发送控制指令接口 地址:
|
||||
///http://iot-manage.uts-data.com:5001/api/sockettcp/send_data_to_targetnew
|
||||
///
|
||||
///发送数据如下:
|
||||
///{
|
||||
/// "Cmd": "tcp_send_data_clientid",
|
||||
/// "Parameterlist": {
|
||||
/// "device_clientid": "71",
|
||||
/// "command_word":"04",
|
||||
/// "data": "AA BB CC DD EE FF AA FF AA"
|
||||
/// }
|
||||
///}
|
||||
///command_word 是命令字,device_clientid是CID。data 是要发送的 控制数据
|
||||
/// </summary>
|
||||
/// <param name="data"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPost()]
|
||||
async public Task<RMsg> send_data_to_targetnew([FromBody] Data data)
|
||||
{
|
||||
RMsg r = new RMsg();
|
||||
try
|
||||
{
|
||||
var KKK = CSRedisCacheHelper.ForeverGet<ushort>(FrameNoKey);
|
||||
if (KKK == 0)
|
||||
{
|
||||
CSRedisCacheHelper.Forever(FrameNoKey, 0);
|
||||
}
|
||||
else
|
||||
{
|
||||
CSRedisCacheHelper.GenericSerNo(FrameNoKey);
|
||||
}
|
||||
|
||||
ushort Xuhao = CSRedisCacheHelper.ForeverGet<ushort>(FrameNoKey);
|
||||
ushort NewXuHao = 0;
|
||||
if (Xuhao == ushort.MaxValue)
|
||||
{
|
||||
NewXuHao = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
NewXuHao = (ushort)(Xuhao + 1);
|
||||
}
|
||||
|
||||
CSRedisCacheHelper.Forever<ushort>(FrameNoKey, NewXuHao);
|
||||
|
||||
RestClient client1 = new RestClient(tcp_server);
|
||||
var request1 = new RestRequest("/blw/tcphandle", Method.Post);
|
||||
|
||||
//cmd 是 tcp_send_data
|
||||
request1.AddParameter("cmd", data.Cmd);
|
||||
|
||||
var VData = data.Parameterlist;
|
||||
|
||||
|
||||
//组装命令
|
||||
List<byte> lll = new List<byte>();
|
||||
//包头
|
||||
lll.Add(0xAA);
|
||||
|
||||
//整包长度
|
||||
lll.Add(0x00);
|
||||
lll.Add(0x00);
|
||||
|
||||
//包序号
|
||||
byte[] XXX = BitConverter.GetBytes(NewXuHao);
|
||||
lll.AddRange(XXX);
|
||||
|
||||
//重发次数
|
||||
lll.Add(0x00);
|
||||
|
||||
string SSS = VData.device_clientid;
|
||||
int SXSX = int.Parse(SSS);
|
||||
//设备序列号
|
||||
byte[] SXBy = BitConverter.GetBytes(SXSX);
|
||||
lll.AddRange(SXBy);
|
||||
|
||||
|
||||
// 要加密的数据
|
||||
List<byte> 加密数据表 = new List<byte>();
|
||||
|
||||
//命令字
|
||||
var UUU = VData.command_word;
|
||||
ushort III = ushort.Parse(UUU);
|
||||
byte[] CCC = BitConverter.GetBytes(III);
|
||||
|
||||
加密数据表.AddRange(CCC);
|
||||
|
||||
string? HHH1 = VData.data;
|
||||
string? HHH2 = HHH1.Replace(" ", "");
|
||||
|
||||
byte[] finally_data = Tools.HEXString2ByteArray(HHH2);
|
||||
加密数据表.AddRange(finally_data);
|
||||
|
||||
//将数据头复制一份
|
||||
//List<byte> jisuan = new List<byte>(lll);
|
||||
//加上数据段部分
|
||||
//jisuan.AddRange(加密数据表);
|
||||
//jisuan.Add(0x00);
|
||||
//jisuan.Add(0x00);
|
||||
//var dainfo = jisuan.ToArray();
|
||||
//byte[] CRCList = BitConverter.GetBytes(crc);
|
||||
//加密数据表.AddRange(CRCList);
|
||||
|
||||
|
||||
byte[] key = new byte[] { };
|
||||
var TST = CSRedisCacheHelper.HMGet<string>(0, CacheKey.DeviceInfo, VData.device_clientid);
|
||||
if (TST != null)
|
||||
{
|
||||
if (TST[0] != null)
|
||||
{
|
||||
key = Encoding.ASCII.GetBytes(TST[0]);
|
||||
}
|
||||
else
|
||||
{
|
||||
key = Encoding.ASCII.GetBytes("abcdefg123456");
|
||||
}
|
||||
}
|
||||
byte[] decryptedContent = Tools.IHIOT_Message_Content_Encrypt(NewXuHao, key, 加密数据表.ToArray());
|
||||
|
||||
lll.AddRange(decryptedContent);
|
||||
|
||||
|
||||
var dainfo = lll.ToArray();
|
||||
|
||||
int changdu = dainfo.Length;
|
||||
|
||||
changdu = changdu + 2 + 6;
|
||||
|
||||
ushort sss1 = (ushort)changdu;
|
||||
byte[] bas = BitConverter.GetBytes(sss1);
|
||||
|
||||
dainfo[1] = bas[0];
|
||||
dainfo[2] = bas[1];
|
||||
|
||||
//CRC
|
||||
ushort crc = Tools.CRC16(dainfo, dainfo.Length);//最后两个字节,加CRC16校验
|
||||
//dainfo[dainfo.Length - 2] = Convert.ToByte(crc & 0xff);
|
||||
//dainfo[dainfo.Length - 1] = Convert.ToByte((crc >> 8) & 0xff);
|
||||
|
||||
|
||||
var USB = dainfo.ToList();
|
||||
byte[] CRCList = BitConverter.GetBytes(crc);
|
||||
|
||||
USB.AddRange(CRCList);
|
||||
USB.AddRange(new byte[] { 0x2D, 0x2D, 0x0D, 0x0A, 0x2D, 0x2D });
|
||||
|
||||
var CMDdata = USB.ToArray();
|
||||
VData.data = Tools.ByteToString(CMDdata);
|
||||
|
||||
if (IsIllegalHexadecimal(HHH2) == false)
|
||||
{
|
||||
request1.AddParameter("parameterlist", JsonSerializer.Serialize(VData));
|
||||
var Q = await client1.ExecuteAsync(request1);
|
||||
r.isok = true;
|
||||
r.message = "success";
|
||||
}
|
||||
else
|
||||
{
|
||||
r.isok = false;
|
||||
r.message = "错误,发送的数据必须是 16进制";
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
r.message = ex.Message + ex.StackTrace;
|
||||
r.isok = false;
|
||||
}
|
||||
return r;
|
||||
|
||||
}
|
||||
|
||||
|
||||
[HttpPost()]
|
||||
async public Task<RMsg> send_data_to_lowermachine([FromBody] Data data)
|
||||
{
|
||||
RMsg r = new RMsg();
|
||||
try
|
||||
{
|
||||
var KKK = CSRedisCacheHelper.ForeverGet<ushort>(FrameNoKey);
|
||||
if (KKK == 0)
|
||||
{
|
||||
CSRedisCacheHelper.Forever(FrameNoKey, 0);
|
||||
}
|
||||
else
|
||||
{
|
||||
CSRedisCacheHelper.GenericSerNo(FrameNoKey);
|
||||
}
|
||||
|
||||
var Xuhao = CSRedisCacheHelper.ForeverGet<ushort>(FrameNoKey);
|
||||
|
||||
RestClient client1 = new RestClient(tcp_server);
|
||||
var request1 = new RestRequest("/blw/tcphandle", Method.Post);
|
||||
|
||||
//cmd 是 tcp_send_data
|
||||
request1.AddParameter("cmd", data.Cmd);
|
||||
|
||||
var VData = data.Parameterlist;
|
||||
//var HHH = JsonSerializer.Deserialize<SendData>(VData);
|
||||
List<byte> lll = new List<byte>();
|
||||
//包头
|
||||
lll.Add(0xAA);
|
||||
|
||||
//整包长度
|
||||
lll.Add(0x00);
|
||||
lll.Add(0x00);
|
||||
|
||||
//包序号
|
||||
byte[] XXX = BitConverter.GetBytes(Xuhao);
|
||||
lll.AddRange(XXX);
|
||||
|
||||
//重发次数
|
||||
lll.Add(0x00);
|
||||
|
||||
string SSS = VData.device_clientid;
|
||||
int SXSX = int.Parse(SSS);
|
||||
//设备序列号
|
||||
byte[] SXBy = BitConverter.GetBytes(SXSX);
|
||||
lll.AddRange(SXBy);
|
||||
|
||||
|
||||
List<byte> lll_new = new List<byte>(lll.ToArray());
|
||||
//命令字
|
||||
List<byte> jia_mi_bytes = new List<byte>();
|
||||
var UUU = VData.command_word;
|
||||
ushort III = ushort.Parse(UUU);
|
||||
byte[] CCC = BitConverter.GetBytes(III);
|
||||
lll.AddRange(CCC);
|
||||
|
||||
jia_mi_bytes.AddRange(CCC);
|
||||
|
||||
|
||||
string? HHH1 = VData.data;
|
||||
string? HHH2 = HHH1.Replace(" ", "");
|
||||
|
||||
byte[] finally_data = Tools.HEXString2ByteArray(HHH2);
|
||||
|
||||
lll.AddRange(finally_data);
|
||||
jia_mi_bytes.AddRange(finally_data);
|
||||
|
||||
lll.Add(0x00);
|
||||
lll.Add(0x00);
|
||||
|
||||
var dainfo = lll.ToArray();
|
||||
|
||||
//CRC
|
||||
ushort crc = Tools.CRC16(dainfo, dainfo.Length - 2);//最后两个字节,加CRC16校验
|
||||
dainfo[dainfo.Length - 2] = Convert.ToByte(crc & 0xff);
|
||||
dainfo[dainfo.Length - 1] = Convert.ToByte((crc >> 8) & 0xff);
|
||||
|
||||
var dataF = dainfo.ToList();
|
||||
byte[] CRCList = BitConverter.GetBytes(crc);
|
||||
|
||||
jia_mi_bytes.AddRange(CRCList);
|
||||
|
||||
byte[] key = new byte[] { };
|
||||
var TST = CSRedisCacheHelper.HMGet<DeviceCacheInfo>(0, CacheKey.DeviceInfo, VData.device_clientid);
|
||||
if (TST != null)
|
||||
{
|
||||
key = Encoding.ASCII.GetBytes(TST[0].SecretKey);
|
||||
}
|
||||
byte[] decryptedContent = Tools.IHIOT_Message_Content_Encrypt(Xuhao, key, jia_mi_bytes.ToArray());
|
||||
|
||||
dataF.AddRange(new byte[] { 0x2D, 0x2D, 0x0D, 0x0A, 0x2D, 0x2D });
|
||||
var CMDdata = dataF.ToArray();
|
||||
int len = CMDdata.Length;
|
||||
ushort sss1 = (ushort)len;
|
||||
byte[] bas = BitConverter.GetBytes(sss1);
|
||||
|
||||
CMDdata[1] = bas[0];
|
||||
CMDdata[2] = bas[1];
|
||||
|
||||
VData.data = Tools.ByteToString(CMDdata);
|
||||
|
||||
if (IsIllegalHexadecimal(HHH2) == false)
|
||||
{
|
||||
request1.AddParameter("parameterlist", JsonSerializer.Serialize(VData));
|
||||
var Q = await client1.ExecuteAsync(request1);
|
||||
r.isok = true;
|
||||
r.message = "success";
|
||||
}
|
||||
else
|
||||
{
|
||||
r.isok = false;
|
||||
r.message = "错误,发送的数据必须是 16进制";
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.Error("错误:" + ex.Message);
|
||||
r.message = ex.Message;
|
||||
r.isok = false;
|
||||
}
|
||||
return r;
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 判断十六进制字符串hex是否正确
|
||||
/// </summary>
|
||||
/// <param name="hex">十六进制字符串</param>
|
||||
/// <returns>true:不正确,false:正确</returns>
|
||||
public bool IsIllegalHexadecimal(string hex)
|
||||
{
|
||||
foreach (char item in hex)
|
||||
{
|
||||
if (!HexSet.Contains<char>(item))
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public class MQTTData
|
||||
{
|
||||
public List<Dictionary<string, object>> data { get; set; }
|
||||
public Dictionary<string, object> meta { get; set; }
|
||||
}
|
||||
public class NiMingOO
|
||||
{
|
||||
public string? Listener { get; set; }
|
||||
public string? UserName { get; set; }
|
||||
public string? WWWWIP { get; set; }
|
||||
public string? WWWWPort { get; set; }
|
||||
public string? ClientId { get; set; }
|
||||
public string? Connected { get; set; }
|
||||
public string? connected_DateTime { get; set; }
|
||||
}
|
||||
|
||||
public class QueryData
|
||||
{
|
||||
public int Limit { get; set; }
|
||||
public int Page { get; set; }
|
||||
}
|
||||
public class RMsg
|
||||
{
|
||||
public string message { get; set; }
|
||||
public bool isok { get; set; }
|
||||
}
|
||||
public class Data
|
||||
{
|
||||
public string? Cmd { get; set; }
|
||||
public SendData? Parameterlist { get; set; }
|
||||
}
|
||||
public class SendData
|
||||
{
|
||||
public string? endpoint { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 设备序号
|
||||
/// </summary>
|
||||
public string? device_clientid { get; set; }
|
||||
public string? command_word { get; set; }
|
||||
public string? data { get; set; }
|
||||
}
|
||||
}
|
||||
157
EMQX_HttpAuth/Controllers/ValuesController.cs
Normal file
157
EMQX_HttpAuth/Controllers/ValuesController.cs
Normal file
@@ -0,0 +1,157 @@
|
||||
using System.Text;
|
||||
using System.Transactions;
|
||||
using Common;
|
||||
using CommonEntity;
|
||||
using LogCap.Common;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using NLog;
|
||||
|
||||
namespace EMQX_HttpAuth.Controllers
|
||||
{
|
||||
[Route("api/[controller]/[action]")]
|
||||
[ApiController]
|
||||
public class ValuesController : ControllerBase
|
||||
{
|
||||
|
||||
private readonly Logger _logger = LogManager.GetCurrentClassLogger();
|
||||
|
||||
[HttpPost()]
|
||||
public Resp Validate([FromBody] UserData data)
|
||||
{
|
||||
Resp r = new Resp();
|
||||
try
|
||||
{
|
||||
if (data.username.Equals("admin") && data.password.Equals("@8xq*BU3+3kuE:Oj"))
|
||||
{
|
||||
r.result = "allow";
|
||||
r.is_superuser = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
string Key = CacheKey.MQTTValidatePrefix + data.username;
|
||||
string password = CSRedisCacheHelper.Get_Partition<string>(Key, 1);
|
||||
if (!string.IsNullOrEmpty(password))
|
||||
{
|
||||
if (data.password.Equals(password))
|
||||
{
|
||||
r.result = "allow";
|
||||
r.is_superuser = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.Error("deny 111: " + data.username + " " + data.password);
|
||||
r.result = "deny";
|
||||
r.is_superuser = false;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.Error("deny 222: " + data.username + " " + data.password);
|
||||
r.result = "deny";
|
||||
r.is_superuser = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.Error("chu cuo: " + ex.Message);
|
||||
r.result = "deny";
|
||||
r.is_superuser = false;
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
[HttpPost()]
|
||||
public ReturnInfo SetChache(List<UserData> datalist)
|
||||
{
|
||||
ReturnInfo r = new ReturnInfo();
|
||||
try
|
||||
{
|
||||
foreach (var data in datalist)
|
||||
{
|
||||
string Key = CacheKey.MQTTValidatePrefix + data.username;
|
||||
CSRedisCacheHelper.Set_Partition<string>(Key, data.password, 1);
|
||||
}
|
||||
r.isok = true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.Error(ex.Message);
|
||||
r.isok = false;
|
||||
r.message = ex.Message;
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 设置设备的ClientId对应的Key
|
||||
/// </summary>
|
||||
/// <param name="datalist"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPost()]
|
||||
public ReturnInfo SetDeviceInfoChache(List<DeviceCacheInfo> datalist)
|
||||
{
|
||||
string Key =CacheKey.DeviceInfo;
|
||||
ReturnInfo r = new ReturnInfo();
|
||||
try
|
||||
{
|
||||
foreach (var data in datalist)
|
||||
{
|
||||
CSRedisCacheHelper.HMSet(0, Key, data.ClientId, data.SecretKey);
|
||||
}
|
||||
r.isok = true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.Error(ex.Message);
|
||||
r.isok = false;
|
||||
r.message = ex.Message;
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
|
||||
|
||||
[HttpPost()]
|
||||
public ReturnInfo DelCache(List<UserData> data)
|
||||
{
|
||||
ReturnInfo r = new ReturnInfo();
|
||||
try
|
||||
{
|
||||
var q = data.Select(A => A.username).ToArray();
|
||||
CSRedisCacheHelper.Del_Partition(q, 1);
|
||||
r.isok = true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
r.isok = false;
|
||||
r.message = ex.Message;
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
public void MonitorMQTTClient()
|
||||
{
|
||||
var readResult = Request.BodyReader.ReadAsync().Result;
|
||||
Request.BodyReader.AdvanceTo(readResult.Buffer.Start, readResult.Buffer.End);
|
||||
string body = Encoding.UTF8.GetString(readResult.Buffer.FirstSpan);
|
||||
}
|
||||
public void GenerateSecret()
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
public class UserData
|
||||
{
|
||||
public string username { get; set; }
|
||||
public string password { get; set; }
|
||||
}
|
||||
public class Resp
|
||||
{
|
||||
public string result { get; set; }
|
||||
public bool is_superuser { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
33
EMQX_HttpAuth/Controllers/WeatherForecastController.cs
Normal file
33
EMQX_HttpAuth/Controllers/WeatherForecastController.cs
Normal file
@@ -0,0 +1,33 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace EMQX_HttpAuth.Controllers
|
||||
{
|
||||
[ApiController]
|
||||
[Route("[controller]")]
|
||||
public class WeatherForecastController : ControllerBase
|
||||
{
|
||||
private static readonly string[] Summaries = new[]
|
||||
{
|
||||
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
|
||||
};
|
||||
|
||||
private readonly ILogger<WeatherForecastController> _logger;
|
||||
|
||||
public WeatherForecastController(ILogger<WeatherForecastController> logger)
|
||||
{
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public IEnumerable<WeatherForecast> Get()
|
||||
{
|
||||
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
|
||||
{
|
||||
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
|
||||
TemperatureC = Random.Shared.Next(-20, 55),
|
||||
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
|
||||
})
|
||||
.ToArray();
|
||||
}
|
||||
}
|
||||
}
|
||||
25
EMQX_HttpAuth/EMQX_HttpAuth.csproj
Normal file
25
EMQX_HttpAuth/EMQX_HttpAuth.csproj
Normal file
@@ -0,0 +1,25 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Confluent.Kafka" Version="2.12.0" />
|
||||
<PackageReference Include="Google.Protobuf" Version="3.33.0" />
|
||||
<PackageReference Include="MessagePack" Version="3.1.4" />
|
||||
<PackageReference Include="NetMQ" Version="4.0.1.16" />
|
||||
<PackageReference Include="NLog" Version="5.4.0" />
|
||||
<PackageReference Include="NLog.Schema" Version="5.4.0" />
|
||||
<PackageReference Include="RestSharp" Version="112.1.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\CommonEntity\CommonEntity.csproj" />
|
||||
<ProjectReference Include="..\Common\Common.csproj" />
|
||||
<ProjectReference Include="..\ViewModels\ViewModels.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
6
EMQX_HttpAuth/EMQX_HttpAuth.http
Normal file
6
EMQX_HttpAuth/EMQX_HttpAuth.http
Normal file
@@ -0,0 +1,6 @@
|
||||
@EMQX_HttpAuth_HostAddress = http://localhost:5116
|
||||
|
||||
GET {{EMQX_HttpAuth_HostAddress}}/weatherforecast/
|
||||
Accept: application/json
|
||||
|
||||
###
|
||||
58
EMQX_HttpAuth/Program.cs
Normal file
58
EMQX_HttpAuth/Program.cs
Normal file
@@ -0,0 +1,58 @@
|
||||
using NetMQ;
|
||||
using NetMQ.Sockets;
|
||||
using ViewModels;
|
||||
|
||||
namespace EMQX_HttpAuth
|
||||
{
|
||||
public class Program
|
||||
{
|
||||
public static void Main(string[] args)
|
||||
{
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
// Add services to the container.
|
||||
|
||||
builder.Services.AddControllers();
|
||||
|
||||
builder.Services.AddCors(options =>
|
||||
{
|
||||
options.AddPolicy(name: "Vue3",
|
||||
policy =>
|
||||
{
|
||||
//policy.WithOrigins("http://localhost:5180",
|
||||
// "http://localhost:8809/",
|
||||
// "http://www.contoso.com",
|
||||
// "http://new.uts-data.com:6688/", "http://new.uts-data.com")
|
||||
policy
|
||||
.AllowAnyOrigin()
|
||||
.AllowAnyHeader()
|
||||
.AllowAnyMethod();
|
||||
});
|
||||
});
|
||||
var app = builder.Build();
|
||||
|
||||
// Configure the HTTP request pipeline.
|
||||
|
||||
app.UseCors("Vue3");
|
||||
app.UseHttpsRedirection();
|
||||
|
||||
app.UseAuthorization();
|
||||
|
||||
|
||||
app.MapControllers();
|
||||
|
||||
|
||||
|
||||
//using (var server = new ResponseSocket())
|
||||
//{
|
||||
// server.Bind("tcp://*:5556");
|
||||
// string msg = server.ReceiveFrameString();
|
||||
// Console.WriteLine("From Client: {0}", msg);
|
||||
// server.SendFrame("World");
|
||||
//}
|
||||
|
||||
app.Run();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!--
|
||||
https://go.microsoft.com/fwlink/?LinkID=208121.
|
||||
-->
|
||||
<Project>
|
||||
<PropertyGroup>
|
||||
<DeleteExistingFiles>false</DeleteExistingFiles>
|
||||
<ExcludeApp_Data>false</ExcludeApp_Data>
|
||||
<LaunchSiteAfterPublish>true</LaunchSiteAfterPublish>
|
||||
<LastUsedBuildConfiguration>Release</LastUsedBuildConfiguration>
|
||||
<LastUsedPlatform>Any CPU</LastUsedPlatform>
|
||||
<PublishProvider>FileSystem</PublishProvider>
|
||||
<PublishUrl>bin\Release\net8.0\publish\</PublishUrl>
|
||||
<WebPublishMethod>FileSystem</WebPublishMethod>
|
||||
<_TargetId>Folder</_TargetId>
|
||||
<SiteUrlToLaunchAfterPublish />
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<RuntimeIdentifier>linux-x64</RuntimeIdentifier>
|
||||
<ProjectGuid>90b96dfb-a847-439a-8eeb-a5c830bd9b15</ProjectGuid>
|
||||
<SelfContained>false</SelfContained>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,11 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!--
|
||||
https://go.microsoft.com/fwlink/?LinkID=208121.
|
||||
-->
|
||||
<Project>
|
||||
<PropertyGroup>
|
||||
<_PublishTargetUrl>E:\CsharpDemo\BooliveMQTT_Auth\EMQX_HttpAuth\bin\Release\net8.0\publish\</_PublishTargetUrl>
|
||||
<History>True|2025-05-13T11:25:08.6912484Z||;True|2025-05-13T19:18:56.4087022+08:00||;True|2025-05-13T19:14:11.0663012+08:00||;True|2025-05-13T19:13:49.8913918+08:00||;True|2025-05-13T19:09:01.5167212+08:00||;True|2025-05-13T19:08:13.0072735+08:00||;</History>
|
||||
<LastFailureDetails />
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,22 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!--
|
||||
https://go.microsoft.com/fwlink/?LinkID=208121.
|
||||
-->
|
||||
<Project>
|
||||
<PropertyGroup>
|
||||
<DeleteExistingFiles>false</DeleteExistingFiles>
|
||||
<ExcludeApp_Data>false</ExcludeApp_Data>
|
||||
<LaunchSiteAfterPublish>true</LaunchSiteAfterPublish>
|
||||
<LastUsedBuildConfiguration>Release</LastUsedBuildConfiguration>
|
||||
<LastUsedPlatform>Any CPU</LastUsedPlatform>
|
||||
<PublishProvider>FileSystem</PublishProvider>
|
||||
<PublishUrl>bin\Release\net8.0\publish\</PublishUrl>
|
||||
<WebPublishMethod>FileSystem</WebPublishMethod>
|
||||
<_TargetId>Folder</_TargetId>
|
||||
<SiteUrlToLaunchAfterPublish />
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<RuntimeIdentifier>linux-x64</RuntimeIdentifier>
|
||||
<ProjectGuid>90b96dfb-a847-439a-8eeb-a5c830bd9b15</ProjectGuid>
|
||||
<SelfContained>false</SelfContained>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,11 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!--
|
||||
https://go.microsoft.com/fwlink/?LinkID=208121.
|
||||
-->
|
||||
<Project>
|
||||
<PropertyGroup>
|
||||
<_PublishTargetUrl>E:\tian\chongxin\EMQX\BooliveMQTT_Auth\EMQX_HttpAuth\bin\Release\net8.0\publish\</_PublishTargetUrl>
|
||||
<History>True|2025-10-29T07:43:50.2655182Z||;True|2025-10-29T15:40:24.6390115+08:00||;True|2025-10-29T09:33:40.6782694+08:00||;True|2025-10-28T15:04:43.5086758+08:00||;True|2025-10-28T14:49:51.8408435+08:00||;True|2025-10-28T14:24:38.0532771+08:00||;True|2025-10-28T14:18:19.8238155+08:00||;True|2025-10-28T13:57:33.8718907+08:00||;True|2025-10-28T10:10:25.0590935+08:00||;True|2025-10-28T10:10:14.9693259+08:00||;True|2025-10-28T10:01:12.5904478+08:00||;True|2025-10-24T17:32:40.2543342+08:00||;True|2025-10-24T17:18:51.0229206+08:00||;True|2025-10-24T17:18:01.7134771+08:00||;True|2025-09-29T19:17:15.1528904+08:00||;True|2025-09-29T16:14:39.6592930+08:00||;True|2025-09-29T16:14:04.5120554+08:00||;True|2025-06-20T15:43:46.7435251+08:00||;True|2025-06-20T13:47:51.3514840+08:00||;True|2025-06-12T09:19:57.9915530+08:00||;True|2025-06-10T15:19:56.4138897+08:00||;True|2025-06-09T08:45:14.8710815+08:00||;True|2025-05-30T10:22:17.3787481+08:00||;True|2025-05-30T10:16:54.5414326+08:00||;True|2025-05-29T16:35:12.9432210+08:00||;True|2025-05-28T16:18:47.4770614+08:00||;True|2025-05-28T15:56:42.7055062+08:00||;True|2025-05-26T16:14:50.1944344+08:00||;True|2025-05-26T16:13:38.4354621+08:00||;True|2025-05-26T16:07:14.7322349+08:00||;True|2025-05-26T16:07:08.0414505+08:00||;True|2025-05-26T16:02:27.0711058+08:00||;True|2025-05-26T10:19:01.3755622+08:00||;True|2025-05-15T17:00:19.8345092+08:00||;True|2025-05-15T15:23:08.5601222+08:00||;True|2025-05-15T15:22:12.7078315+08:00||;</History>
|
||||
<LastFailureDetails />
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
41
EMQX_HttpAuth/Properties/launchSettings.json
Normal file
41
EMQX_HttpAuth/Properties/launchSettings.json
Normal file
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"$schema": "http://json.schemastore.org/launchsettings.json",
|
||||
"iisSettings": {
|
||||
"windowsAuthentication": false,
|
||||
"anonymousAuthentication": true,
|
||||
"iisExpress": {
|
||||
"applicationUrl": "http://localhost:26776",
|
||||
"sslPort": 44305
|
||||
}
|
||||
},
|
||||
"profiles": {
|
||||
"http": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": true,
|
||||
"launchUrl": "weatherforecast",
|
||||
"applicationUrl": "http://localhost:5116",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
},
|
||||
"https": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": true,
|
||||
"launchUrl": "weatherforecast",
|
||||
"applicationUrl": "https://localhost:7120;http://localhost:5116",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
},
|
||||
"IIS Express": {
|
||||
"commandName": "IISExpress",
|
||||
"launchBrowser": true,
|
||||
"launchUrl": "weatherforecast",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
10
EMQX_HttpAuth/View/htmlpage.html
Normal file
10
EMQX_HttpAuth/View/htmlpage.html
Normal file
@@ -0,0 +1,10 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title></title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
13
EMQX_HttpAuth/WeatherForecast.cs
Normal file
13
EMQX_HttpAuth/WeatherForecast.cs
Normal file
@@ -0,0 +1,13 @@
|
||||
namespace EMQX_HttpAuth
|
||||
{
|
||||
public class WeatherForecast
|
||||
{
|
||||
public DateOnly Date { get; set; }
|
||||
|
||||
public int TemperatureC { get; set; }
|
||||
|
||||
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
|
||||
|
||||
public string? Summary { get; set; }
|
||||
}
|
||||
}
|
||||
13
EMQX_HttpAuth/app.json
Normal file
13
EMQX_HttpAuth/app.json
Normal file
@@ -0,0 +1,13 @@
|
||||
{
|
||||
//redis
|
||||
"session_expire_minutes": "5",
|
||||
"redis_server_session": "127.0.0.1:6379",
|
||||
"get_redis_auth": "",
|
||||
"redis_max_read_pool": "1000",
|
||||
"redis_max_write_pool": "1000",
|
||||
|
||||
"MQTT_ServerIP": "120.24.73.62",
|
||||
"MQTT_ServerPort": 1883,
|
||||
"MQTT_User": "blw",
|
||||
"MQTT_PWD": "blw@1234"
|
||||
}
|
||||
8
EMQX_HttpAuth/appsettings.Development.json
Normal file
8
EMQX_HttpAuth/appsettings.Development.json
Normal file
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
}
|
||||
}
|
||||
23
EMQX_HttpAuth/appsettings.json
Normal file
23
EMQX_HttpAuth/appsettings.json
Normal file
@@ -0,0 +1,23 @@
|
||||
{
|
||||
|
||||
//redis
|
||||
"session_expire_minutes": "5",
|
||||
"redis_server_session": "127.0.0.1:6379",
|
||||
"get_redis_auth": "",
|
||||
"redis_max_read_pool": "1000",
|
||||
"redis_max_write_pool": "1000",
|
||||
|
||||
"MQTT_ServerIP": "120.24.73.62",
|
||||
"MQTT_ServerPort": 1883,
|
||||
"MQTT_User": "blw",
|
||||
"MQTT_PWD": "blw@1234",
|
||||
"Key": "3ff392405dbe9bd1",
|
||||
"Security": "KpGqGUzZrMZeo9CaqLqwb5vcb9BWuoEs6OtBlHG1YmAcB",
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
},
|
||||
"AllowedHosts": "*"
|
||||
}
|
||||
35
EMQX_HttpAuth/nlog.config
Normal file
35
EMQX_HttpAuth/nlog.config
Normal file
@@ -0,0 +1,35 @@
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
|
||||
|
||||
<!-- enable asp.net core layout renderers -->
|
||||
<targets>
|
||||
<!--项目日志保存文件路径说明fileName="${basedir}/保存目录,以年月日的格式创建/${shortdate}/${记录器名称}-${单级记录}-${shortdate}.txt"-->
|
||||
<target name="info_file" xsi:type="File"
|
||||
fileName="${basedir}/Logs/${shortdate}/info_${shortdate}.txt"
|
||||
layout="${longdate}|${level:uppercase=true}|${logger}|${message}|${exception:format=ToString} ${newline} ${stacktrace} ${newline}"
|
||||
archiveFileName="${basedir}/archives/info_${shortdate}-{#####}.txt"
|
||||
archiveAboveSize="102400"
|
||||
archiveNumbering="Sequence"
|
||||
concurrentWrites="true"
|
||||
keepFileOpen="false" />
|
||||
<target name="error_file" xsi:type="File"
|
||||
fileName="${basedir}/Logs/${shortdate}/error_${shortdate}.txt"
|
||||
layout="${longdate}|${level:uppercase=true}|${logger}|${message}|${exception:format=ToString} ${newline} ${stacktrace} ${newline}"
|
||||
archiveFileName="${basedir}/archives/error_${shortdate}-{#####}.txt"
|
||||
archiveAboveSize="102400"
|
||||
archiveNumbering="Sequence"
|
||||
concurrentWrites="true"
|
||||
keepFileOpen="false" />
|
||||
</targets>
|
||||
|
||||
<!--规则配置,final - 最终规则匹配后不处理任何规则-->
|
||||
<!--规则配置,final - 最终规则匹配后不处理任何规则-->
|
||||
<!--定义使用哪个target输出-->
|
||||
<rules>
|
||||
<!-- 优先级从高到低依次为:OFF、FATAL、ERROR、WARN、INFO、DEBUG、TRACE、 ALL -->
|
||||
<!-- 将所有日志输出到文件 -->
|
||||
<logger name="*" minlevel="FATAL" maxlevel="FATAL" writeTo="info_file" />
|
||||
<logger name="*" minlevel="ERROR" maxlevel="ERROR" writeTo="error_file" />
|
||||
</rules>
|
||||
</nlog>
|
||||
151
EMQX_HttpAuth/services/KafkaProduce.cs
Normal file
151
EMQX_HttpAuth/services/KafkaProduce.cs
Normal file
@@ -0,0 +1,151 @@
|
||||
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Channels;
|
||||
using Common;
|
||||
using CommonEntity;
|
||||
using CommonEntity.RCUEntity;
|
||||
using CommonTools;
|
||||
using Confluent.Kafka;
|
||||
using Google.Protobuf;
|
||||
using MessagePack;
|
||||
using Microsoft.Extensions.Caching.Memory;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using NLog;
|
||||
using RestSharp;
|
||||
using static CSRedis.CSRedisClient;
|
||||
|
||||
namespace BLWLogProduce.Services
|
||||
{
|
||||
public class KafkaProduce : BackgroundService
|
||||
{
|
||||
public IConfiguration Configuration { get; set; }
|
||||
public IMemoryCache _Cache { get; set; }
|
||||
|
||||
public KafkaProduce(IConfiguration configuration, IMemoryCache cache)
|
||||
{
|
||||
this.Configuration = configuration;
|
||||
_Cache = cache;
|
||||
}
|
||||
|
||||
//private static Channel<string> _messageChannel;
|
||||
public static Logger logger = LogManager.GetCurrentClassLogger();
|
||||
protected async override Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
await Task.Factory.StartNew((state) =>
|
||||
{
|
||||
try
|
||||
{
|
||||
string? ipport = Configuration["Kafka:EndPoint"];
|
||||
string? user = Configuration["Kafka:UserName"];
|
||||
string? pwd = Configuration["Kafka:PassWord"];
|
||||
var config = new ProducerConfig
|
||||
{
|
||||
BootstrapServers = ipport,
|
||||
SecurityProtocol = SecurityProtocol.SaslPlaintext,
|
||||
SaslMechanism = SaslMechanism.Plain,
|
||||
SaslUsername = user,
|
||||
SaslPassword = pwd
|
||||
};
|
||||
var p = new ProducerBuilder<string, byte[]>(config).Build();
|
||||
|
||||
// JS= #{hostnum=>VS1,endpoint=>JieGuo,data=>RedisData,currenttimestamp=>CurrentTimestamp}
|
||||
var DingYue1 = (RedisKey.NewVersion_RCU_Data, new Action<SubscribeMessageEventArgs>(async (args) =>
|
||||
{
|
||||
string body = args.Body;
|
||||
var USA = JsonConvert.DeserializeObject<RCU_UDPData>(body);
|
||||
var UUA = USA.endpoint;
|
||||
var hostnum = USA.hostnum;
|
||||
|
||||
var timestamp = USA.currenttimestamp;
|
||||
var data = USA.data;
|
||||
var endpoint_1 = Encoding.ASCII.GetString(UUA);
|
||||
var hostnum_1 = Encoding.ASCII.GetString(hostnum);
|
||||
|
||||
RCU_UDPData_With_String rs = new RCU_UDPData_With_String();
|
||||
rs.currenttimestamp = timestamp;
|
||||
rs.data = data;
|
||||
rs.hostnum = hostnum_1;
|
||||
rs.endpoint = endpoint_1;
|
||||
|
||||
byte[] qf = MyMessagePacker.FastSerialize(rs);
|
||||
|
||||
string TopicKey = KafkaKey.New_RCU_Data_Topic;
|
||||
string DetailKey = KafkaKey.UDPckageAllUDPDataKey;
|
||||
|
||||
|
||||
await p.ProduceAsync(TopicKey, new Message<string, byte[]> { Key = DetailKey, Value = qf });
|
||||
|
||||
}));
|
||||
|
||||
//var DingYue = ("redis-power", new Action<SubscribeMessageEventArgs>(async (args) =>
|
||||
//{
|
||||
// string body = args.Body;
|
||||
|
||||
// object poo = null;
|
||||
// byte[] qf = MyMessagePacker.FastSerialize(poo);
|
||||
|
||||
// string TopicKey = KafkaKey.BLWLog_RCU_Topic;
|
||||
// string DetailKey = KafkaKey.UDPPackagePowerMonitor;
|
||||
// await p.ProduceAsync(TopicKey, new Message<string, byte[]> { Key = DetailKey, Value = qf });
|
||||
|
||||
|
||||
// //宝镜系统使用
|
||||
// //EnergyConsumption ese = new EnergyConsumption();
|
||||
|
||||
// //byte[] data = ese.ToByteArray();
|
||||
// byte[] data = null;
|
||||
// string TopicKey1 = "";
|
||||
// string DetailKey1 = "";
|
||||
|
||||
// await p.ProduceAsync(TopicKey1, new Message<string, byte[]> { Key = DetailKey1, Value = data });
|
||||
|
||||
//}));
|
||||
|
||||
//CSRedisCacheHelper.redis.Subscribe(DingYue);
|
||||
CSRedisCacheHelper.redis.Subscribe(DingYue1);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.Error(ex.Message);
|
||||
logger.Error(ex.StackTrace);
|
||||
}
|
||||
}, TaskCreationOptions.LongRunning, stoppingToken);
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 百度api
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static string GetBaiduIp(string ip)
|
||||
{
|
||||
string location = "";
|
||||
try
|
||||
{
|
||||
string url = $"https://sp0.baidu.com";
|
||||
//WebClient client = new WebClient();
|
||||
RestSharp.RestClient client1 = new RestSharp.RestClient(url);
|
||||
RestSharp.RestRequest request = new RestSharp.RestRequest($"/8aQDcjqpAAV3otqbppnN2DJv/api.php?query={ip}&co=&resource_id=6006&oe=utf8", Method.Get);
|
||||
var buffer = client1.DownloadData(request);
|
||||
//var buffer = client.DownloadData(url);
|
||||
string jsonText = Encoding.UTF8.GetString(buffer);
|
||||
JObject jo = JObject.Parse(jsonText);
|
||||
|
||||
Root root = JsonConvert.DeserializeObject<Root>(jo.ToString());
|
||||
foreach (var item in root.data)
|
||||
{
|
||||
location = item.location;
|
||||
}
|
||||
return location;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//Console.WriteLine(ex);
|
||||
return location;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user