Ejemplo n.º 1
0
        public async Task <object> HandleAlexaRequest(SmartHomeRequest request, ILambdaContext context)
        {
            LambdaLogger.Log("Building discovery list.");

            DiscoverResponse response = new DiscoverResponse
            {
                Event = new Event
                {
                    Header = new Header
                    {
                        MessageId      = request.Directive.Header.MessageId,
                        Namespace      = "Alexa.Discovery",
                        Name           = "Discover.Response",
                        PayloadVersion = "3"
                    },
                    Payload = new EventPayload
                    {
                        Endpoints = new List <Endpoint>()
                    }
                }
            };

            await AddDeviceEndpoints(request, response);

            LambdaLogger.Log("Discovery complete");
            LambdaLogger.Log("***********************************************" + Environment.NewLine);

            return(response);
        }
Ejemplo n.º 2
0
        private object PrepareDicsoverMessage()
        {
            var devices = new List <AlexaDevice>();

            foreach (var area in _areService.GetAreas())
            {
                var areaName       = area.Settings?.Caption;
                var areaComponents = area.GetComponents();

                devices.AddRange(GetDevicesFromArea(areaName, areaComponents));
            }

            devices.AddRange(GetExplisitRegiterDevices());

            return(DiscoverResponse.GenerateResponse(devices));
        }
        public async Task DiscoverDevices_ForSingleDevice_ShouldOnlyAddDevice()
        {
            // Arrange
            List <DeviceDto> devices = new List <DeviceDto>
            {
                new DeviceDto
                {
                    MetaTags    = new List <MetaTagDto>(),
                    Tags        = new List <string> (),
                    DisplayName = "Test Device",
                    Id          = "Device-Id"
                }
            };


            string           messageId = "MessageId1";
            SmartHomeRequest request   = BuildRequest(messageId);

            IDevicesClient  devicesClient   = new FakeDevicesClient(devices);
            DiscoveryHelper discoveryHelper = new DiscoveryHelper(devicesClient);

            // Act
            DiscoverResponse response = (DiscoverResponse)await discoveryHelper.HandleAlexaRequest(request, null);

            // Assert
            Assert.IsNotNull(response, "response nul");
            Assert.IsNotNull(response.Event, "Event null");
            Assert.IsNotNull(response.Event.Header, "Header null");
            Assert.AreEqual("Alexa.Discovery", response.Event.Header.Namespace, "Namespace");
            Assert.AreEqual("Discover.Response", response.Event.Header.Name, "Name");
            Assert.AreEqual("3", response.Event.Header.PayloadVersion, "PayloadVersion");
            Assert.AreEqual(messageId, response.Event.Header.MessageId, "MessageId");

            var endpoints = response.Event.Payload.Endpoints;

            Assert.IsNotNull(endpoints, "response.Event.Payload.Endpoints null");

            // Expect 2 sub-devices as only 2 are names.
            // plus one parent device.
            Assert.AreEqual(1, endpoints.Count, "response.Event.Payload.Endpoints null");

            Assert.AreEqual("Test Device", endpoints[0].FriendlyName, "endpoints[0].FriendlyName");
            Assert.AreEqual("Device-Id", endpoints[0].EndpointId, "endpoints[0].EndpointId");
        }
Ejemplo n.º 4
0
        public override async Task DoEffect(Game game, FreeUse useWay)
        {
            Player player = game.GetPlayer(useWay.PlayerId);
            await player.DropEventCard(game, player.EventCards[0], true);

            DiscoverResponse respond = await game.WaitAnswer(new DiscoverRequest()
            {
                Count           = 1,
                EnoughOnly      = true,
                PlayerId        = useWay.PlayerId,
                RequsetInfo     = "从事件弃牌堆中选择一张事件牌放入手中",
                SelectableCards = new List <int>(game.UsedEventDeck.Select(c => c.Id))
            }.SetTimeOut(game.RequestTime)) as DiscoverResponse;

            EventCard eventCard = game.UsedEventDeck.Find(c => c.Id == respond.SelectedCards[0]);

            game.UsedEventDeck.Remove(eventCard);
            player.EventCards.Add(eventCard);
            player.avoidSetEvent        = true;
            eventCard.UnaffectedPlayers = new List <Player>(game.Players.Where(p => p != player));
        }
        internal static JObject ToJObject(this DiscoverResponse payload)
        {
            JObject result = new JObject();

            foreach (DiscoveryDirection direction in Enum.GetValues(typeof(DiscoveryDirection)))
            {
                GetCoordinatesFromDirection(direction, out int y, out int x);
                if (payload.Distances[y, x] == -1)
                {
                    continue;
                }

                var propertyName = "distance" + direction.ToString();
                if (!result.TryAdd(propertyName, payload.Distances[y, x]))
                {
                    throw new JsonSerializationException($"Duplicated property \"{propertyName}\" found in serialized object");
                }
            }

            return(result);
        }
