Exemplo n.º 1
0
        public async Task <ActionResult <bool> > Call([FromBody] CallRequest request)
        {
            if (request == null)
            {
                return(BadRequest());
            }

            log.Info($"Request to Call. SipAddress={request.SipAddress} Callee={request.Callee} Profile={request.ProfileName} DeviceEncoder={request.DeviceEncoder}");

            var caller = new SipUri(request.SipAddress).UserAtHost;

            // Could be a SIP-uri or phone number that lacks domain
            string callee = request.Callee;

            if (!callee.IsNumeric())
            {
                // Sip-address.
                callee = new SipUri(callee).UserAtHost;
            }

            string callWithDeviceEncoder = string.IsNullOrEmpty(request.DeviceEncoder) ?  "Program" : request.DeviceEncoder;

            return(await Execute(caller,
                                 async (codecApi, codecInformation) => await codecApi.CallAsync(codecInformation.Ip, callee, request.ProfileName, callWithDeviceEncoder)));
        }
Exemplo n.º 2
0
        internal async Task <object[]> CallMethodAsync(UaItem item, object[] inputArguments)
        {
            var session = Session;

            if (session != null && session.Connected)
            {
                try
                {
                    var callRequest = new CallRequest {
                        MethodsToCall = { new CallMethodRequest {
                                              ObjectId = item.StartNodeId, MethodId = item.ResolvedNodeId, InputArguments = inputArguments.Select(a => new Variant(a)).ToArray()
                                          } }
                    };
                    var callResponse = await session.CallAsync(callRequest).ConfigureAwait(false);

                    for (int i = 0; i < callResponse.Results.Count; i++)
                    {
                        if (StatusCode.IsNotGood(callResponse.Results[i].StatusCode))
                        {
                            Trace.TraceError("Error calling method with MethodId {0} : {1}", callRequest.MethodsToCall[i].MethodId, callResponse.Results[i].StatusCode);
                        }
                    }
                    return(callResponse.Results[0].OutputArguments.Select(a => a.Value).ToArray());
                }
                catch (Exception ex)
                {
                    Trace.TraceError("Error calling method with MethodId {0} : {1}", item.ResolvedNodeId, ex.Message);
                }
            }
            else
            {
                Trace.TraceError("Error calling method with MethodId {0} : {1}", item.ResolvedNodeId, "Session is null or not connected");
            }
            return(null);
        }
Exemplo n.º 3
0
        public CallAnswer HandleCallRequest(CallRequest callRequest)
        {
            CallAnswer result = null;
            MethodInfo methodInfo;

            methodInfos.TryGetValue(callRequest.MethodInfoId, out methodInfo);
            if (methodInfo != null)
            {
                callRequest.Target = GetRealObject(callRequest.Target);
                object[] paramValues = callRequest.ParameterValues;
                for (int i = 0; i < paramValues.Length; i++)
                {
                    paramValues[i] = GetRealObject(paramValues[i]);
                }

                result = new CallAnswer();

                try
                {
                    object returnValue = methodInfo.Invoke(callRequest.Target, paramValues);
                    result.ReturnValue = GetObjectId(returnValue);
                    //foreach()
                }
                catch (Exception ex)
                {
                    result.ExceptionMessage = ex.Message;
                }
            }
            return(result);
        }
Exemplo n.º 4
0
        public static LogEntry For(CallRequest request)
        {
            LogEntry entry = new LogEntry("CallRequest");

            entry.Add("RequestHeader", For(request.RequestHeader));
            entry.Add("MethodsToCall", For(request.MethodsToCall));
            return(entry);
        }
 public ActionResult New(CallRequest request)
 {
     return(TwiML(response => response
                  .Say("Thanks for calling the All Knowing Magical 8 Ball.")
                  .Say("Ask a Question after the Beep.")
                  .Say("Press Pound when done.")
                  .Record(Url.Action("Question"))));
 }
 public void ProcessCall(CallRequest request)
 {
     foreach (var employee in _employees)
     {
         if (employee.CanHandleTheCall())
         {
             employee.ProcessCall(request);
         }
     }
 }
        public void Write(CallRequest <T> value, IMsgPackWriter writer)
        {
            writer.WriteMapHeader(2);

            _keyConverter.Write(Key.FunctionName, writer);
            _stringConverter.Write(value.FunctionName, writer);

            _keyConverter.Write(Key.Tuple, writer);
            _tupleConverter.Write(value.Tuple, writer);
        }
Exemplo n.º 8
0
        public ActionResult MakeCall([FromBody] CallRequest callRequest)
        {
            if (LoginStatus.LoggedIn != LoginManager.Instance.CurrentLoginStatus)
            {
                return(GetErrInfo(Constants.ErrorCode.NOT_LOGGED_IN));
            }

            callDialOut.StartVideoCall(false, false, callRequest.callee, callRequest.displayName, callRequest.password);
            return(Content(""));
        }
Exemplo n.º 9
0
 public void TimeOver(CallRequest unhappyCustomer)
 {
     print("Time over, you lazy fool");
     requestEnds.Remove(unhappyCustomer);
     if (rand.Next(0, 1000) == 69)
     {
         GameOver("You have died of dysentery");
     }
     GameOver("You ran out of time. Martha couldn't order her pizza and starved to death.");
 }
