初始化

This commit is contained in:
2025-11-26 11:32:30 +08:00
commit 2163829349
1853 changed files with 1896668 additions and 0 deletions

View File

@@ -0,0 +1,42 @@
using Newtonsoft.Json;
using Org.BouncyCastle.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MQTTServerSideAPI.Controllers
{
public class BaseController : Controller
{
/// <summary>
/// 在Action方法调用前使用使用场景如何验证登录等。
/// </summary>
/// <param name="filterContext"></param>
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
try
{
base.OnActionExecuting(filterContext);
if (Session["username"] == null)
{
filterContext.Result = new RedirectResult("/LoginViews/Index");
}
else
{
}
}
catch (Exception ex)
{
Logger.LogCalloutanaSide("Session:__________________" + ex);
}
}
}
}

View File

@@ -0,0 +1,56 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using TencentCloud.Common.Profile;
using TencentCloud.Common;
namespace MQTTServerSideAPI.Controllers
{
public class ConfigController : ApiController
{
// GET api/<controller>
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/<controller>/5
public string Get(string cmd6tsp)
{
string retString = "";
if (String.IsNullOrEmpty(cmd6tsp))
cmd6tsp = "0";
if(cmd6tsp == "0")
{
SQLiteDBHelper.UpdateCm6TSP("0");
}
else
{
SQLiteDBHelper.UpdateCm6TSP(cmd6tsp);
}
return retString;
}
// POST api/<controller>
public void Post([FromBody] string value)
{
}
// PUT api/<controller>/5
public void Put(int id, [FromBody] string value)
{
}
// DELETE api/<controller>/5
public void Delete(int id)
{
}
}
}

View File

@@ -0,0 +1,94 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using TencentCloud.Common;
using TencentCloud.Common.Profile;
using TencentCloud.Iotcloud.V20210408;
using TencentCloud.Iotcloud.V20210408.Models;
namespace MQTTServerSideAPI.Controllers
{
public class DevicesController : ApiController
{
// GET api/<controller>
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/<controller>/5
public string Get(string productid)
{
string strProductId = productid;
string retString = "";
try
{
// 实例化一个认证对象,入参需要传入腾讯云账户 SecretId 和 SecretKey此处还需注意密钥对的保密
// 代码泄露可能会导致 SecretId 和 SecretKey 泄露并威胁账号下所有资源的安全性。以下代码示例仅供参考建议采用更安全的方式来使用密钥请参见https://cloud.tencent.com/document/product/1278/85305
// 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
Credential cred = new Credential
{
SecretId = "AKIDKhz84sbEqFPRK1Uo0zUnwwjNp4884vc4",
SecretKey = "JQ8qZGxgQAtbCfvxb7VqzxujOtFVb1KT"
};
// 实例化一个client选项可选的没有特殊需求可以跳过
ClientProfile clientProfile = new ClientProfile();
// 实例化一个http选项可选的没有特殊需求可以跳过
HttpProfile httpProfile = new HttpProfile();
httpProfile.Endpoint = ("iotcloud.tencentcloudapi.com");
clientProfile.HttpProfile = httpProfile;
// 实例化要请求产品的client对象,clientProfile是可选的
IotcloudClient client = new IotcloudClient(cred, "ap-guangzhou", clientProfile);
// 实例化一个请求对象,每个接口都会对应一个request对象
DescribeDevicesRequest req = new DescribeDevicesRequest();
req.ProductId = "HICL5RNXAU"; //strProductId
req.Offset = 0;
req.Limit = 250;
Logger.LogDownSide(String.Format("Send request: req.ProductId:{0}, req.Offset:{1}, req.Limit:{2}",
req.ProductId,
req.Offset,
req.Limit
));
// 返回的resp是一个DescribeDevicesResponse的实例与请求对象对应
DescribeDevicesResponse resp = client.DescribeDevicesSync(req);
// 输出json格式的字符串回包
retString = AbstractModel.ToJsonString(resp);
Logger.LogDownSide("Success return !! " + retString);
}
catch (Exception e)
{
if (e.InnerException != null)
retString = "Error " + e.InnerException.ToString();
Logger.LogDownSide("Failed exception !! " + e.ToString());
}
return retString;
}
// POST api/<controller>
public void Post([FromBody] string value)
{
}
// PUT api/<controller>/5
public void Put(int id, [FromBody] string value)
{
}
// DELETE api/<controller>/5
public void Delete(int id)
{
}
}
}

View File

@@ -0,0 +1,37 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using static Org.BouncyCastle.Math.EC.ECCurve;
namespace MQTTServerSideAPI.Controllers
{
public class HomeController : BaseController
{
public ActionResult Index()
{
ViewBag.Title = "Home Page";
return View();
}
public ActionResult RefreshDevice()
{
ViewBag.Title = "RefreshDevice";
return View();
}
public ActionResult Offlinerecord()
{
ViewBag.Title = "Offlinerecord";
return View();
}
public ActionResult Viewofflinerecordsofalldevices()
{
ViewBag.Title = "Viewofflinerecordsofalldevices";
return View();
}
}
}

View File

@@ -0,0 +1,39 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Helpers;
using System.Web.Http;
using System.Xml.Linq;
namespace MQTTServerSideAPI.Controllers
{
public class LoginController : ApiController
{
[HttpPost]
public bool Login([FromBody] loginuser name)
{
//user list = SqlSugarDBHelp.authoriydb.Queryable<user>().First(x => x.password == name.password && x.user_name == name.user_name);
int count= SQLiteDBHelper.Loning(name);
if (count>0)
{
return true;
}
else
{
return false;
}
}
}
public class loginuser
{
public string password { get; set; }
public string user_name { get; set; }
}
}

