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> /// 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; } }
/// <summary> /// 更改是否自身播放音乐状态反转 /// </summary> /// <param name="msg">user:zys_Server type:other msg: /// zys_DCD9165057AD;1;111;all;admin,admin,shouquanma,zys_Server,DCD9165057AD,192.168.88.101$/r$</param> /// ssxy_C40BCB80050A;111;all;Zip;H4sIAAAAAAAAADN0AAILi+KUNAsgMDKuKAPRAHas4VgWAAAA$/r$ public static string Host111(string msg) { try { string account_mac = msg.Split(';')[0]; if (account_mac.Contains("_")) { string account = account_mac.Split('_')[0]; string mac = account_mac.Split('_')[1]; //如果发送到音响失败,则不修改数据库 using (HsfDBContext hsfDBContext = new HsfDBContext()) { //获取主机和设备,删除标记为0,未删除的 var accountEntity = hsfDBContext.host_account.Where(t => t.Account == account && t.DeleteMark == 0).FirstOrDefault(); if (accountEntity != null) { return($"H4sIAAAAAAAAADN0AAILi+KUNAsgMDKuKAPRAHas4VgWAAAA");//user:{account_mac} type:other msg:{account_mac};111;all;Zip; $/r$ } else { return($"H4sIAAAAAAAAAEstKsovAgBxvN1dBQAAAA==");//user:{account_mac} type:other msg:{account_mac};111;all;Zip; $/r$ } } } else { return($"Command Fail"); } } catch (Exception) { throw; } }
/// <summary> /// 注册音响 /// </summary> /// <param name="msg">user:wali_Server type:other /// msg:wali_Server;8;8212;ALL;H4sIAAAAAAAAAG2RsU7DMBCG38VzVOUcN6TZGBlggBGh6ORcUkuJHdlJI1RVYmFn4ykQAyuv04G3wIlLRBHy4u/+/3y/zvd7dkPjLUljS5b3dqCIFcpf44jJrdKosSWWM5RZUiUgCKsL5qUGnasmH8s8lrTDBm3rMZDcotbULKwkzWbgsAbBIRYiSeOT1s1CEqhFOeGGryDNVlm2gpgHpUOLLN/72cZNkY7PH1+vbxEHiPz522A60pPp8+n48v6/6RCeNbZfcnbGqV4ZHaICCJHGsPlJaqmWpqTfcV2PPS3tM8E58gX7x26yXl4V16Tr0gy+rFqsw2q8AeK1LzW1myP5H+jM6Bc7nAYMjuxsHbFRxR3ZHVl2ePgGQ/XuYsMBAAA=$/r$</param> public static void RegSoundHost(string msg) { string msg64j = EncryptionHelp.Decrypt(msg.Split(';')[4].Replace("$/r$", ""), true);//解密"设备无法识别@打开窗帘" msg64j = msg64j.Replace("[", "").Replace("]", ""); SoundHost _SoundHost = JsonConvert.DeserializeObject <SoundHost>(msg64j);//反序列化 using (HsfDBContext hsfDBContext = new HsfDBContext()) { sound_host sound_Host = new sound_host() { id = Guid.NewGuid().ToString(), chinaname = _SoundHost.chinaname, classfid = _SoundHost.classfid, deviceid = _SoundHost.deviceid, devip = _SoundHost.devip, devmac = _SoundHost.devmac, devport = _SoundHost.devport, devposition = _SoundHost.devposition, devregcode = _SoundHost.devregcode, devtype = _SoundHost.devtype, imageid = _SoundHost.imageid, lgsort = _SoundHost.lgsort, userid = _SoundHost.userid, playstate = 1,//是否自身播放音乐状态反转,0:否,1:是 createtime = DateTime.Now }; hsfDBContext.sound_host.Add(sound_Host); hsfDBContext.SaveChanges(); } }
/// <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!"); } } } } }
/// <summary> /// 更改是否自身播放音乐状态反转 /// </summary> /// <param name="msg">user:wali_Server type:other /// msg:wali_C40BCB80050A;8;8215;88888888;1$/r$</param> public static void UpdatePlayState(string msg) { if (msg.IndexOf(";") > 0) { string userid = msg.Split(';')[0]; string deviceid = msg.Split(';')[3]; // using (HsfDBContext hsfDBContext = new HsfDBContext()) { var soundhostEntity = hsfDBContext.sound_host.Where(t => t.userid == userid && t.deviceid == deviceid).FirstOrDefault(); if (soundhostEntity.playstate == 1 || soundhostEntity.playstate == null) { soundhostEntity.playstate = 0; } else { soundhostEntity.playstate = 1; } hsfDBContext.SaveChanges(); } SoundPassiveRequest _SoundPassiveRequest = new SoundPassiveRequest() { sessionId = Guid.NewGuid().ToString(), deviceId = deviceid, actionId = "8215", blwakeup = "0" }; DoRequestEvent(_SoundPassiveRequest); } }
/// <summary> /// 注册音响 /// </summary> /// <param name="msg">user:wali_Server type:other /// msg:wali_Server;8;8212;ALL;H4sIAAAAAAAAAG2RsU7DMBCG38VzVOUcN6TZGBlggBGh6ORcUkuJHdlJI1RVYmFn4ykQAyuv04G3wIlLRBHy4u/+/3y/zvd7dkPjLUljS5b3dqCIFcpf44jJrdKosSWWM5RZUiUgCKsL5qUGnasmH8s8lrTDBm3rMZDcotbULKwkzWbgsAbBIRYiSeOT1s1CEqhFOeGGryDNVlm2gpgHpUOLLN/72cZNkY7PH1+vbxEHiPz522A60pPp8+n48v6/6RCeNbZfcnbGqV4ZHaICCJHGsPlJaqmWpqTfcV2PPS3tM8E58gX7x26yXl4V16Tr0gy+rFqsw2q8AeK1LzW1myP5H+jM6Bc7nAYMjuxsHbFRxR3ZHVl2ePgGQ/XuYsMBAAA=$/r$</param> public static string RegSoundBinding(string msg) { string msg64j = EncryptionHelp.Decrypt(msg.Split(';')[4].Replace("$/r$", ""), true);//解密"设备无法识别@打开窗帘" msg64j = msg64j.Replace("[", "").Replace("]", ""); SoundHost _SoundHost = JsonConvert.DeserializeObject <SoundHost>(msg64j);//反序列化 if (!string.IsNullOrEmpty(_SoundHost.userid)) { using (HsfDBContext hsfDBContext = new HsfDBContext()) { _SoundHost.userid = GetNewUserId_Server(_SoundHost.userid); //根据音响的设备id:devmac去判断,有的话软删除,没有的话注册新增 var soundhostEntity = hsfDBContext.sound_host.Where(t => t.devmac == _SoundHost.devmac && t.deletemark == 0).FirstOrDefault(); if (soundhostEntity != null) { soundhostEntity.deletemark = 1;//软删除old记录 soundhostEntity.modifiytime = DateTime.Now; BindNewHost(hsfDBContext, _SoundHost); return($"Binding OK Again"); } else { BindNewHost(hsfDBContext, _SoundHost); return($"Binding OK"); } } } else { return($"Binding Fail"); } }
/// <summary> ///1.告诉主机删除设备 ///user:123_Server type:other msg:123_DCD9165057AD;8;822;1041656180510$/r$ ///2.主机返回删除成功delok@105 124612 6590 ///user:123_DCD9165057AD type:other msg:123_DCD9165057AD;822;1041656180510;Zip;H4sIAAAAAAAAAEtJzcnPdjA0MDE0MzUztDAwNTQAAJxecTETAAAA$/r$ /// </summary> /// <param name="msg"></param> public static string Host822(string msg) { try { if (msg.Split(';').Length >= 4) { string appUser = msg.Split(';')[0]; string account = appUser.Split('_')[0]; string deviceId = msg.Split(';')[3].Replace("$/r$", ""); string posid = ""; string cachekey = ""; using (HsfDBContext hsfDBContext = new HsfDBContext()) { //能否确定deviceid唯一,用时间来做标识??隐患 :添加用户限定排除风险 var deviceEntity = hsfDBContext.host_device.Where(t => t.deviceid == deviceId && t.account == account && t.deletemark == 0).FirstOrDefault(); if (deviceEntity != null) { posid = deviceEntity.devposition; cachekey = deviceEntity.devmac + "_" + deviceEntity.devport;//存在mac相同,端口不相同的多键设备 deviceEntity.deletemark = 1; deviceEntity.modifiyuser = appUser; deviceEntity.modifiytime = DateTime.Now; hsfDBContext.SaveChanges(); //2.主机返回app删除成功 string msgResult = $"{appUser};822;{deviceId};Zip;H4sIAAAAAAAEAEtJzcnPBgBd3KDfBQAAAA==$/r$";//拼接 delok //清除房间设备列表缓存 service.HashDelete("RoomDevices", account + "|" + posid); log.Debug($"清除房间设备列表缓存RoomDevices {account}|{posid}"); //清除当前设备状态 service.HashDelete("DeviceStatus", cachekey); log.Debug($"清除当前设备状态DeviceStatus {cachekey}"); //清除当前设备类型的设备列表缓存 service.HashDelete("TypeDevices", account + "|" + deviceEntity.devtype); log.Debug($"清除当前设备类型的设备列表缓存TypeDevices {account}|{deviceEntity.devtype}"); log.Debug($"822 OK,删除设备成功!返回信息:{msgResult}"); return(msgResult); } else { log.Debug($"822 Fail,删除设备失败,设备不存在!"); return(null); } } } else { log.Debug($"822 Fail,删除设备失败,命令不符合规范!"); return(null); } } catch (Exception) { throw; } }
/// <summary> /// 添加设备 8;8211;All;+Base64(zip(设备对象jhson串)) /// </summary> /// <param name="msg">user:123_Server type:other msg: /// 123_DCD9165057AD;8;8211;ALL;H4sIAAAAAAAAAH2QPU7EMBCF7zJ1CjuRs2wuQEdBuQitBmectZTEke2wQqutEAeg5Bx0SHscfo6Bf6JINMiNv/eeZ8Zzd4IbOt6SNLaFxtuZCtjrcGUFyIMeccSBoIGvt4+f58v35fXz5Z1B8Hp0TsUgXAVs6RF7tEPATPKA40j9ylpSCvOyFFyIWvCKbdniTcFgTKlSxlNjrRgTG6WyPaD815/QIjSncwZjfWxTic12sY3TXpsx1siKpU6altI0VZacR0/rsIn4XyxX9E9TjO5090C0v44PC9ADdvmHIcGZCFLfuTRM2ORkjmE/89JhdmRTFM73v4aKUN2AAQAA$/r$</param> public static string Host8211(string msg) { try { if (msg.Split(';').Length >= 4) { string appUser = msg.Split(';')[0]; string zipStr = msg.Split(';')[4].Replace("$/r$", ""); string base64j = EncryptionHelp.Decrypt(zipStr, true); var deviceLists = JsonConvert.DeserializeObject <List <host_device> >(base64j);//list多件开关,ALL数组 string posid = ""; string cachekey = ""; using (HsfDBContext hsfDBContext = new HsfDBContext()) { foreach (var item in deviceLists) { posid = item.devposition; cachekey = item.devmac + "_" + item.devport;//存在mac相同,端口不相同的多键设备 if (string.IsNullOrEmpty(item.userid)) { item.userid = appUser; } var deviceEntity = hsfDBContext.host_device.Where(t => t.cachekey == cachekey && t.deletemark == 0).FirstOrDefault(); if (deviceEntity != null) { deviceEntity.deletemark = 1; deviceEntity.modifiytime = DateTime.Now; AddDevice(hsfDBContext, item); log.Debug($"8211 OK,重新添加设备成功!"); } else { //当前房间id需要保存,网关房间id为0,不可以 AddDevice(hsfDBContext, item); } } //2.主机返回app添加成功 string msgResult = $"{appUser};8211;ALL;Zip;H4sIAAAAAAAAAHNMScnPBgD0Si5gBQAAAA==$/r$"; //拼接 //清除房间设备列表缓存 using (RedisHashService service = new RedisHashService()) { service.RemoveEntryFromHash("RoomDevices", appUser + "|" + posid);//解决默认posid都为0的问题 } log.Info($"8211 OK,添加设备成功!返回信息:{msgResult}"); return(msgResult); } } else { log.Error($"8211 Fail,添加设备失败,命令不符合规范!"); return(null); } } catch (Exception) { throw; } }
/// <summary> /// 新增房间数据库操作 /// </summary> /// <param name="hsfDBContext"></param> /// <param name="_SoundHost"></param> public static void AddRoom(HsfDBContext hsfDBContext, host_room room) { room.id = Guid.NewGuid().ToString(); room.CreateTime = DateTime.Now; room.DeleteMark = 0; hsfDBContext.host_room.Add(room); hsfDBContext.SaveChanges(); }
/// <summary> ///1.告诉主机重命名设备名称 解压(射灯,0115170616344) 新名,房间id ///connect user:123_Server type:other msg:123_DCD9165057AD;8;823;01240943509560;5bCE54GvLDAxMTUxNzA2MTYzNDQ=$/r$ ///2.主机返回改名成功renameok@1041140155612 ///user:DAJCHSF_2047DABEF936 type:other msg:DAJCHSF_2047DABEF936;823;1041140155612;Zip;H4sIAAAAAAAAACtKzUvMTc3PdjA0MDE0NDEwNDU1MzQCAFBUoP4WAAAA$/r$ /// </summary> /// <param name="msg"></param> public static string Host823(string msg) { try { if (msg.Split(';').Length >= 4) { string appUser = msg.Split(';')[0]; string account = appUser.Split('_')[0]; string deviceId = msg.Split(';')[3]; string newName_Pid_ya = msg.Split(';')[4].Replace("$/r$", ""); string newName_Pid = EncryptionHelp.Decrypt(newName_Pid_ya, false); string newName = newName_Pid.Split(',')[0]; string posid = newName_Pid.Split(',')[1]; using (HsfDBContext hsfDBContext = new HsfDBContext()) { //根据房间id+设备id查询要改名的设备 var deviceEntity = hsfDBContext.host_device.Where(t => t.deviceid == deviceId && t.devposition == posid && t.deletemark == 0).FirstOrDefault(); if (deviceEntity != null) { deviceEntity.chinaname = newName;//改名 deviceEntity.modifiyuser = appUser; deviceEntity.modifiytime = DateTime.Now; hsfDBContext.SaveChanges(); //2.主机返回app删除成功 string msgResult = $"{appUser};823;{deviceId};Zip;H4sIAAAAAAAEACtKzUvMTc3PBgC88yB7CAAAAA==$/r$";//拼接 renameok //清除房间设备列表缓存 service.HashDelete("RoomDevices", account + "|" + posid); log.Debug($"清除房间设备列表缓存RoomDevices {account}|{posid}"); //清除当前设备类型的设备列表缓存 service.HashDelete("TypeDevices", account + "|" + deviceEntity.devtype); log.Debug($"清除当前设备类型的设备列表缓存TypeDevices {account}|{deviceEntity.devtype}"); log.Debug($"823 OK,设备重命名成功!返回信息:{msgResult}"); return(msgResult); } else { log.Debug($"823 Fail,设备重命名失败,设备不存在!"); return(null); } } } else { log.Debug($"823 Fail,设备重命名失败,命令不符合规范!"); return(null); } } catch (Exception) { throw; } }
/// <summary> /// 添加新的设备数据库 /// </summary> /// <param name="hsfDBContext"></param> /// <param name="_SoundHost"></param> public static void AddDevice(HsfDBContext hsfDBContext, host_device item) { item.id = Guid.NewGuid().ToString(); item.createtime = DateTime.Now; item.deletemark = 0; item.cachekey = item.devmac + "_" + item.devport; hsfDBContext.host_device.Add(item); hsfDBContext.SaveChanges(); }
/// <summary> /// 新增房间 /// </summary> /// <param name="msg">user:123_Server type:other msg: /// 123_DCD9165057AD;8;836;H4sIAAAAAAAAAC2Muw7CIBSG3+XMDBxavLAZmR18gYbgiTIADdAQ0/Tdhdbt+68rPKg+ycb0AlXSQgwm15AzsB8XTDCeQEGtwMDZGBp38uZNvQYpRo/NmWPeNQohceQ4ohguhz+bZECt2y7Kd+5/vEW5mELH35Ip/efDpO/6iifJ5fmmYfsBAlhUH6EAAAA=$/r$ /// {"NewRecord":true,"_id":0,"chinaname":"ww","icon":"","imageid":"room1","posid":"1225140141238","pospara":{},"postype":"0","state":"","userid":"123_DCD9165057AD"}</param> public static void Host836(string msg) { try { if (msg.Split(';').Length >= 3) { string appUser = msg.Split(';')[0]; if (appUser.Contains("_")) { string account = appUser.Split('_')[0]; string mac = appUser.Split('_')[1]; string zipStr = msg.Split(';')[3].Replace("$/r$", ""); string base64j = EncryptionHelp.Decrypt(zipStr, true); var room = JsonConvert.DeserializeObject <host_room>(base64j);//list多件开关 room.Account = account; room.Mac = mac; using (HsfDBContext hsfDBContext = new HsfDBContext()) { var roomEntity = hsfDBContext.host_room.Where(t => t.posid == room.posid && t.DeleteMark == 0).FirstOrDefault(); if (roomEntity != null) { roomEntity.DeleteMark = 1; roomEntity.ModifyTime = DateTime.Now; AddRoom(hsfDBContext, room); log.Debug($"836 Ok,房间信息修改成功!"); } else { //当前房间id需要保存,网关房间id为0,不可以 AddRoom(hsfDBContext, room); log.Info($"836 OK,添加房间成功!"); } //清除房间缓存信息,等待查询之后再次缓存 using (RedisHashService service = new RedisHashService()) { service.RemoveEntryFromHash("Room", account);//解决默认posid都为0的问题 } } } else { log.Error($"836 Fail,添加房间失败,命令不符合规范!"); } } else { log.Error($"836 Fail,添加房间失败,命令不符合规范!"); } } catch (Exception) { throw; } }
/// <summary> /// 新增房间数据库操作 /// </summary> /// <param name="hsfDBContext"></param> /// <param name="_SoundHost"></param> public static void AddRoom(HsfDBContext hsfDBContext, host_room room, string appUser, string account, string mac) { room.CreateUser = appUser; room.Account = account; room.Mac = mac; room.id = Guid.NewGuid().ToString(); room.CreateTime = DateTime.Now; room.DeleteMark = 0; hsfDBContext.host_room.Add(room); hsfDBContext.SaveChanges(); }
/// <summary> /// 添加新的设备数据库 /// </summary> /// <param name="hsfDBContext"></param> /// <param name="_SoundHost"></param> public static void AddDeviceEntity(HsfDBContext hsfDBContext, host_device item, string appUser, string account, string mac) { item.createuser = appUser; item.account = account; item.mac = mac; item.Id = Guid.NewGuid().ToString(); item.createtime = DateTime.Now; item.deletemark = 0; item.cachekey = item.devmac + "_" + item.devport; hsfDBContext.host_device.Add(item); hsfDBContext.SaveChanges(); }
/// <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="hsfDBContext"></param> /// <param name="_SoundHost"></param> public static void BindNewHost(HsfDBContext hsfDBContext, SoundHost _SoundHost) { sound_host sound_Host = GetNewSoundHost(_SoundHost); hsfDBContext.sound_host.Add(sound_Host); hsfDBContext.SaveChanges(); using (RedisHashService service = new RedisHashService()) { //service.Set<string>(_SoundHost.devmac, _SoundHost.userid);//缓存主机与音响的绑定关系 service.SetEntryInHash("Sound_Host", _SoundHost.devmac, _SoundHost.userid);//缓存主机与音响的绑定关系,重复绑定覆盖 } }
/// <summary> /// 新增业主数据库操作 /// </summary> /// <param name="hsfDBContext"></param> /// <param name="_SoundHost"></param> public static void AddReg(HsfDBContext hsfDBContext, RedisHashService service, hsf_owner owner) { owner.Id = Guid.NewGuid().ToString(); owner.host = owner.residential + "-" + owner.building + "-" + owner.unit + "-" + owner.floor + "-" + owner.room; owner.createtime = DateTime.Now; owner.deletemark = 0; hsfDBContext.hsf_owner.Add(owner); hsfDBContext.SaveChanges(); //缓存业主json service.SetEntryInHash("Owner", owner.telphone, JsonConvert.SerializeObject(owner)); //缓存账号密码 service.SetEntryInHash("Login", owner.telphone, owner.password); }
/// <summary> /// 新增房间 /// </summary> /// <param name="msg">user:123_Server type:other msg: /// 123_DCD9165057AD;8;836;H4sIAAAAAAAAAC2Muw7CIBSG3+XMDBxavLAZmR18gYbgiTIADdAQ0/Tdhdbt+68rPKg+ycb0AlXSQgwm15AzsB8XTDCeQEGtwMDZGBp38uZNvQYpRo/NmWPeNQohceQ4ohguhz+bZECt2y7Kd+5/vEW5mELH35Ip/efDpO/6iifJ5fmmYfsBAlhUH6EAAAA=$/r$ /// {"NewRecord":true,"_id":0,"chinaname":"ww","icon":"","imageid":"room1","posid":"1225140141238","pospara":{},"postype":"0","state":"","userid":"123_DCD9165057AD"}</param> public static string Host836(string msg) { try { string appUser = msg.Split(';')[0]; if (appUser.Contains("_")) { string account = appUser.Split('_')[0]; string mac = appUser.Split('_')[1]; string zipStr = msg.Split(';')[3].Replace("$/r$", ""); string base64j = EncryptionHelp.Decrypt(zipStr, true); var room = JsonConvert.DeserializeObject <host_room>(base64j); using (HsfDBContext hsfDBContext = new HsfDBContext()) { using (RedisHashService service = new RedisHashService()) { var roomEntity = hsfDBContext.host_room.Where(t => t.posid == room.posid && t.DeleteMark == 0).FirstOrDefault(); if (roomEntity != null) { //roomEntity.DeleteMark = 1; //roomEntity.ModifyUser = appUser; //roomEntity.ModifyTime = DateTime.Now; hsfDBContext.host_room.Remove(roomEntity);//真实删除 AddRoom(hsfDBContext, room, appUser, account, mac); log.Debug($"836 Ok,房间信息修改成功!"); } else { //当前房间id需要保存,网关房间id为0,不可以 AddRoom(hsfDBContext, room, appUser, account, mac); log.Debug($"836 OK,添加房间成功!"); } //清除房间缓存信息,等待查询之后再次缓存 service.RemoveEntryFromHash("Room", account); //解决默认posid都为0的问题 log.Debug($"清除家庭缓存{account}"); return($"{appUser};836;ALL;Zip;H4sIAAAAAAAAAHNMScnPBgD0Si5gBQAAAA==$/r$"); //Addok } } } else { log.Debug($"836 Fail,添加房间失败,命令不符合规范!"); return($"{appUser};836;ALL;Zip;H4sIAAAAAAAEAEstKsovAgBxvN1dBQAAAA==$/r$");//error } } catch (Exception) { throw; } }
/// <summary> /// 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="msg">user:wali_Server type:other /// msg:wali_C40BCB80050A;8;8215;88888888;1$/r$</param> public static string SoundReversal(string msg) { string userid = msg.Split(';')[0]; userid = GetNewUserId_Server(userid);//主机_Server string devmac = msg.Split(';')[3]; SoundBodyResult _SoundPassiveRequest = new SoundBodyResult() { sessionId = Guid.NewGuid().ToString(), deviceId = devmac, actionId = "8215", blwakeup = "0" }; //如果发送到音响失败,则不修改数据库 if (_NlpControlerRequestMsg(_SoundPassiveRequest)) { using (HsfDBContext hsfDBContext = new HsfDBContext()) { //获取主机和设备,删除标记为0,未删除的 var soundhostEntity = hsfDBContext.sound_host.Where(t => t.userid == userid && t.devmac == devmac && t.deletemark == 0).FirstOrDefault(); if (soundhostEntity != null) { //反转状态 if (soundhostEntity.playstate == 1 || soundhostEntity.playstate == null) { soundhostEntity.playstate = 0; } else { soundhostEntity.playstate = 1; } soundhostEntity.modifiytime = DateTime.Now; hsfDBContext.SaveChanges(); return($"Reversal OK"); } else { return($"Reversal Fail Database"); } } } else { return($"Reversal Fail"); } }
/// <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; } }
public static string GetHostId(string deviceId) { string hostid = ""; using (RedisHashService service = new RedisHashService()) { //hostid = service.Get(body.deviceId);//获取缓存中与音响绑定的主机 hostid = service.GetValueFromHash("Sound_Host", deviceId); //缓存中不存在再查数据库 if (!string.IsNullOrEmpty(hostid)) { return(hostid); } else { //根据设备id获取主机ID using (HsfDBContext hsfDBContext = new HsfDBContext()) { //根据音响devmac找对应的主机userid,向主机发送消息 var soundhostEntity = hsfDBContext.sound_host.Where(t => t.devmac == deviceId && t.deletemark == 0).FirstOrDefault(); if (soundhostEntity != null) { if (!string.IsNullOrEmpty(soundhostEntity.userid)) { hostid = soundhostEntity.userid; //service.Set<string>(body.deviceId, hostid);//缓存主机与音响的绑定关系 service.SetEntryInHash("Sound_Host", deviceId, hostid);//缓存主机与音响的绑定关系,重复绑定覆盖 return(hostid); } else { return(null); } } else { return(null); } } } } }
/// <summary> /// 删除房间 /// </summary> /// <param name="msg">123_DCD9165057AD;8;837;+posid</param> public static void Host837(string msg) { try { if (msg.Split(';').Length >= 3) { string appUser = msg.Split(';')[0]; string account = appUser.Split('_')[0]; string posid = msg.Split(';')[3].Replace("$/r$", ""); using (HsfDBContext hsfDBContext = new HsfDBContext()) { var roomEntity = hsfDBContext.host_room.Where(t => t.posid == posid && t.DeleteMark == 0).FirstOrDefault(); if (roomEntity != null) { roomEntity.DeleteMark = 1; roomEntity.ModifyUser = appUser; roomEntity.ModifyTime = DateTime.Now; hsfDBContext.SaveChanges(); //清除房间缓存信息,等待查询之后再次缓存 service.HashDelete("Room", account);//解决默认posid都为0的问题 log.Debug($"837 Ok,删除房间成功!清除家庭缓存:{account}"); } else { //当前房间id需要保存,网关房间id为0,不可以 log.Debug($"837 Fail,删除房间失败,房间id不存在!"); } } } else { log.Debug($"837 Fail,删除房间失败,命令不符合规范!"); } } catch (Exception) { throw; } }
/// <summary> /// 删除房间 /// </summary> /// <param name="msg">123_DCD9165057AD;8;837;+posid</param> public static string Host837(string msg) { try { string appUser = msg.Split(';')[0]; string account = appUser.Split('_')[0]; string posid = msg.Split(';')[3].Replace("$/r$", ""); using (HsfDBContext hsfDBContext = new HsfDBContext()) { using (RedisHashService service = new RedisHashService()) { var roomEntity = hsfDBContext.host_room.Where(t => t.posid == posid && t.DeleteMark == 0).FirstOrDefault(); if (roomEntity != null) { //roomEntity.DeleteMark = 1; //roomEntity.ModifyUser = appUser; //roomEntity.ModifyTime = DateTime.Now; hsfDBContext.host_room.Remove(roomEntity);//真实删除 hsfDBContext.SaveChanges(); //清除房间缓存信息,等待查询之后再次缓存 service.RemoveEntryFromHash("Room", account); //解决默认posid都为0的问题 log.Debug($"837 Ok,删除房间成功!清除家庭缓存:{account}"); return($"{appUser};837;ALL;Zip;H4sIAAAAAAAEAHNJzcnPBgBZ82EeBQAAAA==$/r$"); //Delok } else { //当前房间id需要保存,网关房间id为0,不可以 log.Debug($"837 Fail,删除房间失败,房间id不存在!"); return($"{appUser};837;ALL;Zip;H4sIAAAAAAAEAEstKsovAgBxvN1dBQAAAA==$/r$");//error } } } } catch (Exception) { throw; } }
//判断验证码是否正确 public static string ValidateSmsCode(string tel, string smsCode) { using (HsfDBContext hsfDBContext = new HsfDBContext()) { var model = hsfDBContext.smsinfo.Where(t => t.Tel == tel && t.Type == (int)SmsType.注册).OrderByDescending(t => t.CreateTime).FirstOrDefault(); if (model == null) { return("error:Verification code error");//验证码不正确 } if (smsCode != model.Captcha) { return("error:Verification code error"); } //判断是否过期 if (model.CreateTime.AddMonths(WebSiteConfig.SMS_EXPIRE_MIN) < DateTime.Now) { return("error:The validation code has expired. Please send it again."); //验证码已过期,请重新发送 } return("smsCode ok"); } }
/// <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> /// 重置密码 /// </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> /// 处理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; } }