예제 #1
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();
        }
    }
예제 #2
0
    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");
        }
    }
예제 #3
0
    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;
        }
    }
예제 #4
0
    private static void ReceiveResistanceLevel(byte[] data)
    {
        BLEDebug.LogInfo("Resistance Level Received");
        int level = data[BLEProtocol.Index.ResistanceLevel];

        _bikeListener.OnReceiveResistanceLevel(level);
    }
 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 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;
 }
예제 #7
0
    private static void ReceiveWorkoutControlState(byte[] data)
    {
        BLEDebug.LogInfo("Workout Control State Received");
        int controlState = data[BLEProtocol.Index.WorkoutControlState];

        _bikeListener.OnReceiveWorkoutControlState(controlState);
    }
예제 #8
0
    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);
    }
예제 #9
0
    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]);
        }
    }
예제 #10
0
    // 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;
        }
    }
예제 #11
0
    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
                                              )
                                          )
                                      );
    }
예제 #12
0
    public static string ConvertBytesToString(byte[] data)
    {
        string message = System.Convert.ToBase64String(data);

        BLEDebug.LogInfo("Converted Byte to String: " + message);
        return(message);
    }
예제 #13
0
    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);
    }
예제 #14
0
    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);
    }
 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);
 }
예제 #16
0
    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];
    }
예제 #17
0
    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]);
    }
예제 #18
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
 }
예제 #19
0
    /**
     *  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;
        }
    }
예제 #20
0
 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);
 }
예제 #21
0
    public void RequestEnableBLE()
    {
        if (!_nativePluginInstance.EnabledBLE)
        {
            _nativePluginInstance.RequestEnableBLE();
        }
        else
        {
            BLEDebug.LogWarning("BLE Already Enabled, Ignoring Request");
        }

        RequestEnableLocation();
    }
예제 #22
0
    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);
    }
예제 #23
0
    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())));
    }
예제 #24
0
    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);
    }
예제 #25
0
    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;
     }
 }
예제 #27
0
    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())));
    }
예제 #28
0
    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);
    }
예제 #29
0
    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);
            }
        }
    }