Priyanka JoshiShubham Kothari
Published

Smart Park With Astro

A smart parking mobile app to assist you in finding and reserving an available parking spot nearby so that others wouldn't beat you to it.

IntermediateWork in progress5 hours1,102
Smart Park With Astro

Things used in this project

Hardware components

Resistor 1k ohm
Resistor 1k ohm
×1
Servos (Tower Pro MG996R)
×1
Standard LCD - 16x2 White on Blue
Adafruit Standard LCD - 16x2 White on Blue
×1
Breadboard (generic)
Breadboard (generic)
×1
NodeMCU ESP8266 Breakout Board
NodeMCU ESP8266 Breakout Board
×1

Software apps and online services

Arduino IDE
Arduino IDE
OM2M
OneM2M
Android Studio
Android Studio

Hand tools and fabrication machines

Soldering iron (generic)
Soldering iron (generic)
Mastech MS8217 Autorange Digital Multimeter
Digilent Mastech MS8217 Autorange Digital Multimeter

Story

Read more

Schematics

HighLevelDiagram

Highleveldiagram 5sjt80hxgd

Code

Main Java

Java
package com.demo.smartparkng;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {
    private ListStatusTask listStatusTask;
    Button button1;
    Button button2;
    Button button3;
    Button button4;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listStatusTask = new ListStatusTask();
        listStatusTask.execute();

        button1 = (Button) findViewById(R.id.button1);
        button2 = (Button) findViewById(R.id.button2);
        button3 = (Button) findViewById(R.id.button3);
        button4 = (Button) findViewById(R.id.button4);
        View.OnClickListener cl = new View.OnClickListener() {
            public void onClick(View v) {
                Button cur = (Button) v;
                Intent intent = new Intent(getApplicationContext()
                        , Unlock.class)
                        .putExtra(Intent.EXTRA_TEXT, cur.getText());
                startActivity(intent);
            }
        };

        button1.setOnClickListener(cl);
        button2.setOnClickListener(cl);
        button3.setOnClickListener(cl);
        button4.setOnClickListener(cl);
    }
    class ListStatusTask extends AsyncTask<Void, Void, boolean[]> {
        private final String LOG_TAG = getClass().getSimpleName();


        @Override
        protected boolean[] doInBackground(Void... params) {
            HttpURLConnection urlConnection = null;
            BufferedReader reader = null;

            String forecastJsonStr = null;

            try {

                String baseUrl = "http://10.24.47.29:3000/list";
                URL url = new URL(baseUrl);

                // Create the request to OpenWeatherMap, and open the connection
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");
                urlConnection.connect();
                InputStream inputStream = urlConnection.getInputStream();
                StringBuilder buffer = new StringBuilder();
                if (inputStream != null) {
                    reader = new BufferedReader(new InputStreamReader(inputStream));

                    String line;
                    while ((line = reader.readLine()) != null) {
                        buffer.append(line).append("\n");
                    }

                    if (buffer.length() != 0) {
                        forecastJsonStr = buffer.toString();
                        Log.i(LOG_TAG, forecastJsonStr);
                    }
                    JSONArray forecastJson = new JSONArray(forecastJsonStr);
                    boolean[] b = new boolean[4];
                    for(int i = 0; i < 4; i++)
                        b[i] = forecastJson.getBoolean(i);
                    return b;
                }

            } catch (IOException e) {
                Log.e("PlaceholderFragment", "Error ", e);
            } catch (JSONException e) {
                Log.e("JSON parser", "Error ", e);
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
                if (reader != null) {
                    try {
                        reader.close();

                    } catch (final IOException e) {
                        Log.e("PlaceholderFragment", "Error closing stream", e);
                    }
                }

            }
            return null;
        }

        @Override
        protected void onPostExecute(boolean[] b) {
            if(b != null) {
                int cr = getColor(R.color.red);
                int cg = getColor(R.color.green);
                if (b[0]) button1.setTextColor(cg);
                else button1.setTextColor(cr);
                if (b[1]) button2.setTextColor(cg);
                else button2.setTextColor(cr);
                if (b[2]) button3.setTextColor(cg);
                else button3.setTextColor(cr);
                if (b[3]) button4.setTextColor(cg);
                else button4.setTextColor(cr);
            }
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    listStatusTask = new ListStatusTask();
                    listStatusTask.execute();
                }
            }, 1000);
        }
    }
}

OneM2m-Monitor.js

JavaScript
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var request = require('request');
var app = express();

///////////////Parameters/////////////////
//CSE Params
var cseUri = "http://10.24.47.29:8080";

//AE params
var aeId = "Cae-monitor1";
var aeIp = "10.24.47.29";
var aePort = 3000;
var thresh = 200;
//////////////////////////////////////////

app.use(bodyParser.json());
app.listen(aePort, function () {
	console.log("AE Monitor listening on: "+aeIp+":"+aePort);
});
var avail = [true, true, true, true];
var reserve = [false, false, false, false];
var unlock = [false, false, false, false];
app.post('/', function (req, res) {
	console.log("\n")
	var content = req.body["m2m:sgn"].nev.rep["m2m:cin"].con;
	console.log("Receieved luminosity: "+content);
	content = content.split(',');
	var id = parseInt(content[0]) - 1;
	content = content[1];

	if(content>thresh != avail[id]){
		if(!reserve[id] && !unlock[id]){
			avail[id] = content>thresh;
			createContenInstance(id);
		}
		else{
			if(reserve[id] && unlock[id]){
				if(!avail[id]){
					reserve[id] = false;
					unlock[id] = false;
				}
				avail[id] = content>thresh;
				createContenInstance(id);
			}
		}
	}
	res.sendStatus(200);	
});

app.get('/list', function(req, res) {
	a = [];
	for(var i = 0; i < 4; i++){
		a[i] = avail[i] && !reserve[i] && !unlock[i]
	}
	res.json(a)
})
app.post('/reserve', function(req, res) {
	var id = req.body["id"]
	if(avail[id] && !reserve[id] && !unlock[id]){
		reserve[id] = true;
		createContenInstance(id);
		res.json(true);
	}
	else
		res.json(false);
})
app.post('/unlock', function(req, res) {
	var id = req.body["id"]
    if(avail[id] && reserve[id] && !unlock[id]){
    	unlock[id] = true;
    	createContenInstance(id);
    	res.json(true);
    }
    res.json(false);
})

createAE();
function createAE(){
	console.log("\n");
	var method = "POST";
	var uri= cseUri+"/server";
	var resourceType=2;
	var requestId = "123456";
	var representation = {
		"m2m:ae":{
			"rn":"mymonitor1",			
			"api":"app.company.com",
			"rr":"true",
			"poa":["http://"+aeIp+":"+aePort]
		}
	};

	console.log(method+" "+uri);
	console.log(representation);

	var options = {
		uri: uri,
		method: method,
		headers: {
			"X-M2M-Origin": aeId,
			"X-M2M-RI": requestId,
			"Content-Type": "application/json;ty="+resourceType
		},
		json: representation
	};

	request(options, function (error, response, body) {
		console.log("");
		if(error){
			console.log(error);
		}else{
			console.log(response.statusCode);
			console.log(body);
			createSubscription(1);
			createSubscription(2);
			createSubscription(3);
			createSubscription(4);
		}
	});
}


function createSubscription(dev){
	console.log("\n");
	var method = "POST";
	var uri= cseUri+"/server/mydevice" + dev + "/luminosity";
	var resourceType=23;
	var requestId = "123456" + dev;
	var representation = {
		"m2m:sub": {
			"rn": "subMonitor",
			"nu": ["Cae-monitor1"],
			"nct": 2,
			"enc": {
				"net": 3
			}
		}
	};

	console.log(method+" "+uri);
	console.log(representation);

	var options = {
		uri: uri,
		method: method,
		headers: {
			"X-M2M-Origin": aeId,
			"X-M2M-RI": requestId,
			"Content-Type": "application/json;ty="+resourceType
		},
		json: representation
	};

	request(options, function (error, response, body) {
		console.log("");
		if(error){
			console.log(error);
		}else{
			console.log(response.statusCode);
			console.log(body);
		}
	});
}

