Exemple #1
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();
        }
        /// <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!");
                        }
                    }
                }
            }
        }
Exemple #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);
            }
        }
        /// <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);
        }
Exemple #5
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;
            }
        }
Exemple #7
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);//缓存主机与音响的绑定关系,重复绑定覆盖
            }
        }
Exemple #8
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);
 }
        /// <summary>
        /// 根据房间获取房间内设备列表
        /// </summary>
        /// <param name="service"></param>
        /// <param name="hostId"></param>
        /// <param name="posid"></param>
        /// <returns></returns>
        public List <host_device> GetDeviceListByRoom(RedisHashService service, string hostId, string posid)
        {
            List <host_device> roomDeviceList = null;
            //获取当前区域的设备列表
            string roomDeviceListJson = service.GetValueFromHash("RoomDevices", hostId + "|" + posid);

            if (!string.IsNullOrEmpty(roomDeviceListJson))
            {
                roomDeviceList = JsonConvert.DeserializeObject <List <host_device> >(roomDeviceListJson);
            }
            else
            {
                if (posid != "0")
                {
                    using (HsfDBContext hsfDBContext = new HsfDBContext())
                    {
                        //默认房间为0,查询当前账号所有设备列表
                        roomDeviceList = hsfDBContext.host_device.Where(t => t.account == hostId && t.devposition == posid && t.deletemark == 0).OrderBy(t => t.createtime).ToList();

                        //缓存当前房间的设备列表,不包括状态,不管空与否都缓存,防止第二次还查数据库RoomDevices
                        service.SetEntryInHash("RoomDevices", hostId + "|" + posid, JsonConvert.SerializeObject(roomDeviceList));
                    }
                }
                else
                {
                    using (HsfDBContext hsfDBContext = new HsfDBContext())
                    {
                        //默认房间为0,查询当前账号所有设备列表
                        roomDeviceList = hsfDBContext.host_device.Where(t => t.account == hostId && t.deletemark == 0).OrderBy(t => t.createtime).ToList();

                        //缓存当前房间的设备列表,不包括状态,不管空与否都缓存,防止第二次还查数据库RoomDevices
                        service.SetEntryInHash("RoomDevices", hostId + "|0", JsonConvert.SerializeObject(roomDeviceList));
                    }
                }
            }
            return(roomDeviceList);
        }
 /// <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;
     }
 }
        /// <summary>
        /// 重置密码
        /// </summary>
        /// <param name="account"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static string Password(string account, string password)
        {
            hsf_owner ownerEntity = null;

            using (HsfDBContext hsfDBContext = new HsfDBContext())
            {
                using (RedisHashService service = new RedisHashService())
                {
                    ownerEntity = hsfDBContext.hsf_owner.Where(t => t.telphone == account && t.deletemark == 0).FirstOrDefault();
                    if (ownerEntity != null)
                    {
                        ownerEntity.password = password;
                        hsfDBContext.SaveChanges();
                        service.SetEntryInHash("Login", account, password);
                        service.SetEntryInHash("Owner", ownerEntity.telphone, JsonConvert.SerializeObject(ownerEntity));
                        return("password ok");
                    }
                    else
                    {
                        return("error:No account exists!");
                    }
                }
            }
        }
        /// <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;
            }
        }
        /// <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;
            }
        }
Exemple #14
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);
                        }
                    }
                }
            }
        }
Exemple #15
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}");
                    }
                }
            }
        }
Exemple #16
0
        private void MyServer_NewRequestReceived(HansAppSession session, HansRequestInfo requestInfo)
        {
            string msg = requestInfo.Body.StartMark + requestInfo.Body.BodyString + requestInfo.Body.EndMark;//encoding.GetString(requestInfo.Body.BodyBuffer);

            if (msg.Contains("101,"))
            {
                //心跳
                TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
                session.Send("{\"code\":1001,\"result\":0,\"timestamp\": " + Convert.ToInt64(ts.TotalSeconds) + "}");
            }
            else if (msg.Contains("104,"))
            {
                //状态
                dynamic result = JsonConvert.DeserializeObject <dynamic>(msg);//反序列化
                //缓存设备状态
                using (RedisHashService service = new RedisHashService())
                {
                    service.SetEntryInHash("104", result.id.Value, result.st.on.Value.ToString());
                }
            }
                        log.Debug(msg);
        }
