choongman kim
/
21300206kimchoongmanhw3
21300206kimchoongmanhw3
Fork of coap-example by
Revision 1:72dca6351fc1, committed 2018-01-02
- Comitter:
- trnoo
- Date:
- Tue Jan 02 14:27:09 2018 +0000
- Parent:
- 0:0681e205d0e9
- Commit message:
- 21300206 KimChoongMan
Changed in this revision
--- a/mbed_app.json Wed Feb 15 21:18:58 2017 +0100 +++ b/mbed_app.json Tue Jan 02 14:27:09 2018 +0000 @@ -2,7 +2,7 @@ "config": { "network-interface":{ "help": "options are ETHERNET, WIFI_ESP8266, WIFI_ODIN, MESH_LOWPAN_ND, MESH_THREAD", - "value": "ETHERNET" + "value": "WIFI_ESP8266" }, "mesh_radio_type": { "help": "options are ATMEL, MCR20", @@ -10,20 +10,20 @@ }, "esp8266-tx": { "help": "Pin used as TX (connects to ESP8266 RX)", - "value": "D1" + "value": "D8" }, "esp8266-rx": { "help": "Pin used as RX (connects to ESP8266 TX)", - "value": "D0" + "value": "D2" }, "esp8266-debug": { "value": true }, "wifi-ssid": { - "value": "\"SSID\"" + "value": "\"netlab2\"" }, "wifi-password": { - "value": "\"Password\"" + "value": "\"netlab2@414\"" }, "button": { "help": "Pin which you'll use as button (can be overriden per target below)",
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/source/DHT.cpp Tue Jan 02 14:27:09 2018 +0000 @@ -0,0 +1,226 @@ +/* + * DHT Library for Digital-output Humidity and Temperature sensors + * + * Works with DHT11, DHT22 + * SEN11301P, Grove - Temperature&Humidity Sensor (Seeed Studio) + * SEN51035P, Grove - Temperature&Humidity Sensor Pro (Seeed Studio) + * AM2302 , temperature-humidity sensor + * HM2303 , Digital-output humidity and temperature sensor + * + * Copyright (C) Wim De Roeve + * based on DHT22 sensor library by HO WING KIT + * Arduino DHT11 library + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documnetation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS OR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "DHT.h" + +#define DHT_DATA_BIT_COUNT 40 + +DHT::DHT(PinName pin, eType DHTtype) +{ + _pin = pin; + _DHTtype = DHTtype; + _firsttime = true; +} + +DHT::~DHT() +{ + +} + +eError DHT::stall(DigitalInOut &io, int const level, int const max_time) +{ + int cnt = 0; + while (level == io) { + if (cnt > max_time) { + return ERROR_NO_PATIENCE; + } + cnt++; + wait_us(1); + } + return ERROR_NONE; +} + +eError DHT::readData() +{ + uint8_t i = 0, j = 0, b = 0, data_valid = 0; + uint32_t bit_value[DHT_DATA_BIT_COUNT] = {0}; + + eError err = ERROR_NONE; + time_t currentTime = time(NULL); + + DigitalInOut DHT_io(_pin); + + // IO must be in hi state to start + if (ERROR_NONE != stall(DHT_io, 0, 250)) { + return BUS_BUSY; + } + + // start the transfer + DHT_io.output(); + DHT_io = 0; + // only 500uS for DHT22 but 18ms for DHT11 + (_DHTtype == 11) ? wait_ms(18) : wait(0.0005); + DHT_io = 1; + wait_us(30); + DHT_io.input(); + // wait till the sensor grabs the bus + if (ERROR_NONE != stall(DHT_io, 1, 40)) { + return ERROR_NOT_PRESENT; + } + // sensor should signal low 80us and then hi 80us + if (ERROR_NONE != stall(DHT_io, 0, 100)) { + return ERROR_SYNC_TIMEOUT; + } + if (ERROR_NONE != stall(DHT_io, 1, 100)) { + return ERROR_NO_PATIENCE; + } + // capture the data + for (i = 0; i < 5; i++) { + for (j = 0; j < 8; j++) { + if (ERROR_NONE != stall(DHT_io, 0, 75)) { + return ERROR_DATA_TIMEOUT; + } + // logic 0 is 28us max, 1 is 70us + wait_us(40); + bit_value[i*8+j] = DHT_io; + if (ERROR_NONE != stall(DHT_io, 1, 50)) { + return ERROR_DATA_TIMEOUT; + } + } + } + // store the data + for (i = 0; i < 5; i++) { + b=0; + for (j=0; j<8; j++) { + if (bit_value[i*8+j] == 1) { + b |= (1 << (7-j)); + } + } + DHT_data[i]=b; + } + + // uncomment to see the checksum error if it exists + //printf(" 0x%02x + 0x%02x + 0x%02x + 0x%02x = 0x%02x \n", DHT_data[0], DHT_data[1], DHT_data[2], DHT_data[3], DHT_data[4]); + data_valid = DHT_data[0] + DHT_data[1] + DHT_data[2] + DHT_data[3]; + if (DHT_data[4] == data_valid) { + _lastReadTime = currentTime; + _lastTemperature = CalcTemperature(); + _lastHumidity = CalcHumidity(); + + } else { + err = ERROR_CHECKSUM; + } + + return err; + +} + +float DHT::CalcTemperature() +{ + float v; + + switch (_DHTtype) { + case DHT11: + v = DHT_data[2]; + return float(v); + case DHT22: + v = DHT_data[2] & 0x7F; + v *= 256; + v += DHT_data[3]; + v /= 10; + if (DHT_data[2] & 0x80) + v *= -1; + return float(v); + } + return 0; +} + +float DHT::ReadHumidity() +{ + return _lastHumidity+30; +} + +float DHT::ConvertCelciustoFarenheit(float const celsius) +{ + return celsius * 9 / 5 + 32; +} + +float DHT::ConvertCelciustoKelvin(float const celsius) +{ + return celsius + 273.15; +} + +// dewPoint function NOAA +// reference: http://wahiduddin.net/calc/density_algorithms.htm +float DHT::CalcdewPoint(float const celsius, float const humidity) +{ + float A0= 373.15/(273.15 + celsius); + float SUM = -7.90298 * (A0-1); + SUM += 5.02808 * log10(A0); + SUM += -1.3816e-7 * (pow(10, (11.344*(1-1/A0)))-1) ; + SUM += 8.1328e-3 * (pow(10,(-3.49149*(A0-1)))-1) ; + SUM += log10(1013.246); + float VP = pow(10, SUM-3) * (humidity); + float T = log(VP/0.61078); // temp var + return (241.88 * T) / (17.558-T); +} + +// delta max = 0.6544 wrt dewPoint() +// 5x faster than dewPoint() +// reference: http://en.wikipedia.org/wiki/Dew_point +/*float DHT::CalcdewPointFast(float const celsius, float const humidity) +{ + float a = 17.271; + float b = 237.7; + float temp = (a * celsius) / (b + celsius) + log(humidity/100); + float Td = (b * temp) / (a - temp); + return Td; +}*/ + +float DHT::ReadTemperature(eScale Scale) +{ + if (Scale == FARENHEIT) + return ConvertCelciustoFarenheit(_lastTemperature); + else if (Scale == KELVIN) + return ConvertCelciustoKelvin(_lastTemperature); + else + return _lastTemperature; +} + +float DHT::CalcHumidity() +{ + float v; + + switch (_DHTtype) { + case DHT11: + v = DHT_data[0]; + return float(v); + case DHT22: + v = DHT_data[0]; + v *= 256; + v += DHT_data[1]; + v /= 10; + return float(v); + } + return 0; +} +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/source/DHT.h Tue Jan 02 14:27:09 2018 +0000 @@ -0,0 +1,99 @@ +/* + * DHT Library for Digital-output Humidity and Temperature sensors + * + * Works with DHT11, DHT21, DHT22 + * SEN11301P, Grove - Temperature&Humidity Sensor (Seeed Studio) + * SEN51035P, Grove - Temperature&Humidity Sensor Pro (Seeed Studio) + * AM2302 , temperature-humidity sensor + * RHT01,RHT02, RHT03 , Humidity and Temperature Sensor (Sparkfun) + * + * Copyright (C) Wim De Roeve + * based on DHT22 sensor library by HO WING KIT + * Arduino DHT11 library + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documnetation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS OR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#ifndef MBED_DHT_H +#define MBED_DHT_H + +#include "mbed.h" + +typedef enum eType eType; +enum eType { + DHT11 = 11, + SEN11301P = 11, + RHT01 = 11, + DHT22 = 22, + AM2302 = 22, + SEN51035P = 22, + RHT02 = 22, + RHT03 = 22 +}; + +typedef enum eError eError; +enum eError { + ERROR_NONE = 0, + BUS_BUSY, + ERROR_NOT_PRESENT, + ERROR_ACK_TOO_LONG, + ERROR_SYNC_TIMEOUT, + ERROR_DATA_TIMEOUT, + ERROR_CHECKSUM, + ERROR_NO_PATIENCE +}; + +typedef enum eScale eScale; +enum eScale { + CELCIUS = 0, + FARENHEIT, + KELVIN +}; + + +class DHT +{ + +public: + + DHT(PinName pin, eType DHTtype); + ~DHT(); + eError readData(void); + float ReadHumidity(void); + float ReadTemperature(eScale const Scale); + float CalcdewPoint(float const celsius, float const humidity); + float CalcdewPointFast(float const celsius, float const humidity); + +private: + time_t _lastReadTime; + float _lastTemperature; + float _lastHumidity; + PinName _pin; + bool _firsttime; + eType _DHTtype; + uint8_t DHT_data[5]; + float CalcTemperature(); + float CalcHumidity(); + float ConvertCelciustoFarenheit(float const); + float ConvertCelciustoKelvin(float const); + eError stall(DigitalInOut &io, int const level, int const max_time); + +}; + +#endif
--- a/source/main.cpp Wed Feb 15 21:18:58 2017 +0100 +++ b/source/main.cpp Tue Jan 02 14:27:09 2018 +0000 @@ -1,136 +1,86 @@ -/* - * PackageLicenseDeclared: Apache-2.0 - * Copyright (c) 2017 ARM Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include <string> +#include <string.h> #include "mbed.h" #include "easy-connect.h" -#include "sn_nsdl.h" -#include "sn_coap_protocol.h" -#include "sn_coap_header.h" +#include "TCPSocket.h" +#include "DHT.h" -UDPSocket socket; // Socket to talk CoAP over -Thread recvfromThread; // Thread to receive messages over CoAP +DHT sensor(A0,DHT22); -struct coap_s* coapHandle; -coap_version_e coapVersion = COAP_VERSION_1; +#define SERVER_IP "192.168.0.7" +#define SERVER_PORT 50000 -// CoAP HAL -void* coap_malloc(uint16_t size) { - return malloc(size); -} +Serial pc(USBTX, USBRX); // computer to mbed boardSerial esp(D1, D0); + +//void http_demo(NetworkInterface *net) { TCPSocket socket; // for HTTP +//pc.printf("Sending HTTP request to %s : %d ...\r\n", SERVER_IP, SERVER_PORT); -void coap_free(void* addr) { - free(addr); -} + +char rbuffer[20]; -// tx_cb and rx_cb are not used in this program -uint8_t coap_tx_cb(uint8_t *a, uint16_t b, sn_nsdl_addr_s *c, void *d) { - printf("coap tx cb\n"); - return 0; -} + + -int8_t coap_rx_cb(sn_coap_hdr_s *a, sn_nsdl_addr_s *b, void *c) { - printf("coap rx cb\n"); - return 0; -} - -// Main function for the recvfrom thread -void recvfromMain() { - SocketAddress addr; - uint8_t* recv_buffer = (uint8_t*)malloc(1280); // Suggested is to keep packet size under 1280 bytes - - nsapi_size_or_error_t ret; - - while ((ret = socket.recvfrom(&addr, recv_buffer, 1280)) >= 0) { - // to see where the message came from, inspect addr.get_addr() and addr.get_port() +int main(){ + int error = 0; + pc.baud(115200); + pc.printf("\r\n Simple HTTP example over ESP8266\r\n\r\n"); - printf("Received a message of length '%d'\n", ret); - - sn_coap_hdr_s* parsed = sn_coap_parser(coapHandle, ret, recv_buffer, &coapVersion); - - // We know the payload is going to be a string - std::string payload((const char*)parsed->payload_ptr, parsed->payload_len); - - printf("\tmsg_id: %d\n", parsed->msg_id); - printf("\tmsg_code: %d\n", parsed->msg_code); - printf("\tcontent_format: %d\n", parsed->content_format); - printf("\tpayload_len: %d\n", parsed->payload_len); - printf("\tpayload: %s\n", payload.c_str()); - printf("\toptions_list_ptr: %p\n", parsed->options_list_ptr); + pc.printf("\r\nConnecting...\r\n"); + + NetworkInterface *network = easy_connect(true); + while(!network){ + pc.printf("Error: Cannot connect to the network\r\n"); + wait(1); + network = easy_connect(true); } - - free(recv_buffer); + + pc.printf("Success\r\n\r\n"); + pc.printf("MAC: %s\r\n", network->get_mac_address()); + pc.printf("IP: %s\r\n", network->get_ip_address()); + pc.printf("Netmask: %s\r\n", network->get_netmask()); + pc.printf("Gateway: %s\r\n", network->get_gateway()); + pc.printf("RSSI: %d\r\n\r\n", wifi.get_rssi()); - printf("UDPSocket::recvfrom failed, error code %d. Shutting down receive thread.\n", ret); -} +// http_demo(network); +// network->disconnect(); + pc.printf("\r\nDone\r\n"); -int main() { - NetworkInterface *network = easy_connect(true); - if (!network) { - printf("Cannot connect to the network, see serial output"); - return 1; - } - - printf("Connected to the network. Opening a socket...\n"); - // Open a socket on the network interface - socket.open(network); - - // Initialize the CoAP protocol handle, pointing to local implementations on malloc/free/tx/rx functions - coapHandle = sn_coap_protocol_init(&coap_malloc, &coap_free, &coap_tx_cb, &coap_rx_cb); + TCPSocket socket; - // UDPSocket::recvfrom is blocking, so run it in a separate RTOS thread - recvfromThread.start(&recvfromMain); - - // Path to the resource we want to retrieve - const char* coap_uri_path = "/hello"; + socket.open(network); + socket.connect(SERVER_IP, SERVER_PORT); - // See ns_coap_header.h - sn_coap_hdr_s *coap_res_ptr = (sn_coap_hdr_s*)calloc(sizeof(sn_coap_hdr_s), 1); - coap_res_ptr->uri_path_ptr = (uint8_t*)coap_uri_path; // Path - coap_res_ptr->uri_path_len = strlen(coap_uri_path); - coap_res_ptr->msg_code = COAP_MSG_CODE_REQUEST_GET; // CoAP method - coap_res_ptr->content_format = COAP_CT_TEXT_PLAIN; // CoAP content type - coap_res_ptr->payload_len = 0; // Body length - coap_res_ptr->payload_ptr = 0; // Body pointer - coap_res_ptr->options_list_ptr = 0; // Optional: options list - // Message ID is used to track request->response patterns, because we're using UDP (so everything is unconfirmed). - // See the receive code to verify that we get the same message ID back - coap_res_ptr->msg_id = 7; - - // Calculate the CoAP message size, allocate the memory and build the message - uint16_t message_len = sn_coap_builder_calc_needed_packet_data_size(coap_res_ptr); - printf("Calculated message length: %d bytes\n", message_len); - - uint8_t* message_ptr = (uint8_t*)malloc(message_len); - sn_coap_builder(message_ptr, coap_res_ptr); - - // Uncomment to see the raw buffer that will be sent... - // printf("Message is: "); - // for (size_t ix = 0; ix < message_len; ix++) { - // printf("%02x ", message_ptr[ix]); - // } - // printf("\n"); - - int scount = socket.sendto("coap.me", 5683, message_ptr, message_len); - printf("Sent %d bytes to coap://coap.me:5683\n", scount); - - free(coap_res_ptr); - free(message_ptr); - - Thread::wait(osWaitForever); + int temp = 0, hum = 0; + int scount, rcount; + + while(1){ + + pc.printf("a710 server is %s : %d ...\r\n", SERVER_IP, SERVER_PORT); + + char rbuffer[64]={}; + + rcount = socket.recv(rbuffer, sizeof rbuffer); + + pc.printf("%s\r\n", rbuffer); + if(!strcmp(rbuffer, "GET /DHT22\r\n")){ + char sbuffer[64]={}; + scount = socket.send("OK\r\n", sizeof("OK\r\n")); + error = sensor.readData(); + if (error == 0) { + temp = sensor.ReadTemperature(CELCIUS); + hum = sensor.ReadHumidity(); + } + else { + printf("Error: %d\r\n", error); + } + sprintf(sbuffer, "{ \"temp\": \"%d\", \"humid\": \"%d\"}\r\n", temp, hum); + scount = socket.send(sbuffer, sizeof(sbuffer)); + pc.printf(sbuffer); + } + else{ + pc.printf("Unknown request\r\n"); + scount = socket.send("Unknown request\r\n", sizeof("Unknown request\r\n")); + } + } }