初始化

This commit is contained in:
2025-12-11 14:04:39 +08:00
commit 1f65bbf628
2676 changed files with 838983 additions and 0 deletions

View File

@@ -0,0 +1,136 @@
using System.Text;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Scripting.Utils;
using IotManager.Common;
using ViewModels;
using CommonEntity;
namespace SupplierManager.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class ConfigPYController : ControllerBase
{
[HttpPost()]
[Authorize()]
public async Task<ReturnInfo> GetConfigString()
{
ReturnInfo r = new ReturnInfo();
try
{
string[] str = await System.IO.File.ReadAllLinesAsync("script\\webapi.py");
List<VK> ll = new List<VK>();
foreach (var item in str)
{
if (!string.IsNullOrWhiteSpace(item))
{
string[] a = item.Split('=');
VK v = new VK();
v.VarName = a[0];
v.VarValue = a[1];
ll.Add(v);
}
}
r.isok = true;
r.response = ll;
}
catch (Exception ex)
{
r.isok = false;
r.message = ex.Message;
}
return r;
}
[HttpPost()]
[Authorize()]
public ReturnInfo RefreshConfig()
{
ReturnInfo info = new ReturnInfo();
info.isok = true;
try
{
StaticData.GetWebAPIMethod();
StaticData.GetWebAPIMethod1();
info.message = "Sucess";
}
catch (Exception ex)
{
info.isok = false;
info.message = ex.Message;
}
return info;
}
public class VK
{
public string VarName { get; set; }
public string VarValue { get; set; }
}
[HttpPost()]
[Authorize()]
public async Task<ReturnInfo> SaveOrAddConfigString([FromBody] VK data)
{
ReturnInfo info = new ReturnInfo();
info.isok = true;
try
{
var sss = System.IO.File.ReadAllLines("script\\webapi.py", Encoding.UTF8).ToList<string>();
for (int i = 0; i < sss.Count; i++)
{
string item = sss[i];
string[] txtdata = item.Split('=');
if (txtdata[0].Equals(data.VarName))
{
txtdata[1] = data.VarValue;
sss[i] = txtdata[0] + "=" + txtdata[1];
}
}
bool exists = sss.Any(A => A.StartsWith(data.VarName));
if (exists == false)
{
sss.AddRange<string>(new string[] { data.VarName + "=" + data.VarValue });
}
await System.IO.File.WriteAllLinesAsync("script\\webapi.py", sss, Encoding.UTF8);
StaticData.GetWebAPIMethod();
info.message = "Sucess";
}
catch (Exception ex)
{
info.isok = false;
info.message = ex.Message;
}
return info;
}
[HttpPost()]
[Authorize()]
public ReturnInfo GetSingleValue([FromBody] Dictionary<string, string> dic)
{
ReturnInfo info = new ReturnInfo();
info.isok = true;
try
{
string VarValue = dic["VarName"];
if (!string.IsNullOrEmpty(VarValue))
{
var QQQ = StaticData.scope1.GetVariable(VarValue);
string str = System.Text.Json.JsonSerializer.Serialize(QQQ);
info.response = str;
}
}
catch (Exception ex)
{
info.isok = false;
info.message = ex.Message;
}
return info;
}
}
}

View File

