Beispiel #1
0
        /// <summary>
        /// Removes the all subscriptions asiciated to the specified IModule from the SharedVariableSubscriptionList.
        /// </summary>
        /// <param name="module">The IModule used to remove the subscriptions.</param>
        /// <returns>true if items was successfully removed from the SharedVariableSubscriptionList; otherwise, false. This method also returns false if item is not found in the original SharedVariableSubscriptionList</returns>
        public bool Remove(IModuleClient module)
        {
            bool result;
            Queue <SharedVariableSubscription> removed;

            result = false;
            rwLock.AcquireWriterLock(-1);
            removed = new Queue <SharedVariableSubscription>(subscriptions.Capacity);
            for (int i = 0; i < subscriptions.Count; ++i)
            {
                if (subscriptions[i].Subscriber == module)
                {
                    removed.Enqueue(subscriptions[i]);
                    subscriptions.RemoveAt(i);
                    --i;
                    result = true;
                }
            }
            rwLock.ReleaseWriterLock();

            foreach (SharedVariableSubscription subscription in removed)
            {
                OnSubscriptionRemoved(subscription);
            }

            return(result);
        }
Beispiel #2
0
 public InMemoryMessageBroker(IModuleClient moduleClient, MessagingOptions messagingOptions,
                              IAsynchronousDispatcher asynchronousDispatcher)
 {
     _moduleClient           = moduleClient;
     _messagingOptions       = messagingOptions;
     _asynchronousDispatcher = asynchronousDispatcher;
 }
Beispiel #3
0
        public async Task CreateFromEnvironment_NoRuntimeInfoProvider(
            Option <UpstreamProtocol> upstreamProtocol,
            Option <IWebProxy> webProxy,
            string productInfo)
        {
            // Arrange
            ITransportSettings receivedTransportSettings = null;

            var sdkModuleClient = new Mock <ISdkModuleClient>();

            var sdkModuleClientProvider = new Mock <ISdkModuleClientProvider>();

            sdkModuleClientProvider.Setup(s => s.GetSdkModuleClient(It.IsAny <ITransportSettings>()))
            .Callback <ITransportSettings>(t => receivedTransportSettings = t)
            .ReturnsAsync(sdkModuleClient.Object);

            bool     closeOnIdleTimeout            = false;
            TimeSpan idleTimeout                   = TimeSpan.FromMinutes(5);
            ConnectionStatusChangesHandler handler = (status, reason) => { };

            // Act
            var moduleClientProvider = new ModuleClientProvider(
                sdkModuleClientProvider.Object,
                Option.None <Task <IRuntimeInfoProvider> >(),
                upstreamProtocol,
                webProxy,
                productInfo,
                closeOnIdleTimeout,
                idleTimeout,
                false);
            IModuleClient moduleClient = await moduleClientProvider.Create(handler);

            // Write product info explicitly
            sdkModuleClient.Verify(s => s.SetProductInfo(productInfo), Times.Once);
        }
Beispiel #4
0
        async Task <IModuleClient> InitModuleClient()
        {
            using (await this.stateLock.LockAsync())
            {
                IModuleClient moduleClient = await this.moduleClient
                                             .Filter(m => m.IsActive)
                                             .Map(Task.FromResult)
                                             .GetOrElse(
                    async() =>
                {
                    IModuleClient mc = await this.moduleClientProvider.Create(this.connectionStatusChangesHandler);

                    if (this.enableSubscriptions)
                    {
                        await this.EnableSubscriptions(mc);
                    }

                    mc.Closed        += this.OnModuleClientClosed;
                    this.moduleClient = Option.Some(mc);
                    Events.InitializedNewModuleClient(this.enableSubscriptions);
                    return(mc);
                });

                return(moduleClient);
            }
        }
Beispiel #5
0
        async Task RefreshTwinAsync()
        {
            try
            {
                // if GetTwinAsync fails its possible that it might be due to transient network errors or because
                // we are getting throttled by IoT Hub; if we didn't attempt a retry then this object would be
                // stuck in an "error" state till either the connection status on the underlying device connection
                // changes or we receive a patch deployment; doing an exponential back-off retry here allows us to
                // recover from this situation
                var retryPolicy = new RetryPolicy(AllButFatalErrorDetectionStrategy, this.retryStrategy);
                retryPolicy.Retrying += (_, args) => Events.RetryingGetTwin(args);
                IModuleClient dc   = this.deviceClient.Expect(() => new InvalidOperationException("DeviceClient not yet initialized"));
                Twin          twin = await retryPolicy.ExecuteAsync(() => dc.GetTwinAsync());

                this.desiredProperties  = twin.Properties.Desired;
                this.reportedProperties = Option.Some(twin.Properties.Reported);
                await this.UpdateDeploymentConfig();

                Events.TwinRefreshSuccess();
                this.ResetRefreshTimer();
            }
            catch (Exception ex) when(!ex.IsFatal())
            {
                this.deploymentConfigInfo = Option.Some(new DeploymentConfigInfo(this.desiredProperties?.Version ?? 0, ex));
                Events.TwinRefreshError(ex);
            }
        }
Beispiel #6
0
 /// <summary>
 /// Gets the element with the specified name
 /// </summary>
 /// <param name="moduleName">The name of the module element to get or set</param>
 /// <returns>The module with specified name</returns>
 public IModuleClient this[string moduleName]
 {
     get
     {
         this.rwLock.AcquireReaderLock(-1);
         if (!this.modulesDicc.ContainsKey(moduleName))
         {
             this.rwLock.ReleaseReaderLock();
             throw new ArgumentException("The module is not currently a member of the collection");
         }
         IModuleClient mc = this.modules[this.modulesDicc[moduleName]];
         this.rwLock.ReleaseReaderLock();
         return(mc);
     }
     set
     {
         if (value == null)
         {
             throw new ArgumentNullException();
         }
         this.rwLock.AcquireWriterLock(-1);
         if (!this.modulesDicc.ContainsKey(moduleName))
         {
             this.rwLock.ReleaseWriterLock();
             throw new ArgumentException("The module is not currently a member of the collection");
         }
         this.modules[this.modulesDicc[moduleName]] = value;
         this.rwLock.ReleaseWriterLock();
     }
 }
        /// <summary>
        /// Receive a Balloon Message, need to transmit the data in a new TrackerMessage
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public async Task <bool> Receive(BalloonMessage balloonMessage, IModuleClient moduleClient)
        {
            Logger.LogInfo($"Received Balloon Message.");
            UpdatePacketReceiveHistory(true);
            packetReceiptTimer.Change(packetReceiptInterval, packetReceiptInterval);

            this.FlightId = balloonMessage.FlightId;

            var trackerMessage = new TrackerMessage()
            {
                Location   = this.Location,
                DeviceName = this.DeviceName,
                FlightId   = balloonMessage.FlightId,
                PacketReceivedPercentage = CalculatePacketReceivedPercentage()
            };

            try
            {
                Message balloonMessageRaw = new Message(balloonMessage.ToRawBytes());
                await moduleClient.SendEventAsync(TrackerOutputName, balloonMessageRaw);

                Message trackerMessageRaw = new Message(trackerMessage.ToRawBytes());
                await moduleClient.SendEventAsync(TrackerOutputName, trackerMessageRaw);

                Logger.LogInfo($"transmitted message: {JsonConvert.SerializeObject(trackerMessage)}.");
            }
            catch (Exception ex)
            {
                // Todo - wire in with application insights
                Logger.LogWarning($"Error Transmitter tracker message: {ex.Message}");
                return(false);
            }

            return(true);
        }
Beispiel #8
0
 public BackgroundDispatcher(IMessageChannel messageChannel, IModuleClient moduleClient,
                             ILogger <BackgroundDispatcher> logger)
 {
     _messageChannel = messageChannel;
     _moduleClient   = moduleClient;
     _logger         = logger;
 }
        /// <summary>
        /// Ctor
        /// </summary>
        public IoTHubTwinConfigurationProvider()
        {
            AgentConfiguration.AgentConfigurationChanged += UpdateReportedProperties;

            _moduleClient = ModuleClientProvider.GetClient();
            _moduleClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertyUpdateCallback, null);
        }
Beispiel #10
0
 /// <summary>
 /// Manages the changes on the ready status of a module to update shared variables.
 /// </summary>
 /// <param name="sender">The module which Ready status changed</param>
 private void module_ReadyChanged(IModuleClient sender)
 {
     if (sharedVariables.Contains("ready"))
     {
         sharedVariables["ready"].ReportSubscribers(sender);
     }
 }
Beispiel #11
0
        /// <inheritdoc />
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            try
            {
                _moduleClient = _serviceProvider.GetService <IModuleClient>();
                if (_moduleClient is null)
                {
                    throw new InvalidOperationException("IModuleClient not found.");
                }

                await _moduleClient.OpenAsync().ConfigureAwait(false);

                _logger.LogInformation("IoT Hub module client initialized.");

                await ConfigureStartupAsync().ConfigureAwait(false);

                await ConfigureMethodsAsync().ConfigureAwait(false);

                await ConfigureMessagesAsync().ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error occurred on startup");
                throw;
            }
        }
 public InMemoryMessageBroker(IModuleClient moduleClient, IAsyncMessageDispatcher asyncMessageDispatcher,
                              MessagingOptions messagingOptions)
 {
     _moduleClient           = moduleClient;
     _asyncMessageDispatcher = asyncMessageDispatcher;
     _messagingOptions       = messagingOptions;
 }
Beispiel #13
0
        /// <summary>
        /// Removes the specified Module from the parent Blackboard's ModuleCollection object
        /// </summary>
        /// <param name="item">The Module to be removed</param>
        /// <returns>true if the specified Module exists in the collection; otherwise, false</returns>
        public bool Remove(IModuleClient item)
        {
            if (item == null)
            {
                return(false);
            }
            this.rwLock.AcquireWriterLock(-1);
            if (!this.modulesDicc.ContainsKey(item.Name))
            {
                this.rwLock.ReleaseWriterLock();
                return(false);
            }
            item.Parent = null;
            int index = this.modulesDicc[item.Name];

            this.modulesDicc.Remove(item.Name);
            this.modules.RemoveAt(index);
            for (int i = index; i < this.modules.Count; ++i)
            {
                this.modulesDicc[this.modules[i].Name] = i;
            }
            this.rwLock.ReleaseWriterLock();
            if (ModuleRemoved != null)
            {
                ModuleRemoved(item);
            }
            return(true);
        }
