public ActionResult Edit([Bind(Include = "residential, building, unit, deviceid, chinaname, devtype")] hsf_outdevice hsf_outdevice)
        {
            if (ModelState.IsValid)
            {
                hsf_outdevice hsf_outdeviceDB = ihsf_outdeviceService.Find <hsf_outdevice>(hsf_outdevice.Id);
                hsf_outdeviceDB.residential = hsf_outdevice.residential;
                hsf_outdeviceDB.building    = hsf_outdevice.building;
                hsf_outdeviceDB.unit        = hsf_outdevice.unit;
                hsf_outdeviceDB.deviceid    = hsf_outdevice.deviceid;
                hsf_outdeviceDB.chinaname   = hsf_outdevice.chinaname;
                hsf_outdeviceDB.devtype     = hsf_outdevice.devtype;
                hsf_outdeviceDB.createtime  = DateTime.Now;
                ihsf_outdeviceService.Update(hsf_outdeviceDB);

                using (RedisHashService service = new RedisHashService())
                {
                    //室外,大华产品
                    string _residential = hsf_outdevice.residential;                    //小区
                    string _building    = hsf_outdevice.building;                       //楼号
                    string _unit        = hsf_outdevice.unit;                           //单元
                    string cachekey     = _residential + "-" + _building + "-" + _unit; //默认房间

                    //清除当前设备类型的设备列表缓存
                    service.RemoveEntryFromHash("OutDevices", cachekey);
                    logger.Debug($"清除当前单元的室外设备列表 {cachekey}");
                }

                return(RedirectToAction("Index"));
            }
            else
            {
                throw new Exception("ModelState未通过检测");
            }
        }
        public ActionResult Delete(string id)
        {
            if (id == null)
            {
                throw new Exception("Not Found");
            }
            hsf_outdevice hsf_outdevice = ihsf_outdeviceService.Find <hsf_outdevice>(id);

            if (hsf_outdevice == null)
            {
                throw new Exception("Not Found");
            }
            else
            {
                ihsf_outdeviceService.Delete(hsf_outdevice);

                using (RedisHashService service = new RedisHashService())
                {
                    //室外,大华产品
                    string _residential = hsf_outdevice.residential;                    //小区
                    string _building    = hsf_outdevice.building;                       //楼号
                    string _unit        = hsf_outdevice.unit;                           //单元
                    string cachekey     = _residential + "-" + _building + "-" + _unit; //默认房间

                    //清除当前设备类型的设备列表缓存
                    service.RemoveEntryFromHash("OutDevices", cachekey);
                    logger.Debug($"清除当前单元的室外设备列表 {cachekey}");
                }
            }
            return(RedirectToAction("Index"));
        }
Example #3
0
 public void Remove(string name)
 {
     using (var service = new RedisHashService())
     {
         service.RemoveEntryFromHash(RedisKey, name);
     }
 }