Exemplo n.º 10
0
    private void CreatePlugGoal()
    {
        var goalPlug = new PlugEnds();

        print("Okay, now connect " + goalPlug.first.CoordString() + " to " + goalPlug.second.CoordString());
        GameObject  newCallPanel = Instantiate(callPanelPrefab, commandPanel.transform);
        CallRequest call         = newCallPanel.GetComponent <CallRequest>();

        call.StartRequest(goalPlug, colSyms, rowSyms, 20f);

        requestEnds.Add(call);
    }
Exemplo n.º 11
0
        private void HandleCall(IPEndPoint remote, int index, CallRequest request)
        {
            var status = StatusCode.Success;
            var reason = string.Empty;

            IUser        target  = null;
            ICallSession session = null;

            if (!_users.TryGet(remote, out IUser source))
            {
                status = StatusCode.NotAuthorized;
                reason = "User is not logged in";
            }
            else if (!_users.TryGet(request.Target, out target))
            {
                status = StatusCode.UserNotFound;
                reason = "Target not found";
            }
            else if (source == target)
            {
                status = StatusCode.Failure;
                reason = "Don't target at yourself";
            }
            else if (!_callController.TryGetOrAdd(source.Name, request.Target, out session))
            {
                status = StatusCode.CallDuplicate;
                reason = "Call exists";
            }
            else if (!ushort.TryParse(request.RoutePort.ToString(), out _) || request.RoutePort == ushort.MinValue)
            {
                status = StatusCode.Failure;
                reason = $"Invalid parameters: {nameof(CallRequest.RoutePort)}";
            }

            _core.Send(new MessageResult {
                Status = status, Reason = reason
            }, remote, index);
            if (status != StatusCode.Success)
            {
                return;
            }

            session.AppendOrUpdate(source, request.RoutePort);
            session.AppendOrUpdate(target);

            _core.Send(new CallResponse {
                SessionId = session.Id, RouteId = session.RouteId
            }, remote, index);

            session.RaiseState();
        }
Exemplo n.º 12
0
        public async Task CallAsync()
        {
            var response = new CallResponse();
            var request  = new CallRequest();
            var channel  = new TestRequestChannel(response);

            var ret = await channel.CallAsync(request);

            ret
            .Should().BeSameAs(response);

            channel.Request
            .Should().BeSameAs(request);
        }
Exemplo n.º 13
0
 public virtual Response <object> Call(CallRequest body, CancellationToken cancellationToken = default)
 {
     using var scope = _clientDiagnostics.CreateScope("RosettaClient.Call");
     scope.Start();
     try
     {
         return(RestClient.Call(body, cancellationToken));
     }
     catch (Exception e)
     {
         scope.Failed(e);
         throw;
     }
 }
Exemplo n.º 14
0
 public virtual async Task <Response <object> > CallAsync(CallRequest body, CancellationToken cancellationToken = default)
 {
     using var scope = _clientDiagnostics.CreateScope("RosettaClient.Call");
     scope.Start();
     try
     {
         return(await RestClient.CallAsync(body, cancellationToken).ConfigureAwait(false));
     }
     catch (Exception e)
     {
         scope.Failed(e);
         throw;
     }
 }