@@ -0,0 +1,472 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using Common;
using CommonEntity;
using IotManager.Common;
using LogCap.Common;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.VisualBasic;
using MySQLAccess.PGModels;
using NLog;
using NPOI.OpenXmlFormats.Dml;
using Proto.Extensions;
using RestSharp;
using ViewModels;
namespace IotManager.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class DeviceinfoesController : ControllerBase
{
private readonly Logger _logger = LogManager.GetCurrentClassLogger();
private readonly PostgresContext _context;
public DeviceinfoesController(PostgresContext context)
{
_context = context;
}
// GET: api/Deviceinfoes
[HttpPost()]
public async Task<ReturnInfo> GetDeviceinfos(QueryAll_Or_Single Q)
{
ReturnInfo r = new ReturnInfo();
try
{
if (Q.IsAll)
{
r.isok = true;
r.response = await _context.Deviceinfos.ToListAsync();
}
else
{
var deviceinfo = await _context.Deviceinfos.FindAsync(Q.ID);
if (deviceinfo == null)
{
r.isok = false;
r.message = "找不到此数据";
}
r.isok = true;
r.response = deviceinfo;
}
}
catch (Exception ex)
{
r.isok = false;
r.message = ex.Message;
}
return r;
}
[HttpPost()]
public async Task<ReturnInfo> GetAllBatchFlag(QueryMachineType S)
{
ReturnInfo r = new ReturnInfo();
try
{
int one = S.MachineType;
var st = S.StartTime;
var et = S.EndTime;
var ST = DateTime.Parse(st);
var ET = DateTime.Parse(et);
var data = await _context.Deviceinfos.Where(A => A.MachineType == one && A.CreateTime > ST && A.CreateTime <= ET)
.GroupBy(d => d.ExcelBatchFlag)
.Select(g => new
{
ExcelBatchFlag = g.Key.ToString(),
CreateTime = g.Select(x => x.CreateTime).FirstOrDefault(),
Count = g.Count()
})
.ToListAsync();
r.isok = true;
r.response = data;
return r;
}
catch (Exception ex)
{
r.isok = false;
r.response = ex.Message;
}
return r;
}
[Authorize()]
[HttpPost()]
public async Task<ReturnInfo> GetDeviceinfosByBatchFlag(Dictionary<string, string> Q)
{
ReturnInfo r = new ReturnInfo();
try
{
string batchflag = Q["FileBatchFlag"];
long NNN = 0L;
long.TryParse(batchflag, out NNN);
var data = from a in _context.Deviceinfos
join b in _context.EmqxLogininfos
on a.Uuid equals b.DeviceUuid
into DeviceInfo
from d in DeviceInfo.DefaultIfEmpty()
where a.ExcelBatchFlag == NNN
select new { a.DeviceName, a.OrderNo, a.ClientId, a.SecretKey, a.Remark, d.PassWord };
var data1 = await data.Select(A => new DeviceInfoResponse
{
DeviceName = A.DeviceName,
MO = A.OrderNo,
ClientID = A.ClientId,
MQTT_Login_Password = A.PassWord,
Key = A.SecretKey,
Remark = A.Remark
}).ToListAsync();
r.isok = true;
r.response = data1;
}
catch (Exception ex)
{
r.isok = false;
r.response = ex.Message;
}
return r;
}
[Authorize()]
[HttpPost()]
public async Task<ReturnInfo> EditDeviceinfo(Deviceinfo deviceinfo)
{
ReturnInfo r = new ReturnInfo();
try
{
if (!DeviceinfoExists(deviceinfo.ClientId))
{
r.isok = false;
r.message = "not found";
return r;
}
_context.Entry(deviceinfo).State = EntityState.Modified;
await _context.SaveChangesAsync();
r.isok = true;
}
catch (Exception ex)
{
r.isok = false;
r.message = ex.Message;
}
return r;
}
public string GetId(string device_name, string uuid)
{
string NNN = PasswordGenerator.Generate(16);
//string data = string.Format("inhaos_{0}_{1}_{2}", device_name, uuid, NNN);
//// 密钥用于生成MAC
//string key = "[secNret)Key#&!";
//// 计算MAC
//byte[] mac = Base64.ComputeHMACSHA256(data, key);
//string str = Convert.ToBase64String(mac);
return NNN;
}
public record DeviceInfoRequest
{
public int id { get; set; }
public string DeviceName { get; set; }
public string MO { get; set; }
public int MachineType { get; set; }
public string Remark { get; set; }
}
public record DeviceInfoResponse
{
public string? DeviceName { get; set; }
public string? MO { get; set; }
public long? ClientID { get; set; }
public string? MQTT_Login_Password { get; set; }
public string? Key { get; set; }
public string? Remark { get; set; }
}
public record IdFilter
{
public int id { get; set; }
public string UUID { get; set; }
}
/// <summary>
/// 设备查询参数
/// </summary>
public class DeviceQueryParams
{
public int MachineType { get; set; }
public string Mcu_Uuid { get; set; }
public int? Brandld { get; set; }
}
public class UserData
{
public string username { get; set; }
public string password { get; set; }
}
[HttpPost()]
public async Task<string> SendHttpData(List<UserData> userdata)
{
string resp = "";
try
{
resp = await RedisWriter(userdata);
}
catch (Exception ex)
{
_logger.Error(ex.Message);
}
return resp;
}
private async Task<string> RedisWriter(List<UserData> userdata)
{
RestClient client1 = new RestClient("http://iot-manage.uts-data.com:5001");
string ti = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
var request1 = new RestRequest("/api/Values/SetChache", Method.Post);
request1.AddJsonBody(userdata);
var re = await client1.ExecuteAsync(request1);
string resp = re.Content;
_logger.Error("Redis缓存" + resp);
return resp;
}
[Authorize()]
[HttpPost]
public async Task<ReturnInfo> AddDeviceinfo(List<DeviceInfoRequest> List_LLL)
{
ReturnInfo returnInfo = new ReturnInfo();
try
{
var QQQ = List_LLL.Select(A => A.DeviceName);
var q1 = _context.Deviceinfos.Any(A => QQQ.Contains(A.DeviceName));
if (q1)
{
returnInfo.isok = false;
returnInfo.message = "设备名字重复,不可导入";
return returnInfo;
}
var worker = new IdWorker(31, 30);
long filebatch = worker.nextId();
List<UserData> lll = new List<UserData>();
_context.Database.BeginTransaction();
var DT = DateTime.Now;
var LT = Tools.ToUnixTimestampBySeconds(DT);
List<Deviceinfo> device_list = new List<Deviceinfo>();
List<EmqxLogininfo> login_list = new List<EmqxLogininfo>();
foreach (var LLL in List_LLL)
{
UserData u = new UserData();
var LLL1 = new Deviceinfo();
var uuid = Guid.NewGuid().ToString("N");
LLL1.Uuid = uuid;
LLL1.DeviceName = LLL.DeviceName;
LLL1.OrderNo = LLL.MO;
LLL1.MachineType = LLL.MachineType;
LLL1.SecretKey = PasswordGenerator.Generate(16);
LLL1.Remark = LLL.Remark;
LLL1.ExcelBatchFlag = filebatch;
LLL1.CreateTime = DT;
LLL1.UpdateTime = DT;
LLL1.CreateTimeUnix = LT;
LLL1.UpdateTimeUnix = LT;
device_list.Add(LLL1);
// 如果 是MQTT才会
if (LLL.MachineType != 1)
{
EmqxLogininfo l = new EmqxLogininfo();
l.DeviceUuid = uuid;
l.UserName = LLL.DeviceName;
l.PassWord = GetId(l.UserName, uuid);
l.UpdateTime = DT;
l.UpdateTimeUnix = LT;
l.CreateTime = DT;
l.CreateTimeUnix = LT;
login_list.Add(l);
u.username = LLL1.DeviceName;
u.password = l.PassWord;
lll.Add(u);
}
//_context.EmqxLogininfos.Add(l);
}
_context.Deviceinfos.AddRange(device_list);
_context.EmqxLogininfos.AddRange(login_list);
_context.SaveChanges();
if (lll.Count > 0)
{
string tr = await RedisWriter(lll);
if (!string.IsNullOrEmpty(tr))
{
var rest = JsonSerializer.Deserialize<ReturnInfo>(tr);
if (rest?.isok == false)
{
throw new Exception("Redis写入失败");
}
}
}
_context.Database.CommitTransaction();
returnInfo.response = filebatch.ToString();
returnInfo.isok = true;
}
catch (Exception ex)
{
returnInfo.isok = false;
returnInfo.message = ex.Message;
}
return returnInfo;
}
[HttpPost()]
public async Task<ReturnInfo> DeleteDeviceinfo(Dictionary<string, string> data)
{
ReturnInfo r = new ReturnInfo();
try
{
string id = data["id"];
var deviceinfo = await _context.Deviceinfos.FindAsync(id);
if (deviceinfo == null)
{
r.isok = false;
r.message = "not found this data";
}
_context.Deviceinfos.Remove(deviceinfo);
await _context.SaveChangesAsync();
}
catch (Exception ex)
{
r.isok = false;
r.isok = true;
}
return r;
}
/// <summary>
/// 条件查询接口 - 根据MachineType、UUID和Brandld查询唯一记录
/// </summary>
/// <param name="queryParams">查询参数</param>
/// <returns>查询结果</returns>
[HttpPost]
public async Task<ReturnInfo> GetDeviceByCondition(DeviceQueryParams queryParams)
{
ReturnInfo r = new();
try
{
var query = _context.Deviceinfos
.Where(d => d.MachineType == queryParams.MachineType && d.McuUuid.Equals(queryParams.Mcu_Uuid));
// 如果Brandld不为空则添加Brandld条件
if (queryParams.Brandld != null)
{
query = query.Where(d => d.Brandld == queryParams.Brandld);
}
var ddd = query.ToList();
var deviceinfo = await query.FirstOrDefaultAsync();
r.isok = true;
r.response = deviceinfo;
}
catch (Exception ex)
{
r.isok = false;
r.message = ex.Message;
}
return r;
}
private bool DeviceinfoExists(long id)
{
return _context.Deviceinfos.Any(e => e.ClientId == id);
}
/// <summary>
/// 条件查询并修改接口
/// </summary>
/// <param name="queryParams">查询参数</param>
/// <returns>查询或更新后的记录</returns>
[HttpPost]
public async Task<ReturnInfo> GetOrUpdateDevice(DeviceQueryParams queryParams)
{
ReturnInfo r = new();
try
{
// 第一步:根据条件查询
var query = _context.Deviceinfos
.Where(d => d.MachineType == queryParams.MachineType && d.McuUuid.Equals(queryParams.Mcu_Uuid));
// 如果Brandld不为空则添加Brandld条件
if (queryParams.Brandld != null)
{
query = query.Where(d => d.Brandld == queryParams.Brandld);
}
var deviceinfo = await query.FirstOrDefaultAsync();
if (deviceinfo == null)
{
// 第二步查询ClientId最小MachineType匹配且Uuid为空的记录
var minClientIdQuery = _context.Deviceinfos
.Where(d => d.MachineType == queryParams.MachineType && string.IsNullOrEmpty(d.McuUuid))
.OrderBy(d => d.ClientId);
var minClientIdDevice = await minClientIdQuery.FirstOrDefaultAsync();
if (minClientIdDevice != null)
{
// 第三步:更新记录
minClientIdDevice.McuUuid = queryParams.Mcu_Uuid;
minClientIdDevice.Brandld = queryParams.Brandld;
minClientIdDevice.UpdateTime = DateTime.Now;
minClientIdDevice.UpdateTimeUnix = Tools.ToUnixTimestampBySeconds(DateTime.Now);
_context.Deviceinfos.Update(minClientIdDevice);
await _context.SaveChangesAsync();
// 第四步:查询更新后的记录
deviceinfo = await _context.Deviceinfos.FindAsync(minClientIdDevice.ClientId);
}
}
r.isok = true;
r.response = deviceinfo;
}
catch (Exception ex)
{
r.isok = false;
r.message = ex.Message;
}
return r;
}
}
}

