/// <summary> /// Load token from local app data /// </summary> private UserDataInfo LoadToken() { string rootPath = Utils.GetAppTmpPath(); string targetDir = Path.Combine(rootPath, Config.ProfilesDir); if (!Directory.Exists(targetDir)) { UnityEngine.Debug.Log("LoadToken: not exists directory " + targetDir); return(new UserDataInfo()); } string fileDir = Path.Combine(targetDir, Config.TmpDataFileName); if (!File.Exists(fileDir)) { UnityEngine.Debug.Log("LoadToken: not exists file " + fileDir); return(new UserDataInfo()); } try { Stream stream = File.Open(fileDir, FileMode.Open); BinaryFormatter bformater = new BinaryFormatter(); UserDataInfo tokenInfo = (UserDataInfo)bformater.Deserialize(stream); stream.Close(); return(tokenInfo); } catch (System.Exception e) { UnityEngine.Debug.LogError("LoadToken: can not read user data : " + e.Message); return(new UserDataInfo()); } }
private void OnAuthorizedOK(object sender, string cortexToken) { if (!String.IsNullOrEmpty(cortexToken)) { UnityEngine.Debug.Log("Authorize successfully."); UserDataInfo tokenInfo = new UserDataInfo(); tokenInfo.CortexToken = cortexToken; tokenInfo.LastLoginTime = Utils.ISODateTimeToEpocTime(DateTime.Now); lock (_locker) { tokenInfo.EmotivId = _emotivId; _cortexToken = cortexToken; } // save token SaveToken(tokenInfo); // Save App version Utils.SaveAppVersion(Config.AppVersion); // get license information _ctxClient.GetLicenseInfo(cortexToken); } else { AuthorizedFailed(this, cortexToken); UnityEngine.Debug.Log("Invalid Token."); } }
private void OnRefreshTokenOK(object sender, string cortexToken) { UnityEngine.Debug.Log("The cortex token is refreshed successfully."); // load cortexToken UserDataInfo tokenInfo = new UserDataInfo(); tokenInfo.CortexToken = cortexToken; tokenInfo.LastLoginTime = Utils.ISODateTimeToEpocTime(DateTime.Now); lock (_locker) { tokenInfo.EmotivId = _emotivId; _cortexToken = cortexToken; } // save token SaveToken(tokenInfo); // get license information _ctxClient.GetLicenseInfo(cortexToken); }
/// <summary> /// Save token to local app data for next using /// </summary> private void SaveToken(UserDataInfo tokenSavedInfo) { string rootPath = Utils.GetAppTmpPath(); string targetDir = Path.Combine(rootPath, Config.ProfilesDir); if (!Directory.Exists(targetDir)) { try { // create directory Directory.CreateDirectory(targetDir); UnityEngine.Debug.Log("SaveCortexToken: create directory " + targetDir); } catch (Exception e) { UnityEngine.Debug.Log("Can not create directory: " + targetDir + " : failed: " + e.ToString()); return; } finally {} } string fileDir = Path.Combine(targetDir, Config.TmpDataFileName); try { using (var fileStream = new FileStream(fileDir, FileMode.Create)) { BinaryFormatter bformatter = new BinaryFormatter(); bformatter.Serialize(fileStream, tokenSavedInfo); // var data = JsonConvert.SerializeObject(tokenSavedInfo); // byte[] dataByte = new UTF8Encoding(true).GetBytes(data); // fileStream.Write(dataByte, 0, dataByte.Length); } UnityEngine.Debug.Log("Save token successfully."); } catch (Exception e) { UnityEngine.Debug.Log("Can not save token failed: " + e.ToString()); return; } }
/// <summary> /// Handle response message. /// A response means success message to distinguish from error object /// </summary> private void HandleResponse(string method, JToken data) { // UnityEngine.Debug.Log("handleResponse: " + method); if (method == "queryHeadsets") { List <Headset> headsetLists = new List <Headset>(); foreach (JObject item in data) { headsetLists.Add(new Headset(item)); } QueryHeadsetOK(this, headsetLists); } else if (method == "controlDevice") { string command = (string)data["command"]; if (command == "connect") { string message = (string)data["message"]; } else if (command == "disconnect") { HeadsetDisConnectedOK(this, true); } } else if (method == "getUserLogin") { JArray users = (JArray)data; UserDataInfo loginData = new UserDataInfo(); if (users.Count > 0) { foreach (JObject user in users) { if (user["currentOSUId"].ToString() == user["loggedInOSUId"].ToString()) { loginData.EmotivId = user["username"].ToString(); DateTime lastLoginTime = user.Value <DateTime>("lastLoginTime"); loginData.LastLoginTime = Utils.ISODateTimeToEpocTime(lastLoginTime); } } } GetUserLoginDone(this, loginData); } else if (method == "hasAccessRight") { bool hasAccessRight = (bool)data["accessGranted"]; HasAccessRightOK(this, hasAccessRight); } else if (method == "requestAccess") { bool hasAccessRight = (bool)data["accessGranted"]; ORequestAccessDone(this, hasAccessRight); } else if (method == "generateNewToken") { string cortexToken = data["cortexToken"].ToString(); RefreshTokenOK(this, cortexToken); } else if (method == "getLicenseInfo") { License lic = new License(data["license"]); GetLicenseInfoDone(this, lic); } else if (method == "getUserInformation") { //TODO } else if (method == "authorize") { string token = (string)data["cortexToken"]; if (data["warning"] != null) { JObject warning = (JObject)data["warning"]; string warningMessage = warning["message"].ToString(); UnityEngine.Debug.Log("User has not accepted eula. Please accept EULA on EMOTIV App to proceed."); EULANotAccepted(this, warningMessage); } AuthorizeOK(this, token); } else if (method == "createSession") { string sessionId = (string)data["id"]; string status = (string)data["status"]; string appId = (string)data["appId"]; JObject headset = (JObject)data["headset"]; string headsetId = headset["id"].ToString(); CreateSessionOK(this, new SessionEventArgs(sessionId, status, appId, headsetId)); } else if (method == "updateSession") { string sessionId = (string)data["id"]; string status = (string)data["status"]; string appId = (string)data["appId"]; JObject headset = (JObject)data["headset"]; string headsetId = headset["id"].ToString(); UpdateSessionOK(this, new SessionEventArgs(sessionId, status, appId, headsetId)); } else if (method == "createRecord") { Record record = new Record((JObject)data["record"]); CreateRecordOK(this, record); } else if (method == "stopRecord") { Record record = new Record((JObject)data["record"]); StopRecordOK(this, record); } else if (method == "updateRecord") { Record record = new Record((JObject)data); UpdateRecordOK(this, record); } else if (method == "queryRecords") { int count = (int)data["count"]; JArray records = (JArray)data["records"]; List <Record> recordLists = new List <Record>(); foreach (JObject ele in records) { recordLists.Add(new Record(ele)); } QueryRecordsDone(this, recordLists); } else if (method == "deleteRecord") { JArray successList = (JArray)data["success"]; JArray failList = (JArray)data["failure"]; DeleteRecordsDone(this, new MultipleResultEventArgs(successList, failList)); } else if (method == "unsubscribe") { JArray successList = (JArray)data["success"]; JArray failList = (JArray)data["failure"]; UnSubscribeDataDone(this, new MultipleResultEventArgs(successList, failList)); } else if (method == "subscribe") { // UnityEngine.Debug.Log("################subscribe: "); JArray successList = (JArray)data["success"]; JArray failList = (JArray)data["failure"]; SubscribeDataDone(this, new MultipleResultEventArgs(successList, failList)); } else if (method == "injectMarker") { JObject marker = (JObject)data["marker"]; InjectMarkerOK(this, marker); } else if (method == "updateMarker") { JObject marker = (JObject)data["marker"]; UpdateMarkerOK(this, marker); } else if (method == "getDetectionInfo") { GetDetectionInfoDone(this, (JObject)data); } else if (method == "getCurrentProfile") { if (data["name"] == null) { GetCurrentProfileDone(this, ""); } else { GetCurrentProfileDone(this, (string)data["name"]); } } else if (method == "setupProfile") { string action = (string)data["action"]; string profileName = (string)data["name"]; if (action == "create") { CreateProfileOK(this, profileName); } else if (action == "load") { LoadProfileOK(this, profileName); } else if (action == "save") { SaveProfileOK(this, profileName); } else if (action == "unload") { UnloadProfileDone(this, true); } else if (action == "rename") { RenameProfileOK(this, profileName); } else if (action == "delete") { DeleteProfileOK(this, profileName); } } else if (method == "queryProfile") { QueryProfileOK(this, (JArray)data); } else if (method == "training") { TrainingOK(this, (JObject)data); } else if (method == "getTrainingTime") { GetTrainingTimeDone(this, (double)data["time"]); } }
private void OnGetUserLoginDone(object sender, UserDataInfo loginData) { UnityEngine.Debug.Log("OnGetUserLoginDone."); // if emotivId is not empty -> has login user if (!String.IsNullOrEmpty(loginData.EmotivId)) { // stop timer if (_waitUserLoginTimer != null && _waitUserLoginTimer.Enabled) { _waitUserLoginTimer.Stop(); } // save emotivId lock (_locker) _emotivId = loginData.EmotivId; double lastLoginTime = loginData.LastLoginTime; // notify change sate ConnectServiceStateChanged(this, ConnectToCortexStates.Authorizing); // If app version different saved app version if (!Utils.IsSameAppVersion(Config.AppVersion)) { // re authorize again UnityEngine.Debug.Log("There are new version of App. Need to re-authorize."); _ctxClient.HasAccessRights(); return; } // load cortexToken UserDataInfo tokenInfo = LoadToken(); string savedEmotivId = tokenInfo.EmotivId; double savedTime = tokenInfo.LastLoginTime; // Re-Authorize if saved emotivId different logged in emotivId if (string.IsNullOrEmpty(savedEmotivId) || savedEmotivId != loginData.EmotivId) { // re authorize again UnityEngine.Debug.Log("There are new logging user. Need to re-authorize."); _ctxClient.HasAccessRights(); return; } if (lastLoginTime >= savedTime) { UnityEngine.Debug.Log("User has just re-logined. Need to re-authorize."); _ctxClient.HasAccessRights(); return; } UnityEngine.Debug.Log("Refresh token for next using."); // genereate new token _ctxClient.GenerateNewToken(tokenInfo.CortexToken); } else { bool checkEmotivAppRequire = true; // require to check emotiv apps installed or not #if UNITY_EDITOR checkEmotivAppRequire = false; #endif // check EmotivApp has installed if (Utils.CheckEmotivAppInstalled(Config.EmotivAppsPath, checkEmotivAppRequire)) { ConnectServiceStateChanged(this, ConnectToCortexStates.Login_notYet); } else { // EMOTIVApp not found ConnectServiceStateChanged(this, ConnectToCortexStates.EmotivApp_NotFound); } // start waiting user login SetWaitUserLoginTimer(); _waitUserLoginTimer.Start(); UnityEngine.Debug.Log("You must login via EMOTIV App before working with Cortex"); } }