/// <summary>
        /// 登录验证
        /// </summary>
        /// <param name="account"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static string CheckLogin(string account, string password)
        {
            hsf_owner ownerEntity = null;

            using (HsfDBContext hsfDBContext = new HsfDBContext())
            {
                using (RedisHashService service = new RedisHashService())
                {
                    string _password = service.GetValueFromHash("Login", account);
                    if (string.IsNullOrEmpty(_password))
                    {
                        ownerEntity = hsfDBContext.hsf_owner.Where(t => t.telphone == account && t.deletemark == 0).FirstOrDefault();
                        if (ownerEntity != null)
                        {
                            service.SetEntryInHash("Login", account, ownerEntity.password);
                            if (ownerEntity.password == password)
                            {
                                return(EncryptionHelp.Encryption(JsonConvert.SerializeObject(ownerEntity), false));
                            }
                            else
                            {
                                return("error:Password error!");
                            }
                        }
                        else
                        {
                            return("error:No account exists!");
                        }
                    }
                    else
                    {
                        if (_password == password)
                        {
                            string _Owner = service.GetValueFromHash("Owner", account);
                            if (string.IsNullOrEmpty(_Owner))
                            {
                                ownerEntity = hsfDBContext.hsf_owner.Where(t => t.telphone == account && t.deletemark == 0).FirstOrDefault();
                                if (ownerEntity != null)
                                {
                                    service.SetEntryInHash("Owner", ownerEntity.telphone, JsonConvert.SerializeObject(ownerEntity));
                                    return(EncryptionHelp.Encryption(JsonConvert.SerializeObject(ownerEntity), false));
                                }
                                else
                                {
                                    return("error:No account exists!");
                                }
                            }
                            else
                            {
                                return(EncryptionHelp.Encryption(_Owner, false));
                            }
                        }
                        else
                        {
                            return("error:Password error!");
                        }
                    }
                }
            }
        }
        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
        /// <summary>
        /// 测试作业
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task Execute(IJobExecutionContext context)
        {
            //JobDataMap dataMap = context.JobDetail.JobDataMap;
            //string k = dataMap.GetString("key");//获取参数(可根据传递的类型使用GetInt、GetFloat、GetString.....)
            //_log.Debug("run TestJob debug");
            //_log.Error("run TestJob error");
            //_log.Info("run TestJob info");
            // 在这里处理你的任务
            using (HmkDBContext hmkDBContext = new HmkDBContext())
            {
                hmkDBContext.Database.CommandTimeout = 120;
                int seeCount   = 3052851 + hmkDBContext.TelphoneLiangSee.Count();//浏览记录老bak表总数量3052851
                var shareCount = hmkDBContext.TelphoneLiangShare.Count();
                var joinCount  = hmkDBContext.TelphoneLiangJoin.Count();
                var orgCount   = hmkDBContext.Base_Organize.Count();
                var telCount   = hmkDBContext.TelphoneLiang.Count();

                using (RedisHashService service = new RedisHashService())
                {
                    service.SetEntryInHash("Hmk_Count", "seeCount", seeCount.ToString());
                    service.SetEntryInHash("Hmk_Count", "shareCount", shareCount.ToString());
                    service.SetEntryInHash("Hmk_Count", "joinCount", joinCount.ToString());
                    service.SetEntryInHash("Hmk_Count", "orgCount", orgCount.ToString());
                    service.SetEntryInHash("Hmk_Count", "telCount", telCount.ToString());
                }
                _log.Info("存入缓存--》seeCount:" + seeCount + " 分享:" + shareCount + " 加盟:" + joinCount + " 机构:" + orgCount + " 号码:" + telCount);
            }
        }
Example #4
0
 public void Remove(string name)
 {
     using (var service = new RedisHashService())
     {
         service.RemoveEntryFromHash(RedisKey, name);
     }
 }
Example #5
0
 public T Get <T>(string name)
 {
     using (var service = new RedisHashService())
     {
         return(service.Get <T>(RedisKey, name));
     };
 }
Example #6
0
        ///// <summary>
        ///// 登录验证
        ///// </summary>
        ///// <param name="account"></param>
        ///// <param name="password"></param>
        ///// <returns></returns>
        //public hsf_owner CheckLogin(string account, string password)
        //{
        //    hsf_owner ownerEntity = null;
        //    using (HsfDBContext hsfDBContext = new HsfDBContext())
        //    {
        //        using (RedisHashService service = new RedisHashService())
        //        {
        //            string _password = service.GetValueFromHash("Login", account);
        //            if (string.IsNullOrEmpty(_password))
        //            {
        //                ownerEntity = hsfDBContext.hsf_owner.Where(t => t.telphone == account && t.deletemark == 0).FirstOrDefault();
        //                if (ownerEntity != null)
        //                {
        //                    service.SetEntryInHash("Login", account, ownerEntity.password);
        //                    if (ownerEntity.password == password)
        //                    {
        //                        return ownerEntity;
        //                    }
        //                    else
        //                    {
        //                        return null;
        //                    }
        //                }
        //                else
        //                {
        //                    return null;
        //                }
        //            }
        //            else
        //            {
        //                if (_password == password)
        //                {
        //                    string _Owner = service.GetValueFromHash("Owner", account);
        //                    if (string.IsNullOrEmpty(_Owner))
        //                    {
        //                        ownerEntity = hsfDBContext.hsf_owner.Where(t => t.telphone == account && t.deletemark == 0).FirstOrDefault();
        //                        if (ownerEntity != null)
        //                        {
        //                            service.SetEntryInHash("Owner", ownerEntity.telphone, JsonConvert.SerializeObject(ownerEntity));
        //                            return ownerEntity;
        //                        }
        //                        else
        //                        {
        //                            return null;
        //                        }
        //                    }
        //                    else
        //                    {
        //                        return JsonConvert.DeserializeObject<hsf_owner>(_Owner);
        //                    }
        //                }
        //                else
        //                {
        //                    return null;
        //                }
        //            }
        //        }
        //    }
        //}

        /// <summary>
        /// 新风登录验证:t_customer_user表unionid(补充手机号,一个公众号对应一个),得到id作为网关id,缓存手机号-网关
        /// </summary>
        /// <param name="account"></param>
        /// <param name="password"></param>
        /// <returns>返回用户实体</returns>
        public string CheckLogin(string account, string password)
        {
            using (NewiotDBContext newiotDBContext = new NewiotDBContext())
            {
                using (RedisHashService service = new RedisHashService())
                {
                    string password_redis = service.GetValueFromHash("Host", account);//redis值
                    //string password_md5 = PasswordHelper.MD5Encoding("123456","huiquan");//不知道salt多少盐值得到=77d3b7ed9db7d236b9eac8262d27f6a5
                    if (string.IsNullOrEmpty(password_redis))
                    {
                        t_customer_user ownerEntity = newiotDBContext.t_customer_user.Where(t => t.unionid == account).FirstOrDefault();
                        if (ownerEntity != null)
                        {
                            service.SetEntryInHash("Host", account, ownerEntity.id.ToString());
                            return(ownerEntity.id.ToString());
                        }
                        else
                        {
                            return(null);
                        }
                    }
                    else
                    {
                        return(password_redis);
                    }
                }
            }
        }
        /// <summary>
        /// 8145关闭设备 8;8135;设备id
        /// user:123_DCD9165057AD type:other msg:123_DCD9165057AD;8;8145;01120925117040;3,0$/r$
        /// 8135打开设备 8;8135;设备id
        /// user:123_DCD9165057AD type:other msg:123_DCD9165057AD;8;8135;01120925117040;2;8$/r$
        /// user:123_Server type:other msg:123_e0ddc0a405d9;8;8135;A$/r$
        /// {"code":1002,"id":"010000124b0014c6aaee","ep":1,"serial":1,"control":{"on":true},"result":0,"zigbee":"00ff2c2c2c6a6f005979"}
        /// user:DAJCHSF_% type:other msg:DAJCHSF_Server;devrefresh;1041656180510,true,DAJCHSF_2047DABEF936$/r$
        ///
        /// user:MMSJ-1#1-5-501 type:other msg:MMSJ-1-1-5-501;8;8145;08$/r$
        ///
        /// </summary>
        /// <param name="msg"></param>
        public static bool DeviceStateChange(string msg)//, string code, bool state, string success, out string relayUser
        {
            try
            {
                string appUser  = msg.Split(';')[0];
                string code     = msg.Split(';')[2];
                string deviceId = msg.Split(';')[3].Replace("$/r$", "");//新app设备id为最后一位
                bool   state;
                if (code == "8135")
                {
                    state = true;
                }
                else if (code == "8145")
                {
                    state = false;
                }
                else
                {
                    log.Debug($"{msg}code指令不对返回失败!");
                    return(false);//指令不对返回失败
                }

                using (RedisHashService service = new RedisHashService())
                {
                    string      deviceEntityStr = service.GetValueFromHash("DeviceEntity", deviceId);//8231有关联,改mac的情况下,其它改状态,改名称,不需要清理
                    host_device deviceEntity    = null;
                    if (!string.IsNullOrEmpty(deviceEntityStr))
                    {
                        deviceEntity = JsonConvert.DeserializeObject <host_device>(deviceEntityStr);//设备实体缓存
                    }
                    else
                    {
                        using (HsfDBContext hsfDBContext = new HsfDBContext())
                        {
                            deviceEntity = hsfDBContext.host_device.Where(t => t.deviceid == deviceId && t.deletemark == 0).FirstOrDefault();//注意device的唯一性
                            if (deviceEntity != null)
                            {
                                //缓存设备id与设备实体对应关系,避免查询数据库
                                service.SetEntryInHash("DeviceEntity", deviceId, JsonConvert.SerializeObject(deviceEntity));
                            }
                        }
                    }

                    if (deviceEntity != null)
                    {
                        //拼装1002指令,发送给网关,执行改变状态操作
                        return(ChangeStateMain.StateChangeByType(deviceEntity, state));
                    }
                    else
                    {
                        //relayUser = appUser;
                        return(false);//error
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
Example #8
0
        void myServer_SessionClosed(HansAppSession session, SuperSocket.SocketBase.CloseReason value)
        {
            foreach (var item in Gateway_SessionDic)
            {
                if (item.Value == session)
                {
                    HansAppSession dd = null;
                    Gateway_SessionDic.TryRemove(item.Key, out dd);
                    using (RedisHashService service = new RedisHashService())
                    {
                        service.SetEntryInHash("DeviceStatus", item.Key + "_13579", "");//设置离线,
                        log.Info($"{item.Key} 离开服务器");
                        //网关下的所有设备状态设置为离线
                        using (HsfDBContext db = new HsfDBContext())
                        {
                            var channelList = db.host_device.Where(t => t.devchannel == item.Key && t.deletemark == 0);
                            foreach (var item2 in channelList)
                            {
                                service.SetEntryInHash("DeviceStatus", item2.cachekey, "");//设置离线
                            }
                        }
                    }
                }
            }
            connectCount--;
            Console.WriteLine($"{session.RemoteEndPoint.ToString()} 离开服务器 {connectCount} {DateTime.Now.ToString()}");
            log.Info($"{session.RemoteEndPoint.ToString()} 离开服务器 {connectCount}");

            //throw new NotImplementedException();
        }
        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未通过检测");
            }
        }
Example #10
0
        /// <summary>
        /// 新增用户信息
        /// </summary>
        /// <param name="user"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool AddUserInfo(T_Sys_User user, out string msg)
        {
            msg = string.Empty;
            //检验该账户是否已存在
            var existUser = Db.Select<T_Sys_User>()
                .Where(i => i.Account.Equals(user.Account, StringComparison.CurrentCultureIgnoreCase)).First();
            if (existUser != null)
            {
                msg = "该账号已存在!";
                return false;
            }

            //密码MD5加密
            user.Password = EncryptHelper.MD5Encrypt(user.Password);
            user.CreateTime = DateTime.Now;
            user.UpdateTime = DateTime.Now;
            long id = Db.Insert<T_Sys_User>(user).ExecuteIdentity();

            if (id <= 0)
            {
                msg = "新增用户失败,请联系系统管理员!";
                return false;
            }

            //写入缓存
            using (RedisHashService service = new RedisHashService())
            {
                user.Id = id;
                service.StoreAsHash(user);
            }

            return true;
        }
Example #11
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 #12
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;
            }
        }
Example #13
0
        /// <summary>
        /// 收到YunZig状态改变队列数据
        /// </summary>
        public static void GetYunZigStateChangeQueue()
        {
            Task.Run(() =>
            {
                ToolHelper.FunctionHelper.writeLog("手动或App上报状态", "启动线程……", "YunZigStateChangeQueue");
                try
                {
                    using (RedisListService service = new RedisListService())
                    {
                        service.Subscribe("YunZigStateChangeQueue", (c, cachekey, iRedisSubscription) =>
                        {
                            //log.Debug($"收到YunZig状态改变队列数据,同步状态 {c}:{message},Dosomething else");
                            //ToolHelper.FunctionHelper.writeLog("状态订阅", cachekey, "YunZigStateChangeQueue");
                            using (RedisHashService serviceHash = new RedisHashService())
                            {
                                //获取openUid
                                string openUid = serviceHash.GetValueFromHash("DuerOSOpenUid_Device", cachekey);
                                if (!string.IsNullOrEmpty(openUid))
                                {
                                    var tempPostModel = new ChangeReportRequestModel()
                                    {
                                        header = new Models.CommonModel.Head()
                                        {
                                            messageId      = FunctionHelper.GetTimStamp() + "",
                                            name           = "ChangeReportRequest",
                                            @namespace     = "DuerOS.ConnectedHome.Control",
                                            payloadVersion = 1
                                        },
                                        payload = new Models.ReturnModel.Payload.ChangeReportRequestPayload()
                                        {
                                            botId     = DuerOSSyncBotId,
                                            openUid   = openUid,
                                            appliance = new Models.ReturnModel.Payload.TempAppliance()
                                            {
                                                applianceId   = cachekey,
                                                attributeName = "turnOnState"
                                            }
                                        }
                                    };

                                    var tempRes = ToolHelper.FunctionHelper.PostJsonString(DuerOSChangeReportUrl, JsonConvert.SerializeObject(tempPostModel));//{"status":21093,"msg":"Appliance specificed not exist, stop sync","messageId":"1557135094549","data":{"updated_attribute_num":0}}
                                    ToolHelper.FunctionHelper.writeLog("手动或App上报状态: " + cachekey, tempRes, "YunZigStateChangeQueue");
                                    Thread.Sleep(100);
                                }
                            }
                        });//blocking
                    }
                }
                catch (Exception ex)
                {
                    FunctionHelper.writeLog("状态订阅异常", ex.Message, "YunZigStateChangeQueue");
                    throw;
                }
            });
        }
Example #14
0
 /// <summary>
 /// 向智能主机发送音响语音内容,异步返回答案为null
 /// </summary>
 /// <param name="body"></param>
 /// <returns></returns>
 public NlpAnswers SendMsg(SoundBodyRequest body)
 {
     log.Debug($"SmartHomeNlp接收到问题 :{body.questions}");
     try
     {
         string hostid = "";
         using (RedisHashService service = new RedisHashService())
         {
             //hostid = service.Get(body.deviceId);//获取缓存中与音响绑定的主机
             hostid = service.GetValueFromHash("Sound_Host", body.deviceId);
             //缓存中不存在再查数据库
             if (!string.IsNullOrEmpty(hostid))
             {
                 //hostid = hostid.Replace("\"", "");
                 SendStr(body, hostid);
             }
             else
             {
                 //根据设备id获取主机ID
                 using (HsfDBContext hsfDBContext = new HsfDBContext())
                 {
                     //根据音响devmac找对应的主机userid,向主机发送消息
                     var soundhostEntity = hsfDBContext.sound_host.Where(t => t.devmac == body.deviceId && t.deletemark == 0).FirstOrDefault();
                     if (soundhostEntity != null)
                     {
                         if (!string.IsNullOrEmpty(soundhostEntity.userid))
                         {
                             hostid = soundhostEntity.userid;
                             //service.Set<string>(body.deviceId, hostid);//缓存主机与音响的绑定关系
                             service.SetEntryInHash("Sound_Host", body.deviceId, hostid);//缓存主机与音响的绑定关系,重复绑定覆盖
                             SendStr(body, hostid);
                         }
                         else
                         {
                             log.Info($"音响{body.deviceId},对应的主机为空字符");
                             return(null);
                         }
                     }
                     else
                     {
                         log.Info($"未到找音响{body.deviceId},对应的主机");
                         return(null);
                     }
                 }
             }
         }
     }
     catch (Exception ex)
     {
         log.Info($"SmartHomeNlp SendMsg 异常:{ex.Message}");
     };
     return(null);
 }
Example #15
0
        /// <summary>
        /// 绑定新的主机
        /// </summary>
        /// <param name="hsfDBContext"></param>
        /// <param name="_SoundHost"></param>
        public static void BindNewHost(HsfDBContext hsfDBContext, SoundHost _SoundHost)
        {
            sound_host sound_Host = GetNewSoundHost(_SoundHost);

            hsfDBContext.sound_host.Add(sound_Host);
            hsfDBContext.SaveChanges();
            using (RedisHashService service = new RedisHashService())
            {
                //service.Set<string>(_SoundHost.devmac, _SoundHost.userid);//缓存主机与音响的绑定关系
                service.SetEntryInHash("Sound_Host", _SoundHost.devmac, _SoundHost.userid);//缓存主机与音响的绑定关系,重复绑定覆盖
            }
        }
 /// <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;
     }
 }
        /// <summary>
        /// 新增业主数据库操作
        /// </summary>
        /// <param name="hsfDBContext"></param>
        /// <param name="_SoundHost"></param>
        public static void AddReg(HsfDBContext hsfDBContext, RedisHashService service, hsf_owner owner)
        {
            owner.Id         = Guid.NewGuid().ToString();
            owner.host       = owner.residential + "-" + owner.building + "-" + owner.unit + "-" + owner.floor + "-" + owner.room;
            owner.createtime = DateTime.Now;
            owner.deletemark = 0;
            hsfDBContext.hsf_owner.Add(owner);
            hsfDBContext.SaveChanges();

            //缓存业主json
            service.SetEntryInHash("Owner", owner.telphone, JsonConvert.SerializeObject(owner));
            //缓存账号密码
            service.SetEntryInHash("Login", owner.telphone, owner.password);
        }
 /// <summary>
 /// 1.请求主机房间列表
 /// user:DAJCHSF_Server type:other msg:DAJCHSF_2047DABEF936;8;835;admin$/r$
 /// 2.主机返回房间列表
 /// user:DAJCHSF_2047DABEF936 type:other msg:DAJCHSF_2047DABEF936;835;admin;Zip;H4sIAAAAAAAAAIuuViotTi3KTFGyUlLSUSouSSxJBTJLikpTgdzkjMy8xLzEXJDQs46Jz2e1PF23DSiemZyfB9GQmZuYngrTXZBfDGYaQNgFiUWJSlbVSimpZSX5JYk5QBlDS5AliWmpxaklJZl56TCrasEaSioLUqHa40EGGego+aWWB6Um5xcBeSCFtTrY3Yvm1qfrFj3ta8Xh0KL8/FxDJNcaGhgbmpoYG1iam5iiOJzajupd/nTdEtIcBcRmBjR1VNe8p61rSHaXkampBW0Da13nyxmbSHOUsYmBkTl5jooFAHQFerEIAwAA$/r$
 /// </summary>
 /// <param name="msg">user:DAJCHSF_Server type:other msg:DAJCHSF_2047DABEF936;8;835;admin$/r$</param>
 public static string Host835(string msg)
 {
     try
     {
         if (msg.Split(';').Length >= 3)
         {
             string appUser = msg.Split(';')[0];
             if (appUser.Contains("_"))
             {
                 string           account      = appUser.Split('_')[0];//DAJCHSF,一个家庭可能有多个用户,mac不同,只取账户
                 List <host_room> roomList     = null;
                 string           roomListJson = "";
                 string           msgResult    = "";
                 using (RedisHashService service = new RedisHashService())
                 {
                     //获取当前房间的设备列表,先找缓存
                     roomListJson = service.GetValueFromHash("Room", account);
                     if (string.IsNullOrEmpty(roomListJson))
                     {
                         using (HsfDBContext hsfDBContext = new HsfDBContext())
                         {
                             roomList     = hsfDBContext.host_room.Where(t => t.Account == account && t.DeleteMark == 0).ToList();
                             roomListJson = JsonConvert.SerializeObject(roomList);
                             //缓存当前账户房间列表返回字符串
                             service.SetEntryInHash("Room", account, JsonConvert.SerializeObject(roomList));
                         }
                     }
                     msgResult = $"{appUser};835;admin;Zip;{EncryptionHelp.Encryption(roomListJson, true)}$/r$";//带上用户信息
                     log.Debug($"835 OK,返回房间列表成功!返回信息:{msgResult}");
                     return(msgResult);
                 }
             }
             else
             {
                 log.Debug($"835 Fail,命令不符合规范!");
                 return(null);
             }
         }
         else
         {
             log.Debug($"835 Fail,命令不符合规范!");
             return(null);
         }
     }
     catch (Exception)
     {
         throw;
     }
 }
