UavDeviceService.cs 44.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
using NCC.Common.Core.Manager;
using NCC.Common.Enum;
using NCC.Common.Extension;
using NCC.Common.Filter;
using NCC.Dependency;
using NCC.DynamicApiController;
using NCC.FriendlyException;
using NCC.Extend.Interfaces.UavDevice;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using NCC.Extend.Entitys;
using NCC.Extend.Entitys.Dto.UavDevice;
using Yitter.IdGenerator;
using NCC.Common.Helper;
using NCC.JsonSerialization;
using NCC.Extend.Entitys.Dto.UavDeviceCell;
using NCC.Extend.Entitys.Enums;
using System.ComponentModel;
using System.Reflection;
using NCC.Code;
using Microsoft.AspNetCore.Authorization;
using NCC.Extend.Interfaces.MqttPublisher;
using Serilog;
using NCC.System.Entitys.Permission;

namespace NCC.Extend.UavDevice
{
    /// <summary>
    /// 无人机机柜管理服务
    /// </summary>
    [ApiDescriptionSettings(Tag = "无人机机柜管理服务", Name = "UavDevice", Order = 200)]
    [Route("api/Extend/[controller]")]
    public class UavDeviceService : IUavDeviceService, IDynamicApiController, ITransient
    {
        /// <summary>
        /// MQTT配置信息类
        /// </summary>
        private class MqttConfig
        {
            public string ServerUri { get; set; }
            public int Port { get; set; }
            public string Username { get; set; }
            public string Password { get; set; }
            public string Qos { get; set; }
        }

        /// <summary>
        /// 设备配置信息类
        /// </summary>
        private class DeviceConfig
        {
            public MqttConfig Mqtt { get; set; }
            public string MaxRetryCount { get; set; }
            public string DevicePortPath { get; set; }
            public string RfidPortPath { get; set; }
            public int DeleteVideo { get; set; }
        }
        private readonly ISqlSugarRepository<UavDeviceEntity> _uavDeviceRepository;
        private readonly SqlSugarScope _db;
        private readonly IUserManager _userManager;

        private readonly IMqttPublisherService _mqttService;

        /// <summary>
        /// 初始化一个<see cref="UavDeviceService"/>类型的新实例
        /// </summary>
        public UavDeviceService(
            ISqlSugarRepository<UavDeviceEntity> uavDeviceRepository,
            IUserManager userManager,
            IMqttPublisherService mqttService)
        {
            _uavDeviceRepository = uavDeviceRepository;
            _db = _uavDeviceRepository.Context;
            _userManager = userManager;
            _mqttService = mqttService;
        }

        #region 获取无人机机柜管理信息
        /// <summary>
        /// 获取无人机机柜管理
        /// </summary>
        /// <param name="id">参数</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<dynamic> GetInfo(string id)
        {
            var entity = await _db.Queryable<UavDeviceEntity>().FirstAsync(p => p.Id == id);
            var output = entity.Adapt<UavDeviceInfoOutput>();
            output.uavDeviceCellEntities = _db.Queryable<UavDeviceCellEntity>().Where(p => p.DeviceId == output.id)
                .Select(it => new UavDeviceCellListOutput
                {
                    id = it.Id,
                    deviceId = it.DeviceId,
                    cellCode = it.CellCode,
                    status = it.Status,
                    rfid1 = it.Rfid1,
                    rfid2 = it.Rfid2,
                    uavCode = it.UavCode,
                }).ToList();
            output.isOnline = await _mqttService.IsClientOnlineAsync(output.deviceCode);
            return output;
        }

        #endregion

        #region 获取无人机机柜管理列表
        /// <summary>
        /// 获取无人机机柜管理列表
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        [HttpGet("")]
        public async Task<dynamic> GetList([FromQuery] UavDeviceListQueryInput input)
        {
            var sidx = input.sidx == null ? "id" : input.sidx;
            var data = await _db.Queryable<UavDeviceEntity>()
                .WhereIF(!string.IsNullOrEmpty(input.deviceName), p => p.DeviceName.Contains(input.deviceName))
                .WhereIF(!string.IsNullOrEmpty(input.deviceCode), p => p.DeviceCode.Contains(input.deviceCode))
                .WhereIF(!string.IsNullOrEmpty(input.belongUserId), p => p.BelongUserId.Contains(input.belongUserId))
                .Select(it => new UavDeviceListOutput
                {
                    id = it.Id,
                    deviceName = it.DeviceName,
                    deviceCode = it.DeviceCode,
                    siteId = it.SiteId,
                    belongUserId = it.BelongUserId,
                    lng = it.Lng,
                    lat = it.Lat,
                    status = it.Status,
                    remark = it.Remark,
                    appVersion = it.AppVersion,
                    cellnumber = SqlFunc.Subqueryable<UavDeviceCellEntity>().Where(u => u.DeviceId == it.Id).Count(),
                    belongUserName = SqlFunc.Subqueryable<UserEntity>().Where(u => u.Id == it.BelongUserId).Select(u => u.RealName),
                }).MergeTable().Mapper(async res =>
                {
                    res.uavDeviceCells = _db.Queryable<UavDeviceCellEntity>().Where(p => p.DeviceId == res.id).Select(it => new UavDeviceCellListOutput
                    {
                        id = it.Id,
                        cellCode = it.CellCode,
                        status = it.Status,
                        rfid1 = it.Rfid1,
                        rfid2 = it.Rfid2,
                        uavCode = it.UavCode,
                    }).ToList();
                    res.isOnline = await _mqttService.IsClientOnlineAsync(res.deviceCode);
                }).OrderBy(sidx + " " + input.sort).ToPagedListAsync(input.currentPage, input.pageSize);
            return PageResult<UavDeviceListOutput>.SqlSugarPageResult(data);
        }
        #endregion

        #region 获取代理商获取自己的无人机机柜管理列表
        /// <summary>
        /// 获取代理商获取自己的无人机机柜管理列表
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        [HttpGet("GetListByCurrent")]
        public async Task<dynamic> GetListByCurrent([FromQuery] UavDeviceListQueryInput input)
        {
            var sidx = input.sidx == null ? "id" : input.sidx;
            var data = await _db.Queryable<UavDeviceEntity>()
                .WhereIF(!string.IsNullOrEmpty(input.deviceName), p => p.DeviceName.Contains(input.deviceName))
                .WhereIF(!string.IsNullOrEmpty(input.deviceCode), p => p.DeviceCode.Contains(input.deviceCode))
                .WhereIF(!string.IsNullOrEmpty(input.siteId), p => p.SiteId == input.siteId)
                .Where(p => p.BelongUserId == _userManager.UserId)
                .Select(it => new UavDeviceListOutput
                {
                    id = it.Id,
                    deviceName = it.DeviceName,
                    deviceCode = it.DeviceCode,
                    siteId = it.SiteId,
                    belongUserId = it.BelongUserId,
                    lng = it.Lng,
                    lat = it.Lat,
                    status = it.Status,
                    remark = it.Remark,
                    siteName = SqlFunc.Subqueryable<UavSiteEntity>().Where(u => u.Id == it.SiteId).Select(u => u.SiteName),
                    cellnumber = SqlFunc.Subqueryable<UavDeviceCellEntity>().Where(u => u.DeviceId == it.Id).Count(),
                }).MergeTable().Mapper(async it =>
                {
                    it.isOnline = await _mqttService.IsClientOnlineAsync(it.deviceCode);
                }).OrderBy(sidx + " " + input.sort).ToPagedListAsync(input.currentPage, input.pageSize);
            return PageResult<UavDeviceListOutput>.SqlSugarPageResult(data);
        }
        #endregion

        #region 获取根据代理商id获取的无人机机柜管理列表
        /// <summary>
        /// 获取根据代理商id获取的无人机机柜管理列表
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        [HttpGet("GetListByUserId")]
        public async Task<dynamic> GetListByUserId([FromQuery] UavDeviceListQueryInput input)
        {
            var sidx = input.sidx == null ? "id" : input.sidx;
            var data = await _db.Queryable<UavDeviceEntity>()
                .WhereIF(!string.IsNullOrEmpty(input.deviceName), p => p.DeviceName.Contains(input.deviceName))
                .WhereIF(!string.IsNullOrEmpty(input.deviceCode), p => p.DeviceCode.Contains(input.deviceCode))
                .WhereIF(!string.IsNullOrEmpty(input.siteId), p => p.SiteId == input.siteId)
                .Where(p => p.BelongUserId == input.belongUserId)
                .Select(it => new UavDeviceListOutput
                {
                    id = it.Id,
                    deviceName = it.DeviceName,
                    deviceCode = it.DeviceCode,
                    siteId = it.SiteId,
                    belongUserId = it.BelongUserId,
                    lng = it.Lng,
                    lat = it.Lat,
                    status = it.Status,
                    remark = it.Remark,
                    siteName = SqlFunc.Subqueryable<UavSiteEntity>().Where(u => u.Id == it.SiteId).Select(u => u.SiteName),
                    cellnumber = SqlFunc.Subqueryable<UavDeviceCellEntity>().Where(u => u.DeviceId == it.Id).Count(),
                }).MergeTable().Mapper(async res =>
                {
                    res.isOnline = await _mqttService.IsClientOnlineAsync(res.deviceCode);
                }).OrderBy(sidx + " " + input.sort).ToPagedListAsync(input.currentPage, input.pageSize);
            return PageResult<UavDeviceListOutput>.SqlSugarPageResult(data);
        }
        #endregion

        #region 新建无人机机柜管理
        /// <summary>
        /// 新建无人机机柜管理
        /// </summary>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPost("")]
        public async Task Create([FromBody] UavDeviceCrInput input)
        {
            var entity = input.Adapt<UavDeviceEntity>();
            entity.Id = YitIdHelper.NextId().ToString();
            entity.BelongUserId = _userManager.UserId;
            if (input.deviceCode.IsNullOrEmpty())
            {
                entity.DeviceCode = "SA" + YitIdHelper.NextId().ToString();
            }
            var isOk = await _db.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
            //新建完毕后,添加格位的信息,也就是货道信息
            List<UavDeviceCellEntity> cellEntities = new List<UavDeviceCellEntity>();
            //初始化的时候就提供6个货道
            for (int i = 1; i <= 6; i++)
            {
                UavDeviceCellEntity uavDeviceCellEntitycellEntity = new UavDeviceCellEntity
                {
                    Id = YitIdHelper.NextId().ToString(),
                    DeviceId = entity.Id,
                    CellCode = i.ToString(),
                    Status = DeviceCellStatusEnum.空闲.GetHashCode(),
                    CreateTime = DateTime.Now,
                };
                cellEntities.Add(uavDeviceCellEntitycellEntity);
            }
            isOk = await _db.Insertable(cellEntities).ExecuteCommandAsync();
            if (!(isOk > 0)) throw NCCException.Oh(ErrorCode.COM1000);
        }
        #endregion

        #region 更新无人机机柜管理
        /// <summary>
        /// 更新无人机机柜管理
        /// </summary>
        /// <param name="id">主键</param>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task Update(string id, [FromBody] UavDeviceUpInput input)
        {
            var entity = input.Adapt<UavDeviceEntity>();
            var isOk = await _db.Updateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
            if (!(isOk > 0)) throw NCCException.Oh(ErrorCode.COM1001);
        }
        #endregion

        #region 小程序端更新无人机机柜信息
        /// <summary>
        /// 更新无人机机柜管理
        /// </summary>
        /// <param name="id">主键</param>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPut("UpdateByWechat")]
        public async Task UpdateByWechat(string id, [FromBody] UavDeviceUpInput input)
        {
            var entity = input.Adapt<UavDeviceEntity>();
            var isOk = await _db.Updateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
            //更新完基本信息后,需要去更新机柜格子信息
            foreach (var item in input.uavDeviceCellEntities)
            {
                var cellEntity = await _db.Queryable<UavDeviceCellEntity>().FirstAsync(p => p.Id == item.id);
                //需要判断是否有此机柜格子
                if (cellEntity != null)
                {
                    cellEntity.DeviceId = input.id;
                    cellEntity.CellCode = item.cellCode;
                    cellEntity.Status = item.status;
                    cellEntity.Remark = item.remark;
                    await _db.Updateable(cellEntity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
                }
                else
                {
                    //如果没有这个机柜格子,则创建
                    UavDeviceCellEntity uavDeviceCellEntity = new UavDeviceCellEntity
                    {
                        DeviceId = input.id,
                        CellCode = item.cellCode,
                        Status = item.status,
                        Remark = item.remark,
                        Id = YitIdHelper.NextId().ToString(),
                        CreateTime = DateTime.Now,
                        UpdateTime = DateTime.Now,
                        CreatorId = _userManager.UserId
                    };
                    await _db.Insertable(uavDeviceCellEntity).ExecuteCommandAsync();
                }
            }
            if (!(isOk > 0)) throw NCCException.Oh(ErrorCode.COM1001);
        }
        #endregion

        #region 获取设备状态枚举列表
        /// <summary>
        /// 获取设备状态枚举列表
        /// </summary>
        [HttpGet("GetDeviceStatusEnum")]
        public async Task<dynamic> GetDeviceStatusEnum()
        {
            var list = Enum.GetValues(typeof(DeviceStatusEnum))
                .Cast<DeviceStatusEnum>()
                .Select(e => new
                {
                    Value = (int)e,
                    Label = GetDescription(e)
                }).ToList();

            return list;
        }

        private string GetDescription(Enum enumValue)
        {
            var fieldInfo = enumValue.GetType().GetField(enumValue.ToString());
            var descriptionAttribute = fieldInfo?.GetCustomAttribute<DescriptionAttribute>();
            return descriptionAttribute?.Description ?? enumValue.ToString();
        }
        #endregion

        #region 删除无人机机柜管理
        /// <summary>
        /// 删除无人机机柜管理
        /// </summary>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task Delete(string id)
        {
            var entity = await _db.Queryable<UavDeviceEntity>().FirstAsync(p => p.Id == id);
            _ = entity ?? throw NCCException.Oh(ErrorCode.COM1005);
            var isOk = await _db.Deleteable<UavDeviceEntity>().Where(d => d.Id == id).ExecuteCommandAsync();
            if (!(isOk > 0)) throw NCCException.Oh(ErrorCode.COM1002);
        }
        #endregion

        #region 解绑设备
        /// <summary>
        /// 解绑设备
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPut("UnbindDevice/{id}")]
        public async Task UnbindDevice(string id)
        {
            var entity = await _db.Queryable<UavDeviceEntity>().FirstAsync(p => p.Id == id);
            entity.BelongUserId = "";
            var isOk = await _db.Updateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
            if (!(isOk > 0)) throw NCCException.Oh(ErrorCode.COM1001);
        }
        #endregion