Exemplo n.º 15
0
        public async Task <CallResponse> CallAsync(CallRequest request)
        {
            // For now, we'll route both Invoke and Call through IMocks.CallAsync.
            var args = ToDictionary(request.Args);

            var result = await _mocks.CallAsync(new MockCallArgs
            {
                Token    = request.Tok,
                Args     = args,
                Provider = request.Provider,
            })
                         .ConfigureAwait(false);

            return(new CallResponse {
                Return = await SerializeAsync(result).ConfigureAwait(false)
            });
        }
        public async Task VectorAdd()
        {
            var channel = new UaTcpSessionChannel(
                this.localDescription,
                this.certificateStore,
                new AnonymousIdentity(),
                "opc.tcp://*****:*****@"  ------------------");
            Console.WriteLine($"  {result}");

            Console.WriteLine($"Closing session '{channel.SessionId}'.");
            await channel.CloseAsync();

            result.Z
            .Should().Be(6.0);
        }
Exemplo n.º 17
0
 public void Request(CallRequest request)
 {
     if (!IsMoving)
     {
         if (CurrentFloor == request.Floor.Number)
         {
             OpenDoors();
             return;
         }
         request.RequestServedEvent += RequestServed;
         request.Execute(this);
     }
     else
     {
         request.RequestServedEvent += RequestServed;
         RequestQueue.Enqueue(request);
     }
 }
Exemplo n.º 18
0
        private static void TestMessageSerialization()
        {
            CallRequest msg1 = new CallRequest();

            msg1.MethodInfoId    = Guid.NewGuid();
            msg1.Target          = Guid.NewGuid();
            msg1.ParameterValues = new object[] { 1, 2, 3 };
            byte[] data = msg1.ToBytes();

            CallRequest msg2 = (CallRequest)MessageManager.Create(msg1.Id, data);

            Debug.Assert(msg2.Id == msg1.Id);
            Debug.Assert(object.Equals(msg1.Target, msg2.Target));
            Debug.Assert(msg1.ParameterValues.Length == msg2.ParameterValues.Length);

            CallRequest msg3;

            using (MemoryStream ms = new MemoryStream())
            {
                msg1.BeginWrite(ms);

                Thread.Sleep(100);
                ms.Position = 0;

                var ar = AMessage.BeginRead(ms);
                Thread.Sleep(100);

                msg3 = ar.GetMessage() as CallRequest;
            }

            Debug.Assert(msg1.Id == msg3.Id);
            Debug.Assert(object.Equals(msg1.Target, msg3.Target));
            Debug.Assert(msg1.ParameterValues.Length == msg3.ParameterValues.Length);

            var mainMethodInfo         = typeof(Program).GetMethod("Main", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic);
            MethodInfoAnswer miAnswer1 = new MethodInfoAnswer();

            miAnswer1.MethodInfoId = Guid.NewGuid();
            miAnswer1.MethodInfo   = mainMethodInfo;
            byte[]           miAnswerBytes = miAnswer1.ToBytes();
            MethodInfoAnswer miAnswer2     = (MethodInfoAnswer)AMessage.Create(miAnswer1.Id, miAnswerBytes);

            Debug.Assert(miAnswer1.MethodInfo == miAnswer2.MethodInfo);
        }
Exemplo n.º 19
0
        public Call Call(CallRequest request)
        {
            Request call_req;
            Call    call;

            call_req        = PrepareCallRequest(request, out call);
            call.AccountSid = request.AccountSid;

            fsInbound.CallRequest[call.Sid] = call_req;
            if (fsInbound.Originate(call.Sid))
            {
                //save call back to database
                try
                {
                    _callService.AddCallLog(call);
                }
                catch (Exception ex)
                {
                }
            }


            return(call);
        }
Exemplo n.º 20
0
        public async Task <CallResponse> CallAsync(CallRequest callRequest)
        {
            UpdateRequestHeader(callRequest, true, "Call");
            CallResponse callResponse = null;

            try
            {
                if (UseTransportChannel)
                {
                    var serviceResponse = await Task <IServiceResponse> .Factory.FromAsync(TransportChannel.BeginSendRequest, TransportChannel.EndSendRequest, callRequest, null).ConfigureAwait(false);

                    if (serviceResponse == null)
                    {
                        throw new ServiceResultException(StatusCodes.BadUnknownResponse);
                    }
                    ValidateResponse(serviceResponse.ResponseHeader);
                    callResponse = (CallResponse)serviceResponse;
                }
                else
                {
                    var callResponseMessage = await Task <CallResponseMessage> .Factory.FromAsync(InnerChannel.BeginCall, InnerChannel.EndCall, new CallMessage(callRequest), null).ConfigureAwait(false);

                    if (callResponseMessage == null || callResponseMessage.CallResponse == null)
                    {
                        throw new ServiceResultException(StatusCodes.BadUnknownResponse);
                    }
                    callResponse = callResponseMessage.CallResponse;
                    ValidateResponse(callResponse.ResponseHeader);
                }
            }
            finally
            {
                RequestCompleted(callRequest, callResponse, "Call");
            }
            return(callResponse);
        }
Exemplo n.º 21
0
        public AMessage GetResponse(AMessage message)
        {
            if (message == null)
            {
                return(null);
            }

            AMessage result = null;

            switch (message.Id)
            {
            // ---- Call ----
            case MessageId.CallRequest:
                CallRequest callRequest = (CallRequest)message;
                result = callHandler.HandleCallRequest(callRequest);
                if (result == null)
                {
                    lock (sync)
                    {
                        // Add the call request to the queue
                        pendingRequests.Add(callRequest);
                    }
                    // Send a method info request
                    MethodInfoRequest methodInfoRequest = new MethodInfoRequest();
                    methodInfoRequest.MethodInfoId = callRequest.MethodInfoId;
                    result = methodInfoRequest;
                }
                break;

            case MessageId.CallAnswer:
                callHandler.HandleCallAnswer((CallAnswer)message);
                break;

            // ---- MethodInfo ----
            case MessageId.MethodInfoRequest:
                result = callHandler.HandleMethodInfoRequest((MethodInfoRequest)message);
                break;

            case MessageId.MethodInfoAnswer:
                MethodInfoAnswer methodInfoAnswer = (MethodInfoAnswer)message;
                callHandler.HandleMethodInfoAnswer(methodInfoAnswer);

                CallRequest pendingCallRequest = null;
                lock (sync)
                {
                    for (int i = 0; i < pendingRequests.Count; i++)
                    {
                        if (pendingRequests[i].MethodInfoId == methodInfoAnswer.MethodInfoId)
                        {
                            // We got the answer for a method info
                            pendingCallRequest = pendingRequests[i];
                            pendingRequests.RemoveAt(i);
                        }
                    }
                }
                if (pendingCallRequest != null)
                {
                    result = callHandler.HandleCallRequest(pendingCallRequest);
                }
                break;

            // ---- ConnectionInfo ----
            case MessageId.ConnectionInfoRequest:
                result = HandleConnectionInfoRequest((ConnectionInfoRequest)message);
                break;

            case MessageId.ConnectionInfoAnswer:
                HandleConnectionInfoAnswer((ConnectionInfoAnswer)message);
                break;

            default:
                string errorMsg = string.Format("Messages of Id={0} and type={1} are not supported", message.Id, message.GetType());
                throw new NotSupportedException(errorMsg);
            }
            return(result);
        }
Exemplo n.º 22
0
 private Employee GetCallHandler(CallRequest callRequst)
 {
     var availableFresher = freshers.FirstOrDefault(e => e.IsFree());
     if (availableFresher.CanHandleACall(callRequst)) return availableFresher;
     else if (teamLead.CanHandleACall(callRequst)) return teamLead;
     else return projectManager;
 }
Exemplo n.º 23
0
        private Request PrepareCallRequest(CallRequest request, out Call call)
        {
            call = new Call()
            {
                AccountSid = request.AccountSid, CallTo = request.To, AnswerUrl = request.AnswerUrl, Direction = "outbound-api", CallerId = request.From, Timeout = request.TimeLimit
            };
            Queue <DialString> dialStrings = new Queue <DialString>();

            System.Text.StringBuilder args_list = new System.Text.StringBuilder();
            string sched_hangup_id = string.Empty;

            // don't allow "|" and "," in 'to' (destination) to avoid call injection
            request.To = request.To.Split(',', '|')[0];
            //set hangup_on_ring
            int hangup = 0;

            if (!int.TryParse(request.HangupOnRing, out hangup))
            {
                hangup = -1;
            }
            if (hangup == 0)
            {
                args_list.Append("execute_on_ring='hangup ORIGINATOR_CANCEL',");
            }
            else if (hangup > 0)
            {
                args_list.Append(string.Format("execute_on_ring='sched_hangup +{0} ORIGINATOR_CANCEL',", hangup));
            }
            // set send_digits
            if (!string.IsNullOrEmpty(request.SendDigits))
            {
                args_list.Append(string.Format("execute_on_answer='send_dtmf {0}',", request.SendDigits));
            }
            //set time_limit
            int time = 0;

            if (!int.TryParse(request.TimeLimit, out time))
            {
                time = -1;
            }
            if (time > 0)
            {
                //create sched_hangup_id
                sched_hangup_id = System.Guid.NewGuid().ToString();
                args_list.Append(string.Format("api_on_answer='sched_api {0} +{1} hupall ALLOTTED_TIMEOUT agbara_callSid {2}',", sched_hangup_id, request.TimeLimit, call.Sid));
                args_list.Append(string.Format("agbara_sched_hangup_id={0}", sched_hangup_id));
            }

            if (!string.IsNullOrEmpty(request.StatusCallbackUrl))
            {
                args_list.Append(string.Format("agbara_statuscallback_url={0},", request.StatusCallbackUrl));
                args_list.Append(string.Format("agbara_statuscallbackmethod={0},", request.StatusCallbackMethod));
            }

            if (!string.IsNullOrEmpty(request.FallbackUrl))
            {
                args_list.Append(string.Format("agbara_fallbackrul={0},", request.FallbackUrl));
                args_list.Append(string.Format("agbara_fallbackmethod={0},", request.FallbackMethod));
            }

            if (!string.IsNullOrEmpty(request.ApplicationSid))
            {
                args_list.Append(string.Format("agbara_applicationsid={0},", request.ApplicationSid));
            }

            args_list.Append(string.Format("agbara_callsid={0},", call.Sid));
            args_list.Append(string.Format("agbara_accountsid={0},", call.AccountSid));
            args_list.Append(string.Format("agbara_answer_url={0},", request.AnswerUrl));

            args_list.Append(string.Format("origination_caller_id_number={0},", request.From));

            //session_heartbeat
            args_list.Append(string.Format("enable_heartbeat_events={0},", 60));
            //Set Direction
            args_list.Append(string.Format("agbara_call_direction={0}", CallDirection.outboundapi));


            foreach (Gateway gate in _fsService.GetGatewaysForNumber(call.CallTo, FS.Sid))
            {
                for (int i = 1; i < int.Parse(gate.GatewayRetry); i++)
                {
                    DialString dialString = new DialString(call.Sid, request.To, gate.GatewayString, gate.GatewayCodec, gate.GatewayTimeout.ToString(), args_list.ToString());
                    dialStrings.Enqueue(dialString);
                }
            }
            Request call_req = new Request(call.Sid, dialStrings, request.AnswerUrl, request.StatusCallbackUrl, request.StatusCallbackMethod);

            return(call_req);
        }
        public async Task ReadHistoryRawValues()
        {
            // describe this client application.
            var clientDescription = new ApplicationDescription
            {
                ApplicationName = "Workstation.UaClient.FeatureTests",
                ApplicationUri  = $"urn:{System.Net.Dns.GetHostName()}:Workstation.UaClient.FeatureTests",
                ApplicationType = ApplicationType.Client
            };

            // place to store certificates
            var certificateStore = new DirectoryStore("./pki");

            // create a 'UaTcpSessionChannel', a client-side channel that opens a 'session' with the server.
            var channel = new UaTcpSessionChannel(
                clientDescription,
                certificateStore,
                new AnonymousIdentity(),      // the anonymous identity
                "opc.tcp://localhost:48010"); // the endpoint of Unified Automation's UaCPPServer.

            try
            {
                // try opening a session and reading a few nodes.
                await channel.OpenAsync();

                Console.WriteLine($"Opened session with endpoint '{channel.RemoteEndpoint.EndpointUrl}'.");
                Console.WriteLine($"SecurityPolicy: '{channel.RemoteEndpoint.SecurityPolicyUri}'.");
                Console.WriteLine($"SecurityMode: '{channel.RemoteEndpoint.SecurityMode}'.");
                Console.WriteLine($"UserIdentityToken: '{channel.UserIdentity}'.");

                Console.WriteLine("\nCheck if DataLogger active.");

                // check if DataLoggerActive is true. If not, then call method StartLogging.
                var req = new ReadRequest
                {
                    NodesToRead = new[] {
                        new ReadValueId {
                            NodeId = NodeId.Parse("ns=2;s=Demo.History.DataLoggerActive"), AttributeId = AttributeIds.Value
                        }
                    },
                };
                var res = await channel.ReadAsync(req);

                if (StatusCode.IsBad(res.Results[0].StatusCode))
                {
                    throw new InvalidOperationException("Error reading 'Demo.History.DataLoggerActive'. ");
                }
                var isActive = res.Results[0].GetValueOrDefault <bool>();

                if (!isActive)
                {
                    Console.WriteLine("Activating DataLogger.");

                    var req1 = new CallRequest
                    {
                        MethodsToCall = new[] {
                            new CallMethodRequest {
                                ObjectId = NodeId.Parse("ns=2;s=Demo.History"), // parent node
                                MethodId = NodeId.Parse("ns=2;s=Demo.History.StartLogging")
                            },
                        },
                    };
                    var res1 = await channel.CallAsync(req1);

                    if (StatusCode.IsBad(res1.Results[0].StatusCode))
                    {
                        throw new InvalidOperationException("Error calling method 'Demo.History.StartLogging'.");
                    }
                    Console.WriteLine("Note: Datalogger has just been activated, so there will be little or no history data to read.");
                    Console.WriteLine("      Try again in 1 minute.");
                }

                Console.WriteLine("\nReading history for last 1 minute(s).");

                // A continuation point is returned if there are more values to return than the
                // limit set by parameter NumValuesPerNode. A client should continue calling HistoryRead
                // until the continuation point returns null.
                byte[] cp = null;

                do
                {
                    var req2 = new HistoryReadRequest
                    {
                        HistoryReadDetails = new ReadRawModifiedDetails
                        {
                            StartTime        = DateTime.UtcNow.Add(TimeSpan.FromSeconds(-60)), // set start time to 1 minute ago
                            EndTime          = DateTime.UtcNow,
                            NumValuesPerNode = 100,                                            // sets limit. if there are more values to return then a continuation point is returned.
                            ReturnBounds     = false,                                          // set true to return interpolated values for the start and end times
                        },
                        TimestampsToReturn        = TimestampsToReturn.Both,
                        ReleaseContinuationPoints = false, // set true to abandon returning any remaining values from this interval
                        NodesToRead = new[] {
                            new HistoryReadValueId {
                                NodeId = NodeId.Parse("ns=2;s=Demo.History.DoubleWithHistory"), ContinuationPoint = cp
                            },
                        },
                    };

                    var res2 = await channel.HistoryReadAsync(req2);

                    if (StatusCode.IsGood(res2.Results[0].StatusCode))
                    {
                        var historyData = res2.Results[0].HistoryData as HistoryData;

                        Console.WriteLine($"Found {historyData.DataValues.Length} value(s) for node '{req2.NodesToRead[0].NodeId}':");

                        foreach (var dv in historyData.DataValues)
                        {
                            Console.WriteLine($"Read {dv.Value}, q: {dv.StatusCode}, ts: {dv.SourceTimestamp}");
                        }

                        cp = res2.Results[0].ContinuationPoint;
                        // if ContinuationPoint is null, then there is no more data to return.
                        if (cp == null)
                        {
                            break;
                        }
                    }
                    else
                    {
                        Console.WriteLine($"HistoryRead return statuscode: {res2.Results[0].StatusCode}");
                        break;
                    }
                } while (cp != null); // loop while ContinuationPoint is not null.

                Console.WriteLine($"\nClosing session '{channel.SessionId}'.");
                await channel.CloseAsync();
            }
            catch (Exception ex)
            {
                await channel.AbortAsync();

                Console.WriteLine(ex.Message);
            }
        }
Exemplo n.º 25
0
        private void TaskAudioPlayback(Logger logger, CancellationToken cancelToken, BlockingCollection <IMsgPackTypeName> queue)
        {
            while (!cancelToken.IsCancellationRequested)
            {
                if (queue.TryTake(out IMsgPackTypeName data, 500))
                {
                    switch (data.GetType().Name)
                    {
                    case nameof(AudioRxDto):
                    {
                        var dto = (AudioRxDto)data;
                        soundcardSampleProvider.AddOpusSamples(dto, dto.Transceivers);
                        if (logger.IsTraceEnabled)
                        {
                            logger.Trace(dto.ToDebugString());
                        }
                        break;
                    }

                    case nameof(CallRequestDto):
                    {
                        var dto = (CallRequestDto)data;
                        if (incomingCallRequest != null)
                        {
                            Connection.VoiceServerTransmitQueue.Add(new CallResponseDto()
                                {
                                    Request = dto, Event = CallResponseEvent.Busy
                                });
                        }
                        else
                        {
                            incomingCallRequest = dto;
                            soundcardSampleProvider.LandLineRing(true);
                            CallRequest?.Invoke(this, new CallRequestEventArgs()
                                {
                                    Callsign = dto.FromCallsign
                                });
                        }
                        break;
                    }

                    case nameof(CallResponseDto):
                    {
                        var dto = (CallResponseDto)data;
                        switch (dto.Event)
                        {
                        // Server events
                        case CallResponseEvent.Routed:
                            soundcardSampleProvider.LandLineRing(true);
                            CallResponse?.Invoke(this, new CallResponseEventArgs()
                                {
                                    Callsign = dto.Request.ToCallsign, Event = CallResponseEvent.Routed
                                });                                                                                                                                             //Our request was routed
                            break;

                        case CallResponseEvent.NoRoute:
                            CallResponse?.Invoke(this, new CallResponseEventArgs()
                                {
                                    Callsign = dto.Request.ToCallsign, Event = CallResponseEvent.NoRoute
                                });                                                                                                                                             //Our request was not routed
                            break;

                        //Remote party events
                        case CallResponseEvent.Busy:
                            soundcardSampleProvider.LandLineRing(false);
                            //Play busy tone
                            CallResponse?.Invoke(this, new CallResponseEventArgs()
                                {
                                    Callsign = dto.Request.ToCallsign, Event = CallResponseEvent.Busy
                                });
                            break;

                        case CallResponseEvent.Accept:
                            soundcardSampleProvider.LandLineRing(false);
                            CallResponse?.Invoke(this, new CallResponseEventArgs()
                                {
                                    Callsign = dto.Request.ToCallsign, Event = CallResponseEvent.Accept
                                });
                            break;

                        case CallResponseEvent.Reject:
                            soundcardSampleProvider.LandLineRing(false);
                            //Play reject tone
                            CallResponse?.Invoke(this, new CallResponseEventArgs()
                                {
                                    Callsign = dto.Request.ToCallsign, Event = CallResponseEvent.Reject
                                });
                            break;
                        }
                        break;
                    }
                    }
                }
            }
        }
Exemplo n.º 26
0
 public async Task <CallResponse> CallAsync(CallRequest request)
 => await this._client.CallAsync(request);
Exemplo n.º 27
0
 public CallControl(CallRequest callRequest)
 {
     InitializeComponent();
     CallRequest = callRequest;
 }
 /// <summary>Performs a CALL request.</summary>
 /// <param name="callRequest">The call request.</param>
 /// <param name="cancellationToken">The cancellation token.</param>
 /// <returns>The <see cref="Task" /> with MessagePackObject as result.</returns>
 public async Task <MessagePackObject> CallAsync(CallRequest callRequest, CancellationToken cancellationToken)
 {
     return(await RequestAsync(callRequest, cancellationToken).ConfigureAwait(false));
 }
Exemplo n.º 29
0
 public CallRequestBuilder(CallRequest callRequest) : base(callRequest)
 {
     _callRequest = callRequest;
 }
Exemplo n.º 30
0
 public bool CanHandleACall(CallRequest callRequest)
 {
     return false;
 }
 public void ProcessCall(CallRequest request)
 {
     //Some logic
 }
Exemplo n.º 32
0
        /// <summary>
        /// Begins an asynchronous invocation of the Call service.
        /// </summary>
        public IAsyncResult BeginCall(
            RequestHeader               requestHeader,
            CallMethodRequestCollection methodsToCall,
            AsyncCallback               callback,
            object                      asyncState)
        {
            CallRequest request = new CallRequest();

            request.RequestHeader = requestHeader;
            request.MethodsToCall = methodsToCall;

            UpdateRequestHeader(request, requestHeader == null, "Call");

            if (UseTransportChannel)
            {
                return TransportChannel.BeginSendRequest(request, callback, asyncState);
            }

            return InnerChannel.BeginCall(new CallMessage(request), callback, asyncState);
        }
    /// <summary>
    /// Example testing DAPI endpoints using Classes
    /// </summary>
    public DAPIResponse runDAPICall(string method, Dictionary<string, string> args, UserToken userToken = null, AppToken appToken = null, string stringToken = null)
    {
        Uri u = new Uri("https://api.zynga.com");
        TTransport transport = new THttpModClient(u);
        TProtocol protocol = new TDAPIProtocol(transport);
        DAPI.Client client = new DAPI.Client(protocol);

        transport.Open();

        List<CallRequest> dapiCalls = new List<CallRequest>();
        CallRequest callRequest = new CallRequest();
        callRequest.Method = method;
        callRequest.Argz = args;
        dapiCalls.Add(callRequest);

        DAPIRequest dapiRequest = new DAPIRequest();
        dapiRequest.Calls = dapiCalls;
        dapiRequest.UserToken = userToken;
        dapiRequest.AppToken = appToken;
        dapiRequest.StringToken = stringToken;

        DAPIResponse dapiResponse = client.call(dapiRequest);

        transport.Close();

        return dapiResponse;
    }
        public void Call(
            OperationContext         context,
            IList<CallMethodRequest> methodsToCall,
            IList<CallMethodResult>  results,
            IList<ServiceResult>     errors)
        {
            if (context == null)       throw new ArgumentNullException("context");
            if (methodsToCall == null) throw new ArgumentNullException("methodsToCall");
            if (results == null)       throw new ArgumentNullException("results");
            if (errors == null)        throw new ArgumentNullException("errors");

#if LEGACY_CORENODEMANAGER
            List<CallRequest> callables = new List<CallRequest>();
#endif

            lock (m_lock)
            {
                for (int ii = 0; ii < methodsToCall.Count; ii++)
                {
                    CallMethodRequest methodToCall = methodsToCall[ii];

                    // skip items that have already been processed.
                    if (methodToCall.Processed)
                    {
                        continue;
                    }
                                        
                    // look up the node.
                    ILocalNode node = GetLocalNode(methodToCall.ObjectId) as ILocalNode;

                    if (node == null)
                    {
                        continue;
                    }
                    
                    methodToCall.Processed = true;                                      
                                        
                    // look up the method.
                    ILocalNode method = GetLocalNode(methodToCall.MethodId) as ILocalNode;

                    if (method == null)
                    {
                        errors[ii] = ServiceResult.Create(StatusCodes.BadMethodInvalid, "Method is not in the address space.");
                        continue;
                    }

                    // check that the method is defined for the object.
                    if (!node.References.Exists(ReferenceTypeIds.HasComponent, false, methodToCall.MethodId, true, m_server.TypeTree))
                    {
                        errors[ii] = ServiceResult.Create(StatusCodes.BadMethodInvalid, "Method is not a component of the Object.");
                        continue;
                    } 
                             
                    #if LEGACY_CORENODEMANAGER  
                    // find object to call.
                    ICallable callable = method as ICallable;

                    SourceHandle handle = method.Handle as SourceHandle;

                    if (handle != null)
                    {
                        callable = handle.Source as ICallable;
                    }

                    if (callable == null)
                    { 
                        errors[ii] = ServiceResult.Create(StatusCodes.BadNotImplemented, "Method does not have a source registered.");
                        continue;
                    }
                                                 
                    // get the input arguments.
                    IVariable argumentNode = GetLocalNode(method.NodeId, ReferenceTypes.HasProperty, false, false, BrowseNames.InputArguments) as IVariable;
                    
                    // extract the arguments from the node.
                    Argument[] arguments = null;

                    if (argumentNode != null)
                    {
                        Array value = argumentNode.Value as Array;

                        if (value != null)
                        {
                            arguments = ExtensionObject.ToArray(value, typeof(Argument)) as Argument[];
                        }
                    }

                    // validate the input arguments.
                    bool argumentError = false;

                    List<ServiceResult> argumentErrors = new List<ServiceResult>();

                    object[] validatedArguments = new object[methodToCall.InputArguments.Count];
                    
                    // check if the argument is expected.
                    if ((arguments == null && methodToCall.InputArguments.Count > 0) || (methodToCall.InputArguments.Count != arguments.Length))
                    {
                        errors[ii] = StatusCodes.BadArgumentsMissing;
                        continue;
                    }

                    for (int jj = 0; jj < methodToCall.InputArguments.Count; jj++)
                    {                
                        // can't do anything if the argument definition is missing.
                        Argument argumentDefinition = arguments[jj];

                        if (argumentDefinition == null)
                        {
                            argumentErrors.Add(ServiceResult.Create(StatusCodes.BadConfigurationError, "Server does not have a defintion for argument."));
                            argumentError = true;
                            continue;
                        }

                        // a null value can be used for optional arguments.
                        object argumentValue = methodToCall.InputArguments[jj].Value;

                        if (argumentValue == null)
                        {
                            argumentErrors.Add(ServiceResult.Create(StatusCodes.BadInvalidArgument, "Argument cannot be null."));
                            argumentError = true;
                            continue;
                        }                                                          
      
                        // get the datatype.
                        if (!m_server.TypeTree.IsEncodingFor(argumentDefinition.DataType, argumentValue))
                        {
                            argumentErrors.Add(ServiceResult.Create(StatusCodes.BadTypeMismatch, "Expecting value with datatype '{0}'.", argumentDefinition.DataType));
                            argumentError = true;
                            continue;
                        }

                        // check the array size.
                        Array array = argumentValue as Array;
                        
                        if (array != null)
                        {
                            if (argumentDefinition.ValueRank == ValueRanks.Scalar)
                            {
                                argumentErrors.Add(ServiceResult.Create(StatusCodes.BadTypeMismatch, "Expecting a scalar value."));
                                argumentError = true;
                                continue;
                            }
                            
                            if (argumentDefinition.ValueRank > 0 && array.Length != argumentDefinition.ValueRank)
                            {
                                argumentErrors.Add(ServiceResult.Create(StatusCodes.BadTypeMismatch, "Expecting an array with length {0}.", argumentDefinition.ValueRank));
                                argumentError = true;
                                continue;
                            }
                        }
                        else
                        {
                            if (argumentDefinition.ValueRank >= 0)
                            {
                                argumentErrors.Add(ServiceResult.Create(StatusCodes.BadTypeMismatch, "Expecting an array value."));
                                argumentError = true;
                                continue;
                            }
                        }

                        // argument passed initial validation.
                        validatedArguments[jj] = argumentValue;
                        argumentErrors.Add(null);
                    }
                    #else
                    errors[ii] = StatusCodes.BadNotImplemented;
                    #endif

                    #if LEGACY_CORENODEMANAGER  
                    CallRequest request = new CallRequest();

                    request.Callable           = callable;
                    request.Index              = ii;
                    request.MethodId           = method.NodeId;
                    request.MethodHandle       = (handle != null)?handle.Handle:null;
                    request.ObjectId           = node.NodeId;
                    request.InputArguments     = validatedArguments;
                    request.ArgumentErrors     = argumentErrors;
                    request.HasInvalidArgument = argumentError;

                    callables.Add(request);
                    #endif
                }
            }
                  
            #if LEGACY_CORENODEMANAGER
            // check if nothing to do.
            if (callables.Count == 0)
            {
                return;
            }                    

            // call the methods.
            foreach (CallRequest callable in callables)
            {       
                // call method if no errors occurred.
                List<object> outputArguments = new List<object>();

                if (!callable.HasInvalidArgument)
                {
                    try
                    {
                        errors[callable.Index] = callable.Callable.Call(
                            context,
                            callable.MethodId,
                            callable.MethodHandle,
                            callable.ObjectId,
                            callable.InputArguments,
                            callable.ArgumentErrors,
                            outputArguments);
                    }
                    catch (Exception e)
                    {
                        errors[callable.Index] = ServiceResult.Create(e, StatusCodes.BadUnexpectedError, "Error occurred invoking method.");
                    }
                }
                else
                {
                    errors[callable.Index] = ServiceResult.Create(StatusCodes.BadInvalidArgument, "One or more arguments were not valid.");
                }

                // create the result item.
                CallMethodResult result = results[callable.Index] = new CallMethodResult();

                // process argument errors.
                bool errorExists = false;

                foreach (ServiceResult argumentError in callable.ArgumentErrors)
                {
                    if (ServiceResult.IsBad(argumentError))
                    {
                        result.InputArgumentResults.Add(argumentError.Code);

                        DiagnosticInfo diagnosticInfo = null;

                        if ((context.DiagnosticsMask & DiagnosticsMasks.OperationAll) != 0)
                        {
                            diagnosticInfo = ServerUtils.CreateDiagnosticInfo(m_server, context, argumentError);
                            errorExists = true;
                        }

                        result.InputArgumentDiagnosticInfos.Add(diagnosticInfo);
                    }
                    else
                    {
                        result.InputArgumentResults.Add(StatusCodes.Good);
                    }
                }

                if (!errorExists)
                {
                    result.InputArgumentDiagnosticInfos.Clear();
                }

                // copy output arguments into result.
                result.OutputArguments.Clear();

                foreach (object outputArgument in outputArguments)
                {
                    result.OutputArguments.Add(new Variant(outputArgument));
                }                
            }
            #endif
        }
Exemplo n.º 35
0
 /// <summary>
 /// Initializes the message with the body.
 /// </summary>
 public CallMessage(CallRequest CallRequest)
 {
     this.CallRequest = CallRequest;
 }
Exemplo n.º 36
0
        /// <summary>
        /// Calls (invokes) a list of Methods.
        /// </summary>
        /// <param name="channel">A instance of <see cref="IRequestChannel"/>.</param>
        /// <param name="request">A <see cref="CallRequest"/>.</param>
        /// <returns>A <see cref="Task"/> representing the asynchronous operation that returns a <see cref="CallResponse"/>.</returns>
        /// <seealso href="https://reference.opcfoundation.org/v104/Core/docs/Part4/5.11.2/">OPC UA specification Part 4: Services, 5.11.2</seealso>
        public static async Task <CallResponse> CallAsync(this IRequestChannel channel, CallRequest request, CancellationToken token = default)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            return((CallResponse)await channel.RequestAsync(request, token).ConfigureAwait(false));
        }
