#include "Ultrasonic.h"                     //초음파센서 외부라이브러리
#include <LiquidCrystal.h>               //LCD 라이브러리
//#include <SoftwareSerial.h>           //블루투스 라이브러리

//와이파이 라이브러리
#include <SPI.h>
#include <WiFi.h>
//#include <Ethernet.h> //이더넷 라이브러리 - 사용하지않음



// SoftwareSerial(RX, TX) 블루투스 핀번호 지정
//SoftwareSerial BTSerial(9, 10);

LiquidCrystal lcd(0, 1, 2, 3, 4, 5);     // LCD 핀번호 지정 BS E D4 D5 D6 D7

Ultrasonic ultrasonic(7,6);                // 초음파센서 핀번호 지정 Tring,Echo

// 데이터를 수신 받을 버퍼
byte buffer[1024];
int bufferPosition;
//--------------------------------------------------------------
int DHpin = 8;                             //습온도센서 핀번호 지정
byte dat [5];
byte read_data () {
  byte data;
  for (int i = 0; i < 8; i ++) {
    if (digitalRead (DHpin) == LOW) {
      while (digitalRead (DHpin) == LOW); // wait for 50us
      delayMicroseconds (30); // determine the duration of the high level to determine the data is '0 'or '1'
      if (digitalRead (DHpin) == HIGH)
        data |= (1 << (7-i)); // high front and low in the post
      while (digitalRead (DHpin) == HIGH); // data '1 ', wait for the next one receiver
     }
  }
return data;
}

//습온도센서 함수
void start_test () {
  digitalWrite (DHpin, LOW); // bus down, send start signal
  delay (30); // delay greater than 18ms, so DHT11 start signal can be detected
 
  digitalWrite (DHpin, HIGH);
  delayMicroseconds (40); // Wait for DHT11 response
 
  pinMode (DHpin, INPUT);
  while (digitalRead (DHpin) == HIGH);
  delayMicroseconds (80); // DHT11 response, pulled the bus 80us
  if (digitalRead (DHpin) == LOW);
  delayMicroseconds (80); // DHT11 80us after the bus pulled to start sending data
 
  for (int i = 0; i < 4; i ++) // receive temperature and humidity data, the parity bit is not considered
    dat[i] = read_data ();
 
  pinMode (DHpin, OUTPUT);
  digitalWrite (DHpin, HIGH); // send data once after releasing the bus, wait for the host to open the next Start signal
}

//-----------------------------------------------

char ssid[] = "솔라씨";      //  연결되는 와이파이 SSID
char pass[] = "01094062682";   // 네트워크 보안키

int status = WL_IDLE_STATUS;

WiFiServer server(80);  // 80  포트를 사용하는 웹서버 선언














void setup() {
  // LCD 초기화 (16 rows, 2 columns)
  lcd.begin(16, 2);
  Serial.begin(9600);
//  BTSerial.begin(9600);
 
  // 버퍼 위치 초기화
  bufferPosition = 0;
  pinMode (DHpin, OUTPUT);

//와이파이
 if (WiFi.status() == WL_NO_SHIELD) { // 현재 아두이노에 연결된 실드를 확인
    Serial.println("WiFi shield not present");
    while (true);  // 와이파이 실드가 아닐 경우 계속 대기ㅇㅇ
  }
 
  // 와이파이에 연결 시도
  while ( status != WL_CONNECTED) { //연결될 때까지 반복ㅇㅇ
    Serial.print("Attempting to connect to SSID: ");
    Serial.println(ssid);
    status = WiFi.begin(ssid, pass);  // WPA/WPA2 연결
  }//ㅇㅇ

  server.begin();

  printWifiStatus();  // 연결 성공시 연결된 네트워크 정보를 출력
}

//--------------------------------------------------------------
char Ldistance[4] = {0,};
 













void loop() {
  lcd.clear();
  // LCE에 표시되는 메시지
  lcd.print("Blueswa ;)");
  // Display Temperature in C
  // -----------------------------------------------------------
  lcd.setCursor(11, 0);
 

  start_test ();
  //lcd.print ("Current humdity ="); //습도 - 사용하지않음
  //lcd.print (dat [0], DEC); // display the humidity-bit integer 상수;
  //lcd.print ('.');
  //lcd.print (dat [1], DEC); // display the humidity decimal places 소수점;
  //lcd.println ('%');

 
  //lcd.print ("Current temperature ="); //온도
//  char a =dat [2];
  lcd.print(dat [2], DEC); // display the temperature of integer bits 상수;
  lcd.print('.');
  lcd.print(dat [3], DEC); // display the temperature of decimal places 소수점;
  lcd.print('C');
  //------------------------------------------------------------
 
  // 두번재 줄로 이동한다.
  lcd.setCursor(0, 1);

  lcd.print("Distance: ");
  // 거리를 측정한다.
  int b = ultrasonic.Ranging(CM);
  sprintf(Ldistance,"%03d",b); //초음파센서로 측정한 값을 Ldistance에 3자리로 저장한다
  lcd.print(Ldistance);
 
  lcd.print("cm");
 
  delay(500);
 
 
  WiFiClient client = server.available();  // 들어오는 클라이언트를 수신한다.
  if (client) {  // 클라이언트를 수신 시
    Serial.println("new client");  // 클라이언트 접속 확인 메시지 출력
    boolean currentLineIsBlank = true;

    while (client.connected ()) {
      if (client.available()) {
        char c = client.read();
        // 문자의 끝을 입력 받으면 http 요청이 종료되고, 답신을 보낼 수 있습니다.
        if (c == '\n' && currentLineIsBlank) {
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println("Connection: close");
          client.println("Refresh: 1"); // 1초당 페이지 refresh
          client.println();
          client.println("<!DOCTYPE HTML>");
          client.println("<meta charset=utf-8/>");
          client.print("<meta name=view content=width=device-width, ");
          client.println("initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no />");
          client.println("<html>");
          client.println("<head>"); 
          client.println("<title>Many Sensor</title>");
          client.println("</head>");
          client.println("<h1>Many Sensor</h1>");
          client.println("<div data-role=content>");
          client.print("DH Sensor value : ");
          client.println(dat [2], DEC);           // 온도 센서 값 출력,dec(십진수)
          client.println("<br>");
          client.println("<br>");
          client.print("UltraSonic Sensor value : ");
          client.println(Ldistance);              // 초음파 센서 값 출력
          client.println("<br>");
          client.println("</div>");
          client.println("</body>");
          client.println("</html>");
          break;
        }
        if (c == '\n') {
          currentLineIsBlank = true;
        }

        else if (c != '\r') {
          currentLineIsBlank = false;
        }
      }
    }
    delay(1);
    client.stop();
    Serial.println("client disonnected");
    // 클라이언트와 연결을 끊는다.
  }
 
















  // 블루투스로 데이터 수신-------------------------------------------
  int Temp = dat [2]; //온도
  int Distance = ultrasonic.Ranging(CM); //초음파센서
  char BTvalue[9] = {0,}; //전송문자열 정의
  sprintf(BTvalue,"%04d%04d",Temp,Distance); //문자열에 두측정값을 각 4자리로 순서대로 표기
//  BTSerial.print(BTvalue); //출력
 
}


void printWifiStatus() {  // 연결된 네트워크 정보 출력
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());
  // 네트워크 SSID 출력

  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);
  // 네트워크 ip 출력

  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
  // 수신 강도 출력
}