        #region 绑定设备
        /// <summary>
        /// 绑定设备
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPut("BindDevice")]
        public async Task<dynamic> BindDevice(UavDeviceUpInput input)
        {
            var entity = await _db.Queryable<UavDeviceEntity>().FirstAsync(p => p.DeviceCode == input.deviceCode);
            if (entity.IsNull())
            {
                return new
                {
                    code = -1,
                    message = "设备不存在!",
                };
            }
            if (entity.BelongUserId.IsNotEmptyOrNull())
            {
                return new
                {
                    code = -1,
                    message = "该设备已绑定,请勿重复绑定!",
                };
            }
            entity.DeviceName = input.deviceCode;
            entity.BelongUserId = _userManager.UserId;
            entity.SiteId = input.siteId;
            entity.Remark = input.remark;
            entity.Status = input.status;
            var isOk = await _db.Updateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
            if (!(isOk > 0))
            {
                return NCCException.Oh(ErrorCode.COM1001);
            }
            return new
            {
                code = 0,
                message = "绑定设备成功!",
            };
        }

        #endregion

        #region 获取代理商设备数量信息
        /// <summary>
        /// 获取代理商设备数量信息
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetAgentDeviceCount")]
        public async Task<dynamic> GetAgentDeviceCount()
        {
            var DeviceCount = await _db.Queryable<UavDeviceEntity>().Where(p => p.BelongUserId == _userManager.UserId).CountAsync();
            return new
            {
                DeviceCount = DeviceCount
            };
        }
        #endregion

        #region 柜子服务端进行绑定
        /// <summary>
        /// 柜子服务端进行绑定
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPut("CabinetBind")]
        [AllowAnonymous]
        public async Task<dynamic> CabinetBind(UavDeviceBindCrInput input)
        {
            var entity = await _db.Queryable<UavDeviceEntity>().FirstAsync(p => p.Id == input.id);
            if (entity.MacAddress.IsNotEmptyOrNull())
            {
                return new
                {
                    code = -1,
                    message = "设备已绑定!",
                };
            }
            entity.MacAddress = input.macAddress;
            var isOk = await _db.Updateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
            return new
            {
                code = 0,
                message = "绑定成功!",
            };
        }
        #endregion

        #region 测试发布订阅
        /// <summary>
        /// 测试发布订阅
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("testPublish")]
        public async Task<dynamic> testPublish(UavDeviceOprnNotifyCrInput input)
        {
            string topic = $"device/{input.id}/response";
            string message = input.ToJson();
            await _mqttService.PublishAsync(topic, message);
            return new { code = 200, msg = "测试开门指令已发送" };
        }
        #endregion

        #region 检测开门
        /// <summary>
        /// 检测开门
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("DetectionCheckOpenDoor")]
        public async Task<dynamic> DetectionCheckOpenDoor(UavDeviceOpenCrInput input)
        {
            var entity = await _db.Queryable<UavDeviceEntity>().FirstAsync(p => p.Id == input.id);
            string topic = $"device/{entity.DeviceCode}/uav";
            string message = new MqttContent
            {
                className = "DetectionOpen",
                action = "open",
                lane = input.lane,
                orderNo = "",
                instructionTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                tokenUrl = ""
            }.ToJson();
            await _mqttService.PublishAsync(topic, message);
            return new { code = 200, msg = "测试开门指令已发送" };
        }
        #endregion

        #region 同步设备信息(补货)
        /// <summary>
        /// 同步设备信息(补货)
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("SyncDeviceInfo")]
        [AllowAnonymous]
        public async Task<dynamic> SyncDeviceInfo(UavDeviceOprnNotifyCrInput input)
        {
            //获取设备信息
            var DeviceInfo = await _db.Queryable<UavDeviceEntity>().FirstAsync(p => p.Id == input.id);
            //通过设备编号以及货道code获取信息
            var DeviceCellInfo = await _db.Queryable<UavDeviceCellEntity>().FirstAsync(p => p.DeviceId == input.id && p.CellCode == input.lane);
            if (input.rfid_1.IsNotEmptyOrNull())
            {
                //如果传入的无人机FRID不为空,就需要去修改无人机的信息
                //通过传入的无人机FRID以及电池FRID去查询信息
                var UavInfo = await _db.Queryable<UavAircraftEntity>().FirstAsync(p => p.UavFrid == input.rfid_1);
                UavInfo.Status = UavAircraftStatusEnum.空闲.GetHashCode();
                UavInfo.UavFrid = input.rfid_1;
                UavInfo.DeviceId = input.id;
                UavInfo.CellId = DeviceCellInfo.Id;
                UavInfo.BatteryCapacity = input.batteryCapacity;
                _db.Updateable(UavInfo).ExecuteCommand();
            }
            else
            {
                //如果传入的无人机FRID为空,就通过货道id去找到之前绑定的无人机,然后去把绑定取消,并且标注无人机为
                var UavInfo = _db.Queryable<UavAircraftEntity>().Where(x => x.CellId == DeviceCellInfo.Id).First();
                UavInfo.Status = UavAircraftStatusEnum.维修.GetHashCode();
                UavInfo.DeviceId = string.Empty;
                UavInfo.CellId = string.Empty;
                UavInfo.BatteryCapacity = input.batteryCapacity;
                _db.Updateable(UavInfo).ExecuteCommand();
            }
            return new
            {
                code = 0,
                message = "同步成功!",
            };
        }
        #endregion

        #region 注册设备
        /// <summary>
        /// 注册设备
        /// </summary>
        /// <param name="DeviceCOde"></param>
        /// <returns></returns>
        [HttpPost("RegisterDevice/{DeviceCOde}")]
        [AllowAnonymous]
        public async Task<dynamic> RegisterDevice(string DeviceCOde)
        {
            Log.Information($"设备更新信息1111: {DeviceCOde}");
            // 查询是否存在该设备
            // 查询是否存在该设备
            var entity = await _db.Queryable<UavDeviceEntity>().Where(x => x.DeviceCode == DeviceCOde).FirstAsync();
            if (!entity.IsNullOrEmpty())
            {
                return new { success = true, message = "设备已存在,无需重复注册。" };
            }
            // 开启事务
            try
            {
                await _db.Ado.UseTranAsync(async () =>
                {
                    // 新建设备
                    var info = new UavDeviceEntity
                    {
                        Id = YitIdHelper.NextId().ToString(),
                        DeviceCode = DeviceCOde,
                        DeviceName = DeviceCOde,
                        Status = DeviceStatusEnum.启用.GetHashCode(),
                        CreateTime = DateTime.Now,
                    };
                    await _db.Insertable(info).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
                    // 新建货道
                    var cellEntities = new List<UavDeviceCellEntity>();
                    for (int i = 1; i <= 6; i++)
                    {
                        cellEntities.Add(new UavDeviceCellEntity
                        {
                            Id = YitIdHelper.NextId().ToString(),
                            DeviceId = info.Id,
                            CellCode = i.ToString(),
                            Status = DeviceCellStatusEnum.空闲.GetHashCode(),
                            CreateTime = DateTime.Now
                        });
                    }
                    await _db.Insertable(cellEntities).ExecuteCommandAsync();
                });
                return new { success = true, message = "设备注册成功。" };
            }
            catch (Exception ex)
            {
                // 日志记录异常(如有日志组件)
                Log.Error($"设备注册异常: {ex.Message}");
                return new { success = false, message = "设备注册失败,请联系系统管理员。" };
            }
        }
        #endregion

        #region 注册设备(用于APP更新)
        /// <summary>
        /// 注册设备(用于APP更新)
        /// </summary>
        /// <param name="DeviceCodeInfo"></param>
        /// <returns></returns>
        [HttpPost("RegisterDeviceForAppUpdate")]
        [AllowAnonymous]
        public async Task<dynamic> RegisterDeviceForAppUpdate(UavDeviceBindInput DeviceCodeInfo)
        {
            Log.Information($"设备更新信息: {DeviceCodeInfo.ToJson()}");
            // 查询是否存在该设备
            var entity = await _db.Queryable<UavDeviceEntity>().Where(x => x.DeviceCode == DeviceCodeInfo.newDeviceCode || x.DeviceCode == DeviceCodeInfo.deviceCode).FirstAsync();
            if (!entity.IsNullOrEmpty())
            {
                entity.AppVersion = DeviceCodeInfo.appVersion;
                //判断两个设备编号
                if (entity.DeviceCode == DeviceCodeInfo.newDeviceCode)
                {
                    await _db.Updateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
                    return new { success = true, message = "设备已存在,无需重复注册。" };
                }
                //如果两个设备编号不一致,则需要修改设备编号
                entity.DeviceCode = DeviceCodeInfo.newDeviceCode;
                await _db.Updateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
                return new { success = true, message = "设备信息更新成功" };
            }
            // 开启事务
            try
            {
                await _db.Ado.UseTranAsync(async () =>
                {
                    // 新建设备
                    var info = new UavDeviceEntity
                    {
                        Id = YitIdHelper.NextId().ToString(),
                        DeviceCode = DeviceCodeInfo.newDeviceCode,
                        DeviceName = DeviceCodeInfo.newDeviceCode,
                        Status = DeviceStatusEnum.启用.GetHashCode(),
                        CreateTime = DateTime.Now,
                        AppVersion = DeviceCodeInfo.appVersion,
                    };
                    await _db.Insertable(info).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
                    // 新建货道
                    var cellEntities = new List<UavDeviceCellEntity>();
                    for (int i = 1; i <= 6; i++)
                    {
                        cellEntities.Add(new UavDeviceCellEntity
                        {
                            Id = YitIdHelper.NextId().ToString(),
                            DeviceId = info.Id,
                            CellCode = i.ToString(),
                            Status = DeviceCellStatusEnum.空闲.GetHashCode(),
                            CreateTime = DateTime.Now
                        });
                    }
                    await _db.Insertable(cellEntities).ExecuteCommandAsync();
                });
                return new { success = true, message = "设备注册成功。" };
            }
            catch (Exception ex)
            {
                // 日志记录异常(如有日志组件)
                Log.Error($"设备注册异常: {ex.Message}");
                return new { success = false, message = "设备注册失败,请联系系统管理员。" };
            }
        }
        #endregion

        #region 机柜获取MQTT配置
        /// <summary>
        /// 机柜获取MQTT配置
        /// </summary>
        /// <param name="deviceCode">设备编码</param>
        /// <returns>MQTT配置信息</returns>
        [HttpGet("GetMqttConfig/{deviceCode}")]
        [AllowAnonymous]
        public async Task<dynamic> GetMqttConfig(string deviceCode = "")
        {
            var mqttBaseConfig = new
            {
                serverUri = "mqtt.cqjiangzhichao.cn",
                port = 1883,
                username = "wrjservice",
                password = "P@ssw0rd",
                qos = "0"
            };

            var baseConfig = new
            {
                mqtt = mqttBaseConfig,
                maxRetryCount = "3",
                devicePortPath = "/dev/ttyS2",
                rfidPortPath = "/dev/ttyS4",
                downloadUrl = "https://wrj.cqjiangzhichao.cn/app.apk",
                deleteVideo = deviceCode.IsNullOrEmpty() ? 168 : (await _db.Queryable<UavDeviceEntity>().FirstAsync(p => p.DeviceCode == deviceCode))?.DelVideoTime ?? 168,
                openLogActions = "close"
            };

            return baseConfig;
        }

        #endregion

        #region 设备转让
        /// <summary>
        /// 设备转让
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("TransferDevice")]
        public async Task<dynamic> TransferDevice([FromBody] UavDeviceTransferInput input)
        {
            var entity = await _db.Queryable<UavDeviceEntity>().FirstAsync(x => x.Id == input.id);
            if (entity.IsNullOrEmpty())
            {
                return NCCException.Oh("设备不存在!");
            }
            var userBool = await _db.Queryable<UserEntity>().Where(x => x.Id == entity.BelongUserId).AnyAsync();
            if (!userBool)
            {
                return NCCException.Oh("用户不存在!");
            }
            entity.BelongUserId = input.belongUserId;
            var isOk = await _db.Updateable(entity).ExecuteCommandAsync();
            if (isOk > 0)
            {
                return new
                {
                    code = 0,
                    message = "转让成功!",
                };
            }
            else
            {
                return NCCException.Oh("转让失败!");
            }
        }
        #endregion

        #region 推送APP更新消息
        /// <summary>
        /// 推送APP更新消息给设备
        /// </summary>
        /// <param name="deviceCode">设备编码</param>
        /// <param name="downloadUrl">APP下载地址</param>
        /// <returns></returns>
        [HttpPost("PushAppUpdate")]
        public async Task<dynamic> PushAppUpdate(string deviceCode, string downloadUrl = "")
        {
            try
            {
                // 验证设备是否存在
                var device = await _db.Queryable<UavDeviceEntity>().FirstAsync(x => x.DeviceCode == deviceCode);
                if (device == null)
                {
                    return new { code = 400, msg = "设备不存在" };
                }

                // 如果没有提供下载地址,使用默认地址
                if (string.IsNullOrEmpty(downloadUrl))
                {
                    downloadUrl = "https://wrj.cqjiangzhichao.cn/app.apk";
                }

                // 构建MQTT消息
                string topic = $"device/{deviceCode}/uav";
                string message = new MqttContent
                {
                    className = "updateapp",
                    action = "open",
                    lane = "1", // APP更新通常使用固定货道
                    orderNo = downloadUrl, // 将下载地址放在orderNo字段中
                    instructionTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                    tokenUrl = ""
                }.ToJson();

                // 发送MQTT消息
                await _mqttService.PublishAsync(topic, message);
                Log.Information($"已推送APP更新消息到设备 {deviceCode},下载地址:{downloadUrl}");
                return new
                {
                    code = 200,
                    msg = "APP更新消息推送成功",
                    data = new
                    {
                        deviceCode = deviceCode,
                        downloadUrl = downloadUrl,
                        messageId = Guid.NewGuid().ToString()
                    }
                };
            }
            catch (Exception ex)
            {
                Log.Error($"推送APP更新消息失败:{ex.Message}");
                return new { code = 500, msg = $"推送APP更新消息失败:{ex.Message}" };
            }
        }

        /// <summary>
        /// 批量推送APP更新消息给多个设备
        /// </summary>
        /// <param name="deviceCodes">设备编码列表</param>
        /// <param name="downloadUrl">APP下载地址</param>
        /// <returns></returns>
        [HttpPost("PushAppUpdateBatch")]
        public async Task<dynamic> PushAppUpdateBatch(string downloadUrl = "")
        {
            try
            {
                var deviceCodes = await _db.Queryable<UavDeviceEntity>().ToListAsync();
                // 如果没有提供下载地址,使用默认地址
                if (string.IsNullOrEmpty(downloadUrl))
                {
                    downloadUrl = "https://wrj.cqjiangzhichao.cn/app.apk";
                }

                var results = new List<object>();
                var successCount = 0;
                var failCount = 0;

                foreach (var item in deviceCodes)
                {
                    try
                    {
                        // 构建MQTT消息
                        string topic = $"device/{item.DeviceCode}/uav";
                        string message = new MqttContent
                        {
                            className = "updateapp",
                            action = "open",
                            lane = "1",
                            orderNo = downloadUrl,
                            instructionTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                            tokenUrl = ""
                        }.ToJson();

                        // 发送MQTT消息
                        await _mqttService.PublishAsync(topic, message);

                        results.Add(new { item.DeviceCode, success = true, message = "推送成功" });
                        successCount++;
                    }
                    catch (Exception ex)
                    {
                        results.Add(new { item.DeviceCode, success = false, message = ex.Message });
                        failCount++;
                    }
                }

                Log.Information($"批量推送APP更新消息完成,成功:{successCount},失败:{failCount}");

                return new
                {
                    code = 200,
                    msg = $"批量推送完成,成功:{successCount},失败:{failCount}",
                    data = new
                    {
                        totalCount = deviceCodes.Count,
                        successCount = successCount,
                        failCount = failCount,
                        results = results,
                        downloadUrl = downloadUrl
                    }
                };
            }
            catch (Exception ex)
            {
                Log.Error($"批量推送APP更新消息失败:{ex.Message}");
                return new { code = 500, msg = $"批量推送APP更新消息失败:{ex.Message}" };
            }
        }
        #endregion

        #region 查询设备是否在线
        /// <summary>
        /// 查询设备是否在线
        /// </summary>
        /// <param name="deviceCode"></param>
        /// <returns></returns>
        [HttpGet("IsDeviceOnline/{deviceCode}")]

        public async Task<dynamic> IsDeviceOnline(string deviceCode)
        {
            //return new { deviceId = deviceCode, isOnline = true };
            try
            {
                bool isOnline = await _mqttService.IsClientOnlineAsync(deviceCode);
                return new { deviceId = deviceCode, isOnline = isOnline };
            }
            catch (Exception ex)
            {
                Log.Error($"查询设备 {deviceCode} 在线状态失败: {ex.Message}");
                return new { deviceId = deviceCode, isOnline = false };
            }
        }
        #endregion

        #region 批量查询设备在线状态
        /// <summary>
        /// 批量查询设备在线状态(优化版本)
        /// </summary>
        /// <param name="input">设备ID列表</param>
        /// <returns></returns>
        [HttpPost("BatchCheckOnlineStatus")]
        public async Task<dynamic> BatchCheckOnlineStatus([FromBody] BatchCheckOnlineStatusInput input)
        {
            if (input?.DeviceIds == null || input.DeviceIds.Count == 0)
            {
                return new { success = false, message = "设备ID列表不能为空", data = new List<object>() };
            }

            try
            {
                // 使用新的批量查询方法,提高效率
                var onlineStatusDict = await _mqttService.BatchCheckOnlineStatusAsync(input.DeviceIds);

                // 转换为前端期望的格式
                var result = input.DeviceIds.Select(deviceId => new
                {
                    deviceId = deviceId,
                    isOnline = onlineStatusDict.ContainsKey(deviceId) ? onlineStatusDict[deviceId] : false
                }).ToList();

                return new
                {
                    success = true,
                    message = $"成功查询 {result.Count} 个设备的在线状态",
                    data = result
                };
            }
            catch (Exception ex)
            {
                Log.Error($"批量查询设备在线状态失败: {ex.Message}");
                return new
                {
                    success = false,
                    message = $"批量查询失败: {ex.Message}",
                    data = new List<object>()
                };
            }
        }

        /// <summary>
        /// 获取设备列表(用于App更新推送,不包含在线状态查询)
        /// </summary>
        /// <param name="input">查询参数</param>
        /// <returns></returns>
        [HttpGet("GetDeviceListForUpdate")]
        public async Task<dynamic> GetDeviceListForUpdate([FromQuery] UavDeviceListQueryInput input)
        {
            var sidx = input.sidx == null ? "id" : input.sidx;
            var data = await _db.Queryable<UavDeviceEntity>()
                .WhereIF(!string.IsNullOrEmpty(input.deviceName), p => p.DeviceName.Contains(input.deviceName))
                .WhereIF(!string.IsNullOrEmpty(input.deviceCode), p => p.DeviceCode.Contains(input.deviceCode))
                .WhereIF(!string.IsNullOrEmpty(input.belongUserId), p => p.BelongUserId.Contains(input.belongUserId))
                .Select(it => new UavDeviceListOutput
                {
                    id = it.Id,
                    deviceName = it.DeviceName,
                    deviceCode = it.DeviceCode,
                    siteId = it.SiteId,
                    belongUserId = it.BelongUserId,
                    lng = it.Lng,
                    lat = it.Lat,
                    status = it.Status,
                    remark = it.Remark,
                    appVersion = it.AppVersion,
                    cellnumber = SqlFunc.Subqueryable<UavDeviceCellEntity>().Where(u => u.DeviceId == it.Id).Count(),
                }).MergeTable().OrderBy(sidx + " " + input.sort).ToPagedListAsync(input.currentPage, input.pageSize);
            return PageResult<UavDeviceListOutput>.SqlSugarPageResult(data);
        }
        #endregion
      
        #region 修改时间超个半小时的无人机改为充电完成

        /// <summary>
        /// 将超过30分钟充电状态的无人机格子状态改为充电完成
        /// </summary>
        /// <returns></returns>
        [HttpPost("UpdateChargingStatusToComplete")]
        public async Task<dynamic> UpdateChargingStatusToComplete()
        {
            try
            {
                // 计算30分钟前的时间
                var thirtyMinutesAgo = DateTime.Now.AddMinutes(-30);
                
                // 查询状态为充电且更新时间超过30分钟的无人机格子
                var chargingCells = await _db.Queryable<UavDeviceCellEntity>().Where(x => x.Status == DeviceCellStatusEnum.充电.GetHashCode() &&  x.UpdateTime.HasValue && 
                               x.UpdateTime.Value < thirtyMinutesAgo)
                    .ToListAsync();

                if (chargingCells == null || chargingCells.Count == 0)
                {
                    return new { success = true, message = "没有需要更新的充电状态格子", updatedCount = 0 };
                }

                // 批量更新状态为充电完成
                var updateCount = await _db.Updateable<UavDeviceCellEntity>()
                    .SetColumns(x => new UavDeviceCellEntity
                    {
                        Status = DeviceCellStatusEnum.充电完成.GetHashCode()
                    })
                    .Where(x => chargingCells.Select(c => c.Id).Contains(x.Id))
                    .ExecuteCommandAsync();

                Log.Information($"成功将 {updateCount} 个充电状态超过30分钟的无人机格子状态更新为充电完成");

                return new 
                { 
                    success = true, 
                    message = $"成功更新 {updateCount} 个无人机格子状态为充电完成", 
                    updatedCount = updateCount,
                    updatedCells = chargingCells.Select(x => new { id = x.Id, cellCode = x.CellCode, deviceId = x.DeviceId })
                };
            }
            catch (Exception ex)
            {
                Log.Error($"更新充电状态失败: {ex.Message}");
                return new { success = false, message = $"更新失败: {ex.Message}", updatedCount = 0 };
            }
        }

        /// <summary>
        /// 定时任务:自动更新超过30分钟的充电状态
        /// </summary>
        /// <returns></returns>
        [HttpPost("AutoUpdateChargingStatus")]
        public async Task<dynamic> AutoUpdateChargingStatus()
        {
            try
            {
                // 计算30分钟前的时间
                var thirtyMinutesAgo = DateTime.Now.AddMinutes(-30);
                
                // 查询并更新状态
                var updateCount = await _db.Updateable<UavDeviceCellEntity>()
                    .SetColumns(x => new UavDeviceCellEntity
                    {
                        Status = DeviceCellStatusEnum.充电完成.GetHashCode(),
                        UpdateTime = DateTime.Now
                    })
                    .Where(x => x.Status == DeviceCellStatusEnum.充电.GetHashCode() && 
                               x.UpdateTime.HasValue && 
                               x.UpdateTime.Value < thirtyMinutesAgo)
                    .ExecuteCommandAsync();

                if (updateCount > 0)
                {
                    Log.Information($"定时任务:自动将 {updateCount} 个充电状态超过30分钟的无人机格子状态更新为充电完成");
                }

                return new 
                { 
                    success = true, 
                    message = $"自动更新完成,共更新 {updateCount} 个格子", 
                    updatedCount = updateCount,
                    updateTime = DateTime.Now
                };
            }
            catch (Exception ex)
            {
                Log.Error($"自动更新充电状态失败: {ex.Message}");
                return new { success = false, message = $"自动更新失败: {ex.Message}", updatedCount = 0 };
            }
        }

        #endregion
    }
}