/// <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="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; } }
/// <summary> /// 收到YunZig状态改变队列数据 /// </summary> public static void GetYunZigStateChangeQueue() { Task.Run(() => { ToolHelper.FunctionHelper.writeLog("手动或App上报状态", "启动线程……", "YunZigStateChangeQueue"); try { using (RedisListService service = new RedisListService()) { service.Subscribe("YunZigStateChangeQueue", (c, cachekey, iRedisSubscription) => { //log.Debug($"收到YunZig状态改变队列数据,同步状态 {c}:{message},Dosomething else"); //ToolHelper.FunctionHelper.writeLog("状态订阅", cachekey, "YunZigStateChangeQueue"); using (RedisHashService serviceHash = new RedisHashService()) { //获取openUid string openUid = serviceHash.GetValueFromHash("DuerOSOpenUid_Device", cachekey); if (!string.IsNullOrEmpty(openUid)) { var tempPostModel = new ChangeReportRequestModel() { header = new Models.CommonModel.Head() { messageId = FunctionHelper.GetTimStamp() + "", name = "ChangeReportRequest", @namespace = "DuerOS.ConnectedHome.Control", payloadVersion = 1 }, payload = new Models.ReturnModel.Payload.ChangeReportRequestPayload() { botId = DuerOSSyncBotId, openUid = openUid, appliance = new Models.ReturnModel.Payload.TempAppliance() { applianceId = cachekey, attributeName = "turnOnState" } } }; var tempRes = ToolHelper.FunctionHelper.PostJsonString(DuerOSChangeReportUrl, JsonConvert.SerializeObject(tempPostModel));//{"status":21093,"msg":"Appliance specificed not exist, stop sync","messageId":"1557135094549","data":{"updated_attribute_num":0}} ToolHelper.FunctionHelper.writeLog("手动或App上报状态: " + cachekey, tempRes, "YunZigStateChangeQueue"); Thread.Sleep(100); } } });//blocking } } catch (Exception ex) { FunctionHelper.writeLog("状态订阅异常", ex.Message, "YunZigStateChangeQueue"); throw; } }); }
/// <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); }
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}"); } } } }
/// <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; } }
public static void PutDeviceChangeQueue(string host) { //如果存在百度音响的设备列表缓存,则清空,再发布同步消息队列 using (RedisHashService service1 = new RedisHashService()) { string duerOSHost = service1.GetValueFromHash("DuerOS_DiscoverPayload", host); if (!string.IsNullOrEmpty(duerOSHost)) { service1.RemoveEntryFromHash("DuerOS_DiscoverPayload", host); log.Debug($"删除掉DuerOS_DiscoverPayload:{host}"); using (RedisListService service = new RedisListService()) { service.Publish("LotDeviceChangeQueue", host); log.Debug($"放入设备同步队列LotDeviceChangeQueue:{host}"); } } } }
/// <summary> /// 收到Lot设备同步订阅 /// </summary> public static void GetLotDeviceChangeQueue() { Task.Run(() => { ToolHelper.FunctionHelper.writeLog("主动上报设备改变", "启动线程……", "LotDeviceChangeQueue"); try { using (RedisListService service = new RedisListService()) { service.Subscribe("LotDeviceChangeQueue", (c, Account, iRedisSubscription) => { //ToolHelper.FunctionHelper.writeLog("设备同步订阅", Account, "LotDeviceChangeQueue"); using (RedisHashService serviceHash = new RedisHashService()) { //获取openUid string openUid = serviceHash.GetValueFromHash("DuerOSOpenUid_Host", Account); if (!string.IsNullOrEmpty(openUid)) { var tempPostModel = new DuerOSSyncDevice() { botId = DuerOSSyncBotId, logId = FunctionHelper.GetTimStamp() + Account, openUids = new List <string> { openUid } }; var tempRes = ToolHelper.FunctionHelper.PostJsonString(DuerOSSyncUrl, JsonConvert.SerializeObject(tempPostModel));//{"status":21093,"msg":"Appliance specificed not exist, stop sync","messageId":"1557135094549","data":{"updated_attribute_num":0}} //{"status":0,"msg":"ok","logid":"1557387335989AAA","data":{"discover":"succeed","failed":[],"succeed":["ee65663a03e810214acc0ac1c18260e7"]}} ToolHelper.FunctionHelper.writeLog("主动上报设备改变: " + Account, tempRes, "LotDeviceChangeQueue"); Thread.Sleep(100); } } }); } } catch (Exception ex) { FunctionHelper.writeLog("设备同步订阅异常", ex.Message, "LotDeviceChangeQueue"); throw; } }); }
/// <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="service"></param> /// <param name="cachekey"></param> /// <returns></returns> public AttributesItem GetStateByCachekey(RedisHashService service, string cachekey) { string devstate = ""; if (!string.IsNullOrEmpty(cachekey)) { //读取缓存状态 string status = service.GetValueFromHash("DeviceStatus", cachekey); if (string.IsNullOrEmpty(status)) { //离线 devstate = "false"; } else { devstate = status.ToLower(); } } return(GetAttributesItem(devstate)); }
/// <summary> /// 确认器,读取缓存状态,半秒读取一次,共读取3秒左右,没反应就返回失败 /// </summary> /// <param name="cachekey"></param> /// <param name="ok"></param> /// <returns></returns> public static bool StateResult(string cachekey, string st) { using (RedisHashService service = new RedisHashService()) { bool state = false; int i = 0; while (i < 30)//6s,次数限制redis { i++; Thread.Sleep(200); //读取缓存状态 string status = service.GetValueFromHash("DeviceStatus", cachekey); if (status == st) { log.Debug($"设备状态改变成功! cachekey:{cachekey}!轮询次数: {i}"); state = true; break; } } return(state); } }
/// <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> /// 获得当前房间的设备列表的命令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> ///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; } }
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($"保存到句子表和分词表"); }); } }
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="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); } }
/// <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 { } }
/// <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; } }
/// <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; } }
/// <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> /// 处理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> /// 获取室外设备大华 /// </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; } }