Example #19
0
        /// <summary>
        ///清除session
        /// </summary>
        /// <returns></returns>
        public static bool Destroy()
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[CookieName];

            if (cookie != null)
            {
                cookie.Expires = DateTime.Now.AddDays(-1);
                HttpContext.Current.Response.Cookies.Set(cookie);
                using (var service = new RedisHashService())
                {
                    service.Remove(RedisKey);
                }
            }
            return(false);
        }
Example #20
0
 public object this[string name]
 {
     get
     {
         using (var service = new RedisHashService())
         {
             return(service.Get <object>(RedisKey, name));
         }
     }
     set
     {
         using (var service = new RedisHashService())
         {
             service.Set(RedisKey, name, value.ToString());
             service.ExpireEntryAt(RedisKey, DateTime.Now.AddMinutes(SessionTimeOut));
         }
     }
 }
 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}");
             }
         }
     }
 }
Example #22
0
        /// <summary>
        /// 收到Lot设备同步订阅
        /// </summary>
        public static void GetLotDeviceChangeQueue()
        {
            Task.Run(() =>
            {
                ToolHelper.FunctionHelper.writeLog("主动上报设备改变", "启动线程……", "LotDeviceChangeQueue");
                try
                {
                    using (RedisListService service = new RedisListService())
                    {
                        service.Subscribe("LotDeviceChangeQueue", (c, Account, iRedisSubscription) =>
                        {
                            //ToolHelper.FunctionHelper.writeLog("设备同步订阅", Account, "LotDeviceChangeQueue");
                            using (RedisHashService serviceHash = new RedisHashService())
                            {
                                //获取openUid
                                string openUid = serviceHash.GetValueFromHash("DuerOSOpenUid_Host", Account);
                                if (!string.IsNullOrEmpty(openUid))
                                {
                                    var tempPostModel = new DuerOSSyncDevice()
                                    {
                                        botId    = DuerOSSyncBotId,
                                        logId    = FunctionHelper.GetTimStamp() + Account,
                                        openUids = new List <string> {
                                            openUid
                                        }
                                    };

                                    var tempRes = ToolHelper.FunctionHelper.PostJsonString(DuerOSSyncUrl, JsonConvert.SerializeObject(tempPostModel));//{"status":21093,"msg":"Appliance specificed not exist, stop sync","messageId":"1557135094549","data":{"updated_attribute_num":0}}
                                    //{"status":0,"msg":"ok","logid":"1557387335989AAA","data":{"discover":"succeed","failed":[],"succeed":["ee65663a03e810214acc0ac1c18260e7"]}}
                                    ToolHelper.FunctionHelper.writeLog("主动上报设备改变: " + Account, tempRes, "LotDeviceChangeQueue");
                                    Thread.Sleep(100);
                                }
                            }
                        });
                    }
                }
                catch (Exception ex)
                {
                    FunctionHelper.writeLog("设备同步订阅异常", ex.Message, "LotDeviceChangeQueue");
                    throw;
                }
            });
        }