View File

@@ -0,0 +1,134 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
namespace SupplierManager.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class FileUploadController : ControllerBase
{
public static string[] FolderG = new string[] {"face" };
[Authorize()]
[HttpPost()]
public async Task<IActionResult> UploadFile([FromForm] UploadFileModel model)
{
if (model.File == null || model.File.Length == 0)
{
return BadRequest("没有上传任何文件");
}
try
{
// 获取文件名和扩展名
string originalFileName = Path.GetFileNameWithoutExtension(model.File.FileName);
string fileExtension = Path.GetExtension(model.File.FileName); // 包含扩展名前的点(如.jpg
// 生成8位GUID取完整GUID的前8位字符
string guidPart = Guid.NewGuid().ToString("N")[..16];
// 组合新文件名原文件名_8位GUID.扩展名
string newFileName = $"{originalFileName}_{guidPart}{fileExtension}";
var filePath = Path.Combine(Directory.GetCurrentDirectory(),
$"wwwroot/Uploads/{model.Folder}",
newFileName);
using (var stream = new FileStream(filePath, FileMode.Create))
{
await model.File.CopyToAsync(stream);
}
return Ok(new { FileName = newFileName });
}
catch (Exception ex)
{
return BadRequest(new { Message = ex.Message });
}
}
public record DF
{
public string? FileName { get; set; }
}
// 示例:通过文件名获取图片
[Authorize()]
[HttpPost()]
public IActionResult DownloadFile([FromBody]DF imageName)
{
try
{
// 拼接图片物理路径(假设图片存放在项目的 wwwroot/images 目录下)
var imagePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/", imageName.FileName);
// 检查文件是否存在
if (!System.IO.File.Exists(imagePath))
{
return NotFound("Image not found");
}
if (imageName.FileName.Contains(".."))
{
return BadRequest("Invalid file name");
}
// 读取文件流并返回
var imageStream = System.IO.File.OpenRead(imagePath);
// 根据扩展名自动设置 Content-TypeMIME类型
var mimeType = GetMimeType(imageName.FileName);
return File(imageStream, mimeType);
}
catch (Exception ex)
{
return StatusCode(500, $"Internal server error: {ex.Message}");
}
}
[Authorize()]
[HttpPost()]
public IActionResult GetFileNameList()
{
try
{
// 拼接图片物理路径(假设图片存放在项目的 wwwroot/images 目录下)
var filePath = Path.Combine(Directory.GetCurrentDirectory(),
$"wwwroot/Download/customization","");
string[] files= System.IO.Directory.GetFiles(filePath);
var myfiles= files.Select(A=>Path.GetFileName(A));
return Ok(new { FileNameList = myfiles });
}
catch (Exception ex)
{
return StatusCode(500, $"Internal server error: {ex.Message}");
}
}
// 获取 MIME 类型映射
private string GetMimeType(string fileName)
{
var extension = Path.GetExtension(fileName).ToLowerInvariant();
return
extension switch
{
".jpg" => "image/jpeg",
".jpeg" => "image/jpeg",
".png" => "image/png",
".gif" => "image/gif",
".xls" =>"application/vnd.ms-excel",
".xlsx"=>"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
_ => "application/octet-stream" // 默认类型
};
}
}
public class UploadFileModel
{
public IFormFile File { get; set; }
public string Folder { get; set; }
}
}