Exemplo n.º 37
0
        /// <summary>
        /// Invokes the Call service.
        /// </summary>
        public virtual ResponseHeader Call(
            RequestHeader                  requestHeader,
            CallMethodRequestCollection    methodsToCall,
            out CallMethodResultCollection results,
            out DiagnosticInfoCollection   diagnosticInfos)
        {
            CallRequest request = new CallRequest();
            CallResponse response = null;

            request.RequestHeader = requestHeader;
            request.MethodsToCall = methodsToCall;

            UpdateRequestHeader(request, requestHeader == null, "Call");

            try
            {
                if (UseTransportChannel)
                {
                    IServiceResponse genericResponse = TransportChannel.SendRequest(request);

                    if (genericResponse == null)
                    {
                        throw new ServiceResultException(StatusCodes.BadUnknownResponse);
                    }

                    ValidateResponse(genericResponse.ResponseHeader);
                    response = (CallResponse)genericResponse;
                }
                else
                {
                    CallResponseMessage responseMessage = InnerChannel.Call(new CallMessage(request));

                    if (responseMessage == null || responseMessage.CallResponse == null)
                    {
                        throw new ServiceResultException(StatusCodes.BadUnknownResponse);
                    }

                    response = responseMessage.CallResponse;
                    ValidateResponse(response.ResponseHeader);
                }

                results         = response.Results;
                diagnosticInfos = response.DiagnosticInfos;
            }
            finally
            {
                RequestCompleted(request, response, "Call");
            }

            return response.ResponseHeader;
        }
        public async Task VectorAdd()
        {
            // describe this client application.
            var clientDescription = new ApplicationDescription
            {
                ApplicationName = "Workstation.UaClient.FeatureTests",
                ApplicationUri = $"urn:{System.Net.Dns.GetHostName()}:Workstation.UaClient.FeatureTests",
                ApplicationType = ApplicationType.Client
            };

            // place to store certificates
            var certificateStore = new DirectoryStore("./pki");

            // create a 'UaTcpSessionChannel', a client-side channel that opens a 'session' with the server.
            var channel = new UaTcpSessionChannel(
                clientDescription,
                certificateStore,
                new AnonymousIdentity(), // the anonymous identity
                "opc.tcp://*****:*****@"  ------------------");
                Console.WriteLine($"  {result}");

                Console.WriteLine($"\nClosing session '{channel.SessionId}'.");
                await channel.CloseAsync();
            }
            catch (Exception ex)
            {
                await channel.AbortAsync();
                Console.WriteLine(ex.Message);
            }
        }