public void SendWorkoutStatusNotification() { if (controlState == BLEProtocol.WorkoutControlState.Stop) { timestamp = 0; count = 0; rpm = 0; heartrate = 0; } else if (controlState == BLEProtocol.WorkoutControlState.Start) { ++timestamp; count += 2; rpm = 120; heartrate = 0; } BLEDebug.LogInfo("Sending WorkoutStatusNotification"); BLEPluginInstance.SendMessage("ReceivePluginMessage", BLEProtocol.ConvertBytesToString( BLENotify.PrepareWorkoutStatusBytes( timestamp, count, rpm, heartrate ) ) ); }
public static string ConvertBytesToString(byte[] data) { string message = System.Convert.ToBase64String(data); BLEDebug.LogInfo("Converted Byte to String: " + message); return(message); }
private static void ReceiveResistanceLevel(byte[] data) { BLEDebug.LogInfo("Resistance Level Received"); int level = data[BLEProtocol.Index.ResistanceLevel]; _bikeListener.OnReceiveResistanceLevel(level); }
private static void ReceiveWorkoutStatus(byte[] data) { BLEDebug.LogInfo("Workout Status Received"); int timeStamp = BLEProtocol.ExtractDataInt( BLEProtocol.Index.TimeStamp.Begin, BLEProtocol.Index.TimeStamp.End, data ); int count = BLEProtocol.ExtractDataInt( BLEProtocol.Index.Count.Begin, BLEProtocol.Index.Count.End, data ); int rpm = BLEProtocol.ExtractDataInt( BLEProtocol.Index.RPM.Begin, BLEProtocol.Index.RPM.End, data ); int heartRate = data[BLEProtocol.Index.HeartRate]; _bikeListener.OnReceiveWorkoutStatus(timeStamp, count, rpm, heartRate); }
private static void ReceiveWorkoutControlState(byte[] data) { BLEDebug.LogInfo("Workout Control State Received"); int controlState = data[BLEProtocol.Index.WorkoutControlState]; _bikeListener.OnReceiveWorkoutControlState(controlState); }
async void ConnectClient() { await API.Instance.Login("test", "password"); await API.Instance.GetCustomization(); BLEDebug.LogInfo(API.Instance.CharacterModelId); await API.Instance.SetCustomization("model2"); BLEDebug.LogInfo(API.Instance.CharacterModelId); await API.Instance.SetCustomization("model1"); BLEDebug.LogInfo(API.Instance.CharacterModelId); await API.Instance.CreateMatchmakingTicket(); do { await API.Instance.CheckMatchmakingTicketStatus(); } while (API.Instance.Status == "SEARCHING" || API.Instance.Status == "PLACING"); if (API.Instance.Status == "COMPLETED") { BLEDebug.LogInfo("Connecting to GameLift Realtime Session"); BLEDebug.LogInfo($"DNS: {API.Instance.DnsName}"); BLEDebug.LogInfo($"TCP Port: {API.Instance.TcpPort}"); BLEDebug.LogInfo($"UDP Port: {API.Instance.UdpPort}"); BLEDebug.LogInfo($"PlayerSessionId: {API.Instance.PlayerSessionId}"); RealTimeClient.Instance.Connect(API.Instance.PlayerId, API.Instance.DnsName, API.Instance.TcpPort, API.Instance.UdpPort, ConnectionType.RT_OVER_WEBSOCKET, API.Instance.PlayerSessionId, new byte[0]); } }
public async Task CheckMatchmakingTicketStatus() { BLEDebug.LogInfo("Checking MatchMaking Ticket Status"); FlatJSON fJSON = new FlatJSON(); fJSON.Add("TicketId", TicketId); HttpContent req = fJSON.SerializeContent(); HttpResponseMessage result = await client.PostAsync("https://echelon.3pointlabs.org/matchmaking/status", req); string body = await result.Content.ReadAsStringAsync(); BLEDebug.LogInfo("Ticket " + body); fJSON.Deserialize(body); fJSON.TryGetStringValue("Status", out _Status); if (Status == "COMPLETED") { fJSON.TryGetStringValue("GameSessionArn", out _GameSessionArn); fJSON.TryGetStringValue("IpAddress", out _IpAddress); fJSON.TryGetStringValue("DnsName", out _DnsName); fJSON.TryGetIntValue("Port", out _TcpPort); fJSON.TryGetStringValue("PlayerSessionId", out _PlayerSessionId); FindAvailableUDPPort(); } }
public void OnReceiveResistanceLevelRange(int min, int max) { BLEDebug.LogInfo($"Resistance Level Range Received: ({min},{max})"); // TODO - Current implementation uses Units.Min/Max and ignores what the bike says Bike.Instance.ResistanceMin = min; Bike.Instance.ResistanceMax = max; }
public async Task Login(string username, string password) { CurrentLoginStatus = LoginStatus.LOGGING_IN; BLEDebug.LogInfo("Logging In"); FlatJSON fJSON = new FlatJSON(); fJSON.Add("username", username); fJSON.Add("password", password); HttpContent req = fJSON.SerializeContent(); var result = await client.PostAsync("https://echelon.3pointlabs.org/auth/login", req); string body = await result.Content.ReadAsStringAsync(); BLEDebug.LogInfo("Auth " + body); fJSON.Deserialize(body); fJSON.TryGetStringValue("username", out _PlayerId); fJSON.TryGetStringValue("idToken", out idToken); fJSON.TryGetStringValue("refreshToken", out refreshToken); fJSON.TryGetStringValue("accessToken", out accessToken); if (idToken != null) { // Set Token for Authentication client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(idToken); CurrentLoginStatus = LoginStatus.LOGGED_IN; } else { CurrentLoginStatus = LoginStatus.FAILED; } }
// Update is called once per frame public void Update() { timer += Time.deltaTime; if (east1.isDone) { pingEast1 = east1.time; } if (east2.isDone) { pingEast2 = east2.time; } if (timer >= pingInterval) { if (RealTimeClient.Instance.IsConnected()) { BLEDebug.LogInfo("Connected"); float[] playerPos = { 1, 2, 3 }; float progressDistance = 10; RealTimeClient.Instance.UpdateStats(0, 0, playerPos, progressDistance); } //BLEDebug.LogInfo("East1 Ping" + pingEast1); //BLEDebug.LogInfo("East2 Ping" + pingEast2); east1 = new UnityEngine.Ping("3.208.0.0"); east2 = new UnityEngine.Ping("3.14.0.0"); timer = 0.0f; } }
public void OnReceiveDeviceInformation(int modelID, string hardwareVersion, string firmwareVersion) { BLEDebug.LogInfo($"Device Info ModelID: {modelID}, Hardware Version: {hardwareVersion} Firmware Version: {firmwareVersion}"); Bike.Instance.ModelID = modelID; Bike.Instance.HardwareVersion = hardwareVersion; Bike.Instance.FirmwareVersion = firmwareVersion; }
private async void StartMatchMaking() { await API.Instance.CreateMatchmakingTicket(); do { BLEDebug.LogInfo("Checking Matchmaking Ticket Status"); await API.Instance.CheckMatchmakingTicketStatus(); } while (API.Instance.Status == "SEARCHING" || API.Instance.Status == "PLACING"); if (API.Instance.Status == "COMPLETED") { BLEDebug.LogInfo("Connecting to GameLift Realtime Session"); BLEDebug.LogInfo($"DNS: {API.Instance.DnsName}"); BLEDebug.LogInfo($"TCP Port: {API.Instance.TcpPort}"); BLEDebug.LogInfo($"UDP Port: {API.Instance.UdpPort}"); levelLoader.GetComponent <LevelLoader>().LoadLevel("EchelonDomeTrack"); // StartCoroutine("CheckConnectionV2"); } else { Debug.Log("API.Instance.Status != Connected"); } }
private static void ReceiveResistanceLevelRange(byte[] data) { BLEDebug.LogInfo("Resistance Level Range Received"); int minResistance = data[BLEProtocol.Index.ResistanceLevelRange.Min]; int maxResistance = data[BLEProtocol.Index.ResistanceLevelRange.Max]; _bikeListener.OnReceiveResistanceLevelRange(minResistance, maxResistance); }
private static void ReceiveErrorLog(byte[] data) { BLEDebug.LogInfo("Error Log Received"); int take = data.Length - (BLEProtocol.Index.ErrorLogStart + 1); byte[] log = data.Skip(BLEProtocol.Index.ErrorLogStart).Take(take).ToArray(); _bikeListener.OnReceiveErrorLog(log); }
public void OnDropdownSelect(Dropdown change) { BLEDebug.LogInfo("Changed #: " + change.value); BLEDebug.LogInfo("Name: " + found.ToArray()[change.value]); Bike.Instance.Addresses.TryGetValue(found.ToArray()[change.value], out string address); BLEDebug.LogInfo("Address: " + address); BLEPlugin.Instance.Connect(address); Bike.Instance.RegisterBikeListener(_bikeListener); }
IEnumerator SpawnCoroutine() { yield return(new WaitForSecondsRealtime(1.0f)); RealTimeClient.Instance.UpdateCustomization(PlayerPrefs.GetString("Model")); BLEDebug.LogInfo($"peerId :{RealTimeClient.Instance.peerId}, CharacterModelId: {API.Instance.CharacterModelId}"); Spawn(API.Instance.CharacterModelId, RealTimeClient.Instance.peerId); playerCam.GetComponent <CameraPivot>().SetTarget(players[RealTimeClient.Instance.peerId]); minimapCam.GetComponent <MinimapFollow>().target = players[RealTimeClient.Instance.peerId]; }
private void Awake() { //players = new GameObject[numRoutes]; players = new Dictionary <int, GameObject>(); RealTimeClient.Instance.CustomizationUpdate += SpawnPlayer; RealTimeClient.Instance.PlayerDisconnect += DespawnPlayer; BLEDebug.LogInfo($"Realtime PlayerId: {API.Instance.PlayerId}, PlayerSessionId: {API.Instance.PlayerSessionId}"); RealTimeClient.Instance.Connect(API.Instance.PlayerId, API.Instance.DnsName, API.Instance.TcpPort, API.Instance.UdpPort, ConnectionType.RT_OVER_WEBSOCKET, API.Instance.PlayerSessionId, new byte[0]); }
public void OnReceiveWorkoutStatus(int timestamp, int count, int rpm, int heartrate) { BLEDebug.LogInfo($"Timestamp: {timestamp}, Count: {count}, RPM: {rpm}, Heart rate {heartrate}"); Bike.Instance.Timestamp = timestamp; Bike.Instance.Count = count; Bike.Instance.RPM = rpm; Bike.Instance.Heartrate = heartrate; BLEDebug.LogInfo($"Timestamp: {Bike.Instance.Timestamp}, Count: {Bike.Instance.Count}, RPM: {Bike.Instance.RPM}, Heart rate {Bike.Instance.Heartrate}"); // TODO - Feed this to workout for calculations }
/** * Handle data received from the Realtime server */ private void OnDataReceived(object sender, DataReceivedEventArgs e) { FlatJSON fJSON = new FlatJSON(); BLEDebug.LogInfo("OPCODE " + e.OpCode + " Received, Data:" + BytesToString(e.Data)); switch (e.OpCode) { // handle message based on OpCode case OP_CODE_PLAYER_ACCEPTED: _peerId = e.Sender; OnPlayerAccepted(peerId); break; case OP_CODE_PLAYER_DISCONNECTED: Int32.TryParse(BytesToString(e.Data), out _peerId); OnPlayerDisconnected(peerId); break; case OP_CODE_RACE_START: OnRaceStart(); break; case OP_CODE_RACE_END: OnRaceEnd(); break; case OP_CODE_TIME_TILL_TERMINATE: int time; Int32.TryParse(BytesToString(e.Data), out time); OnNotifyTimeTillTerminate(time); break; case OP_CODE_STATS_UPDATE: fJSON.Deserialize(BytesToString(e.Data)); fJSON.TryGetIntValue("rotations", out int rotations); fJSON.TryGetIntValue("rpm", out int rpm); fJSON.TryGetFloatArray("playerPosition", out float[] playerPosition); fJSON.TryGetFloatValue("progressDistance", out float progressDistance); OnStatsUpdate(e.Sender, rotations, rpm, playerPosition, progressDistance); break; case OP_CODE_CUSTOMIZATION_UPDATE: fJSON.Deserialize(BytesToString(e.Data)); fJSON.TryGetStringValue("PlayerId", out string customplayer); fJSON.TryGetStringValue("characterModelId", out string characterModel); OnCustomizationUpdate(e.Sender, customplayer, characterModel); break; default: BLEDebug.LogWarning("Unknown OPCODE Received"); break; } }
public static byte[] PrepareGetCommandBytes(byte actionCode) { byte[] preparedBytes = new byte[] { StartByte, actionCode, 0x00, 0x00 }; // Calculate and set checksum preparedBytes[preparedBytes.Length - 1] = CalculateChecksum(preparedBytes); BLEDebug.LogInfo("Get HexByte Array: " + ByteArrayToHexString(preparedBytes)); return(preparedBytes); }
public async Task GetCustomization() { BLEDebug.LogInfo("Getting CharacterModelId"); FlatJSON fJSON = new FlatJSON(); HttpResponseMessage result = await client.GetAsync("https://echelon.3pointlabs.org/profile/customization"); string body = await result.Content.ReadAsStringAsync(); BLEDebug.LogInfo("CharacterModel " + body); fJSON.Deserialize(body); fJSON.TryGetStringValue("characterModelId", out _CharacterModelId); }
public void UpdateCustomization(string characterModelId) { BLEDebug.LogInfo("Sending Customization Update"); FlatJSON fJSON = new FlatJSON(); fJSON.Add("PlayerId", PlayerId); fJSON.Add("characterModelId", characterModelId); Client.SendMessage(Client.NewMessage(OP_CODE_CUSTOMIZATION_UPDATE) .WithDeliveryIntent(DeliveryIntent.Reliable) .WithTargetPlayer(Constants.PLAYER_ID_SERVER) .WithPayload(StringToBytes(fJSON.ToString()))); }
private static void ReceiveDeviceInformation(byte[] data) { BLEDebug.LogInfo("Device Information Received"); int modelID = data[BLEProtocol.Index.ModelID]; string hardwareVersion = String.Format( $"{data[BLEProtocol.Index.HardwareVersion.Major]}.{data[BLEProtocol.Index.HardwareVersion.Minor]}" ); string firmwareVersion = String.Format( $"{data[BLEProtocol.Index.FirmwareVersion.Major]}.{data[BLEProtocol.Index.FirmwareVersion.Minor]}.{data[BLEProtocol.Index.FirmwareVersion.Patch]}" ); _bikeListener.OnReceiveDeviceInformation(modelID, hardwareVersion, firmwareVersion); }
public static void ProcessReceiveData(byte[] data) { BLEDebug.LogInfo("BLEAction Processing Received Data"); // Ignore and log invalid data if (!BLEProtocol.ValidateData(data)) { BLEDebug.LogWarning("Warning: Receive Data could not be validated"); return; } byte responseCode = BLEProtocol.GetResponseCode(data); BLEDebug.LogInfo($"Processing Response Code {responseCode}"); switch (responseCode) { case BLEProtocol.ResponseCode.Acknowledge: Acknowledge(); break; case BLEProtocol.ResponseCode.DeviceInformationResponse: ReceiveDeviceInformation(data); break; case BLEProtocol.ResponseCode.ErrorLogResponse: ReceiveErrorLog(data); break; case BLEProtocol.ResponseCode.ResistanceLevelRangeResponse: ReceiveResistanceLevelRange(data); break; case BLEProtocol.ResponseCode.ResistanceLevelResponse: case BLEProtocol.ResponseCode.ResistanceLevelNotification: ReceiveResistanceLevel(data); break; case BLEProtocol.ResponseCode.WorkoutControlStateResponse: case BLEProtocol.ResponseCode.WorkoutControlStateNotification: ReceiveWorkoutControlState(data); break; case BLEProtocol.ResponseCode.WorkoutStatusNotification: ReceiveWorkoutStatus(data); break; default: BLEDebug.LogError("Error: Invalid ResponseCode received from native plugin"); return; } }
public void Update() { if (Bike.Instance.Matches.Count != lastsize) { DropdownBox.GetComponent <Dropdown>().options.Clear(); found.Clear(); foreach (string s in Bike.Instance.Matches) { BLEDebug.LogInfo($"Dropdown Option: {s}"); DropdownBox.GetComponent <Dropdown>().options.Add(new Dropdown.OptionData(s)); found.Add(s); } lastsize = Bike.Instance.Matches.Count; } }
public void UpdateStats(int rotations, int rpm, float[] playerPosition, float progressDistance) { BLEDebug.LogInfo("Sending Stats Update"); FlatJSON fJSON = new FlatJSON(); fJSON.Add("rotations", rotations); fJSON.Add("rpm", rpm); fJSON.Add("playerPosition", playerPosition); fJSON.Add("progressDistance", progressDistance); Client.SendMessage(Client.NewMessage(OP_CODE_STATS_UPDATE) .WithDeliveryIntent(DeliveryIntent.Reliable) .WithTargetPlayer(Constants.PLAYER_ID_SERVER) .WithPayload(StringToBytes(fJSON.ToString()))); }
public async Task CreateMatchmakingTicket() { BLEDebug.LogInfo("Creating MatchMaking Ticket"); FlatJSON fJSON = new FlatJSON(); HttpContent req = fJSON.SerializeContent(); HttpResponseMessage result = await client.PostAsync("https://echelon.3pointlabs.org/matchmaking/ticket", req); string body = await result.Content.ReadAsStringAsync(); BLEDebug.LogInfo("Ticket" + body); fJSON.Deserialize(body); fJSON.TryGetStringValue("TicketId", out TicketId); fJSON.TryGetStringValue("Status", out _Status); }
public void ReceiveMatch(string matchRecord) { string[] sep = { "|" }; string[] matchSplit = matchRecord.Split(sep, 2, StringSplitOptions.RemoveEmptyEntries); Bike.Instance.Matches.Add(matchSplit[0]); if (!Bike.Instance.Addresses.ContainsKey(matchSplit[0])) { Bike.Instance.Addresses.Add(matchSplit[0], matchSplit[1]); } // Test Value Was Added string s = ""; Bike.Instance.Addresses.TryGetValue(matchSplit[0], out s); BLEDebug.LogInfo("Match Received: " + matchSplit[0] + " " + s); }
// Update is called once per frame void Update() { if (bikesListed.Count != Bike.Instance.Matches.Count) { BLEDebug.LogInfo("BLE Button Added"); HashSet <string> newBikes = new HashSet <string>(Bike.Instance.Matches); newBikes.ExceptWith(bikesListed); foreach (string name in newBikes) { Button b = Object.Instantiate(prefabButton, Vector3.zero, Quaternion.identity); RectTransform r = b.GetComponent <RectTransform>(); r.SetParent(scrollContent.GetComponent <RectTransform>()); b.GetComponentInChildren <Text>().text = name; bikesListed.Add(name); } } }
public static void Set(byte actionCode, int value) { BLEDebug.LogInfo("BLEAction Set"); switch (actionCode) { case BLEProtocol.ActionCode.SetWorkoutControlState: case BLEProtocol.ActionCode.SetResistanceLevel: BLEPlugin.Instance.SendPluginMessage( BLEProtocol.ConvertBytesToString( BLEProtocol.PrepareSetCommandBytes(actionCode, value) ) ); break; default: BLEDebug.LogError("Error: Attempting to send invalid Set ActionCode"); break; } }