View File

@@ -0,0 +1,11 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace IotManager.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class GrafanaMonitorController : ControllerBase
{
}
}

View File

@@ -0,0 +1,144 @@
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using CommonEntity;
using IotManager.Common;
using IotManager.private_key;
using Jose;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using MySQLAccess.PGModels;
using NLog;
using ViewModels;
namespace IotManager.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class LoginController : ControllerBase
{
private readonly Logger _logger = LogManager.GetCurrentClassLogger();
public IConfiguration? configuration { get; set; }
private PostgresContext IotServerContext { get; set; }
public LoginController(IConfiguration _configuration, PostgresContext iot)
{
configuration = _configuration;
this.IotServerContext = iot;
}
/// <summary>
/// 登录
/// </summary>
/// <param name="username">用户名</param>
/// <param name="password">密码</param>
/// <returns></returns>
[HttpPost]
public ReturnInfo Login([FromBody] LoginData data)
{
ReturnInfo res = new ReturnInfo();
try
{
Userinfo? entity = null;
string password = data.password;
string username = data.username;
string TokenString = "";
//using (var q = new IotServerContext())
//{
entity = IotServerContext.Userinfos.SingleOrDefault(A => A.UserName.Equals(username));
if (entity != null)
{
bool vvv = JiaJieMi.VerifyHashedPassword(entity.PassWord, password);
if (vvv == false)
{
res.isok = false;
res.message = "密码错误";
}
else
{
TokenString = GetToken(entity);
res.isok = true;
ResLoginData r = new ResLoginData();
r.AccessToken = TokenString;
r.Id = entity.Id;
r.Permission = entity.Permission;
r.UserName = entity.UserName;
r.RealName = entity.RealName;
r.CompanyName = entity.CompanyName;
res.response = r;
}
}
else
{
res.isok = false;
res.message = "用户不存在";
}
//}
}
catch (Exception ex)
{
res.message = ex.Message;
res.isok = false;
}
return res;
}
public string GetToken([FromBody] Userinfo? entity)
{
string TokenString;
var claims = new Claim[]
{
new Claim(ClaimTypes.NameIdentifier, entity.Id.ToString()),
new Claim(ClaimTypes.Name, entity.UserName),
new Claim(ClaimTypes.Hash,Guid.NewGuid().ToString("N"))
};
var secretByte = Encoding.UTF8.GetBytes(configuration["JwT:SecretKey"]);
var signingKey = new SymmetricSecurityKey(secretByte);
var a = SecurityAlgorithms.HmacSha256;
var signingCredentials = new SigningCredentials(signingKey, a);
//有效期设置为1天signingCredentials //数字名
var token = new JwtSecurityToken(
issuer: configuration?["JwT:Issuer"],
audience: configuration?["JwT:Audience"],//接收
claims: claims,//存放的用户信息
notBefore: DateTime.UtcNow,//发布时间
expires: DateTime.UtcNow.AddHours(12),
signingCredentials: signingCredentials
);
TokenString = new JwtSecurityTokenHandler().WriteToken(token);
return TokenString;
}
[HttpPost()]
[Authorize()]
public string Helloooo(string key)
{
return "allow";
}
[HttpPost()]
public string MyTTT(DengLu key)
{
return "allow";
}
}
public class DengLu
{
public string UserName { get; set; }
public string PassWord { get; set; }
}
}

View File

@@ -0,0 +1,92 @@
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; }
}
}

View File