View File

@@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Xml.Linq;
namespace MQTTServerSideAPI.Controllers
{
public class LoginViewsController : Controller
{
// GET: LoginViews
public ActionResult Index()
{
Session["username"] = "登录成功了";
return View();
}
}
}

View File

@@ -0,0 +1,355 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Mvc;
using TencentCloud.Common.Profile;
using TencentCloud.Common;
using TencentCloud.Iotcloud.V20180614;
using TencentCloud.Iotcloud.V20180614.Models;
using Newtonsoft.Json;
using static MQTTServerSideAPI.SQLiteDBHelper;
using K4os.Compression.LZ4;
using MySqlX.XDevAPI;
using static Org.BouncyCastle.Math.EC.ECCurve;
using System.Web.UI.WebControls;
using MySql.Data.MySqlClient;
using System.Data;
using static System.Data.Entity.Infrastructure.Design.Executor;
using System.Net.NetworkInformation;
namespace MQTTServerSideAPI.Controllers
{
public class apifanhinfo
{
public int TotalCount { get; set; }
public List<deviceinformation> Devices { get; set; }
public string RequestId { get; set; }
}
public class deviceinformation
{
//public int id { get; set; }
public string DeviceName { get; set; }
public int Online { get; set; }
public string LoginTime { get; set; }
public string Version { get; set; }
public string DeviceCert { get; set; }
public string DevicePsk { get; set; }
public int DeviceType { get; set; }
public string Imei { get; set; }
public string Isp { get; set; }
public string ConnIP { get; set; }
public string LastUpdateTime { get; set; }
public string LoraDevEui { get; set; }
public int LoraMoteType { get; set; }
public string FirstOnlineTime { get; set; }
public string LastOfflineTime { get; set; }
public string CreateTime { get; set; }
public int LogLevel { get; set; }
public int CertState { get; set; }
public int EnableState { get; set; }
public string ClientIP { get; set; }
public string FirmwareUpdateTime { get; set; }
public int CreateUserId { get; set; }
public string NBIoTDeviceID { get; set; }
}
public class LogsController : ApiController
{
// GET api/<controller>
public List<string> Get(string Name, int zhant)
{
return SQLiteDBHelper.GetAllCallinBYName(Name, zhant);
}
public List<string> Get(string productid, string devicename, string shijian, int cmdname)
{
return SQLiteDBHelper.jianzaogduo(productid, devicename, shijian, cmdname);
}
public void Get()
{
try
{
// 实例化一个认证对象,入参需要传入腾讯云账户 SecretId 和 SecretKey此处还需注意密钥对的保密
// 代码泄露可能会导致 SecretId 和 SecretKey 泄露并威胁账号下所有资源的安全性。以下代码示例仅供参考建议采用更安全的方式来使用密钥请参见https://cloud.tencent.com/document/product/1278/85305
// 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
Credential cred = new Credential
{
SecretId = "AKIDKhz84sbEqFPRK1Uo0zUnwwjNp4884vc4",
SecretKey = "JQ8qZGxgQAtbCfvxb7VqzxujOtFVb1KT"
};
// 实例化一个client选项可选的没有特殊需求可以跳过
ClientProfile clientProfile = new ClientProfile();
// 实例化一个http选项可选的没有特殊需求可以跳过
HttpProfile httpProfile = new HttpProfile();
httpProfile.Endpoint = ("iotcloud.tencentcloudapi.com");
clientProfile.HttpProfile = httpProfile;
// 实例化要请求产品的client对象,clientProfile是可选的
IotcloudClient client = new IotcloudClient(cred, "ap-guangzhou", clientProfile);
// 实例化一个请求对象,每个接口都会对应一个request对象
DescribeDevicesRequest req = new DescribeDevicesRequest();
req.ProductId = "HICL5RNXAU";
req.Offset = 0;
req.Limit = 250;
// 返回的resp是一个DescribeDevicesResponse的实例与请求对象对应
DescribeDevicesResponse resp = client.DescribeDevicesSync(req);
// 输出json格式的字符串回包
var abs = AbstractModel.ToJsonString(resp);
apifanhinfo shujiu = JsonConvert.DeserializeObject<apifanhinfo>(abs);
DataSet ds = new DataSet();
string strSqlCmd = "SELECT DeviceName,Online FROM deviceinformation ";
using (MySqlConnection connection = new MySqlConnection(strSqliteConn))
{
using (MySqlCommand cmd = new MySqlCommand())
{
connection.Open();
cmd.Connection = connection;
MySqlDataAdapter command = new MySqlDataAdapter(strSqlCmd, connection);
command.Fill(ds);
}
}
List<string> devname = new List<string>();
List<int> devOnline = new List<int>();
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
string namessdd = ds.Tables[0].Rows[i]["DeviceName"].ToString();
int on = int.Parse(ds.Tables[0].Rows[i]["Online"].ToString());
devOnline.Add(on);
devname.Add(namessdd);
}
string sql = "";
List<deviceinformation> list = shujiu.Devices.Where(x => devname.Contains(x.DeviceName)).ToList();
List<deviceinformation> lists = shujiu.Devices.Where(x => !devname.Contains(x.DeviceName)).ToList();
//string ip = "";
//// 获取所有网络接口
//NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
//// 遍历每个网络接口
//foreach (NetworkInterface networkInterface in interfaces)
//{
// // 获取IP地址
// IPInterfaceProperties ipProperties = networkInterface.GetIPProperties();
// UnicastIPAddressInformationCollection ipAddresses = ipProperties.UnicastAddresses;
// // 遍历每个IP地址
// foreach (UnicastIPAddressInformation ipAddress in ipAddresses)
// {
// // 判断是否为IPv4地址
// if (ipAddress.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
// {
// //过滤本地ip
// if (ipAddress.Address.ToString() != "127.0.0.1")
// {
// //局域网ip
// ip = ipAddress.Address.ToString();
// }
// }
// }
//}
if (list.Count() > 0)
{ //sql案例
//UPDATE deviceinformation set Online = 1 where DeviceName = 'F305-00178'
for (int i = 0; i < list.Count(); i++)
{
sql = "UPDATE deviceinformation set Online = ";
sql += list[i].Online;
sql += " where DeviceName = ";
sql += "'" + list[i].DeviceName + "'";
using (MySqlConnection connection = new MySqlConnection(strSqliteConn))
{
using (MySqlCommand cmd = new MySqlCommand())
{
connection.Open();
cmd.Connection = connection;
var strSql = sql;
cmd.CommandText = strSql;
int retRecAffected = cmd.ExecuteNonQuery();
}
}
//sql = "insert into programeventlog(eventname,modifycontent,Online,ip,ctime) value(";
//sql += "'访问腾讯云所以设备列表,修改本地设备状态',";
//sql += "'" + list[i].DeviceName + "',";
//sql += list[i].Online + ",";
//sql += "'" + ip + "',";
//sql += "'" + DateTime.Now + "')";
//using (MySqlConnection connection = new MySqlConnection(strSqliteConn))
//{
// using (MySqlCommand cmd = new MySqlCommand())
// {
// connection.Open();
// cmd.Connection = connection;
// cmd.CommandText = sql;
// int retRecAffected = cmd.ExecuteNonQuery();
// }
//}
if (list[i].Online == 0 || list[i].Online == 3)
{
sql = "UPDATE deviceinformation set districtinfo = ";
sql += "' '";
sql += " where DeviceName = ";
sql += "'" + list[i].DeviceName + "'";
using (MySqlConnection connection = new MySqlConnection(strSqliteConn))
{
using (MySqlCommand cmd = new MySqlCommand())
{
connection.Open();
cmd.Connection = connection;
var strSql = sql;
cmd.CommandText = strSql;
int retRecAffected = cmd.ExecuteNonQuery();
}
}
////日志记录
//sql = "insert into programeventlog(eventname,modifycontent,ip,ctime) value(";
//sql += "'访问腾讯云所以设备列表,修改本地设备地址消息为空',";
//sql += "'设备名称:" + list[i].DeviceName + "',";
//sql += "'" + ip + "',";
//sql += "'" + DateTime.Now + "')";
//using (MySqlConnection connection = new MySqlConnection(strSqliteConn))
//{
// using (MySqlCommand cmd = new MySqlCommand())
// {
// connection.Open();
// cmd.Connection = connection;
// cmd.CommandText = sql;
// int retRecAffected = cmd.ExecuteNonQuery();
// }
//}
}
}
}
//日志记录
//List<deviceinformation> listdsd = new List<deviceinformation>();
//for (int j = 0; j < list.Count(); j++)
//{
// deviceinformation listdsds = shujiu.Devices.Where(x => x.Online != devOnline[j]).FirstOrDefault();
// if (listdsds != null)
// {
// listdsd.Add(listdsds);
// }
//}
//for (int p = 0; p < list.Count(); p++)
//{
if (lists.Count() > 0)
{
//sql案例
// insert into deviceinformation(DeviceName, Online, LoginTime, Version,
//DeviceCert, DevicePsk, DeviceType, Imei, Isp, ConnIP, LastUpdateTime, LoraDevEui,LoraMoteType, FirstOnlineTime, LastOfflineTime, CreateTime, LogLevel, CertState, EnableState,
//ClientIP, FirmwareUpdateTime, CreateUserId, NBIoTDeviceID)value(
//'1', 1, '1211321', '12331424', '123424242253', 'bdsnnskj', 2, 'daghj', 'safdag', 'vsghs','11', '1213', 1, 'wqewe', 'ahdauf', 'adawd', 12, 2, 3, 'dwda', 'dada', 12, '1221212')
for (int i = 0; i < lists.Count(); i++)
{
sql = "insert into deviceinformation(DeviceName, Online, LoginTime, Version,DeviceCert, DevicePsk, DeviceType, Imei, Isp, ConnIP, LastUpdateTime, LoraDevEui,LoraMoteType, FirstOnlineTime, LastOfflineTime, CreateTime, LogLevel, CertState, EnableState,ClientIP, FirmwareUpdateTime, CreateUserId, NBIoTDeviceID) value(";
sql += "'" + lists[i].DeviceName + "',";
sql += lists[i].Online + ",";
sql += "'" + lists[i].LoginTime + "',";
sql += "'" + lists[i].Version + "',";
sql += "'" + lists[i].DeviceCert + "',";
sql += "'" + lists[i].DevicePsk + "',";
sql += lists[i].DeviceType + ",";
sql += "'" + lists[i].Imei + "',";
sql += "'" + lists[i].Isp + "',";
sql += "'" + lists[i].ConnIP + "',";
sql += "'" + lists[i].LastUpdateTime + "',";
sql += "'" + lists[i].LoraDevEui + "',";
sql += lists[i].LoraMoteType + ",";
sql += "'" + lists[i].FirstOnlineTime + "',";
sql += "'" + lists[i].LastOfflineTime + "',";
sql += "'" + lists[i].CreateTime + "',";
sql += lists[i].LogLevel + ",";
sql += lists[i].CertState + ",";
sql += lists[i].EnableState + ",";
sql += "'" + lists[i].ClientIP + "',";
sql += "'" + lists[i].FirmwareUpdateTime + "',";
sql += lists[i].CreateUserId + ",";
sql += "'" + lists[i].NBIoTDeviceID + "')";
using (MySqlConnection connection = new MySqlConnection(strSqliteConn))
{
using (MySqlCommand cmd = new MySqlCommand())
{
connection.Open();
cmd.Connection = connection;
var strSql = sql;
cmd.CommandText = strSql;
int retRecAffected = cmd.ExecuteNonQuery();
}
}
////日志记录
//sql = "insert into programeventlog(eventname,modifycontent,Onlineip,ctime) value(";
//sql += "'访问腾讯云所以设备列表,添加设备消息',";
//sql += "'" + list[i].DeviceName + "',";
//sql += list[i].Online + ",";
//sql += "'" + ip + "',";
//sql += "'" + DateTime.Now + "')";
//using (MySqlConnection connection = new MySqlConnection(strSqliteConn))
//{
// using (MySqlCommand cmd = new MySqlCommand())
// {
// connection.Open();
// cmd.Connection = connection;
// cmd.CommandText = sql;
// int retRecAffected = cmd.ExecuteNonQuery();
// }
//}
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public List<string> Get(string productid, string devicename, string stime, string etime,int cmdname)
{
List<string> t = new List<string>();
t = SQLiteDBHelper.GetLOGCallin(productid, devicename, stime, etime, cmdname);
return t;
}
// POST api/<controller>
public void Post([FromBody] string value)
{
}
// PUT api/<controller>/5
public void Put(int id, [FromBody] string value)
{
}
// DELETE api/<controller>/5
public void Delete(int id)
{
}
}
}

View File

@@ -0,0 +1,389 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using TencentCloud.Common;
using TencentCloud.Common.Profile;
using TencentCloud.Iotcloud.V20210408;
using TencentCloud.Iotcloud.V20210408.Models;
using Newtonsoft.Json.Linq;
namespace MQTTServerSideAPI.Controllers
{
public class MessageSendController : ApiController
{
public static UInt16 snNum = 0;
// GET api/<controller>
public List<string> Get(string productid,string devicename)
{
List<string> t = new List<string>();
t = SQLiteDBHelper.GetLOGCallin(productid, devicename);
return t;
}
// GET api/<controller>/5
public string Get(int id)
{
return "value";
}
//public static string PostDownCmd6(String strDevice, UInt32 uintCustTSP, int rspType=1)
//{
// if (String.IsNullOrWhiteSpace(strDevice))
// strDevice = "F305-00003";
// string strTopic = "HICL5RNXAU/" + strDevice + "/control";
// string strProductId = "HICL5RNXAU";
// string strDeviceName = strDevice;
// string strBytesPara1 = "00 00 00 00 00 00"
// + "00 00 00 00 00 00"
// + "00 00 00 00 00 00"
// + "00 00 00 00 00 00"
// + "00 00 00 00 00 00";
// DateTimeOffset tof = new DateTimeOffset(DateTime.UtcNow);
// byte[] timeNow = BitConverter.GetBytes((UInt32)(tof.ToUnixTimeSeconds()));
// Logger.LogCalloutanaSide("\r\n命令06回复设备3设备" + strDevice + " TSP:" + uintCustTSP + " rspType:" + rspType);
// byte a;
// int paraLen = 0;
// byte[] tmpParaBt = new byte[400];
// string strBytesPara = "";
// if (rspType == 1) //MAC
// {
// tmpParaBt[paraLen] = 0x01;
// paraLen++;
// strBytesPara = strBytesPara1;
// strBytesPara = strBytesPara.Trim();
// if (!String.IsNullOrWhiteSpace(strBytesPara))
// {
// strBytesPara = strBytesPara.Trim();
// string[] hexes = strBytesPara.Split(' ');
// for (int i = 0; i < hexes.Length; i++)
// {
// a = Convert.ToByte(hexes[i], 16);
// tmpParaBt[paraLen] = a;
// paraLen++;
// }
// }
// }
// else // == 2, TimeStamp
// {
// tmpParaBt[paraLen] = 0x02;
// paraLen++;
// if (uintCustTSP != 0)
// {
// byte[] timeNow1 = BitConverter.GetBytes(uintCustTSP);
// tmpParaBt[paraLen] = timeNow1[0];
// paraLen++;
// tmpParaBt[paraLen] = timeNow1[1];
// paraLen++;
// tmpParaBt[paraLen] = timeNow1[2];
// paraLen++;
// tmpParaBt[paraLen] = timeNow1[3];
// paraLen++;
// string downstr1 = "";
// for (int i = paraLen-4; i < paraLen; i++)
// {
// downstr1 += tmpParaBt[i].ToString("X2");
// }
// Logger.LogCalloutanaSide("\r\n命令06回复设备3.5 ,时间戳字节:" + downstr1);
// }
// else
// {
// tmpParaBt[paraLen] = timeNow[0];
// paraLen++;
// tmpParaBt[paraLen] = timeNow[1];
// paraLen++;
// tmpParaBt[paraLen] = timeNow[2];
// paraLen++;
// tmpParaBt[paraLen] = timeNow[3];
// paraLen++;
// }
// }
// Logger.LogCalloutanaSide("\r\n命令06回复设备4");
// byte[] fixedHead = new byte[12];
// fixedHead[0] = 0xA6;
// snNum++;
// byte[] btSn = BitConverter.GetBytes(snNum);
// fixedHead[1] = btSn[0];
// fixedHead[2] = btSn[1];
// fixedHead[3] = timeNow[0];
// fixedHead[4] = timeNow[1];
// fixedHead[5] = timeNow[2];
// fixedHead[6] = timeNow[3];
// fixedHead[10] = 0x01;
// fixedHead[11] = 0x06;
// Logger.LogCalloutanaSide("\r\n命令06回复设备5");
// int resultLen = 0;
// byte[] resultByte = new byte[500];
// for (int i = 0; i < fixedHead.Length; i++)
// {
// resultByte[resultLen] = fixedHead[i];
// resultLen++;
// }
// for (int i = 0; i < paraLen; i++)
// {
// resultByte[resultLen] = tmpParaBt[i];
// resultLen++;
// }
// byte[] lenbtye = BitConverter.GetBytes((UInt16)resultByte.Length);
// resultByte[7] = lenbtye[0];
// resultByte[8] = lenbtye[1];
// //校验和
// resultByte[9] = 0x00;
// resultByte[9] = GetCheckSum(resultByte, resultLen);
// string resultBase64 = Convert.ToBase64String(resultByte, 0, resultLen);
// Logger.LogCalloutanaSide("\r\n命令06回复设备6");
// string downstr = "";
// for (int i = 0; i < resultLen; i++)
// {
// downstr += resultByte[i].ToString("X2");
// }
// Logger.LogCalloutanaSide("\r\n下发命令字节" + downstr);
// string retString = SendMQTTServerAPI(strProductId, strDeviceName, strTopic, resultBase64);
// Logger.LogCalloutanaSide("\r\n命令06回复设备7");
// return retString;
//}
// POST api/<controller>
public string Post([FromBody] JObject uisenddata)
{
string retString = "value";
string strTopic = (String)uisenddata["topic"];
string strProductId = (String)uisenddata["productid"];
string strDeviceName = (String)uisenddata["devicename"];
string strCmd = (String)uisenddata["cmd"];
string strBytesPara = (String)uisenddata["bytepara"];
byte a;
int paraLen = 0;
byte[] tmpParaBt = new byte[400];
strBytesPara = strBytesPara.Trim();
if(!String.IsNullOrWhiteSpace(strBytesPara))
{
strBytesPara = strBytesPara.Trim();
string[] hexes = strBytesPara.Split(' ');
for(int i = 0; i < hexes.Length; i ++)
{
a = Convert.ToByte(hexes[i], 16);
tmpParaBt[paraLen] = a;
paraLen++;
}
}
DateTimeOffset tof = new DateTimeOffset(DateTime.UtcNow);
byte[] fixedHead = new byte[12];
fixedHead[0] = 0xA6;
snNum++;
byte[] btSn = BitConverter.GetBytes(snNum);
fixedHead[1] = btSn[0];
fixedHead[2] = btSn[1];
byte[] timeNow = BitConverter.GetBytes((UInt32)(tof.ToUnixTimeSeconds()));
fixedHead[3] = timeNow[0];
fixedHead[4] = timeNow[1];
fixedHead[5] = timeNow[2];
fixedHead[6] = timeNow[3];
fixedHead[10] = 0x01;
if (strCmd == "06")
fixedHead[11] = 0x06;
else if (strCmd == "07")
fixedHead[11] = 0x07;
else if (strCmd == "08")
fixedHead[11] = 0x08;
else if (strCmd == "09")
fixedHead[11] = 0x09;
else
fixedHead[11] = Convert.ToByte(strCmd, 16);
int resultLen = 0;
byte[] resultByte = new byte[500];
for(int i = 0; i < fixedHead.Length; i ++)
{
resultByte[resultLen] = fixedHead[i];
resultLen++;
}
for (int i = 0; i < paraLen; i++)
{
resultByte[resultLen] = tmpParaBt[i];
resultLen++;
}
byte[] lenbtye = BitConverter.GetBytes((UInt16)resultLen);
resultByte[7] = lenbtye[0];
resultByte[8] = lenbtye[1];
//校验和
resultByte[9] = 0x00;
resultByte[9] = GetCheckSum(resultByte, resultLen);
string downstr = "";
for(int i = 0; i < resultLen; i ++)
{
downstr += resultByte[i].ToString() + " ";
}
Logger.LogCalloutanaSide("设备"+strDeviceName + "下发命令字节:" + downstr);
string resultBase64 = Convert.ToBase64String(resultByte, 0, resultLen);
try
{
// 实例化一个认证对象,入参需要传入腾讯云账户 SecretId 和 SecretKey此处还需注意密钥对的保密
// 代码泄露可能会导致 SecretId 和 SecretKey 泄露并威胁账号下所有资源的安全性。以下代码示例仅供参考建议采用更安全的方式来使用密钥请参见https://cloud.tencent.com/document/product/1278/85305
// 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
Credential cred = new Credential
{
SecretId = "AKIDKhz84sbEqFPRK1Uo0zUnwwjNp4884vc4",
SecretKey = "JQ8qZGxgQAtbCfvxb7VqzxujOtFVb1KT"
};
// 实例化一个client选项可选的没有特殊需求可以跳过
ClientProfile clientProfile = new ClientProfile();
// 实例化一个http选项可选的没有特殊需求可以跳过
HttpProfile httpProfile = new HttpProfile();
httpProfile.Endpoint = ("iotcloud.tencentcloudapi.com");
clientProfile.HttpProfile = httpProfile;
// 实例化要请求产品的client对象,clientProfile是可选的
IotcloudClient client = new IotcloudClient(cred, "ap-guangzhou", clientProfile);
// 实例化一个请求对象,每个接口都会对应一个request对象
PublishMessageRequest req = new PublishMessageRequest();
req.Topic = strTopic; // "HICL5RNXAU/F305-00002/control";
req.Payload = resultBase64;
req.ProductId = strProductId; // "HICL5RNXAU";
req.DeviceName = strDeviceName; // "F305-00002";
req.PayloadEncoding = "base64";
Logger.LogDownSide(String.Format("Send request: req.Topic:{0}, req.PayLoad:{1}, req.ProductId:{2}, req.DeviceName:{3}",
req.Topic,
req.Payload,
req.ProductId,
req.DeviceName
));
// 返回的resp是一个PublishMessageResponse的实例与请求对象对应
PublishMessageResponse resp = client.PublishMessageSync(req);
// 输出json格式的字符串回包
retString = "Success " + AbstractModel.ToJsonString(resp);
Logger.LogDownSide("Success return !! " + retString);
}
catch (Exception e)
{
if (e.InnerException != null)
retString = "Error " + e.InnerException.ToString();
Logger.LogDownSide("Failed exception !! " + e.ToString());
}
return retString;
}
//public static string SendMQTTServerAPI(string strProductId, string strDeviceName, string strTopic, string resultBase64)
//{
// string retString = "";
// try
// {
// // 实例化一个认证对象,入参需要传入腾讯云账户 SecretId 和 SecretKey此处还需注意密钥对的保密
// // 代码泄露可能会导致 SecretId 和 SecretKey 泄露并威胁账号下所有资源的安全性。以下代码示例仅供参考建议采用更安全的方式来使用密钥请参见https://cloud.tencent.com/document/product/1278/85305
// // 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
// Credential cred = new Credential
// {
// SecretId = "AKIDKhz84sbEqFPRK1Uo0zUnwwjNp4884vc4",
// SecretKey = "JQ8qZGxgQAtbCfvxb7VqzxujOtFVb1KT"
// };
// // 实例化一个client选项可选的没有特殊需求可以跳过
// ClientProfile clientProfile = new ClientProfile();
// // 实例化一个http选项可选的没有特殊需求可以跳过
// HttpProfile httpProfile = new HttpProfile();
// httpProfile.Endpoint = ("iotcloud.tencentcloudapi.com");
// clientProfile.HttpProfile = httpProfile;
// // 实例化要请求产品的client对象,clientProfile是可选的
// IotcloudClient client = new IotcloudClient(cred, "ap-guangzhou", clientProfile);
// // 实例化一个请求对象,每个接口都会对应一个request对象
// PublishMessageRequest req = new PublishMessageRequest();
// req.Topic = strTopic; // "HICL5RNXAU/F305-00002/control";
// req.Payload = resultBase64;
// req.ProductId = strProductId; // "HICL5RNXAU";
// req.DeviceName = strDeviceName; // "F305-00002";
// req.PayloadEncoding = "base64";
// Logger.LogDownSide(String.Format("Send request: req.Topic:{0}, req.PayLoad:{1}, req.ProductId:{2}, req.DeviceName:{3}",
// req.Topic,
// req.Payload,
// req.ProductId,
// req.DeviceName
// ));
// // 返回的resp是一个PublishMessageResponse的实例与请求对象对应
// PublishMessageResponse resp = client.PublishMessageSync(req);
// // 输出json格式的字符串回包
// retString = "Success " + AbstractModel.ToJsonString(resp);
// Logger.LogDownSide("Success return !! " + retString);
// }
// catch (Exception e)
// {
// if (e.InnerException != null)
// retString = "Error " + e.InnerException.ToString();
// Logger.LogDownSide("Failed exception !! " + e.ToString());
// }
// return retString;
//}
public static byte GetCheckSum(byte[] data, int datalen)
{
List<byte> m = new List<byte>();
int sum = 0;
for (int i = 0; i < datalen; i++)
{
m.Add(data[i]);
sum += data[i];
}
sum = sum % 256;
//sum = ~sum + 1; 跟设备端操作对过不用加1
sum = ~sum;
return (byte)sum;
}
// PUT api/<controller>/5
public void Put(int id, [FromBody] string value)
{
}
// DELETE api/<controller>/5
public void Delete(int id)
{
}
}
}

View File

@@ -0,0 +1,65 @@
using MQTTServerSideAPI.Models;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Helpers;
using System.Web.Http;
using System.Xml.Linq;
namespace MQTTServerSideAPI.Controllers
{
public class StateController : ApiController
{
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET: api/State
public List<string> Get(string devicename,string stime,string etime)
{
return SQLiteDBHelper.GetSelectStatus(devicename, stime, etime);
}
// GET: api/State/5
public List<string> Get(string productid, string devicename,string times, string Statuss)
{
return SQLiteDBHelper.GetSelectStatus(productid, devicename, times, Statuss);
}
public List<string> Get(string productid, string devicename)
{
return SQLiteDBHelper.GetSelectStatus(productid, devicename);
}
//public StateByecharts Get(string devicename)
//{
// return SQLiteDBHelper.GetSelectStatus(devicename); ;
//}
// POST: api/State
public void Post([FromBody] JObject mqttmessage)
{
//Logger.LogCalloutanaSide("StateController" + mqttmessage);
SQLiteDBHelper.InsertState(mqttmessage);
}
// PUT: api/State/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE: api/State/5
public void Delete(int id)
{
}
}
}

View File

@@ -0,0 +1,240 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Helpers;
using System.Web.Http;
using Microsoft.Ajax.Utilities;
using MQTTServerSideAPI.Models;
using System.Web;
using System.Text;
using TencentCloud.Common;
using TencentCloud.Common.Profile;
using TencentCloud.Iotcloud.V20210408;
using TencentCloud.Iotcloud.V20210408.Models;
using Newtonsoft.Json.Linq;
using System.Data.SQLite;
using System.Data;
using static MQTTServerSideAPI.SQLiteDBHelper;
using MySql.Data.MySqlClient;
using System.Timers;
using System.Web.UI.WebControls.WebParts;
using MySqlX.XDevAPI.Relational;
using System.Xml.Linq;
using System.Threading;
using System.Web.UI;
namespace MQTTServerSideAPI.Controllers
{
public class ValuesController : ApiController
{
public static int count = 0;
public List<string> Get(string devname, string startT, string endT, string productid, int cmdname = 3)
{
//List<string> t = new List<string>();
//t = SQLiteDBHelper.GetLOGCallin(productid, devname, startT, endT, cmdname);
//return t;
return SQLiteDBHelper.GetAllpowerstatisticschart(devname, startT, endT, productid, cmdname);
}
public static Dictionary<string, DateTime> nameData = new Dictionary<string, DateTime>();
public void Post([FromBody] JObject mqttmessage)//这个是腾讯那边发过来的包,设备发的包是包在这个包里面的。
{
//SQLiteDBHelper.InsertCallin(mqttmessage);
//Logger.LogCalloutanaSide("准备开始线程:" + count);
Thread revT = new Thread(xianc.InsertCallindd);
revT.Start(mqttmessage);
//byte[] btTmp = Convert.FromBase64String(mqttmessage["payload"].ToString());//取到设备发出来的原始包。
//Logger.LogCalloutanaSide("设备" + mqttmessage["devicename"] + "上报字节:" + GetHexStringFromByteArray(btTmp));
}
// PUT api/values/5
public void Put(int id, [FromBody] string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
}
public static class xianc
{
public static void InsertCallindd(object mqqt)
{
try
{
JObject mqttmessage = (mqqt as JObject);
SQLiteDBHelper.InsertCallin(mqttmessage);
byte[] btTmp = Convert.FromBase64String(mqttmessage["payload"].ToString());//取到设备发出来的原始包。
StringBuilder sb = new StringBuilder();
for (int i = 0; i < btTmp.Length; i++)
{
sb.Append(btTmp[i].ToString("X2") + " ");
}
FixedHeaderPart headerPart = SQLiteDBHelper.AnalysisFixedHeader(btTmp);
string yuanshidata = GetHexStringFromByteArray(btTmp);
try
{
//10 当前取电状态
string strResult = "";
headerPart.PowerStatus = btTmp[10];
if (btTmp[10] == 0x00)
strResult = "无效";
else if (btTmp[10] == 0x01)
strResult = "取电";
else if (btTmp[10] == 0x02)
strResult = "断电";
else
strResult = "无效值";
switch (btTmp[11])
{
case 0x04: //设备上报定期动作
IntervalMessagePara paraInt = AnalysisIntervalMessagePara(btTmp.Skip(12).ToArray());
string sql = "INSERT INTO deviceelectricquantity(devicename,lockElectricQuantity,PIR1ElectricQuantity,PIR2ElectricQuantity,PIR3ElectricQuantity,PIR4ElectricQuantity,GMElectricQuantity,creationtime,Power,PIR5ElectricQuantity,PIR6ElectricQuantity,PIR7ElectricQuantity,PIR8ElectricQuantity)select ";
sql += "'" + mqttmessage["devicename"] + "',";
sql += paraInt.LockCapacity + ",";
sql += paraInt.PIR1Capacity + ",";
sql += paraInt.PIR2Capacity + ",";
sql += paraInt.PIR3Capacity + ",";
sql += paraInt.PIR4Capacity + ",";
sql += paraInt.GatemagnetCapacity + ",";
sql += "'" + DateTime.Now + "', ";
sql += "'" + paraInt.CheckP + "', ";
sql += paraInt.PIR5Capacity + ",";
sql += paraInt.PIR6Capacity + ",";
sql += paraInt.PIR7Capacity + ",";
sql += paraInt.PIR8Capacity;
sql += " where not exists(select 1 from deviceelectricquantity where devicename = '" + mqttmessage["devicename"] + "' and creationtime > date_add('" + DateTime.Now + "', interval - 1 hour));";
using (MySqlConnection connection = new MySqlConnection(strSqliteConn))
{
using (MySqlCommand cmd = new MySqlCommand())
{
connection.Open();
cmd.Connection = connection;
//var strSqlname = sql;
cmd.CommandText = sql;
int retRecAffected = cmd.ExecuteNonQuery();
}
}
string strSqlCmd = "select DeviceName from deviceinformation where `Online`= 1 and DeviceName LIKE " + "'%" + mqttmessage["devicename"] + "%'";
DataSet ds = new DataSet();
using (MySqlConnection connection = new MySqlConnection(strSqliteConn))
{
using (MySqlCommand cmd = new MySqlCommand())
{
connection.Open();
cmd.Connection = connection;
MySqlDataAdapter command = new MySqlDataAdapter(strSqlCmd, connection);
command.Fill(ds);
}
}
if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
{
foreach (DataRow row in ds.Tables[0].Rows)
{
string pw = "";
if (paraInt.CheckP.ToString().Length >= 8)
{
pw = paraInt.CheckP.ToString().Substring(0, 8);
}
string updatesql = "update deviceinformation set ";
updatesql += " powerintakestatus='" + strResult + "',";
updatesql += "Power='" + pw + "',";
updatesql += "pir1status='" + paraInt.PIR1OnlineStatus + "',";
updatesql += "pir2status='" + paraInt.PIR2OnlineStatus + "',";
updatesql += "pir3status='" + paraInt.PIR3OnlineStatus + "',";
updatesql += "pir4status='" + paraInt.PIR4OnlineStatus + "',";
updatesql += "gatemagnetstatus='" + paraInt.GatemagnetStatus + "',";
updatesql += "pir5status='" + paraInt.PIR5OnlineStatus + "',";
updatesql += "pir6status='" + paraInt.PIR6OnlineStatus + "',";
updatesql += "pir7status='" + paraInt.PIR7OnlineStatus + "',";
updatesql += "pir8status='" + paraInt.PIR8OnlineStatus + "' ";
updatesql += " where DeviceName='" + row["DeviceName"] + "'";
using (MySqlConnection connection = new MySqlConnection(strSqliteConn))
{
using (MySqlCommand cmd = new MySqlCommand())
{
connection.Open();
cmd.Connection = connection;
cmd.CommandText = updatesql;
int retRecAffected = cmd.ExecuteNonQuery();
}
}
}
}
break;
case 0x0C: //设备启动信息
DeviceStartPara paradvst = AnalysisDeviceStartPara(btTmp.Skip(12).ToArray());
string strSqlCmds = "select DeviceName from deviceinformation where `Online`= 1 and DeviceName LIKE " + "'%" + mqttmessage["devicename"] + "%'";
DataSet dss = new DataSet();
using (MySqlConnection connection = new MySqlConnection(strSqliteConn))
{
using (MySqlCommand cmd = new MySqlCommand())
{
connection.Open();
cmd.Connection = connection;
MySqlDataAdapter command = new MySqlDataAdapter(strSqlCmds, connection);
command.Fill(dss);
}
}
if (dss.Tables.Count > 0 && dss.Tables[0].Rows.Count > 0)
{
foreach (DataRow row in dss.Tables[0].Rows)
{
string pw = "";
string updatesql = "update deviceinformation set ";
updatesql += "powerOnEquipment='" + paradvst.reason + "',";
updatesql += "equipmenttime='" + DateTime.Now + "',";
updatesql += "powerOnEquipmentinfo='" + paradvst.strHex + "',";
updatesql += "yingjianbanbinfo='" + paradvst.verHardware + "',";
updatesql += "ruanjianbanbinfo='" + paradvst.verHigh + "."+ paradvst.verLow + "' ";
updatesql += " where DeviceName='" + row["DeviceName"] + "'";
using (MySqlConnection connection = new MySqlConnection(strSqliteConn))
{
using (MySqlCommand cmd = new MySqlCommand())
{
connection.Open();
cmd.Connection = connection;
cmd.CommandText = updatesql;
int retRecAffected = cmd.ExecuteNonQuery();
}
}
}
}
break;
}
}
catch (Exception ex)
{
Logger.LogCalloutanaSide("直接解析错误:" + ex);
}
//Thread.Sleep(20000);
}
catch (Exception ex)
{
Logger.LogCalloutanaSide("多线程错误:" + ex);
}
}
}
}

View File

@@ -0,0 +1,43 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Web.Http;
using System.Xml.Linq;
namespace MQTTServerSideAPI.Controllers
{
public class propmaeinfo
{
public string Name { get; set; }
public string Description { get; set; }
public string Type { get; set; }
public string TypeDescription { get; set; }
}
public class ceshiapiController : ApiController
{
// POST: api/ceshiapi
public string Post([FromBody] string valuedsfsfs)
{
Logger.LogCalloutanaSide("准备开始线程:");
Thread revT = new Thread(sfsfds.InsertCallindd);
revT.Start(valuedsfsfs);
Logger.LogCalloutanaSide("准备了一个线程:");
return "dssssssssssssssssss";
}
}
public static class sfsfds
{
public static void InsertCallindd(object name)
{
Console.WriteLine(name);
}
}
}