Home
Amazon echo (alexa) with PHP Hello World
- Details
This is my Helloworld for interacting with the amazon echo.
I packed it into one file. i'm not a big fan of samples being weighed down by includes (unless it calls for it).
In this example. Say your phrase: Alexa start Count Example
The echo will respond by saying the phrase "Welcome to the Our Ace count example say next item" and sending you a card in your echo app
The echo light will stay on and wait for you to say "next item" or "next"
When you say next it will count up by 1 using the session attributes in the json. You pass it json attributes and it passes them back
say next item until it hits five then it will quit. The light will go off on your echo.
Please note: you have to access you developer portal and set up your URL web service and SSL settings. Also, make sure your echo is using your developer email. If not setup another user on your echo and switch profiles to your developer account.
your dev setup area is here dev aw
Intent Schema:
{ "intents": [ { "intent": "quit", "slots": [] }, { "intent": "next", "slots": [] } ] }
Sample Utterances
next item
Below is the PHP code.
$EchoJArray = json_decode(file_get_contents('php://input')); $RequestType = $EchoJArray->request->type; $JsonOut = GetJsonMessageResponse($RequestType,$EchoJArray); $size = strlen($JsonOut); header('Content-Type: application/json'); header("Content-length: $size"); echo $JsonOut; //-----------------------------------------------------------------------------------------// // Some functions //-----------------------------------------------------------------------------------------// //This function returns a json blob for output function GetJsonMessageResponse($RequestMessageType,$EchoJArray){ $RequestId = $EchoJArray->request->requestId; $ReturnValue = ""; if( $RequestMessageType == "LaunchRequest" ){ $ReturnValue= ' { "version": "1.0", "sessionAttributes": { "countActionList": { "read": true, "category": true, "currentTask": "none", "currentStep": 0 } }, "response": { "outputSpeech": { "type": "PlainText", "text": "Welcome to the, Our, Ace, count example" }, "card": { "type": "Simple", "title": "Our Ace count example", "content": "I can count to five." }, "reprompt": { "outputSpeech": { "type": "PlainText", "text": "Can I help you with anything else?" } }, "shouldEndSession": false } }'; } if( $RequestMessageType == "SessionEndedRequest" ) { $ReturnValue = '{ "type": "SessionEndedRequest", "requestId": "$RequestId", "timestamp": "' . date("c") . '", "reason": "USER_INITIATED " } '; } if( $RequestMessageType == "IntentRequest" ){ $NextNumber = 0; $EndSession = "false"; $SpeakPhrase = "The next number is "; if( $EchoJArray->request->intent->name == "next" ) { $NextNumber = $EchoJArray->session->attributes->countActionList->currentStep + 1; $SpeakPhrase = "The next number is $NextNumber"; if( $EchoJArray->session->attributes->countActionList->currentStep == 3 ) { $EndSession = "true"; $SpeakPhrase = "Thank you for counting and good bye"; } } $ReturnValue= ' { "version": "1.0", "sessionAttributes": { "countActionList": { "read": true, "category": true, "currentTask": "none", "currentStep": '.$NextNumber.' } }, "response": { "outputSpeech": { "type": "PlainText", "text": "' . $SpeakPhrase . '" }, "card": { "type": "Simple", "title": "Our Ace count example", "content": "' . $SpeakPhrase . '" }, "reprompt": { "outputSpeech": { "type": "PlainText", "text": "Say next item to continue." } }, "shouldEndSession": ' . $EndSession . ' } }'; } return $ReturnValue; }// end function GetJsonMessageResponse
If you want Alexa to repeat phrases back to you try this:
Intent: { "intents": [ { "intent": "repeat", "slots": [ { "name": "Words", "type": "LITERAL" } ] } ] } Utterances: repeat words {any|Words} repeat words {any|Words} {any|Words} repeat words {any|Words} {any|Words} {any|Words} repeat words {any|Words} {any|Words} {any|Words} {any|Words} repeat words {any|Words} {any|Words} {any|Words} {any|Words} {any|Words} repeat words {any|Words} {any|Words} {any|Words} {any|Words} {any|Words} {any|Words} repeat words {any|Words} {any|Words} {any|Words} {any|Words} {any|Words} {any|Words} {any|Words} repeat words {any|Words} {any|Words} {any|Words} {any|Words} {any|Words} {any|Words} {any|Words} {any|Words}
each repeat Words line allows for inputs. the first line would grab only 1 word. if there are 3 words after the phrase "repeat words" it would match the 3rd utterance down. If you wanted to catch a lot of words you would need to extend how many utterances are listed and keep adding an extra {any|Words} for each line.
To get the words into PHP it would look like this
$TempWords = $EchoJArray->request->intent->slots->Words->value; //based off the above code.
PHP and MongoDB
- Details
I get the question how to interact with MongoDB at least once a month. So here is the simple version.
You will need to have the Mongo Functions installed on your web server see the installation guide (http://php.net/manual/en/mongo.installation.php)
Connecting to the database:
Just like any other database you need to specify an IP, port, database, username, and password.
$connect_mongo = "mongodb://localhost:27017/mytestdatabasename";
$o_mongo_connection= new Mongo($connect_mongo,array('username'=>'YourUsername','password'=>'YourPassword'));
You will need to assign that database to a var so you can reference it easily.
$o_database = $o_mongo_connection->selectDB('yourdb');
Now thinking in the terms of normal database like MySQL or MS SQL you generally write a select statement against a table. In the case of MongoDB we are going to make a reference to the collection (sorta of like a table).
$o_collection = $o_database->collection; //grabs the default collection
$o_collection = $o_database->selectCollection('collection'); //grabs a specific collection. Recommended
If you wanted to make a new collection you can do this:
$o_recipes = $o_database->recipes;
You now have a collection called recipes
To add a recipe:
$a_ingredients = array('Item' => '1 pound flour','Item' => '1 pound butter', 'Item' => '1 pound sugar');
$a_recipe = array(
'title' => 'Pound Cake',
'description' => 'They called it pound cake becuase it literally used a pound of butter, pound of sugar, and a pound of flour',
'ingredients' => $a_ingredients,
'create_date' => new MongoDate()
);
$o_recipes->insert($a_recipe);
Yes, you can simply pass it an array and that is your new document.
Please note that $recipe now has a new key called '_id' which was created for you and which you can now use to find the item in the database.
Reading and Finding
So to pull out the record you just made you could (wouldn't really need to do this since $recipes is already loaded into memory):
$id = $recipe['_id'];
$results = $o_recipes::findOne(array('_id' => $id));
To find all recipes that use 1 pound of flour:
$a_query = array('Item' => '1 pound flour');
// for a like use this: $a_query = array('Item' =>array('$regex' => '1 pound')); //there are various ways to do a like some are more optimal than others
$a_results = $o_recipes::find($a_query);
To iterate the array:
foreach ($a_results as $doc) {
print_r($doc);
}
To Update
To update a recipe you pass back the recipe you found. the _id is the key here.
if your record has an _id then it is an update. if no _id then it is new.
if you pass in new array keys they will be added.
To Delete:
to remove a single document you will want to use the _id for the most part
$id = $recipe['_id']; //or you got it from a POST or GET
$o_recipes::remove(array('_id' => $id));
or
$o_recipes::remove(array('_id' => 777), array("justOne" => true));
References:
http://php.net/manual/en/mongo.core.php
Self driving cars and ethics
- Details
It’s a happy sunny day as you are driven down the road by your self-driving car. You have been down this road 100 times. The trees sway in the wind and the flowers look even more amazing then you ever remember. You stare your lover in the eyes and toast to a most wonderful year and how the good times have made this year seem to fly by. Your lover points to the front of the car and reminds you of the time you kissed under the stars on the old single lane bridge that is approaching. As you speed toward the bridge you barley notice a person climbing the bridge supporting column. The person falls in your path. There is not enough time to stop. If the breaks are applied your car will surely plow into this person. If the car swerves left or right you will fly off the bridge and to your death. There is no override since you are in the back seat with your love. Someone is going to die today at the hands of software developer thousands of miles away.
The car’s onboard system constantly collects the information about what the car is doing and where the card is located geographically. It knows there is a living person in the front of it and is aware that it cannot stop in time. It quickly tries to find a safe route around the person it has determined that both left and right sides of the bridge have a huge elevation change indicating a cliff. The system estimates the chance of not falling off the cliff when impacting the column is slim to none.
The ethical module is the last set of processes that will be called before making its decision. It knows there are two lives in the car. It knows there is one life in the road way. The system is design to save as many lives as possible. The car slams into the person while applying the brakes in hopes to do as little damage as possible.
You and yours are lucky because if there had been one more person in the road way you’d been plummeting to your death.
GeoIP service
- Details
I wrote a GeoIP service.
it will get the ip of the user hitting the page or you can attach ip= to the query string.
get vars to pass are:
no format query modifiers will give you the following:
ip address matched to| loc id| country| state| city| zip | longitude | latitude
Formatting the Results:
format= xml,json,bar
Only the elements you want:
f=flags
Flags
- i = ip
- d = locid
- c = country
- s = state
- l = city (this is L for locality)
- z = zip
- n = longitude
- a = latitude
so if the query string had &f=naz you would get back longitude, latitude , and the zip code
Some Examples:
This would get the zip, lng, lat for the IP 8.8.8.8 in json format:
path/index.php?format=json&f=naz&ip=8.8.8.8
This would get the zip ,lng, lat of the person hitting the web server in json format:
path/index.php?format=json&f=naz
This would get the city, state of the person hitting the web server in bar format ( city|state):
path/index.php?format=bar&f=ls
Page 7 of 40