// this method makes a HTTP connection to the server:
void sendData(int device_id,int sensor_id,int thisData) {
// if there's a successful connection:
if (wifi.ipConfig(TCP,server, 80)) {
DebugSerial.println("connecting...");
// send the HTTP PUT request:
String cmd;
cmd = "POST /v1.0/device/";
cmd += String(device_id);
cmd += "/sensor/";
cmd += String(sensor_id);
cmd += "/datapoints";
cmd += " HTTP/1.1\r\n";
cmd += "Host: api.yeelink.net\r\n";
cmd += "Accept: *";
cmd += "/";
cmd += "*\r\n";
cmd += "U-ApiKey: ";
cmd += APIKEY;
cmd += "\r\n";
cmd += "Content-Length: ";
int thisLength = 10 + getLength(thisData);
cmd += String(thisLength);
cmd += "\r\n";
cmd += "Content-Type: application/x-www-form-urlencoded\r\n";
cmd += "Connection: close\r\n";
cmd += "\r\n";
cmd += "{\"value\":";
cmd += String(thisData);
cmd += "}\r\n";
DebugSerial.println(cmd);
wifi.Send(cmd);
// note the time that the connection was made:
lastConnectionTime = millis();
}
else {
// if you couldn't make a connection:
DebugSerial.println("connection failed");
DebugSerial.println("disconnecting.");
wifi.closeMux();
}
}
int getLength(int someValue) {
// there's at least one byte:
int digits = 1;
// continually divide the value by ten,
// adding one to the digit count for each
// time you divide, until you're at 0:
int dividend = someValue /10;
while (dividend > 0) {
dividend = dividend /10;
digits++;
}
// return the number of digits:
return digits;
}
int dht11_read(int pin)
{
// BUFFER TO RECEIVE
int bits[5];
int cnt = 7;
int idx = 0;
// EMPTY BUFFER
for (int i=0; i< 5; i++)
{bits= 0;}
// REQUEST SAMPLE
pinMode(pin, OUTPUT);
digitalWrite(pin, LOW);
delay(18);
digitalWrite(pin, HIGH);
delayMicroseconds(40);
pinMode(pin, INPUT);
// ACKNOWLEDGE or TIMEOUT
unsigned int loopCnt = 10000;
while(digitalRead(pin) == LOW)
if (loopCnt-- == 0) return -2;
loopCnt = 10000;
while(digitalRead(pin) == HIGH)
if (loopCnt-- == 0) return -2;
// READ OUTPUT - 40 BITS => 5 BYTES or TIMEOUT
for (int i=0; i<40; i++)
{
loopCnt = 10000;
while(digitalRead(pin) == LOW)
if (loopCnt-- == 0) return -2;
unsigned long t = micros();
loopCnt = 10000;
while(digitalRead(pin) == HIGH)
if (loopCnt-- == 0) return -2;
if ((micros() - t) > 40) bits[idx] |= (1 << cnt);
if (cnt == 0) // next byte?
{
cnt = 7; // restart at MSB
idx++; // next byte!
}
else cnt--;
}
// WRITE TO RIGHT VARS
// as bits[1] and bits[3] are allways zero they are omitted in formulas.
humidity = bits[0];
temperature = bits[2];
int sum = bits[0] + bits[2];
if (bits[4] != sum) return -1;
return 0;
}
|