Beispiel #14
0
        async Task <Option <Twin> > GetTwinFromIoTHub()
        {
            try
            {
                async Task <Twin> GetTwinFunc()
                {
                    Events.GettingModuleClient();
                    IModuleClient moduleClient = await this.moduleConnection.GetOrCreateModuleClient();

                    Events.GotModuleClient();
                    return(await moduleClient.GetTwinAsync());
                }

                // if GetTwinAsync fails its possible that it might be due to transient network errors or because
                // we are getting throttled by IoT Hub; if we didn't attempt a retry then this object would be
                // stuck in an "error" state till either the connection status on the underlying device connection
                // changes or we receive a patch deployment; doing an exponential back-off retry here allows us to
                // recover from this situation
                var retryPolicy = new RetryPolicy(AllButFatalErrorDetectionStrategy, this.retryStrategy);
                retryPolicy.Retrying += (_, args) => Events.RetryingGetTwin(args);
                Twin twin = await retryPolicy.ExecuteAsync(GetTwinFunc);

                Events.GotTwin(twin);
                return(Option.Some(twin));
            }
            catch (Exception e)
            {
                Events.ErrorGettingTwin(e);
                return(Option.None <Twin>());
            }
        }
Beispiel #15
0
        public async Task CreateFromEnvironmentTest(
            Option <UpstreamProtocol> upstreamProtocol,
            Option <IWebProxy> webProxy,
            string productInfo)
        {
            // Arrange
            ITransportSettings receivedTransportSettings = null;

            var sdkModuleClient = new Mock <ISdkModuleClient>();

            var sdkModuleClientProvider = new Mock <ISdkModuleClientProvider>();

            sdkModuleClientProvider.Setup(s => s.GetSdkModuleClient(It.IsAny <ITransportSettings>()))
            .Callback <ITransportSettings>(t => receivedTransportSettings = t)
            .ReturnsAsync(sdkModuleClient.Object);

            bool     closeOnIdleTimeout            = false;
            TimeSpan idleTimeout                   = TimeSpan.FromMinutes(5);
            ConnectionStatusChangesHandler handler = (status, reason) => { };

            // Act
            var moduleClientProvider = new ModuleClientProvider(
                sdkModuleClientProvider.Object,
                upstreamProtocol,
                webProxy,
                productInfo,
                closeOnIdleTimeout,
                idleTimeout,
                false);
            IModuleClient moduleClient = await moduleClientProvider.Create(handler);

            // Assert
            Assert.NotNull(moduleClient);
            sdkModuleClientProvider.Verify(s => s.GetSdkModuleClient(It.IsAny <ITransportSettings>()), Times.Once);

            sdkModuleClient.Verify(s => s.SetProductInfo(productInfo), Times.Once);

            Assert.NotNull(receivedTransportSettings);
            UpstreamProtocol up = upstreamProtocol.GetOrElse(UpstreamProtocol.Amqp);

            Assert.Equal(up, moduleClient.UpstreamProtocol);
            switch (up)
            {
            case UpstreamProtocol.Amqp:
            case UpstreamProtocol.AmqpWs:
                var amqpTransportSettings = receivedTransportSettings as AmqpTransportSettings;
                Assert.NotNull(amqpTransportSettings);
                webProxy.ForEach(w => Assert.Equal(w, amqpTransportSettings.Proxy));
                break;

            case UpstreamProtocol.Mqtt:
            case UpstreamProtocol.MqttWs:
                var mqttTransportSettings = receivedTransportSettings as MqttTransportSettings;
                Assert.NotNull(mqttTransportSettings);
                webProxy.ForEach(w => Assert.Equal(w, mqttTransportSettings.Proxy));
                break;
            }

            sdkModuleClient.Verify(s => s.OpenAsync(), Times.Once);
        }
Beispiel #16
0
        /// <summary>
        /// Adds the specified Module object to the collection.
        /// </summary>
        /// <param name="item">The Module to add to the collection</param>
        public void Add(IModuleClient item)
        {
            if (item == null)
            {
                throw new ArgumentNullException();
            }

            this.rwLock.AcquireWriterLock(-1);
            if (this.modulesDicc.ContainsKey(item.Name))
            {
                this.rwLock.ReleaseWriterLock();
                throw new ArgumentException("Another element with the same name exists in the collection");
            }
            item.Parent = owner;
            this.modules.Add(item);
            this.modulesDicc.Add(item.Name, 0);
            modules.Sort();
            for (int i = 0; i < this.modules.Count; ++i)
            {
                this.modulesDicc[this.modules[i].Name] = i;
            }
            this.rwLock.ReleaseWriterLock();
            if (ModuleAdded != null)
            {
                ModuleAdded(item);
            }
        }
 public MessageEmitter(IModuleClient moduleClient, CancellationTokenSource cancellationTokenSource)
 {
     MessageIndex            = 0;
     IntervalInMilliseconds  = 1000;
     ModuleClient            = moduleClient;
     CancellationTokenSource = cancellationTokenSource;
 }
