Giter Site home page Giter Site logo

alexa.net.gadgets's Introduction

Alexa.NET.Gadgets

A simple skill built to work with the Alexa Gadgets API, using Alexa.NET as the core

Game Controller Support

Set all attached buttons to the same color

A good one to show the user active buttons during roll call

using Alexa.NET.Gadgets.GadgetController
...
response.GadgetColor("0000FF",10000)

which is the same as

var setLight = new SetLightDirective
{
    Parameters =
        SetLightParameter.Create(
            SetLightAnimation.CreateSingle(
				AnimationSegment.Create("0000FF", 10000)))
};

response.Response.Directives.Add(setLight);

Set light color of a specific gadget

using Alexa.NET.Gadgets.GadgetController
...
response.GadgetColor("0000FF", new[] { "gadgetid1"}, 10000);

which is the same as

var setLight = new SetLightDirective
{
    TargetGadgets = new List<string>{"gadgetid1"},
    Parameters =
        SetLightParameter.Create(
            SetLightAnimation.CreateSingle(
				AnimationSegment.Create("0000FF", 10000)))
};

response.Response.Directives.Add(setLight);

Set light with more explicit settings

var setLight = new SetLightDirective
{
    TargetGadgets = new List<string> { "gadgetId1", "gadgetId2" },
    Parameters = new SetLightParameter
    {
        TriggerEvent = TriggerEvent.Down,
        TriggerEventTimeMilliseconds = 200,
        Animations = new List<SetLightAnimation> {
            new SetLightAnimation {
                Repeat = 1,
                TargetLights = new List<int> { 1 },
                Sequence = new List<AnimationSegment>
                        {
                            new AnimationSegment
                            {
                                Blend=false,
                                DurationMilliseconds = 3000,
                                Color="0000FF"
                            }
                        }
            }
        }
    }
};
skillResponse.Response.Directives.Add(setLight);

Game Engine Support

Add support for GameEngine requests - please this in constructor/startup

new GadgetRequestHandler().AddToRequestConverter();

Roll Call - Ask User to identify buttons

Adds a directive to the response that looks for buttons to be pressed, and assigns them to the list passed in on a first come first served basis (Good to use in combination with a general GadgetColor from GameController to show the user which buttons they can pick from)

using Alexa.NET.Gadgets.GameEngine
...
response.AddRollCall("first", "second");

This is equivalent to:

  • A StartInputHandler Directive - Proxy added for each name passed in - A timed out event - A "rollcall complete" event - A "rollcall complete" recogniser
    • A pattern for each name to be pressed down, once, in order.

Roll Call - Find mandatory gadgets used in roll call

When an InputHandlerEventRequest is identified, this will check to see if it was a rollcall event, and then map the matched events to the gadget ids in the order passed in. If not all gadgets are pressed down within the time it will return false.

Assuming the previous AddRollCall method was used, this would return a dictionary mapping first -> firstGadgetId, second -> secondGadgetId

using Alexa.NET.Gadgets.GameEngine
...
switch(skillRequest.Request)
{
    case InputHandlerEventRequest inputHandler:
      inputHandler.TryRollCallResult(out Dictionary<string,string> mapping, "first","second");
}

Roll Call - Find optional gadgets used in roll call

When an InputHandlerEventRequest is identified, this will check to see if it was a rollcall event, and then map the matched events to the gadget ids in the order passed in. If not all gadgets are passed in, it will return a mapping for those distinct buttons pressed during the time. If the event was neither roll call nor time out, or no event was found, then it will return false.

Assuming the previous AddRollCall method was used, this would return:

  • a dictionary mapping first -> firstGadgetId, second -> secondGadgetId if both buttons were pressed
  • a dictionary mapping first -> firstGadgetId if one button was pressed within the timeout
  • a false result and a null mapping object if the event was neither rollcall nor timeout
using Alexa.NET.Gadgets.GameEngine
...
switch(skillRequest.Request)
{
    case InputHandlerEventRequest inputHandler:
      inputHandler.TryRollCallOptionalResult(out Dictionary<string,string> mapping, "first","second");
}

In Game - find out which gadget is pressed down first

Adds a directive which triggers a InputHandlerEventRequest when any of the mentioned buttons is pressed.

The triggered event is given the name passed in (in this case buzzedIn)

using Alexa.NET.Gadgets.GameEngine
...
response.WhenFirstButtonDown(new[] { gadget1, gadget2 }, "buzzedIn", 10000);

this can also be done with a roll call result:

using Alexa.NET.Gadgets.GameEngine
...
switch(skillRequest.Request)
{
    case InputHandlerEventRequest inputHandler:
      if(inputHandler.TryRollCallOptionalResult(out Dictionary<string,string> mapping, "first","second"))
      {
        response.WhenFirstButtonDown(mapping, "buzzedIn", 10000);
      }
}

In Game - find out which gadget pressed first

When an InputHandlerEventRequest is identified, this will see if the named event is found and what the gadget that triggered it was

using Alexa.NET.Gadgets.GameEngine
...
switch(skillRequest.Request)
{
    case InputHandlerEventRequest inputHandler:
      if(inputHandler.TryMapEventGadget("buzzedIn", out var gadgetId))
      {
        //Perform logic based on who buzzed in
      }
}

Custom Interface Support

Get endpoints

  var api = new EndpointApi(skillRequest);
  var endpoints = await api.GetEndpoints();

Send Interface Directive

  SendDirective.AddToDirectiveConverter(); //Only if you're deserializing directives from JSON
  var directive = new SendDirective(endpointId, interfaceNamespace, interfaceName, customPayload);
  skillResponse.Response.Directives.Add(directive);

Start Monitoring Interface Events

   StartEventHandler.AddToDirectiveConverter(); //As before - if deserializing
   const string gameOverText = "Game over! Would you like to hear your stats?";
   var token = Guid.Parse("1234abcd-40bb-11e9-9527-6b98b093d166");
   var expected = new StartEventHandler(
       token,
       new Expiration(8000, new {gameOverSpeech=gameOverText}),
       FilterMatchAction.SendAndTerminate,
       new CombinedFilterExpression(
           CombinationOperator.And,
           new ComparisonFilterExpression(ComparisonOperator.Equals, "header.namespace", "Custom.Robot"),
           new ComparisonFilterExpression(ComparisonOperator.GreaterThan, "payload.angle", 10)
               )
   );

Receive Interface Events

  new CustomInterfaceHandler().AddToRequestConverter();
  ...
  var request = skillRequest.Request as EventsReceivedRequest;
  var event = request.Events.First();
  //...or
  var request = skillRequest.Request as ExpiredRequest;
  var payload = request.ExpirationPayload;

Stop Monitoring Interface Events

  StopEventHandler.AddToDirectiveConverter(); //As before - if deserializing
  var directive = new StopEventHandler(tokenFromStartHandler);
  skillResponse.Response.Directives.Add(directive);

alexa.net.gadgets's People

Contributors

stoiveyp avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

Forkers

javierpuntonet

alexa.net.gadgets's Issues

Object reference not set to an instance of an object

So, Im currently working with a Custom Gadget (Lego Mindstorm Ev3) and want to send directives to the python Code running on my Gadget. Somehow, when I try adding the directive, Alexa tells me that there is an error during the Answer of the requested Skill. Am I doing something wrong? This is the Code that is given as a sample Directive Request:

  SendDirective.AddToDirectiveConverter(); //Only if you're deserializing directives from JSON
  var directive = new SendDirective(endpointId, interfaceNamespace, interfaceName, customPayload);
  skillResponse.Response.AddDirective(directive);

Notice, that the AddDirective(directive) method is not available anymore. What I did then, was just to add my SendDirective directive to the Dictionary, that is given like so:

 SendDirective.AddToDirectiveConverter();
 SendDirective directive = new SendDirective(endpoint.EndpointId, "Custom.Mindstorms.Gadget", "Control", JsonConvert.SerializeObject(speedData));
 skillResponse.Response.Directives.Add(directive);

Doing it like this, seems to work, even tho the List Im adding it to is a IList and not a SendDirective List. The problem obove then occures, whenever i tell Alexa to send the Request.

Would be glad, to get a quick response :)

Serialize Alexa Request

Hi,
I've a problem serializing the Alexa Request. I've been writing the request to CloudWatch this since using Alexa.NET library. In my newest project i'm working with Echo buttons and therefore the Alexa.NET Gadgets library.

The first request can be serialized and logged without any problems. In the first response i'm doing a roll call. When pressing my two echo buttons there are recongized and sent back to my skill with the second request which i'm not able to serialize using JSonSerializer.

Maybe someone can help me because during development it is really helpful to write the complete request string into a cloud watch stream.

private void LogRequestResponse(object requestResponse, string title)
        {
            var serializer = new Amazon.Lambda.Serialization.Json.JsonSerializer();

            using (var ms = new MemoryStream())
            {
                try
                {
                    serializer.Serialize(requestResponse, ms);
                    var jsonText = Encoding.UTF8.GetString(ms.ToArray());

                    Log.LogLine(string.Format("{0} - {1}", title, jsonText));
                }
                catch (Exception e)
                {
                    ErrorFormat("Error serializing {0}, Error: {1}", title, e.ToString());
                }
            }
        }

this leads to the following Exception:

ERROR - Error serializing REQUEST, Error: Newtonsoft.Json.JsonWriterException: Token PropertyName in state Property would result in an invalid JSON object. Path 'request.events[0].inputEvents[0]'.
at Newtonsoft.Json.JsonWriter.AutoComplete(JsonToken tokenBeingWritten)
at Newtonsoft.Json.JsonTextWriter.WritePropertyName(String name, Boolean escape)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType)
at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType)
at Amazon.Lambda.Serialization.Json.JsonSerializer.Serialize[T](T response, Stream responseStream)

AddRollCall can't handle optional button roll call

Currently AddRollCall and TryGetRollCallResult requires the skill to know how many buttons it needs to work.

Often a skill will want to know how many buttons there are as a way of registering players etc, so ideally the package would have a way of figuring out the mapping from a timed out event.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.