Ejemplo n.º 6
0
        public Task <BaseResponse> HandleAlexaRequest(SmartHomeRequest request, ILambdaContext context)
        {
            DiscoverResponse response = new DiscoverResponse
            {
                Event = new Event
                {
                    Header = new Header
                    {
                        MessageId      = request.Directive.Header.MessageId,
                        Namespace      = "Alexa.Discovery",
                        Name           = "Discover.Response",
                        PayloadVersion = "3"
                    },
                    Payload = new EventPayload
                    {
                        Endpoints = GetEndpoints()
                    }
                }
            };

            return(Task.FromResult <BaseResponse>(response));
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Add Tinamous devices tagged with "Alexa.SmartDevice"
        /// </summary>
        /// <param name="request"></param>
        /// <param name="response"></param>
        /// <returns></returns>
        private async Task AddDeviceEndpoints(SmartHomeRequest request, DiscoverResponse response)
        {
            // Get a list of devices filtered by the Alexa.SmartDevice Tag from Tinamous.
            List <DeviceDto> devices = await _devicesClient.GetDevicesAsync(request.Directive.Payload.Scope.Token);

            LambdaLogger.Log("Found " + devices.Count + " devices from Tinamous.");

            // Add each of the devices as an endpoint.
            foreach (DeviceDto device in devices)
            {
                LambdaLogger.Log("Adding device " + device.DisplayName);

                if (!device.Connected)
                {
                    LambdaLogger.Log("*** Device is not connected but adding it anyway: " + device.DisplayName);
                }

                if (!device.IsReporting)
                {
                    LambdaLogger.Log("*** Device is not reporting but adding it anyway: " + device.DisplayName);
                }

                // Add the base device, regardless of if it's a 2 port, 4 port or whatever outlet device.
                // Allows SmartHome basics such as get temperature, and turn on/off to apply to all ports.
                response.Event.Payload.Endpoints.Add(CreateDeviceEndpoint(device));

                // If the device is tagged as a multiport device (i.e. multiple outlets)
                // Try and also add each of the outlets as a device, giving it a name based
                // on a state tag set in the devices details.
                if (device.Tags.Contains("MultiPort"))
                {
                    LambdaLogger.Log("Adding Multi-Port Device as multiple-devices for " + device.DisplayName);
                    response.Event.Payload.Endpoints.AddRange(CreateMultiDeviceEndpoint(device));
                }
            }

            LambdaLogger.Log("Found " + response.Event.Payload.Endpoints.Count + " devices.");
        }
Ejemplo n.º 8
0
        public IEnumerator discoverTest_TurnEnd()
        {
            TestGameflow.createGame(out var game, out var you, out var _, new GameOption()
            {
                timeoutForTurn = 1
            });
            game.skipTurnUntil(() => game.currentPlayer == you);
            var cards = you.hand.randomTake(game, 3);
            var task  = you.discover(game, cards);

            Assert.NotNull(game.answers.getRequest <DiscoverRequest>(you.id));
            THHGame.TurnEndEventArg turnEnd = null;
            game.triggers.onEventBefore += obj =>
            {
                if (obj is THHGame.TurnEndEventArg)
                {
                    turnEnd = obj as THHGame.TurnEndEventArg;
                }
            };
            DiscoverResponse discoverResponse = null;

            game.answers.onResponse += response =>
            {
                if (response is DiscoverResponse)
                {
                    discoverResponse = response as DiscoverResponse;
                }
            };
            yield return(new WaitForSeconds(1.1f));

            Assert.NotNull(turnEnd);
            Assert.NotNull(discoverResponse);
            Assert.AreNotEqual(you, game.currentPlayer);
            Assert.Null(game.answers.getRequest <DiscoverRequest>(you.id));
            Assert.True(task.IsCompleted);
            Assert.True(cards.Contains(task.Result));
        }
Ejemplo n.º 9
0
        public async Task <IActionResult> ProcessDiscovery(Guid requestId, [FromBody] DiscoverDirective directive)
        {
            var resp = new DiscoverResponse
            {
                Event = new DiscoverEvent
                {
                    Header = new Header
                    {
                        MessageId      = directive.Directive.Header.MessageId,
                        Name           = "Discover.Response",
                        PayloadVersion = "3",
                        Namespace      = "Alexa.Discovery"
                    },
                    Payload = new DiscoverEventPayload
                    {
                        Endpoints = new List <Endpoint>
                        {
                            new Endpoint
                            {
                                EndpointId        = "smartwater01",
                                Description       = "Smart Water Heater Control",
                                DisplayCategories = new List <string>
                                {
                                    "THERMOSTAT",
                                    "TEMPERATURE_SENSOR"
                                },
                                FriendlyName     = "Hot Water",
                                ManufacturerName = "Ryan Mack",
                                Cookie           = new EmptyObject(),
                                Capabilities     = new List <AlexaInterface>
                                {
                                    new AlexaInterface
                                    {
                                        Interface           = "Alexa.ThermostatController",
                                        Version             = "3",
                                        ProactivelyReported = true,
                                        Retrievable         = true,
                                        Properties          = new InterfacePropery
                                        {
                                            Supported = new List <SupportedValue>
                                            {
                                                new SupportedValue("lowerSetpoint"),
                                                new SupportedValue("targetSetpoint")
                                            }
                                        }
                                    }, new AlexaInterface
                                    {
                                        Interface           = "Alexa.TemperatureSensor",
                                        Version             = "3",
                                        ProactivelyReported = false,
                                        Retrievable         = true,
                                        Properties          = new InterfacePropery
                                        {
                                            Supported = new List <SupportedValue>
                                            {
                                                new SupportedValue("temperature")
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            };

            return(await Task.FromResult(Ok(resp)));
        }
        public async Task DiscoverDevices_WithMultiPorts_ShouldAddMultipleDevices()
        {
            // Arrange
            List <DeviceDto> devices = new List <DeviceDto>
            {
                new DeviceDto
                {
                    MetaTags = new List <MetaTagDto>
                    {
                        new MetaTagDto {
                            Name = "PortCount", NumericValue = 4
                        },
                        new MetaTagDto {
                            Name = "Port-1", Value = "USB Light"
                        },
                        new MetaTagDto {
                            Name = "Port-4", Value = "ThingyStick"
                        },
                    },
                    Tags = new List <string> {
                        "MultiPort"
                    },
                    DisplayName = "Test Device",
                    Id          = "Device-Id"
                }
            };


            string           messageId = "MessageId1";
            SmartHomeRequest request   = BuildRequest(messageId);

            IDevicesClient  devicesClient   = new FakeDevicesClient(devices);
            DiscoveryHelper discoveryHelper = new DiscoveryHelper(devicesClient);

            // Act
            DiscoverResponse response = (DiscoverResponse)await discoveryHelper.HandleAlexaRequest(request, null);

            // Assert
            Assert.IsNotNull(response, "response nul");
            Assert.IsNotNull(response.Event, "Event null");
            Assert.IsNotNull(response.Event.Header, "Header null");
            Assert.AreEqual("Alexa.Discovery", response.Event.Header.Namespace, "Namespace");
            Assert.AreEqual("Discover.Response", response.Event.Header.Name, "Name");
            Assert.AreEqual("3", response.Event.Header.PayloadVersion, "PayloadVersion");
            Assert.AreEqual(messageId, response.Event.Header.MessageId, "MessageId");

            var endpoints = response.Event.Payload.Endpoints;

            Assert.IsNotNull(endpoints, "response.Event.Payload.Endpoints null");

            // Expect 2 sub-devices as only 2 are names.
            // plus one parent device.
            Assert.AreEqual(3, endpoints.Count, "response.Event.Payload.Endpoints null");

            Assert.AreEqual("Test Device", endpoints[0].FriendlyName, "endpoints[0].FriendlyName");
            Assert.AreEqual("Device-Id", endpoints[0].EndpointId, "endpoints[0].EndpointId");

            Assert.AreEqual("USB Light", endpoints[1].FriendlyName, "endpoints[1].FriendlyName");
            Assert.AreEqual("Device-Id#port-1#", endpoints[1].EndpointId, "endpoints[1].EndpointId");

            Assert.AreEqual("ThingyStick", endpoints[2].FriendlyName, "endpoints[2].FriendlyName");
            Assert.AreEqual("Device-Id#port-4#", endpoints[2].EndpointId, "endpoints[2].EndpointId");
        }
Ejemplo n.º 11
0
        /// <param name='organizationUrl'>
        /// Required. Organization URL
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        public async Task <HttpOperationResponse <object> > GetOrgDetailsWithOperationResponseAsync(string organizationUrl, CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            // Validate
            if (organizationUrl == null)
            {
                throw new ArgumentNullException("organizationUrl");
            }

            // Tracing
            bool   shouldTrace  = ServiceClientTracing.IsEnabled;
            string invocationId = null;

            if (shouldTrace)
            {
                invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("organizationUrl", organizationUrl);
                ServiceClientTracing.Enter(invocationId, this, "GetOrgDetailsAsync", tracingParameters);
            }

            // Construct URL
            string url = "";

            url = url + "/crm/exporter/metadata/discover";
            List <string> queryParameters = new List <string>();

            queryParameters.Add("organizationUrl=" + Uri.EscapeDataString(organizationUrl));
            if (queryParameters.Count > 0)
            {
                url = url + "?" + string.Join("&", queryParameters);
            }
            string baseUrl = this.Client.BaseUri.AbsoluteUri;

            // Trim '/' character from the end of baseUrl and beginning of url.
            if (baseUrl[baseUrl.Length - 1] == '/')
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            if (url[0] == '/')
            {
                url = url.Substring(1);
            }
            url = baseUrl + "/" + url;
            url = url.Replace(" ", "%20");

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = new HttpRequestMessage();

            httpRequest.Method     = HttpMethod.Get;
            httpRequest.RequestUri = new Uri(url);

            // Set Credentials
            if (this.Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
            }

            // Send Request
            if (shouldTrace)
            {
                ServiceClientTracing.SendRequest(invocationId, httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);

            if (shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
            }
            HttpStatusCode statusCode = httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

            if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.BadRequest && statusCode != HttpStatusCode.Unauthorized && statusCode != HttpStatusCode.Forbidden && statusCode != HttpStatusCode.InternalServerError)
            {
                HttpOperationException <object> ex = new HttpOperationException <object>();
                ex.Request  = httpRequest;
                ex.Response = httpResponse;
                ex.Body     = null;
                if (shouldTrace)
                {
                    ServiceClientTracing.Error(invocationId, ex);
                }
                throw ex;
            }

            // Create Result
            HttpOperationResponse <object> result = new HttpOperationResponse <object>();

            result.Request  = httpRequest;
            result.Response = httpResponse;

            // Deserialize Response
            if (statusCode == HttpStatusCode.OK)
            {
                DiscoverResponse resultModel = new DiscoverResponse();
                JToken           responseDoc = null;
                if (string.IsNullOrEmpty(responseContent) == false)
                {
                    responseDoc = JToken.Parse(responseContent);
                }
                if (responseDoc != null)
                {
                    resultModel.DeserializeJson(responseDoc);
                }
                result.Body = resultModel;
            }
            if (statusCode == HttpStatusCode.BadRequest || statusCode == HttpStatusCode.InternalServerError)
            {
                ErrorResponse resultModel = new ErrorResponse();
                JToken        responseDoc = null;
                if (string.IsNullOrEmpty(responseContent) == false)
                {
                    responseDoc = JToken.Parse(responseContent);
                }
                if (responseDoc != null)
                {
                    resultModel.DeserializeJson(responseDoc);
                }
                result.Body = resultModel;
            }

            if (shouldTrace)
            {
                ServiceClientTracing.Exit(invocationId, result);
            }
            return(result);
        }