Beispiel #18
0
        async Task <IModuleClient> InitModuleClient()
        {
            using (await this.stateLock.LockAsync())
            {
                IModuleClient moduleClient = await this.moduleClient
                                             .Filter(m => m.IsActive)
                                             .Map(Task.FromResult)
                                             .GetOrElse(
                    async() =>
                {
                    IModuleClient mc = await this.moduleClientProvider.Create(this.connectionStatusChangesHandler);
                    mc.Closed       += this.OnModuleClientClosed;
                    if (this.enableSubscriptions)
                    {
                        await mc.SetDefaultMethodHandlerAsync(this.MethodCallback);
                        await mc.SetDesiredPropertyUpdateCallbackAsync(this.desiredPropertyUpdateCallback);
                    }

                    this.moduleClient = Option.Some(mc);
                    Events.InitializedNewModuleClient(this.enableSubscriptions);
                    return(mc);
                });

                return(moduleClient);
            }
        }
Beispiel #19
0
        /// <summary>
        /// Sends all subscription messages to the subscribers
        /// </summary>
        /// <param name="writer">The IModule object which requested the write operation</param>
        protected internal void ReportSubscribers(IModuleClient writer)
        {
            // Generate parameters for notify subscription type
            //string pNotify = name + " " + Data.Length.ToString();
            string pNotify = "{ " + type + (isArray ? "[" + ((size != -1) ? size.ToString() : "") + "] " : " ") + name + " } ";
            // Generate parameters for content subscription type
            string pContent = StringToSend + " ";
            // The chosen parameters
            string param;
            // The response object
            Response response;

            OnWritten();
            lock (subscriptions)
            {
                for (int i = 0; i < subscriptions.Count; ++i)
                {
                    switch (subscriptions[i].ReportType)
                    {
                    case SharedVariableReportType.Notify:
                        param = pNotify;
                        break;

                    case SharedVariableReportType.SendContent:
                        param = pContent;
                        break;

                    default:
                        param = pNotify;
                        break;
                    }

                    param   += subscriptions[i].ReportType.ToString();
                    param   += " % " + subscriptions[i].SubscriptionType.ToString();
                    param   += " % " + writer.Name;
                    response = new Response(this.Owner, subscriptions[i].Subscriber, "read_var", param, true);

                    switch (subscriptions[i].SubscriptionType)
                    {
                    case SharedVariableSubscriptionType.Creation:
                        break;

                    case SharedVariableSubscriptionType.WriteAny:
                        response.Send();
                        break;

                    case SharedVariableSubscriptionType.WriteModule:
                        break;

                    case SharedVariableSubscriptionType.WriteOthers:
                    default:
                        if (writer != subscriptions[i].Subscriber)
                        {
                            response.Send();
                        }
                        break;
                    }
                }
            }
        }
Beispiel #20
0
 /// <summary>
 /// Gets the element at the specified index position
 /// </summary>
 /// <param name="i">The zero based index of the element to get or set</param>
 /// <returns>The module at position i</returns>
 public IModuleClient this[int i]
 {
     get
     {
         this.rwLock.AcquireReaderLock(-1);
         if ((i < 0) || (i >= this.modules.Count))
         {
             this.rwLock.ReleaseReaderLock();
             throw new ArgumentOutOfRangeException();
         }
         IModuleClient mc = this.modules[i];
         this.rwLock.ReleaseReaderLock();
         return(mc);
     }
     set
     {
         if (value == null)
         {
             throw new ArgumentNullException();
         }
         this.rwLock.AcquireWriterLock(-1);
         IModuleClient old = modules[i];
         if (old == value)
         {
             this.rwLock.ReleaseWriterLock();
             return;
         }
         this.modules[i] = value;
         this.rwLock.ReleaseWriterLock();
     }
 }
Beispiel #21
0
        /// <summary>
        /// Sends all subscription messages to the subscribers
        /// </summary>
        /// <param name="writer">The IModule object which requested the write operation</param>
        protected override void ReportSubscribers(IModuleClient writer)
        {
            // Generate parameters for notify subscription type
            //string pNotify = name + " " + Data.Length.ToString();
            string pNotify = name;
            // Generate parameters for content subscription type
            string pContent = value.SerializeToRawText();
            // The chosen parameters
            string param;
            // The response object
            Response response;

            lock (subscriptions)
            {
                for (int i = 0; i < subscriptions.Count; ++i)
                {
                    switch (subscriptions[i].ReportType)
                    {
                    case SharedVariableReportType.Notify:
                        param = pNotify;
                        break;

                    case SharedVariableReportType.SendContent:
                        param = pContent;
                        break;

                    default:
                        param = pNotify;
                        break;
                    }

                    param   += "|" + subscriptions[i].ReportType.ToString();
                    param   += "|" + subscriptions[i].SubscriptionType.ToString();
                    param   += "|" + writer.Name;
                    response = new Response(this.Owner, subscriptions[i].Subscriber, "read_var", param, true);

                    switch (subscriptions[i].SubscriptionType)
                    {
                    case SharedVariableSubscriptionType.Creation:
                        break;

                    case SharedVariableSubscriptionType.WriteAny:
                        response.Send();
                        break;

                    case SharedVariableSubscriptionType.WriteModule:
                        break;

                    case SharedVariableSubscriptionType.WriteOthers:
                    default:
                        if (writer != subscriptions[i].Subscriber)
                        {
                            response.Send();
                        }
                        break;
                    }
                }
            }
        }
 /// <summary>
 /// Initializes a new instance of SharedVariableSubscription
 /// </summary>
 /// <param name="variableName">The name of the shared variable</param>
 /// <param name="subscriber">The IModule object that subscribes to the shared variable</param>
 /// <param name="subscriptionType">The type of subscription to the shared variable</param>
 /// <param name="reportType">The report type choosen by the subscriber</param>
 /// <param name="variableSize">The size the variable must match to send a subscription notification. A -1 value indicates any size</param>
 public SharedVariableSubscription(string variableName, IModuleClient subscriber, SharedVariableSubscriptionType subscriptionType, SharedVariableReportType reportType, int variableSize)
 {
     this.reportType       = reportType;
     this.subscriber       = subscriber;
     this.subscriptionType = subscriptionType;
     this.variableName     = variableName;
     this.variableSize     = variableSize;
 }
Beispiel #23
0
 public SimulatorModule(IConfiguration configuration,
                        IModuleClient moduleClient,
                        CancellationTokenSource cancellationTokenSource)
 {
     Configuration           = configuration;
     ModuleClient            = moduleClient;
     CancellationTokenSource = cancellationTokenSource;
 }
Beispiel #24
0
 public MockMessageInjector(IConfiguration configuration,
                            IModuleClient moduleClient,
                            InjectMessageAsyncDelegate injectMessage)
 {
     Configuration = configuration;
     ModuleClient  = moduleClient;
     InjectMessage = injectMessage;
 }
Beispiel #25
0
 public AddGroupHandler(IGroupRepository groupRepository,
                        IModuleClient moduleClient,
                        IClock clock)
 {
     _groupRepository = groupRepository;
     _moduleClient    = moduleClient;
     _clock           = clock;
 }
Beispiel #26
0
 public MessageBroker(IModuleClient moduleClient, IBusPublisher busPublisher,
                      IAsyncMessageDispatcher asyncMessageDispatcher, MessagingOptions messagingOptions)
 {
     _moduleClient           = moduleClient;
     _busPublisher           = busPublisher;
     _asyncMessageDispatcher = asyncMessageDispatcher;
     _messagingOptions       = messagingOptions;
 }
        /// <summary>
        /// Ctor
        /// </summary>
        public IoTHubTwinConfigurationProvider()
        {
            AgentConfiguration.AgentConfigurationChanged += UpdateReportedProperties;

            _moduleClient = ModuleClientProvider.GetClient();
            _moduleClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertyUpdateCallback, null);
            ConfigSectionName = LocalIoTHubConfiguration.IotInterface.RemoteConfigurationObject;
        }
Beispiel #28
0
        public async Task <IModuleClient> GetOrCreateModuleClient()
        {
            IModuleClient moduleClient = await this.moduleClient
                                         .Filter(m => m.IsActive)
                                         .Map(Task.FromResult)
                                         .GetOrElse(this.InitModuleClient);

            return(moduleClient);
        }
Beispiel #29
0
        public Task ConfigureAsync(IModuleClient moduleClient)
        {
            // Use the ConfigureAsync method to configure the module client.
            // The module client is not connected yet. Use this method to save the instance of the module client.
            // _moduleClient = moduleClient;

            Log.Information("Configure");
            return(Task.CompletedTask);
        }
Beispiel #30
0
 /// <summary>
 /// Initiates a new instance of CommandBase
 /// </summary>
 /// <param name="source">Module which generated the command</param>
 /// <param name="destination">Module to which this command will be sent</param>
 /// <param name="command">Command sent</param>
 /// <param name="param">Param sent</param>
 /// <param name="id">id of the command</param>
 public CommandBase(ModuleClient source, ModuleClient destination, string command, string param, int id)
 {
     this.source       = source;
     this.destination  = destination;
     this.parameters   = param;
     this.id           = id;
     this.sentStatus   = SentStatus.NotSentYet;
     this.sendAttempts = 0;
 }
		private void SetupBlackboardModule(IModuleClient iModuleClient)
		{
			if (this.InvokeRequired)
			{
				if (!this.IsHandleCreated || this.Disposing || this.IsDisposed)
					return;
				this.BeginInvoke(dlgSetupBlackboardModule, iModuleClient);
				return;
			}
			ModuleClient mc = iModuleClient as ModuleClient;
			if (mc == null) return;
			mc.StatusChanged += new StatusChangedEH(module_StatusChanged);
			AddModuleButton(mc);
			AddSecondaryModuleButton(mc);
			AddModuleMenu(mc);
		}
 private void module_ResponseReceived(IModuleClient sender, ITextResponse r)
 {
     Response rsp = r as Response;
     if (rsp == null)
         return;
     // A response has been received so it is stored
     lock (responses)
     {
         responses.Add(rsp);
     }
     if(sender == virtualModule)
         Log.WriteLine(6, "<- [" + r.Source.Name + "]: " + r.ToString());
     else
         Log.WriteLine(5, "<- [" + r.Source.Name + "]: " + r.ToString());
 }
 /// <summary>
 /// Compares the current Module with another object of the same type.
 /// </summary>
 /// <param name="other">An object to compare with this object</param>
 /// <returns>A 32-bit signed integer that indicates the relative order of the objects being compared.</returns>
 public int CompareTo(IModuleClient other)
 {
     return name.CompareTo(other.Name);
 }
 private void module_CommandReceived(IModuleClient sender, ITextCommand c)
 {
     Command cmd = c as Command;
     if (c == null)
         return;
     // A command has been received so it is stored
     commandsPending.Produce(cmd);
     if (sender == virtualModule)
         Log.WriteLine(6, "<- [" + c.Source.Name + "]: " + c.ToString());
     else
         Log.WriteLine(5, "<- [" + c.Source.Name + "]: " + c.ToString());
 }
 /// <summary>
 /// Look for a module in the blackboard that supports specified command
 /// </summary>
 /// <param name="commandName">The name of the command to look for</param>
 /// <param name="destination">When this method returns, contains the Module that supports the command
 /// specified, if the conversion succeeded, or null if no module supports the command.
 /// The search fails if the s parameter is a null reference (Nothing in Visual Basic) or is not of the correct format.
 /// This parameter is passed uninitialized</param>
 /// <returns>true if a destination module was found, false otherwise</returns>
 public bool FindDestinationModule(string commandName, out IModuleClient destination)
 {
     IPrototype p;
     return FindDestinationModule(commandName, out destination, out p);
 }
		void BlackboardModuleAdded(IModuleClient module)
		{
			SetupBlackboardModule(module);
		}
Beispiel #37
0
        /// <summary>
        /// Initiates a new instance of Message
        /// </summary>
        /// <param name="source">Module which generated the command</param>
        /// <param name="destination">Module to which this command will be sent</param>
        /// <param name="command">Command name</param>
        /// <param name="param">Parameters of the command</param>
        /// <param name="id">id of the command</param>
        public Command(IModuleClient source, IModuleClient destination, string command, string param, int id)
            : base()
        {
            this.source = source;
            this.destination = destination;
            this.command = command;
            this.parameters = param;
            this.id = id;

            if (source.Parent != destination.Parent)
                throw new Exception("Source and destination modules does not belong to the same blackboard");
            this.prototype = destination.Prototypes[command];
            // Check if command matchs a prototype
            if (this.prototype.ParamsRequired && ((param == null) || (param.Length < 1)))
                throw new Exception("Invalid string. The Command requires parameters");
        }
Beispiel #38
0
        /*

        /// <summary>
        /// Initiates a new instance of Message
        /// </summary>
        /// <param name="source">Module which generated the message</param>
        /// <param name="command">Command sent</param>
        /// <param name="param">Param sent</param>
        public Command(Module source, string command, string param) : this(source, null, command, param, -1) { }

        /// <summary>
        /// Initiates a new instance of Message
        /// </summary>
        /// <param name="source">Module which generated the command</param>
        /// <param name="command">Command name</param>
        /// <param name="param">Parameters of the command</param>
        /// <param name="id">id of the command</param>
        public Command(Module source, string command, string param, int id) : this(source, null, command, param, id) { }

        */
        /// <summary>
        /// Initiates a new instance of Message
        /// </summary>
        /// <param name="source">Module which generated the message</param>
        /// <param name="destination">Module to which this message will be sent</param>
        /// <param name="command">Command sent</param>
        /// <param name="param">Param sent</param>
        public Command(IModuleClient source, IModuleClient destination, string command, string param)
            : this(source, destination, command, param, -1)
        {
        }
Beispiel #39
0
        /// <summary>
        /// Initiates a new instance of Message
        /// </summary>
        /// <param name="source">Module which generated the message</param>
        /// <param name="destination">Module to which this message will be sent</param>
        /// <param name="response">Response sent</param>
        /// <param name="param">Param sent</param>
        /// <param name="id">id of the message</param>
        /// <param name="success">Value that indicates if the command was executed successfully</param>
        public Response(IModuleClient source, IModuleClient destination, string response, string param, bool success, int id)
            : base()
        {
            this.source = source;
            this.destination = destination;
            this.command = response;
            this.parameters = param;
            this.id = id;
            if (this.success = success) failReason = ResponseFailReason.None;
            else failReason = ResponseFailReason.Unknown;
            this.arrivalTime = DateTime.Now;

            if ((destination != null) && (source.Parent != destination.Parent))
                throw new Exception("Source and destination modules does not belong to the same blackboard");
            this.prototype = source.Prototypes[response];
            // Check if response matchs a prototype
            if (this.prototype.ParamsRequired && ((param == null) || (param.Length < 1)))
                throw new Exception("Invalid string. The Response requires parameters");
        }
 /// <summary>
 /// Configures the Module object added to the ModuleCollection of the Blackboard object
 /// </summary>
 /// <param name="module">Module to configure</param>
 private void modules_ModuleAdded(IModuleClient module)
 {
     if (module is ModuleClient)
     {
         ((ModuleClient)module).Connected += new ModuleConnectionEH(module_Connected);
         ((ModuleClient)module).Disconnected += new ModuleConnectionEH(module_Disconnected);
         ((ModuleClient)module).ActionExecuted += new ActionExecutedEH(module_ActionExecuted);
     }
     IPrototype[] aProto = module.Prototypes.ToArray();
     foreach (IPrototype proto in aProto)
         AddPrototype(module, proto);
     module.CommandReceived += new CommandReceivedEH(module_CommandReceived);
     module.ResponseReceived += new ResponseReceivedEH(module_ResponseReceived);
     module.Started += new StatusChangedEH(module_Started);
     module.Stopped += new StatusChangedEH(module_Stopped);
     Log.WriteLine(1, "Added module: " + module.Name);
 }
        /// <summary>
        /// Safely adds support for a new command to the system, avoiding duplicates in a thread-safe way
        /// </summary>
        /// <param name="module">The module which will host the new command</param>
        /// <param name="proto">The prototype which contains command information</param>
        /// <returns>true if the new prototype was added, false otherwise</returns>
        internal bool AddPrototype(IModuleClient module, IPrototype proto)
        {
            if ((proto == null) || (module == null) || !module.Enabled || ((proto is Prototype) && ((Prototype)proto).IsSystem) || !modules.Contains(module))
                return false;

            prototypesLock.AcquireWriterLock(-1);
            if (this.prototypes.ContainsKey(proto.Command))
            {
                //if (this.prototypes[proto.Command] == proto)
                //    return;
                //if ((proto.Parent != null) && this.prototypes[proto.Command].Parent != proto.Parent)
                //    proto.Parent.Prototypes.Remove(proto.Command);
                //return;
                prototypesLock.ReleaseWriterLock();
                return false;

            }
            module.Prototypes.Add(proto);
            this.prototypes.Add(proto.Command, proto);
            prototypesLock.ReleaseWriterLock();
            return true;
        }
 /// <summary>
 /// Look for a module in the blackboard that supports specified command
 /// </summary>
 /// <param name="commandName">The name of the command to look for</param>
 /// <param name="destination">When this method returns, contains the Module that supports the command
 /// specified, if the conversion succeeded, or null if no module supports the command.
 /// The search fails if the s parameter is a null reference (Nothing in Visual Basic) or is not of the correct format.
 /// This parameter is passed uninitialized</param>
 /// <param name="prototype">When this method returns, contains the Prototype for the command
 /// specified, if the conversion succeeded, or null if no module supports the command.
 /// The conversion fails if the s parameter is a null reference (Nothing in Visual Basic) or is not of the correct format.
 /// This parameter is passed uninitialized</param>
 /// <returns>true if a destination module was found, false otherwise</returns>
 public bool FindDestinationModule(string commandName, out IModuleClient destination, out IPrototype prototype)
 {
     destination = null;
     prototype = null;
     if (commandName == null) return false;
     if (VirtualModule.SupportCommand(commandName, out prototype))
     {
         destination = VirtualModule;
         return true;
     }
     this.prototypesLock.AcquireReaderLock(-1);
     if (!this.prototypes.ContainsKey(commandName))
         return false;
     prototype = this.prototypes[commandName];
     destination = prototype.Parent;
     return destination.Enabled;
 }
Beispiel #43
0
 private void WriteModulePrototypes(IModuleClient m)
 {
     foreach (IPrototype p in m.Prototypes)
     {
         if (systemPrototypes.ContainsKey(p.Command))
             continue;
         Console.Write("\t");
         WritePrototype(p);
     }
 }
		private void module_StatusChanged(IModuleClient sender)
		{
			try
			{
				if (this.InvokeRequired)
				{
					if (!this.IsHandleCreated || this.Disposing || this.IsDisposed)
						return;
					this.BeginInvoke(dlgModuleStatusChanged, sender);
					return;
				}
				//moduleButtons[sender.Name].Enabled = sender.IsRunning;
				//moduleButtonsClone[sender.Name].Enabled = sender.IsRunning;

				if (sender == selectedMC)
				{
					if (sender.IsRunning)
					{
						btnModuleStartStopModule.Text = "Stop Module";
						btnModuleStartStopModule.Image = Properties.Resources.Stop_16;
						btnModuleStartStopModule.Enabled = true;
					}
					else
					{
						btnModuleStartStopModule.Text = "Start Module";
						btnModuleStartStopModule.Image = Properties.Resources.run16;
						btnModuleStartStopModule.Enabled = true;
					}
				}

				if (!sender.Enabled)
				{
					moduleButtons[sender.Name].Image = Properties.Resources.ExitRed_16;
					moduleButtonsClone[sender.Name].Image = Properties.Resources.ExitRed_16;
					return;
				}

				if (!sender.IsRunning)
				{
					moduleButtons[sender.Name].Image = Properties.Resources.ExitGreen_16;
					moduleButtonsClone[sender.Name].Image = Properties.Resources.ExitGreen_16;
					return;
				}
				if (sender.Busy)
				{
					moduleButtons[sender.Name].Image = Properties.Resources.busy16;
					moduleButtonsClone[sender.Name].Image = Properties.Resources.busy16;
					return;
				}
				if (!sender.IsConnected)
				{
					moduleButtons[sender.Name].Image = Properties.Resources.err16;
					moduleButtonsClone[sender.Name].Image = Properties.Resources.err16;
					return;
				}
				if (!sender.IsAlive || !sender.Ready)
				{
					moduleButtons[sender.Name].Image = Properties.Resources.wrn16;
					moduleButtonsClone[sender.Name].Image = Properties.Resources.wrn16;
				}
				else
				{
					moduleButtons[sender.Name].Image = Properties.Resources.ok16;
					moduleButtonsClone[sender.Name].Image = Properties.Resources.ok16;
				}
			}
			catch { }
		}
 /// <summary>
 /// Initializes a new instance of the ServerAddressCollection class for the specified parent IModule.
 /// </summary>
 /// <param name="owner">The module that the IP address collection is created for</param>
 internal ServerAddressCollection(IModuleClient owner)
     : this(owner, 10)
 {
 }
Beispiel #46
0
        /*

        /// <summary>
        /// Initiates a new instance of Message
        /// </summary>
        /// <param name="source">Module which generated the message</param>
        /// <param name="response">Response sent</param>
        /// <param name="param">Param sent</param>
        public Response(Module source, string response, string param) : this(source, null, response, param, -1) { }

        /// <summary>
        /// Initiates a new instance of Message
        /// </summary>
        /// <param name="source">Module which generated the message</param>
        /// <param name="response">Response sent</param>
        /// <param name="param">Param sent</param>
        /// <param name="id">id of the message</param>
        public Response(Module source, string response, string param, int id) : this(source, null, response, param, id) { }

        */
        /// <summary>
        /// Initiates a new instance of Message
        /// </summary>
        /// <param name="source">Module which generated the message</param>
        /// <param name="destination">Module to which this message will be sent</param>
        /// <param name="response">Response sent</param>
        /// <param name="param">Param sent</param>
        /// <param name="success">Value that indicates if the command was executed successfully</param>
        public Response(IModuleClient source, IModuleClient destination, string response, string param, bool success)
            : this(source, destination, response, param, success, -1)
        {
        }
 private void module_Stopped(IModuleClient m)
 {
     Log.WriteLine(4, "Stopped module [" + m.Name + "]");
 }
 /// <summary>
 /// Initializes a new instance of the ServerAddressCollection class for the specified parent IModule.
 /// </summary>
 /// <param name="owner">The module that the IP address collection is created for</param>
 /// <param name="capacity">The number of elements that the new ServerAddressCollection can initially store</param>
 internal ServerAddressCollection(IModuleClient owner, int capacity)
 {
     if (owner == null) throw new ArgumentException("Owner cannot be null");
     this.owner = owner;
     this.addresses = new List<IPAddress>(capacity);
 }
 /// <summary>
 /// Overrides the base method WriteStringData to always return false
 /// </summary>
 /// <param name="writer">The IModule object which requested the write operation</param>
 /// <param name="dataType">The received type of the data to update the variable</param>
 /// <param name="arraySize">Specifies the size of the array if the variable was created as an array. If the variable is not an array must be -1</param>
 /// <param name="content">The data in hexadecimal string representation</param>
 /// <returns>false</returns>
 public override bool WriteStringData(IModuleClient writer, string dataType, int arraySize, string content)
 {
     return false;
 }
 /// <summary>
 /// Configures the Module object removed the ModuleCollection of the Blackboard object
 /// </summary>
 /// <param name="module">Module to configure</param>
 private void modules_ModuleRemoved(IModuleClient module)
 {
     if (module is ModuleClient)
     {
         ((ModuleClient)module).Connected -= new ModuleConnectionEH(module_Connected);
         ((ModuleClient)module).Disconnected -= new ModuleConnectionEH(module_Disconnected);
         ((ModuleClient)module).ActionExecuted -= new ActionExecutedEH(module_ActionExecuted);
     }
     IPrototype[] aProto = module.Prototypes.ToArray();
     foreach (IPrototype proto in aProto)
         RemovePrototype(proto);
     module.CommandReceived -= new CommandReceivedEH(module_CommandReceived);
     module.ResponseReceived -= new ResponseReceivedEH(module_ResponseReceived);
     Log.WriteLine(1, "Removed module: " + module.Name);
 }
Beispiel #51
0
        private void WriteModule(IModuleClient m)
        {
            string status;
            ConsoleColor color = Console.ForegroundColor;
            if (!m.Enabled)
            {
                Console.ForegroundColor = ConsoleColor.DarkGray;
                Console.WriteLine("{0} Disabled", m.Name.PadRight(20, ' '));
                Console.ForegroundColor = color;
                return;
            }
            else if (m.Simulation.SimulationEnabled)
            {
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("{0} OK (Simulated)", m.Name.PadRight(20, ' '));
                Console.ForegroundColor = color;
                return;
            }
            else if (!m.IsConnected)
            {
                Console.ForegroundColor = ConsoleColor.DarkRed;
                Console.WriteLine("{0} Disconnected", m.Name.PadRight(20, ' '));
                Console.ForegroundColor = color;
                return;
            }
            else if (!m.IsAlive || !m.Ready)
            {
                status = String.Empty;
                if (!m.Ready) status = "Not ready";
                if (!m.IsAlive) status = (String.IsNullOrEmpty(status) ? "Not responding" : status + ", not responding");
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine("{0} {1}", m.Name.PadRight(20, ' '), status);
                Console.ForegroundColor = color;
                return;
            }

            status = "OK";
            if (m.Busy) status = "Busy";
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("{0} {1}", m.Name.PadRight(20, ' '), status);
            Console.ForegroundColor = color;
        }