Thursday, February 12, 2015

Use iPhone and Arduino to Control Home Appliances

https://www.youtube.com/watch?v=YYBSB4Fak4E



Code

File:get.php

<?php
    
    header("Access-Control-Allow-Origin: *");
    
    $param = $_GET['object'];

    $servername = "localhost";
    $username = "dbuser";
    $password = "dbpassword";
    $dbname = "myvardb";

    // Create connection
    mysql_connect($servername, $username, $password ) or die(mysql_error());

    mysql_select_db($dbname) or die(mysql_error());

    $result = mysql_query("SELECT varvalue FROM myvardb.keyvalue where varname = '" . $param . "'");

    $json = array();
    
    $total_records = mysql_num_rows($result);

    if($total_records >= 1){
      while ($row = mysql_fetch_array($result, MYSQL_ASSOC)){
        $json[] = $row;
      }
    }
    $ret_val = "{" . $json[0]["varvalue"] . "}";
    echo json_encode($ret_val);
?>

File:control.php

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
</head>
<body>

<div data-role="page" id="pageone">
  <div data-role="header">
    <h1>Home Appliance Controller</h1>
  </div>

  <div data-role="main" class="ui-content">
      
    <p>Lighting : F1L1</p>
    <a id="off_f1l1" href="#" class="ui-btn ui-btn-inline">OFF</a>
    <a id="on_f1l1" href="#" class="ui-btn ui-btn-inline">ON</a>
    <br/>
    <p>Geyser : F1G1</p>
    <a id="off_f1g1" href="#" class="ui-btn ui-btn-inline">OFF</a>
    <a id="on_f1g1" href="#" class="ui-btn ui-btn-inline">ON</a>

  </div>

  <div data-role="footer">
    <h1>Giridhar Bhujanga</h1>
  </div>
  
  <div data-role="footer">
    <h3>giridharmb@gmail.com</h3>
  </div>
</div> 

<script>
$(document).ready(function(){

  $.ajax({
    type: "GET"
    ,url: "http://www.my-server.in/mypath/arduino/get.php?object=F1L1"
    ,success:function(d) {
      console.info("--success--");
      console.info(d[2]);
      if(d[2] == "1") {
        $("#on_f1l1").addClass('ui-btn-b');
        $("#off_f1l1").removeClass('ui-btn-b');
      }
      if(d[2] == "0") {
        $("#off_f1l1").addClass('ui-btn-b');
        $("#on_f1l1").removeClass('ui-btn-b');
      }
    }
    ,error: function(e) {
      console.info("--error--");
      console.info(e[2]);
    }
  });

  $.ajax({
    type: "GET"
    ,url: "http://www.my-server.in/mypath/arduino/get.php?object=F1G1"
    ,success:function(d) {
      console.info("--success--");
      console.info(d[2]);
      if(d[2] == "1") {
        $("#on_f1g1").addClass('ui-btn-b');
        $("#off_f1g1").removeClass('ui-btn-b');
      }
      if(d[2] == "0") {
        $("#off_f1g1").addClass('ui-btn-b');
        $("#on_f1g1").removeClass('ui-btn-b');
      }
    }
    ,error: function(e) {
      console.info("--error--");
      console.info(e[2]);
    }
  });

  $("#off_f1l1").click(function(){
    $("#off_f1l1").addClass('ui-btn-b');
    $("#on_f1l1").removeClass('ui-btn-b');
    $.ajax({
    type: "GET"
    ,url: "http://www.my-server.in/mypath/mysql.php?variable=F1L1&value=0"
    ,success:function(d) {
      console.info("--success--");
      console.info(d);
    }
    ,error:function(e) {
      console.info("--error--");
      console.info(e);
    }
    });
  });

  $("#on_f1l1").click(function(){
    $("#on_f1l1").addClass('ui-btn-b');
    $("#off_f1l1").removeClass('ui-btn-b');
    $.ajax({
    type: "GET"
    ,url: "http://www.my-server.in/mypath/mysql.php?variable=F1L1&value=1"
    ,success:function(d) {
      console.info("--success--");
      console.info(d);
    }
    ,error:function(e) {
      console.info("--error--");
      console.info(e);
    }
    });
  });

  $("#off_f1g1").click(function(){
    $("#off_f1g1").addClass('ui-btn-b');
    $("#on_f1g1").removeClass('ui-btn-b');
    $.ajax({
    type: "GET"
    ,url: "http://www.my-server.in/mypath/mysql.php?variable=F1G1&value=0"
    ,success:function(d) {
      console.info("--success--");
      console.info(d);
    }
    ,error:function(e) {
      console.info("--error--");
      console.info(e);
    }
    });
  });

  $("#on_f1g1").click(function(){
    $("#on_f1g1").addClass('ui-btn-b');
    $("#off_f1g1").removeClass('ui-btn-b');
    $.ajax({
    type: "GET"
    ,url: "http://www.my-server.in/mypath/mysql.php?variable=F1G1&value=1"
    ,success:function(d) {
      console.info("--success--");
      console.info(d);
    }
    ,error:function(e) {
      console.info("--error--");
      console.info(e);
    }
    });
  });
});
</script>

File:mysql.php

<?php

    $varname = $_GET["variable"];
    $value = $_GET["value"];

    $servername = "localhost";
    $username = "dbuser";
    $password = "dbpassword";
    $dbname = "myvardb";

    // Create connection
    mysql_connect($servername, $username, $password ) or die(mysql_error());

    mysql_select_db($dbname) or die(mysql_error());


    $my_query = "INSERT INTO keyvalue (varname,varvalue) VALUES('" . $varname . "','" . $value . "') ON DUPLICATE KEY UPDATE varvalue='" . $value . "'";

    $retval = mysql_query( $my_query );

    if(! $retval )
    {
      die('Could not enter data: ' . mysql_error());
    }

    echo "SUCCESS";

    mysql_close($conn);
    
?> 

MySQL Dump of the DB/Table on the WWW server

-- MySQL dump 10.13  Distrib 5.6.19, for osx10.7 (i386)
--
-- Host: www.my-server.in    Database: myvardb
-- ------------------------------------------------------
-- Server version   5.5.32-cll-lve

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

--
-- Table structure for table `keyvalue`
--

DROP TABLE IF EXISTS `keyvalue`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `keyvalue` (
  `varname` varchar(256) NOT NULL,
  `varvalue` varchar(256) NOT NULL,
  PRIMARY KEY (`varname`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `keyvalue`
--

LOCK TABLES `keyvalue` WRITE;
/*!40000 ALTER TABLE `keyvalue` DISABLE KEYS */;
INSERT INTO `keyvalue` VALUES ('F1G1','0'),('F1L1','0');
/*!40000 ALTER TABLE `keyvalue` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

-- Dump completed on 2015-02-12  9:54:38

Arduino Code

#include <Arduino.h>
#include <SoftwareSerial.h>
#include <WiFly.h>
#include "HTTPClient.h"
#include "Timer.h"

#define SSID      "WiFiNetworkName"
#define KEY       "WiFiPassword"
// WIFLY_AUTH_OPEN / WIFLY_AUTH_WPA1 / WIFLY_AUTH_WPA1_2 / WIFLY_AUTH_WPA2_PSK
#define AUTH      WIFLY_AUTH_WPA2_PSK

#define HTTP_GET_URL "http://www.my-server.in/giridharmb/arduino/get.php?object=F1L1"
#define HTTP_POST_URL "http://httpbin.org/post"
#define HTTP_POST_DATA "Hello world!"

// Pins' connection
// Arduino       WiFly
//  2    <---->    TX
//  3    <---->    RX
SoftwareSerial uart(2, 3);
WiFly wifly(uart);
HTTPClient http;
char get;

Timer t;

String response = "";
bool start_appending = false;

int RelayPin3 = 5; 

void setup() {
  pinMode(RelayPin3, OUTPUT);
  response = "";
  Serial.begin(9600);    
  Serial.println("------- WIFLY HTTP --------");
  
  
  uart.begin(9600);         // WiFly UART Baud Rate: 9600
  // Wait WiFly to init
//  delay(3000);

  // check if WiFly is associated with AP(SSID)
  if (!wifly.isAssociated(SSID)) {
    while (!wifly.join(SSID, KEY, AUTH)) {
      Serial.println("Failed to join " SSID);
      Serial.println("Wait 0.1 second and try again...");
      delay(100);
    }
    
    wifly.save();    // save configuration, 
  }


  Serial.println("\r\nTry to get url - " HTTP_GET_URL);
  Serial.println("------------------------------");
  while (http.get(HTTP_GET_URL, 10000) < 0) {
  }
  while (wifly.receive((uint8_t *)&get, 1, 1000) == 1) {
    Serial.print(get);
    if(get == '{')
    {
      start_appending = true;
    }
    if(get == '}')
    {
      start_appending = false;
      response = response + get;
    }
    if(start_appending == true)
    {
      response = response + get;
    }
  }
  
  Serial.println("\n---response---\n");
  Serial.println(response);
  Serial.println("\n--\n");
  
  if(response[1] == '1')
  {
    digitalWrite(RelayPin3,HIGH);
  }
  
  if(response[1] == '0')
  {
    digitalWrite(RelayPin3,LOW);
  }
  
  
  /*
  Serial.println("\r\n\r\nTry to post data to url - " HTTP_POST_URL);
  Serial.println("-------------------------------");
  while (http.post(HTTP_POST_URL, HTTP_POST_DATA, 10000) < 0) {
  }
  while (wifly.receive((uint8_t *)&get, 1, 1000) == 1) {
    Serial.print(get);
  }
  */
   
  if (wifly.commandMode()) {
    Serial.println("\r\n\r\nEnter command mode. Send \"exit\"(with \\r) to exit command mode");
  }
  
  t.every(15000, check_status);
   
    
}

void check_status()
{
  response = "";
   Serial.println("\r\nTry to get url - " HTTP_GET_URL);
  Serial.println("------------------------------");
  while (http.get(HTTP_GET_URL, 10000) < 0) {
  }
  while (wifly.receive((uint8_t *)&get, 1, 1000) == 1) {
    Serial.print(get);
    if(get == '{')
    {
      start_appending = true;
    }
    if(get == '}')
    {
      start_appending = false;
      response = response + get;
    }
    if(start_appending == true)
    {
      response = response + get;
    }
  }
  
  Serial.println("\n---response---\n");
  Serial.println(response);
  Serial.println("\n--\n");
  
  if(response[1] == '1')
  {
    digitalWrite(RelayPin3,HIGH);
  }
  
  if(response[1] == '0')
  {
    digitalWrite(RelayPin3,LOW);
  }
 
}

void loop() {
  t.update();
  int c;
  while (wifly.available()) {
    c = wifly.read();
    if (c > 0) {
      Serial.write((char)c);
    }
  }
  
  while (Serial.available()) {
    c = Serial.read();
    if (c >= 0) {
      wifly.write((char)c);
    }
  }
}

GITHUB Repo : iOS XCode Project

https://github.com/giridharmb/HomeController-iPhoneArduino.git