@@ -0,0 +1,167 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CommonEntity;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using MySQLAccess.PGModels;
namespace IotManager.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class MachineTypesController : ControllerBase
{
private readonly PostgresContext _context;
private readonly IConfiguration _config;
public MachineTypesController(PostgresContext context, IConfiguration config)
{
_context = context;
_config = config;
}
// GET: api/MachineTypes
[HttpPost()]
[Authorize()]
public async Task<ReturnInfo> GetMachineTypes(QueryAll_Or_Single Q)
{
ReturnInfo r = new ReturnInfo();
try
{
if (Q.IsAll)
{
r.isok = true;
r.response = await _context.MachineTypes.Where(A=>A.IsDelete==false).ToListAsync();
}
else
{
var machineType = await _context.MachineTypes.FindAsync(Q.ID);
if (machineType == null)
{
r.isok = false;
r.message = "找不到数据";
}
}
}
catch (Exception ex)
{
r.isok = false;
r.message = ex.Message;
}
return r;
}
// PUT: api/MachineTypes/5
// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
[HttpPost()]
public async Task<ReturnInfo> EditMachineType(MachineType machineType)
{
ReturnInfo r = new ReturnInfo();
try
{
if (!MachineTypeExistsById(machineType.Id))
{
r.message = "找不到这条数据";
r.isok = false;
}
else
{
r.isok = true;
machineType.UpdateTime = DateTime.Now;
_context.Entry(machineType).State = EntityState.Modified;
await _context.SaveChangesAsync();
}
}
catch (Exception ex)
{
r.message = ex.Message;
r.isok = false;
}
return r;
}
// POST: api/MachineTypes
// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
[HttpPost]
public async Task<ReturnInfo> AddMachineType(MachineType machineType)
{
ReturnInfo r = new ReturnInfo();
try
{
if (MachineTypeExists(machineType.DeviceTypeName))
{
r.isok = false;
r.message = "已经存在此机型";
}
else
{
machineType.UpdateTime = DateTime.Now;
machineType.CreateTime = DateTime.Now;
r.isok = true;
_context.MachineTypes.Add(machineType);
await _context.SaveChangesAsync();
}
}
catch (Exception ex)
{
r.message = ex.Message;
r.isok = false;
}
return r;
}
// DELETE: api/MachineTypes/5
[HttpPost()]
public async Task<ReturnInfo> DeleteMachineType(Dictionary<string, int> data)
{
ReturnInfo r = new ReturnInfo();
try
{
var machineType = await _context.MachineTypes.FindAsync(data["id"]);
if (machineType == null)
{
r.isok = false;
r.message = "要删除的数据不存在";
}
else
{
r.isok = true;
machineType.IsDelete = true;
machineType.UpdateTime = DateTime.Now;
_context.MachineTypes.Update(machineType);
await _context.SaveChangesAsync();
}
}
catch (Exception ex)
{
r.message = ex.Message;
r.isok = false;
}
return r;
}
private bool MachineTypeExists(string name)
{
return _context.MachineTypes.Any(e => e.DeviceTypeName.Equals(name));
}
private bool MachineTypeExistsById(int id)
{
return _context.MachineTypes.Any(e => e.Id == id);
}
}
}

View File

@@ -0,0 +1,16 @@
namespace IotManager.Controllers
{
public class QueryAll_Or_Single
{
public bool IsAll { get; set; }
public int ID { get; set; }
}
public class QueryMachineType
{
public int MachineType { get; set; }
public string StartTime { get; set; }
public string EndTime { get; set; }
}
}

View File

@@ -0,0 +1,241 @@
using CommonEntity;
using IotManager.Common;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using MySQLAccess.PGModels;
using NPOI.OpenXmlFormats.Spreadsheet;
using NuGet.Protocol.Plugins;
using ViewModels;
namespace IotManager.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class RolesController : ControllerBase
{
public PostgresContext q { get; set; }
public RolesController(PostgresContext dbcontext)
{
q = dbcontext;
}
public class DelData
{
public int Id { get; set; }
}
/// <summary>
/// 删除角色
/// </summary>
/// <param name="LLL"></param>
/// <returns></returns>
[HttpPost()]
[Authorize()]
public ReturnInfo DelRole([FromBody] DelData LLL)
{
ReturnInfo returnInfo = new();
if (LLL.Id == 1)
{
returnInfo.isok = false;
returnInfo.message = "超级管理员不可删除!";
return returnInfo;
}
try
{
var FFF = q.Roleinfos.FirstOrDefault(A => A.Id == LLL.Id);
if (FFF != null)
{
FFF.IsDelete = true;
q.Roleinfos.Update(FFF);
q.SaveChanges();
returnInfo.isok = true;
}
}
catch (Exception ex)
{
returnInfo.isok = false;
returnInfo.message = ex.Message;
}
return returnInfo;
}
/// <summary>
/// 修改角色
/// </summary>
/// <param name="LLL"></param>
/// <returns></returns>
[HttpPost()]
[Authorize()]
public ReturnInfo EditRole([FromBody] ReturnRole LLL)
{
ReturnInfo returnInfo = new ReturnInfo();
try
{
//using (var q = new IotServerContext())
//{
var lll = q.Roleinfos.SingleOrDefault(A => A.Id == LLL.Id);
if (lll != null)
{
lll.Permission = LLL.Permission;
lll.DeviceLicense = LLL.DeviceLicense;
lll.UpdateTime = DateTime.Now;
q.Roleinfos.Update(lll);
q.SaveChanges();
returnInfo.isok = true;
}
//}
}
catch (Exception ex)
{
returnInfo.isok = false;
returnInfo.message = ex.Message;
}
return returnInfo;
}
/// <summary>
/// 获取角色信息
/// </summary>
/// <param name="S"></param>
/// <returns></returns>
[HttpPost()]
[Authorize()]
public ReturnInfo GetRoleInfo([FromBody] QueryAll_Or_Single S)
{
ReturnInfo returnInfo = new ReturnInfo();
try
{
if (S.IsAll)
{
returnInfo.isok = true;
returnInfo.response = q.Roleinfos.Where(A => A.IsDelete == false).Select(F => new ReturnRole
{
Id = F.Id,
Rolename = F.Rolename,
Permission = F.Permission,
DeviceLicense = F.DeviceLicense,
}).ToList();
}
else
{
//机型有哪些功能
var query = from mt in q.MachineTypes
join df in q.MachineTypeFuns on mt.Id equals df.MachineTypeId into dfGroup
from df in dfGroup.DefaultIfEmpty()
//机型功能和 角色联动
join rfm in q.RoleFunMappings on df.Id equals rfm.DeviceFunId into rfmGroup
from rfm in rfmGroup.DefaultIfEmpty()
join ri in q.Roleinfos on rfm.RoleId equals ri.Id into riGroup
from ri in riGroup.DefaultIfEmpty()
where ri.Id == S.ID
select new
{
MachineType = mt.Id, //机型
MachineFun = df.FunctionName, //功能
RoleName = ri.Rolename,
Id = ri.Id,
};
returnInfo.isok = true;
//var a = q.Roleinfos.SingleOrDefault(A => A.Id == S.ID);
var a = query.FirstOrDefault();
if (a != null)
{
//ReturnRole u = new ReturnRole();
//u.Id = a.Id;
//u.Rolename = a.Rolename;
//u.Permission = a.Permission;
returnInfo.response = a;
}
}
//}
}
catch (Exception ex)
{
returnInfo.isok = false;
returnInfo.message = ex.Message;
}
return returnInfo;
}
[HttpGet()]
public object TTT( )
{
return null;
}
/// <summary>
/// 新增角色
/// </summary>
/// <param name="LLL"></param>
/// <returns></returns>
[HttpPost()]
//[Authorize()]
public ReturnInfo AddRole([FromBody] ReturnRole LLL)
{
ReturnInfo returnInfo = new ReturnInfo();
try
{
Roleinfo lll = new Roleinfo();
string Rolename = LLL.Rolename;
lll.Rolename = Rolename;
lll.IsDelete = false;
lll.Permission = LLL.Permission;
lll.DeviceLicense = LLL.DeviceLicense;
lll.CreateTime = DateTime.Now;
lll.UpdateTime = DateTime.Now;
//using (var q = new IotServerContext())
//{
var Q = q.Roleinfos.Where(A => A.Rolename.Equals(Rolename));
if (Q.Count() > 0)
{
returnInfo.isok = false;
returnInfo.message = "此角色名已经存在";
}
else
{
q.Roleinfos.Add(lll);
returnInfo.isok = true;
}
q.SaveChanges();
//}
}
catch (Exception ex)
{
returnInfo.isok = false;
returnInfo.message = ex.Message;
}
return returnInfo;
}
}
/// <summary>
/// 返回角色信息
/// </summary>
public class ReturnRole
{
/// <summary>
/// 主键
/// </summary>
public int Id { get; set; } = 0;
public string? Rolename { get; set; }
public string? Permission { get; set; }
public string? DeviceLicense { get; set; }
}
}

