diff --git a/.gitignore b/.gitignore index 90bb5bf..d431066 100644 --- a/.gitignore +++ b/.gitignore @@ -7,11 +7,16 @@ ENV/ env.bak/ venv.bak/ -# Mac OS +# [Start mac OS git ignore] + +# mac OS *.idea/ *.DS_Store -##Flutter## +# [End mac OS git ignore] + +# [Start Flutter git ignore] + # Flutter/Dart/Pub related **/doc/api/ .dart_tool/ @@ -65,3 +70,25 @@ build/ !**/ios/**/default.pbxuser !**/ios/**/default.perspectivev3 !/packages/flutter_tools/test/data/dart_dependencies_test/**/.packages + +# [End Flutter git ignore] + +# [Start Go git ignore] + +# Binaries for programs and plugins +*.exe +*.exe~ +*.dll +*.so +*.dylib + +# Test binary, built with `go test -c` +*.test + +# Output of the go coverage tool, specifically when used with LiteIDE +*.out + +# Dependency directories (remove the comment below to include it) +# vendor/ + +# [End Go git ignore] diff --git a/README.md b/README.md deleted file mode 100644 index 351fe13..0000000 --- a/README.md +++ /dev/null @@ -1,4 +0,0 @@ -### Smart Farmer - -Internship at [CONCAT.Inc](https://concat.kr) in summer, 2020 - diff --git a/src/cloud/functions/smartfarm/crud.go b/src/cloud/functions/smartfarm/crud.go index 10485a8..27fbe7f 100644 --- a/src/cloud/functions/smartfarm/crud.go +++ b/src/cloud/functions/smartfarm/crud.go @@ -2,6 +2,7 @@ // and implements cloud functions for CRUD operations. package smartfarm +// [Start smart_farm_dependencies] import ( "context" "encoding/json" @@ -11,32 +12,60 @@ import ( "cloud.google.com/go/firestore" ) +// [End smart_farm_dependencies] + const projectID = "superfarmers" +// [Start smart_farm_insert] + // Insert inserts sensor data into Firestore. func Insert(writer http.ResponseWriter, req *http.Request) { ctx := context.Background() client, err := firestore.NewClient(ctx, projectID) - defer client.Close() if err != nil { fmt.Fprintf(writer, "firestore.NewClient: %v", err) return } + defer client.Close() var sensorData SensorData if err = json.NewDecoder(req.Body).Decode(&sensorData); err != nil { fmt.Fprintf(writer, "json.Decode: %v", err) return } + // update creation time of sensor data sensorData.setTime() + + // check whether sensor data is usual or not if err = sensorData.verify(); err != nil { fmt.Fprintf(writer, "verification failed: %v", err) return } + // store into collection if _, _, err = client.Collection("sensor_data").Add(ctx, sensorData); err != nil { fmt.Fprintf(writer, "insert: %v", err) return } } + +// [End smart_farm_insert] + +// [Start smart_farm_get] + +// Get gets documents from Firestore with given query. +func Get(writer http.ResponseWriter, req *http.Request) { + ctx := context.Background() + + client, err := firestore.NewClient(ctx, projectID) + if err != nil { + fmt.Fprintf(writer, "firestore.NewClient: %v", err) + return + } + defer client.Close() + + // TODO: define query format, get from collection +} + +// [End smart_farm_get] diff --git a/src/cloud/functions/smartfarm/data.go b/src/cloud/functions/smartfarm/data.go index df91883..1888cd7 100644 --- a/src/cloud/functions/smartfarm/data.go +++ b/src/cloud/functions/smartfarm/data.go @@ -4,6 +4,8 @@ package smartfarm import "time" +// [Start smart_farm_sensor_data_struct] + // SensorData represents a single document of smartfarm sensor data collection. type SensorData struct { UUID string `json:"uuid"` @@ -21,6 +23,8 @@ type SensorData struct { LocalTime time.Time `json:"local_time"` } +// [End smart_farm_sensor_data_struct] + // setTime sets the time of sensor data. func (s *SensorData) setTime() { s.LocalTime = time.Now() diff --git a/src/hardware/sensor_test/TDS.ino b/src/hardware/sensor_test/TDS.ino deleted file mode 100644 index c326182..0000000 --- a/src/hardware/sensor_test/TDS.ino +++ /dev/null @@ -1,101 +0,0 @@ -/*************************************************** - DFRobot Gravity: Analog TDS Sensor/Meter - - - *************************************************** - This sample code shows how to read the tds value and calibrate it with the standard buffer solution. - 707ppm(1413us/cm)@25^c standard buffer solution is recommended. - - Created 2018-1-3 - By Jason - - GNU Lesser General Public License. - See for details. - All above must be included in any redistribution. - ****************************************************/ - - /***********Notice and Trouble shooting*************** - 1. This code is tested on Arduino Uno with Arduino IDE 1.0.5 r2 and 1.8.2. - 2. Calibration CMD: - enter -> enter the calibration mode - cal:tds value -> calibrate with the known tds value(25^c). e.g.cal:707 - exit -> save the parameters and exit the calibration mode - ****************************************************/ - -#include -#include "GravityTDS.h" - -#define TdsSensorPin A1 -GravityTDS gravityTds; - -float temperature = 25,tdsValue = 0; - -void setup() -{ - Serial.begin(115200); - gravityTds.setPin(TdsSensorPin); - gravityTds.setAref(5.0); //reference voltage on ADC, default 5.0V on Arduino UNO - gravityTds.setAdcRange(1024); //1024 for 10bit ADC;4096 for 12bit ADC - gravityTds.begin(); //initialization -} - -void loop() -{ - //temperature = readTemperature(); //add your temperature sensor and read it - gravityTds.setTemperature(temperature); // set the temperature and execute temperature compensation - gravityTds.update(); //sample and calculate - tdsValue = gravityTds.getTdsValue(); // then get the value - Serial.print(tdsValue,0); - Serial.println("ppm"); - delay(1000); -}/*************************************************** - DFRobot Gravity: Analog TDS Sensor/Meter - - - *************************************************** - This sample code shows how to read the tds value and calibrate it with the standard buffer solution. - 707ppm(1413us/cm)@25^c standard buffer solution is recommended. - - Created 2018-1-3 - By Jason - - GNU Lesser General Public License. - See for details. - All above must be included in any redistribution. - ****************************************************/ - - /***********Notice and Trouble shooting*************** - 1. This code is tested on Arduino Uno with Arduino IDE 1.0.5 r2 and 1.8.2. - 2. Calibration CMD: - enter -> enter the calibration mode - cal:tds value -> calibrate with the known tds value(25^c). e.g.cal:707 - exit -> save the parameters and exit the calibration mode - ****************************************************/ - -#include -#include "GravityTDS.h" - -#define TdsSensorPin A1 -GravityTDS gravityTds; - -float temperature = 25,tdsValue = 0; - -void setup() -{ - Serial.begin(115200); - gravityTds.setPin(TdsSensorPin); - gravityTds.setAref(5.0); //reference voltage on ADC, default 5.0V on Arduino UNO - gravityTds.setAdcRange(1024); //1024 for 10bit ADC;4096 for 12bit ADC - gravityTds.begin(); //initialization -} - -void loop() -{ - //temperature = readTemperature(); //add your temperature sensor and read it - gravityTds.setTemperature(temperature); // set the temperature and execute temperature compensation - gravityTds.update(); //sample and calculate - tdsValue = gravityTds.getTdsValue(); // then get the value - Serial.print(tdsValue,0); - Serial.println("ppm"); - delay(1000); -} diff --git a/src/hardware/sensor_test/ec.ino b/src/hardware/sensor_test/ec.ino new file mode 100644 index 0000000..9cd6a63 --- /dev/null +++ b/src/hardware/sensor_test/ec.ino @@ -0,0 +1,30 @@ +#include +#include "GravityTDS.h" + +#define board_rate 115200 +#define ec_pin A1 + +GravityTDS gravityTds; + +float temperature = 25; +float tdsValue = 0; + +void setup() +{ + Serial.begin(board_rate); + gravityTds.setPin(ec_pin); + gravityTds.setAref(5.0); //reference voltage on ADC, default 5.0V on Arduino UNO + gravityTds.setAdcRange(1024); //1024 for 10bit ADC;4096 for 12bit ADC + gravityTds.begin(); //initialization +} + +void loop() +{ + //temperature = readTemperature(); //add your temperature sensor and read it + gravityTds.setTemperature(temperature); // set the temperature and execute temperature compensation + gravityTds.update(); //sample and calculate + tdsValue = gravityTds.getTdsValue(); // then get the value + Serial.print(tdsValue,0); + Serial.println("ppm"); + delay(1000); +} diff --git a/src/hardware/sensor_test/tempratureHumidity.ino b/src/hardware/sensor_test/humidity_temprature.ino similarity index 62% rename from src/hardware/sensor_test/tempratureHumidity.ino rename to src/hardware/sensor_test/humidity_temprature.ino index dd91e2e..684bc1f 100644 --- a/src/hardware/sensor_test/tempratureHumidity.ino +++ b/src/hardware/sensor_test/humidity_temprature.ino @@ -1,25 +1,27 @@ -#include #include -int pin=4; + +#define board_rate 115200 +#define temperature_humidity_pin 4 + DHT11 dht11(pin); + +float temperature; +float humidity; + void setup() { - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for Leonardo only - } + Serial.begin(board_rate); } void loop() { int err; - float temp, humi; if((err=dht11.read(humi, temp))==0) { Serial.print("temperature:"); - Serial.print(temp); + Serial.print(temperature); Serial.print(" humidity:"); - Serial.print(humi); + Serial.print(humidity); Serial.println(); } else diff --git a/src/hardware/sensor_test/level.ino b/src/hardware/sensor_test/level.ino deleted file mode 100644 index 942ab93..0000000 --- a/src/hardware/sensor_test/level.ino +++ /dev/null @@ -1,24 +0,0 @@ -/*************************************************** -* Liquid Level Sensor-FS-IR02 -* **************************************************** -* This example is to get liquid level - -* @author jackli(Jack.li@dfrobot.com) -* @version V1.0 -* @date 2016-1-30 - -* GNU Lesser General Public License. -* See for details. -* All above must be included in any redistribution -* ****************************************************/ -int Liquid_level=0; -void setup() { - Serial.begin(9600); - pinMode(5,INPUT); -} - -void loop() { -Liquid_level=digitalRead(5); -Serial.print("Liquid_level= ");Serial.println(Liquid_level,DEC); -delay(500); -} diff --git a/src/hardware/sensor_test/light.ino b/src/hardware/sensor_test/light.ino index c68934a..2d51458 100644 --- a/src/hardware/sensor_test/light.ino +++ b/src/hardware/sensor_test/light.ino @@ -1,13 +1,17 @@ -void setup(){ +#define board_rate 115200 +#define light_pin A0 - Serial.begin(9600); +int light +void setup(){ + Serial.begin(board_rate); } void loop(){ + int light = read_light(); + Serial.println(light); +} - int d = analogRead(A0); - - Serial.println(d); - +int read_light(){ + return analogRead(light_pin); } diff --git a/src/hardware/sensor_test/liquid_level.ino b/src/hardware/sensor_test/liquid_level.ino new file mode 100644 index 0000000..145387a --- /dev/null +++ b/src/hardware/sensor_test/liquid_level.ino @@ -0,0 +1,19 @@ +#define board_rate 115200 +#define liquid_level_pin 5 + +boolean liquid_level; + +void setup() { + Serial.begin(board_rate); + pinMode(liquid_level_pin, INPUT); +} + +void loop() { + liquid_level=read_liquid_level() + Serial.print("Liquid_level= ");Serial.println(liquid_level,DEC); + delay(500); +} + +boolean read_liquid_level(){ + return digitalRead(liquid_level_pin); +} diff --git a/src/hardware/sensor_test/liquid_temperature.ino b/src/hardware/sensor_test/liquid_temperature.ino new file mode 100644 index 0000000..8e5c55c --- /dev/null +++ b/src/hardware/sensor_test/liquid_temperature.ino @@ -0,0 +1,55 @@ +#include + +#define board_rate 115200 +#define liquid_temperature_pin 2 + +float liquid_temperature; + +OneWire ds(liquid_temperature_pin); //2번 핀과 연결되 OneWire 객체 생성 + +void setup(void) { + Serial.begin(board_rate); + delay(300); +} + +void loop(void) { + liquid_temperature = read_liquid_temperature(); //온도 측정 후 변수에 저장 + Serial.print("liquid_temperature: "); + Serial.println(liquid_temperature); //온도 LCD에 출력 + + delay(1000); //5초마다 측정 후 출력 + +} + +//온도 측정 후 반환하는 함수 +float read_liquid_temperature(){ + byte data[12]; + byte addr[8]; + if ( !ds.search(addr)) { + ds.reset_search(); + return -3000; + } + if ( OneWire::crc8( addr, 7) != addr[7]) { + Serial.println("CRC is not valid!"); + return -2000; + } + if ( addr[0] != 0x10 && addr[0] != 0x28) { + Serial.print("Device is not recognized"); + return -1000; + } + ds.reset(); + ds.select(addr); + ds.write(0x44,1); //변환 + byte present = ds.reset(); + ds.select(addr); + ds.write(0xBE); + for (int i = 0; i < 9; i++) { + data[i] = ds.read(); //Scratchpad 읽음 + } + ds.reset_search(); + byte MSB = data[1]; + byte LSB = data[0]; + float tempRead = ((MSB << 8) | LSB); + float TemperatureSum = tempRead / 16; + return TemperatureSum; +} diff --git a/src/hardware/sensor_test/ph.ino b/src/hardware/sensor_test/pH.ino similarity index 51% rename from src/hardware/sensor_test/ph.ino rename to src/hardware/sensor_test/pH.ino index 5e6a70d..1827c3a 100644 --- a/src/hardware/sensor_test/ph.ino +++ b/src/hardware/sensor_test/pH.ino @@ -1,22 +1,13 @@ -/* - # This sample code is used to test the pH meter Pro V1.0. - # Editor : YouYou - # Ver : 1.0 - # Product: analog pH meter Pro - # SKU : SEN0169 -*/ -#define SensorPin A0 //pH meter Analog output to Arduino Analog Input 0 -#define Offset -3.70 //deviation compensate -#define LED 13 -#define samplingInterval 20 -#define printInterval 800 -#define ArrayLenth 40 //times of collection -int pHArray[ArrayLenth]; //Store the average value of the sensor feedback +#define board_rate 115200 +#define pH_pin A1 //pH meter Analog output to Arduino Analog Input 0 +#define pH_Offset -3.70 //deviation compensate + +int pHArray[40]; //Store the average value of the sensor feedback int pHArrayIndex=0; + void setup(void) { - pinMode(LED,OUTPUT); - Serial.begin(9600); + Serial.begin(board_rate); Serial.println("pH meter experiment!"); //Test the serial monitor } void loop(void) @@ -24,22 +15,21 @@ void loop(void) static unsigned long samplingTime = millis(); static unsigned long printTime = millis(); static float pHValue,voltage; - if(millis()-samplingTime > samplingInterval) + if(millis()-samplingTime > 20) { - pHArray[pHArrayIndex++]=analogRead(SensorPin); - if(pHArrayIndex==ArrayLenth)pHArrayIndex=0; - voltage = avergearray(pHArray, ArrayLenth)*5.0/1024; - pHValue = 12.5*voltage+Offset; - samplingTime=millis(); + pHArray[pHArrayIndex++]=analogRead(pH_pin); + if(pHArrayIndex==40)pHArrayIndex=0; + voltage = avergearray(pHArray, 40)*5.0/1024; + pHValue = 12.5*voltage+pH_Offset; + samplingTime=millis(); } - if(millis() - printTime > printInterval) //Every 800 milliseconds, print a numerical, convert the state of the LED indicator + if(millis() - printTime > 800) //Every 800 milliseconds, print a numerical { Serial.print("Voltage:"); - Serial.print(voltage,2); - Serial.print(" pH value: "); + Serial.print(voltage,2); + Serial.print(" pH value: "); Serial.println(pHValue,2); - digitalWrite(LED,digitalRead(LED)^1); - printTime=millis(); + printTime=millis(); } } double avergearray(int* arr, int number){ @@ -57,7 +47,8 @@ double avergearray(int* arr, int number){ } avg = amount/number; return avg; - }else{ + } + else{ if(arr[0] - -int DS18S20_Pin = 2; //온도센서와 연결 - -OneWire ds(DS18S20_Pin); //2번 핀과 연결되 OneWire 객체 생성 - -void setup(void) { - Serial.begin(9600); - delay(300); -} - -void loop(void) { - float temperature = getTemp(); //온도 측정 후 변수에 저장 - Serial.print("tmp: "); - Serial.println(temperature); //온도 LCD에 출력 - - delay(1000); //5초마다 측정 후 출력 - -} - -//온도 측정 후 반환하는 함수 -float getTemp(){ - - byte data[12]; - byte addr[8]; - - if ( !ds.search(addr)) { - ds.reset_search(); - return -3000; - } - - if ( OneWire::crc8( addr, 7) != addr[7]) { - Serial.println("CRC is not valid!"); - return -2000; - } - - if ( addr[0] != 0x10 && addr[0] != 0x28) { - Serial.print("Device is not recognized"); - return -1000; - } - - ds.reset(); - ds.select(addr); - ds.write(0x44,1); //변환 - - byte present = ds.reset(); - ds.select(addr); - ds.write(0xBE); - - - for (int i = 0; i < 9; i++) { - data[i] = ds.read(); //Scratchpad 읽음 - } - - ds.reset_search(); - - byte MSB = data[1]; - byte LSB = data[0]; - - float tempRead = ((MSB << 8) | LSB); - float TemperatureSum = tempRead / 16; - - return TemperatureSum; - -} diff --git a/src/hardware/smart_farm_sensor/smart_farm_sensor.ino b/src/hardware/smart_farm_sensor/smart_farm_sensor.ino new file mode 100644 index 0000000..3b9f7d0 --- /dev/null +++ b/src/hardware/smart_farm_sensor/smart_farm_sensor.ino @@ -0,0 +1,325 @@ +#include +#include +#include +#include +#include +#include +#include "GravityTDS.h" +#include + +#define board_rate 115200 + +#define liquid_temperature_pin 20 +#define humidity_temperature_pin 2 +#define pH_pin A15 +#define ec_pin A14 +#define liquid_level_pin 45 +#define light_pin A0 +#define fan_pin 26 +#define led_pin 46 + +#define pH_Offset 0.00 + +//#define PATH "in" // 테스트용 +#define PATH "Insert" + +#define get_rate 3000 // 3sec +#define post_rate 180000 // 3min + +DHT11 dht11(humidity_temperature_pin); +OneWire ds(liquid_temperature_pin); +DallasTemperature sensors(&ds); +GravityTDS gravityTds; + +// ethernet interface mac address, must be unique on the LAN +byte mymac[] = { 0x74, 0x69, 0x69, 0x2D, 0x30, 0x31 }; + +//const char website[] PROGMEM = "ec2-13-125-23-94.ap-northeast-2.compute.amazonaws.com"; // 테스트용 +const char website[] PROGMEM = "asia-northeast1-superfarmers.cloudfunctions.net"; + +// POST request 변수 +String uuid; +float liquid_temperature; +float temperature; +float humidity; +float liquid_flow_rate = 25.5; +float pH; +float ec; +int light; +boolean liquid_level; +boolean valve = 0; +boolean led = 0; +boolean fan; + +// GET request 변수 +char query_string[80] = "RecentStatus?uuid="; +char char_uuid[20]; + +byte Ethernet::buffer[700]; +uint32_t post_timer = 0; +uint32_t get_timer = 0; +int pHArray[40]; +int pHArrayIndex = 0; + +Stash stash; + +static void my_callback (byte status, word off, word len) { + Ethernet::buffer[off + 1000] = 0; + String fullres = (const char*) Ethernet::buffer + off; + fullres = fullres.substring(fullres.indexOf("{"), fullres.indexOf("}") + 1); + + const size_t capacity = JSON_OBJECT_SIZE(3) + 20; + DynamicJsonDocument doc(capacity); + deserializeJson(doc, fullres); + valve = doc["velve"]; + led = doc["led"]; + fan = doc["fan"]; + + //벨브, led, 펜 조정하는 부분 + //digitalWrite하자 + // if (valve == false) { + // digitalWrite(valve_pin, LOW); + // } + // else { + // digitalWrite(valve_pin, HIGH); + // } + // + if (led == false) { + digitalWrite(led_pin, LOW); + } + else { + digitalWrite(led_pin, HIGH); + } + + if (fan == false) { + digitalWrite(fan_pin, LOW); + } + else { + digitalWrite(fan_pin, HIGH); + } +} + + +void read_uuid() { + for (size_t i = 0; i < 8; i++) + { + if (UniqueID8[i] < 0x10) + uuid += "0"; + uuid += String(UniqueID8[i], HEX); + } +} + + +int read_light() { + return analogRead(light_pin); +} + + +void read_humidity_and_temperature() { + dht11.read(humidity, temperature); +} + + +boolean read_liquid_level() { + return digitalRead(liquid_level_pin); +} + + +float read_liquid_temperature() { + float tempC; + sensors.requestTemperatures(); + tempC = sensors.getTempCByIndex(0); + tempC = round(tempC * 10) / 10.0; + return tempC; +} + + +float read_ec() { + float tdsValue; + gravityTds.setTemperature(liquid_temperature); // set the temperature and execute temperature compensation + gravityTds.update(); //sample and calculate + tdsValue = gravityTds.getTdsValue(); // then get the value + tdsValue = round(tdsValue) / 500; + tdsValue = round(tdsValue * 10) / 10.0; + return tdsValue; +} + +//pH측정을 위한 함수 +double avergearray(int* arr, int number) { + int i; + int max, min; + double avg; + long amount = 0; + if (number <= 0) { + Serial.println("Error number for the array to avraging!/n"); + return 0; + } + if (number < 5) { //less than 5, calculated directly statistics + for (i = 0; i < number; i++) { + amount += arr[i]; + } + avg = amount / number; + return avg; + } + else { + if (arr[0] < arr[1]) { + min = arr[0]; max = arr[1]; + } + else { + min = arr[1]; max = arr[0]; + } + for (i = 2; i < number; i++) { + if (arr[i] < min) { + amount += min; //arr max) { + amount += max; //arr>max + max = arr[i]; + } else { + amount += arr[i]; //min<=arr<=max + } + } + } + avg = (double)amount / (number - 2); + } + return avg; +} + + +float read_pH() { + static unsigned long samplingTime = millis(); + static unsigned long printTime = millis(); + static float pHValue, voltage; + if (millis() - samplingTime > 20) + { + pHArray[pHArrayIndex++] = analogRead(pH_pin); + if (pHArrayIndex == 40)pHArrayIndex = 0; + voltage = avergearray(pHArray, 40) * 5.0 / 1024; + pHValue = 3.5 * voltage + pH_Offset; + samplingTime = millis(); + } + return round(pHValue * 10) / 10.0; +} + + +void setup () { + // 시리얼 통신 셋팅 + Serial.begin(board_rate); + + // 네트워크 셋팅 + Serial.println("\n[Smart Farm]"); + if (ether.begin(sizeof Ethernet::buffer, mymac, 53) == 0) + Serial.println( "Failed to access Ethernet controller"); + if (!ether.dhcpSetup()) + Serial.println("DHCP failed"); + ether.printIp("IP: ", ether.myip); + ether.printIp("GW: ", ether.gwip); + ether.printIp("DNS: ", ether.dnsip); + if (!ether.dnsLookup(website)) + Serial.println("DNS failed"); + ether.printIp("SRV: ", ether.hisip); + + // 핀 설정 + // 수위 + pinMode(liquid_level_pin, INPUT); + + // ec + gravityTds.setPin(ec_pin); + gravityTds.setAref(5.0); //reference voltage on ADC, default 5.0V on Arduino UNO + gravityTds.setAdcRange(1024); //1024 for 10bit ADC;4096 for 12bit ADC + gravityTds.begin(); //initialization + + // fan + pinMode(fan_pin, OUTPUT); + digitalWrite(fan_pin, HIGH); + + // led + pinMode(led_pin, OUTPUT); + digitalWrite(led_pin, HIGH); + + // read_uuid + read_uuid(); + + // query string + strcpy(char_uuid, uuid.c_str()); + strcat(query_string, char_uuid); +} + + +void loop () { + ether.packetLoop(ether.packetReceive()); + // 테스트용 포트번호 + // ether.hisport = 5000; + + // pH + pH = read_pH(); + + if (get_timer == post_timer) { + post_timer += 1000; + } + + if (millis() > get_timer) { + get_timer = millis() + get_rate; + ether.browseUrl(PSTR("/"), query_string, website, my_callback); + } + + if (millis() > post_timer) { + post_timer = millis() + post_rate; + + // liquid_temperature + liquid_temperature = read_liquid_temperature(); + + // humidity_and_temperature + read_humidity_and_temperature(); + temperature = round(temperature * 10) / 10.0; + + // ec + ec = read_ec(); + + // liquid_level + liquid_level = read_liquid_level(); + + // light + light = read_light(); + light = map(light, 0, 1023, 0, 100); + + // json create + byte sd = stash.create(); + char jsondata[250]; + const size_t capacity = JSON_OBJECT_SIZE(12) + 50; + DynamicJsonDocument doc(capacity); + doc["uuid"] = uuid; + doc["liquid_temperature"] = liquid_temperature; + doc["temperature"] = temperature; + doc["humidity"] = humidity; + doc["liquid_flow_rate"] = liquid_flow_rate; + doc["pH"] = pH; + doc["ec"] = ec; + doc["light"] = light; + doc["liquid_level"] = liquid_level; + doc["valve"] = valve; + doc["led"] = led; + doc["fan"] = fan; + + serializeJson(doc, jsondata, sizeof(jsondata)); + Serial.print("sizeof(jsondata) : "); + Serial.println(sizeof(jsondata)); + Serial.println(jsondata); + stash.print(jsondata); + stash.save(); + + // generate the header with payload - note that the stash size is used, + // and that a "stash descriptor" is passed in as argument using "$H" + // send post json + Stash::prepare(PSTR("POST http://$F/$F HTTP/1.1" "\r\n" + "Host: $F" "\r\n" + "Content-Length: $D" "\r\n" + "Content-Type: application/json" "\r\n" + "\r\n" + "$H"), + website, PSTR(PATH), website, stash.size(), sd); + // send the packet - this also releases all stash buffers once done + ether.tcpSend(); + } +} diff --git a/src/hardware/test/Combination.ino b/src/hardware/test/Combination.ino new file mode 100644 index 0000000..90c45d1 --- /dev/null +++ b/src/hardware/test/Combination.ino @@ -0,0 +1,171 @@ +#include +#include +#include +#include + +// your variable +#define board_rate 115200 +#define liquid_temperature_pin 2 +#define liquid_level_pin 5 + +DHT11 dht11(4); +OneWire ds(liquid_temperature_pin); //2번 핀과 연결되 OneWire 객체 생성 + +#define PATH "in" +// ethernet interface mac address, must be unique on the LAN +byte mymac[] = { 0x74,0x69,0x69,0x2D,0x30,0x31 }; + +const char website[] PROGMEM = "ec2-13-125-23-94.ap-northeast-2.compute.amazonaws.com"; + +String uuid = "57 39 39 31 34 31 10 15 0E"; +float liquid_temperature; +float temperature; +float humidity; +float liquid_flow_rate = 25.51; +float ph = 7.1; +float ec = 0.12; +int light; +boolean liquid_level; +boolean valve = 0; +boolean led = 0; +boolean fan = 0; + +byte Ethernet::buffer[500]; +uint32_t timer; +Stash stash; + +void setup () { + //시리얼 통신 셋팅 + Serial.begin(board_rate); + + //핀 설정 + //수위센서 + pinMode(liquid_level_pin, INPUT); + + //네트워크 셋팅 + Serial.println("\n[webClient]"); + if (ether.begin(sizeof Ethernet::buffer, mymac) == 0) + Serial.println( "Failed to access Ethernet controller"); + if (!ether.dhcpSetup()) + Serial.println("DHCP failed"); + ether.printIp("IP: ", ether.myip); + ether.printIp("GW: ", ether.gwip); + ether.printIp("DNS: ", ether.dnsip); + if (!ether.dnsLookup(website)) + Serial.println("DNS failed"); + ether.printIp("SRV: ", ether.hisip); + +} + +void loop () { + + //read_Humidity_and_Temperature(); + + //Serial.println(humidity); + //Serial.println(temperature); + + + ether.packetLoop(ether.packetReceive()); + if (millis() > timer) { + timer = millis() + 5000; + Serial.println(); + Serial.println("<<< REQ "); + + liquid_temperature = round(read_liquid_temperature()*100)/100.00; + light = read_light(); + dht11.read(humidity, temperature); + liquid_level = read_liquid_level(); + + //포트번호 + ether.hisport = 5000; + byte sd = stash.create(); + String jsondata = ""; + StaticJsonBuffer<170> jb; + //DynamicJsonBuffer jb; + JsonObject& obj = jb.createObject(); + + obj["uuid"] = uuid; + obj["liquid_temperature"] = liquid_temperature; + obj["temperature"] = temperature; + obj["humidity"] = humidity; + obj["liquid_flow_rate"] = liquid_flow_rate; + obj["ph"] = ph; + obj["ec"] = ec; + obj["light"] = light; + obj["liquid_level"] = liquid_level; + obj["valve"] = valve; + obj["led"] = led; + obj["fan"] = fan; + + + obj.printTo(jsondata); + Serial.println(jsondata); + stash.print(jsondata); + //stash.print("light="); + //stash.print(light); + //stash.print("&humidity="); + //stash.print(humidity); + //stash.print("&temperature="); + //stash.print(temperature); + int stash_size = stash.size(); + Serial.println(stash_size); + stash.save(); + + // generate the header with payload - note that the stash size is used, + // and that a "stash descriptor" is passed in as argument using "$H" + Stash::prepare(PSTR("POST https://$F/$F HTTP/1.1" "\r\n" + "Host: $F" "\r\n" + "Content-Length: $D" "\r\n" + "Content-Type: application/json" "\r\n" + "\r\n" + "$H"), + website, PSTR(PATH), website, stash_size, sd); + // send the packet - this also releases all stash buffers once done + ether.tcpSend(); + } +} + +int read_light(){ + return analogRead(A0); +} + +void read_Humidity_and_Temperature(){ + dht11.read(humidity, temperature); +} + +boolean read_liquid_level(){ + return digitalRead(liquid_level_pin); +} + +//온도 측정 후 반환하는 함수 +float read_liquid_temperature(){ + byte data[12]; + byte addr[8]; + if ( !ds.search(addr)) { + ds.reset_search(); + return -3000; + } + if ( OneWire::crc8( addr, 7) != addr[7]) { + Serial.println("CRC is not valid!"); + return -2000; + } + if ( addr[0] != 0x10 && addr[0] != 0x28) { + Serial.print("Device is not recognized"); + return -1000; + } + ds.reset(); + ds.select(addr); + ds.write(0x44,1); //변환 + byte present = ds.reset(); + ds.select(addr); + ds.write(0xBE); + for (int i = 0; i < 9; i++) { + data[i] = ds.read(); //Scratchpad 읽음 + } + ds.reset_search(); + byte MSB = data[1]; + byte LSB = data[0]; + float tempRead = ((MSB << 8) | LSB); + float TemperatureSum = tempRead / 16; + return TemperatureSum; +}