using System; using System.Collections.Generic; using Newtonsoft.Json.Linq; using Shared; using Shared.Phone.UserCenter; namespace ZigBee.Device { public class DoorLock : CommonDevice { public DoorLock() { this.Type = DeviceType.DoorLock; } #region 与云端通讯接口 /// /// 添加门锁 /// public class AddDoorLockData { /// /// RequestVersion /// public string RequestVersion = Shared.Common.CommonPage.RequestVersion; /// /// LoginAccessToken /// public string LoginAccessToken = Shared.Common.Config.Instance.Token; /// /// 住宅Id -->键名 : HomeId /// public string HomeId = ""; /// /// 云端帐号Id -->键名 : CloudAccountId /// public string CloudAccountId = ""; /// /// 门锁Id -->键名 : DoorLockId /// public string DoorLockId = ""; /// /// OpenLockMode 开锁方式(密码、指纹、IC卡) -->键名 : OpenLockMode (可选) /// public int OpenLockMode = 0; /// /// 门锁本地用户Id -->键名 : DoorLockLocalUserId /// public string DoorLockLocalUserId = ""; /// /// Data 相关内容(如:密码、指纹、IC卡 的二进制) -->键名 : Data (可选) public byte[] Data = null; /// /// 用户Id备注 -->键名 : UserIdRemarks /// public string UserIdRemarks = ""; /// /// IsFreezeUser 是否冻结用户 -->键名 : IsFreezeUser (可选) /// public bool IsFreezeUser = false; /// /// IsTempUnlockAuthority 是否临时开锁权限 -->键名 : IsTempUnlockAuthority(可选) /// public bool IsTempUnlockAuthority = false; /// /// EntryTime 录入时间 -->键名 : EntryTime(可选) /// public DateTime EntryTime; } /// /// 获取子账户信息 /// static List DoorLockAccountList = new List { }; public static async System.Threading.Tasks.Task> GetSubAccountByDistributedMark() { DoorLockAccountList.Clear(); return await System.Threading.Tasks.Task.Run((Func>>)(async () => { var pra = new Shared.Phone.UserCenter.MemberListInfoPra(); string result = await UserCenterLogic.GetResponseDataByRequestHttps("ZigbeeUsers/GetSubAccountByDistributedMark", true, pra); var listInfo = Newtonsoft.Json.JsonConvert.DeserializeObject>(result); return listInfo; })); } /// /// 服务器获取数据失败提示 /// public void FailureToServer() { Application.RunOnMainThread(() => { var alert = new Alert(Language.StringByID(Shared.R.MyInternationalizationString.TIP), Language.StringByID(Shared.R.MyInternationalizationString.RequestServerFailed), Language.StringByID(Shared.R.MyInternationalizationString.Confrim)); alert.Show(); }); } #endregion #region 门锁本地变量 /// /// 门锁本地用户列表 /// /// public Dictionary localDoorLockUserList = new Dictionary(); public string currentUserDisplayMethod = string.Empty; #endregion public async System.Threading.Tasks.Task GetDoorLockAllInfo() { FingerprintInfo fingerprint = await GetFingerprintAsync(); var password = GetPasswordAsync(); var proximity = GetProximityAsync(); } #region 门锁操作事件通知 /// /// 门锁操作事件通知 /// public DoorLockOperatingEventNotificationCommand doorLockOperatingEventNotificationCommand; /// /// 门锁操作事件通知 /// [System.Serializable] public class DoorLockOperatingEventNotificationCommand { /// /// 用户id ///门锁本地录入的密码、指纹、感应卡都有唯一对应的用户Id /// public int UserID; /// /// 事件触发源 /// 常用: /// 0:Keypad(键盘/密码);3:RFID(射频卡);15:指纹 ///不常用: /// 1:RF(Zigbee无线);2:Manual(手动);255:Indeterminate(不确定) /// public int OperationEventSource; /// /// 事件码 /// 常用: /// 键盘/密码,指纹、感应卡:1:Lock命令成功事件;2:Unlock命令成功事件 ///不常用: /// 请查看枚举 /// public int OperationEventCode; /// /// 保留,默认0 /// public int PIN; /// /// 门锁本地当前时间的时间戳 /// public int ZigbeeLocalTime; } public class AccountsObj { /// /// 关联app账号 /// public string Account; /// /// 保留 /// public int Type; /// /// 保留 /// public int Status; } /// /// “OperationEventSoure”列表 /// public enum OperationEventSoure { /// /// 键盘/密码 /// Keypad = 0, /// /// Zigbee无线 /// RF = 1, /// /// 手动 /// Manual = 2, /// /// 射频卡 /// RFID = 3, /// /// 指纹 /// Fingerprint = 15, /// /// Indeterminate(不确定) /// Indeterminate = 255, } /// /// “OperationEventSoure”类型为“Keypad”即密码 的“OperationEventCode”事件 /// public enum KeypadEventDescription { /// /// 未知事件 /// UnknownEvent = 0, /// /// Lock命令成功事件 /// LockSuccessEvent = 1, /// /// Unlock命令成功事件 /// UnlockSuccessEvent = 2, /// /// Lock命令:error,invalid PIN事件 /// LockInvalidPinEvent = 3, /// /// Lock命令:error,invalid schedule事件 /// LockInvalidScheduleEvent = 4, /// /// Unlock命令:error,invalid PIN事件 /// UnlockInvalidPinEvent = 5, /// /// Unlock命令:error,invalid schedule事件Unlock命令:error,invalid schedule事件 /// UnlockInvalidScheduleEvent = 6, /// /// 非访问用户操作事件 /// NonAccess = 15, } /// /// “OperationEventSoure”类型为“RF” 的“OperationEventCode”事件 /// public enum RfEventDescription { /// /// 未知事件 /// UnknownEvent = 0, /// /// Lock命令成功事件 /// LockSuccessEvent = 1, /// /// Unlock命令成功事件 /// UnlockSuccessEvent = 2, /// /// Lock命令:error,invalid code事件 /// LockInvalidPinEvent = 3, /// /// Lock命令:error,invalid schedule事件 /// LockInvalidScheduleEvent = 4, /// /// Unlock命令:error,invalid code事件 /// UnlockInvalidPinEvent = 5, /// /// Unlock命令:error,invalid schedule事件 /// UnlockInvalidScheduleEvent = 6, } /// /// “OperationEventSoure”类型为“Manual” 的“OperationEventCode”事件 /// public enum ManualEventDescription { /// /// 未知事件 /// UnknownEvent = 0, /// /// Thumbturn Lock;手动转动上锁 /// ThumbturnLockEvent = 1, /// /// Thumbturn Unlock;手动转动解锁 /// UnlockSuccessEvent = 2, /// /// One touch Lock;一键上锁 /// LockInvalidPinEvent = 7, /// ///Key Lock;按键上锁 /// LockInvalidScheduleEvent = 8, /// /// Key Unlock;按键解锁 /// UnlockInvalidPinEvent = 9, /// /// Auto lock;自动上锁 /// UnlockInvalidScheduleEvent = 10, /// /// Schedule Lock;时间表上锁 /// ScheduleLockEvent = 11, /// /// Schedule Unlock;时间表解锁 /// ScheduleUnlockEvent = 12, /// /// Manual Lock(Key or Thumbturn);手动上锁 /// ManualLockEvent = 13, /// ///anual Unlock(Key or Thumbturn);手动解锁 /// ManualUnlockEvent = 14, } /// /// “OperationEventSoure”类型为“RFID” 的“OperationEventCode”事件 /// public enum RfidEventDescription { /// /// 未知事件 /// UnknownEvent = 0, /// /// Lock命令成功事件 /// LockSuccessEvent = 1, /// /// Unlock命令成功事件 /// UnlockSuccessEvent = 2, /// /// Lock命令:error,invalid RFID ID事件 /// LockInvalidRfidIdEvent = 3, /// /// Lock命令:error,invalid schedule事件 /// LockInvalidScheduleEvent = 4, /// /// Unlock命令:error,invalid RFID ID事件 /// UnlockInvalidRfidIdEvent = 5, /// /// Unlock命令:error,invalid schedule事件 /// UnlockInvalidScheduleEvent = 6, } #endregion #region 门锁编程事件通知 /// /// 门锁编程事件通知 /// public DoorLockProgrammingEventNotificationCommand doorLockProgrammingEventNotificationCommand; /// /// 门锁编程事件通知 /// [System.Serializable] public class DoorLockProgrammingEventNotificationCommand { /// /// 用户id ///门锁本地录入的密码、指纹、感应卡都有唯一对应的用户Id /// public int UserID; /// /// 保留 /// public int UserType; /// /// 保留 /// public int UserStatus; /// /// 编程事件触发源 /// 常用: /// 0:Keypad(键盘/密码);3:RFID(射频卡);15:指纹 ///不常用: /// 1:RF(Zigbee无线);2:Manual(手动);255:Indeterminate(不确定) /// public int ProgramEventSoure; /// /// 编程事件码 /// 常用: /// 键盘/密码,指纹、感应卡:1:Lock命令成功事件;2:Unlock命令成功事件 ///不常用: /// 请查看枚举 /// public int ProgramEventCode; /// /// 保留,默认0 /// public int PIN; /// /// 门锁本地当前时间的时间戳 /// public int ZigbeeLocalTime; } #endregion /* #region 获取门锁本地log记录 /// ///获取门锁本地log记录 ///若命令中的PIN/RFID Code与门锁中的PIN/RFID Code相匹配,则将门锁上锁 ///command :门锁设备记录的索引号;取值范围: ///1~“Number of Log Records Supported attribute”; ///值为0表示获取设备最近的记录数据。 /// public async System.Threading.Tasks.Task LogRecordAsync(int logIndex) { if (Gateway == null) { return null; } return await System.Threading.Tasks.Task.Run(async () => { LogRecordResponAllData dataRes = null; Action action = (topic, message) => { var gatewayID = topic.Split('/')[0]; var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); if (topic == gatewayID + "/" + "Error_Respon") { var gatewayTemp = new ZbGateway() { Time = jobject.Value("Time"), DataID = jobject.Value("Data_ID"), CurrentGateWayId = Gateway.getGatewayBaseInfo.gwID }; var temp = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (temp == null) { dataRes = new LogRecordResponAllData { errorMessageBase = "网关错误回复,且数据是空" }; } else { dataRes = new LogRecordResponAllData { errorResponData = temp, errorMessageBase = ErrorMess(temp.Error) }; } } if (topic == gatewayID + "/" + "DoorLock/DoorLockGetLogRecordResponseCommand") { var gatewayTemp = new ZbGateway() { DeviceID = jobject.Value("Device_ID"), DeviceAddr = jobject.Value("DeviceAddr"), DeviceEpoint = jobject.Value("Epoint"), CurrentGateWayId = Gateway.getGatewayBaseInfo.gwID }; var tempData = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (tempData == null) { dataRes = new LogRecordResponAllData { errorMessageBase = "网关返回的数据为空" }; } else { dataRes = new LogRecordResponAllData { logRecordResData = tempData }; DebugPrintLog($"UI收到通知后的主题_{ topic}"); } } }; Gateway.Actions += action; DebugPrintLog("DoorLock/DoorLockGetLogRecordResponseCommand_Actions 启动" + System.DateTime.Now.ToString()); try { var jObject = new JObject { { "DeviceAddr", DeviceAddr }, { "Epoint", DeviceEpoint }, { "Cluster_ID", 257 }, { "Command", 4 }, { "SendMode", 2 } }; var data = new JObject { { "LogIndex", logIndex } }; jObject.Add("Data", data); Gateway.Send("DoorLock/test", jObject.ToString()); } catch { } var dateTime = DateTime.Now; while ((DateTime.Now - dateTime).TotalMilliseconds < WaitReceiveDataTime) { await System.Threading.Tasks.Task.Delay(10); if (dataRes != null) { break; } } if ((DateTime.Now - dateTime).TotalMilliseconds > WaitReceiveDataTime) { dataRes = new LogRecordResponAllData { errorMessageBase = " 回复超时,请重新操作" }; } Gateway.Actions -= action; DebugPrintLog("DoorLock/DoorLockGetLogRecordResponseCommand_Actions 退出" + System.DateTime.Now.ToString()); return dataRes; }); } /// ///获取门锁本地log记录 /// public class LogRecordResponAllData { /// /// 错误信息 /// public string errorMessageBase; /// /// 网关信息错误反馈 /// 当网关接收到客户端信息后,出现以下异常情况将反馈错误。 /// public ErrorResponData errorResponData; /// /// 获取门锁本地log记录 /// public LogRecordResData logRecordResData; } /// ///获取门锁本地log记录 /// public class LogRecordResData { /// /// 事件触发 /// public int OperationEventSoure; /// /// 事件 /// public int OperationEventCode; /// /// 设备当前时间的时间戳 /// public int ZigbeeLocalTime; } #endregion */ /* 获取网关门锁信息,暂不支持 #region 获取所有门锁所有用户信息 /// ///获取所有门锁所有用户信息 /// public async System.Threading.Tasks.Task GetAlldoorlockUserInfoRspAsync() { if (Gateway == null) { return null; } return await System.Threading.Tasks.Task.Run(async () => { AlldoorlockUserInfoResponAllData dataRes = null; Action action = (topic, message) => { var gatewayID = topic.Split('/')[0]; var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); if (topic == gatewayID + "/" + "Error_Respon") { var gatewayTemp = new ZbGateway() { Time = jobject.Value("Time"), DataID = jobject.Value("Data_ID"), CurrentGateWayId = Gateway.getGatewayBaseInfo.gwID }; var temp = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (temp == null) { dataRes = new AlldoorlockUserInfoResponAllData { errorMessageBase = "网关错误回复,且数据是空" }; } else { dataRes = new AlldoorlockUserInfoResponAllData { errorResponData = temp, errorMessageBase = ErrorMess(temp.Error) }; } } if (topic == gatewayID + "/" + "Doorlock/GetAlldoorlockUserInfoRsp") { var gatewayTemp = new ZbGateway() { DeviceID = jobject.Value("Device_ID"), DeviceAddr = jobject.Value("DeviceAddr"), DeviceEpoint = jobject.Value("Epoint"), CurrentGateWayId = Gateway.getGatewayBaseInfo.gwID }; var tempData = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (tempData == null) { dataRes = new AlldoorlockUserInfoResponAllData { errorMessageBase = "网关返回的数据为空" }; } else { dataRes = new AlldoorlockUserInfoResponAllData { alldoorlockUserInfoResData = tempData }; DebugPrintLog($"UI收到通知后的主题_{ topic}"); } } }; Gateway.Actions += action; DebugPrintLog("门锁Doorlock/GetAlldoorlockUserInfoRsp_Actions 启动" + System.DateTime.Now.ToString()); try { var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 6100 } }; Gateway.Send("DoorLock/test", jObject.ToString()); } catch { } var dateTime = DateTime.Now; while ((DateTime.Now - dateTime).TotalMilliseconds < WaitReceiveDataTime) { await System.Threading.Tasks.Task.Delay(10); if (dataRes != null) { break; } } if ((DateTime.Now - dateTime).TotalMilliseconds > WaitReceiveDataTime) { dataRes = new AlldoorlockUserInfoResponAllData { errorMessageBase = " 回复超时,请重新操作" }; } Gateway.Actions -= action; DebugPrintLog("门锁Doorlock/GetAlldoorlockUserInfoRsp_Actions 退出" + System.DateTime.Now.ToString()); return dataRes; }); } /// ///获取所有门锁所有用户信息 /// public class AlldoorlockUserInfoResponAllData { /// /// 错误信息 /// public string errorMessageBase; /// /// 网关信息错误反馈 /// 当网关接收到客户端信息后,出现以下异常情况将反馈错误。 /// public ErrorResponData errorResponData; /// /// 获取所有门锁所有用户信息 /// public AlldoorlockUserInfoResData alldoorlockUserInfoResData; } /// ///获取所有门锁所有用户信息 /// public class AlldoorlockUserInfoResData { /// /// 事件触发 /// public int doorlockUserInfoRecordSum; /// /// 事件 /// public int OperationEventCode; /// /// 设备当前时间的时间戳 /// public int ZigbeeLocalTime; } #endregion #region 获取单个门锁单个用户信息 /// ///获取单个门锁单个用户信息 ///userId:门锁本地用户Id /// public async System.Threading.Tasks.Task GetdoorlockUserInfoByMACEPUserIdAsync(int userId) { if (Gateway == null) { return null; } return await System.Threading.Tasks.Task.Run(async () => { UserInfoByMACEPUserIdResponAllData dataRes = null; Action action = (topic, message) => { var gatewayID = topic.Split('/')[0]; var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); if (topic == gatewayID + "/" + "Error_Respon") { var gatewayTemp = new ZbGateway() { Time = jobject.Value("Time"), DataID = jobject.Value("Data_ID"), CurrentGateWayId = Gateway.getGatewayBaseInfo.gwID }; var temp = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (temp == null) { dataRes = new UserInfoByMACEPUserIdResponAllData { errorMessageBase = "网关错误回复,且数据是空" }; } else { dataRes = new UserInfoByMACEPUserIdResponAllData { errorResponData = temp, errorMessageBase = ErrorMess(temp.Error) }; } } if (topic == gatewayID + "/" + "Doorlock/GetdoorlockUserInfoByMACEPUserIdRsp") { var gatewayTemp = new ZbGateway() { DeviceID = jobject.Value("Device_ID"), DeviceAddr = jobject.Value("DeviceAddr"), DeviceEpoint = jobject.Value("Epoint"), CurrentGateWayId = Gateway.getGatewayBaseInfo.gwID }; var tempData = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (tempData == null) { dataRes = new UserInfoByMACEPUserIdResponAllData { errorMessageBase = "网关返回的数据为空" }; } else { dataRes = new UserInfoByMACEPUserIdResponAllData { userInfoByMACEPUserIdRspResData = tempData }; DebugPrintLog($"UI收到通知后的主题_{ topic}"); } } }; Gateway.Actions += action; DebugPrintLog("门锁Doorlock/GetdoorlockUserInfoByMACEPUserIdRsp 启动" + System.DateTime.Now.ToString()); try { var jObject = new JObject { { "DeviceAddr", DeviceAddr }, { "Epoint", DeviceEpoint }, { "Cluster_ID", 0 }, { "Command", 6102 } }; var data = new JObject { { "UserId", userId } }; jObject.Add("Data", data); Gateway.Send("DoorLock/test", jObject.ToString()); } catch { } var dateTime = DateTime.Now; while ((DateTime.Now - dateTime).TotalMilliseconds < WaitReceiveDataTime) { await System.Threading.Tasks.Task.Delay(10); if (dataRes != null) { break; } } if ((DateTime.Now - dateTime).TotalMilliseconds > WaitReceiveDataTime) { dataRes = new UserInfoByMACEPUserIdResponAllData { errorMessageBase = " 回复超时,请重新操作" }; } Gateway.Actions -= action; DebugPrintLog("门锁Doorlock/GetdoorlockUserInfoByMACEPUserIdRsp 退出" + System.DateTime.Now.ToString()); return dataRes; }); } /// ///获取单个门锁单个用户信息 /// public class UserInfoByMACEPUserIdResponAllData { /// /// 错误信息 /// public string errorMessageBase; /// /// 网关信息错误反馈 /// 当网关接收到客户端信息后,出现以下异常情况将反馈错误。 /// public ErrorResponData errorResponData; /// /// 获取单个门锁单个用户信息 /// public UserInfoByMACEPUserIdRspResData userInfoByMACEPUserIdRspResData; } /// ///获取所有门锁所有用户信息 /// public class UserInfoByMACEPUserIdRspResData { /// /// 事件触发 /// public int OperationEventSoure; /// /// 事件 /// public int OperationEventCode; /// /// 设备当前时间的时间戳 /// public int ZigbeeLocalTime; } #endregion */ #region 临时密码信息 /// /// 临时密码本地存储对象 /// public TempPasswordObj tempPasswordObj = new TempPasswordObj(); /// /// 临时密码本地对象 /// [System.Serializable] public class TempPasswordObj { /// /// 门锁有效时间 /// public int validTime; /// /// 门锁时间 /// public int times; } #endregion #region 指纹信息 public async System.Threading.Tasks.Task GetFingerprintAsync() { FingerprintInfo result = null; return result; } /// /// 用户指纹列表 /// public List fingerprintList = new List(); /// /// 用户指纹列表信息 /// [System.Serializable] public class FingerprintInfo { /// /// 指纹备注 /// public string fingerprintRemark = string.Empty; /// /// 指纹图片 /// public string fingerprintImage = string.Empty; /// /// 指纹ID /// public int userFingerprintID; /// /// 指纹目标列表 /// public readonly List sceneFingerprintTargetList = new List(); } #endregion #region 密码信息 public PasswordInfo GetPasswordAsync() { return null; } /// /// 用户密码列表 /// public List passwordList = new List(); /// /// 用户密码列表信息 /// [System.Serializable] public class PasswordInfo { /// /// 密码备注 /// public string passwordRemark = string.Empty; /// /// 密码图片 /// public string passwordImage = string.Empty; /// /// 密码ID /// public int userPasswordID; /// /// 密码目标列表 /// public readonly List scenePasswordTargetList = new List(); } #endregion #region 感应卡信息 public ProximityInfo GetProximityAsync() { return null; } /// /// 用户感应卡列表 /// public List proximityList = new List(); /// /// 用户感应卡列表信息 /// [System.Serializable] public class ProximityInfo { /// /// 感应卡备注 /// public string proximityRemark = string.Empty; /// /// 感应卡图片 /// public string proximityImage = string.Empty; /// /// 感应卡ID /// public int userProximityID; /// /// 感应卡目标列表 /// public readonly List sceneProximityTargetList = new List(); } #endregion #region 历史记录 /// /// 历史记录列表 /// public List historyRecordList = new List { }; /// /// 门锁状态和报警信息 /// [System.Serializable] public class HistoryRecord { /// /// 门锁开锁类型对应1 2 3 6 /// public byte type; /// /// 门锁开锁用户ID /// public int userID; /// /// 年 /// public string year; /// /// 月 /// public string month; /// /// 日 /// public string day; /// /// 时 /// public string hour; /// /// 分 /// public string minute; /// /// 秒 /// public string second; } #endregion #region 私有命令 #region 回复默认响应的控制 /// ///默认响应控制 /// passData:透传数据 /// public async System.Threading.Tasks.Task DefaultControlAsync(string passData) { ResponseAllData result = null; if (Gateway == null) { result = new ResponseAllData { errorMessageBase = "当前没有网关" }; return result; } return await System.Threading.Tasks.Task.Run(async () => { Action action = (topic, message) => { var gatewayID = topic.Split('/')[0]; var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); if (topic == gatewayID + "/" + "Error_Respon") { var gatewayTemp = new ZbGateway() { Time = jobject.Value("Time"), DataID = jobject.Value("Data_ID"), CurrentGateWayId = Gateway.getGatewayBaseInfo.gwID }; var temp = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (temp == null) { result = new ResponseAllData { errorMessageBase = "网关错误回复,且数据是空" }; } else { result = new ResponseAllData { errorResponData = temp, errorMessageBase = ErrorMess(temp.Error) }; } } if (topic == gatewayID + "/" + "ZbDataPassthrough") { var gatewayTemp = new ZbGateway() { DataID = jobject.Value("Data_ID") }; gatewayTemp.clientDataPassthroughResponseData = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (gatewayTemp.clientDataPassthroughResponseData == null) { result = new ResponseAllData { errorMessageBase = "网关返回的数据为空" }; } else { if (gatewayTemp.clientDataPassthroughResponseData?.PassData != null) { var data = gatewayTemp.clientDataPassthroughResponseData.PassData; if (data.Length == 16) { var command = data[4].ToString() + data[5].ToString() + data[2].ToString() + data[3].ToString(); if (command == "0002") { var tempD = new ResponseData(); tempD.command = Convert.ToInt32(data[10].ToString() + data[11].ToString() + data[12].ToString() + data[13].ToString(), 16); tempD.status = Convert.ToInt32(data[14].ToString() + data[15].ToString(), 16); result = new ResponseAllData { responseData = tempD }; DebugPrintLog($"UI收到通知后的主题_command:0402_{ topic}"); } } } } } }; Gateway.Actions += action; DebugPrintLog("ClientDataPassthrough_Actions 启动" + System.DateTime.Now.ToString()); try { var jObject = new JObject { { "DeviceAddr", DeviceAddr }, { "Epoint", 200 }, { "Cluster_ID", 64513 }, { "Command", 0 } }; var data = new JObject { { "PassData", passData } }; jObject.Add("Data", data); Gateway.Send(("ClientDataPassthrough"), jObject.ToString()); } catch { } var dateTime = DateTime.Now; while ((DateTime.Now - dateTime).TotalMilliseconds < 9000)// WaitReceiveDataTime) { await System.Threading.Tasks.Task.Delay(10); if (result != null) { break; } } if ((DateTime.Now - dateTime).TotalMilliseconds > WaitReceiveDataTime) { result = new ResponseAllData { errorMessageBase = " 回复超时,请重新操作" }; } Gateway.Actions -= action; DebugPrintLog("ClientDataPassthrough_Actions 退出" + System.DateTime.Now.ToString()); return result; }); } #endregion #region 用户管理发送数据 /// /// 用户管理发送数据 /// public string SetUserAccessData(int userId, AccessType accessType) { string data = ""; string dataLength = "07"; string dataComand1 = "50"; string dataComand2 = "04"; string dataSerialNum = "01"; string addDataLength = "03"; string delUserTypeStr = ""; string userIdStr = ""; try { switch ((int)accessType) { case 0: delUserTypeStr = "00"; break; case 1: delUserTypeStr = "01"; break; case 2: delUserTypeStr = "20"; break; case 3: delUserTypeStr = "21"; break; } var sbString = new System.Text.StringBuilder(); string temp = Convert.ToString(userId, 16); switch (temp.Length) { case 1: userIdStr = "0" + temp + "00"; break; case 2: userIdStr = temp + "00"; break; case 3: var thirdBit = temp.Substring(temp.Length - 2, 1); userIdStr = temp + "0" + thirdBit; break; case 4: userIdStr = temp; break; } sbString.Append(userIdStr.ToString().ToUpper()); data = dataLength + dataComand1 + dataComand2 + dataSerialNum + addDataLength + delUserTypeStr + sbString; } catch { }; return data; } #endregion #region 远程发送数据 /// /// 远程发送数据 /// public string RemoteData(string keyPassword, string password, string fixedPassword = "190605") { string data = ""; string dataLength = "09"; string dataComand1 = "62"; string dataComand2 = "04"; string dataSerialNum = "01"; string addDataLength = "04"; string passwordStr = ""; try { int keyPasswordInt = System.Convert.ToInt32(keyPassword, 16); int passwordInt = System.Convert.ToInt32(password, 16); var fixedPasswordInt = System.Convert.ToInt32(fixedPassword, 16); var pawStr = System.Convert.ToString((keyPasswordInt ^ passwordInt) + fixedPasswordInt, 16); pawStr = pawStr.PadLeft(8, '0'); for (int i = 6; i >= 0; i = i - 2) { passwordStr += passwordStr.Substring(i, 2); } data = dataLength + dataComand1 + dataComand2 + dataSerialNum + addDataLength + passwordStr; } catch { }; return data; } #endregion #region 临时密码发送数据 /// /// 临时密码发送数据 /// public string TempPasswordData(string keyPassword, string password, System.DateTime startTime, System.DateTime endTime, string fixedPassword = "190605") { string data = ""; string dataLength = "14";//十进制是19 string dataComand1 = "63"; string dataComand2 = "04"; string dataSerialNum = "01"; string addDataLength = "0c"; string passwordStr = ""; string vaildTimeStr = ""; string invalidTimeStr = ""; try { int keyPasswordInt = System.Convert.ToInt32(keyPassword, 16); int passwordInt = System.Convert.ToInt32(password, 16); var fixedPasswordInt = System.Convert.ToInt32(fixedPassword, 16); var pawStr = System.Convert.ToString((keyPasswordInt ^ passwordInt) + fixedPasswordInt, 16); pawStr = pawStr.PadLeft(8, '0'); for (int i = 6; i >= 0; i = i - 2) { passwordStr += passwordStr.Substring(i, 2); } var startTimeStr = System.Convert.ToString(GetUnixTimeStamp(startTime, false), 16); var endTimeStr = System.Convert.ToString(GetUnixTimeStamp(endTime, false), 16); for (int i = 6; i >= 0; i = i - 2) { vaildTimeStr += startTimeStr.Substring(i, 2); invalidTimeStr += endTimeStr.Substring(i, 2); } data = dataLength + dataComand1 + dataComand2 + dataSerialNum + addDataLength + passwordStr + vaildTimeStr + vaildTimeStr; } catch { }; return data; } #endregion #region 获取门锁密钥 /// /// 门锁随机密码 /// 获取加密的随机密钥,返回的密钥经过一个简单的加法加密加上0x190605,因此获取的密钥需要减上0x190605 /// /// async System.Threading.Tasks.Task GetkeyPassword() { var result = await GetKeyPassworAsync(); if (result == null || result.keyPassword == null) { return ""; } return result.keyPassword; } /// ///获取门锁密钥 /// public async System.Threading.Tasks.Task GetKeyPassworAsync(int keyType = 0) { KeyPasswordInfo result = null; if (Gateway == null) { result = new KeyPasswordInfo { errorMessageBase = "当前没有网关" }; return result; } return await System.Threading.Tasks.Task.Run(async () => { Action action = (topic, message) => { var gatewayID = topic.Split('/')[0]; var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); if (topic == gatewayID + "/" + "Error_Respon") { var gatewayTemp = new ZbGateway() { Time = jobject.Value("Time"), DataID = jobject.Value("Data_ID"), CurrentGateWayId = Gateway.getGatewayBaseInfo.gwID }; var temp = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (temp == null) { result = new KeyPasswordInfo { errorMessageBase = "网关错误回复,且数据是空" }; } else { result = new KeyPasswordInfo { errorResponData = temp, errorMessageBase = ErrorMess(temp.Error) }; } } if (topic == gatewayID + "/" + "ZbDataPassthrough") { var gatewayTemp = new ZbGateway() { DataID = jobject.Value("Data_ID") }; gatewayTemp.clientDataPassthroughResponseData = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (gatewayTemp.clientDataPassthroughResponseData == null) { result = new KeyPasswordInfo { errorMessageBase = "网关返回的数据为空" }; } else { if (gatewayTemp.clientDataPassthroughResponseData?.PassData != null) { var data = gatewayTemp.clientDataPassthroughResponseData.PassData; if (data.Length == 14) { var command = data[4].ToString() + data[5].ToString() + data[2].ToString() + data[3].ToString(); if (command == "0461") { var kType = Convert.ToInt32(data[10].ToString() + data[11].ToString(), 16); var keyPassword = data[12].ToString() + data[13].ToString() + data[14].ToString() + data[15].ToString() + data[16].ToString() + data[17].ToString() + data[18].ToString() + data[19].ToString(); result = new KeyPasswordInfo { keyType = kType, keyPassword = keyPassword }; System.Console.WriteLine($"UI收到通知后的主题_command:0406_{ topic}"); } } } } } }; Gateway.Actions += action; System.Console.WriteLine("ClientDataPassthrough_Actions 启动" + System.DateTime.Now.ToString()); try { var passData = KeyPasswordData(keyType); var jObject = new JObject { { "DeviceAddr", DeviceAddr }, { "Epoint", 200 }, { "Cluster_ID", 64513 }, { "Command", 0 } }; var data = new JObject { { "PassData", passData } }; jObject.Add("Data", data); Gateway.Send(("ClientDataPassthrough"), jObject.ToString()); } catch { } var dateTime = DateTime.Now; while ((DateTime.Now - dateTime).TotalMilliseconds < 9000)//WaitReceiveDataTime) { await System.Threading.Tasks.Task.Delay(10); if (result != null) { break; } } if ((DateTime.Now - dateTime).TotalMilliseconds > WaitReceiveDataTime) { result = new KeyPasswordInfo { errorMessageBase = " 回复超时,请重新操作" }; } Gateway.Actions -= action; System.Console.WriteLine("ClientDataPassthrough_Actions 退出" + System.DateTime.Now.ToString()); return result; }); } /// /// 获取门锁密钥 /// string KeyPasswordData(int keyType) { string data = ""; string dataLength = "05"; string dataComand1 = "60"; string dataComand2 = "04"; string dataSerialNum = "01"; string addDataLength = "01"; string keyTypeData = ""; try { var tempTypeString = new System.Text.StringBuilder(); var temp = Convert.ToString(keyType, 16); switch (temp.Length) { case 1: keyTypeData = "0" + temp; break; case 2: keyTypeData = temp; break; } tempTypeString.Append(keyTypeData.ToString().ToUpper()); data = dataLength + dataComand1 + dataComand2 + dataSerialNum + addDataLength + tempTypeString; } catch { }; return data; } /// /// 获取门锁密钥回复 /// [System.Serializable] public class KeyPasswordInfo { /// /// 错误信息 /// public string errorMessageBase; /// /// 网关信息错误反馈 /// 当网关接收到客户端信息后,出现以下异常情况将反馈错误。 /// public ErrorResponData errorResponData; /// ///密钥类型 /// /// public int keyType = -1; /// /// 密钥 /// public string keyPassword; } #endregion #region 读取锁上信息 /// ///读取锁上信息 /// public async System.Threading.Tasks.Task GetDoorlockUserInfoAsync(int keyType = 0) { DoorlockUserInfo result = null; if (Gateway == null) { result = new DoorlockUserInfo { errorMessageBase = "当前没有网关" }; return result; } return await System.Threading.Tasks.Task.Run(async () => { Action action = (topic, message) => { var gatewayID = topic.Split('/')[0]; var jobject = Newtonsoft.Json.Linq.JObject.Parse(message); if (topic == gatewayID + "/" + "Error_Respon") { var gatewayTemp = new ZbGateway() { Time = jobject.Value("Time"), DataID = jobject.Value("Data_ID"), CurrentGateWayId = Gateway.getGatewayBaseInfo.gwID }; var temp = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (temp == null) { result = new DoorlockUserInfo { errorMessageBase = "网关错误回复,且数据是空" }; } else { result = new DoorlockUserInfo { errorResponData = temp, errorMessageBase = ErrorMess(temp.Error) }; } } if (topic == gatewayID + "/" + "ZbDataPassthrough") { var gatewayTemp = new ZbGateway() { DataID = jobject.Value("Data_ID") }; gatewayTemp.clientDataPassthroughResponseData = Newtonsoft.Json.JsonConvert.DeserializeObject(jobject["Data"].ToString()); if (gatewayTemp.clientDataPassthroughResponseData == null) { result = new DoorlockUserInfo { errorMessageBase = "网关返回的数据为空" }; } else { if (gatewayTemp.clientDataPassthroughResponseData?.PassData != null) { var data = gatewayTemp.clientDataPassthroughResponseData.PassData; if (data.Length == 14) { var command = data[4].ToString() + data[5].ToString() + data[2].ToString() + data[3].ToString(); if (command == "0452") { //var kType = Convert.ToInt32(data[10].ToString() + data[11].ToString(), 16); //var keyPassword = data[12].ToString() + data[13].ToString() + data[14].ToString() + data[15].ToString() + data[16].ToString() + data[17].ToString() + data[18].ToString() + data[19].ToString(); //result = new DoorlockUserInfo { keyType = kType, keyPassword = keyPassword }; System.Console.WriteLine($"UI收到通知后的主题_command:0451_{ topic}"); } } } } } }; Gateway.Actions += action; System.Console.WriteLine("ClientDataPassthrough_Actions 启动" + System.DateTime.Now.ToString()); try { var passData = KeyPasswordData(keyType); var jObject = new JObject { { "DeviceAddr", DeviceAddr }, { "Epoint", 200 }, { "Cluster_ID", 64513 }, { "Command", 0 } }; var data = new JObject { { "PassData", passData } }; jObject.Add("Data", data); Gateway.Send(("ClientDataPassthrough"), jObject.ToString()); } catch { } var dateTime = DateTime.Now; while ((DateTime.Now - dateTime).TotalMilliseconds < 9000)//WaitReceiveDataTime) { await System.Threading.Tasks.Task.Delay(10); if (result != null) { break; } } if ((DateTime.Now - dateTime).TotalMilliseconds > WaitReceiveDataTime) { result = new DoorlockUserInfo { errorMessageBase = " 回复超时,请重新操作" }; } Gateway.Actions -= action; System.Console.WriteLine("ClientDataPassthrough_Actions 退出" + System.DateTime.Now.ToString()); return result; }); } /// /// 读取锁上信息 /// string DoorlockUserData(int userType) { string data = ""; string dataLength = "05"; string dataComand1 = "51"; string dataComand2 = "04"; string dataSerialNum = "01"; string addDataLength = "01"; string keyTypeData = ""; try { var tempTypeString = new System.Text.StringBuilder(); var temp = Convert.ToString(userType, 16); switch (temp.Length) { case 1: keyTypeData = "0" + temp; break; case 2: keyTypeData = temp; break; } tempTypeString.Append(keyTypeData.ToString().ToUpper()); data = dataLength + dataComand1 + dataComand2 + dataSerialNum + addDataLength + tempTypeString; } catch { }; return data; } /// /// 读取锁上信息回复 /// [System.Serializable] public class DoorlockUserInfo { /// /// 错误信息 /// public string errorMessageBase; /// /// 网关信息错误反馈 /// 当网关接收到客户端信息后,出现以下异常情况将反馈错误。 /// public ErrorResponData errorResponData; } public class DoorLockUserDetailData { /// /// 类型 /// public int userType; /// /// 数据包总数 /// public int totalNum; /// /// 数据包序号 /// public int currentNum; /// /// 用户数据 /// public byte userData; } #endregion public enum AccessType { /// /// 0x00 删除全部单次用户 /// DelAllUsers = 0, /// /// 0x01 删除指定用户(按编号) /// DelCurrentUser = 1, /// /// 0x20 冻结指定用户 /// DisEnable = 2, /// /// 0x21 解冻指定用户 /// Enable = 3, } /// /// 获取从格林威治时间到当前某一时刻的总毫秒数 /// /// 北京时间 /// 精确到毫秒,否到秒 /// 返回一个长整数时间戳 public static long GetUnixTimeStamp(DateTime dateTime, bool accurateToMilliseconds) { DateTime startTime = TimeZoneInfo.ConvertTimeToUtc(new DateTime(1970, 1, 1, 8, 0, 0));//北京所在东八区 DateTime endTime = TimeZoneInfo.ConvertTimeToUtc(dateTime); return (long)(accurateToMilliseconds ? (endTime - startTime).TotalMilliseconds : (endTime - startTime).TotalSeconds); } /// /// 将UNIX时间戳转为北京时间 /// /// 时间戳 /// 精确到毫秒,佛为秒 /// public static DateTime GetLocalTime(long unixTimeStamp, bool accurateToMilliseconds) { DateTime startTime = TimeZoneInfo.ConvertTimeToUtc(new DateTime(1970, 1, 1, 8, 0, 0));//北京所在东八区 return (accurateToMilliseconds ? startTime.AddMilliseconds(unixTimeStamp) : startTime.AddSeconds(unixTimeStamp)).ToLocalTime(); } #endregion } }