Skip to content

Instantly share code, notes, and snippets.

@rondagdag
Created November 30, 2015 20:20
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rondagdag/4bff1724cdf624b04db8 to your computer and use it in GitHub Desktop.
Save rondagdag/4bff1724cdf624b04db8 to your computer and use it in GitHub Desktop.
Here's my code to connect Unity3d to Littlebits Cloudbit via websockets
using UnityEngine;
using System.Collections;
using System;
using System.Security.Policy;
using System.Threading;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using WebSocketSharp;
using WebSocketSharp.Net;
public class LittlebitsWebSocket : MonoBehaviour {
// receiving Thread
Thread receiveThread;
public string access_token = "<Access Token Here>";
public string device_id = "<Device ID Here>";
private string uri = "wss://api-stream.littlebitscloud.cc/primus/?access_token=";
public int value;
WebSocket ws;
GameObject energyLight;
EnergyScript energyScript;
// Use this for initialization
void Start () {
uri = uri + access_token;
energyLight = GameObject.FindGameObjectWithTag ("Light");
energyScript = energyLight.GetComponent<EnergyScript> ();
init ();
}
// Update is called once per frame
void Update () {
}
private void init()
{
receiveThread = new Thread(
new ThreadStart(ReceiveData));
receiveThread.IsBackground = true;
receiveThread.Start();
}
private void ReceiveData()
{
ws = new WebSocket (uri);
{
// Set the WebSocket events.
//connect to littlebits and subscribe to a device
ws.OnOpen += (sender, e) =>
{
var data = new JObject();
data.Add("name","subscribe");
var args1 = new JObject();
args1.Add("device_id",device_id);
data.Add("args",args1);
ws.Send(data.ToString());
};
// when we receive a message from littlebits, we need to parse the data
ws.OnMessage += (sender, e) =>
{
var data = e.Data.Substring(1,e.Data.Length -2);
var newData = data.Replace("\\", "");
JObject json = JObject.Parse(newData);
var payload = json["payload"];
if (payload != null)
{
var newValue = payload["percent"].Value<int>();
//if (value != newValue)
{
energyScript.LocalVelocity_Y = value / 10;
}
value = newValue;
Debug.Log ("Cloudbit:" + value);
}
};
ws.OnError += (sender, e) =>
Debug.Log ("Error >>" + e.Message);
ws.OnClose += (sender, e) =>
Debug.Log(String.Format("WebSocket Close ({0})", e.Code));
#if DEBUG
// To change the logging level.
ws.Log.Level = LogLevel.Trace;
// To change the wait time for the response to the Ping or Close.
ws.WaitTime = TimeSpan.FromSeconds(10);
// To emit a WebSocket.OnMessage event when receives a ping.
ws.EmitOnPing = true;
#endif
}
ws.ConnectAsync ();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment