예제 #1
0
        public void TestWoopsaClientSubscriptionToProperty()
        {
            bool             isValueChanged = false;
            TestObjectServer objectServer   = new TestObjectServer();

            using (WoopsaServer server = new WoopsaServer(objectServer))
            {
                using (WoopsaClient client = new WoopsaClient("http://localhost/woopsa"))
                {
                    WoopsaBoundClientObject  root          = client.CreateBoundRoot();
                    WoopsaClientProperty     propertyVotes = root.Properties.ByName("Votes") as WoopsaClientProperty;
                    WoopsaClientSubscription subscription  = propertyVotes.Subscribe((sender, e) => { isValueChanged = true; },
                                                                                     TimeSpan.FromMilliseconds(10), TimeSpan.FromMilliseconds(20));
                    objectServer.Votes = 2;
                    Stopwatch watch = new Stopwatch();
                    watch.Start();
                    while ((!isValueChanged) && (watch.Elapsed < TimeSpan.FromSeconds(20)))
                    {
                        Thread.Sleep(10);
                    }
                    if (isValueChanged)
                    {
                        Console.WriteLine("Notification after {0} ms", watch.Elapsed.TotalMilliseconds);
                    }
                    else
                    {
                        Console.WriteLine("No notification received");
                    }
                    subscription.Unsubscribe();
                    Assert.AreEqual(true, isValueChanged);
                }
            }
        }
        public void TestWoopsaClientSubscriptionToProperty()
        {
            bool             isVotesChanged       = false;
            bool             isStringValueChanged = false;
            TestObjectServer objectServer         = new TestObjectServer();

            using (WoopsaServer server = new WoopsaServer(objectServer, TestingPort))
            {
                using (WoopsaClient client = new WoopsaClient(TestingUrl))
                {
                    int    newVotes                        = 0;
                    string newStringValue                  = string.Empty;
                    WoopsaBoundClientObject  root          = client.CreateBoundRoot();
                    WoopsaClientProperty     propertyVotes = root.Properties.ByName("Votes") as WoopsaClientProperty;
                    WoopsaClientSubscription subscription  = propertyVotes.Subscribe((sender, e) =>
                    {
                        newVotes       = e.Notification.Value;
                        isVotesChanged = true;
                    },
                                                                                     TimeSpan.FromMilliseconds(10), TimeSpan.FromMilliseconds(20));

                    WoopsaClientProperty     propertyString = root.Properties.ByName("StringValue") as WoopsaClientProperty;
                    WoopsaClientSubscription subscription2  = propertyString.Subscribe((sender, e) =>
                    {
                        var t                = client.ClientProtocol.Read("Votes");
                        newStringValue       = e.Notification.Value;
                        isStringValueChanged = true;
                    },
                                                                                       TimeSpan.FromMilliseconds(10), TimeSpan.FromMilliseconds(20));

                    objectServer.Votes       = 2;
                    objectServer.StringValue = "Test";
                    Stopwatch watch = new Stopwatch();
                    watch.Start();
                    while ((!isVotesChanged || !isStringValueChanged) && (watch.Elapsed < TimeSpan.FromSeconds(20)))
                    {
                        Thread.Sleep(10);
                    }
                    if (isVotesChanged)
                    {
                        Console.WriteLine("Notification after {0} ms", watch.Elapsed.TotalMilliseconds);
                    }
                    else
                    {
                        Console.WriteLine("No notification received");
                    }
                    subscription.Unsubscribe();
                    Assert.AreEqual(true, isVotesChanged);
                    Assert.AreEqual(true, isStringValueChanged);

                    Assert.AreEqual(2, newVotes);
                    Assert.AreEqual("Test", newStringValue);
                }
            }
        }
        public void TestWoopsaClientSubscriptionChannelServerRestartAfter()
        {
            bool             isValueChanged = false;
            TestObjectServer objectServer   = new TestObjectServer();

            using (WoopsaClient client = new WoopsaClient(TestingUrl))
            {
                WoopsaUnboundClientObject root         = client.CreateUnboundRoot("");
                WoopsaClientSubscription  subscription = root.Subscribe(nameof(TestObjectServer.Votes),
                                                                        (sender, e) => { isValueChanged = true; },
                                                                        TimeSpan.FromMilliseconds(10), TimeSpan.FromMilliseconds(20));
                using (WoopsaServer server = new WoopsaServer(objectServer, TestingPort))
                {
                    objectServer.Votes = 2;
                    Stopwatch watch = new Stopwatch();
                    watch.Start();
                    while ((!isValueChanged) && (watch.Elapsed < TimeSpan.FromSeconds(2)))
                    {
                        Thread.Sleep(10);
                    }
                    if (isValueChanged)
                    {
                        Console.WriteLine("Notification after {0} ms", watch.Elapsed.TotalMilliseconds);
                    }
                    else
                    {
                        Console.WriteLine("No notification received");
                    }
                    Assert.AreEqual(true, isValueChanged);
                }
                isValueChanged = false;
                using (WoopsaServer server = new WoopsaServer(objectServer, TestingPort))
                {
                    objectServer.Votes = 3;
                    Stopwatch watch = new Stopwatch();
                    watch.Start();
                    while ((!isValueChanged) && (watch.Elapsed < TimeSpan.FromSeconds(2)))
                    {
                        Thread.Sleep(10);
                    }
                    if (isValueChanged)
                    {
                        Console.WriteLine("Notification after {0} ms", watch.Elapsed.TotalMilliseconds);
                    }
                    else
                    {
                        Console.WriteLine("No notification received");
                    }
                    Assert.AreEqual(true, isValueChanged);
                }
                subscription.Unsubscribe();
            }
        }
        public void TestWoopsaClientSubscriptionChannel5000SubscriptionsObservableCollection()
        {
            const int objectsCount       = 5000;
            int       totalNotifications = 0;
            ObservableCollection <ManySubscriptionTestObject> list =
                new ObservableCollection <ManySubscriptionTestObject>();

            for (int i = 0; i < objectsCount; i++)
            {
                list.Add(new ManySubscriptionTestObject()
                {
                    Trigger = i
                });
            }
            using (WoopsaServer server = new WoopsaServer(new WoopsaObjectAdapter(null, "list", list, null, null,
                                                                                  WoopsaObjectAdapterOptions.None, WoopsaVisibility.DefaultIsVisible | WoopsaVisibility.IEnumerableObject), TestingPort))
            {
                using (WoopsaClient client = new WoopsaClient(TestingUrl, null, objectsCount))
                {
                    WoopsaBoundClientObject root = client.CreateBoundRoot();
                    for (int i = 0; i < list.Count; i++)
                    {
                        int index = i;
                        WoopsaClientSubscription subscription = root.Subscribe(
                            WoopsaUtils.CombinePath(
                                WoopsaObjectAdapter.EnumerableItemDefaultName(i),
                                nameof(ManySubscriptionTestObject.Trigger)),
                            (sender, e) =>
                        {
                            list[index].HasNotified = true;
                            totalNotifications++;
                        },
                            TimeSpan.FromMilliseconds(10), TimeSpan.FromMilliseconds(200));
                    }
                    Stopwatch watch = new Stopwatch();
                    watch.Start();
                    while ((totalNotifications < objectsCount) && (watch.Elapsed < TimeSpan.FromSeconds(500)))
                    {
                        Thread.Sleep(10);
                    }
                    if (totalNotifications == objectsCount)
                    {
                        Console.WriteLine("All notification after {0} ms", watch.Elapsed.TotalMilliseconds);
                    }
                    else
                    {
                        Console.WriteLine("{0} notification received, {1} expected", totalNotifications, objectsCount);
                    }
                    Assert.AreEqual(objectsCount, totalNotifications);
                }
            }
        }
예제 #5
0
        public void TestWoopsaIsLastCommunicationSuccessful()
        {
            bool             isSuccessfull = false;
            TestObjectServer objectServer  = new TestObjectServer();

            using (WoopsaClient client = new WoopsaClient("http://localhost/woopsa"))
            {
                WoopsaUnboundClientObject root         = client.CreateUnboundRoot("root");
                WoopsaClientSubscription  subscription = root.Subscribe(nameof(TestObjectServer.Votes),
                                                                        (sender, e) => {  },
                                                                        TimeSpan.FromMilliseconds(10), TimeSpan.FromMilliseconds(20));
                client.ClientProtocol.IsLastCommunicationSuccessfulChange +=
                    (sender, e) =>
                {
                    isSuccessfull = client.ClientProtocol.IsLastCommunicationSuccessful;
                };
                Stopwatch watch = new Stopwatch();
                using (WoopsaServer server = new WoopsaServer(objectServer))
                {
                    watch.Restart();
                    while ((!isSuccessfull) && (watch.Elapsed < TimeSpan.FromSeconds(20)))
                    {
                        Thread.Sleep(10);
                    }
                    if (isSuccessfull)
                    {
                        Console.WriteLine("Sucessful after {0} ms", watch.Elapsed.TotalMilliseconds);
                    }
                    else
                    {
                        Console.WriteLine("No successful communication");
                    }
                    Assert.IsTrue(isSuccessfull);
                }
                watch.Restart();
                while ((isSuccessfull) && (watch.Elapsed < TimeSpan.FromSeconds(20)))
                {
                    Thread.Sleep(10);
                }
                if (!isSuccessfull)
                {
                    Console.WriteLine("Communication loss detected after {0} ms", watch.Elapsed.TotalMilliseconds);
                }
                else
                {
                    Console.WriteLine("No communication loss detection");
                }
                Assert.IsFalse(isSuccessfull);
                subscription.Unsubscribe();
            }
        }
예제 #6
0
        public void TestWoopsaMultiRequest()
        {
            WoopsaObject           serverRoot   = new WoopsaObject(null, "");
            TestObjectMultiRequest objectServer = new TestObjectMultiRequest();
            WoopsaObjectAdapter    adapter      = new WoopsaObjectAdapter(serverRoot, "TestObject", objectServer);

            using (WoopsaServer server = new WoopsaServer(serverRoot))
            {
                using (WoopsaClient client = new WoopsaClient("http://localhost/woopsa"))
                {
                    ExecuteMultiRequestTestSerie(client, objectServer);
                }
            }
        }
예제 #7
0
        public void TestWoopsaMultiRequestNoRemoteMultiRequestService()
        {
            WoopsaObject           serverRoot   = new WoopsaObject(null, "");
            TestObjectMultiRequest objectServer = new TestObjectMultiRequest();
            WoopsaObjectAdapter    adapter      = new WoopsaObjectAdapter(serverRoot, "TestObject", objectServer);

            using (WoopsaServer server = new WoopsaServer((IWoopsaContainer)serverRoot, TestingPort))
            {
                using (WoopsaClient client = new WoopsaClient(TestingUrl))
                {
                    ExecuteMultiRequestTestSerie(client, objectServer);
                }
            }
        }
        public RaspberryPi(ILogger <RaspberryPi> logger, IGpio gpio, ICamera camera)
        {
            _logger       = logger;
            _woopsaServer = new WoopsaServer(this);
            _woopsaServer.Authenticator = new SimpleAuthenticator("Raspberry",
                                                                  (sender, e) => e.IsAuthenticated = e.Username == "admin" && e.Password == "admin");

            _gpio   = gpio;
            _camera = camera;
            _logger.LogDebug("Raspberry pi created");


            //TODO : to that more dynamically
            _woopsaServer.WebServer.Routes.Add("camera", HTTPMethod.GET, new RouteHandlerFileSystem(Camera.SharedFolder));
        }
예제 #9
0
        static void Main(string[] args)
        {
            var          root   = new WoopsaObject(null, "Gateway.IoT");
            WoopsaClient client = new WoopsaClient("http://192.168.1.66/woopsa", root);

            client.Username = "******";
            client.Password = "******";

            client.CreateBoundRoot("device_garage");

            var woopsaServer = new WoopsaServer(root, 10443);

            woopsaServer.Authenticator = new SimpleAuthenticator("Raspberry",
                                                                 (sender, e) => e.IsAuthenticated = e.Username == "admin" && e.Password == "admin");
        }
예제 #10
0
        public void TestWoopsaProtocolRootContainer()
        {
            WoopsaRoot          serverRoot   = new WoopsaRoot();
            TestObjectServer    objectServer = new TestObjectServer();
            WoopsaObjectAdapter adapter      = new WoopsaObjectAdapter(serverRoot, "TestObject", objectServer);

            using (WoopsaServer server = new WoopsaServer(serverRoot))
            {
                using (WoopsaClient client = new WoopsaClient("http://localhost/woopsa"))
                {
                    WoopsaBoundClientObject root = client.CreateBoundRoot();
                    (root.Items.ByName("TestObject") as WoopsaObject).Properties.ByName("Votes").Value = 17;
                    Assert.AreEqual(objectServer.Votes, 17);
                }
            }
        }
        public void TestWoopsaClientSubscriptionDisappearingProperty()
        {
            bool       isValueChanged = false;
            MainClass  objectServer   = new MainClass();
            InnerClass inner          = new InnerClass();

            objectServer.Inner = inner;
            using (WoopsaServer server = new WoopsaServer(objectServer, TestingPort))
            {
                using (WoopsaClient client = new WoopsaClient(TestingUrl))
                {
                    WoopsaBoundClientObject  root         = client.CreateBoundRoot();
                    WoopsaObject             Inner        = root.Items.ByName(nameof(MainClass.Inner)) as WoopsaObject;
                    WoopsaClientProperty     propertyInfo = Inner.Properties.ByName(nameof(InnerClass.Info)) as WoopsaClientProperty;
                    WoopsaClientSubscription subscription = propertyInfo.Subscribe(
                        (sender, e) =>
                    {
                        isValueChanged = true;
                    },
                        TimeSpan.FromMilliseconds(10), TimeSpan.FromMilliseconds(20));
                    inner.Info = "Test";
                    Stopwatch watch = new Stopwatch();
                    watch.Start();
                    while ((!isValueChanged) && (watch.Elapsed < TimeSpan.FromSeconds(20)))
                    {
                        Thread.Sleep(10);
                    }
                    if (isValueChanged)
                    {
                        Console.WriteLine("Notification after {0} ms", watch.Elapsed.TotalMilliseconds);
                    }
                    else
                    {
                        Console.WriteLine("No notification received");
                    }
                    isValueChanged     = false;
                    objectServer.Inner = new BaseInnerClass();
                    //                    objectServer.Inner = new object();
                    while ((!isValueChanged) && (watch.Elapsed < TimeSpan.FromSeconds(20)))
                    {
                        Thread.Sleep(10);
                    }
                    subscription.Unsubscribe();
                    Assert.AreEqual(true, isValueChanged);
                }
            }
        }
예제 #12
0
        public void Load()
        {
            _rootWoopsaObject = new WoopsaObject(null, "root");
            _woopsaServer     = new WoopsaServer(_rootWoopsaObject, port);
            _woopsaServer.WebServer.Routes.Add("/Pages", HTTPMethod.GET, new RouteHandlerFileSystem(folderPathWebPages));
            Thread thread;

            #region infoDebug
            DiagnosticWindow.AddToDebug("\nWoopsa server listening on http://localhost:" + _woopsaServer.WebServer.Port + _woopsaServer.RoutePrefix);
            DiagnosticWindow.AddToDebug("Some examples of what you can do directly from your browser:");
            DiagnosticWindow.AddToDebug(" * View the object hierarchy of the root object:");
            DiagnosticWindow.AddToDebug("   http://localhost:" + _woopsaServer.WebServer.Port + _woopsaServer.RoutePrefix + "meta/");
            DiagnosticWindow.AddToDebug(" * Read the value of a property:");
            DiagnosticWindow.AddToDebug("   http://localhost:" + _woopsaServer.WebServer.Port + _woopsaServer.RoutePrefix + "read/Temperature ");
            DiagnosticWindow.AddToDebug(" * Surfing on the web pages found in the directory \n   specified in Advanced Settings :");
            DiagnosticWindow.AddToDebug("   http://localhost:" + _woopsaServer.WebServer.Port + "/Pages/ \n");

            #endregion

            bool allThreadAreAbort;
            do
            {
                lock (_thisLock)
                {
                    allThreadAreAbort = _allThreadAreAbort;
                }
            }while (!allThreadAreAbort);
            DiagnosticWindow.ResetPlcStatus();
            _woopsaAdsThreadList = new List <Thread>();
            lock (plcParameterList)
            {
                _shouldStop = false;
            }

            foreach (PlcParameter parameter in plcParameterList)
            {
                thread      = new Thread(Start);
                thread.Name = "WoopsaAdsController - " + parameter.name;
                thread.Start(parameter);
                _woopsaAdsThreadList.Add(thread);
            }
            lock (_thisLock)
            {
                _allThreadAreAbort = false;
            }
            isRunning = true;
        }
예제 #13
0
        public void TestWoopsaProtocolUnboundClient()
        {
            TestObjectServer objectServer = new TestObjectServer();

            using (WoopsaClient client = new WoopsaClient("http://localhost/woopsa"))
            {
                WoopsaUnboundClientObject root         = client.CreateUnboundRoot("root");
                WoopsaProperty            propertyVote = root.GetProperty("Votes", WoopsaValueType.Integer, false);
                using (WoopsaServer server = new WoopsaServer(objectServer))
                {
                    propertyVote.Value = new WoopsaValue(123);
                    Assert.AreEqual(objectServer.Votes, 123);
                    var result = propertyVote.Value;
                    Assert.AreEqual(result.ToInt64(), 123);
                }
            }
        }
예제 #14
0
        public void ShutDown()
        {
            lock (plcParameterList)
            {
                _shouldStop = true;
            }

            // Thread to liberate de mainThread because another thread use Dispatcher.Invoke
            Thread joinWoopsaAdsThread = new Thread(() => JoinWoopsaAdsThread(_woopsaAdsThreadList));

            joinWoopsaAdsThread.Name = "Join WoopsaAdsThread";
            joinWoopsaAdsThread.Start();

            isRunning = false;
            _woopsaServer.Dispose();
            _woopsaServer = null;
        }
        public void TestWoopsaDynamicNotificationUnexistingProperty()
        {
            TestObjectServer objectServer = new TestObjectServer();

            using (WoopsaServer server = new WoopsaServer(objectServer, TestingPort))
            {
                // Solution with dynamic client
                using (dynamic dynamicClient = new WoopsaDynamicClient(TestingUrl))
                {
                    int channel = dynamicClient.SubscriptionService.CreateSubscriptionChannel(QUEUE_SIZE);
                    // Subscription for an nonexistent variable (should work)
                    dynamicClient.SubscriptionService.RegisterSubscription(channel,
                                                                           WoopsaValue.WoopsaRelativeLink("/Vote"), TimeSpan.FromMilliseconds(MONITOR_INTERVAL),
                                                                           TimeSpan.FromMilliseconds(PUBLISH_INTERVAL));

                    Stopwatch      watch = new Stopwatch();
                    WoopsaValue    lastNotifications;
                    WoopsaJsonData jsonData;
                    int            lastNotificationId;
                    watch.Start();
                    do
                    {
                        lastNotifications = dynamicClient.SubscriptionService.WaitNotification(channel, 0);
                        Assert.AreEqual(lastNotifications.Type, WoopsaValueType.JsonData);
                        jsonData = lastNotifications.JsonData;
                        if (watch.ElapsedMilliseconds > 1000)
                        {
                            Assert.Fail("Timeout without receveiving any notification");
                        }
                    }while (jsonData.Length == 0);
                    lastNotificationId = jsonData[jsonData.Length - 1]["Id"];
                    Assert.AreEqual(lastNotificationId, 1);
                    // Get again the same notification
                    lastNotifications = dynamicClient.SubscriptionService.WaitNotification(channel, 0);
                    jsonData          = lastNotifications.JsonData;
                    Assert.IsTrue(jsonData.IsArray);
                    Assert.AreEqual(jsonData.Length, 1);
                    Assert.IsTrue(jsonData[0].IsDictionary);
                    lastNotificationId = jsonData[jsonData.Length - 1]["Id"];
                    Assert.AreEqual(lastNotificationId, 1);
                }
            }
        } //end TestWoopsaDynamicNotification
예제 #16
0
        static void Main(string[] args)
        {
            int refresh = ManageRefreshArg(args);

            VerboseMode = ManageVerboseArg(args);

            try
            {
                JacuzziParameters parameters = JacuzziParameters.DeSerializeOrCreate();
                Jacuzzi           root       = new Jacuzzi(parameters, ManageHostArg(args));
                using (WoopsaServer woopsaServer = new WoopsaServer(root, 10001))
                {
                    woopsaServer.BeforeWoopsaModelAccess += (object sender, EventArgs e) => { Monitor.Enter(root.locker); };
                    woopsaServer.AfterWoopsaModelAccess  += (object sender, EventArgs e) => { Monitor.Exit(root.locker); };

                    woopsaServer.WebServer.Routes.Add("web", HTTPMethod.GET, new RouteHandlerEmbeddedResources("HTML", Assembly.GetEntryAssembly()));
                    woopsaServer.WebServer.Routes.Add("web", HTTPMethod.GET, new RouteHandlerEmbeddedResources("HTML.index.html", Assembly.GetEntryAssembly()));

                    Console.WriteLine("Woopsa server started. Client at http://localhost:10001/web/");

                    for (;;)
                    {
                        try
                        {
                            lock (root.locker)
                                root.CyclicUpdate();
                        }
                        catch (Exception e)
                        {
                            ManageException(e);
                            Thread.Sleep(refresh * 3);
                        }
                        Thread.Sleep(refresh);
                    }
                }
            }
            catch (Exception e)
            {
                ManageException(e);
            }
        }
        public void TestWoopsaClientSubscriptionChannelUnexistingItem()
        {
            TestObjectServer objectServer = new TestObjectServer();

            using (WoopsaServer server = new WoopsaServer(objectServer, TestingPort))
            {
                using (WoopsaClient client = new WoopsaClient(TestingUrl))
                {
                    WoopsaBoundClientObject root = client.CreateBoundRoot();
                    try
                    {
                        WoopsaClientSubscription sub = root.Subscribe("ThisDoesNotExistInTheServer",
                                                                      (sender, e) => { },
                                                                      TimeSpan.FromMilliseconds(10), TimeSpan.FromMilliseconds(20));
                        Assert.Fail();
                    }
                    catch (Exception)
                    {
                    }
                }
            }
        }
        public void TestWoopsaClientSubscriptionChannelNoRemoteSubscriptionService()
        {
            bool           isValueChanged = false;
            WoopsaObject   objectServer   = new WoopsaObject(null, "");
            int            votes          = 0;
            WoopsaProperty propertyVotes  = new WoopsaProperty(objectServer, "Votes", WoopsaValueType.Integer, (p) => votes,
                                                               (p, value) => { votes = value.ToInt32(); });

            using (WoopsaServer server = new WoopsaServer((IWoopsaContainer)objectServer, TestingPort))
            {
                using (WoopsaClient client = new WoopsaClient(TestingUrl))
                {
                    WoopsaBoundClientObject  root         = client.CreateBoundRoot();
                    WoopsaClientSubscription subscription = root.Subscribe(nameof(TestObjectServer.Votes),
                                                                           (sender, e) => { isValueChanged = true; },
                                                                           TimeSpan.FromMilliseconds(10), TimeSpan.FromMilliseconds(20));
                    votes = 2;
                    Stopwatch watch = new Stopwatch();
                    watch.Start();
                    while ((!isValueChanged) && (watch.Elapsed < TimeSpan.FromSeconds(2000)))
                    {
                        Thread.Sleep(10);
                    }
                    if (isValueChanged)
                    {
                        Console.WriteLine("Notification after {0} ms", watch.Elapsed.TotalMilliseconds);
                    }
                    else
                    {
                        Console.WriteLine("No notification received");
                    }
                    subscription.Unsubscribe();
                    Assert.AreEqual(true, isValueChanged);
                }
            }
        }
        public void TestWoopsaIsLastCommunicationSuccessful()
        {
            bool             isSuccessfull = false;
            int              counter       = 0;
            TestObjectServer objectServer  = new TestObjectServer();

            using (WoopsaClient client = new WoopsaClient(TestingUrl))
            {
                Assert.IsFalse(client.ClientProtocol.IsLastCommunicationSuccessful);

                client.ClientProtocol.IsLastCommunicationSuccessfulChange +=
                    (sender, e) =>
                {
                    isSuccessfull = client.ClientProtocol.IsLastCommunicationSuccessful;
                    counter++;
                };
                // Initial & unsuccessful
                try
                {
                    client.ClientProtocol.Read("Not existing");
                }
                catch
                { }
                Assert.IsFalse(isSuccessfull);
                Assert.AreEqual(1, counter);


                WoopsaUnboundClientObject root         = client.CreateUnboundRoot("root");
                WoopsaClientSubscription  subscription = root.Subscribe(nameof(TestObjectServer.Votes),
                                                                        (sender, e) => {  },
                                                                        TimeSpan.FromMilliseconds(10), TimeSpan.FromMilliseconds(20));

                Stopwatch watch = new Stopwatch();
                using (WoopsaServer server = new WoopsaServer(objectServer, TestingPort))
                {
                    watch.Restart();
                    while ((!isSuccessfull) && (watch.Elapsed < TimeSpan.FromSeconds(20)))
                    {
                        Thread.Sleep(10);
                    }
                    if (isSuccessfull)
                    {
                        Console.WriteLine("Sucessful after {0} ms", watch.Elapsed.TotalMilliseconds);
                    }
                    else
                    {
                        Console.WriteLine("No successful communication");
                    }
                    Assert.IsTrue(isSuccessfull);
                }
                watch.Restart();
                while ((isSuccessfull) && (watch.Elapsed < TimeSpan.FromSeconds(20)))
                {
                    Thread.Sleep(10);
                }
                if (!isSuccessfull)
                {
                    Console.WriteLine("Communication loss detected after {0} ms", watch.Elapsed.TotalMilliseconds);
                }
                else
                {
                    Console.WriteLine("No communication loss detection");
                }
                Assert.IsFalse(isSuccessfull);
                subscription.Unsubscribe();
            }
        }
        public void TestWoopsaWaitNotification()
        {
            TestObjectServer objectServer = new TestObjectServer();

            using (WoopsaServer server = new WoopsaServer(objectServer, TestingPort))
            {
                using (WoopsaClient client = new WoopsaClient(TestingUrl))
                {
                    WoopsaBoundClientObject root = client.CreateBoundRoot();
                    // Just to show how to see all items
                    foreach (var item in root.Items)
                    {
                        Console.WriteLine("Item = " + item.Name);
                        if (item.Name == "SubscriptionService")
                        {
                            Console.WriteLine("Trouvé");
                        }
                    }

                    // create a subscription object
                    WoopsaObject subscription = root.Items.ByNameOrNull("SubscriptionService") as WoopsaObject;
                    if (subscription != null)
                    {
                        int          result = 0;
                        WoopsaMethod methodCreateScubscriptionChannel = subscription.Methods.ByNameOrNull("CreateSubscriptionChannel");
                        if (methodCreateScubscriptionChannel != null)
                        {
                            // call the method "CreateSubscriptionChannel" on the server
                            result = methodCreateScubscriptionChannel.Invoke(1000);   // define the queue size
                        }
                        int channel = result;

                        WoopsaMethod methodRegisterScubscription = subscription.Methods.ByNameOrNull("RegisterSubscription");
                        if (methodRegisterScubscription != null)
                        {
                            // call the method "registerScubscription" on the server
                            result = methodRegisterScubscription.Invoke(channel, WoopsaValue.WoopsaRelativeLink("/Votes"), 0.01, 0.01);
                        }
                        int subscriptionNbr = result;

                        WoopsaJsonData jData;
                        WoopsaMethod   methodWaitNotification = subscription.Methods.ByNameOrNull("WaitNotification");
                        if (methodWaitNotification != null)
                        {
                            Stopwatch watch = new Stopwatch();
                            watch.Start();
                            // call the method "WaitNotification" on the server
                            Thread.Sleep(100);
                            jData = methodWaitNotification.Invoke(channel, 0).JsonData;
                            Assert.IsTrue(jData.Length > 0);
                            int lastNotification;
                            lastNotification = jData[0]["Id"];
                            Assert.AreEqual(lastNotification, 1);
                            // Get notifications again
                            Thread.Sleep(100);
                            jData = methodWaitNotification.Invoke(channel, 0).JsonData;
                            Assert.IsTrue(jData.Length > 0);
                            lastNotification = jData[0]["Id"];
                            Assert.AreEqual(lastNotification, 1);
                        }
                    }
                }
            }
        }
예제 #21
0
        static void Main(string[] args)
        {
            try
            {
                WeatherStation root = new WeatherStation();
                bool           done = false;
                using (WoopsaServer woopsaServer = new WoopsaServer(root, 80))
                {
                    Console.WriteLine("Woopsa server listening on http://localhost:{0}{1}", woopsaServer.WebServer.Port, woopsaServer.RoutePrefix);
                    Console.WriteLine("Some examples of what you can do directly from your browser:");
                    Console.WriteLine(" * View the object hierarchy of the root object:");
                    Console.WriteLine("   http://localhost:{0}{1}meta/", woopsaServer.WebServer.Port, woopsaServer.RoutePrefix);
                    Console.WriteLine(" * Read the value of a property:");
                    Console.WriteLine("   http://localhost:{0}{1}read/Temperature", woopsaServer.WebServer.Port, woopsaServer.RoutePrefix);


                    Console.WriteLine();
                    Console.WriteLine("Commands : QUIT, AUTH, NOAUTH");
                    do
                    {
                        Console.Write(">");
                        switch (Console.ReadLine().ToUpper())
                        {
                        case "QUIT":
                            done = true;
                            break;

                        case "AUTH":
                            woopsaServer.Authenticator = new SimpleAuthenticator(
                                "WoopsaDemoServer",
                                (sender, e) => { e.IsAuthenticated = e.Username == "woopsa"; });
                            break;

                        case "NOAUTH":
                            woopsaServer.Authenticator = null;
                            break;

                        default:
                            Console.WriteLine("Invalid command");
                            break;
                        }
                    }while (!done);
                }
            }
            catch (SocketException e)
            {
                // A SocketException is caused by an application already listening on a port in most cases
                // Applications known to use port 80:
                //  - On Windows 10, IIS is on by default on some configurations. Disable it here:
                //    http://stackoverflow.com/questions/30758894/apache-server-xampp-doesnt-run-on-windows-10-port-80
                //  - IIS
                //  - Apache
                //  - Nginx
                //  - Skype
                Console.WriteLine("Error: Could not start Woopsa Server. Most likely because an application is already listening on port 80.");
                Console.WriteLine("Known culprits:");
                Console.WriteLine(" - On Windows 10, IIS is on by default on some configurations.");
                Console.WriteLine(" - Skype");
                Console.WriteLine(" - Apache, nginx, etc.");
                Console.WriteLine("SocketException: {0}", e.Message);
                Console.ReadLine();
            }
        }
        public void TestWoopsaDynamicNotification()
        {
            TestObjectServer objectServer = new TestObjectServer();

            using (WoopsaServer server = new WoopsaServer(objectServer, TestingPort))
            {
                // Solution with dynamic client
                using (dynamic dynamicClient = new WoopsaDynamicClient(TestingUrl))
                {
                    int channel = dynamicClient.SubscriptionService.CreateSubscriptionChannel(QUEUE_SIZE);
                    // Subscription for a valid variable
                    dynamicClient.SubscriptionService.RegisterSubscription(channel,
                                                                           WoopsaValue.WoopsaRelativeLink("/Votes"), TimeSpan.FromMilliseconds(MONITOR_INTERVAL),
                                                                           TimeSpan.FromMilliseconds(PUBLISH_INTERVAL));

                    Stopwatch      watch = new Stopwatch();
                    WoopsaValue    lastNotifications;
                    WoopsaJsonData jsonData;
                    int            lastNotificationId;
                    watch.Start();
                    do
                    {
                        lastNotifications = dynamicClient.SubscriptionService.WaitNotification(channel, 0);
                        Assert.AreEqual(lastNotifications.Type, WoopsaValueType.JsonData);
                        jsonData = lastNotifications.JsonData;
                        if (watch.ElapsedMilliseconds > 1000)
                        {
                            Assert.Fail("Timeout without receveiving any notification");
                        }
                    }while (jsonData.Length == 0);
                    lastNotificationId = jsonData[jsonData.Length - 1]["Id"];
                    Assert.AreEqual(lastNotificationId, 1);
                    // Get again the same notification
                    lastNotifications = dynamicClient.SubscriptionService.WaitNotification(channel, 0);
                    jsonData          = lastNotifications.JsonData;
                    Assert.IsTrue(jsonData.IsArray);
                    Assert.AreEqual(jsonData.Length, 1);
                    Assert.IsTrue(jsonData[0].IsDictionary);
                    lastNotificationId = jsonData[jsonData.Length - 1]["Id"];
                    Assert.AreEqual(lastNotificationId, 1);
                    // Generate a new notification
                    objectServer.Votes++;
                    Thread.Sleep(PUBLISH_INTERVAL * 10);
                    // Check we have now 2
                    lastNotifications = dynamicClient.SubscriptionService.WaitNotification(channel, 0);
                    jsonData          = lastNotifications.JsonData;
                    Assert.IsTrue(jsonData.IsArray);
                    Assert.AreEqual(jsonData.Length, 2);
                    Assert.IsTrue(jsonData[0].IsDictionary);
                    lastNotificationId = jsonData[jsonData.Length - 1]["Id"];
                    Assert.AreEqual(lastNotificationId, 2);
                    // Check we can remove 1 and still have 1
                    lastNotifications = dynamicClient.SubscriptionService.WaitNotification(channel, 1);
                    jsonData          = lastNotifications.JsonData;
                    Assert.AreEqual(jsonData.Length, 1);
                    lastNotificationId = jsonData[jsonData.Length - 1]["Id"];
                    Assert.AreEqual(lastNotificationId, 2);
                    // Enable the code below to test the wait of the timeout when they are 0 notifications pending

                    /*
                     * // Check we can remove 1 and have 0. This takes 5 seconds (we wait the timeout)
                     * lastNotifications = dynamicClient.SubscriptionService.WaitNotification(channel, lastNotificationId);
                     * jsonData = lastNotifications.JsonData;
                     * Assert.AreEqual(jsonData.Length, 0);
                     */
                }
            }
        } //end TestWoopsaDynamicNotification
예제 #23
0
        public void TestWoopsaSubscriptionRemovedWhenServerRestart()
        {
            bool             isValueChanged = false;
            TestObjectServer objectServer   = new TestObjectServer();

            using (WoopsaClient client = new WoopsaClient(TestingUrl))
            {
                using (WoopsaServer server = new WoopsaServer(objectServer, TestingPort))
                    using (WoopsaBoundClientObject root = client.CreateBoundRoot())
                    {
                        using (WoopsaClientSubscription subscription = root.Subscribe(nameof(TestObjectServer.Votes),
                                                                                      (sender, e) => { isValueChanged = true; },
                                                                                      TimeSpan.FromMilliseconds(10), TimeSpan.FromMilliseconds(20)))
                        {
                            Stopwatch watch = new Stopwatch();
                            watch.Start();
                            while ((!isValueChanged) && (watch.Elapsed < TimeSpan.FromSeconds(10)))
                            {
                                Thread.Sleep(10);
                            }

                            Assert.AreEqual(1, client.SubscriptionChannel.RegisteredSubscriptionCount);
                            if (isValueChanged)
                            {
                                Console.WriteLine("Notification after {0} ms", watch.Elapsed.TotalMilliseconds);
                            }
                            else
                            {
                                Console.WriteLine("No notification received");
                            }
                        }
                    }

                Assert.IsTrue(isValueChanged);
                Assert.AreEqual(1, client.SubscriptionChannel.SubscriptionsCount);
                Assert.AreEqual(1, client.SubscriptionChannel.RegisteredSubscriptionCount);

                isValueChanged = false;
                using (WoopsaServer server = new WoopsaServer(objectServer, TestingPort))
                    using (WoopsaBoundClientObject root = client.CreateBoundRoot())
                    {
                        using (WoopsaClientSubscription subscription = root.Subscribe(nameof(TestObjectServer.Votes),
                                                                                      (sender, e) => { isValueChanged = true; },
                                                                                      TimeSpan.FromMilliseconds(10), TimeSpan.FromMilliseconds(20)))
                        {
                            Stopwatch watch = new Stopwatch();
                            watch.Start();
                            while ((!isValueChanged) && (watch.Elapsed < TimeSpan.FromSeconds(10)))
                            {
                                Thread.Sleep(10);
                            }

                            Assert.AreEqual(1, client.SubscriptionChannel.RegisteredSubscriptionCount);
                            if (isValueChanged)
                            {
                                Console.WriteLine("Notification after {0} ms", watch.Elapsed.TotalMilliseconds);
                            }
                            else
                            {
                                Console.WriteLine("No notification received");
                            }
                        }
                    }
                Assert.IsTrue(isValueChanged);
                Assert.AreEqual(1, client.SubscriptionChannel.SubscriptionsCount);
                Assert.AreEqual(1, client.SubscriptionChannel.RegisteredSubscriptionCount);
            }
        }