Ejemplo n.º 1
0
        public async Task <bool> UpdateOrAddDevice(TDevice data)
        {
            var node = nodemap.Find(m => m.objId == data.ParentID);

            if (node == null)
            {
                return(false);              //没有父节点,返回
            }
            var dev = DevList.Find(n => n.OrgiData.ID == data.ID);

            if (dev == null)    //新增设备,返回新增的设备,等web新增成功,插入数据库
            {
                dev = new SuperBDevice(data, node.nodeIsid);
                var map = new SqlDeviceMap()
                {
                    devIsid = dev.Device.dvIsid, objId = data.ID, groupIsid = Uuid.Create16Token()
                };
                var req = await HttpUtil.PostAsync($"http://{cfg.AppSettings["serverUrl"]}/inIoT/devServer/deviceRes",
                                                   JsonSrialize.Srialize(new DevModel()
                {
                    dvIsid      = dev.Device.dvIsid,
                    dvName      = dev.Device.dvName,
                    dvTypeCode  = dev.Device.dvTypeCode,
                    managerIsid = cfg.AppSettings["managerIsid"],
                    nodeIsid    = dev.NodeIsid,
                    addrRes     = new MqttCommon.Setup.AddResource()
                    {
                        communicationType = 1,
                        dvAddr1           = "1.1.1.1",
                        dvAddr2           = "2222"
                    }
                }), SuperBCenter.ServerToken);

                if (req == null || req.codeid != 0)
                {
                    return(false);
                }

                try
                {
                    await _db.tDevice.AddAsync(dev.DbData);

                    if (!devicemap.Exists(d => d.objId == dev.OrgiData.ID && d.devIsid == dev.NodeIsid))
                    {
                        await _db.devicemap.AddAsync(map);

                        devicemap.Add(map);
                    }
                    await _db.SaveChangesAsync();

                    DevList.Add(dev);
                }
                catch (Exception ex)
                {
                    LogHelper.Error(ex);
                    return(false);
                }
            }
            else
            {
                if (!devicemap.Exists(d => d.objId == dev.OrgiData.ID && d.devIsid == dev.Device.dvIsid))
                {
                    return(false);
                }
                if (dev.Update(data))
                {
                    try
                    {
                        _db.tDevice.Update(dev.DbData);
                        await _db.SaveChangesAsync();
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Error(ex);
                        return(false);
                    }
                }
            }

            return(true);
        }