Introduction: Fortune Cookie Teller With Particle Photon, Thethings.iO & Twitter

In this instructable we're going to build and program an awesome fortune cookie teller, using the Particle Photon connected to thethings.iO via mqtt and to Twitter via api requests.

Desired functionality:

- Each time the button (connected to the Photon) is pressed, this will publish a message to thethings.iO via mqtt

- From thethings.iO, a trigger is going to be activated. First to update a twitter account with a new tweet (a random fortune cookie, above 50).

- After the twitter is sent, the trigger writes to a resource named blink with value equal to 1. Then the photon, with the callback, detects this writing and it blinks 3 times, showing that the tweet is writed.

Step 1: Hardware Requirements

For this instructable, the necessary hardware equipment is the following:

  • A Particle Photon.
  • A button (with a led).
  • 0.1" male-to-male wires.
  • 270ohm resistor.
  • 10K ohm resistor.
  • A protoboard

In order to improve the aesthetics, a wood box is provided.

Step 2: Hardware Connections

The hardware connections are as follows:

  1. Place the Photon in the protoboard, saving some space from both sides.
  2. Place the button and connect the wire from the photon 3.3v to a pin. Then connect a cable from the opposite pin in diagonal to the D1 pin in the photon. After this previous wire, connect a 10Kohm resistor to gnd, in order to force a low voltage when the button is not pressed.
  3. Place the LED to and connect the largest pin (+) with a resistor to the D2 photon pin. Connect the other LED pin to GND.

Step 3: Thethings.iO Account Creation & Thing Creation

In order to maintain all the fortune cookies, send them to twitter and provide a communication with the photon, visit us at thethings.iO.

Register clicking start now (at the top right region).

For every device we want to connect to thethings.iO, a new thing should be created:

  1. Once you register, press Things at the left region.
  2. Click on new Product. Check that the format is JSON. Select "Other" board (by now).
  3. After creating the thing, click on it. Activate a new code on "Get activation codes".
  4. Generate an activation code and activate it.

Remember the Thing Token, needed in both the photon code and the trigger.

Step 4: Particle Code

  1. Go to particle build and create a new empty project.
  2. Copy the example code from our github repository.
  3. Add the MQTT library files to your project. From the left panel, select Libraries (after Code < >).
  4. Subtitute your wifi ssid, password and TOKEN.
  5. Flash de firmware to your photon.

Step 5: Using Twitter API

1.- Enter http://dev.twitter.com/apps with your twitter account.

2.- Register a new application

3.- Click Keys and acces tokens and press Generate acces tokens.

Save both (Normal and secret) consumer and access keys in order to automatically send tweets from thethings.iO.

Step 6: Connecting Photon to Thethings.iO

    1. Trigger to twiter:

    After uploading the code to the photon, create a trigger from the cloud code:

    1. Click to Cloud Code > Add trigger > Add a name and select the product with your thing name.
    2. Paste this code, also available at our github.
    3. Change the token and all the the access and consumer keys from your twitter account.
    /*
       params: is an object with the keys:
        - action: one of 'write' | 'read'
        - thingToken: the thing that triggered the trigger
        - values: only if action == 'write'. Is an array of values where each value is an object with:
        - key: the key
        - value: the data sent
        - datetime: (can be null)
    
       callback: is a function to be called when the trigger ends can contain a
           parameter string *error* if the trigger needs to report an error.
    */
    
    function trigger(params, callback){
      if (params.action !== 'write') return callback();
      var values = {
          values: params.values
        };
      
      var fortune_cookies = ["Today it's up to you to create the peacefulness you long for.",
    "A friend asks only for your time not your money.",
    "If you refuse to accept anything but the best, you very often get it.",
    "A smile is your passport into the hearts of others.",
    "A good way to keep healthy is to eat more Chinese food.",
    "Your high-minded principles spell success.",
    "Hard work pays off in the future, laziness pays off now.",
    "Change can hurt, but it leads a path to something better.",
    "Enjoy the good luck a companion brings you.",
    "People are naturally attracted to you.",
    "Hidden in a valley beside an open stream- This will be the type of place where you will find your dream.",
    "A chance meeting opens new doors to success and friendship.",
    "You learn from your mistakes... You will learn a lot today.",
    "If you have something good in your life, don't let it go!",
    "What ever you're goal is in life, embrace it visualize it, and for it will be yours.",
    "Your shoes will make you happy today.",
    "You cannot love life until you live the life you love.",
    "Be on the lookout for coming events; They cast their shadows beforehand.",
    "Land is always on the mind of a flying bird.",
    "The man or woman you desire feels the same about you.",
    "Meeting adversity well is the source of your strength.",
    "A dream you have will come true.",
    "Our deeds determine us, as much as we determine our deeds.",
    "Never give up. You're not a failure if you don't give up.",
    "You will become great if you believe in yourself.",
    "There is no greater pleasure than seeing your loved ones prosper.",
    "You will marry your lover.",
    "A very attractive person has a message for you.",
    "You already know the answer to the questions lingering inside your head.",
    "It is now, and in this world, that we must live.",
    "You must try, or hate yourself for not trying.",
    "You can make your own happiness.",
    "The greatest risk is not taking one.",
    "The love of your life is stepping into your planet this summer.",
    "Love can last a lifetime, if you want it to.",
    "Adversity is the parent of virtue.",
    "Serious trouble will bypass you.",
    "A short stranger will soon enter your life with blessings to share.",
    "Now is the time to try something new.",
    "Wealth awaits you very soon.",
    "If you feel you are right, stand firmly by your convictions.",
    "If winter comes, can spring be far behind?",
    "Keep your eye out for someone special.",
    "You are very talented in many ways.",
    "A stranger, is a friend you have not spoken to yet.",
    "A new voyage will fill your life with untold memories.",
    "You will travel to many exotic places in your lifetime.",
    "Your ability for accomplishment will follow with success.",
    "Nothing astonishes men so much as common sense and plain dealing.",
    "Its amazing how much good you can do if you dont care who gets the credit."];
      
      for (var i = 0; i < values.values.length; ++i) {
        if (values.values[i].key == 'buttonPressed' && values.values[i].value == '1') {
        	var inputTwitter = {
              'status': 'Awesome things happening!'
            }
            inputTwitter.status = fortune_cookies[Math.floor((Math.random() * 50))];
            
             var twitter = new Twitter({
                accessToken: '',
                accessTokenSecret: '',
                consumerKey: '',
                consumerSecret: ''
     		 });
    
      		 twitter.postTweet(inputTwitter, callback);
          
          	console.log(values);
        	values.values[0].key = 'blink';
        	values.values[0].value = '1';
      		thethingsAPI.thingWrite(
        	  'your token',
        	  values,
        	  function() { callback(null, 'ok'); }
        	);
          	values.values[0].key = 'fortuneCookie';
        	values.values[0].value = inputTwitter.status;
      		thethingsAPI.thingWrite(
        	  'your token',
        	  values,
        	  function() { callback(null, 'ok'); }
        	);
          
      	}
      }
      console.log(values);
      
      
       callback();
    }
    

    2. Creating the Dashboard

    Lets create a dashboard with some widgets to display, in real time, which fortune cookie is sent to twitter and the total statistics. (Remember first to connect the particle in order to display the resources).

    The statistics widget:

    1. Press Edit Dashboard > Add widget.
    2. Select a name, choose Thing Resource inside Data source.
    3. Choose the name of your product, the thing and the resource (fortuneCookie).
    4. Choose last Value and check the bars graph.
    5. Remember to check the Realtime option.

    The logs widget:

    1. Press Edit Dashboard > Add widget
    2. Select a name, choose Thing Resource inside Data source.
    3. Choose the name of your product, the thing and the resource (fortuneCookie).
    4. Choose Historical and check the log.
    5. Remember to check the Realtime option.

    The last image represents the final dashboard with this to widgets.

    Step 7: Final Results

    The above picture shows the final structure with the wood box. A full video is coming soon!

    Stay tuned for more awesome instructables and visit our blog and webpage!