Example #4
0
        /// <summary>
        /// 添加设备 8;8211;All;+Base64(zip(设备对象jhson串))
        /// </summary>
        /// <param name="msg">user:123_Server type:other msg:
        /// 123_DCD9165057AD;8;8211;ALL;H4sIAAAAAAAAAH2QPU7EMBCF7zJ1CjuRs2wuQEdBuQitBmectZTEke2wQqutEAeg5Bx0SHscfo6Bf6JINMiNv/eeZ8Zzd4IbOt6SNLaFxtuZCtjrcGUFyIMeccSBoIGvt4+f58v35fXz5Z1B8Hp0TsUgXAVs6RF7tEPATPKA40j9ylpSCvOyFFyIWvCKbdniTcFgTKlSxlNjrRgTG6WyPaD815/QIjSncwZjfWxTic12sY3TXpsx1siKpU6altI0VZacR0/rsIn4XyxX9E9TjO5090C0v44PC9ADdvmHIcGZCFLfuTRM2ORkjmE/89JhdmRTFM73v4aKUN2AAQAA$/r$</param>
        public static string Host8211(string msg)
        {
            try
            {
                if (msg.Split(';').Length >= 4)
                {
                    string appUser     = msg.Split(';')[0];
                    string zipStr      = msg.Split(';')[4].Replace("$/r$", "");
                    string base64j     = EncryptionHelp.Decrypt(zipStr, true);
                    var    deviceLists = JsonConvert.DeserializeObject <List <host_device> >(base64j);//list多件开关,ALL数组
                    string posid       = "";
                    string cachekey    = "";
                    using (HsfDBContext hsfDBContext = new HsfDBContext())
                    {
                        foreach (var item in deviceLists)
                        {
                            posid    = item.devposition;
                            cachekey = item.devmac + "_" + item.devport;//存在mac相同,端口不相同的多键设备
                            if (string.IsNullOrEmpty(item.userid))
                            {
                                item.userid = appUser;
                            }
                            var deviceEntity = hsfDBContext.host_device.Where(t => t.cachekey == cachekey && t.deletemark == 0).FirstOrDefault();
                            if (deviceEntity != null)
                            {
                                deviceEntity.deletemark  = 1;
                                deviceEntity.modifiytime = DateTime.Now;
                                AddDevice(hsfDBContext, item);
                                log.Debug($"8211 OK,重新添加设备成功!");
                            }
                            else
                            {
                                //当前房间id需要保存,网关房间id为0,不可以
                                AddDevice(hsfDBContext, item);
                            }
                        }
                        //2.主机返回app添加成功
                        string msgResult = $"{appUser};8211;ALL;Zip;H4sIAAAAAAAAAHNMScnPBgD0Si5gBQAAAA==$/r$"; //拼接
                                                                                                               //清除房间设备列表缓存
                        using (RedisHashService service = new RedisHashService())
                        {
                            service.RemoveEntryFromHash("RoomDevices", appUser + "|" + posid);//解决默认posid都为0的问题
                        }

                        log.Info($"8211 OK,添加设备成功!返回信息:{msgResult}");
                        return(msgResult);
                    }
                }
                else
                {
                    log.Error($"8211 Fail,添加设备失败,命令不符合规范!");
                    return(null);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
Example #5
0
        /// <summary>
        /// 新增房间
        /// </summary>
        /// <param name="msg">user:123_Server type:other msg:
        /// 123_DCD9165057AD;8;836;H4sIAAAAAAAAAC2Muw7CIBSG3+XMDBxavLAZmR18gYbgiTIADdAQ0/Tdhdbt+68rPKg+ycb0AlXSQgwm15AzsB8XTDCeQEGtwMDZGBp38uZNvQYpRo/NmWPeNQohceQ4ohguhz+bZECt2y7Kd+5/vEW5mELH35Ip/efDpO/6iifJ5fmmYfsBAlhUH6EAAAA=$/r$
        /// {"NewRecord":true,"_id":0,"chinaname":"ww","icon":"","imageid":"room1","posid":"1225140141238","pospara":{},"postype":"0","state":"","userid":"123_DCD9165057AD"}</param>
        public static void Host836(string msg)
        {
            try
            {
                if (msg.Split(';').Length >= 3)
                {
                    string appUser = msg.Split(';')[0];
                    if (appUser.Contains("_"))
                    {
                        string account = appUser.Split('_')[0];
                        string mac     = appUser.Split('_')[1];

                        string zipStr  = msg.Split(';')[3].Replace("$/r$", "");
                        string base64j = EncryptionHelp.Decrypt(zipStr, true);
                        var    room    = JsonConvert.DeserializeObject <host_room>(base64j);//list多件开关
                        room.Account = account;
                        room.Mac     = mac;
                        using (HsfDBContext hsfDBContext = new HsfDBContext())
                        {
                            var roomEntity = hsfDBContext.host_room.Where(t => t.posid == room.posid && t.DeleteMark == 0).FirstOrDefault();
                            if (roomEntity != null)
                            {
                                roomEntity.DeleteMark = 1;
                                roomEntity.ModifyTime = DateTime.Now;
                                AddRoom(hsfDBContext, room);
                                log.Debug($"836 Ok,房间信息修改成功!");
                            }
                            else
                            {
                                //当前房间id需要保存,网关房间id为0,不可以
                                AddRoom(hsfDBContext, room);
                                log.Info($"836 OK,添加房间成功!");
                            }
                            //清除房间缓存信息,等待查询之后再次缓存
                            using (RedisHashService service = new RedisHashService())
                            {
                                service.RemoveEntryFromHash("Room", account);//解决默认posid都为0的问题
                            }
                        }
                    }
                    else
                    {
                        log.Error($"836 Fail,添加房间失败,命令不符合规范!");
                    }
                }
                else
                {
                    log.Error($"836 Fail,添加房间失败,命令不符合规范!");
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
 /// <summary>
 /// 新增房间
 /// </summary>
 /// <param name="msg">user:123_Server type:other msg:
 /// 123_DCD9165057AD;8;836;H4sIAAAAAAAAAC2Muw7CIBSG3+XMDBxavLAZmR18gYbgiTIADdAQ0/Tdhdbt+68rPKg+ycb0AlXSQgwm15AzsB8XTDCeQEGtwMDZGBp38uZNvQYpRo/NmWPeNQohceQ4ohguhz+bZECt2y7Kd+5/vEW5mELH35Ip/efDpO/6iifJ5fmmYfsBAlhUH6EAAAA=$/r$
 /// {"NewRecord":true,"_id":0,"chinaname":"ww","icon":"","imageid":"room1","posid":"1225140141238","pospara":{},"postype":"0","state":"","userid":"123_DCD9165057AD"}</param>
 public static string Host836(string msg)
 {
     try
     {
         string appUser = msg.Split(';')[0];
         if (appUser.Contains("_"))
         {
             string account = appUser.Split('_')[0];
             string mac     = appUser.Split('_')[1];
             string zipStr  = msg.Split(';')[3].Replace("$/r$", "");
             string base64j = EncryptionHelp.Decrypt(zipStr, true);
             var    room    = JsonConvert.DeserializeObject <host_room>(base64j);
             using (HsfDBContext hsfDBContext = new HsfDBContext())
             {
                 using (RedisHashService service = new RedisHashService())
                 {
                     var roomEntity = hsfDBContext.host_room.Where(t => t.posid == room.posid && t.DeleteMark == 0).FirstOrDefault();
                     if (roomEntity != null)
                     {
                         //roomEntity.DeleteMark = 1;
                         //roomEntity.ModifyUser = appUser;
                         //roomEntity.ModifyTime = DateTime.Now;
                         hsfDBContext.host_room.Remove(roomEntity);//真实删除
                         AddRoom(hsfDBContext, room, appUser, account, mac);
                         log.Debug($"836 Ok,房间信息修改成功!");
                     }
                     else
                     {
                         //当前房间id需要保存,网关房间id为0,不可以
                         AddRoom(hsfDBContext, room, appUser, account, mac);
                         log.Debug($"836 OK,添加房间成功!");
                     }
                     //清除房间缓存信息,等待查询之后再次缓存
                     service.RemoveEntryFromHash("Room", account);                              //解决默认posid都为0的问题
                     log.Debug($"清除家庭缓存{account}");
                     return($"{appUser};836;ALL;Zip;H4sIAAAAAAAAAHNMScnPBgD0Si5gBQAAAA==$/r$"); //Addok
                 }
             }
         }
         else
         {
             log.Debug($"836 Fail,添加房间失败,命令不符合规范!");
             return($"{appUser};836;ALL;Zip;H4sIAAAAAAAEAEstKsovAgBxvN1dBQAAAA==$/r$");//error
         }
     }
     catch (Exception)
     {
         throw;
     }
 }
 public static void PutDeviceChangeQueue(string host)
 {
     //如果存在百度音响的设备列表缓存,则清空,再发布同步消息队列
     using (RedisHashService service1 = new RedisHashService())
     {
         string duerOSHost = service1.GetValueFromHash("DuerOS_DiscoverPayload", host);
         if (!string.IsNullOrEmpty(duerOSHost))
         {
             service1.RemoveEntryFromHash("DuerOS_DiscoverPayload", host);
             log.Debug($"删除掉DuerOS_DiscoverPayload:{host}");
             using (RedisListService service = new RedisListService())
             {
                 service.Publish("LotDeviceChangeQueue", host);
                 log.Debug($"放入设备同步队列LotDeviceChangeQueue:{host}");
             }
         }
     }
 }
        /// <summary>
        /// 删除房间
        /// </summary>
        /// <param name="msg">123_DCD9165057AD;8;837;+posid</param>
        public static string Host837(string msg)
        {
            try
            {
                string appUser = msg.Split(';')[0];
                string account = appUser.Split('_')[0];
                string posid   = msg.Split(';')[3].Replace("$/r$", "");

                using (HsfDBContext hsfDBContext = new HsfDBContext())
                {
                    using (RedisHashService service = new RedisHashService())
                    {
                        var roomEntity = hsfDBContext.host_room.Where(t => t.posid == posid && t.DeleteMark == 0).FirstOrDefault();
                        if (roomEntity != null)
                        {
                            //roomEntity.DeleteMark = 1;
                            //roomEntity.ModifyUser = appUser;
                            //roomEntity.ModifyTime = DateTime.Now;
                            hsfDBContext.host_room.Remove(roomEntity);//真实删除
                            hsfDBContext.SaveChanges();
                            //清除房间缓存信息,等待查询之后再次缓存
                            service.RemoveEntryFromHash("Room", account);                              //解决默认posid都为0的问题
                            log.Debug($"837 Ok,删除房间成功!清除家庭缓存:{account}");
                            return($"{appUser};837;ALL;Zip;H4sIAAAAAAAEAHNJzcnPBgBZ82EeBQAAAA==$/r$"); //Delok
                        }
                        else
                        {
                            //当前房间id需要保存,网关房间id为0,不可以
                            log.Debug($"837 Fail,删除房间失败,房间id不存在!");
                            return($"{appUser};837;ALL;Zip;H4sIAAAAAAAEAEstKsovAgBxvN1dBQAAAA==$/r$");//error
                        }
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        public JsonResult AjaxDelete(string id)
        {
            if (id == null)
            {
                throw new Exception("Not Found");
            }
            hsf_outdevice hsf_outdevice = ihsf_outdeviceService.Find <hsf_outdevice>(id);

            if (hsf_outdevice == null)
            {
                throw new Exception("Not Found");
            }
            else
            {
                ihsf_outdeviceService.Delete <hsf_outdevice>(id);

                using (RedisHashService service = new RedisHashService())
                {
                    //室外,大华产品
                    string _residential = hsf_outdevice.residential;                    //小区
                    string _building    = hsf_outdevice.building;                       //楼号
                    string _unit        = hsf_outdevice.unit;                           //单元
                    string cachekey     = _residential + "-" + _building + "-" + _unit; //默认房间

                    //清除当前设备类型的设备列表缓存
                    service.RemoveEntryFromHash("OutDevices", cachekey);
                    logger.Debug($"清除当前单元的室外设备列表 {cachekey}");
                }

                AjaxResult ajaxResult = new AjaxResult()
                {
                    Result    = DoResult.Success,
                    PromptMsg = "删除成功"
                };
                return(Json(ajaxResult));
            }
        }
        /// <summary>
        ///1.修改总线开关mac地址  解压(总线开关01,0115170616344,58.57.32.162;F1;06,58.57.32.162;F1;01) 新名,房间id,老的地址,新的地址
        ///connect user:123_Server type:other msg:123_DCD9165057AD;8;823;01240943509560;5bCE54GvLDAxMTUxNzA2MTYzNDQ=$/r$
        ///2.主机返回改名成功renameok@1041140155612
        ///user:DAJCHSF_2047DABEF936 type:other msg:DAJCHSF_2047DABEF936;823;1041140155612;Zip;H4sIAAAAAAAAACtKzUvMTc3PdjA0MDE0NDEwNDU1MzQCAFBUoP4WAAAA$/r$
        /// </summary>
        /// <param name="msg"></param>
        public static string Host8231(string msg)
        {
            string msgResult = "";

            try
            {
                if (msg.Split(';').Length >= 4)
                {
                    string appUser        = msg.Split(';')[0];
                    string account        = appUser.Split('_')[0];
                    string deviceId       = msg.Split(';')[3];
                    string newName_Pid_ya = msg.Split(';')[4].Replace("$/r$", "");
                    string newName_Pid    = EncryptionHelp.Decrypt(newName_Pid_ya, false);

                    string newName   = newName_Pid.Split(',')[0];
                    string posid     = newName_Pid.Split(',')[1];
                    string oldDevmac = newName_Pid.Split(',')[2]; //总线开关旧的mac地址
                    string newDevmac = newName_Pid.Split(',')[3]; //总线开关新的mac地址
                    if (!string.IsNullOrEmpty(oldDevmac) && !string.IsNullOrEmpty(newDevmac) && oldDevmac != newDevmac)
                    {
                        //发送修改mac地址指令到网关服务器
                        bool isModify = RYZigMacModifyMsg(oldDevmac, newDevmac);
                        if (isModify)
                        {
                            using (HsfDBContext hsfDBContext = new HsfDBContext())
                            {
                                using (RedisHashService service = new RedisHashService())
                                {
                                    //根据老mac检索出同一开关下的继电器,一起修改mac
                                    List <host_device> deviceList = hsfDBContext.host_device.Where(t => t.devmac == oldDevmac && t.devposition == posid && t.account == account && t.deletemark == 0).ToList();
                                    if (deviceList.Count() != 0)
                                    {
                                        string devtype = deviceList[0].devtype;
                                        foreach (var item in deviceList)
                                        {
                                            //修改mac,缓存状态也要对应的修改,否则显示离线
                                            //先拿到之前的key状态,删掉,再赋值给新的key
                                            string st = service.GetValueFromHash("DeviceStatus", item.cachekey);
                                            service.RemoveEntryFromHash("DeviceStatus", item.cachekey);

                                            //当前名称变动的话,修改名称
                                            if (deviceId == item.deviceid)
                                            {
                                                item.chinaname = newName;                      //改名
                                            }
                                            item.devmac      = newDevmac;                      //改mac
                                            item.devip       = newDevmac;                      //改mac
                                            item.cachekey    = newDevmac + "_" + item.devport; //改mac
                                            item.modifiyuser = appUser;
                                            item.modifiytime = DateTime.Now;
                                            hsfDBContext.SaveChanges();

                                            //再赋值给新的key{"String 引用没有设置为 String 的实例。\r\n参数名: s"}
                                            if (!string.IsNullOrEmpty(st))
                                            {
                                                service.SetEntryInHash("DeviceStatus", item.cachekey, st);
                                                log.Debug($"改名key缓存新的状态 {item.cachekey} :{st}");
                                            }
                                            else
                                            {
                                                service.SetEntryInHash("DeviceStatus", item.cachekey, "False");
                                                log.Debug($"改名key缓存新的状态 {item.cachekey} 默认:False");
                                            }

                                            //清除当前设备缓存
                                            service.RemoveEntryFromHash("DeviceEntity", item.deviceid);
                                            log.Debug($"清除设备缓存DeviceEntity {item.deviceid}");
                                        }
                                        //2.主机返回app修改成功
                                        msgResult = $"{appUser};8231;{deviceId};Zip;H4sIAAAAAAAEACtKzUvMTc3PBgC88yB7CAAAAA==$/r$";//拼接 renameok

                                        //清除房间设备列表缓存
                                        service.RemoveEntryFromHash("RoomDevices", account + "|" + posid);
                                        log.Debug($"清除房间设备列表缓存RoomDevices {account}|{posid}");
                                        //清除当前设备类型的设备列表缓存
                                        service.RemoveEntryFromHash("TypeDevices", account + "|" + devtype);
                                        log.Debug($"清除当前设备类型的设备列表缓存TypeDevices {account}|{devtype}");

                                        log.Debug($"8231 OK,设备重命名成功!返回信息:{msgResult}");
                                        return(msgResult);
                                    }
                                    else
                                    {
                                        log.Debug($"8231 Fail,修改mac地址数据库失败,设备不存在!");
                                        return(null);
                                    }
                                }
                            }
                        }
                        else
                        {
                            log.Debug($"8231 Fail,修改mac地址失败,修改失败!");
                            msgResult = $"{appUser};8231;{deviceId};Zip;H4sIAAAAAAAEAEstKsovAgBxvN1dBQAAAA==$/r$";//拼接 error
                            return(msgResult);
                        }
                    }
                    else
                    {
                        log.Debug($"8231 Fail,修改mac地址失败,mac地址不能为空,新旧地址不能相同!");
                        msgResult = $"{appUser};8231;{deviceId};Zip;H4sIAAAAAAAEAEstKsovAgBxvN1dBQAAAA==$/r$";//拼接 error
                        return(msgResult);
                    }
                }
                else
                {
                    log.Debug($"8231 Fail,设备重命名失败,命令不符合规范!");
                    return(null);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
Example #11
0
        public static void Show()
        {
            Student student_1 = new Student()
            {
                Id   = 11,
                Name = "Eleven"
            };
            Student student_2 = new Student()
            {
                Id     = 12,
                Name   = "Twelve",
                Remark = "123423245"
            };

            Console.WriteLine("====Basic redis test====");
            {
                using (RedisStringService service = new RedisStringService())
                {
                    service.Set <string>("student1", "May");
                    Console.WriteLine(service.Get("student1"));

                    service.Append("student1", " from china");
                    Console.WriteLine($"After append : {service.Get("student1")}");

                    service.GetAndSetValue("student1", "Modified May ");
                    Console.WriteLine(service.Get("student1"));

                    service.Set <string>("stu2", "Lee", DateTime.Now.AddSeconds(5));
                    //Thread.Sleep(1000);
                    Console.WriteLine(service.Get("stu2"));

                    service.Set <int>("age", 23);
                    service.Incr("age");
                    Console.WriteLine($"After Incr: {service.Get("age")}");
                    service.IncrBy("age", 10);
                    Console.WriteLine($"After Incr by 10: {service.Get("age")}");
                    service.Decr("age");
                    Console.WriteLine($"After Decr: {service.Get("age")}");
                    service.DecrBy("age", 10);
                    Console.WriteLine($"After Decr by 10: {service.Get("age")}");
                }

                {
                    Console.WriteLine("===Basic redis hash table===");
                    using (RedisHashService service = new RedisHashService())
                    {
                        service.SetEntryInHash("stuHash", "id", "123");
                        service.SetEntryInHash("stuHash", "name", "MayHash");
                        service.SetEntryInHash("stuHash", "remark", "Graudate");

                        var keys      = service.GetHashKeys("stuHash");
                        var values    = service.GetHashValues("stuHash");
                        var keyValues = service.GetAllEntriesFromHash("stuHash");

                        string valueId = service.GetValueFromHash("stuHash", "id");
                        Console.WriteLine(valueId);

                        service.SetEntryInHashIfNotExists("stuHash", "name", "MayHashUpdated");
                        service.SetEntryInHashIfNotExists("stuHash", "description", "Advanced class");
                        Console.WriteLine(service.GetValueFromHash("stuHash", "name"));
                        Console.WriteLine(service.GetValueFromHash("stuHash", "description"));
                        service.RemoveEntryFromHash("stuHash", "description");
                        Console.WriteLine($"After remove: {service.GetValueFromHash("stuHash", "description")}");
                    }
                }
            }
        }
        /// <summary>
        ///1.告诉主机重命名设备名称  解压(射灯,0115170616344) 新名,房间id
        ///connect user:123_Server type:other msg:123_DCD9165057AD;8;823;01240943509560;5bCE54GvLDAxMTUxNzA2MTYzNDQ=$/r$
        ///2.主机返回改名成功renameok@1041140155612
        ///user:DAJCHSF_2047DABEF936 type:other msg:DAJCHSF_2047DABEF936;823;1041140155612;Zip;H4sIAAAAAAAAACtKzUvMTc3PdjA0MDE0NDEwNDU1MzQCAFBUoP4WAAAA$/r$
        /// </summary>
        /// <param name="msg"></param>
        public static string Host823(string msg)
        {
            string msgResult = "";

            try
            {
                if (msg.Split(';').Length >= 4)
                {
                    string appUser        = msg.Split(';')[0];
                    string account        = appUser.Split('_')[0];
                    string deviceId       = msg.Split(';')[3];
                    string newName_Pid_ya = msg.Split(';')[4].Replace("$/r$", "");
                    string newName_Pid    = EncryptionHelp.Decrypt(newName_Pid_ya, false);

                    string newName = newName_Pid.Split(',')[0];
                    string posid   = newName_Pid.Split(',')[1];

                    using (HsfDBContext hsfDBContext = new HsfDBContext())
                    {
                        using (RedisHashService service = new RedisHashService())
                        {
                            //根据房间id+设备id查询要改名的设备
                            var deviceEntity = hsfDBContext.host_device.Where(t => t.deviceid == deviceId && t.devposition == posid && t.deletemark == 0).FirstOrDefault();
                            if (deviceEntity != null)
                            {
                                deviceEntity.chinaname   = newName;//改名
                                deviceEntity.modifiyuser = appUser;
                                deviceEntity.modifiytime = DateTime.Now;
                                hsfDBContext.SaveChanges();

                                //2.主机返回app重命名成功
                                msgResult = $"{appUser};823;{deviceId};Zip;H4sIAAAAAAAEACtKzUvMTc3PBgC88yB7CAAAAA==$/r$";//拼接 renameok

                                //清除房间设备列表缓存
                                service.RemoveEntryFromHash("RoomDevices", account + "|" + posid);
                                log.Debug($"1.设备重命名,清除房间设备列表缓存RoomDevices {account}|{posid}");
                                if (posid != "0")
                                {
                                    service.RemoveEntryFromHash("RoomDevices", account + "|0");//房间内设备变动时,0所有设备的缓存也随之清除
                                }
                                //清除当前设备类型的设备列表缓存
                                service.RemoveEntryFromHash("TypeDevices", account + "|" + deviceEntity.devtype);
                                log.Debug($"2.设备重命名,清除当前设备类型的设备列表缓存TypeDevices {account}|{deviceEntity.devtype}");
                                //4同步DuerOS设备
                                DuerOSClient.PutDeviceChangeQueue(account);
                                log.Debug($"3.设备重命名,同步DuerOS设备 {account}");

                                log.Debug($"823 OK,设备重命名成功!返回信息:{msgResult}");
                                return(msgResult);
                            }
                            else
                            {
                                log.Debug($"823 Fail,设备重命名失败,设备不存在!");
                                msgResult = $"{appUser};823;{deviceId};Zip;H4sIAAAAAAAEAEstKsovAgBxvN1dBQAAAA==$/r$";//拼接 error
                                return(msgResult);
                            }
                        }
                    }
                }
                else
                {
                    log.Debug($"823 Fail,设备重命名失败,命令不符合规范!");
                    return(null);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        /// <summary>
        ///1.告诉主机删除设备
        ///user:123_Server type:other msg:123_DCD9165057AD;8;822;1041656180510$/r$
        ///2.主机返回删除成功delok@105 124612 6590
        ///user:123_DCD9165057AD type:other msg:123_DCD9165057AD;822;1041656180510;Zip;H4sIAAAAAAAAAEtJzcnPdjA0MDE0MzUztDAwNTQAAJxecTETAAAA$/r$
        /// </summary>
        /// <param name="msg"></param>
        public static string Host822(string msg)
        {
            string msgResult = "";

            try
            {
                if (msg.Split(';').Length >= 4)
                {
                    string appUser  = msg.Split(';')[0];
                    string account  = appUser.Split('_')[0];
                    string deviceId = msg.Split(';')[3].Replace("$/r$", "");
                    string posid    = "";
                    string cachekey = "";
                    using (HsfDBContext hsfDBContext = new HsfDBContext())
                    {
                        using (RedisHashService service = new RedisHashService())
                        {
                            //能否确定deviceid唯一,用时间来做标识??隐患 :添加用户限定排除风险
                            var deviceEntity = hsfDBContext.host_device.Where(t => t.deviceid == deviceId && t.account == account && t.deletemark == 0).FirstOrDefault();
                            if (deviceEntity != null)
                            {
                                posid    = deviceEntity.devposition;
                                cachekey = deviceEntity.devmac + "_" + deviceEntity.devport;//存在mac相同,端口不相同的多键设备

                                //deviceEntity.deletemark = 1;
                                //deviceEntity.modifiyuser = appUser;
                                //deviceEntity.modifiytime = DateTime.Now;
                                hsfDBContext.host_device.Remove(deviceEntity);//真实删除
                                hsfDBContext.SaveChanges();

                                //2.主机返回app删除成功
                                msgResult = $"{appUser};822;{deviceId};Zip;H4sIAAAAAAAEAEtJzcnPBgBd3KDfBQAAAA==$/r$";//拼接 delok

                                //1清除房间设备列表缓存
                                service.RemoveEntryFromHash("RoomDevices", account + "|" + posid);
                                log.Debug($"1.删除设备,清除房间设备列表缓存RoomDevices {account}|{posid}");
                                if (posid != "0")
                                {
                                    service.RemoveEntryFromHash("RoomDevices", account + "|0");//房间内设备变动时,0所有设备的缓存也随之清除
                                }
                                //2清除当前设备状态
                                service.RemoveEntryFromHash("DeviceStatus", cachekey);
                                log.Debug($"2.删除设备,清除当前设备状态DeviceStatus {cachekey}");
                                //3清除当前设备类型的设备列表缓存
                                service.RemoveEntryFromHash("TypeDevices", account + "|" + deviceEntity.devtype);
                                log.Debug($"3.删除设备,清除当前设备类型的设备列表缓存TypeDevices {account}|{deviceEntity.devtype}");
                                //4同步DuerOS设备
                                DuerOSClient.PutDeviceChangeQueue(account);
                                log.Debug($"4.删除设备,同步DuerOS设备 {account}");


                                log.Debug($"822 OK,删除设备成功!返回信息:{msgResult}");
                                return(msgResult);
                            }
                            else
                            {
                                log.Debug($"822 Fail,删除设备失败,设备不存在!");
                                msgResult = $"{appUser};822;{deviceId};Zip;H4sIAAAAAAAEAEstKsovAgBxvN1dBQAAAA==$/r$";//拼接 error
                                return(msgResult);
                            }
                        }
                    }
                }
                else
                {
                    log.Debug($"822 Fail,删除设备失败,命令不符合规范!");
                    return(null);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        /// <summary>
        /// 添加设备 8;8211;All;+Base64(zip(设备对象jhson串))
        /// </summary>
        /// <param name="msg">user:123_Server type:other msg:
        /// 123_DCD9165057AD;8;8211;ALL;H4sIAAAAAAAAAH2QPU7EMBCF7zJ1CjuRs2wuQEdBuQitBmectZTEke2wQqutEAeg5Bx0SHscfo6Bf6JINMiNv/eeZ8Zzd4IbOt6SNLaFxtuZCtjrcGUFyIMeccSBoIGvt4+f58v35fXz5Z1B8Hp0TsUgXAVs6RF7tEPATPKA40j9ylpSCvOyFFyIWvCKbdniTcFgTKlSxlNjrRgTG6WyPaD815/QIjSncwZjfWxTic12sY3TXpsx1siKpU6altI0VZacR0/rsIn4XyxX9E9TjO5090C0v44PC9ADdvmHIcGZCFLfuTRM2ORkjmE/89JhdmRTFM73v4aKUN2AAQAA$/r$
        /// user:123_DCD9165057AD type:other msg:
        /// 123_DCD9165057AD;8;8212;ALL;H4sIAAAAAAAAAG2RsU7DMBCG38VzVOUcN6TZGBlggBGh6ORcUkuJHdlJI1RVYmFn4ykQAyuv04G3wIlLRBHy4u/+/3y/zvd7dkPjLUljS5b3dqCIFcpf44jJrdKosSWWM5RZUiUgCKsL5qUGnasmH8s8lrTDBm3rMZDcotbULKwkzWbgsAbBIRYiSeOT1s1CEqhFOeGGryDNVlm2gpgHpUOLLN/72cZNkY7PH1+vbxEHiPz522A60pPp8+n48v6/6RCeNbZfcnbGqV4ZHaICCJHGsPlJaqmWpqTfcV2PPS3tM8E58gX7x26yXl4V16Tr0gy+rFqsw2q8AeK1LzW1myP5H+jM6Bc7nAYMjuxsHbFRxR3ZHVl2ePgGQ/XuYsMBAAA=$/r$
        /// [{"NewRecord":true,"_id":0,"chinaname":"ac83f314eaf7","classfid":"8","devalarm":"","devchannel":"","deviceid":"12151421044360","devip":"123","devmac":"192.168.88.102","devpara":{"close":"关闭,211,1,192.168.88.102","open":"开启,211,1,192.168.88.102"},"devport":"","devposition":"1211144601960","devregcode":"123","devstate":"","devstate1":"","devstate2":"","devtype":"AI_Mengdou","imageid":"dev105","lgsort":0,"powvalue":"","userid":"wali_Server"}]
        ///
        /// </param>
        public static string AddDeviceToRoom(string msg, string code)
        {
            try
            {
                if (msg.Split(';').Length >= 4)
                {
                    using (RedisHashService service = new RedisHashService())
                    {
                        string appUser     = msg.Split(';')[0];
                        string account     = appUser.Split('_')[0];
                        string mac         = appUser.Split('_')[1];
                        string zipStr      = msg.Split(';')[4].Replace("$/r$", "");
                        string base64j     = EncryptionHelp.Decrypt(zipStr, true);
                        var    deviceLists = JsonConvert.DeserializeObject <List <host_device> >(base64j);//list多件开关,ALL数组
                        using (HsfDBContext hsfDBContext = new HsfDBContext())
                        {
                            string posid      = "";
                            string cachekey   = "";
                            string devchannel = "";
                            string devtype    = "";
                            string devmac     = "";
                            foreach (var item in deviceLists)
                            {
                                devtype    = item.devtype;
                                devchannel = item.devchannel;
                                posid      = item.devposition;
                                devmac     = item.devmac;
                                if (!string.IsNullOrEmpty(item.devport))
                                {
                                    cachekey = item.devmac + "_" + item.devport;//存在mac相同,端口不相同的多键设备
                                }
                                else
                                {
                                    cachekey = item.devmac;//存在mac相同,端口不相同的多键设备
                                }

                                var deviceEntity = hsfDBContext.host_device.Where(t => t.cachekey == cachekey && t.deletemark == 0).FirstOrDefault();
                                if (deviceEntity != null)
                                {
                                    //deviceEntity.deletemark = 1;
                                    //deviceEntity.modifiyuser = appUser;
                                    //deviceEntity.modifiytime = DateTime.Now;
                                    hsfDBContext.host_device.Remove(deviceEntity);//真实删除
                                    AddDeviceEntity(hsfDBContext, item, appUser, account, mac);
                                    log.Debug($"{code} OK,重新添加设备成功!");
                                }
                                else
                                {
                                    //当前房间id需要保存,网关房间id为0,不可以
                                    AddDeviceEntity(hsfDBContext, item, appUser, account, mac);
                                }

                                string statusStr = service.GetValueFromHash("DeviceStatus", cachekey);
                                if (string.IsNullOrEmpty(statusStr))
                                {
                                    //缓存状态不存在的,先设备状态默认为False,在线,关闭
                                    service.SetEntryInHash("DeviceStatus", cachekey, "False");
                                }
                            }
                            //如果设备网关字段不为空,则查询网关最初状态,可能不全部关闭?
                            if (!string.IsNullOrEmpty(devchannel) && devtype.Contains("Zigbee"))
                            {
                                YunZigClient.SendMsg($"{{\"code\" :5001,\"serial\": 11111,\"device\":[{{\"id\": \"{devmac}\"}}],\"zigbee\":\"{devchannel}\"}}");//zigbee查询初始状态,向网关
                            }

                            //1清除房间设备列表缓存
                            service.RemoveEntryFromHash("RoomDevices", account + "|" + posid);
                            if (posid != "0")
                            {
                                service.RemoveEntryFromHash("RoomDevices", account + "|0");//房间内设备变动时,0所有设备的缓存也随之清除
                            }
                            log.Debug($"1.添加设备,清除房间设备列表缓存RoomDevices {account}|{posid}");
                            //2清除当前设备类型的设备列表缓存
                            service.RemoveEntryFromHash("TypeDevices", account + "|" + devtype);
                            log.Debug($"2.添加设备,清除当前设备类型的设备列表缓存TypeDevices {account}|{devtype}");
                            //3同步DuerOS设备
                            DuerOSClient.PutDeviceChangeQueue(account);
                            log.Debug($"3.添加设备,同步DuerOS设备 {account}");

                            //主机返回app添加成功
                            string msgResult = $"{appUser};{code};ALL;Zip;H4sIAAAAAAAAAHNMScnPBgD0Si5gBQAAAA==$/r$";//拼接
                            log.Debug($"{code} OK,添加设备成功!返回信息:{msgResult}");
                            return(msgResult);
                        }
                    }
                }
                else
                {
                    log.Debug($"{code} Fail,添加设备失败,命令不符合规范!");
                    return(null);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        public ActionResult AjaxCreate([Bind(Include = "Id, residential, building, unit, deviceid, chinaname, devtype")] hsf_outdevice hsf_outdevice)
        {
            if (!string.IsNullOrEmpty(hsf_outdevice.deviceid))
            {
                hsf_outdevice.Id         = Guid.NewGuid().ToString();
                hsf_outdevice.createtime = DateTime.Now;
                hsf_outdevice.deletemark = 0;
                hsf_outdevice newhsf_outdevice = ihsf_outdeviceService.Insert(hsf_outdevice);

                using (RedisHashService service = new RedisHashService())
                {
                    //室外,大华产品
                    string _residential = hsf_outdevice.residential;                    //小区
                    string _building    = hsf_outdevice.building;                       //楼号
                    string _unit        = hsf_outdevice.unit;                           //单元
                    string cachekey     = _residential + "-" + _building + "-" + _unit; //默认房间

                    //清除当前设备类型的设备列表缓存
                    if (string.IsNullOrEmpty(_building) && string.IsNullOrEmpty(_unit))
                    {
                        //MMSJ--,整个所在小区添加公共设备,比如公共摄像头,所有业主的缓存全部删除
                        List <string> ods = service.GetHashKeys("OutDevices");
                        foreach (var item in ods)
                        {
                            if (item.Contains(_residential))
                            {
                                service.RemoveEntryFromHash("OutDevices", item);
                            }
                        }
                    }
                    else if (string.IsNullOrEmpty(_unit))
                    {
                        //MMSJ-1-所在楼号添加公共设备,比如楼号摄像头,楼号内业主的缓存全部删除
                        List <string> ods = service.GetHashKeys("OutDevices");
                        foreach (var item in ods)
                        {
                            if (item.Contains(_residential + "-" + _building))
                            {
                                service.RemoveEntryFromHash("OutDevices", item);
                            }
                        }
                    }
                    else
                    {
                        //MMSJ-1-1所在单元设备变动,比如单元门,单元内业主的缓存全部删除
                        service.RemoveEntryFromHash("OutDevices", cachekey);
                    }

                    logger.Debug($"清除当前单元的室外设备列表 {cachekey}");
                }

                AjaxResult ajaxResult = new AjaxResult()
                {
                    Result    = DoResult.Success,
                    PromptMsg = "插入成功"
                };
                return(Json(ajaxResult));
            }
            else
            {
                logger.Debug($"error:id不能为空!");
                AjaxResult ajaxResult = new AjaxResult()
                {
                    Result    = DoResult.Failed,
                    PromptMsg = "id不能为空"
                };
                return(Json(ajaxResult));
            }
        }