View File

@@ -0,0 +1,121 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CommonEntity;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using MySQLAccess.PGModels;
namespace IotManager.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class TcpCloseDataController : ControllerBase
{
private readonly PostgresContext _context;
public TcpCloseDataController(PostgresContext context)
{
_context = context;
}
// GET: api/TcpCloseData
[Authorize()]
[HttpGet]
public async Task<ReturnInfo> GetTcpCloseData(int page_size, int page_index, string ip, int port)
{
ReturnInfo r = new ReturnInfo();
try
{
r.isok = true;
r.response = await _context.TcpCloseData.Where(A => A.WwwIp.Equals(ip) && A.WwwPort == port).Skip((page_index - 1) * page_size).Take(page_size).ToListAsync();
}
catch (Exception ex)
{
r.isok = false;
r.message = ex.Message;
}
return r;
}
// GET: api/TcpCloseData/5
[HttpGet("{id}")]
public async Task<ActionResult<TcpCloseDatum>> GetTcpCloseDatum(long id)
{
var tcpCloseDatum = await _context.TcpCloseData.FindAsync(id);
if (tcpCloseDatum == null)
{
return NotFound();
}
return tcpCloseDatum;
}
// PUT: api/TcpCloseData/5
// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
[HttpPut("{id}")]
public async Task<IActionResult> PutTcpCloseDatum(long id, TcpCloseDatum tcpCloseDatum)
{
if (id != tcpCloseDatum.Id)
{
return BadRequest();
}
_context.Entry(tcpCloseDatum).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!TcpCloseDatumExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
// POST: api/TcpCloseData
// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
[HttpPost]
public async Task<ActionResult<TcpCloseDatum>> PostTcpCloseDatum(TcpCloseDatum tcpCloseDatum)
{
_context.TcpCloseData.Add(tcpCloseDatum);
await _context.SaveChangesAsync();
return CreatedAtAction("GetTcpCloseDatum", new { id = tcpCloseDatum.Id }, tcpCloseDatum);
}
// DELETE: api/TcpCloseData/5
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteTcpCloseDatum(long id)
{
var tcpCloseDatum = await _context.TcpCloseData.FindAsync(id);
if (tcpCloseDatum == null)
{
return NotFound();
}
_context.TcpCloseData.Remove(tcpCloseDatum);
await _context.SaveChangesAsync();
return NoContent();
}
private bool TcpCloseDatumExists(long id)
{
return _context.TcpCloseData.Any(e => e.Id == id);
}
}
}

View File

@@ -0,0 +1,14 @@
using Common;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using RestSharp;
namespace IotManager.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class TcpController : ControllerBase
{
}
}

View File

@@ -0,0 +1,344 @@
using CommonEntity;
using IotManager.Common;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MySQLAccess.PGModels;
using ViewModels;
namespace IotManager.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class UsersController : ControllerBase
{
public PostgresContext q { get; set; }
public UsersController(PostgresContext dbcontext)
{
q = dbcontext;
}
public class DelData
{
public int Id { get; set; }
}
/// <summary>
/// 删除用户
/// </summary>
/// <param name="LLL"></param>
/// <returns></returns>
[HttpPost()]
[Authorize()]
public ReturnInfo DelUser([FromBody] DelData LLL)
{
ReturnInfo returnInfo = new();
if (LLL.Id == 2 || LLL.Id == 1)
{
returnInfo.isok = false;
returnInfo.message = "超级管理员不可删除!";
return returnInfo;
}
try
{
var FFF = q.Userinfos.FirstOrDefault(A => A.Id == LLL.Id);
if (FFF != null)
{
FFF.IsDelete = true;
q.Userinfos.Update(FFF);
q.SaveChanges();
returnInfo.isok = true;
}
}
catch (Exception ex)
{
returnInfo.isok = false;
returnInfo.message = ex.Message;
}
return returnInfo;
}
/// <summary>
/// 修改用户
/// </summary>
/// <param name="LLL"></param>
/// <returns></returns>
[HttpPost()]
[Authorize()]
public ReturnInfo EditUser([FromBody] ReturnUser LLL)
{
ReturnInfo returnInfo = new ReturnInfo();
try
{
//using (var q = new IotServerContext())
//{
var lll = q.Userinfos.SingleOrDefault(A => A.Id == LLL.Id);
if (lll != null)
{
string username = LLL.Username;
string? companyName = LLL.CompanyName;
string mobile = LLL.Mobile;
lll.Permission = LLL.Permission;
lll.RealName = LLL.Realname;
lll.UserName = username;
lll.CompanyName = companyName;
lll.Mobile = mobile;
lll.UpdateTime = DateTime.Now;
lll.RoleId = LLL.RoleId;
string PPP = LLL.Password.Trim();
if (!string.IsNullOrWhiteSpace(PPP))
{
lll.PassWord = JiaJieMi.HashPassword(PPP);
lll.PswEncryption = JiaJieMi.EncryptString(PPP);
}
q.Userinfos.Update(lll);
q.SaveChanges();
returnInfo.isok = true;
}
//}
}
catch (Exception ex)
{
returnInfo.isok = false;
returnInfo.message = ex.Message;
}
return returnInfo;
}
/// <summary>
/// 重置密码
/// </summary>
/// <param name="LLL"></param>
/// <returns></returns>
[HttpPost()]
[Authorize()]
public ReturnInfo ModifyPassWord([FromBody] PWD_Reset LLL)
{
ReturnInfo returnInfo = new ReturnInfo();
try
{
//using (var q = new IotServerContext())
//{
var QQQ = q.Userinfos.SingleOrDefault(A => A.Id == LLL.Id);
if (QQQ != null)
{
QQQ.PassWord = JiaJieMi.HashPassword(LLL.PlaintextPwd);
QQQ.PswEncryption = JiaJieMi.EncryptString(LLL.PlaintextPwd);
q.Userinfos.Update(QQQ);
q.SaveChanges();
returnInfo.isok = true;
}
//}
}
catch (Exception ex)
{
returnInfo.isok = false;
returnInfo.message = ex.Message;
}
return returnInfo;
}
/// <summary>
/// 新增密码为123456
/// </summary>
/// <param name="LLL"></param>
/// <returns></returns>
[HttpPost()]
[Authorize()]
public ReturnInfo ResetPassWord([FromBody] PWD_Reset LLL)
{
ReturnInfo returnInfo = new ReturnInfo();
try
{
//using (var q = new IotServerContext())
//{
var Q = q.Userinfos.SingleOrDefault(A => A.Id == LLL.Id);
if (Q != null)
{
Q.PassWord = JiaJieMi.HashPassword("123456");
Q.PswEncryption = JiaJieMi.EncryptString("123456");
q.Userinfos.Update(Q);
q.SaveChanges();
returnInfo.isok = true;
}
//}
}
catch (Exception ex)
{
returnInfo.isok = false;
returnInfo.message = ex.Message;
}
return returnInfo;
}
/// <summary>
/// 获取用户信息
/// </summary>
/// <param name="S"></param>
/// <returns></returns>
[HttpPost()]
[Authorize()]
public ReturnInfo GetUserInfo([FromBody] QueryAll_Or_Single S)
{
ReturnInfo returnInfo = new ReturnInfo();
try
{
//using (var q = new IotServerContext())
//{
if (S.IsAll)
{
returnInfo.isok = true;
returnInfo.response = q.Userinfos.Where(A => A.IsDelete == false).Select(F => new ReturnUser
{
Id = F.Id,
Username = F.UserName,
Realname = F.RealName,
CompanyName = F.CompanyName,
Mobile = F.Mobile,
Permission = F.Permission,
RoleId = F.RoleId
}).ToList();
}
else
{
returnInfo.isok = true;
var a = q.Userinfos.SingleOrDefault(A => A.Id == S.ID);
if (a != null)
{
ReturnUser u = new ReturnUser();
u.Id = a.Id;
u.Username = a.UserName;
u.Realname = a.RealName;
u.CompanyName = a.CompanyName;
u.Mobile = a.Mobile;
u.Permission = a.Permission;
u.RoleId = a.RoleId;
returnInfo.response = u;
}
}
//}
}
catch (Exception ex)
{
returnInfo.isok = false;
returnInfo.message = ex.Message;
}
return returnInfo;
}
/// <summary>
/// 新增用户
/// </summary>
/// <param name="LLL"></param>
/// <returns></returns>
[HttpPost()]
//[Authorize()]
public ReturnInfo AddUser([FromBody] ReturnUser LLL)
{
ReturnInfo returnInfo = new ReturnInfo();
try
{
Userinfo lll = new Userinfo();
string username = LLL.Username;
string mobile = LLL.Mobile;
lll.UserName = username;
lll.RealName = LLL.Realname;
lll.CompanyName = LLL.CompanyName;
lll.Mobile = mobile;
lll.IsDelete = false;
lll.Permission = LLL.Permission;
lll.RoleId = LLL.RoleId;
lll.CreateTime = DateTime.Now;
lll.UpdateTime = DateTime.Now;
//using (var q = new IotServerContext())
//{
var Q = q.Userinfos.Where(A => A.UserName.Equals(username));
if (Q.Count() > 0)
{
returnInfo.isok = false;
returnInfo.message = "此用户名已经存在";
}
else
{
//lll.Password = Tools.HashPassword("123456");
//lll.PswEncryption = Tools.EncryptString("123456");
lll.PassWord = JiaJieMi.HashPassword(LLL.Password.Trim());
lll.PswEncryption = JiaJieMi.EncryptString(LLL.Password.Trim());
q.Userinfos.Add(lll);
returnInfo.isok = true;
}
q.SaveChanges();
//}
}
catch (Exception ex)
{
returnInfo.isok = false;
returnInfo.message = ex.Message;
}
return returnInfo;
}
}
/// <summary>
/// 返回用户信息
/// </summary>
public class ReturnUser
{
/// <summary>
/// 主键
/// </summary>
public int Id { get; set; } = 0;
public string? Permission { get; set; }
/// <summary>
/// 用户名(登录名)
/// </summary>
public string? Username { get; set; }
/// <summary>
/// 真实姓名
/// </summary>
public string? Realname { get; set; }
/// <summary>
/// 所属公司ID
/// </summary>
public string? CompanyName { get; set; }
/// <summary>
/// 密码
/// </summary>
public string Password { get; set; } = "";
/// <summary>
/// 密码加密处理
/// </summary>
public string PswEncryption { get; set; } = "";
/// <summary>
/// 电话号码
/// </summary>
public string? Mobile { get; set; }
/// <summary>
/// 角色ID
/// </summary>
public int? RoleId { get; set; }
}
public class PWD_Reset
{
public int Id { get; set; }
public string PlaintextPwd { get; set; }
}
}

View File

@@ -0,0 +1,160 @@
using System.Data;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using IotManager.Common;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using NLog;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using IotManager.private_key;
using ViewModels;
using ViewModels.Data;
using CommonEntity;
using MySQLAccess.PGModels;
namespace IotManager.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class ValuesController : ControllerBase
{
private readonly Logger _logger = LogManager.GetCurrentClassLogger();
public IConfiguration? configuration { get; set; }
public ValuesController(IConfiguration _configuration)
{
configuration = _configuration;
}
public string GetId(string device_name,string uuid)
{
string data = string.Format("boolive_{0}_{1}", device_name, uuid);
// 密钥用于生成MAC
string key = "secretKey#&!";
// 计算MAC
byte[] mac = Base64.ComputeHMACSHA256Short(data, key);
string str = Convert.ToBase64String(mac);
return str;
}
[HttpGet()]
public ReturnInfo GetAllInfo([FromBody] QueryData data)
{
ReturnInfo r = new ReturnInfo();
try
{
using var context = new PostgresContext();
var q = from dev in context.Deviceinfos
join emqx in context.EmqxLogininfos
on dev.Uuid equals emqx.DeviceUuid
into devinfo
from info in devinfo.DefaultIfEmpty()
select new { dev.ClientId, dev.ProductId, dev.DeviceName, dev.SecretKey, info.UserName, info.PassWord };
var p = q.ToList();
r.isok = true;
r.response = p;
}
catch (Exception ex)
{
r.isok = false;
r.message = ex.Message;
}
return r;
}
[HttpPost()]
public ReturnInfo AddOrUpdateDeviceInfo([FromBody] BooliveDevice LLL)
{
ReturnInfo returnInfo = new ReturnInfo();
try
{
using var D = new PostgresContext();
if (LLL.Id != 0)
{
var Q = D.Deviceinfos.SingleOrDefault(A => A.ClientId == LLL.Id);
Q.DeviceName = LLL.DeviceName;
Q.SecretKey = LLL.DeviceSecret;
var DT = DateTime.Now;
Q.UpdateTime = DT;
Q.UpdateTimeUnix = Tools.ToUnixTimestampBySeconds(DT);
}
else
{
D.Database.BeginTransaction();
var DT = DateTime.Now;
var LT = Tools.ToUnixTimestampBySeconds(DT);
var LLL1 = new Deviceinfo();
var uuid = System.Guid.NewGuid().ToString("N");
LLL1.Uuid = uuid;
LLL1.CreateTime = DT;
LLL1.UpdateTime = DT;
LLL1.CreateTimeUnix = LT;
LLL1.UpdateTimeUnix = LT;
D.Deviceinfos.Add(LLL1);
EmqxLogininfo l = new EmqxLogininfo();
l.DeviceUuid = uuid;
l.UserName = LLL.DeviceName;
l.PassWord = GetId(l.UserName,uuid);
l.UpdateTime = DT;
l.UpdateTimeUnix = LT;
l.CreateTime = DT;
l.CreateTimeUnix = LT;
D.EmqxLogininfos.Add(l);
D.SaveChanges();
D.Database.CommitTransaction();
}
returnInfo.isok = true;
}
catch (Exception ex)
{
returnInfo.isok = false;
returnInfo.message = ex.Message;
}
return returnInfo;
}
[HttpDelete()]
public ReturnInfo DeleteDeviceInfo([FromBody] BooliveDevice LLL)
{
ReturnInfo r = new ReturnInfo();
try
{
using var Q = new PostgresContext();
Q.Database.BeginTransaction();
var a = Q.Deviceinfos.SingleOrDefault(A => A.ClientId == LLL.Id);
Q.Deviceinfos.Remove(a);
var b = Q.EmqxLogininfos.SingleOrDefault(A => A.DeviceUuid.Equals(a.Uuid));
Q.EmqxLogininfos.Remove(b);
Q.SaveChanges();
Q.Database.CommitTransaction();
r.isok = true;
}
catch (Exception ex)
{
r.isok = false;
r.message = ex.Message;
}
return r;
}
}
}

View File

@@ -0,0 +1,33 @@
using Microsoft.AspNetCore.Mvc;
namespace IotManager.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();
}
}
}