function createContenInstance(id){
	console.log("\n");
	var method = "POST";
	var uri= cseUri+"/server/mydevice" + (parseInt(id) + 1) + "/led";
	var resourceType=4;
	var requestId = "123456";
	var value = (avail[id] ? 1 : 0)  + ',' + (reserve[id] ? 1 : 0)  + ',' + (unlock[id] ? 1 : 0);
	var representation = {
		"m2m:cin":{
				"con": value
			}
		};

	console.log(method+" "+uri);
	console.log(representation);

	var options = {
		uri: uri,
		method: method,
		headers: {
			"X-M2M-Origin": aeId,
			"X-M2M-RI": requestId,
			"Content-Type": "application/json;ty="+resourceType
		},
		json: representation
	};

	request(options, function (error, response, body) {
		console.log("");
		if(error){
			console.log(error);
		}else{
			console.log(response.statusCode);
			console.log(body);
		}
	});
}

onem2m-adn.ino

Arduino
#include <LCD.h>
#include <LiquidCrystal.h>
#include <LiquidCrystal_I2C.h>
#include<Servo.h>
#include<Wire.h>
#include <ESP8266WiFi.h>
#include "Timer.h"

///////////////Parameters/////////////////
// WIFI params
const char* ssid = "onem2m";
const char* password = "hackathon";

// CSE params
const char* host = "10.24.47.29";
const int httpPort = 8080;

// AE params
const int aePort   = 80;
const int id = 4;
const String origin   = "Cae_device";
const String deviceUri = "/server/mydevice";
Servo servo;
LiquidCrystal_I2C lcd(0x27,2,1,0,4,5,6,7);
///////////////////////////////////////////

Timer t;

WiFiServer server(aePort);
int sensorPin = A0; // select the input pin for LDR 
int sensorValue = 0; // variable to store the value coming from the sensor
int state = 0; 

void setup() {

  Serial.begin(115200);
  delay(10);

  // Configure pin 5 for LED control
  pinMode(0, OUTPUT);
  digitalWrite(0, 0);

  setAll();
  Serial.println();
  Serial.println();

  // Connect to WIFI network
  Serial.print("Connecting to ");
  Serial.println(ssid);
 
  WiFi.persistent(false);
  
  WiFi.begin(ssid, password);
  
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println();
  Serial.println("WiFi connected");  
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

  lcdPrint(String() + "Available PS" + (id - 1));
  // Start HTTP server
  server.begin();
  Serial.println("Server started");

  // Create AE resource
  String s = "{\"m2m:ae\":{\"rn\":\"mydevice";
  
  String resulat = send("/server",2, s + id + "\",\"api\":\"mydevice" + id + ".company.com\",\"rr\":\"true\",\"poa\":[\"http://"+WiFi.localIP().toString()+":"+aePort+"\"]}}");
  
  if(resulat=="HTTP/1.1 201 Created"){
    // Create Container resource
    send(deviceUri + id,3,"{\"m2m:cnt\":{\"rn\":\"luminosity\"}}");

    // Create ContentInstance resource
    send(deviceUri + id + "/luminosity",4,"{\"m2m:cin\":{\"con\":\"0\"}}");
    
    // Create Container resource
    send(deviceUri + id ,3,"{\"m2m:cnt\":{\"rn\":\"led\"}}");

    // Create ContentInstance resource
    send(deviceUri + id + "/led",4,"{\"m2m:cin\":{\"con\":\"OFF\"}}");

    // Create Subscription resource
    send(deviceUri + id + "/led",23,String() + "{\"m2m:sub\":{\"rn\":\"led_sub\",\"nu\":[\""+ origin + id +"\"],\"nct\":1}}");
  }

  t.every(1000*5, push);
}

