Sarah WatanabeMarios Dardas
Published

Project Wildfire

Using air quality metrics, effective forest fire detection and planning can be achieved.

Work in progress195
Project Wildfire

Things used in this project

Story

Read more

Code

app.R

R
Dashboard for displaying sensor data.

Runs on EC2 instance on AWS or local machine
#Dashboard to Project Wildfire, runs on EC2 instance with Shiny R Server

library(shiny)
library(shinydashboard)

ui <- dashboardPage(
  dashboardHeader(title = "Virtual Forest"),
  dashboardSidebar(
    sidebarMenu(
      menuItem("Dashboard", tabName = "dashboard", icon = icon("dashboard")),
      menuItem("Widgets", tabName = "widgets", icon = icon("th"))
    )
  ),
  dashboardBody(
    tabItems(
      # First tab content
      tabItem(tabName = "dashboard",
              fluidRow(
                box(plotOutput("plot1", height = 250)),
                
                box(
                  title = "Controls",
                  sliderInput("slider", "Number of observations:", 1, 100, 50)
                )
              )
      ),
      
      # Second tab content
      tabItem(tabName = "widgets",
              h2("Widgets tab content")
      )
    )
  ))

server <- function(input, output) { 
  
  DATA <- data.frame(matrix(ncol = 3, nrow=0))
  colnames(DATA) <- c("MQ5", "MQ7", "Tempurature (Celsius)")
  
  con <- socketConnection(host="ENTER IP ADDRESS", port = "ENTER PORT", blocking=TRUE,
                          server=TRUE, open="r+")
  
  observe({
    data <- read.csv(text = readLines(con, 1), sep=",", header = FALSE)
    colnames(data) <- c("MQ5", "MQ7", "Tempurature (Celsius)")
    DATA <- rbind(DATA, data)
    print(DATA)
    output$plot1 <- renderPlot({plot(DATA)})
  })
}

shinyApp(ui, server)

retrieveSensorData.py

Python
Python code that runs on Intel Edison which retrieves sensor data (gas and temperature). The data is sent either to AWS IoT or to client.
#Runs on Intel Edison

import socket                       #Socket/ Server Library
import time, sys, signal, atexit    
import pyupm_gas as upmGas          #MQ Gas Sensor Libraries
import pyupm_grove as grove         #For tempurature sensor

##############################################################################
#       					Set Up Client Code                                         # 
##############################################################################
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = "ENTER IP ADDRESS"
port = "ENTER PORT"
s.connect((host,port))

def SendGas(str):
   s.send(str) 
   data = ''
   data = s.recv(5000).decode()

##############################################################################
#       					Collect Gas Data & Temp Data                               # 
##############################################################################

# Sensors
myTemp = grove.GroveTemp(0)  #AIO1 [Grove Tempurature Sensor]
myMQ7  = upmGas.MQ7(1);      #AIO2 [MQ7 Gas Sensor: Carbon Monoxide (CO)]
myMQ5  = upmGas.MQ5(2);      #AIO3 [MQ5 Gas Senosr: H2, LPG, CH4, CO, Alcohol]

## Exit handlers ##
# This function stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
    raise SystemExit

# This function lets you run code on exit, including functions from myMQ2
def exitHandler():
    print "Exiting"
    sys.exit(0)

# Register exit handlers
atexit.register(exitHandler)
signal.signal(signal.SIGINT, SIGINTHandler)

# Infinite loop, ends when script is cancelled
# Repeatedly, take a sample every 2 microseconds;
# find the average of 128 samples; and
myMQ5Buffer = upmGas.uint16Array(128)
myMQ7Buffer = upmGas.uint16Array(128)

while(1):
    myMQ5Data  = myMQ5.getSample() #Collect MQ5 gas Data 
    myMQ7Data  = myMQ7.getSample() #Collect MQ7 gas Data
    myTempData = myTemp.value()    #Tempurature in celsius

    message = "" + str(myMQ5Data) + "," + str(myMQ7Data) + "," + str(myTempData) + "\n"
    SendGas(message)   
    time.sleep(1)

s.close()

Intel_Edison_AWS_IoT.py

Python
Interfaces Intel Edison Sensors with AWS IoT to upload data.
'''
/*
 * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License").
 * You may not use this file except in compliance with the License.
 * A copy of the License is located at
 *
 *  http://aws.amazon.com/apache2.0
 *
 * or in the "license" file accompanying this file. This file is distributed
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */
 '''

from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
import sys
import logging
import time
import getopt
import signal 
import atexit 

# Custom MQTT message callback
def customCallback(client, userdata, message):
	print("Received a new message: ")
	print(message.payload)
	print("from topic: ")
	print(message.topic)
	print("--------------\n\n")