Example #23
0
        /// <summary>
        /// 8145关闭设备 8;8135;设备id
        /// user:123_DCD9165057AD type:other msg:123_DCD9165057AD;8;8145;01120925117040;3,0$/r$
        /// 8135打开设备 8;8135;设备id
        /// user:123_DCD9165057AD type:other msg:123_DCD9165057AD;8;8135;01120925117040;2;8$/r$
        /// user:123_Server type:other msg:123_e0ddc0a405d9;8;8135;A$/r$
        /// {"code":1002,"id":"010000124b0014c6aaee","ep":1,"serial":1,"control":{"on":true},"result":0,"zigbee":"00ff2c2c2c6a6f005979"}
        /// user:DAJCHSF_% type:other msg:DAJCHSF_Server;devrefresh;1041656180510,true,DAJCHSF_2047DABEF936$/r$
        ///
        /// user:MMSJ-1#1-5-501 type:other msg:MMSJ-1-1-5-501;8;8145;08$/r$
        ///
        /// </summary>
        /// <param name="state"></param>
        /// <param name="cachekey"></param>
        public static bool DeviceStateChange(string cachekey, bool state)//, string code, bool state, string success, out string relayUser
        {
            try
            {
                using (RedisHashService service = new RedisHashService())
                {
                    string      deviceEntityStr = service.GetValueFromHash("DeviceMacEntity", cachekey);//8231有关联,改mac的情况下,其它改状态,改名称,不需要清理
                    host_device deviceEntity    = null;
                    if (!string.IsNullOrEmpty(deviceEntityStr))
                    {
                        deviceEntity = JsonConvert.DeserializeObject <host_device>(deviceEntityStr);//设备实体缓存
                    }
                    else
                    {
                        using (HsfDBContext hsfDBContext = new HsfDBContext())
                        {
                            deviceEntity = hsfDBContext.host_device.Where(t => t.cachekey == cachekey && t.deletemark == 0).FirstOrDefault();//注意device的唯一性
                            if (deviceEntity != null)
                            {
                                //缓存设备id与设备实体对应关系,避免查询数据库
                                service.SetEntryInHash("DeviceMacEntity", cachekey, JsonConvert.SerializeObject(deviceEntity));
                            }
                        }
                    }

                    if (deviceEntity != null)
                    {
                        //拼装1002指令,发送给网关,执行改变状态操作
                        return(StateChangeByType(deviceEntity, state));
                    }
                    else
                    {
                        //relayUser = appUser;
                        return(false);//error
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
Example #24
0
        public static string GetHostId(string deviceId)
        {
            string hostid = "";

            using (RedisHashService service = new RedisHashService())
            {
                //hostid = service.Get(body.deviceId);//获取缓存中与音响绑定的主机
                hostid = service.GetValueFromHash("Sound_Host", deviceId);
                //缓存中不存在再查数据库
                if (!string.IsNullOrEmpty(hostid))
                {
                    return(hostid);
                }
                else
                {
                    //根据设备id获取主机ID
                    using (HsfDBContext hsfDBContext = new HsfDBContext())
                    {
                        //根据音响devmac找对应的主机userid,向主机发送消息
                        var soundhostEntity = hsfDBContext.sound_host.Where(t => t.devmac == deviceId && t.deletemark == 0).FirstOrDefault();
                        if (soundhostEntity != null)
                        {
                            if (!string.IsNullOrEmpty(soundhostEntity.userid))
                            {
                                hostid = soundhostEntity.userid;
                                //service.Set<string>(body.deviceId, hostid);//缓存主机与音响的绑定关系
                                service.SetEntryInHash("Sound_Host", deviceId, hostid);//缓存主机与音响的绑定关系,重复绑定覆盖
                                return(hostid);
                            }
                            else
                            {
                                return(null);
                            }
                        }
                        else
                        {
                            return(null);
                        }
                    }
                }
            }
        }
        /// <summary>
        /// user:MMSJ-1#1-5-501 type:other msg:MMSJ-1-1-5-501;8;8133;08$/r$
        /// connect user:MMSJ-1-1-30-3001_C40BCB80050A type:other msg:MMSJ-1-1-30-3001_C40BCB80050A;8;8133;08$/r$
        /// </summary>
        /// <param name="msg"></param>
        public static bool OutDeviceStateChange(string appUser, string deviceId)
        {
            try
            {
                bool state = true;//室外设备全是打开
                using (RedisHashService service = new RedisHashService())
                {
                    string        deviceEntityStr = service.GetValueFromHash("OutDeviceEntity", deviceId);//8231有关联,改mac的情况下,其它改状态,改名称,不需要清理
                    hsf_outdevice deviceEntity    = null;
                    if (!string.IsNullOrEmpty(deviceEntityStr))
                    {
                        deviceEntity = JsonConvert.DeserializeObject <hsf_outdevice>(deviceEntityStr);//设备实体缓存
                    }
                    else
                    {
                        using (HsfDBContext hsfDBContext = new HsfDBContext())
                        {
                            deviceEntity = hsfDBContext.hsf_outdevice.Where(t => t.deviceid == deviceId && t.deletemark == 0).FirstOrDefault();//注意device的唯一性
                            if (deviceEntity != null)
                            {
                                //缓存设备id与设备实体对应关系,避免查询数据库
                                service.SetEntryInHash("OutDeviceEntity", deviceId, JsonConvert.SerializeObject(deviceEntity));
                            }
                        }
                    }

                    if (deviceEntity != null)
                    {
                        //拼装1002指令,发送给网关,执行改变状态操作
                        return(ChangeStateMain.OutStateChangeByType(appUser, deviceEntity, state));
                    }
                    else
                    {
                        return(false);//error
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
Example #26
0
        /// <summary>
        /// 根据Id查找用户信息/登录
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public T_Sys_User GetUserInfoById(long id)
        {
            T_Sys_User userInfo;
            using (RedisHashService service = new RedisHashService())
            {
                userInfo = service.GetFromHash<T_Sys_User>(id);
                if (userInfo?.Id == id)
                    return userInfo;
            }
            userInfo = Db.Select<T_Sys_User>().Where(i => i.Id == id).ToList().FirstOrDefault();
            //查出来再存到缓存中
            if (userInfo?.Id == id)
            {
                using (RedisHashService service = new RedisHashService())
                {
                    service.StoreAsHash(userInfo);
                }
            }

            return userInfo;
        }
Example #27
0
        public static void PutMqttData(RedisHashService service, string cachekey, string state)
        {
            //如果状态已经是当前要操作的状态
            string state0 = service.GetValueFromHash("DeviceStatus", cachekey);

            //不一致的状态再去修改
            if (state0 != state)
            {
                service.SetEntryInHash("DeviceStatus", cachekey, state);
                string openUid = service.GetValueFromHash("DuerOSOpenUid_Device", cachekey);
                //存在百度音响openUid的同步到百度音响平台
                if (!string.IsNullOrEmpty(openUid))
                {
                    using (RedisListService service2 = new RedisListService())
                    {
                        service2.Publish("YunZigStateChangeQueue", cachekey);
                        log.Debug($"《《《《《《《《《《《《《《《《发布YunZigStateChangeQueue状态同步消息 {cachekey}");
                    }
                }
            }
        }
Example #28
0
        /// <summary>
        /// 获取缓存状态
        /// </summary>
        /// <param name="service"></param>
        /// <param name="cachekey"></param>
        /// <returns></returns>
        public AttributesItem GetStateByCachekey(RedisHashService service, string cachekey)
        {
            string devstate = "";

            if (!string.IsNullOrEmpty(cachekey))
            {
                //读取缓存状态
                string status = service.GetValueFromHash("DeviceStatus", cachekey);
                if (string.IsNullOrEmpty(status))
                {
                    //离线
                    devstate = "false";
                }
                else
                {
                    devstate = status.ToLower();
                }
            }

            return(GetAttributesItem(devstate));
        }
        /// <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;
            }
        }
 /// <summary>
 /// 确认器,读取缓存状态,半秒读取一次,共读取3秒左右,没反应就返回失败
 /// </summary>
 /// <param name="cachekey"></param>
 /// <param name="ok"></param>
 /// <returns></returns>
 public static bool StateResult(string cachekey, string st)
 {
     using (RedisHashService service = new RedisHashService())
     {
         bool state = false;
         int  i     = 0;
         while (i < 30)//6s,次数限制redis
         {
             i++;
             Thread.Sleep(200);
             //读取缓存状态
             string status = service.GetValueFromHash("DeviceStatus", cachekey);
             if (status == st)
             {
                 log.Debug($"设备状态改变成功! cachekey:{cachekey}!轮询次数: {i}");
                 state = true;
                 break;
             }
         }
         return(state);
     }
 }