// Method in charge of receiving event from the CSE
void loop(){
  t.update();
  // Check if a client is connected
  WiFiClient client = server.available();
  if (!client) {
    return;
  }
  
  // Wait until the client sends some data
  Serial.println("new client");
  while(!client.available()){
    delay(1);
  }
  
  // Read the request
  String req = client.readString();
  client.flush();

  if(req.indexOf("1,0,0") != - 1){
    lcdPrint(String() + "Available PS" + (id - 1));
    state = 0;
//    digitalWrite(5, 1);
//    digitalWrite(4, 0);
    digitalWrite(0, 0);
  }
  if(req.indexOf("1,1,0") != - 1){
    lcdPrint("Reserved");
    state = 1;
    servoDir(true);
//    digitalWrite(5, 1);
//    digitalWrite(4, 1);
    digitalWrite(0, 0);
  }
  if(req.indexOf("1,1,1") != - 1){
    lcdPrint("Unlocked");
    state = 2;
    servoDir(false);
//    digitalWrite(5, 1);
//    digitalWrite(4, 1);
    digitalWrite(0, 1);
  }
  if(req.indexOf("0,1,1") != - 1){
    lcdPrint("Reserve inuse");
    state = 3; 
//    digitalWrite(5, 0);
//    digitalWrite(4, 1);
    digitalWrite(0, 1);
  }
  if(req.indexOf("0,0,0") != - 1){
    lcdPrint("inuse");
    state = 4; 
//    digitalWrite(5, 0);
//    digitalWrite(4, 0);
    digitalWrite(0, 0);
  }
  client.flush();

  // Send HTTP response to the client
  String s = "HTTP/1.1 200 OK\r\n";
  client.print(s);
  delay(1);
  Serial.println("Client disonnected");
 
}


// Method in charge of sending request to the CSE
String send(String url,int ty, String rep) {

  // Connect to the CSE address
  Serial.print("connecting to ");
  Serial.println(host);
 
  WiFiClient client;
 
  if (!client.connect(host, httpPort)) {
    Serial.println("connection failed");
    return "error";
  }

  
  // prepare the HTTP request
  String req = String()+"POST " + url + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" +
               "X-M2M-Origin: " + origin + id + "\r\n" +
               "Content-Type: application/json;ty="+ty+"\r\n" +
               "Content-Length: "+ rep.length()+"\r\n"
               "Connection: close\r\n\n" + 
               rep;


  // Send the HTTP request
  client.print(req);
               
  unsigned long timeout = millis();
  while (client.available() == 0) {
    if (millis() - timeout > 5000) {
      Serial.println(">>> Client Timeout !");
      client.stop();
      return "error";
    }
  }

  // Read the HTTP response
  String res="";
  if(client.available()){
    res = client.readStringUntil('\r');
//    Serial.print(res);
  }
  while(client.available()){
    String line = client.readStringUntil('\r');
//    Serial.print(line);
  }
  
  Serial.println();
  Serial.println("closing connection");
  Serial.println();
  return res;
}

void push(){
  sensorValue = analogRead(sensorPin);
  Serial.println(sensorValue);
  String data = String()+"{\"m2m:cin\":{\"con\":\"" + id + "," +sensorValue+"\"}}";
  send(deviceUri + id + "/luminosity",4,data);

}

void setAll(){
  lcd.begin(16,2);
  lcd.setBacklightPin(3,POSITIVE);
  lcd.setBacklight(HIGH);
  Serial.begin(115200);
  servo.attach(10);
  servo.write(0);
  delay(2000);
}

void servoDir(boolean dir){
   
   if(dir){
     servo.write(90);
     delay(1000);
   }
   else {
     servo.write(0);
     delay(1000);
   }
}

void lcdPrint(String str){
  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print(str);
}

Credits

Priyanka Joshi

Priyanka Joshi

1 project • 2 followers
A graduate student at the University of Texas at Dallas majoring in Computer Science with Specialization in Intelligent Systems.
Shubham Kothari

Shubham Kothari

0 projects • 0 followers

Comments

Add projectSign up / Login