# Usage
usageInfo = """Usage:
Use certificate based mutual authentication:
python basicPubSub.py -e <endpoint> -r <rootCAFilePath> -c <certFilePath> -k <privateKeyFilePath>
Use MQTT over WebSocket:
python basicPubSub.py -e <endpoint> -r <rootCAFilePath> -w
Type "python basicPubSub.py -h" for available options.
"""
# Help info
helpInfo = """-e, --endpoint
	Your AWS IoT custom endpoint
-r, --rootCA
	Root CA file path
-c, --cert
	Certificate file path
-k, --key
	Private key file path
-w, --websocket
	Use MQTT over WebSocket
-h, --help
	Help information
"""

# Read in command-line parameters
useWebsocket = False
host = ""
rootCAPath = ""
certificatePath = ""
privateKeyPath = ""
try:
	opts, args = getopt.getopt(sys.argv[1:], "hwe:k:c:r:", ["help", "endpoint=", "key=","cert=","rootCA=", "websocket"])
	if len(opts) == 0:
		raise getopt.GetoptError("No input parameters!")
	for opt, arg in opts:
		if opt in ("-h", "--help"):
			print(helpInfo)
			exit(0)
		if opt in ("-e", "--endpoint"):
			host = arg
		if opt in ("-r", "--rootCA"):
			rootCAPath = arg
		if opt in ("-c", "--cert"):
			certificatePath = arg
		if opt in ("-k", "--key"):
			privateKeyPath = arg
		if opt in ("-w", "--websocket"):
			useWebsocket = True
except getopt.GetoptError:
	print(usageInfo)
	exit(1)

# Missing configuration notification
missingConfiguration = False
if not host:
	print("Missing '-e' or '--endpoint'")
	missingConfiguration = True
if not rootCAPath:
	print("Missing '-r' or '--rootCA'")
	missingConfiguration = True
if not useWebsocket:
	if not certificatePath:
		print("Missing '-c' or '--cert'")
		missingConfiguration = True
	if not privateKeyPath:
		print("Missing '-k' or '--key'")
		missingConfiguration = True
if missingConfiguration:
	exit(2)

# Configure logging
logger = logging.getLogger("AWSIoTPythonSDK.core")
logger.setLevel(logging.DEBUG)
streamHandler = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
streamHandler.setFormatter(formatter)
logger.addHandler(streamHandler)

# Init AWSIoTMQTTClient
myAWSIoTMQTTClient = None
if useWebsocket:
	myAWSIoTMQTTClient = AWSIoTMQTTClient("basicPubSubGasSensor", useWebsocket=True)
	myAWSIoTMQTTClient.configureEndpoint(host, 443)
	myAWSIoTMQTTClient.configureCredentials(rootCAPath)
else:
	myAWSIoTMQTTClient = AWSIoTMQTTClient("basicPubSubGasSensor")
	myAWSIoTMQTTClient.configureEndpoint(host, 8883)
	myAWSIoTMQTTClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath)

# AWSIoTMQTTClient connection configuration
myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20)
myAWSIoTMQTTClient.configureOfflinePublishQueueing(-1)  # Infinite offline Publish queueing
myAWSIoTMQTTClient.configureDrainingFrequency(2)  # Draining: 2 Hz
myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10)  # 10 sec
myAWSIoTMQTTClient.configureMQTTOperationTimeout(5)  # 5 sec

#gas sensor code
#######################
# Attach gas sensor to AIO1
myMQ2 = upmGas.MQ7(1);

## Exit handlers ##
# This function stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
    raise SystemExit

# This function lets you run code on exit, including functions from myMQ2
def exitHandler():
    print "Exiting"
    sys.exit(0)

# Register exit handlers
atexit.register(exitHandler)
signal.signal(signal.SIGINT, SIGINTHandler)

# Connect and subscribe to AWS IoT
myAWSIoTMQTTClient.connect()
myAWSIoTMQTTClient.subscribe("test/gasSensor", 1, customCallback)
time.sleep(2)

threshContext = upmGas.thresholdContext()
threshContext.averageReading = 0
threshContext.runningAverage = 0
threshContext.averagedOver = 2

# Publish to the same topic in a loop forever
loopCount = 0
mybuffer = upmGas.uint16Array(128)

while True:
	samplelen = myMQ2.getSampledWindow(2, 128, mybuffer)
	myAWSIoTMQTTClient.publish("test/gasSensor", "New Message " + str(loopCount), 1)
	if samplelen:
        thresh = myMQ2.findThreshold(threshContext, 30, mybuffer, samplelen)
        myMQ2.printGraph(threshContext, 5)
        if(thresh):
			myAWSIoTMQTTClient.publish("test/gasSensor", "Threshold is " + thresh, 1)
	loopCount += 1
	time.sleep(1)

Credits

Sarah Watanabe

Sarah Watanabe

1 project • 0 followers
I am from California in Tech. Currently, I am living in NYC
Contact
Marios Dardas

Marios Dardas

1 project • 0 followers
Contact

Comments