Skip to content

Instantly share code, notes, and snippets.

@rondagdag
Created January 3, 2016 02:53
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rondagdag/16f1164c81962e89a900 to your computer and use it in GitHub Desktop.
Save rondagdag/16f1164c81962e89a900 to your computer and use it in GitHub Desktop.
Littlebits Web Socket using WebSocketSharp.Net and Newtonsoft.Json
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;
public GameObject Darth;
// Use this for initialization
void Start () {
uri = uri + access_token;
init ();
}
// Update is called once per frame
void Update () {
Darth.transform.Rotate(new Vector3(Darth.transform.rotation.x, Darth.transform.rotation.y + value ,Darth.transform.rotation.z));
}
private void init()
{
// ----------------------------
// Abhören
// ----------------------------
// Lokalen Endpunkt definieren (wo Nachrichten empfangen werden).
// Einen neuen Thread für den Empfang eingehender Nachrichten erstellen.
receiveThread = new Thread(
new ThreadStart(ReceiveData));
receiveThread.IsBackground = true;
receiveThread.Start();
}
private void ReceiveData()
{
ws = new WebSocket (uri);
{
// Set the WebSocket events.
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());
};
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>();
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