Skip to content

Commit

Permalink
StartCoroutine is only safe to call inside Unity's main thread
Browse files Browse the repository at this point in the history
  • Loading branch information
Sauceke committed Dec 6, 2022
1 parent 4ff2f48 commit b5d24e2
Showing 1 changed file with 20 additions and 3 deletions.
23 changes: 20 additions & 3 deletions src/LoveMachine.Core/Buttplug/ButtplugWsClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using LitJson;
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
Expand All @@ -14,6 +15,7 @@ public class ButtplugWsClient : CoroutineHandler
private WebSocket websocket;
private readonly System.Random random = new System.Random();
private bool killSwitchThrown = false;
private ConcurrentQueue<IEnumerator> incoming;

internal event EventHandler<DeviceListEventArgs> OnDeviceListUpdated;

Expand All @@ -34,14 +36,17 @@ public void Open()
{
IsConnected = false;
Devices = new List<Device>();
incoming = new ConcurrentQueue<IEnumerator>();
string address = ButtplugConfig.WebSocketHost.Value
+ ":" + ButtplugConfig.WebSocketPort.Value;
CoreConfig.Logger.LogInfo($"Connecting to Intiface server at {address}");
websocket = new WebSocket(address);
websocket.Opened += (s, e) => HandleCoroutine(OnOpened(s, e));
websocket.MessageReceived += (s, e) => HandleCoroutine(OnMessageReceived(s, e));
websocket.Error += (s, e) => HandleCoroutine(OnError(s, e));
// StartCoroutine is only safe to call inside Unity's main thread
websocket.Opened += (s, e) => incoming.Enqueue(OnOpened(s, e));
websocket.MessageReceived += (s, e) => incoming.Enqueue(OnMessageReceived(s, e));
websocket.Error += (s, e) => incoming.Enqueue(OnError(s, e));
websocket.Open();
HandleCoroutine(RunReceiveLoop());
HandleCoroutine(RunKillSwitchLoop());
HandleCoroutine(RunBatteryLoop());
}
Expand Down Expand Up @@ -309,6 +314,18 @@ private IEnumerator ReadBatteryLevels(int retries)
}
}

private IEnumerator RunReceiveLoop()
{
while (true)
{
while (incoming.TryDequeue(out var coroutine))
{
HandleCoroutine(coroutine);
}
yield return new WaitForSecondsRealtime(1f);
}
}

private IEnumerator RunKillSwitchLoop()
{
while (true)
Expand Down

0 comments on commit b5d24e2

Please sign in to comment.