Things used in this project

Schematics

Schematics
The schematics explains the connection without the Grove shield.
Schematic

Code

connectToAWS.jsJavaScript
Node JS file to register the device to the AWS IoT Thing
var awsIot = require('aws-iot-device-sdk');

var myThingName = 'intel_galileo';

var thingShadows = awsIot.thingShadow({
   keyPath: './cert/6cf88b301c-private.pem.key',   // path of private key - change the name accourding to your key name
  certPath: './cert/6cf88b301c-certificate.pem.crt', // path of certificate - change the name accourding to your cert name
    caPath: './cert/rootCA.pem',  // path of root file
  clientId: myThingName,
    region: 'us-west-2'  // your region
});

mythingstate = {
  "state": {
    "reported": {
      "LocalIP": "unknown"
    }
  }
}

var networkInterfaces = require( 'os' ).networkInterfaces( );
mythingstate["state"]["reported"]["LocalIP"] = networkInterfaces['enp0s20f6'][0]['address'];


// json data for dynamoDB
var msg = "{\"key\":\"value\"}";

thingShadows.on('connect', function() {
  console.log("Connected...");
  console.log("Registering...");
  thingShadows.register( myThingName );

  // An update right away causes a timeout error, so we wait about 2 seconds
  setTimeout( function() {
    console.log("Updating my IP address...");
    clientTokenIP = thingShadows.update(myThingName, mythingstate);
    console.log("Update:" + clientTokenIP);
  }, 2500 );


  // Code below just logs messages for info/debugging
  thingShadows.on('status',
    function(thingName, stat, clientToken, stateObject) {
       console.log('received '+stat+' on '+thingName+': '+
                   JSON.stringify(stateObject));
    });

  thingShadows.on('update',
      function(thingName, stateObject) {
         console.log('received update '+' on '+thingName+': '+
                     JSON.stringify(stateObject));
      });

  thingShadows.on('delta',
      function(thingName, stateObject) {
         console.log('received delta '+' on '+thingName+': '+
                     JSON.stringify(stateObject));
      });

  thingShadows.on('timeout',
      function(thingName, clientToken) {
         console.log('received timeout for '+ clientToken)
      });

  thingShadows
    .on('close', function() {
      console.log('close');
    });
  thingShadows
    .on('reconnect', function() {
      console.log('reconnect');
    });
  thingShadows
    .on('offline', function() {
      console.log('offline');
    });
  thingShadows
    .on('error', function(error) {
      console.log('error', error);
    });


});
controlThings.pyPython
Python file to control the things connected to the Intel Galileo Board via AWS IoT MQTT
import paho.mqtt.client as mqtt #make sure you have installed mqtt client library for python
import ssl
import json
import time
import thread

#defining necessary pins
led = 4
buzzer = 3
button = 2

#Importing Intel Galileo Official UPM Library
import pyupm_grove as grove

# Create the temperature sensor object using AIO pin 0
temp = grove.GroveTemp(0)

# Create the light sensor object using AIO pin 0
light = grove.GroveLight(1)

# make sure python wiring x86 library is installed.
# Import the GPIOEdison class from the wiringx86 module.
from wiringx86 import GPIOGalileoGen2 as GPIO
gpio = GPIO()

gpio.pinMode(led, gpio.OUTPUT)
gpio.pinMode(buzzer , gpio.PWM)
gpio.pinMode(button, gpio.INPUT)

#defining topics
servoTopic  = "things/servo"
ledTopic    = "things/led"
buttonTopic = "things/button"
buzzerTopic = "things/buzzer"
tempTopic   = "things/temp"
potTopic    = "things/pot"
lightTopic    = "things/light"


def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    client.subscribe(servoTopic)
    client.subscribe(ledTopic)
    client.subscribe(buzzerTopic)
    client.subscribe("topic/test")
    print("Subscribed to Necessary Topics")

def on_message(client, userdata, msg):
    print "Message Topic :" + str(msg.topic)
    print "Message :" + str(msg.payload)
    if str(msg.topic) == ledTopic:
	blinkLED(str(msg.payload))
    elif str(msg.topic) == buzzerTopic:
	soundBuzzer(str(msg.payload))


def blinkLED(msg):
    jsonData = json.loads(msg)
    print jsonData
    for x in range(0,(jsonData['loopFor'])):
        gpio.digitalWrite(led, gpio.HIGH)
        time.sleep(jsonData['Period'])
        gpio.digitalWrite(led, gpio.LOW)
        time.sleep(jsonData['Period'])
    print "Blink LED Done"

def soundBuzzer(msg):
    jsonData = json.loads(msg)
    print jsonData
    gpio.analogWrite(buzzer, jsonData['PWM'])
    time.sleep(jsonData['Period'])
    gpio.analogWrite(buzzer, 0)
    print "Sound Buzzer Done"


client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.tls_set(ca_certs='./cert/rootCA.pem', certfile='./cert/6cf88b301c-certificate.pem.crt', keyfile='./cert/6cf88b301c-private.pem.key', tls_version=ssl.PROTOCOL_SSLv23)
client.tls_insecure_set(True)
client.connect("A1K6TUOC3TPQ8H.iot.us-west-2.amazonaws.com", 8883, 60) #Taken from REST API endpoint



#Publishing Analog Values to AWS
def publishTemp(Dummy):
	while (1):
		celsius = temp.value()
		fahrenheit = celsius * 9.0/5.0 + 32.0;
		tempJsonObject = json.dumps("{'Temp in Celsius':" + str(celsius)  + "}")
		client.publish(tempTopic, payload=tempJsonObject , qos=0, retain=False)
		print "%d degrees Celsius, or %d degrees Fahrenheit.. Published to AWS" % (celsius, fahrenheit)
		#Wait for Five second
		time.sleep(5)

def publishLight(Dummy):
	while (1):
		print "Raw Light Value: " + str(light.raw_value() )
		lightJsonObject = json.dumps("{'Raw Light Value':" + str(light.raw_value() )  + "}")
		client.publish(lightTopic, payload=lightJsonObject , qos=0, retain=False)
		#Wait for Five second
		time.sleep(5)

def buttonPress(Dummy):
	while(1):
		#print "In Loop"
		if gpio.digitalRead(button) == 1:
			print "Button Pressed"
			client.publish(buttonTopic, payload="Button Pressed" , qos=0, retain=False)


thread.start_new_thread(publishTemp,("publishTempThread",))
thread.start_new_thread(publishLight,("publishLightThread",))
thread.start_new_thread(buttonPress,("publishbuttonThread",))


client.loop_forever() #MQTT's will never end

Credits

Replications

Did you replicate this project? Share it!

I made one

Love this project? Think it could be improved? Tell us what you think!

Give feedback

Comments

Similar projects you might like

Computer Vision Neural Network on Your Intel NUC / Linux Box
Intermediate
  • 437
  • 5

Work in progress

Want to turn your Intel® NUC, or any Linux box running Ubuntu into an artificially intelligent, IoT connected CCTV hub? Check this out!

Eco-Thing #1  "Eco-Smart-Container V1.0"
Intermediate
  • 2,063
  • 13

Full instructions

An IoT device that could help keep the Sandy River Delta clean, as garbage is a very common problem.

Smart Garbage Monitoring System Using Arduino 101
Intermediate
  • 881
  • 5

Full instructions

A method in which waste management is automated. An innovative system that will help keep the city clean and healthy

Shower Regulator
Intermediate
  • 3,005
  • 3

Full instructions

Learn how to make a device to limit your shower time!

Christmas Gift Box
Intermediate
  • 3,681
  • 595

Full instructions

Christmas Gift Box plays music and sends an email when it is opened.

SensorBoat
Intermediate
  • 181
  • 2

Full instructions

An Arduino controlled boat that takes temperature, accelerometer, and light data from any body of water.

Sign up / LoginProjectsPlatformsTopicsContestsLiveAppsBetaFree StoreBlog