public static async Task <JToken> CreateSubscriptionAndWaitSubscribed(
            this IRtmClient client,
            string channel,
            string position,
            ISubscriptionObserver observer)
        {
            var tcs  = new TaskCompletionSource <JToken>();
            var sobs = new SubscriptionObserver();

            sobs.OnEnterSubscribed += (s) =>
            {
                tcs.TrySetResult(s.Position);
            };
            sobs.OnEnterFailed += (_) =>
            {
                tcs.TrySetException(new Exception("subscription was removed"));
            };
            sobs.OnDeleted += (_) =>
            {
                tcs.TrySetException(new Exception("subscription was removed"));
            };
            var subCfg = new SubscriptionConfig(SubscriptionModes.Advanced)
            {
                Position = position,
                Observer = new SubscriptionCompoundObserver(sobs, observer)
            };

            client.CreateSubscription(channel, subCfg);
            return(await tcs.Task.ConfigureAwait(false));
        }
        public static QueueAsync <string> CreateStateQueue(this IRtmClient client)
        {
            var queue = new QueueAsync <string>();

            client.SetStateObserver(queue);
            return(queue);
        }
Exemple #3
0
 public IRtmClient Register(IRtmClient client)
 {
     Log.V("Updating RTM client in RTM manager: {0}", client);
     this.client?.Dispose();
     this.client = client;
     this.client?.Start();
     return(this.client);
 }
        public static async Task AssertEmpty <T>(this QueueAsync <T> queue, IRtmClient client, int millis)
        {
            await Task.Delay(millis);

            await client.Yield();

            Assert.That(queue.TryDequeue(), Is.EqualTo(null));
        }
 public static void SetStateObserver(this IRtmClient client, IObservableSink <string> observer)
 {
     client.OnEnterStopped    += () => { observer.Next("enter-stopped"); };
     client.OnLeaveStopped    += () => { observer.Next("leave-stopped"); };
     client.OnEnterConnecting += () => { observer.Next("enter-connecting"); };
     client.OnLeaveConnecting += () => { observer.Next("leave-connecting"); };
     client.OnEnterConnected  += (_) => { observer.Next("enter-connected"); };
     client.OnLeaveConnected  += (_) => { observer.Next("leave-connected"); };
     client.OnEnterAwaiting   += () => { observer.Next("enter-awaiting"); };
     client.OnLeaveAwaiting   += () => { observer.Next("leave-awaiting"); };
     client.OnEnterDisposed   += () => { observer.Next("enter-disposed"); };
 }
Exemple #6
0
    static async Task Async(IRtmClient client)
    {
        RtmPublishReply reply = null;

        try
        {
            var message = new Animal
            {
                Who   = "zebra",
                Where = new float[] { 34.134358f, -118.321506f }
            };

            reply = await client.Publish("animals", message, Ack.Yes);

            Console.WriteLine("Publish confirmed");
        }
        catch (Exception ex)
        {
            Console.WriteLine("Failed to publish: " + ex.Message);
        }

        var observer = new SubscriptionObserver();

        observer.OnEnterSubscribed += (ISubscription sub) =>
                                      Console.WriteLine("Subscribed to: " + sub.SubscriptionId);

        observer.OnLeaveSubscribed += (ISubscription sub) =>
                                      Console.WriteLine("Unsubscribed from: " + sub.SubscriptionId);

        observer.OnSubscriptionData += (ISubscription sub, RtmSubscriptionData data) =>
        {
            foreach (JToken jToken in data.Messages)
            {
                Console.WriteLine("Got message: " + jToken);
            }
        };

        observer.OnSubscribeError += (ISubscription sub, Exception err) =>
                                     Console.WriteLine("Failed to subscribe: " + err.Message);

        observer.OnSubscriptionError += (ISubscription sub, RtmSubscriptionError err) =>
                                        Console.WriteLine("Subscription failed. RTM sent the unsolicited error {0}: {1}", err.Code, err.Reason);

        var cfg = new SubscriptionConfig(SubscriptionModes.Simple, observer)
        {
            Position = reply?.Position
        };

        client.CreateSubscription("animals", cfg);
    }
    void Start()
    {
        IRtmClient client = RtmManager.Instance.Register(endpoint, appKey);

        client.OnEnterConnected += cn =>
                                   Debug.Log("Connected to Satori RTM!");

        client.OnError += ex =>
                          Debug.Log("Failed to connect: " + ex.Message);

        client.Start();

        // Publish, subscribe, and perform other operations here
    }
        public static async Task <QueueAsync <string> > StartAndWaitConnected(this IRtmClient client)
        {
            await client.Yield();

            var queue = client.CreateStateQueue();

            client.Start();

            Assert.That(await queue.Dequeue(), Is.EqualTo("leave-stopped"));
            Assert.That(await queue.Dequeue(), Is.EqualTo("enter-connecting"));
            Assert.That(await queue.Dequeue(), Is.EqualTo("leave-connecting"));
            Assert.That(await queue.Dequeue(), Is.EqualTo("enter-connected"));

            return(queue);
        }
Exemple #9
0
    private static async Task PublishLoop(IRtmClient client)
    {
        // Publish messages every 2 seconds

        var random = new Random();

        while (true)
        {
            try
            {
                var message = new Animal
                {
                    Who   = "zebra",
                    Where = new float[] {
                        34.134358f + (float)random.NextDouble() / 100,
                        -118.321506f + (float)random.NextDouble() / 100
                    }
                };

                // At this point, the client may not yet be connected to Satori RTM.
                // If the client is not connected, the SDK internally queues the publish request and
                // will send it once the client connects
                RtmPublishReply reply = await client.Publish(channel, message, Ack.Yes);

                Console.WriteLine("Animal is published: {0}", message);
            }
            catch (PduException ex)
            {
                Console.WriteLine("Failed to publish. RTM replied with the error {0}: {1}", ex.Error.Code, ex.Error.Reason);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed to publish: " + ex.Message);
            }

            await Task.Delay(millisecondsDelay : 2000);
        }
    }
    static async Task Async(IRtmClient client)
    {
        try
        {
            var message = new Animal
            {
                Who   = "zebra",
                Where = new float[] { 34.134358f, -118.321506f }
            };

            RtmPublishReply reply = await client.Publish("animals", message, Ack.Yes);

            Console.WriteLine("Publish confirmed");
        }
        catch (PduException ex)
        {
            Console.WriteLine("Failed to publish. RTM replied with the error {0}: {1}", ex.Error.Code, ex.Error.Reason);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Failed to publish: " + ex.Message);
        }
    }
 public static void SetClientErrorObserver(this IRtmClient client, IObservableSink <string> observer)
 {
     client.OnError += ex => { observer.Next("error:" + ex.GetType().Name); };
 }
    // Use this for initialization
    void Start()
    {
        var textObj = GameObject.Find("text");

        mesh      = (Text)textObj.GetComponent(typeof(Text));
        mesh.text = "";

        // Change logging levels. Default level is Warning.
        DefaultLoggers.Dispatcher.SetLevel(Logger.LogLevel.Verbose);
        DefaultLoggers.Serialization.SetLevel(Logger.LogLevel.Verbose);
        DefaultLoggers.Connection.SetLevel(Logger.LogLevel.Verbose);
        DefaultLoggers.Client.SetLevel(Logger.LogLevel.Verbose);
        DefaultLoggers.ClientRtm.SetLevel(Logger.LogLevel.Verbose);
        DefaultLoggers.ClientRtmSubscription.SetLevel(Logger.LogLevel.Verbose);

        try
        {
            ShowText(string.Format("RTM connection config:\n\tendpoint='{0}'\n\tappkey='{1}'", endpoint, appKey));

            //check if the role is set to authenticate or not
            var toAuthenticate = !new string[] { "YOUR_ROLE", "", null }.Contains(role);
            ShowText(string.Format("Starting RTM client... Authenticate? {0} (role={1})", toAuthenticate, role));

            if (toAuthenticate)
            {
                client = RtmManager.Instance.Register(endpoint, appKey, role, roleSecretKey);
            }
            else
            {   //no authentication (default role)
                client = RtmManager.Instance.Register(endpoint, appKey);
            }

            // Hook up to client connectivity state transitions
            client.OnEnterConnecting += () => ShowText("Connecting...");
            client.OnEnterConnected  += cn => ShowText("Connected to Satori RTM!");
            client.OnLeaveConnected  += cn => ShowText("Disconnected");
            client.OnError           += ex => ShowText("ERROR:\n" + ex);

            // We create a subscription observer object to receive callbacks
            // for incoming messages, subscription state changes and errors.
            // The same observer can be shared between several subscriptions.
            var observer = new SubscriptionObserver();

            observer.OnSubscribeError += (sub, ex) =>
            {
                ShowText("ERROR: subscribing failed. " +
                         "Check channel subscribe permissions in Dev Portal. \n" + ex);
            };

            // when subscription is establshed (confirmed by RTM)
            observer.OnEnterSubscribed += sub =>
            {
                ShowText("Subscribed to " + sub.SubscriptionId);

                // Instruct the Update method to publish next message.
                // We publish a message to the same channel we have subscribed to
                // and so will be receiving our own message.
                // (This is a contrived example just for tutorial purposes)
                publishAnimal = true;
            };

            // when the subscription ends
            observer.OnLeaveSubscribed += sub => ShowText("Unsubscribed from " + sub.SubscriptionId);

            // when a subscription error occurs
            observer.OnSubscriptionError += (ISubscription sub, RtmSubscriptionError err)
                                            => ShowText("ERROR: subscription " + err.Code + ": " + err.Reason);

            // when messages arrive
            observer.OnSubscriptionData += (ISubscription sub, RtmSubscriptionData data) =>
            {
                // Note: sub.SubscriptionId is the channel name
                ShowText("Message received from channel " + sub.SubscriptionId);

                // Messages arrive in an array
                foreach (JToken jToken in data.Messages)
                {
                    ShowText(jToken.ToString());
                    Animal msg  = jToken.ToObject <Animal>();
                    string text = string.Format("Who? {0}. Where? at {1},{2}", msg.who, msg.where[0], msg.where[1]);
                    ShowText(text);
                }
            };

            // At this point, the client may not yet be connected to Satori RTM.
            // If the client is not connected, the SDK internally queues the subscription request and
            // will send it once the client connects
            client.CreateSubscription(channel, observer);
        }
        catch (System.UriFormatException uriEx)
        {
            ShowText("ERRROR: invalid connection credentials. Check endpoint and appkey");
        }
        catch (Exception ex)
        {
            ShowText("ERROR: setting up RTM client failed.\n" + ex);
        }
    }
Exemple #13
0
    static void Main()
    {
        // Log messages from SDK to the console
        Trace.Listeners.Add(new ConsoleTraceListener());

        // Change logging levels to increase verbosity. Default level is Warning.
        DefaultLoggers.Dispatcher.SetLevel(Logger.LogLevel.Warning);
        DefaultLoggers.Serialization.SetLevel(Logger.LogLevel.Warning);
        DefaultLoggers.Connection.SetLevel(Logger.LogLevel.Warning);
        DefaultLoggers.Client.SetLevel(Logger.LogLevel.Warning);
        DefaultLoggers.ClientRtm.SetLevel(Logger.LogLevel.Warning);
        DefaultLoggers.ClientRtmSubscription.SetLevel(Logger.LogLevel.Warning);

        //check if the role is set to authenticate or not
        var toAuthenticate = !new string[] { "YOUR_ROLE", "", null }.Contains(role);

        Console.WriteLine("RTM connection config:\n" +
                          "\tendpoint='{0}'\n" +
                          "\tappkey='{1}'\n" +
                          "\tauthenticate?={2}", endpoint, appKey, toAuthenticate);

        var builder = new RtmClientBuilder(endpoint, appKey);

        if (toAuthenticate)
        {
            builder.SetRoleSecretAuthenticator(role, roleSecretKey);
        }

        IRtmClient client = builder.Build();

        // Hook up to client lifecycle events
        client.OnEnterConnected += cn => Console.WriteLine("Connected to Satori RTM!");
        client.OnError          += ex => Console.WriteLine("RTM client failed: " + ex.Message);

        client.Start();

        // We create a subscription observer object to receive callbacks
        // for incoming messages, subscription state changes and errors.
        // The same observer can be shared between several subscriptions.
        var observer = new SubscriptionObserver();

        // when subscription is established (confirmed by RTM)
        observer.OnEnterSubscribed += sub =>
                                      Console.WriteLine("Subscribed to the channel: " + sub.SubscriptionId);;

        observer.OnSubscribeError += (sub, ex) =>
                                     Console.WriteLine("Subscribing failed. " +
                                                       "Check channel subscribe permissions in Dev Portal. \n" + ex.Message);

        observer.OnSubscriptionError += (ISubscription sub, RtmSubscriptionError err)
                                        => Console.WriteLine("Subscription error " + err.Code + ": " + err.Reason);

        observer.OnSubscriptionData += (ISubscription sub, RtmSubscriptionData data) =>
        {
            // Messages arrive in an array
            foreach (JToken jToken in data.Messages)
            {
                try
                {
                    Animal msg = jToken.ToObject <Animal>();
                    Console.WriteLine("Got animal {0}: {1}", msg.Who, jToken);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Failed to handle the incoming message: {0}", ex.Message);
                }
            }
        };

        // At this point, the client may not yet be connected to Satori RTM.
        // If the client is not connected, the SDK internally queues the subscription request and
        // will send it once the client connects
        client.CreateSubscription(channel, SubscriptionModes.Simple, observer);

        PublishLoop(client).Wait();
    }