Exemple #17
0
        /// <summary>
        /// 获得当前房间的设备列表的命令8;815;+ posid
        /// </summary>
        /// <param name="msg">user:123_Server type:other msg:
        /// 123_DCD9165057AD;8;815;1225155025360$/r$</param>
        public static string Host815(string msg)
        {
            try
            {
                if (msg.Split(';').Length >= 3)
                {
                    string             appUser    = msg.Split(';')[0];
                    string             posid      = msg.Split(';')[3].Replace("$/r$", "");//房间id  ,默认id为0,
                    List <host_device> deviceList = null;
                    //获取当前房间的设备列表,先找缓存
                    using (RedisHashService service = new RedisHashService())
                    {
                        string deviceListJson = service.GetValueFromHash("RoomDevices", appUser + "|" + posid);
                        if (!string.IsNullOrEmpty(deviceListJson))
                        {
                            deviceList = JsonConvert.DeserializeObject <List <host_device> >(deviceListJson);
                        }
                        //如果缓存中没有,再查数据库
                        else
                        {
                            using (HsfDBContext hsfDBContext = new HsfDBContext())
                            {
                                deviceList = hsfDBContext.host_device.Where(t => t.devposition == posid && t.deletemark == 0).ToList();
                                //缓存当前房间的设备列表,不包括状态,不管空与否都缓存,防止第二次还查数据库
                                service.SetEntryInHash("RoomDevices", appUser + "|" + posid, JsonConvert.SerializeObject(deviceList));//解决默认posid都为0的问题
                            }
                        }

                        //真正更新设备状态
                        string zipStr = "";
                        foreach (var item in deviceList)
                        {
                            //读取缓存状态
                            string status = service.GetValueFromHash("DeviceStatus", item.cachekey);
                            if (string.IsNullOrEmpty(status))
                            {
                                //离线
                                item.powvalue = "离线";
                                item.devstate = "false";
                            }
                            else
                            {
                                item.powvalue = "在线";
                                item.devstate = status;
                            }
                        }
                        zipStr = EncryptionHelp.Encryption(JsonConvert.SerializeObject(deviceList), true);
                        string msgResult = $"{appUser};815;{posid};Zip;{zipStr}$/r$\r\n";//拼接
                        log.Info($"815 OK,返回房间设备列表成功!返回信息:{msgResult}");
                        return(msgResult);
                    }
                }
                else
                {
                    log.Error($"815 Fail,命令不符合规范!");
                    return(null);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        /// <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;
            }
        }
Exemple #19
0
        public static void AIFunction(SoundBodyRequest body)
        {
            //百度分词
            BaiduNlp nlpEntity = BaiduSDK.Nlp(body.questions);

            //添加句子表,分词表
            string talkDevice   = "Talk_" + body.deviceId;              //每个音响创建一个会话
            long   newTimestamp = DataHelper.GetTimeSpan(DateTime.Now); //句子时间戳
            string newTitleid   = nlpEntity.log_id.ToString();          //句子id
            string _Talkid      = "";
            string userid       = RedisHelper.GetHostId(body.deviceId); //音响对应用户

            body.timestamp   = newTimestamp;                            //	时间标签(Long型)
            body.baidu_Items = nlpEntity.items;                         //	分词列表(字符串数组)

            string field = AIControler.Getdomain(body);                 //获取领域

            body.field = field;                                         //领域
            int    sort       = 1;                                      //会话中句子的顺序
            string preTitleid = "";                                     //上一个句子id

            string questions = "";                                      //问题列表:(字符串数组) 音箱的会话记录
            string answers   = "";                                      //回答列表:(字符串数组)  AIcontrol会话记录

            //创建会话缓存
            using (RedisHashService service = new RedisHashService())
            {
                string _timestampStr = service.GetValueFromHash(talkDevice, "timestamp");//获取缓存时间戳
                if (!string.IsNullOrEmpty(_timestampStr))
                {
                    long oldTimestamp = Convert.ToInt64(_timestampStr);
                    long cha          = newTimestamp - oldTimestamp;
                    if (cha > 60)                                                                     //一分钟60秒
                    {
                        _Talkid = body.deviceId + "_" + DateTime.Now.ToString("yyyyMMdd-HHmmss-fff"); //超过一分钟,创建新的会话缓存
                        service.SetEntryInHash(talkDevice, "talkid", _Talkid);                        //缓存会话id
                    }
                    //一分钟内继续使用,不更新
                    else
                    {
                        _Talkid = service.GetValueFromHash(talkDevice, "talkid");
                        string sortStr = service.GetValueFromHash(talkDevice, "sort");//先获取当前顺序
                        if (!string.IsNullOrEmpty(sortStr))
                        {
                            sort = Convert.ToInt32(sortStr);
                        }
                        sort++;//一分钟内顺序+1
                    }
                }
                else
                {
                    _Talkid = body.deviceId + "_" + DateTime.Now.ToString("yyyyMMdd-HHmmss-fff"); //没有新建
                    service.SetEntryInHash(talkDevice, "talkid", _Talkid);                        //缓存会话id
                }
                preTitleid = service.GetValueFromHash(talkDevice, "titleid");                     //前个句子id
                //每次都更新句子时间戳
                service.SetEntryInHash(talkDevice, "titleid", newTitleid);                        //缓存新的句子id
                service.SetEntryInHash(talkDevice, "timestamp", newTimestamp.ToString());         //缓存新的时间戳
                service.SetEntryInHash(talkDevice, "field", field);                               //新的领域
                service.SetEntryInHash(talkDevice, "sort", sort.ToString());                      //顺序


                string talkstate = service.GetValueFromHash(talkDevice, "state"); //获取缓存会话模式,提前赋值
                body.talkstate = talkstate;                                       //会话模式
                talkstate      = "inquiry";
                if (talkstate == "inquiry" || talkstate == "await")               //询问,等待
                {
                    Task.Run(() =>
                    {
                        //不用请求任何Nlu服务器,直接丢给AIControl函数Setanswer处理,返回抛给音箱
                        AIControler.Setanswer(body);
                    });
                }
                //else if(_state== "train")//训练模式
                else
                {
                    Task.Run(() =>
                    {
                        //发送收到的语音到NLP管理器
                        NlpControler.ProcessingRequest(body);
                    });
                }

                //启动线程存数据库
                Task.Run(() =>
                {
                    using (HsfDBContext hsfDBContext = new HsfDBContext())
                    {
                        //句子表
                        sound_title sound_Title = new sound_title()
                        {
                            titleid   = newTitleid,
                            titletext = body.questions,
                            timestamp = newTimestamp,
                            preid     = preTitleid,
                            sort      = sort,
                            talkid    = _Talkid,
                            sender    = body.deviceId,
                            userid    = userid,
                            sendtype  = body.sourceId,
                            field     = field,
                            talkstate = talkstate
                        };
                        hsfDBContext.sound_title.Add(sound_Title);

                        int items_sort = 0;
                        //分词表
                        foreach (var item in nlpEntity.items)
                        {
                            items_sort++;
                            baidu_items baidu_Items = new baidu_items()
                            {
                                wordid      = Guid.NewGuid().ToString(),
                                titleid     = newTitleid,
                                byte_length = item.byte_length,
                                byte_offset = item.byte_offset,
                                uri         = item.uri,
                                pos         = item.pos,
                                ne          = item.ne,
                                item        = item.item,
                                basic_words = string.Join(",", item.basic_words),
                                formal      = item.formal,
                                sort        = items_sort,
                                timestamp   = newTimestamp
                            };
                            hsfDBContext.baidu_items.Add(baidu_Items);
                        }
                        hsfDBContext.SaveChanges();
                    }
                    log.Info($"保存到句子表和分词表");
                });
            }
        }
Exemple #20
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>
        /// 服务器端不停的接收客户端发来的消息
        /// </summary>
        /// <param name="o"></param>
        public void Received(object o)
        {
            try
            {
                Socket socketSend = o as Socket;
                string ip         = ((IPEndPoint)socketSend.RemoteEndPoint).Address.ToString();
                while (true)
                {
                    //客户端连接服务器成功后,服务器接收客户端发送的消息
                    byte[] buffer = new byte[1024 * 1024 * 2];//
                    //实际接收到的有效字节数
                    int len = socketSend.Receive(buffer);
                    if (len == 0)
                    {
                        break;
                    }
                    //204为ccdd开头的cc
                    //99为从汉字转换到16进制ToHex》16进制字节strToToHexByte》
                    //《字节转16进制X2,《16进制字符串转字符串UnHex
                    if (buffer[0] == 204 || buffer[0] == 99 || buffer[0] == 227 || buffer[0] == 236)
                    {
                        string strData = string.Empty;
                        for (int i = 0; i < len; i++)
                        {
                            strData += buffer[i].ToString("X2") + " "; //十六进制
                        }
                        log.Debug(socketSend.RemoteEndPoint + "收到消息<<<<<<<<<:" + strData);
                        //Console.WriteLine(socketSend.RemoteEndPoint + "收到消息<<<<<<<<<:" + strData);

                        //string dd = buffer[0].ToString();
                        //log.Debug($"字节1为:{dd}, 转字符串长度:{strData.Length}");

                        if (strData.Length == 33 && strData.Substring(12, 2) == "05")
                        {
                            using (RedisHashService service = new RedisHashService())
                            {
                                //命令开关
                                //CC DD F1 06 05 00 08 01 01 8D EF
                                //cc dd 开头固定
                                //f1 第一个485通道
                                //06 物理地址
                                //05 00 08
                                //00 继电器
                                //01 为打开继电器
                                //8D C8 为crc校验码
                                bool   st    = strData.Substring(24, 2) == "01" ? true : false;
                                string ff    = strData.Substring(6, 2);
                                string mac   = strData.Substring(9, 2);
                                string port  = strData.Substring(21, 2);
                                int    iport = int.Parse(port) + 1;
                                string key   = ip + ";" + ff + ";" + mac + "_0;" + iport;   //58.57.32.162;F1;06_0;3
                                service.SetEntryInHash("DeviceStatus", key, st.ToString()); //解决默认posid都为0的问题
                                log.Debug($"状态改变:{key}:{st.ToString()}");
                            }
                        }
                        else if (strData.Length == 39 && strData.Substring(12, 2) == "20")
                        {
                            //39:手动操作开关为一组,
                            //cc dd f1 06 20 10 11 00 01 00 00 4e b0 cc dd f1 06 20 10 11 00 01 00 7f 0f 50
                            //cc dd f1 01 20 10 13 00 01 00 00 76 96 cc dd f1 01 20 10 13 00 01 00 7f 37 76
                            using (RedisStringService service = new RedisStringService())
                            {
                                Gateway_SessionDic.AddOrUpdate(ip, socketSend, (Func <string, Socket, Socket>)((key, oldValue) => socketSend));
                                service.Set("BusSwitch_" + ip, strData.Substring(9, 2), new TimeSpan(0, 0, 0, 120));//缓存2分钟
                                log.Debug($"缓存mac:BusSwitch_{ip}:{strData.Substring(9, 2)}");

                                //第七位为继电器编号左侧1,11(比指令00+11),第11位为状态(ff开,f7关)
                                //第一个开
                                //cc dd f1 05 20 10 11 00 01 00 80 0f 05
                                //cc dd f1 05 20 10 11 00 01 00 ff 4e e5
                                //中间关
                                //cc dd f1 05 20 10 12 00 01 00 00 4a a5
                                //cc dd f1 05 20 10 12 00 01 00 7f 0b 45
                            }
                        }
                        else if (strData.Length == 24)
                        {
                            //修改mac地址CC DD F1 01 06 00 02 01 03 69 9B
                            //第一种24
                            //cc dd f1 01 06 00 (01->02)
                            //cc dd f1 02 02 01 e8 aa (第二行的第四位02)
                            //CC DD F1 02 06 00 (02->04)
                            //CC DD F1 02 04 01 EB 39 (第二行的第四位04)
                            //cc dd f1 02 06 00 (02->03)
                            //cc dd f1 02 03 01 e9 09
                            //cc dd f1 03 06 00 (03->02)
                            //cc dd f1 02 02 01 e9 48
                            //cc dd f1 02 06 00 (02->01)
                            //cc dd f1 02 01 01 e8 69
                            using (RedisStringService service = new RedisStringService())
                            {
                                Gateway_SessionDic.AddOrUpdate(ip, socketSend, (Func <string, Socket, Socket>)((key, oldValue) => socketSend));
                                service.Set("BusSwitch_" + ip, strData.Substring(12, 2), new TimeSpan(0, 0, 0, 120));//缓存2分钟
                                log.Debug($"BusSwitch_{ip} 修改为新的mac: {strData.Substring(12, 2)}");
                            }
                        }
                        else if (strData.Length == 21)
                        {
                            //修改mac地址成功
                            //CC DD F1 01 06 00 02 01 03 69 9B
                            //cc dd f1 01 06 00 02 01 01 e8 5a
                            //CC DD F1 01 06 00 02 01 01 E8 5A
                            //第二种* 21
                            //CC DD F1 02 06 00 02 (02->01)
                            //CC DD F1 01 01 E8 69
                            //CC DD F1 04 06 00 02
                            //CC DD F1 05 01 EA CF
                            //cc dd F1 03 06 00 02 01 04 29 bb(03->04)
                            //CC DD F1 03 06 00 02
                            //CC DD F1 04 01 EA E8
                            //第三种33
                            //cc dd f1 01 06 00 02 02 01 e8 aa (未处于配置状态)
                            using (RedisStringService service = new RedisStringService())
                            {
                                Gateway_SessionDic.AddOrUpdate(ip, socketSend, (Func <string, Socket, Socket>)((key, oldValue) => socketSend));
                                service.Set("BusSwitch_" + ip, strData.Substring(9, 2), new TimeSpan(0, 0, 0, 120));//缓存2分钟
                                log.Debug($"BusSwitch_{ip} 修改为新的mac: {strData.Substring(9, 2)}");
                            }
                        }
                        else if (strData.Contains("7C") && strData.Contains("3B"))//|;
                        {
                            //35 38 2E 35 37 2E 33 32 2E 31 36 32 3B 46 31 3B 30 35 7C 63 63 20 64 64 20 30 31 20 30 36 20 30 30 20 30 32 20 30 31 20 30 35 20 65 39 20 39 39
                            //63 63 20 64 64 20
                            //cc dd f1 06 05 00 08 00 01 8c 7f|192.168.82.107;f1;06
                            //cc dd f1 01 06 00 02 01 05 e9 99|58.57.32.162;F1;05
                            //cc dd f1 01 06 00 02 01 05 e9 99|192.168.82.107;f1;06
                            string strDataStr = UnHex(strData, "utf-8");
                            log.Debug($"收到请求: {strDataStr}");

                            string ipmac = strDataStr.Split('|')[1].ToString();
                            string wwip  = ipmac.Split(';')[0].ToString();
                            string msg   = strDataStr.Split('|')[0].ToString();
                            //1.开关开关指令,需要三个参数,开关物理地址+继电器地址+开关值+crc校验
                            //01 05 00 08 00 01 8D C8
                            //第一位 01 为开关物理地址
                            //第五位 00(00为第一个继电器,01为第二个继电器,02为第三个继电器)
                            //第六位 01 为打开继电器,00为关闭继电器
                            //第七八位 为crc校验码,百度查找c# 的crc校验函数

                            //2.发送配置物理地址指令
                            //01 06 00 02 01 03 69 9B
                            //第六位 03 为开关新的物理地址,第七八位 为crc校验码
                            //新的固件第一位01固定,老的固件第一位为原mac地址

                            if (Gateway_SessionDic.ContainsKey(wwip))
                            {
                                byte[] bytes = strToToHexByte(msg);
                                Gateway_SessionDic[wwip].Send(bytes);
                                log.Debug($"给控制器{wwip}发送指令:{msg}");
                            }
                            else
                            {
                                log.Debug($"请求网关的session不存在 {ipmac}: {msg}");
                            }
                        }
                        else if (strData.Length == 66)
                        {
                            string mac = strData.Substring(6, 2);
                            string fl  = strData.Substring(15, 2);

                            byte[] bytes = strToToHexByte(strData);
                            //Gateway_SessionDic[fl].Send(bytes);
                            log.Debug($"给控制器{fl}发送指令:{strData}");


                            //if (Gateway_SessionDic.ContainsKey(fl))
                            //{
                            //    byte[] bytes = strToToHexByte(strData);
                            //    Gateway_SessionDic[fl].Send(bytes);
                            //    log.Debug($"给控制器{fl}发送指令:{strData}");
                            //}
                            //else
                            //{
                            //    log.Debug($"请求网关的session不存在 {fl}: {strData}");
                            //}

                            using (RedisHashService service = new RedisHashService())
                            {
                                service.SetEntryInHash("DeviceStatus", mac, "_" + fl);
                                log.Debug($"状态电梯改变:{mac}:{fl}");
                            }
                        }
                        else if (strData.Length == 15)
                        {
                            //确认梯控应答
                            //EC 88 08 01 0D
                            string mac = strData.Substring(6, 2);
                            using (RedisHashService service = new RedisHashService())
                            {
                                string _fl = service.GetValueFromHash("DeviceStatus", mac);
                                string fl  = _fl.Replace("_", "");
                                service.SetEntryInHash("DeviceStatus", mac, fl);
                                log.Debug($"状态电梯改变:{mac}:{fl}");
                            }
                        }
                    }
                }
            }
            catch { }
        }
Exemple #22
0
        public static void Show()
        {
            UserInfo user = new UserInfo()
            {
                Id       = 123,
                Account  = "Administrator",
                Address  = "武汉市",
                Email    = "*****@*****.**",
                Name     = "Eleven",
                Password = "******",
                QQ       = 57265177
            };


            using (RedisStringService service = new RedisStringService())
            {
                //service.Set<string>($"userinfo_{user.Id}", Newtonsoft.Json.JsonConvert.SerializeObject(user));
                service.Set <UserInfo>($"userinfo_{user.Id}", user);
                var userCacheList = service.Get <UserInfo>(new List <string>()
                {
                    $"userinfo_{user.Id}"
                });
                var userCache = userCacheList.FirstOrDefault();
                //string sResult = service.Get($"userinfo_{user.Id}");
                //var userCache = Newtonsoft.Json.JsonConvert.DeserializeObject<UserInfo>(sResult);
                userCache.Account = "Admin";
                service.Set <UserInfo>($"userinfo_{user.Id}", userCache);
            }
            using (RedisHashService service = new RedisHashService())
            {
                service.FlushAll();
                //反射遍历做一下
                service.SetEntryInHash($"userinfo_{user.Id}", "Account", user.Account);
                service.SetEntryInHash($"userinfo_{user.Id}", "Name", user.Name);
                service.SetEntryInHash($"userinfo_{user.Id}", "Address", user.Address);
                service.SetEntryInHash($"userinfo_{user.Id}", "Email", user.Email);
                service.SetEntryInHash($"userinfo_{user.Id}", "Password", user.Password);
                service.SetEntryInHash($"userinfo_{user.Id}", "Account", "Admin");

                service.StoreAsHash <UserInfo>(user);//含ID才可以的
                var result = service.GetFromHash <UserInfo>(user.Id);
            }
            UserInfo user2 = new UserInfo()
            {
                Id       = 234,
                Account  = "Administrator2",
                Address  = "武汉市2",
                Email    = "[email protected]",
                Name     = "Eleven2",
                Password = "******",
                QQ       = 572651772
            };

            using (RedisHashService service = new RedisHashService())
            {
                service.FlushAll();
                //反射遍历做一下
                service.SetEntryInHash($"userinfo_{user2.Id}", "Account", user2.Account);
                service.SetEntryInHash($"userinfo_{user2.Id}", "Name", user2.Name);
                service.SetEntryInHash($"userinfo_{user2.Id}", "Address", user2.Address);
                service.SetEntryInHash($"userinfo_{user2.Id}", "Email", user2.Email);
                service.SetEntryInHash($"userinfo_{user2.Id}", "Remark", "这里是2号用户");

                service.StoreAsHash <UserInfo>(user);//含ID才可以的
                var result = service.GetFromHash <UserInfo>(user.Id);
            }
        }
        /// <summary>
        /// 设备发现方法
        /// </summary>
        /// <param name="commonModel"></param>
        /// <param name="tokenModel"></param>
        /// <returns></returns>
        private object Discove(CommonReceiveModel commonModel, IntelligentHostCacheModel tokenModel)
        {
            //IntelligentHostCacheModel cacheModel = CacheData.GetAccessTokenCache(receiveObj.payload.accessToken);
            //CacheData.SetOpenUid(cacheModel.AccessToken, cacheModel, commonModel.payload.openUid);
            try
            {
                using (RedisHashService service = new RedisHashService())
                {
                    string hostId  = tokenModel.HostId;//账号
                    string openUid = commonModel.payload.openUid;
                    //设置设备与OpenUid的绑定关系
                    service.SetEntryInHash("DuerOSOpenUid_Host", hostId, openUid);
                    //拼装返回消息格式
                    DiscoveReturnModel resModel = new DiscoveReturnModel()
                    {
                        header = new Dueros.Models.CommonModel.Head()
                        {
                            messageId      = commonModel.header.messageId,
                            name           = commonModel.header.name.Replace("Request", "Response"),
                            @namespace     = commonModel.header.@namespace,
                            payloadVersion = commonModel.header.payloadVersion
                        },
                        payload = new DiscoverPayload()
                        {
                            discoveredGroups     = new List <DiscoveredGroup>(),
                            discoveredAppliances = new List <DiscoveredAppliance>()
                        }
                    };

                    //获取当前百度账号的设备列表,先找缓存
                    string discoverPayloadJson = service.GetValueFromHash("DuerOS_DiscoverPayload", hostId);

                    if (!string.IsNullOrEmpty(discoverPayloadJson))
                    {
                        resModel.payload = JsonConvert.DeserializeObject <DiscoverPayload>(discoverPayloadJson);
                    }
                    else
                    {
                        List <host_room>   roomList       = null; //房间区域列表
                        List <host_device> roomDeviceList = null; //区域设备列表

                        //1.找当前账号的房间列表区域
                        string roomListJson = service.GetValueFromHash("Room", hostId);
                        if (!string.IsNullOrEmpty(roomListJson))
                        {
                            roomList = JsonConvert.DeserializeObject <List <host_room> >(roomListJson);
                        }
                        else
                        {
                            using (HsfDBContext hsfDBContext = new HsfDBContext())
                            {
                                //默认房间为0,查询当前账号所有设备列表
                                roomList = hsfDBContext.host_room.Where(t => t.Account == hostId && t.DeleteMark == 0).OrderBy(t => t.CreateTime).ToList();

                                //缓存当前房间的设备列表,不包括状态,不管空与否都缓存,防止第二次还查数据库RoomDevices
                                service.SetEntryInHash("Room", hostId, JsonConvert.SerializeObject(roomList));
                            }
                        }
                        //2.组装区域列表
                        if (roomList.Count > 0)
                        {
                            //房间列表不为空,则拼装区域json
                            foreach (var item in roomList)
                            {
                                //获取当前区域的设备列表
                                roomDeviceList = GetDeviceListByRoom(service, hostId, item.posid);
                                if (roomDeviceList != null)
                                {
                                    List <string> applianceIds = new List <string>();
                                    foreach (var dev in roomDeviceList)
                                    {
                                        applianceIds.Add(dev.cachekey);
                                    }

                                    DiscoveredGroup discoveredGroup = new DiscoveredGroup()
                                    {
                                        groupName              = item.chinaname,
                                        applianceIds           = applianceIds,
                                        groupNotes             = item.chinaname + "分组控制",
                                        additionalGroupDetails = { }
                                    };
                                    resModel.payload.discoveredGroups.Add(discoveredGroup);
                                }
                            }
                        }

                        //调用逻辑获取缓存中0房间所有的设备
                        List <host_device> allDeviceList = GetDeviceListByRoom(service, hostId, "0");
                        foreach (var item in allDeviceList)
                        {
                            //类型对照表
                            List <string> applianceTypes = null;
                            List <string> actions        = null;
                            //根据对照,获取百度的设备类型type,操作action
                            GetDuerOSDveType(item.devtype, out applianceTypes, out actions);

                            //拼装发给百度的设备信息
                            if (applianceTypes != null && actions != null)
                            {
                                DiscoveredAppliance discoveredAppliance = new DiscoveredAppliance()
                                {
                                    applianceTypes             = applianceTypes,
                                    applianceId                = item.cachekey,//不使用id,使用mac+port
                                    modelName                  = item.devtype,
                                    version                    = "1.0",
                                    friendlyName               = item.chinaname,
                                    friendlyDescription        = "",
                                    isReachable                = true,
                                    actions                    = actions,
                                    additionalApplianceDetails = { },
                                    manufacturerName           = "DASKLIMA"
                                };
                                //以对象数组返回客户关联设备云帐户的设备、场景
                                resModel.payload.discoveredAppliances.Add(discoveredAppliance);
                                //设置设备与OpenUid的绑定关系
                                service.SetEntryInHash("DuerOSOpenUid_Device", item.cachekey, openUid);
                            }
                        }
                        //场景处理,后续

                        //缓存百度设备列表payload,不包含状态
                        service.SetEntryInHash("DuerOS_DiscoverPayload", hostId, JsonConvert.SerializeObject(resModel.payload));
                    }

                    //设备状态详情信息,都要执行,因为缓存的DuerOS_DiscoverPayload不存状态
                    foreach (var item in resModel.payload.discoveredAppliances)
                    {
                        List <AttributesItem> attributes = new List <AttributesItem>();
                        //获取当前缓存状态
                        AttributesItem attribute = GetStateByCachekey(service, item.applianceId);
                        attributes.Add(attribute);
                        item.attributes = attributes;
                    }

                    return(resModel);
                }
            }
            catch (Exception ex)
            {
                FunctionHelper.writeLog("GetDevice error:", ex.Message + "   " + ex.StackTrace, "DeviceDiscoverHandleError");
                return(null);
            }
        }
Exemple #24
0
        private void MyServer_NewRequestReceived(HansAppSession session, HansRequestInfo requestInfo)
        {
            Task.Run(() =>
            {
                string msg      = requestInfo.Body.StartMark + requestInfo.Body.BodyString + requestInfo.Body.EndMark;//encoding.GetString(requestInfo.Body.BodyBuffer);
                string[] sArray = Regex.Split(msg, "}{", RegexOptions.IgnoreCase);
                for (int i = 0; i < sArray.Length; i++)
                {
                    if (!sArray[i].StartsWith("{"))
                    {
                        sArray[i] = "{" + sArray[i];
                    }
                    int _left  = Regex.Matches(sArray[i], "{").Count;
                    int _right = Regex.Matches(sArray[i], "}").Count;
                    int cha    = _left - _right;
                    for (int b = 0; b < cha; b++)
                    {
                        sArray[i] = sArray[i] + "}";
                    }

                    var res = DynamicJson.Parse(sArray[i]);
                    if (res.IsDefined("code"))
                    {
                        double code = res.code;
                        if (code == 101)
                        {
                            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
                            session.Send("{\"code\":1001,\"res\":0,\"timestamp\": " + Convert.ToInt64(ts.TotalSeconds) + "}");
                            break;
                        }
                        if (code == 010)
                        {
                            session.Send("alive");
                            break;
                        }
                        else
                        {
                            log.Debug($"收到消息: {msg}");
                            switch (code)
                            {
                            //102为什么不可以?手动操作的时候只有104,没有102
                            case 102:    //{"code":102,"id":"010000124b000f81eea6","ep":8,"serial":1,"control":{"on":true,"pt":100},"result":0}
                                if (res.IsDefined("result"))
                                {
                                    string state = "";     //离线为""
                                    using (RedisHashService service = new RedisHashService())
                                    {
                                        if (res.result == 0)              //成功0,失败3离线
                                        {
                                            if (res.IsDefined("control")) //可能有不存在on的
                                            {
                                                var control = res.control;
                                                if (control.IsDefined("on"))
                                                {
                                                    state = control.on.ToString();
                                                }
                                                else if (control.IsDefined("pt"))
                                                {
                                                    state = Convert.ToInt32(control.pt) > 0 ? "True" : "False";    //窗帘开度,存在关闭的时候104关闭不充分,打开13,关闭86
                                                }
                                                else
                                                {
                                                    state = "False";    //在线没有st,但是没有开关状态的情况,默认关闭
                                                }
                                            }
                                            else
                                            {
                                                state = "False";    //在线没有st,但是没有开关状态的情况,默认关闭
                                            }
                                        }
                                        string cachekey = res.id + "_" + res.ep;
                                        //发布YunZigStateChangeQueue状态同步消息
                                        PutMqttData(service, cachekey, state);
                                    }
                                }
                                break;

                            case 104:    //手动,app无法区分{"code":104,"control":2,"id":"010000124b0014c6aaee","ol":true,"ep":1,"pid":260,"did":0,"st":{"on":false}}
                                if (res.IsDefined("control"))
                                {
                                    if (res.control == 2)
                                    {
                                        string state = "";     //离线为""
                                        using (RedisHashService service = new RedisHashService())
                                        {
                                            if (res.ol == true)          //在线
                                            {
                                                if (res.IsDefined("st")) //可能有不存在on的
                                                {
                                                    var st = res.st;
                                                    if (st.IsDefined("on"))
                                                    {
                                                        state = st.on.ToString();
                                                    }
                                                    else if (st.IsDefined("pt"))
                                                    {
                                                        state = Convert.ToInt32(st.pt) > 0 ? "True" : "False";    //窗帘开度,存在关闭的时候104关闭不充分,打开13,关闭86
                                                    }
                                                    else
                                                    {
                                                        state = "False";    //在线没有on,但是没有开关状态的情况,默认关闭
                                                    }
                                                }
                                                else
                                                {
                                                    state = "False";    //在线没有st,但是没有开关状态的情况,默认关闭
                                                }
                                            }

                                            string cachekey = res.id + "_" + res.ep;
                                            //发布YunZigStateChangeQueue状态同步消息
                                            PutMqttData(service, cachekey, state);
                                        }
                                    }
                                }
                                break;

                            case 1002:    //改变设备状态
                            case 5001:    //查询某个设备状态
                                if (res.IsDefined("zigbee"))
                                {
                                    if (Gateway_SessionDic.ContainsKey(res.zigbee))
                                    {
                                        Gateway_SessionDic[res.zigbee].Send(sArray[i]);
                                    }
                                    else
                                    {
                                        log.Debug($"请求网关的session不存在 {res.zigbee}: {msg}");
                                    }
                                }
                                break;

                            case 501:
                                using (RedisHashService service = new RedisHashService())
                                {
                                    foreach (var item in res.device)  //多键开关
                                    {
                                        string state = "";            //离线为""
                                        if (item.ol == true)          //在线
                                        {
                                            if (item.IsDefined("st")) //可能有不存在on的
                                            {
                                                var st = item.st;
                                                if (st.IsDefined("on"))
                                                {
                                                    state = st.on.ToString();
                                                }
                                                else if (st.IsDefined("pt"))
                                                {
                                                    state = Convert.ToInt32(st.pt) > 0 ? "True" : "False";    //窗帘开度,存在关闭的时候104关闭不充分,打开13,关闭86
                                                }
                                                else
                                                {
                                                    state = "False";    //在线没有on,但是没有开关状态的情况,默认关闭
                                                }
                                            }
                                            else
                                            {
                                                state = "False";    //在线没有on,但是没有开关状态的情况,默认关闭
                                            }
                                        }
                                        service.SetEntryInHash("DeviceStatus", res.id + "_" + res.ep, state);
                                    }
                                }
                                break;

                            default:
                                break;
                            }
                        }
                    }
                    else if (res.IsDefined("mac") && res.IsDefined("id"))
                    {
                        //缓存当前socket连接,初次连接心跳之前会收到网关注册信息{"id":"00ff2c2c2c6a6f005979","mac":"2c:6a:6f:00:59:79"}
                        //Func<string, HansAppSession, HansAppSession> dd = (key,oldValue)=>session;
                        //当网关重新连接的时候,ip换了的时候,替换之前的session
                        Gateway_SessionDic.AddOrUpdate(res.id, session, (Func <string, HansAppSession, HansAppSession>)((key, oldValue) => session));

                        using (RedisHashService service = new RedisHashService())
                        {
                            service.SetEntryInHash("DeviceStatus", res.id + "_13579", "True");//mac_port,
                            //网关会自动上传104所有设备状态
                        }
                        log.Debug($"收到网关注册消息:缓存session: {session.RemoteEndPoint} ,网关状态信息: {msg}");
                        Console.WriteLine($"连接网关Ip: {session.RemoteEndPoint} Mac: {res.mac} {DateTime.Now.ToString()}");
                    }
                    else if (res.IsDefined("lot"))
                    {
                        SmartHome_Session = session;
                        log.Debug($"收到Lot长连接session: {session.RemoteEndPoint} 信息: {msg}");
                    }
                    else
                    {
                        log.Info($"{session.RemoteEndPoint.ToString()} 未识别信息: {sArray[i]}");
                    }
                }
            });
        }
        /// <summary>
        /// 获得当前房间的设备列表的命令8;815;+ posid
        /// </summary>
        /// <param name="msg">user:123_Server type:other msg:
        /// 123_DCD9165057AD;8;815;1225155025360$/r$</param>
        public static string Host815(string msg)
        {
            try
            {
                if (msg.Split(';').Length >= 4)
                {
                    using (RedisHashService service = new RedisHashService())
                    {
                        string             appUser    = msg.Split(';')[0];
                        string             account    = appUser.Split('_')[0];
                        string             posid      = msg.Split(';')[3].Replace("$/r$", "");//房间id  ,默认id为0,
                        List <host_device> deviceList = null;
                        //获取当前房间的设备列表,先找缓存
                        string deviceListJson = service.GetValueFromHash("RoomDevices", account + "|" + posid);
                        if (!string.IsNullOrEmpty(deviceListJson))
                        {
                            deviceList = JsonConvert.DeserializeObject <List <host_device> >(deviceListJson);
                        }
                        else
                        {
                            using (HsfDBContext hsfDBContext = new HsfDBContext())
                            {
                                if (posid == "0")//新app首页获取所有设备account
                                {
                                    //默认房间为0,查询当前账号所有设备列表
                                    deviceList = hsfDBContext.host_device.Where(t => t.account == account && t.deletemark == 0).OrderBy(t => t.createtime).ToList();
                                    ////包括大华的设备
                                    //List<host_device> outdeviceList = GetOutDevice(account);
                                    //foreach (var item in outdeviceList)
                                    //{
                                    //    deviceList.Add(item);//室内+室外
                                    //}
                                    //缓存当前房间的设备列表,不包括状态,不管空与否都缓存,防止第二次还查数据库RoomDevices
                                    service.SetEntryInHash("RoomDevices", account + "|" + posid, JsonConvert.SerializeObject(deviceList));//解决默认posid都为0的问题
                                }
                                else
                                {
                                    //posid房间id
                                    deviceList = hsfDBContext.host_device.Where(t => t.devposition == posid && t.deletemark == 0).OrderBy(t => t.createtime).ToList();
                                    //缓存当前房间的设备列表,不包括状态,不管空与否都缓存,防止第二次还查数据库
                                    service.SetEntryInHash("RoomDevices", account + "|" + posid, JsonConvert.SerializeObject(deviceList));//解决默认posid都为0的问题
                                }
                            }
                        }

                        //真正更新设备状态
                        string zipStr = "";
                        foreach (var item in deviceList)
                        {
                            if (!string.IsNullOrEmpty(item.cachekey))
                            {
                                //读取缓存状态
                                string status = service.GetValueFromHash("DeviceStatus", item.cachekey);
                                if (string.IsNullOrEmpty(status))
                                {
                                    //离线
                                    item.powvalue = "离线";
                                    item.devstate = "false";
                                }
                                else
                                {
                                    item.powvalue = "在线";
                                    item.devstate = status.ToLower();
                                }
                            }
                        }
                        zipStr = EncryptionHelp.Encryption(JsonConvert.SerializeObject(deviceList), true);
                        string msgResult = $"{appUser};815;{posid};Zip;{zipStr}$/r$";//拼接
                        log.Debug($"815 OK,返回房间设备列表成功!返回信息:{msgResult}");
                        return(msgResult);
                    }
                }
                else
                {
                    log.Debug($"815 Fail,命令不符合规范!");
                    return(null);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        /// <summary>
        /// 获取室外设备大华
        /// </summary>
        /// <param name="account"></param>
        /// <returns></returns>
        public static string GetOutDevice(string account)
        {
            try
            {
                string outdeviceListStr = "";
                //List<host_device> outdeviceList = new List<host_device>();
                using (RedisHashService service = new RedisHashService())
                {
                    using (HsfDBContext hsfDBContext = new HsfDBContext())
                    {
                        if (account.Split('-').Length >= 3)//length:1开始
                        {
                            //室外,大华产品
                            string _residential = account.Split('-')[0];                        //小区
                            string _building    = account.Split('-')[1];                        //楼号
                            string _unit        = account.Split('-')[2];                        //单元
                            string cachekey     = _residential + "-" + _building + "-" + _unit; //默认房间

                            //先查单元对应的缓存,没有再缓存
                            string outDeviceListJson = service.GetValueFromHash("OutDevices", cachekey);
                            if (!string.IsNullOrEmpty(outDeviceListJson))
                            {
                                //outdeviceList = JsonConvert.DeserializeObject<List<host_device>>(outDeviceListJson);
                                return(outDeviceListJson);
                            }
                            else
                            {
                                List <hsf_outdevice> dh_deviceList = hsfDBContext.hsf_outdevice.Where(t => t.residential == _residential && t.deletemark == 0).ToList();
                                //foreach (var item in dh_deviceList)
                                //{
                                //    switch (item.devtype)
                                //    {
                                //        case "Dahua_EntranceGuard"://门禁
                                //            host_device EntranceGuard = new host_device()
                                //            {
                                //                deviceid = item.deviceid,
                                //                chinaname = item.chinaname,
                                //                devtype = item.devtype
                                //            };
                                //            outdeviceList.Add(EntranceGuard);
                                //            break;
                                //        case "Dahua_UnitDoor"://大华单元门口机
                                //            if (_building == item.building && _unit == item.unit)
                                //            {
                                //                host_device UnitDoor = new host_device()
                                //                {
                                //                    deviceid = item.deviceid,
                                //                    chinaname = item.chinaname,
                                //                    devtype = item.devtype
                                //                };
                                //                outdeviceList.Add(UnitDoor);
                                //            }
                                //            break;
                                //        case "Elevator"://电梯
                                //            if (_building == item.building && _unit == item.unit)
                                //            {
                                //                host_device Elevator = new host_device()
                                //                {
                                //                    deviceid = item.deviceid,
                                //                    chinaname = item.chinaname,
                                //                    devtype = item.devtype
                                //                };
                                //                outdeviceList.Add(Elevator);
                                //            }
                                //            break;
                                //        default:
                                //            break;
                                //    }
                                //}
                                outdeviceListStr = EncryptionHelp.Encryption(JsonConvert.SerializeObject(dh_deviceList), false);
                                service.SetEntryInHash("OutDevices", cachekey, outdeviceListStr);//缓存室外有权限控制的设备OutDevices
                                return(outdeviceListStr);
                            }
                        }
                        else
                        {
                            return("error:host format error");
                        }
                    }
                }
            }
            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;
            }
        }
Exemple #28
0
        /// <summary>
        /// 处理Nlp请求req
        /// </summary>
        /// <param name="msg">
        ///1.二楼全开
        ///connect user:Nlp_Server type:home msg:Nlp_Server
        ///connect user:Nlp_Server type:other msg:123_25995;5;513;5omT5byA5byA5YWz$/r$
        ///
        ///connect user:Nlp_Server type:other msg:123_17920;5;513;5omT5byA6ZiB5qW8$/r$
        ///123_17920;513;5omT5byA6ZiB5qW8;Zip;H4sIAAAAAAAEAAEYAOf/5omT5byA77ya6ZiB5qW844CC5aSx6LSlgj8c4BgAAAA=$/r$
        ///
        ///2.返回结果  开启所有灯光、音乐、窗帘4
        ///connect user:25995_ac83f317b8c7 type:other msg:25995_ac83f317b8c7;513;5LqM5qW85YWo5byA;Zip;H4sIAAAAAAAAAHu6p+HphPXPOhuezel83rj+aWvn44bGl/M3P9k5Ach4vmr60x0zTAAnYIhxJQAAAA==$/r$
        ///25995_123;513;5omT5byA5byA5YWz;Zip;H4sIAAAAAAAEAHvWOfnpnob3e2Y9m7nrRfNeIPtp62YTk8cNTcgCpqZoAmZmaAIGBmgChoZoAkZGaALGxmgCieh8dIEkdD66QDI6H10gBY2fisZPQ+OnA/lPl2x8sWUpAHyIeM8pAQAA$/r$
        /// </param>
        public static string HostNlpRequest(string msg)
        {
            try
            {
                if (msg.Split(';').Length >= 3)
                {
                    string session_account = msg.Split(';')[0];
                    if (session_account.Contains("_"))
                    {
                        string account   = session_account.Split('_')[1];
                        string req       = msg.Split(';')[3].Replace("$/r$", "");
                        string deviceStr = EncryptionHelp.Decrypt(req, false);//解码无zip
                        string code      = "";
                        string msgResult = "";
                        string actionStr = "";
                        bool   state     = false;
                        if (deviceStr.Contains("打开"))
                        {
                            actionStr = "打开";
                            code      = "8135";
                            deviceStr = deviceStr.Replace("打开", "");
                            state     = true;
                        }
                        else if (deviceStr.Contains("关闭"))
                        {
                            actionStr = "关闭";
                            code      = "8145";
                            deviceStr = deviceStr.Replace("关闭", "");
                            state     = false;
                        }


                        if (!string.IsNullOrEmpty(code))
                        {
                            using (RedisHashService service = new RedisHashService())
                            {
                                List <host_device> deviceList = null;
                                //获取当前房间的设备列表,先找缓存
                                string devices = service.GetValueFromHash("AccountDevices", account);

                                if (!string.IsNullOrEmpty(devices))
                                {
                                    deviceList = JsonConvert.DeserializeObject <List <host_device> >(devices);//list多件开关,ALL数组
                                }
                                else
                                {
                                    using (HsfDBContext hsfDBContext = new HsfDBContext())
                                    {
                                        deviceList = hsfDBContext.host_device.Where(t => t.account == account && t.deletemark == 0).ToList();
                                        service.SetEntryInHash("AccountDevices", account, JsonConvert.SerializeObject(deviceList));
                                    }
                                }
                                if (deviceList.Count() != 0)
                                {
                                    var deviceControl = deviceList.Where(t => t.chinaname.Contains(deviceStr)).ToList();//包含“开关”名称的所有设备
                                    if (deviceControl.Count() != 0)
                                    {
                                        string okDevices   = "";
                                        string failDevices = "";
                                        foreach (var item in deviceControl)
                                        {
                                            //发送指令给网关,改变状态,避免两次查库
                                            //DeviceStateChange($"{session_account};8;{code};{item.deviceid};$/r$")
                                            if (ChangeStateMain.StateChangeByType(item, state))
                                            {
                                                okDevices += item.chinaname + "。";
                                            }
                                            else
                                            {
                                                failDevices += item.chinaname + "。";
                                            }
                                        }
                                        string resultDevices = "";
                                        if (!string.IsNullOrEmpty(okDevices))
                                        {
                                            resultDevices += $"已经为您{actionStr}:{okDevices}";
                                        }
                                        if (!string.IsNullOrEmpty(failDevices))
                                        {
                                            resultDevices += $"{actionStr}:{failDevices}失败";
                                        }
                                        msgResult = $"{session_account};513;{req};Zip;{EncryptionHelp.Encryption(resultDevices, true)}$/r$";
                                        log.Debug($"{resultDevices}! cachekey:{msgResult}");
                                        return(msgResult);
                                    }
                                    else
                                    {
                                        log.Debug($"不存在该设备! {req}");
                                        return(null);
                                    }
                                }
                                else
                                {
                                    log.Debug($"不存在该账户的设备列表! {msg}");
                                    return(null);
                                }
                            }
                        }
                        else
                        {
                            log.Debug($"code不符合规范! {msg}");
                            return(null);
                        }
                    }
                    else
                    {
                        log.Debug($"命令不符合规范! {msg}");
                        return(null);
                    }
                }
                else
                {
                    log.Debug($"命令不符合规范! {msg}");
                    return(null);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        /// <summary>
        /// 获得当前设备类型的设备列表的命令8;855;+ devtype
        /// </summary>
        /// <param name="msg">1.查询设备类型
        /// user:DAJCHSF_Server type:other
        /// msg:DAJCHSF_2047DABEF936;8;855;0;Panel_Smartsix,Panel_Wired_Control,Panel_Zigbee,Panel_SingleZigbee,Panel_485Gao,Panel_485Hotel,Panel_485Bus$/r$  面板
        /// user:JYWH_Server type:other
        /// msg:JYWH_2047DABEF936;8;855;0;Panel_Smartsix,Panel_Wired_Control,Panel_Zigbee,Panel_SingleZigbee,Panel_485Gao,Panel_485Hotel,Panel_485Bus$/r$
        /// user:123_Server type:other
        /// msg:123_DCD9165057AD;8;855;0;Zigbee_Gate$/r$  网关
        /// 2.返回结果
        /// user:DAJCHSF_2047DABEF936 type:other
        /// msg:DAJCHSF_2047DABEF936;855;0;Zip;H4sIAAAAAAAAAOWZb2vTQBjAv4rkdZG7y92l2YcQ8aUi45pdukD/kaQOGQOH5oWFjb0Qq0wcOtGiMgcbUoqyT3Pr+i28a9LON2240kObNjTluculye8JvzyXPNq12hEPgy1rw7JKVqu584TV2lxG4l1vOLiSbd520GANVh83nn0Uh4k46gz3f6iuGosifzJ4i8uxLKxPI2+bNRq8JmMAfB95aqGM+gAQl5J0m8Dj4/EQ2JCiMoYUY5B1tVQ7cu4CucC0rc48tTsI5AciXJFrB/kU80ra32IhszZ299KgGcZqF1lXMwrioNnI/oxgG7gOzg4jilmsTtBntYj/1QSnJzMO0TSMn7bU9veZPMHNh0G1wtWwoM6qfMKjVo3GBwBK1qZqk7/3+M4D7jVDGcVhm++VFsJ//sIkfgKXix8VDL9kL/qfzeFHy8VvFwy/ON03dPW7kABXWz7cdytkHeRz/XZw8/y3+PVMJBfQGH9t++Tw17GPovLf4k+v/uvX56PTQ2P0qa58cugXSD4H34avTkbdS3HUH334aUZBuIwAwlBPQdgDNuFgHRSkbr3JS5H0pIWM4Ud6BsrFX5z65xZ/cmEOv56CcvEXR0E3V8ejbi+dfN1ZPn8HIgApcBewj78W9kn5myr/U/wQLGCfefiLY5/s8jc0+c3wL2KfefiLYx9x8EWcfTL16MexCSJ2mejKh7g2dBeQj/xSsHr4jcknxU915ZODf6Z8VhS/Mfmk+B1d+eTgnymfFcVvavI7wW8vFz8uGP7h167ov1k2fgxcRCB0gOaTN3XrdZk9G3+B3H98KQYdM+6f4td88JaLv3DuNzLtvcWvX3jOxV8g93fei+S7sdoTQ4gBJIRoTnzVixfqLVJ7IkLKq1X6TzNgpP6ZZIBqzn1zMzBTQaubAUM3gUkGoP7Lx7kZmGmhf5+Bx38AI07FAvsgAAA=$/r$</param>
        public static string Host855(string msg)
        {
            try
            {
                if (msg.Split(';').Length >= 4)
                {
                    using (RedisHashService service = new RedisHashService())
                    {
                        string             appUser    = msg.Split(';')[0];
                        string             account    = appUser.Split('_')[0];
                        string             devtypeStr = msg.Split(';')[4].Replace("$/r$", "");//设备类型列表
                        string[]           devtypes   = devtypeStr.Split(',');
                        List <host_device> deviceList = null;
                        //获取当前设备类型的设备列表,先找缓存
                        string deviceListJson = service.GetValueFromHash("TypeDevices", account + "|" + devtypeStr);
                        if (!string.IsNullOrEmpty(deviceListJson))
                        {
                            deviceList = JsonConvert.DeserializeObject <List <host_device> >(deviceListJson);
                        }
                        //如果缓存中没有,再查数据库
                        else
                        {
                            using (HsfDBContext hsfDBContext = new HsfDBContext())
                            {
                                deviceList = hsfDBContext.host_device.Where(t => t.account == account && devtypes.Contains(t.devtype) && t.deletemark == 0).OrderBy(t => t.createtime).ToList();
                                //缓存当前设备类型的设备列表,不包括状态,不管空与否都缓存,防止第二次还查数据库
                                service.SetEntryInHash("TypeDevices", account + "|" + devtypeStr, JsonConvert.SerializeObject(deviceList));//解决默认posid都为0的问题
                            }
                        }

                        //真正更新设备状态
                        string zipStr = "";
                        foreach (var item in deviceList)
                        {
                            //读取缓存状态
                            string status = service.GetValueFromHash("DeviceStatus", item.cachekey);
                            if (string.IsNullOrEmpty(status))
                            {
                                //离线
                                item.powvalue = "离线";
                                item.devstate = "false";
                            }
                            else
                            {
                                item.powvalue = "在线";
                                item.devstate = status.ToLower();
                            }
                        }
                        zipStr = EncryptionHelp.Encryption(JsonConvert.SerializeObject(deviceList), true);
                        string msgResult = $"{appUser};855;0;Zip;{zipStr}$/r$";//拼接
                        log.Debug($"855 OK,返回设备类型的设备列表成功!返回信息:{msgResult}");
                        return(msgResult);
                    }
                }
                else
                {
                    log.Debug($"855 Fail,命令不符合规范!");
                    return(null);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }