/// <summary>
 /// Send an asynchronous request to QLDB.
 /// </summary>
 ///
 /// <param name="request">The request to send.</param>
 /// <param name="cancellationToken">
 ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
 /// </param>
 ///
 /// <returns>The result returned by QLDB for the request.</returns>
 private async Task <SendCommandResponse> SendCommand(
     SendCommandRequest request, CancellationToken cancellationToken)
 {
     request.SessionToken = this.sessionToken;
     this.logger.LogDebug("Sending request: {}", request);
     return(await this.SessionClient.SendCommandAsync(request, cancellationToken));
 }
        /// <summary>
        /// Async factory method for constructing a new Session, creating a new session to QLDB on construction.
        /// </summary>
        ///
        /// <param name="ledgerName">The name of the ledger to create a session to.</param>
        /// <param name="sessionClient">The low-level session used for communication with QLDB.</param>
        /// <param name="logger">The logger to inject any logging framework.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        ///
        /// <returns>A newly created <see cref="Session"/>.</returns>
        internal static async Task <Session> StartSessionAsync(
            string ledgerName,
            IAmazonQLDBSession sessionClient,
            ILogger logger,
            CancellationToken cancellationToken)
        {
            var startSessionRequest = new StartSessionRequest
            {
                LedgerName = ledgerName,
            };
            var request = new SendCommandRequest
            {
                StartSession = startSessionRequest,
            };

            logger.LogDebug("Sending start session request: {}", request);
            var response = await sessionClient.SendCommandAsync(request, cancellationToken);

            return(new Session(
                       ledgerName,
                       sessionClient,
                       response.StartSession.SessionToken,
                       response.ResponseMetadata.RequestId,
                       logger));
        }
Example #3
0
        /// <summary>
        /// Send single command to vehicle
        /// </summary>
        /// <param name="vehicle">Vehicle object</param>
        /// <param name="commandDefinition">Command to send</param>
        /// <param name="addArgumentsFunc">Command parameters</param>
        /// <returns></returns>
        public SendCommandResponse SendSingleCommand(Vehicle vehicle, CommandDefinition commandDefinition, Func <IEnumerable <CommandArgument> > addArgumentsFunc = null)
        {
            SendCommandRequest request = new SendCommandRequest
            {
                ClientId = _connect.AuthorizeHciResponse.ClientId,
                Command  = new UGCS.Sdk.Protocol.Encoding.Command
                {
                    Code      = commandDefinition.Code,
                    Subsystem = commandDefinition.Subsystem,
                }
            };

            request.Vehicles.Add(new Vehicle()
            {
                Id = vehicle.Id
            });
            if (addArgumentsFunc != null)
            {
                request.Command.Arguments.AddRange(addArgumentsFunc());
            }

            var responce = _connect.Executor.Submit <SendCommandResponse>(request);

            responce.Wait();

            if (responce.Value == null)
            {
                return(null);
            }
            return(responce.Value);
        }
        internal virtual async Task <ExecuteStatementResult> ExecuteStatementAsync(
            string txnId, string statement, ValueHolder[] parameters, CancellationToken cancellationToken)
        {
            try
            {
                var executeStatementRequest = new ExecuteStatementRequest
                {
                    TransactionId = txnId,
                    Statement     = statement,
                    Parameters    = parameters.ToList(),
                };
                var request = new SendCommandRequest
                {
                    ExecuteStatement = executeStatementRequest,
                };
                var response = await this.SendCommand(request, cancellationToken);

                return(response.ExecuteStatement);
            }
            catch (IOException e)
            {
                throw new QldbDriverException(ExceptionMessages.FailedToSerializeParameter + e.Message, e);
            }
            finally
            {
                if (parameters != null && parameters.Length != 0)
                {
                    foreach (ValueHolder valueHolder in parameters)
                    {
                        valueHolder.IonBinary.Dispose();
                    }
                }
            }
        }
 public static void Test()
 {
     string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
     ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
     host.AddServiceEndpoint(typeof(ITest), new BasicHttpBinding(), "");
     host.Open();
     Console.WriteLine("Host opened");
     ChannelFactory<ITest> factory = new ChannelFactory<ITest>(new BasicHttpBinding(), new EndpointAddress(baseAddress));
     ITest proxy = factory.CreateChannel();
     SendCommandRequest req = new SendCommandRequest
     {
         CMD = new CMD
         {
             Station = new Station
             {
                 Address = "ABC",
                 Platform = new Platform
                 {
                     Address = "DEF",
                     Command = new string[] { "5" }
                 }
             }
         }
     };
     proxy.SendCommand(req);
     ((IClientChannel)proxy).Close();
     factory.Close();
     Console.Write("Press ENTER to close the host");
     Console.ReadLine();
     host.Close();
 }
Example #6
0
        /// <summary>
        /// Sends a command to an Amazon QLDB ledger.
        ///
        ///  <note>
        /// <para>
        /// Instead of interacting directly with this API, we recommend that you use the Amazon
        /// QLDB Driver or the QLDB Shell to execute data transactions on a ledger.
        /// </para>
        ///  <ul> <li>
        /// <para>
        /// If you are working with an AWS SDK, use the QLDB Driver. The driver provides a high-level
        /// abstraction layer above this <code>qldbsession</code> data plane and manages <code>SendCommand</code>
        /// API calls for you. For information and a list of supported programming languages,
        /// see <a href="https://docs.aws.amazon.com/qldb/latest/developerguide/getting-started-driver.html">Getting
        /// started with the driver</a> in the <i>Amazon QLDB Developer Guide</i>.
        /// </para>
        ///  </li> <li>
        /// <para>
        /// If you are working with the AWS Command Line Interface (AWS CLI), use the QLDB Shell.
        /// The shell is a command line interface that uses the QLDB Driver to interact with a
        /// ledger. For information, see <a href="https://docs.aws.amazon.com/qldb/latest/developerguide/data-shell.html">Accessing
        /// Amazon QLDB using the QLDB Shell</a>.
        /// </para>
        ///  </li> </ul> </note>
        /// </summary>
        /// <param name="request">Container for the necessary parameters to execute the SendCommand service method.</param>
        ///
        /// <returns>The response from the SendCommand service method, as returned by QLDBSession.</returns>
        /// <exception cref="Amazon.QLDBSession.Model.BadRequestException">
        /// Returned if the request is malformed or contains an error such as an invalid parameter
        /// value or a missing required parameter.
        /// </exception>
        /// <exception cref="Amazon.QLDBSession.Model.InvalidSessionException">
        /// Returned if the session doesn't exist anymore because it timed out or expired.
        /// </exception>
        /// <exception cref="Amazon.QLDBSession.Model.LimitExceededException">
        /// Returned if a resource limit such as number of active sessions is exceeded.
        /// </exception>
        /// <exception cref="Amazon.QLDBSession.Model.OccConflictException">
        /// Returned when a transaction cannot be written to the journal due to a failure in the
        /// verification phase of <i>optimistic concurrency control</i> (OCC).
        /// </exception>
        /// <exception cref="Amazon.QLDBSession.Model.RateExceededException">
        /// Returned when the rate of requests exceeds the allowed throughput.
        /// </exception>
        /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/qldb-session-2019-07-11/SendCommand">REST API Reference for SendCommand Operation</seealso>
        public virtual SendCommandResponse SendCommand(SendCommandRequest request)
        {
            var options = new InvokeOptions();

            options.RequestMarshaller    = SendCommandRequestMarshaller.Instance;
            options.ResponseUnmarshaller = SendCommandResponseUnmarshaller.Instance;

            return(Invoke <SendCommandResponse>(request, options));
        }
        /// <summary>
        /// Initiates the asynchronous execution of the SendCommand operation.
        /// </summary>
        ///
        /// <param name="request">Container for the necessary parameters to execute the SendCommand operation on AmazonQLDBSessionClient.</param>
        /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
        /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
        ///          procedure using the AsyncState property.</param>
        ///
        /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndSendCommand
        ///         operation.</returns>
        /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/qldb-session-2019-07-11/SendCommand">REST API Reference for SendCommand Operation</seealso>
        public virtual IAsyncResult BeginSendCommand(SendCommandRequest request, AsyncCallback callback, object state)
        {
            var options = new InvokeOptions();

            options.RequestMarshaller    = SendCommandRequestMarshaller.Instance;
            options.ResponseUnmarshaller = SendCommandResponseUnmarshaller.Instance;

            return(BeginInvoke(request, options, callback, state));
        }
Example #8
0
        /// <summary>
        /// Sends a command to an Amazon QLDB ledger.
        ///
        ///  <note>
        /// <para>
        /// Instead of interacting directly with this API, we recommend that you use the Amazon
        /// QLDB Driver or the QLDB Shell to execute data transactions on a ledger.
        /// </para>
        ///  <ul> <li>
        /// <para>
        /// If you are working with an AWS SDK, use the QLDB Driver. The driver provides a high-level
        /// abstraction layer above this <code>qldbsession</code> data plane and manages <code>SendCommand</code>
        /// API calls for you. For information and a list of supported programming languages,
        /// see <a href="https://docs.aws.amazon.com/qldb/latest/developerguide/getting-started-driver.html">Getting
        /// started with the driver</a> in the <i>Amazon QLDB Developer Guide</i>.
        /// </para>
        ///  </li> <li>
        /// <para>
        /// If you are working with the AWS Command Line Interface (AWS CLI), use the QLDB Shell.
        /// The shell is a command line interface that uses the QLDB Driver to interact with a
        /// ledger. For information, see <a href="https://docs.aws.amazon.com/qldb/latest/developerguide/data-shell.html">Accessing
        /// Amazon QLDB using the QLDB Shell</a>.
        /// </para>
        ///  </li> </ul> </note>
        /// </summary>
        /// <param name="request">Container for the necessary parameters to execute the SendCommand service method.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        ///
        /// <returns>The response from the SendCommand service method, as returned by QLDBSession.</returns>
        /// <exception cref="Amazon.QLDBSession.Model.BadRequestException">
        /// Returned if the request is malformed or contains an error such as an invalid parameter
        /// value or a missing required parameter.
        /// </exception>
        /// <exception cref="Amazon.QLDBSession.Model.InvalidSessionException">
        /// Returned if the session doesn't exist anymore because it timed out or expired.
        /// </exception>
        /// <exception cref="Amazon.QLDBSession.Model.LimitExceededException">
        /// Returned if a resource limit such as number of active sessions is exceeded.
        /// </exception>
        /// <exception cref="Amazon.QLDBSession.Model.OccConflictException">
        /// Returned when a transaction cannot be written to the journal due to a failure in the
        /// verification phase of <i>optimistic concurrency control</i> (OCC).
        /// </exception>
        /// <exception cref="Amazon.QLDBSession.Model.RateExceededException">
        /// Returned when the rate of requests exceeds the allowed throughput.
        /// </exception>
        /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/qldb-session-2019-07-11/SendCommand">REST API Reference for SendCommand Operation</seealso>
        public virtual Task <SendCommandResponse> SendCommandAsync(SendCommandRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var options = new InvokeOptions();

            options.RequestMarshaller    = SendCommandRequestMarshaller.Instance;
            options.ResponseUnmarshaller = SendCommandResponseUnmarshaller.Instance;

            return(InvokeAsync <SendCommandResponse>(request, options, cancellationToken));
        }
        /// <summary>
        /// Send an end session request to QLDB, closing all open results and transactions.
        /// </summary>
        ///
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        ///
        /// <returns>The result of the end session request.</returns>
        internal virtual async Task <EndSessionResult> EndSession(CancellationToken cancellationToken = default)
        {
            var endSessionRequest = new EndSessionRequest();
            var request           = new SendCommandRequest
            {
                EndSession = endSessionRequest,
            };
            var response = await this.SendCommand(request, cancellationToken);

            return(response.EndSession);
        }
        /// <summary>
        /// Send an asynchronous abort request to QLDB, rolling back any active changes and closing any open results.
        /// </summary>
        ///
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        ///
        /// <returns>The result of the abort transaction request.</returns>
        internal virtual async Task <AbortTransactionResult> AbortTransactionAsync(CancellationToken cancellationToken)
        {
            var abortTransactionRequest = new AbortTransactionRequest();
            var request = new SendCommandRequest
            {
                AbortTransaction = abortTransactionRequest,
            };
            var response = await this.SendCommand(request, cancellationToken);

            return(response.AbortTransaction);
        }
Example #11
0
        /// <summary>
        /// Send a start transaction request to QLDB.
        /// </summary>
        ///
        /// <returns>The result of the start transaction request.</returns>
        internal virtual StartTransactionResult StartTransaction()
        {
            var startTransactionRequest = new StartTransactionRequest();
            var request = new SendCommandRequest
            {
                StartTransaction = startTransactionRequest,
            };
            var response = this.SendCommand(request);

            return(response.StartTransaction);
        }
Example #12
0
        /// <summary>
        /// Send an abort request to QLDB, rolling back any active changes and closing any open results.
        /// </summary>
        ///
        /// <returns>The result of the abort transaction request.</returns>
        internal virtual AbortTransactionResult AbortTransaction()
        {
            var abortTransactionRequest = new AbortTransactionRequest();
            var request = new SendCommandRequest
            {
                AbortTransaction = abortTransactionRequest,
            };
            var response = this.SendCommand(request);

            return(response.AbortTransaction);
        }
Example #13
0
        /// <summary>
        /// Send an end session request to QLDB, closing all open results and transactions.
        /// </summary>
        ///
        /// <returns>The result of the end session request.</returns>
        internal virtual EndSessionResult EndSession()
        {
            var endSessionRequest = new EndSessionRequest();
            var request           = new SendCommandRequest
            {
                EndSession = endSessionRequest,
            };
            var response = this.SendCommand(request);

            return(response.EndSession);
        }
        /// <summary>
        /// Send a start transaction request to QLDB.
        ///
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        ///
        /// </summary>
        ///
        /// <returns>The result of the start transaction request.</returns>
        internal virtual async Task <StartTransactionResult> StartTransaction(CancellationToken cancellationToken = default)
        {
            var startTransactionRequest = new StartTransactionRequest();
            var request = new SendCommandRequest
            {
                StartTransaction = startTransactionRequest,
            };
            var response = await this.SendCommand(request, cancellationToken);

            return(response.StartTransaction);
        }
        /// <summary>
        /// Send an asynchronous execute request with parameters to QLDB.
        /// </summary>
        ///
        /// <param name="txnId">The unique ID of the transaction to execute.</param>
        /// <param name="statement">The PartiQL statement to execute.</param>
        /// <param name="parameters">The parameters to use with the PartiQL statement for execution.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        ///
        /// <returns>
        /// The result of the execution, which contains a <see cref="Page"/> representing the first data chunk.
        /// </returns>
        internal virtual async Task <ExecuteStatementResult> ExecuteStatementAsync(
            string txnId, string statement, List <IIonValue> parameters, CancellationToken cancellationToken)
        {
            List <ValueHolder> valueHolders = null;

            try
            {
                valueHolders = parameters.ConvertAll(ionValue =>
                {
                    MemoryStream stream = new MemoryStream();
                    using (var writer = IonBinaryWriterBuilder.Build(stream))
                    {
                        ionValue.WriteTo(writer);
                        writer.Finish();
                    }

                    var valueHolder = new ValueHolder
                    {
                        IonBinary = stream,
                    };
                    return(valueHolder);
                });

                var executeStatementRequest = new ExecuteStatementRequest
                {
                    TransactionId = txnId,
                    Statement     = statement,
                    Parameters    = valueHolders,
                };
                var request = new SendCommandRequest
                {
                    ExecuteStatement = executeStatementRequest,
                };
                var response = await this.SendCommand(request, cancellationToken);

                return(response.ExecuteStatement);
            }
            catch (IOException e)
            {
                throw new QldbDriverException(ExceptionMessages.FailedToSerializeParameter + e.Message, e);
            }
            finally
            {
                if (valueHolders != null)
                {
                    valueHolders.ForEach(valueHolder =>
                    {
                        valueHolder.IonBinary.Dispose();
                    });
                }
            }
        }
        /// <summary>
        /// Send a fetch result request to QLDB, retrieving the next chunk of data for the result.
        /// </summary>
        ///
        /// <param name="txnId">The unique ID of the transaction to execute.</param>
        /// <param name="nextPageToken">The token that indicates what the next expected page is.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        ///
        /// <returns>The result of the <see cref="FetchPageRequest"/>.</returns>
        internal virtual async Task <FetchPageResult> FetchPage(string txnId, string nextPageToken, CancellationToken cancellationToken = default)
        {
            var fetchPageRequest = new FetchPageRequest
            {
                TransactionId = txnId,
                NextPageToken = nextPageToken,
            };
            var request = new SendCommandRequest
            {
                FetchPage = fetchPageRequest,
            };
            var response = await this.SendCommand(request, cancellationToken);

            return(response.FetchPage);
        }
Example #17
0
        /// <summary>
        /// Send a fetch result request to QLDB, retrieving the next chunk of data for the result.
        /// </summary>
        ///
        /// <param name="txnId">The unique ID of the transaction to execute.</param>
        /// <param name="nextPageToken">The token that indicates what the next expected page is.</param>
        ///
        /// <returns>The result of the <see cref="FetchPageRequest"/>.</returns>
        internal virtual FetchPageResult FetchPage(string txnId, string nextPageToken)
        {
            var fetchPageRequest = new FetchPageRequest
            {
                NextPageToken = nextPageToken,
                TransactionId = txnId,
            };
            var request = new SendCommandRequest
            {
                FetchPage = fetchPageRequest,
            };
            var response = this.SendCommand(request);

            return(response.FetchPage);
        }
Example #18
0
        /// <summary>
        /// Send a commit request to QLDB, committing any active changes and closing any open results.
        /// </summary>
        ///
        /// <param name="txnId">The unique ID of the transaction to commit.</param>
        /// <param name="commitDigest">The digest hash of the transaction to commit.</param>
        ///
        /// <returns>The result of the commit transaction request.</returns>
        ///
        /// <exception cref="OccConflictException">Thrown if an OCC conflict has been detected within the transaction.</exception>
        internal virtual CommitTransactionResult CommitTransaction(string txnId, MemoryStream commitDigest)
        {
            var commitTransactionRequest = new CommitTransactionRequest
            {
                TransactionId = txnId,
                CommitDigest  = commitDigest,
            };
            var request = new SendCommandRequest
            {
                CommitTransaction = commitTransactionRequest,
            };
            var response = this.SendCommand(request);

            return(response.CommitTransaction);
        }
        /// <summary>
        /// Send a commit request to QLDB, committing any active changes and closing any open results.
        /// </summary>
        ///
        /// <param name="txnId">The unique ID of the transaction to commit.</param>
        /// <param name="commitDigest">The digest hash of the transaction to commit.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        ///
        /// <returns>The result of the commit transaction request.</returns>
        ///
        /// <exception cref="OccConflictException">Thrown if an OCC conflict has been detected within the transaction.</exception>
        internal virtual async Task <CommitTransactionResult> CommitTransaction(string txnId, MemoryStream commitDigest, CancellationToken cancellationToken = default)
        {
            var commitTransactionRequest = new CommitTransactionRequest
            {
                TransactionId = txnId,
                CommitDigest  = commitDigest,
            };
            var request = new SendCommandRequest
            {
                CommitTransaction = commitTransactionRequest,
            };
            var response = await this.SendCommand(request, cancellationToken);

            return(response.CommitTransaction);
        }
        /// <summary>
        /// Send an execute request with parameters to QLDB.
        /// </summary>
        ///
        /// <param name="txnId">The unique ID of the transaction to execute.</param>
        /// <param name="statement">The PartiQL statement to execute.</param>
        /// <param name="parameters">The parameters to use with the PartiQL statement for execution.</param>
        ///
        /// <returns>The result of the execution, which contains a <see cref="Page"/> representing the first data chunk.</returns>
        internal virtual ExecuteStatementResult ExecuteStatement(string txnId, string statement, List <IIonValue> parameters)
        {
            List <ValueHolder> valueHolders = null;

            try
            {
                valueHolders = parameters.ConvertAll(ionValue =>
                {
                    MemoryStream stream = new MemoryStream();
                    using (var writer = IonBinaryWriterBuilder.Build(stream))
                    {
                        ionValue.WriteTo(writer);
                        writer.Finish();
                    }

                    var valueHolder = new ValueHolder
                    {
                        IonBinary = stream,
                    };
                    return(valueHolder);
                });

                var executeStatementRequest = new ExecuteStatementRequest
                {
                    TransactionId = txnId,
                    Statement     = statement,
                    Parameters    = valueHolders,
                };
                var request = new SendCommandRequest
                {
                    ExecuteStatement = executeStatementRequest,
                };
                var response = this.SendCommand(request);
                return(response.ExecuteStatement);
            }
            finally
            {
                if (valueHolders != null)
                {
                    valueHolders.ForEach(valueHolder =>
                    {
                        valueHolder.IonBinary.Dispose();
                    });
                }
            }
        }
        public Task <SendCommandResponse> SendCommandAsync(SendCommandRequest request,
                                                           CancellationToken cancellationToken = default)
        {
            if (responses.Count == 0)
            {
                return(Task.FromResult(this.defaultResponse));
            }

            var output = responses.Dequeue();

            if (output.exception != null)
            {
                throw output.exception;
            }
            else
            {
                return(Task.FromResult(output.response));
            }
        }
Example #22
0
        /// <summary>
        /// Factory method for constructing a new Session, creating a new session to QLDB on construction.
        /// </summary>
        ///
        /// <param name="ledgerName">The name of the ledger to create a session to.</param>
        /// <param name="sessionClient">The low-level session used for communication with QLDB.</param>
        /// <param name="logger">The logger to inject any logging framework.</param>
        ///
        /// <returns>A newly created <see cref="Session"/>.</returns>
        internal static Session StartSession(string ledgerName, AmazonQLDBSessionClient sessionClient, ILogger logger)
        {
            var startSessionRequest = new StartSessionRequest
            {
                LedgerName = ledgerName,
            };
            var request = new SendCommandRequest
            {
                StartSession = startSessionRequest,
            };

            logger.LogDebug("Sending start session request: {}", request);
            var response = sessionClient.SendCommandAsync(request).GetAwaiter().GetResult();

            return(new Session(
                       ledgerName,
                       sessionClient,
                       response.StartSession.SessionToken,
                       response.ResponseMetadata.RequestId,
                       logger));
        }
Example #23
0
        // TODO: Accept bash script?

        public async Task RunCommandAsync(string commandText, IEnvironment environment, ISecurityContext context)
        {
            Validate.NotNullOrEmpty(commandText, nameof(commandText));
            Validate.NotNull(environment, nameof(environment));
            Validate.NotNull(context, nameof(context));

            var commands = CommandHelper.ToLines(commandText);

            var parameters = new JsonObject {
                { "commands", commands }
            };

            // tag: || InstanceIds
            // if tag: value:WebServer

            var request = new SendCommandRequest {
                DocumentName = "AWS-RunShellScript",
                Targets      = new[] {
                    new CommandTarget("tag:envId", values: new[] { environment.Id.ToString() })
                },
                Parameters = parameters
            };

            var result = await ssm.SendCommandAsync(request);

            #region Logging

            await eventLog.CreateAsync(new Event(
                                           action   : "run:command",
                                           resource : "environment#" + environment.Id,
                                           userId   : context.UserId.Value,
                                           context  : new JsonObject
            {
                { "commandId", result.Command.CommandId }
            }
                                           ));

            #endregion
        }
Example #24
0
        public JObject FunctionHandler(JObject input)
        {
            Amazon.Runtime.BasicAWSCredentials  credentials = new Amazon.Runtime.BasicAWSCredentials(Environment.GetEnvironmentVariable("AD_AccessKey"), Environment.GetEnvironmentVariable("AD_SecretKey"));
            AmazonSimpleSystemsManagementClient client      = new AmazonSimpleSystemsManagementClient(credentials, Amazon.RegionEndpoint.APSoutheast2);

            string username  = input.SelectToken("EventData.username").ToString();
            string accountId = input.SelectToken("CreateAccountResponse.CreateAccountStatus.AccountId").ToString();
            string roleName  = input.SelectToken("EventData.roleName").ToString();
            string groupName = roleName.Split("-")[0] + "-" + accountId + "-" + roleName.Split("-")[1];
            string groupPath = Environment.GetEnvironmentVariable("AD_SandboxOU");
            string type      = input.SelectToken("EventData.type").ToString();

            if (type == "production")
            {
                groupPath = Environment.GetEnvironmentVariable("AD_ProdOU");
            }

            Dictionary <string, List <string> > ParametersData = new Dictionary <string, List <string> >();

            ParametersData.Add("commands", new List <string> {
                string.Format("New-ADGroup -Name \"{0}\" -SamAccountName {0} -GroupCategory Security -GroupScope Global -DisplayName \"{0}\" -Path \"{1}\" -Description \"AWS Account Group\"", groupName, groupPath),
                string.Format("Add-ADGroupMember -Identity {0} -Members {1}", groupName, username)
            });

            SendCommandRequest request = new SendCommandRequest()
            {
                DocumentName = "AWS-RunPowerShellScript",
                InstanceIds  = new List <string> {
                    Environment.GetEnvironmentVariable("AD_InstanceId")
                },
                Parameters = ParametersData
            };

            SendCommandResponse response = client.SendCommandAsync(request).Result;

            return(input);
        }
Example #25
0
        /// <summary>
        /// Send direct control payload command
        /// </summary>
        /// <param name="vehicle">Vehicle object</param>
        /// <param name="commandDefinition">Command to send</param>
        /// <param name="addArgumentsFunc">Command parameters</param>
        public void SendDirectControlCommand(Vehicle vehicle, CommandDefinition commandDefinition, Func <IEnumerable <CommandArgument> > addArgumentsFunc)
        {
            SendCommandRequest request = new SendCommandRequest
            {
                ClientId = _connect.AuthorizeHciResponse.ClientId,
                Command  = new UGCS.Sdk.Protocol.Encoding.Command
                {
                    Code              = commandDefinition.Code,
                    Subsystem         = commandDefinition.Subsystem,
                    Silent            = true,
                    ResultIndifferent = true
                }
            };

            request.Vehicles.Add(new Vehicle()
            {
                Id = vehicle.Id
            });
            if (addArgumentsFunc != null)
            {
                request.Command.Arguments.AddRange(addArgumentsFunc());
            }
            _connect.Executor.Submit <SendCommandResponse>(request);
        }
        static void Main(string[] args)
        {
            //Connect
            TcpClient tcpClient = new TcpClient();

            tcpClient.Connect("localhost", 3334);
            MessageSender   messageSender   = new MessageSender(tcpClient.Session);
            MessageReceiver messageReceiver = new MessageReceiver(tcpClient.Session);
            MessageExecutor messageExecutor =
                new MessageExecutor(messageSender, messageReceiver, new InstantTaskScheduler());

            messageExecutor.Configuration.DefaultTimeout = 10000;
            var notificationListener = new NotificationListener();

            messageReceiver.AddListener(-1, notificationListener);

            //auth
            AuthorizeHciRequest request = new AuthorizeHciRequest();

            request.ClientId = -1;
            request.Locale   = "en-US";
            var future = messageExecutor.Submit <AuthorizeHciResponse>(request);

            future.Wait();
            AuthorizeHciResponse AuthorizeHciResponse = future.Value;
            int clientId = AuthorizeHciResponse.ClientId;

            System.Console.WriteLine("AuthorizeHciResponse precessed");

            //login
            LoginRequest loginRequest = new LoginRequest();

            loginRequest.UserLogin    = "******";
            loginRequest.UserPassword = "******";
            loginRequest.ClientId     = clientId;
            var loginResponcetask = messageExecutor.Submit <LoginResponse>(loginRequest);

            loginResponcetask.Wait();

            // Id of the emu-copter is 2
            var vehicleToControl = new Vehicle {
                Id = 3
            };

            TcpClientt.TcpListener server = new TcpClientt.TcpListener(IPAddress.Any, 8080);
            server.Start(); // run server
            byte[] ok = new byte[100];
            ok = Encoding.Default.GetBytes("ok");
            while (true) // бесконечный цикл обслуживания клиентов
            {
                TcpClientt.TcpClient     client = server.AcceptTcpClient();
                TcpClientt.NetworkStream ns     = client.GetStream();
                while (client.Connected)
                {
                    byte[] msg   = new byte[100];
                    int    count = ns.Read(msg, 0, msg.Length);
                    Console.Write(Encoding.Default.GetString(msg, 0, count));
                    string allMessage  = Encoding.Default.GetString(msg);
                    string result      = allMessage.Substring(0, count - 1);
                    var    commandName = result.ToString().Split(":")[0];


                    switch (commandName)
                    {
                    case "takeoff_command":
                    {
                        Console.Write("got command: {0}", commandName);

                        SendCommandRequest takeoff = new SendCommandRequest
                        {
                            ClientId = clientId,
                            Command  = new Command
                            {
                                Code              = "takeoff_command",
                                Subsystem         = Subsystem.S_FLIGHT_CONTROLLER,
                                Silent            = true,
                                ResultIndifferent = true
                            }
                        };
                        takeoff.Vehicles.Add(vehicleToControl);
                        var takeoffCmd = messageExecutor.Submit <SendCommandResponse>(takeoff);
                        takeoffCmd.Wait();
                        Thread.Sleep(5000);
                        ns.Write(ok, 0, ok.Length);
                        break;
                    }

                    case "direct_vehicle_control":
                    {
                        Console.Write("got command: {0}", commandName);
                        var commandArgs = result.Split(":")[1];
                        Console.Write("args of command: {0}", commandArgs);
                        // Vehicle control in joystick mode
                        SendCommandRequest vehicleJoystickControl = new SendCommandRequest
                        {
                            ClientId = clientId,
                            Command  = new UGCS.Sdk.Protocol.Encoding.Command
                            {
                                Code              = "direct_vehicle_control",
                                Subsystem         = Subsystem.S_FLIGHT_CONTROLLER,
                                Silent            = true,
                                ResultIndifferent = true
                            }
                        };


                        vehicleJoystickControl.Vehicles.Add(vehicleToControl);

                        List <CommandArgument> listJoystickCommands = new List <CommandArgument>();
                        var    directionCommand = commandArgs.ToString().Split(",")[0];
                        string commandValueStr  = commandArgs.ToString().Split(",")[1];
                        double commandValue     = double.Parse(commandValueStr,
                                                               System.Globalization.CultureInfo.InvariantCulture);

                        switch (directionCommand)
                        {
                        case "roll":
                            listJoystickCommands.Add(new CommandArgument
                                {
                                    Code  = "roll",
                                    Value = new Value()
                                    {
                                        DoubleValue = commandValue
                                    }
                                });
                            listJoystickCommands.Add(new CommandArgument
                                {
                                    Code  = "pitch",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            listJoystickCommands.Add(new CommandArgument
                                {
                                    Code  = "yaw",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            listJoystickCommands.Add(new CommandArgument
                                {
                                    Code  = "throttle",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            break;

                        case "pitch":
                            listJoystickCommands.Add(new CommandArgument
                                {
                                    Code  = "pitch",
                                    Value = new Value()
                                    {
                                        DoubleValue = commandValue
                                    }
                                });
                            listJoystickCommands.Add(new CommandArgument
                                {
                                    Code  = "roll",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            listJoystickCommands.Add(new CommandArgument
                                {
                                    Code  = "yaw",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            listJoystickCommands.Add(new CommandArgument
                                {
                                    Code  = "throttle",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            break;

                        case "throttle":
                            listJoystickCommands.Add(new CommandArgument
                                {
                                    Code  = "throttle",
                                    Value = new Value()
                                    {
                                        DoubleValue = commandValue
                                    }
                                });
                            listJoystickCommands.Add(new CommandArgument
                                {
                                    Code  = "pitch",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            listJoystickCommands.Add(new CommandArgument
                                {
                                    Code  = "roll",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            listJoystickCommands.Add(new CommandArgument
                                {
                                    Code  = "yaw",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            break;

                        case "yaw":
                            listJoystickCommands.Add(new CommandArgument
                                {
                                    Code  = "yaw",
                                    Value = new Value()
                                    {
                                        DoubleValue = commandValue
                                    }
                                });
                            listJoystickCommands.Add(new CommandArgument
                                {
                                    Code  = "pitch",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            listJoystickCommands.Add(new CommandArgument
                                {
                                    Code  = "roll",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            listJoystickCommands.Add(new CommandArgument
                                {
                                    Code  = "throttle",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            break;
                        }


                        vehicleJoystickControl.Command.Arguments.AddRange(listJoystickCommands);
                        var sendJoystickCommandResponse =
                            messageExecutor.Submit <SendCommandResponse>(vehicleJoystickControl);
                        sendJoystickCommandResponse.Wait();
                        System.Console.WriteLine("Was sent {0}", commandValue);

                        Thread.Sleep(2000);
                        ns.Write(ok, 0, ok.Length);
                        break;
                    }

                    case "set_relative_heading":
                    {
                        Console.Write("got command: {0}", commandName);
                        var commandArgs = result.Split(":")[1];
                        Console.Write("args of command: {0}", commandArgs);
                        // Vehicle control in joystick mode
                        SendCommandRequest vehicleRelativeOffsetControl = new SendCommandRequest
                        {
                            ClientId = clientId,
                            Command  = new UGCS.Sdk.Protocol.Encoding.Command
                            {
                                Code              = "set_relative_heading",
                                Subsystem         = Subsystem.S_FLIGHT_CONTROLLER,
                                Silent            = false,
                                ResultIndifferent = false
                            }
                        };


                        vehicleRelativeOffsetControl.Vehicles.Add(vehicleToControl);

                        List <CommandArgument> listRelativeOffsetCommands = new List <CommandArgument>();
                        var    directionCommand = commandArgs.ToString().Split(",")[0];
                        string commandValueStr  = commandArgs.ToString().Split(",")[1];
                        double commandValue     = double.Parse(commandValueStr,
                                                               System.Globalization.CultureInfo.InvariantCulture);

                        switch (directionCommand)
                        {
                        case "relative_heading":
                            listRelativeOffsetCommands.Add(new CommandArgument
                                {
                                    Code  = "relative_heading",
                                    Value = new Value()
                                    {
                                        DoubleValue = commandValue
                                    }
                                });
                            break;
                        }

                        vehicleRelativeOffsetControl.Command.Arguments.AddRange(listRelativeOffsetCommands);
                        var sendRelativeOffsetCommandResponse =
                            messageExecutor.Submit <SendCommandResponse>(vehicleRelativeOffsetControl);
                        sendRelativeOffsetCommandResponse.Wait();
                        System.Console.WriteLine("Was sent {0}", commandValue);

                        Thread.Sleep(2000);
                        ns.Write(ok, 0, ok.Length);
                        break;
                    }

                    case "set_position_offset":
                    {
                        Console.Write("got command: {0}", commandName);
                        var commandArgs = result.Split(":")[1];
                        Console.Write("args of command: {0}", commandArgs);
                        // Vehicle control in joystick mode
                        SendCommandRequest vehicleJoystickOffset = new SendCommandRequest
                        {
                            ClientId = clientId,
                            Command  = new UGCS.Sdk.Protocol.Encoding.Command
                            {
                                Code              = "set_position_offset",
                                Subsystem         = Subsystem.S_FLIGHT_CONTROLLER,
                                Silent            = false,
                                ResultIndifferent = false
                            }
                        };


                        vehicleJoystickOffset.Vehicles.Add(vehicleToControl);

                        List <CommandArgument> listJoystickOffsetCommands = new List <CommandArgument>();
                        var    directionCommand = commandArgs.ToString().Split(",")[0];
                        string commandValueStr  = commandArgs.ToString().Split(",")[1];
                        double commandValue     = double.Parse(commandValueStr,
                                                               System.Globalization.CultureInfo.InvariantCulture);

                        switch (directionCommand)
                        {
                        case "x":
                            listJoystickOffsetCommands.Add(new CommandArgument
                                {
                                    Code  = "x",
                                    Value = new Value()
                                    {
                                        DoubleValue = commandValue
                                    }
                                });
                            listJoystickOffsetCommands.Add(new CommandArgument
                                {
                                    Code  = "y",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            listJoystickOffsetCommands.Add(new CommandArgument
                                {
                                    Code  = "z",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            break;

                        case "y":
                            listJoystickOffsetCommands.Add(new CommandArgument
                                {
                                    Code  = "y",
                                    Value = new Value()
                                    {
                                        DoubleValue = commandValue
                                    }
                                });
                            listJoystickOffsetCommands.Add(new CommandArgument
                                {
                                    Code  = "x",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            listJoystickOffsetCommands.Add(new CommandArgument
                                {
                                    Code  = "z",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            break;

                        case "z":
                            listJoystickOffsetCommands.Add(new CommandArgument
                                {
                                    Code  = "z",
                                    Value = new Value()
                                    {
                                        DoubleValue = commandValue
                                    }
                                });
                            listJoystickOffsetCommands.Add(new CommandArgument
                                {
                                    Code  = "y",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            listJoystickOffsetCommands.Add(new CommandArgument
                                {
                                    Code  = "x",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            break;
                        }


                        vehicleJoystickOffset.Command.Arguments.AddRange(listJoystickOffsetCommands);
                        var sendJoystickOffsetResponse =
                            messageExecutor.Submit <SendCommandResponse>(vehicleJoystickOffset);
                        sendJoystickOffsetResponse.Wait();
                        System.Console.WriteLine("Was sent {0}", commandValue);

                        Thread.Sleep(2000);
                        ns.Write(ok, 0, ok.Length);
                        break;
                    }


                    case "payload_control":
                    {
                        Console.Write("got command: {0}", commandName);
                        var commandArgs = result.ToString().Split(":")[1];
                        Console.Write("args of command: {0}", commandArgs);
                        SendCommandRequest vehiclePayloadCommandRequest = new SendCommandRequest
                        {
                            ClientId = clientId,
                            Command  = new UGCS.Sdk.Protocol.Encoding.Command
                            {
                                Code              = "payload_control",
                                Subsystem         = Subsystem.S_CAMERA,
                                Silent            = false,
                                ResultIndifferent = false
                            }
                        };
                        vehiclePayloadCommandRequest.Vehicles.Add(vehicleToControl);
                        List <CommandArgument> listPayloadCommands = new List <CommandArgument>();
                        var    directionCommand = commandArgs.ToString().Split(",")[0];
                        string commandValueStr  = commandArgs.ToString().Split(",")[1];
                        double commandValue     = double.Parse(commandValueStr,
                                                               System.Globalization.CultureInfo.InvariantCulture);

                        switch (directionCommand)
                        {
                        case "tilt":
                            listPayloadCommands.Add(new CommandArgument
                                {
                                    Code  = "tilt",
                                    Value = new Value()
                                    {
                                        DoubleValue = commandValue
                                    }
                                });
                            listPayloadCommands.Add(new CommandArgument
                                {
                                    Code  = "roll",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            listPayloadCommands.Add(new CommandArgument
                                {
                                    Code  = "yaw",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            listPayloadCommands.Add(new CommandArgument
                                {
                                    Code  = "zoom_level",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            break;

                        case "roll":
                            listPayloadCommands.Add(new CommandArgument
                                {
                                    Code  = "roll",
                                    Value = new Value()
                                    {
                                        DoubleValue = commandValue
                                    }
                                });
                            listPayloadCommands.Add(new CommandArgument
                                {
                                    Code  = "tilt",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            listPayloadCommands.Add(new CommandArgument
                                {
                                    Code  = "yaw",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            listPayloadCommands.Add(new CommandArgument
                                {
                                    Code  = "zoom_level",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            break;

                        case "zoom_level":
                            listPayloadCommands.Add(new CommandArgument
                                {
                                    Code  = "zoom_level",
                                    Value = new Value()
                                    {
                                        DoubleValue = commandValue
                                    }
                                });
                            listPayloadCommands.Add(new CommandArgument
                                {
                                    Code  = "tilt",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            listPayloadCommands.Add(new CommandArgument
                                {
                                    Code  = "roll",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            listPayloadCommands.Add(new CommandArgument
                                {
                                    Code  = "yaw",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            break;

                        case "yaw":
                            listPayloadCommands.Add(new CommandArgument
                                {
                                    Code  = "yaw",
                                    Value = new Value()
                                    {
                                        DoubleValue = commandValue
                                    }
                                });
                            listPayloadCommands.Add(new CommandArgument
                                {
                                    Code  = "tilt",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            listPayloadCommands.Add(new CommandArgument
                                {
                                    Code  = "roll",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            listPayloadCommands.Add(new CommandArgument
                                {
                                    Code  = "zoom_level",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            break;
                        }

                        vehiclePayloadCommandRequest.Command.Arguments.AddRange(listPayloadCommands);
                        var sendPayloadCommandResponse =
                            messageExecutor.Submit <SendCommandResponse>(vehiclePayloadCommandRequest);
                        sendPayloadCommandResponse.Wait();
                        System.Console.WriteLine("Was sent {0}", commandValue);
                        Thread.Sleep(2000);
                        ns.Write(ok, 0, ok.Length);
                        break;
                    }

                    case "land_command":
                    {
                        SendCommandRequest land = new SendCommandRequest
                        {
                            ClientId = clientId,
                            Command  = new UGCS.Sdk.Protocol.Encoding.Command
                            {
                                Code              = "land_command",
                                Subsystem         = Subsystem.S_FLIGHT_CONTROLLER,
                                Silent            = false,
                                ResultIndifferent = false
                            }
                        };
                        land.Vehicles.Add(vehicleToControl);
                        var landCmd = messageExecutor.Submit <SendCommandResponse>(land);
                        landCmd.Wait();
                        Thread.Sleep(5000);
                        ns.Write(ok, 0, ok.Length);
                        break;
                    }

                    case "joystick":
                    {
                        SendCommandRequest joystickModeCommand = new SendCommandRequest
                        {
                            ClientId = clientId,
                            Command  = new UGCS.Sdk.Protocol.Encoding.Command
                            {
                                Code              = "joystick",
                                Subsystem         = Subsystem.S_FLIGHT_CONTROLLER,
                                Silent            = false,
                                ResultIndifferent = false
                            }
                        };

                        joystickModeCommand.Vehicles.Add(vehicleToControl);
                        var joystickMode = messageExecutor.Submit <SendCommandResponse>(joystickModeCommand);
                        joystickMode.Wait();
                        ns.Write(ok, 0, ok.Length);
                        break;
                    }

                    case "manual":
                    {
                        break;
                    }
                    }
                }

                // System.Console.ReadKey();
                // tcpClient.Close();
                // messageSender.Cancel();
                // messageReceiver.Cancel();
                // messageExecutor.Close();
                // notificationListener.Dispose();
            }
        }
Example #27
0
    public async Task <SsmCommandResponse> RunSsmCommand(UserRequest request, HandlerConfig config)
    {
        if (request == null || config == null)
        {
            return(null);
        }
        string             errorMessage = string.Empty;
        SsmCommandResponse output       = new SsmCommandResponse()
        {
            Status = "Failed" // If no processing is done.
        };

        AmazonSimpleSystemsManagementConfig clientConfig = new AmazonSimpleSystemsManagementConfig()
        {
            MaxErrorRetry    = config.ClientMaxErrorRetry,
            Timeout          = TimeSpan.FromSeconds(config.ClientTimeoutSeconds),
            ReadWriteTimeout = TimeSpan.FromSeconds(config.ClientReadWriteTimeoutSeconds),
            RegionEndpoint   = RegionEndpoint.GetBySystemName(request.AwsRegion) // Or RegionEndpoint.EUWest1
        };

        try
        {
            // https://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/net-dg-config-creds.html
            // Accessing Credentials and Profiles in an Application
            CredentialProfileStoreChain chain = new CredentialProfileStoreChain(config.AwsProfilesLocation);

            AWSCredentials awsCredentials;
            if (chain.TryGetAWSCredentials(request.AwsRole, out awsCredentials))
            {
                // Use awsCredentials
                AmazonSimpleSystemsManagementClient ssmClient =
                    new AmazonSimpleSystemsManagementClient(awsCredentials, clientConfig);
                if (request.CommandType == "send-command")
                {
                    List <string> instanceIds = new List <string> {
                        request.InstanceId
                    };
                    SendCommandRequest commandRequest = new SendCommandRequest(request.CommandDocument, instanceIds);
                    commandRequest.MaxConcurrency = config.CommandMaxConcurrency; // 50%
                    commandRequest.MaxErrors      = config.CommandMaxErrors;
                    commandRequest.TimeoutSeconds = config.CommandTimeoutSeconds;
                    commandRequest.Comment        = request.CommandComment;
                    commandRequest.Parameters     = request.CommandParameters;
                    SendCommandResponse sendCommandResponse = await ssmClient.SendCommandAsync(commandRequest);

                    output.Status         = "Complete";
                    output.CommandId      = sendCommandResponse.Command.CommandId;
                    output.CommandStatus  = sendCommandResponse.Command.StatusDetails;
                    output.ErrorMessage   = errorMessage;
                    output.CommandComment = sendCommandResponse.Command.Comment;
                }
                else if (request.CommandType == "get-command-invocation")
                {
                    //GetCommandInvocationRequest commandRequest = new GetCommandInvocationRequest()
                    //{
                    //    CommandId = request.CommandId,
                    //    InstanceId = request.InstanceId,
                    //    PluginName = request.CommandPluginName // If there are more than one plugins, this cannot be null.
                    //};
                    //GetCommandInvocationResponse getCommandResponse =
                    //    await ssmClient.GetCommandInvocationAsync(commandRequest);

                    ListCommandInvocationsRequest commandRequest = new ListCommandInvocationsRequest()
                    {
                        CommandId = request.CommandId,
                        Details   = true
                    };
                    ListCommandInvocationsResponse commandResponse = await ssmClient.ListCommandInvocationsAsync(commandRequest);

                    if (commandResponse.CommandInvocations.Count > 0)
                    {
                        output.Status         = "Complete";
                        output.CommandId      = commandResponse.CommandInvocations[0].CommandId;
                        output.CommandStatus  = commandResponse.CommandInvocations[0].StatusDetails;
                        output.CommandComment = commandResponse.CommandInvocations[0].Comment;
                        if (commandResponse.CommandInvocations[0].StatusDetails == "Success" &&
                            commandResponse.CommandInvocations[0].CommandPlugins.Count > 0)
                        {
                            output.StandardOutput = commandResponse.CommandInvocations[0].CommandPlugins[0].Output;
                        }
                        else if (commandResponse.CommandInvocations[0].StatusDetails == "Failed" &&
                                 commandResponse.CommandInvocations[0].CommandPlugins.Count > 0)
                        {
                            GetCommandInvocationRequest invocationRequest = new GetCommandInvocationRequest()
                            {
                                CommandId  = request.CommandId,
                                InstanceId = request.InstanceId,
                                PluginName = request.CommandPluginName // If there are more than one plugins, this cannot be null.
                            };
                            GetCommandInvocationResponse getCommandResponse =
                                await ssmClient.GetCommandInvocationAsync(invocationRequest);

                            output.StandardOutput = getCommandResponse.StandardOutputContent;
                            output.StandardError  = getCommandResponse.StandardErrorContent;
                        }
                    }
                    else
                    {
                        errorMessage = "The command id and instance id specified did not match any invocation.";
                    }
                }
            }
            else
            {
                errorMessage = "AWS credentials cannot be found for the execution.";
            }
        }
        catch (AmazonSimpleSystemsManagementException ex)
        {
            switch (ex.ErrorCode)
            {
            // https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_SendCommand.html
            // Error codes for "SendCommandRequest"
            case "DuplicateInstanceId":
                errorMessage = "You cannot specify an instance ID in more than one association.";
                break;

            case "InternalServerError":
                errorMessage = "Internal server error.";
                break;

            case "InvalidDocument":
                errorMessage = "The specified document does not exist.";
                break;

            case "InvalidDocumentVersion":
                errorMessage = "The document version is not valid or does not exist.";
                break;

            case "ExpiredTokenException":
                errorMessage = "The security token included in the request is expired.";
                break;

            case "InvalidInstanceId":
                errorMessage = "Possible causes are the 1) server instance may not be running 2) Server instance may not exist. 3) SSM agent may not be running. 4) Account used does not have permssion to access the instance.";
                break;

            case "InvalidNotificationConfig":
                errorMessage = "One or more configuration items is not valid.";
                break;

            case "InvalidOutputFolder":
                errorMessage = "The S3 bucket does not exist.";
                break;

            case "InvalidParameters":
                errorMessage =
                    "You must specify values for all required parameters in the Systems Manager document.";
                break;

            case "InvalidRole":
                errorMessage = "The role name can't contain invalid characters.";
                break;

            case "MaxDocumentSizeExceeded":
                errorMessage = "The size limit of a document is 64 KB.";
                break;

            case "UnsupportedPlatformType":
                errorMessage = "The document does not support the platform type of the given instance ID(s).";
                break;

            // Error codes for "GetcommandInvocation"
            case "InvalidCommandId":
                errorMessage = "The command ID is invalid.";
                break;

            case "InvocationDoesNotExist":
                errorMessage =
                    "The command id and instance id specified did not match any invocation.";
                break;

            case "ValidationException":
                errorMessage = ex.Message;
                break;

            default:
                errorMessage = ex.Message;
                break;
            }
        }
        catch (Exception ex)
        {
            errorMessage = ex.Message;
        }

        if (!string.IsNullOrWhiteSpace(errorMessage))
        {
            throw new Exception(errorMessage);
        }
        return(output);
    }
 public void SendCommand(SendCommandRequest req)
 {
     Console.WriteLine("In service");
 }
Example #29
0
        static void Main(string[] args)
        {
            //Connect
            TcpClient tcpClient = new TcpClient();

            tcpClient.Connect("localhost", 3334);
            MessageSender   messageSender   = new MessageSender(tcpClient.Session);
            MessageReceiver messageReceiver = new MessageReceiver(tcpClient.Session);
            MessageExecutor messageExecutor = new MessageExecutor(messageSender, messageReceiver, new InstantTaskScheduler());

            messageExecutor.Configuration.DefaultTimeout = 10000;
            var notificationListener = new NotificationListener();

            messageReceiver.AddListener(-1, notificationListener);

            //auth
            AuthorizeHciRequest request = new AuthorizeHciRequest();

            request.ClientId = -1;
            request.Locale   = "en-US";
            var future = messageExecutor.Submit <AuthorizeHciResponse>(request);

            future.Wait();
            AuthorizeHciResponse AuthorizeHciResponse = future.Value;
            int clientId = AuthorizeHciResponse.ClientId;

            System.Console.WriteLine("AuthorizeHciResponse precessed");

            //login
            LoginRequest loginRequest = new LoginRequest();

            loginRequest.UserLogin    = "******";
            loginRequest.UserPassword = "******";
            loginRequest.ClientId     = clientId;
            var loginResponcetask = messageExecutor.Submit <LoginResponse>(loginRequest);

            loginResponcetask.Wait();

            //Lock vehicle example
            AcquireLockRequest lockRequest = new AcquireLockRequest
            {
                ClientId   = clientId,
                ObjectType = "Vehicle",
                ObjectId   = 2
            };

            var resultLock = messageExecutor.Submit <AcquireLockResponse>(lockRequest);

            resultLock.Wait();

            // Click&Go example

            var sendCommandRequestGuided = new SendCommandRequest
            {
                ClientId = clientId,
                Command  = new UGCS.Sdk.Protocol.Encoding.Command
                {
                    Code      = "guided",
                    Subsystem = Subsystem.S_FLIGHT_CONTROLLER
                }
            };

            sendCommandRequestGuided.Vehicles.Add(new Vehicle {
                Id = 2
            });
            var sendCommandResponseGuided = messageExecutor.Submit <SendCommandResponse>(sendCommandRequestGuided);

            sendCommandResponseGuided.Wait();

            var sendCommandRequest = new SendCommandRequest
            {
                ClientId = clientId,
                Command  = new UGCS.Sdk.Protocol.Encoding.Command
                {
                    Code      = "waypoint",
                    Subsystem = Subsystem.S_FLIGHT_CONTROLLER
                }
            };

            sendCommandRequest.Command.Arguments.AddRange(new CommandArgument[] {
                new CommandArgument {
                    Code = "latitude", Value = new Value {
                        DoubleValue = 0.994445232147517
                    }
                },
                new CommandArgument {
                    Code = "longitude", Value = new Value {
                        DoubleValue = 0.4201742565140717
                    }
                },
                new CommandArgument {
                    Code = "altitude_agl", Value = new Value {
                        DoubleValue = 5.0
                    }
                },
                new CommandArgument {
                    Code = "ground_speed", Value = new Value {
                        DoubleValue = 5.0
                    }
                },
                new CommandArgument {
                    Code = "heading", Value = new Value {
                        DoubleValue = 0.017453292519943295
                    }
                }
            });

            sendCommandRequest.Vehicles.Add(new Vehicle {
                Id = 2
            });

            var sendCommandResponse = messageExecutor.Submit <SendCommandResponse>(sendCommandRequest);

            sendCommandResponse.Wait();
            System.Console.WriteLine("Click&Go command sent");


            //Import mission
            var byteArray = File.ReadAllBytes("Demo mission.xml");
            ImportMissionFromXmlRequest importMissionRequest = new ImportMissionFromXmlRequest()
            {
                ClientId   = clientId,
                MissionXml = byteArray
            };
            var importMissionResponse = messageExecutor.Submit <ImportMissionFromXmlResponse>(importMissionRequest);

            importMissionResponse.Wait();
            //mission contains imported mission from Demo mission.xml
            var mission = importMissionResponse.Value.Mission;

            System.Console.WriteLine("Demo mission.xml imported to UCS with name '{0}'", mission.Name);


            //Get all vehicles
            GetObjectListRequest getObjectListRequest = new GetObjectListRequest()
            {
                ClientId            = clientId,
                ObjectType          = "Vehicle",
                RefreshDependencies = true
            };

            getObjectListRequest.RefreshExcludes.Add("PayloadProfile");
            getObjectListRequest.RefreshExcludes.Add("Route");
            var task = messageExecutor.Submit <GetObjectListResponse>(getObjectListRequest);

            task.Wait();

            var list = task.Value;

            foreach (var v in list.Objects)
            {
                System.Console.WriteLine(string.Format("name: {0}; id: {1}; type: {2}",
                                                       v.Vehicle.Name, v.Vehicle.Id, v.Vehicle.Type.ToString()));
            }
            Vehicle vehicle = task.Value.Objects.FirstOrDefault().Vehicle;

            //Get mission from server
            GetObjectRequest getMissionObjectRequest = new GetObjectRequest()
            {
                ClientId            = clientId,
                ObjectType          = "Mission",
                ObjectId            = mission.Id,
                RefreshDependencies = true
            };
            var getMissionObjectResponse = messageExecutor.Submit <GetObjectResponse>(getMissionObjectRequest);

            getMissionObjectResponse.Wait();
            //missionFromUcs contains retrieved mission
            var missionFromUcs = getMissionObjectResponse.Value.Object.Mission;

            System.Console.WriteLine("mission id '{0}' retrieved from UCS with name '{1}'", mission.Id, missionFromUcs.Name);

            //vehicles in mission
            System.Console.WriteLine("Vehicles in mission:");
            foreach (var vehicleMission in missionFromUcs.Vehicles)
            {
                System.Console.WriteLine(vehicleMission.Vehicle.Name);
            }
            missionFromUcs.Vehicles.Clear();

            //Add vehicle to mission
            missionFromUcs.Vehicles.Add(
                new MissionVehicle
            {
                Vehicle = vehicle
            });

            System.Console.WriteLine("Vehicles in mission after add vehicle:");
            foreach (var vehicleMission in missionFromUcs.Vehicles)
            {
                System.Console.WriteLine(vehicleMission.Vehicle.Name);
            }

            //save mission
            CreateOrUpdateObjectRequest createOrUpdateObjectRequestForMission = new CreateOrUpdateObjectRequest()
            {
                ClientId       = clientId,
                Object         = new DomainObjectWrapper().Put(missionFromUcs, "Mission"),
                WithComposites = true,
                ObjectType     = "Mission",
                AcquireLock    = false
            };
            var updateMissionTask = messageExecutor.Submit <CreateOrUpdateObjectResponse>(createOrUpdateObjectRequestForMission);

            updateMissionTask.Wait();

            //Import route
            var byteArrayRoute = File.ReadAllBytes("Demo route for Copter.xml");
            ImportRouteRequest importRouteRequest = new ImportRouteRequest()
            {
                ClientId  = clientId,
                RouteData = byteArrayRoute,
                Filename  = "Demo route for Copter.xml"
            };
            var importRouteResponse = messageExecutor.Submit <ImportRouteResponse>(importRouteRequest);

            importRouteResponse.Wait();
            //importedRoute contains imported route from Demo route for Copter.xml
            var importedRoute = importRouteResponse.Value.Route;

            System.Console.WriteLine("Demo route for Copter.xml imported to UCS with name '{0}'", importedRoute.Name);
            //Add vehicle profile to route
            GetObjectRequest requestVehicle = new GetObjectRequest()
            {
                ClientId            = clientId,
                ObjectType          = "Vehicle",
                ObjectId            = 1, //EMU-COPTER-17
                RefreshDependencies = true
            };
            var responseVehicle = messageExecutor.Submit <GetObjectResponse>(requestVehicle);

            responseVehicle.Wait();
            importedRoute.VehicleProfile = responseVehicle.Value.Object.Vehicle.Profile;
            //Add route to mission
            importedRoute.Mission = missionFromUcs;
            //Save route on server
            CreateOrUpdateObjectRequest routeSaveRequest = new CreateOrUpdateObjectRequest()
            {
                ClientId       = clientId,
                Object         = new DomainObjectWrapper().Put(importedRoute, "Route"),
                WithComposites = true,
                ObjectType     = "Route",
                AcquireLock    = false
            };
            var updateRouteTask = messageExecutor.Submit <CreateOrUpdateObjectResponse>(routeSaveRequest);

            updateRouteTask.Wait();
            System.Console.WriteLine("route '{0}' added to mission '{1}'", updateRouteTask.Value.Object.Route.Name, missionFromUcs.Name);

            //Get route from server
            GetObjectRequest getRouteObjectRequest = new GetObjectRequest()
            {
                ClientId            = clientId,
                ObjectType          = "Route",
                ObjectId            = updateRouteTask.Value.Object.Route.Id,
                RefreshDependencies = true
            };
            var geRouteObjectResponse = messageExecutor.Submit <GetObjectResponse>(getRouteObjectRequest);

            geRouteObjectResponse.Wait();
            //routeFromUcs contains retrieved route
            var routeFromUcs = geRouteObjectResponse.Value.Object.Route;

            System.Console.WriteLine(string.Format("route id '{0}' retrieved from UCS with name '{1}'", updateRouteTask.Value.Object.Route.Id, routeFromUcs.Name));

            //add action to route
            ActionDefinition actionDefenition = new ActionDefinition();

            actionDefenition.HeadingDefinition                 = new HeadingDefinition();
            actionDefenition.HeadingDefinition.Heading         = 1.57079633; // 90 degrees
            actionDefenition.HeadingDefinition.RelativeToNorth = true;
            if (routeFromUcs.Segments.Count > 2)
            {
                routeFromUcs.Segments[1].ActionDefinitions.Add(actionDefenition);
            }
            System.Console.WriteLine(string.Format("action to route '{0}'", routeFromUcs.Name));

            //save route
            CreateOrUpdateObjectRequest createOrUpdateRouteRequest = new CreateOrUpdateObjectRequest()
            {
                ClientId       = clientId,
                Object         = new DomainObjectWrapper().Put(routeFromUcs, "Route"),
                WithComposites = true,
                ObjectType     = "Route",
                AcquireLock    = false
            };
            var createOrUpdateRouteResponseTask = messageExecutor.Submit <CreateOrUpdateObjectResponse>(createOrUpdateRouteRequest);

            createOrUpdateRouteResponseTask.Wait();
            if (createOrUpdateRouteResponseTask.Value != null)
            {
                System.Console.WriteLine(string.Format("'{0}' route updated on UCS", routeFromUcs.Name));
            }
            else
            {
                System.Console.WriteLine(string.Format("fail to update route '{0}' on UCS", routeFromUcs.Name));
            }

            // Payload control
            SendCommandRequest requestPaload = new SendCommandRequest
            {
                ClientId = clientId,
                Command  = new UGCS.Sdk.Protocol.Encoding.Command
                {
                    Code              = "direct_payload_control",
                    Subsystem         = Subsystem.S_GIMBAL,
                    Silent            = true,
                    ResultIndifferent = true
                }
            };

            requestPaload.Vehicles.Add(new Vehicle()
            {
                Id = vehicle.Id
            });

            List <CommandArgument> listCommands = new List <CommandArgument>();

            listCommands.Add(new CommandArgument
            {
                Code  = "roll",
                Value = new Value()
                {
                    DoubleValue = 1
                }
            });
            listCommands.Add(new CommandArgument
            {
                Code  = "pitch",
                Value = new Value()
                {
                    DoubleValue = 0
                }
            });
            listCommands.Add(new CommandArgument
            {
                Code  = "yaw",
                Value = new Value()
                {
                    DoubleValue = 0
                }
            });
            listCommands.Add(new CommandArgument
            {
                Code  = "zoom",
                Value = new Value()
                {
                    DoubleValue = 0
                }
            });

            requestPaload.Command.Arguments.AddRange(listCommands);

            var resultPayload = messageExecutor.Submit <SendCommandResponse>(requestPaload);

            resultPayload.Wait();

            //update vehicle object
            CreateOrUpdateObjectRequest createOrUpdateObjectRequest = new CreateOrUpdateObjectRequest()
            {
                ClientId       = clientId,
                Object         = new DomainObjectWrapper().Put(vehicle, "Vehicle"),
                WithComposites = true,
                ObjectType     = "Vehicle",
                AcquireLock    = false
            };
            var createOrUpdateObjectResponseTask = messageExecutor.Submit <CreateOrUpdateObjectResponse>(createOrUpdateObjectRequest);

            createOrUpdateObjectResponseTask.Wait();

            //Vehicle notification subscription
            var eventSubscriptionWrapper = new EventSubscriptionWrapper();

            eventSubscriptionWrapper.ObjectModificationSubscription            = new ObjectModificationSubscription();
            eventSubscriptionWrapper.ObjectModificationSubscription.ObjectId   = vehicle.Id;
            eventSubscriptionWrapper.ObjectModificationSubscription.ObjectType = "Vehicle";
            SubscribeEventRequest requestEvent = new SubscribeEventRequest();

            requestEvent.ClientId     = clientId;
            requestEvent.Subscription = eventSubscriptionWrapper;
            var responce = messageExecutor.Submit <SubscribeEventResponse>(requestEvent);

            responce.Wait();
            var subscribeEventResponse = responce.Value;
            SubscriptionToken st       = new SubscriptionToken(subscribeEventResponse.SubscriptionId, (
                                                                   (notification) =>
            {
                //Vehicle notification
            }
                                                                   ), eventSubscriptionWrapper);

            notificationListener.AddSubscription(st);

            // Get Telemetry for vehicle
            DateTime            utcTime               = DateTime.Now.ToUniversalTime();
            DateTime            posixEpoch            = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            TimeSpan            span                  = utcTime - posixEpoch;
            var                 beginningMilliseconds = (long)span.TotalMilliseconds;
            GetTelemetryRequest telemetryRequest      = new GetTelemetryRequest
            {
                ClientId = clientId,
                FromTime = beginningMilliseconds,
                Limit    = 10,
                Vehicle  = new Vehicle()
                {
                    Id = 1
                }
            };
            var responseTelemetry = messageExecutor.Submit <GetTelemetryResponse>(telemetryRequest);

            responseTelemetry.Wait();

            //Go to manual mode
            SendCommandRequest manualModeCommand = new SendCommandRequest
            {
                ClientId = clientId,
                Command  = new UGCS.Sdk.Protocol.Encoding.Command
                {
                    Code              = "manual",
                    Subsystem         = Subsystem.S_FLIGHT_CONTROLLER,
                    Silent            = false,
                    ResultIndifferent = false
                }
            };

            manualModeCommand.Vehicles.Add(new Vehicle()
            {
                Id = 2
            });
            var manualMode = messageExecutor.Submit <SendCommandResponse>(manualModeCommand);

            manualMode.Wait();

            //Go to joystick mode
            SendCommandRequest joystickModeCommand = new SendCommandRequest
            {
                ClientId = clientId,
                Command  = new UGCS.Sdk.Protocol.Encoding.Command
                {
                    Code              = "joystick",
                    Subsystem         = Subsystem.S_FLIGHT_CONTROLLER,
                    Silent            = false,
                    ResultIndifferent = false
                }
            };

            joystickModeCommand.Vehicles.Add(new Vehicle()
            {
                Id = 2
            });
            var joystickMode = messageExecutor.Submit <SendCommandResponse>(joystickModeCommand);

            joystickMode.Wait();

            // Vehicle control in joystick mode
            SendCommandRequest vehicleJoystickControl = new SendCommandRequest
            {
                ClientId = clientId,
                Command  = new UGCS.Sdk.Protocol.Encoding.Command
                {
                    Code              = "direct_vehicle_control",
                    Subsystem         = Subsystem.S_FLIGHT_CONTROLLER,
                    Silent            = true,
                    ResultIndifferent = true
                }
            };

            vehicleJoystickControl.Vehicles.Add(new Vehicle()
            {
                Id = 2
            });

            //List of current joystick values to send to vehicle.
            List <CommandArgument> listJoystickCommands = new List <CommandArgument>();

            listJoystickCommands.Add(new CommandArgument
            {
                Code  = "roll",
                Value = new Value()
                {
                    DoubleValue = 0
                }
            });
            listJoystickCommands.Add(new CommandArgument
            {
                Code  = "pitch",
                Value = new Value()
                {
                    DoubleValue = 0
                }
            });
            listJoystickCommands.Add(new CommandArgument
            {
                Code  = "yaw",
                Value = new Value()
                {
                    DoubleValue = 0
                }
            });
            listJoystickCommands.Add(new CommandArgument
            {
                Code  = "throttle",
                Value = new Value()
                {
                    DoubleValue = 1
                }
            });

            vehicleJoystickControl.Command.Arguments.AddRange(listJoystickCommands);

            for (int i = 1; i < 11; i++)
            {
                var sendJoystickCommandResponse = messageExecutor.Submit <SendCommandResponse>(vehicleJoystickControl);
                resultPayload.Wait();
                System.Console.WriteLine("Joystick command to go UP {0}", i);
                Thread.Sleep(1000);
            }

            //TelemetrySubscription
            var telemetrySubscriptionWrapper = new EventSubscriptionWrapper();

            telemetrySubscriptionWrapper.TelemetrySubscription = new TelemetrySubscription();
            SubscribeEventRequest requestTelemetryEvent = new SubscribeEventRequest();

            requestTelemetryEvent.ClientId     = clientId;
            requestTelemetryEvent.Subscription = telemetrySubscriptionWrapper;
            var responceTelemetry = messageExecutor.Submit <SubscribeEventResponse>(requestTelemetryEvent);

            responceTelemetry.Wait();
            var subscribeEventResponseTelemetry = responceTelemetry.Value;
            SubscriptionToken stTelemetry       = new SubscriptionToken(subscribeEventResponseTelemetry.SubscriptionId, (
                                                                            (notification) =>
            {
                foreach (Telemetry t in notification.Event.TelemetryEvent.Telemetry)
                {
                    System.Console.WriteLine("Vehicle id: {0} Code: {1} Semantic {2} Subsystem {3} Value {4}", notification.Event.TelemetryEvent.Vehicle.Id, t.TelemetryField.Code, t.TelemetryField.Semantic, t.TelemetryField.Subsystem, getTelemetryValue(t.Value));
                }
            }
                                                                            ), telemetrySubscriptionWrapper);

            notificationListener.AddSubscription(stTelemetry);

            //Log notification subscription
            var logSubscriptionWrapper = new EventSubscriptionWrapper();

            logSubscriptionWrapper.ObjectModificationSubscription            = new ObjectModificationSubscription();
            logSubscriptionWrapper.ObjectModificationSubscription.ObjectType = "VehicleLogEntry";
            SubscribeEventRequest requestLogEvent = new SubscribeEventRequest();

            requestLogEvent.ClientId     = clientId;
            requestLogEvent.Subscription = logSubscriptionWrapper;
            var responceLog = messageExecutor.Submit <SubscribeEventResponse>(requestLogEvent);
            var subscribeEventResponseLog = responceLog.Value;

            SubscriptionToken stLog = new SubscriptionToken(subscribeEventResponseLog.SubscriptionId, (
                                                                (notification) =>
            {
                var eventType = notification.Event.ObjectModificationEvent.ModificationType;
                var eventLog = notification.Event.ObjectModificationEvent.Object.VehicleLogEntry;
                if (eventType == ModificationType.MT_CREATE)
                {
                    DateTime start = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                    DateTime date = start.AddMilliseconds(eventLog.Time).ToLocalTime();
                    var command = eventLog.CommandArguments != null ? eventLog.CommandArguments.CommandCode : string.Empty;
                    System.Console.WriteLine("LOG: {0} Vehicle id: {1} Command: {2} Message: {3}", date.ToString("HH:mm:ss"), eventLog.Vehicle.Id, command, eventLog.Message);
                }
            }), logSubscriptionWrapper);

            notificationListener.AddSubscription(stLog);

            //Object notification subscription, subscribe for mission changed
            var missionObjectSubscriptionWrapper = new EventSubscriptionWrapper();

            missionObjectSubscriptionWrapper.ObjectModificationSubscription            = new ObjectModificationSubscription();
            missionObjectSubscriptionWrapper.ObjectModificationSubscription.ObjectType = "Mission";
            SubscribeEventRequest requestMissionEvent = new SubscribeEventRequest();

            requestMissionEvent.ClientId     = clientId;
            requestMissionEvent.Subscription = missionObjectSubscriptionWrapper;
            var responceMission = messageExecutor.Submit <SubscribeEventResponse>(requestMissionEvent);
            var subscribeEventResponseMission = responceMission.Value;

            SubscriptionToken stMission = new SubscriptionToken(subscribeEventResponseMission.SubscriptionId, (
                                                                    (notification) =>
            {
                var eventType = notification.Event.ObjectModificationEvent.ModificationType;
                var missionObject = notification.Event.ObjectModificationEvent.Object.Mission;
                if (eventType == ModificationType.MT_UPDATE)
                {
                    System.Console.WriteLine("Mission id: {0} updated", missionObject.Id);
                }
            }), missionObjectSubscriptionWrapper);

            notificationListener.AddSubscription(stMission);


            System.Console.ReadKey();

            tcpClient.Close();
            messageSender.Cancel();
            messageReceiver.Cancel();
            messageExecutor.Close();
            notificationListener.Dispose();
        }
Example #30
0
 /// <summary>
 /// Send a request to QLDB.
 /// </summary>
 ///
 /// <param name="request">The request to send.</param>
 ///
 /// <returns>The result returned by QLDB for the request.</returns>
 private SendCommandResponse SendCommand(SendCommandRequest request)
 {
     request.SessionToken = this.sessionToken;
     this.logger.LogDebug("Sending request: {}", request);
     return(this.SessionClient.SendCommandAsync(request).GetAwaiter().GetResult());
 }