C# Client  0.0.0.7
C# Library to interface with Corelink
Control.cs
Go to the documentation of this file.
1 using System;
2 using System.Collections.Generic;
3 using System.Net;
4 using System.Net.Sockets;
5 using System.Text;
6 using System.Threading;
7 using SimpleJSON;
8 using UnityEngine;
9 
10 namespace CoreLink
11 {
19 
20  public class Control
21  {
25  public static bool debug;
29  public static int timeoutIterations = 100;
30 
31  private Credentials credentials;
32  private Config config;
33 
34  private CorelinkTCP tcp;
35  private ControlCallbacks ws;
36  private CorelinkUDP udp;
37 
38  private IPAddress myIP;
39 
40  private uint receiverID;
41  private List<SenderStreamParams> senderStreams;
42  private List<ReceiverStreamParams> receiverStreams;
43  private List<uint> allowedStreams;
44 
45  int id = 0;
46  public Control() : this(false) { }
47  public Control(bool debug)
48  {
49  senderStreams = new List<SenderStreamParams>();
50  receiverStreams = new List<ReceiverStreamParams>();
51  allowedStreams = new List<uint>();
53  receiverID = 0;
54  }
55  #region [Basic Usage]
56 
62  public void connect(Config config)
63  {
64  this.config = config;
65 
66  //tcp = new CorelinkTCP(config);
67 
68  Print("Initializing WebSocket Connection");
69  ws = new ControlCallbacks(config.controlDomain);
71  int iterations = 0;
72  while (!ws.isConnectionOpen() && iterations < timeoutIterations)
73  {
74  Thread.Sleep(100);
75  iterations++;
76  }
77  if (iterations == timeoutIterations)
78  {
79  throw new Exception("Timeout error");
80  }
81  }
82  public async void ConnectToServer()
83  {
84  await ws.connect();
85  }
86 
93  public bool login(Credentials credentials)
94  {
95  this.credentials = credentials;
96  JSONNode jsonRequest = credentials.ToJSON();
97  jsonRequest["ID"] = id;
98  string request = jsonRequest.ToString();
99  JSONNode jsonResponse = SendAndErrorCheck(request, id++);
100  this.credentials.Token = jsonResponse["token"].Value;
101  myIP = IPAddress.Parse(jsonResponse["IP"].Value).MapToIPv4(); // client's public facing IP address (usually their router)
102  int statusCode = jsonResponse["statusCode"].AsInt;
103  string message = jsonResponse["message"].Value; // unused for now
104 
105  if (statusCode != 0) throw new CorelinkException(statusCode, message);
106 
107  return statusCode == 0 ? true : false;
108  }
109 
132 
133  public uint createSender(SenderStreamParams streamParams)
134  {
135  JSONNode jsonRequest = streamParams.toJSON();
136  jsonRequest["function"] = "sender";
137  jsonRequest["IP"] = myIP.ToString();
138  jsonRequest["port"] = 0;
139  jsonRequest["token"] = this.credentials.Token;
140  jsonRequest["ID"] = id;
141  string request = jsonRequest.ToString();
142  JSONNode jsonResponse = SendAndErrorCheck(request, id++);
143  int statusCode = jsonResponse["statusCode"].AsInt;
144  uint.TryParse(jsonResponse["streamID"].Value, out streamParams.streamID);
145  int udpPort = jsonResponse["port"].AsInt;
146  string MTU = jsonResponse["MTU"].Value; // unused for now
147  string message = jsonResponse["message"].Value; // unused for now
148 
149  if (statusCode != 0) throw new CorelinkException(statusCode, message);
150 
151  if (streamParams.proto.Equals("udp"))
152  {
153  if (udp == null)
154  {
155  Print("Attempting to open a UDP port at " + jsonResponse["port"].Value);
156  udp = new CorelinkUDP(config.dataIP, udpPort, ref allowedStreams, ref receiverStreams);
157  }
158 
159  }
160  streamParams.port = udpPort;
161  senderStreams.Add(streamParams);
162  return streamParams.streamID;
163  }
164 
176  public List<uint> createReceiver(ReceiverStreamParams streamParams)
177  {
178  if (receiverID != null)
179  {
180  // Update our current receiverID, not generate a new one
181  streamParams.receiverid = receiverID;
182  }
183  JSONNode jsonRequest = streamParams.toJSON();
184  jsonRequest["IP"] = myIP.ToString();
185  jsonRequest["port"] = 0;
186  jsonRequest["token"] = this.credentials.Token;
187  jsonRequest["ID"] = id;
188  string request = jsonRequest.ToString();
189  JSONNode jsonResponse = SendAndErrorCheck(request, id++);
190  uint.TryParse(jsonResponse["streamID"].Value, out streamParams.streamID);
191  if (receiverID == 0)
192  {
193  receiverID = streamParams.streamID;
194  }
195  foreach (JSONNode node in jsonResponse["streamList"])
196  {
197  uint streamID = 0;
198  uint.TryParse(node["streamID"].Value, out streamID);
199  if (streamID == 0) throw new CorelinkException("Error parsing streamID");
200  streamParams.streamIDs.Add(streamID);
201  if (!allowedStreams.Contains(streamID))
202  {
203  allowedStreams.Add(streamID);
204  }
205  }
206 
207  streamParams.port = jsonResponse["port"].AsInt;
208  string proto = jsonResponse["proto"].Value;
209  string MTU = jsonResponse["MTU"].Value; // unused for now
210 
211  if (proto.Equals("udp"))
212  {
213  if (udp == null)
214  {
215  Print("Attempting to open a UDP port at " + jsonResponse["port"].Value);
216  udp = new CorelinkUDP(config.dataIP, streamParams.port, ref allowedStreams, ref receiverStreams);
217  }
218  udp.receiverPing(streamParams.streamID);
219  }
220 
221  receiverStreams.Add(streamParams);
222  return streamParams.streamIDs;
223  }
224 
230  public List<uint> subscribe(List<uint> streamIDs)
231  {
232  if (receiverID == null)
233  {
234  throw new CorelinkException("ERROR: Need to create a receiver stream before subscribing");
235  }
236  JSONNode jsonRequest = JSON.Parse("{}");
237  jsonRequest["function"] = "subscribe";
238  jsonRequest["receiverID"] = receiverID;
239  for (int i = 0; i < streamIDs.Count; i++)
240  {
241  jsonRequest["streamID"][i] = streamIDs[i];
242  }
243  jsonRequest["token"] = this.credentials.Token;
244  jsonRequest["ID"] = id;
245  string request = jsonRequest.ToString();
246  JSONNode jsonResponse = SendAndErrorCheck(request, id++);
247 
248  List<uint> returnedStreamids = new List<uint>();
249  for (int i = 0; i < jsonResponse["streamList"].Count; i++)
250  {
251  uint streamID = 0;
252  uint.TryParse(jsonResponse["streamList"][i]["streamID"].Value, out streamID);
253  if (streamID == 0) throw new CorelinkException("Error parsing streamID");
254  returnedStreamids.Add(streamID);
255  allowedStreams.Add(streamID);
256  }
257 
258  return returnedStreamids;
259  }
260 
266  public List<uint> unsubscribe(List<string> streamIDs)
267  {
268  JSONNode jsonRequest = JSON.Parse("{}");
269  jsonRequest["function"] = "unsubscribe";
270  jsonRequest["receiverID"] = receiverStreams[0].streamID;
271  jsonRequest["streamID"] = new JSONArray();
272  foreach (string w in streamIDs)
273  {
274  jsonRequest["workspaces"].Add(w);
275  }
276  jsonRequest["token"] = credentials.Token;
277  jsonRequest["ID"] = id;
278  string request = jsonRequest.ToString();
279  JSONNode jsonResponse = SendAndErrorCheck(request, id++);
280  List<uint> retval = new List<uint>();
281  foreach (JSONNode f in jsonResponse["streamList"].AsArray)
282  {
283  uint ID = 0;
284  uint.TryParse(f.Value, out ID);
285  if (ID == 0) throw new CorelinkException("Error parsing streamID");
286  retval.Add(ID);
287  }
288  return retval;
289  }
290 
296  public List<string> disconnect()
297  {
298  StreamFilter filter = new StreamFilter();
299  if (receiverStreams.Count > 0)
300  {
301  filter.streamIDs.Add(receiverStreams[0].streamID);
302  }
303  foreach (SenderStreamParams param in senderStreams)
304  {
305  filter.streamIDs.Add(param.streamID);
306  }
307  return disconnect(filter);
308  }
309  public List<string> disconnect(StreamFilter filter)
310  {
311  JSONNode jsonRequest = JSON.Parse("{}");
312  jsonRequest["function"] = "disconnect";
313  jsonRequest["workspaces"] = new JSONArray();
314  foreach (string w in filter.workspaces)
315  {
316  jsonRequest["workspaces"].Add(w);
317  }
318  jsonRequest["types"] = new JSONArray();
319  foreach (string t in filter.types)
320  {
321  jsonRequest["types"].Add(t);
322  }
323  jsonRequest["streamIDs"] = new JSONArray();
324  foreach (uint s in filter.streamIDs)
325  {
326  jsonRequest["streamIDs"].Add(s);
327  }
328  if (receiverID != null)
329  {
330  jsonRequest["streamIDs"].Add(receiverID);
331  }
332  jsonRequest["token"] = this.credentials.Token;
333  jsonRequest["ID"] = id;
334  string request = jsonRequest.ToString();
335  JSONNode jsonResponse = SendAndErrorCheck(request, id++);
336  List<string> retval = new List<string>();
337  foreach (JSONNode f in jsonResponse["streamList"].AsArray)
338  {
339  retval.Add(f.Value);
340  }
341  return retval;
342  }
343 
347  public void exit()
348  {
349  // TODO: Check if all streamIDs are fetched successfully
350  disconnect();
351  ws.stopConnection();
352  if (udp != null) udp.stopConnection();
353  }
354 
361  public void send(uint streamID, byte[] header, byte[] data)
362  {
363  if (udp == null)
364  {
365  throw new Exception("udp connection not created");
366  }
367  udp.send(streamID, header, data);
368  }
369 
370  #endregion
371 
372  #region [Workspace Functions]
373  public bool addWorkspace(string workspace)
379  {
380  JSONNode jsonRequest = JSON.Parse("{}");
381  jsonRequest["function"] = "addWorkspace";
382  jsonRequest["workspace"] = workspace;
383  jsonRequest["token"] = credentials.Token;
384  jsonRequest["ID"] = id;
385  string request = jsonRequest.ToString();
386  JSONNode jsonResponse = SendAndErrorCheck(request, id++);
387  int statusCode = jsonResponse["statusCode"].AsInt;
388  return statusCode == 0 ? true : false;
389  }
390 
396  public bool rmWorkspace(string workspace)
397  {
398  JSONNode jsonRequest = JSON.Parse("{}");
399  jsonRequest["function"] = "rmWorkspace";
400  jsonRequest["workspace"] = workspace;
401  jsonRequest["token"] = credentials.Token;
402  jsonRequest["ID"] = id;
403  string request = jsonRequest.ToString();
404  JSONNode jsonResponse = SendAndErrorCheck(request, id++);
405  int statusCode = jsonResponse["statusCode"].AsInt;
406  return statusCode == 0 ? true : false;
407  }
408 
414  public bool setDefaultWorkspace(string workspace)
415  {
416  JSONNode jsonRequest = JSON.Parse("{}");
417  jsonRequest["function"] = "setDefaultWorkspace";
418  jsonRequest["workspace"] = workspace;
419  jsonRequest["token"] = credentials.Token;
420  jsonRequest["ID"] = id;
421  string request = jsonRequest.ToString();
422  JSONNode jsonResponse = SendAndErrorCheck(request, id++);
423  int statusCode = jsonResponse["statusCode"].AsInt;
424  return statusCode == 0 ? true : false;
425  }
426 
431  public string getDefaultWorkspace()
432  {
433  JSONNode jsonRequest = JSON.Parse("{}");
434  jsonRequest["function"] = "getDefaultWorkspace";
435  jsonRequest["token"] = credentials.Token;
436  jsonRequest["ID"] = id;
437  string request = jsonRequest.ToString();
438  JSONNode jsonResponse = SendAndErrorCheck(request, id++);
439  return jsonResponse["workspace"].Value;
440  }
441 
446  public List<string> listWorkspaces()
447  {
448  JSONNode jsonRequest = JSON.Parse("{}");
449  jsonRequest["function"] = "listWorkspaces";
450  jsonRequest["token"] = this.credentials.Token;
451  string request = jsonRequest.ToString();
452  JSONNode jsonResponse = SendAndErrorCheck(request, id++);
453  List<string> retval = new List<string>();
454  foreach (JSONNode f in jsonResponse["workspaceList"].AsArray)
455  {
456  retval.Add(f.Value);
457  }
458  return retval;
459  }
460 
461  #endregion
462 
463  #region [Function Helpers]
464 
469  public List<string> listFunctions()
470  {
471  JSONNode jsonRequest = JSON.Parse("{}");
472  jsonRequest["function"] = "listFunctions";
473  jsonRequest["token"] = credentials.Token;
474  jsonRequest["ID"] = id;
475  string request = jsonRequest.ToString();
476  JSONNode jsonResponse = SendAndErrorCheck(request, id++);
477  List<string> retval = new List<string>();
478  foreach (JSONNode f in jsonResponse["functionList"].AsArray)
479  {
480  retval.Add(f.Value);
481  }
482  return retval;
483  }
484 
490  public List<string> listServerFunctions()
491  {
492  JSONNode jsonRequest = JSON.Parse("{}");
493  jsonRequest["function"] = "listServerFunctions";
494  jsonRequest["token"] = credentials.Token;
495  jsonRequest["ID"] = id;
496  string request = jsonRequest.ToString();
497  JSONNode jsonResponse = SendAndErrorCheck(request, id++);
498  List<string> retval = new List<string>();
499  foreach (JSONNode f in jsonResponse["functionList"].AsArray)
500  {
501  retval.Add(f.Value);
502  }
503  return retval;
504  }
505 
511  public string describeFunction(string function)
512  {
513  JSONNode jsonRequest = JSON.Parse("{}");
514  jsonRequest["function"] = "describeFunction";
515  jsonRequest["functionName"] = function;
516  jsonRequest["token"] = credentials.Token;
517  jsonRequest["ID"] = id;
518  string request = jsonRequest.ToString();
519  JSONNode jsonResponse = SendAndErrorCheck(request, id++);
520  return jsonResponse["description"].Value;
521 
522  }
523 
529  public string describeServerFunction(string function)
530  {
531  JSONNode jsonRequest = JSON.Parse("{}");
532  jsonRequest["function"] = "describeServerFunction";
533  jsonRequest["functionName"] = function;
534  jsonRequest["token"] = credentials.Token;
535  jsonRequest["ID"] = id;
536  string request = jsonRequest.ToString();
537  JSONNode jsonResponse = SendAndErrorCheck(request, id++);
538  return jsonResponse["description"].Value;
539  }
540 
541  #endregion
542 
543  #region [Stream Info]
544 
550  public JSONArray listStreams(StreamFilter filter)
551  {
552  JSONNode jsonRequest = JSON.Parse("{}");
553  jsonRequest["function"] = "listStreams";
554  jsonRequest["workspaces"] = new JSONArray();
555  foreach (string w in filter.workspaces)
556  {
557  jsonRequest["workspaces"].Add(w);
558  }
559  jsonRequest["types"] = new JSONArray();
560  foreach (string t in filter.types)
561  {
562  jsonRequest["types"].Add(t);
563  }
564  jsonRequest["token"] = credentials.Token;
565  jsonRequest["ID"] = id;
566  string request = jsonRequest.ToString();
567  JSONNode jsonResponse = SendAndErrorCheck(request, id++);
568  return jsonResponse["senderList"].AsArray;
569  }
575  public JSONNode streamInfo(uint streamID)
576  {
577  JSONNode jsonRequest = JSON.Parse("{}");
578  jsonRequest["function"] = "streamInfo";
579  jsonRequest["workspaces"] = new JSONArray();
580  jsonRequest["streamID"] = streamID;
581  jsonRequest["token"] = credentials.Token;
582  jsonRequest["ID"] = id;
583  string request = jsonRequest.ToString();
584  JSONNode jsonResponse = SendAndErrorCheck(request, id++);
585  return jsonResponse;
586 
587  }
588 
589  #endregion
590 
591  #region [User Functions]
592  public List<string> listUsers()
593  {
594  JSONNode jsonRequest = JSON.Parse("{}");
595  jsonRequest["function"] = "streamInfo";
596  jsonRequest["token"] = credentials.Token;
597  jsonRequest["ID"] = id;
598  string request = jsonRequest.ToString();
599  JSONNode jsonResponse = SendAndErrorCheck(request, id++);
600  List<string> retval = new List<string>();
601  foreach (JSONNode f in jsonResponse["userList"].AsArray)
602  {
603  retval.Add(f.Value);
604  }
605  return retval;
606  }
607 
608  #endregion
609  // TODO: keepAlive, password, rmUser, listUsers, addGroup, addUserGroup, rmUserGroup, changeOwner, rmGroup, listGroups, setConfig, expire,
610 
611 
612  #region [Utility]
613  JSONNode SendAndErrorCheck(string request, int id)
617  {
618  Print("Request:\t" + request);
619  ws.sendMessage(request);
620  string response = ws.getResponse();
621 
622  Print("Response: " + response);
623  JSONNode jsonResponse = JSON.Parse(response);
624  int statusCode = jsonResponse["statusCode"].AsInt;
625  int receivedID = jsonResponse["ID"].AsInt;
626  string message = jsonResponse["message"].Value;
627  if (receivedID != id)
628  {
629  throw new CorelinkException("Wrong ID");
630  }
631  if (statusCode != 0) throw new CorelinkException(statusCode, message);
632  return jsonResponse;
633  }
634  public static void Print(string message)
635  {
636  if (debug) Debug.Log(message);
637  }
638  #endregion
639  }
640 }