From 5a6b55af2773bfacd837748b0a7f379eb265edfd Mon Sep 17 00:00:00 2001 From: cohabit Date: Mon, 21 Jun 2021 11:29:53 +0200 Subject: [PATCH] first commit --- .gitignore | 6 + include/README | 39 +++ include/header.h | 43 ++++ include/secret.h | 5 + lib/NTPClient-master/.travis.yml | 10 + lib/NTPClient-master/CHANGELOG | 15 ++ lib/NTPClient-master/NTPClient.cpp | 234 ++++++++++++++++++ lib/NTPClient-master/NTPClient.h | 105 ++++++++ lib/NTPClient-master/README.md | 47 ++++ .../examples/Advanced/Advanced.ino | 37 +++ lib/NTPClient-master/examples/Basic/Basic.ino | 33 +++ lib/NTPClient-master/keywords.txt | 20 ++ lib/NTPClient-master/library.json | 24 ++ lib/NTPClient-master/library.properties | 9 + lib/README | 46 ++++ mqtt-python | 55 ++++ platformio.ini | 21 ++ src/main.cpp | 159 ++++++++++++ test/README | 11 + 19 files changed, 919 insertions(+) create mode 100644 .gitignore create mode 100644 include/README create mode 100644 include/header.h create mode 100644 include/secret.h create mode 100644 lib/NTPClient-master/.travis.yml create mode 100644 lib/NTPClient-master/CHANGELOG create mode 100644 lib/NTPClient-master/NTPClient.cpp create mode 100644 lib/NTPClient-master/NTPClient.h create mode 100644 lib/NTPClient-master/README.md create mode 100644 lib/NTPClient-master/examples/Advanced/Advanced.ino create mode 100644 lib/NTPClient-master/examples/Basic/Basic.ino create mode 100644 lib/NTPClient-master/keywords.txt create mode 100644 lib/NTPClient-master/library.json create mode 100644 lib/NTPClient-master/library.properties create mode 100644 lib/README create mode 100644 mqtt-python create mode 100644 platformio.ini create mode 100644 src/main.cpp create mode 100644 test/README diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8841fbb --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +.pio +.vscode/.browse.c_cpp.db* +.vscode/c_cpp_properties.json +.vscode/launch.json +.vscode/ipch +include/secret.h diff --git a/include/README b/include/README new file mode 100644 index 0000000..45496b1 --- /dev/null +++ b/include/README @@ -0,0 +1,39 @@ + +This directory is intended for project header files. + +A header file is a file containing C declarations and macro definitions +to be shared between several project source files. You request the use of a +header file in your project source file (C, C++, etc) located in `src` folder +by including it, with the C preprocessing directive `#include'. + +```src/main.c + +#include "header.h" + +int main (void) +{ + ... +} +``` + +Including a header file produces the same results as copying the header file +into each source file that needs it. Such copying would be time-consuming +and error-prone. With a header file, the related declarations appear +in only one place. If they need to be changed, they can be changed in one +place, and programs that include the header file will automatically use the +new version when next recompiled. The header file eliminates the labor of +finding and changing all the copies as well as the risk that a failure to +find one copy will result in inconsistencies within a program. + +In C, the usual convention is to give header files names that end with `.h'. +It is most portable to use only letters, digits, dashes, and underscores in +header file names, and at most one dot. + +Read more about using header files in official GCC documentation: + +* Include Syntax +* Include Operation +* Once-Only Headers +* Computed Includes + +https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html diff --git a/include/header.h b/include/header.h new file mode 100644 index 0000000..f1909cc --- /dev/null +++ b/include/header.h @@ -0,0 +1,43 @@ +#ifndef HEADER_H +#define HEADER_H +#include +#include +#include +#include +#include +#include +#include + +#define TOPIC "test1" +#define MQTT_ADRESS "192.168.0.242" +#define MQTT_PORT 1883 +#define DELAI 600000 //en ms +#define ESPNAME "esp32-bastien" +#define GRAPPE "grappe2" +#define NOMBRE_CAPTEUR 5 +#define DHT22 22 +#define TIME_TO_SLEEP 598 +#define uS_TO_S_FACTOR 1000000 +#define R2 100 +#define R3 10 +#define VOLTAGE_OUT(Vin) (((Vin)*R3) / (R2 + R3)) +#define VOLTAGE_MAX 4200 +#define VOLTAGE_MIN 3300 +#define ADC_REFERENCE 1100 +#define VOLTAGE_TO_ADC(in) ((ADC_REFERENCE * (in)) / 4096) +#define BATTERY_MAX_ADC VOLTAGE_TO_ADC(VOLTAGE_OUT(VOLTAGE_MAX)) +#define BATTERY_MIN_ADC VOLTAGE_TO_ADC(VOLTAGE_OUT(VOLTAGE_MIN)) +#define ADC_PIN 34 +#define CONV_FACTOR 2.92 +#define READS 20 + +void setupMQTT(const char *adresse, int port); +void setupWIFI(const char *wifiName, const char *password); +void reconnect(void); +void initCapteurs(DHT *capteurs, int L); +void lireCapteurs(DHT capteurs[], float temp[], float hum[], int L); +void ecrireMessage(char *txt, float *temp, float *hum, int L); + +//timeClient.getEpochTime().toCharArray(date, 50); = convertir un string en char + +#endif diff --git a/include/secret.h b/include/secret.h new file mode 100644 index 0000000..25c9e45 --- /dev/null +++ b/include/secret.h @@ -0,0 +1,5 @@ +#define MQTT_USER "NomUtilisateurMQTT" +#define MQTT_MDP "MotDePasseMQTT" +#define SSID "NomDuWifi" +#define PWD "MotDePasseWifi" + diff --git a/lib/NTPClient-master/.travis.yml b/lib/NTPClient-master/.travis.yml new file mode 100644 index 0000000..fa09d0f --- /dev/null +++ b/lib/NTPClient-master/.travis.yml @@ -0,0 +1,10 @@ +language: c +sudo: false +before_install: + - source <(curl -SLs https://raw.githubusercontent.com/adafruit/travis-ci-arduino/master/install.sh) +script: + - build_platform esp8266 +notifications: + email: + on_success: change + on_failure: change diff --git a/lib/NTPClient-master/CHANGELOG b/lib/NTPClient-master/CHANGELOG new file mode 100644 index 0000000..6a082d5 --- /dev/null +++ b/lib/NTPClient-master/CHANGELOG @@ -0,0 +1,15 @@ +NTPClient 3.1.0 - 2016.05.31 + +* Added functions for changing the timeOffset and updateInterval later. Thanks @SirUli + +NTPClient 3.0.0 - 2016.04.19 + +* Constructors now require UDP instance argument, to add support for non-ESP8266 boards +* Added optional begin API to override default local port +* Added end API to close UDP socket +* Changed return type of update and forceUpdate APIs to bool, and return success or failure +* Change return type of getDay, getHours, getMinutes, and getSeconds to int + +Older + +* Changes not recorded diff --git a/lib/NTPClient-master/NTPClient.cpp b/lib/NTPClient-master/NTPClient.cpp new file mode 100644 index 0000000..6f6a4cd --- /dev/null +++ b/lib/NTPClient-master/NTPClient.cpp @@ -0,0 +1,234 @@ +/** + * The MIT License (MIT) + * Copyright (c) 2015 by Fabrice Weinberg + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation 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 + * furnished 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 FOR 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 "NTPClient.h" + +NTPClient::NTPClient(UDP& udp) { + this->_udp = &udp; +} + +NTPClient::NTPClient(UDP& udp, int timeOffset) { + this->_udp = &udp; + this->_timeOffset = timeOffset; +} + +NTPClient::NTPClient(UDP& udp, const char* poolServerName) { + this->_udp = &udp; + this->_poolServerName = poolServerName; +} + +NTPClient::NTPClient(UDP& udp, const char* poolServerName, int timeOffset) { + this->_udp = &udp; + this->_timeOffset = timeOffset; + this->_poolServerName = poolServerName; +} + +NTPClient::NTPClient(UDP& udp, const char* poolServerName, int timeOffset, unsigned long updateInterval) { + this->_udp = &udp; + this->_timeOffset = timeOffset; + this->_poolServerName = poolServerName; + this->_updateInterval = updateInterval; +} + +void NTPClient::begin() { + this->begin(NTP_DEFAULT_LOCAL_PORT); +} + +void NTPClient::begin(int port) { + this->_port = port; + + this->_udp->begin(this->_port); + + this->_udpSetup = true; +} + +bool NTPClient::isValid(byte * ntpPacket) +{ + //Perform a few validity checks on the packet + if((ntpPacket[0] & 0b11000000) == 0b11000000) //Check for LI=UNSYNC + return false; + + if((ntpPacket[0] & 0b00111000) >> 3 < 0b100) //Check for Version >= 4 + return false; + + if((ntpPacket[0] & 0b00000111) != 0b100) //Check for Mode == Server + return false; + + if((ntpPacket[1] < 1) || (ntpPacket[1] > 15)) //Check for valid Stratum + return false; + + if( ntpPacket[16] == 0 && ntpPacket[17] == 0 && + ntpPacket[18] == 0 && ntpPacket[19] == 0 && + ntpPacket[20] == 0 && ntpPacket[21] == 0 && + ntpPacket[22] == 0 && ntpPacket[22] == 0) //Check for ReferenceTimestamp != 0 + return false; + + return true; +} + +bool NTPClient::forceUpdate() { + #ifdef DEBUG_NTPClient + Serial.println("Update from NTP Server"); + #endif + // flush any existing packets + while(this->_udp->parsePacket() != 0) + this->_udp->flush(); + this->sendNTPPacket(); + + // Wait till data is there or timeout... + byte timeout = 0; + int cb = 0; + do { + delay ( 10 ); + cb = this->_udp->parsePacket(); + + if(cb > 0) + { + this->_udp->read(this->_packetBuffer, NTP_PACKET_SIZE); + if(!this->isValid(this->_packetBuffer)) + cb = 0; + } + + if (timeout > 100) return false; // timeout after 1000 ms + timeout++; + } while (cb == 0); + + this->_lastUpdate = millis() - (10 * (timeout + 1)); // Account for delay in reading the time + + unsigned long highWord = word(this->_packetBuffer[40], this->_packetBuffer[41]); + unsigned long lowWord = word(this->_packetBuffer[42], this->_packetBuffer[43]); + // combine the four bytes (two words) into a long integer + // this is NTP time (seconds since Jan 1 1900): + unsigned long secsSince1900 = highWord << 16 | lowWord; + + this->_currentEpoc = secsSince1900 - SEVENZYYEARS; + + return true; +} + +bool NTPClient::update() { + if ((millis() - this->_lastUpdate >= this->_updateInterval) // Update after _updateInterval + || this->_lastUpdate == 0) { // Update if there was no update yet. + if (!this->_udpSetup) this->begin(); // setup the UDP client if needed + return this->forceUpdate(); + } + return true; +} + +unsigned long NTPClient::getEpochTime() { + return this->_timeOffset + // User offset + this->_currentEpoc + // Epoc returned by the NTP server + ((millis() - this->_lastUpdate) / 1000); // Time since last update +} + +int NTPClient::getDay() { + return (((this->getEpochTime() / 86400L) + 4 ) % 7); //0 is Sunday +} +int NTPClient::getHours() { + return ((this->getEpochTime() % 86400L) / 3600); +} +int NTPClient::getMinutes() { + return ((this->getEpochTime() % 3600) / 60); +} +int NTPClient::getSeconds() { + return (this->getEpochTime() % 60); +} + +String NTPClient::getFormattedTime(unsigned long secs) { + unsigned long rawTime = secs ? secs : this->getEpochTime(); + unsigned long hours = (rawTime % 86400L) / 3600; + String hoursStr = hours < 10 ? "0" + String(hours) : String(hours); + + unsigned long minutes = (rawTime % 3600) / 60; + String minuteStr = minutes < 10 ? "0" + String(minutes) : String(minutes); + + unsigned long seconds = rawTime % 60; + String secondStr = seconds < 10 ? "0" + String(seconds) : String(seconds); + + return hoursStr + ":" + minuteStr + ":" + secondStr; +} + +// Based on https://github.com/PaulStoffregen/Time/blob/master/Time.cpp +// currently assumes UTC timezone, instead of using this->_timeOffset +String NTPClient::getFormattedDate(unsigned long secs) { + unsigned long rawTime = (secs ? secs : this->getEpochTime()) / 86400L; // in days + unsigned long days = 0, year = 1970; + uint8_t month; + static const uint8_t monthDays[]={31,28,31,30,31,30,31,31,30,31,30,31}; + + while((days += (LEAP_YEAR(year) ? 366 : 365)) <= rawTime) + year++; + rawTime -= days - (LEAP_YEAR(year) ? 366 : 365); // now it is days in this year, starting at 0 + days=0; + for (month=0; month<12; month++) { + uint8_t monthLength; + if (month==1) { // february + monthLength = LEAP_YEAR(year) ? 29 : 28; + } else { + monthLength = monthDays[month]; + } + if (rawTime < monthLength) break; + rawTime -= monthLength; + } + String monthStr = ++month < 10 ? "0" + String(month) : String(month); // jan is month 1 + String dayStr = ++rawTime < 10 ? "0" + String(rawTime) : String(rawTime); // day of month + return String(year) + "-" + monthStr + "-" + dayStr + "T" + this->getFormattedTime(secs ? secs : 0) + "Z"; +} + +void NTPClient::end() { + this->_udp->stop(); + + this->_udpSetup = false; +} + +void NTPClient::setTimeOffset(int timeOffset) { + this->_timeOffset = timeOffset; +} + +void NTPClient::setUpdateInterval(unsigned long updateInterval) { + this->_updateInterval = updateInterval; +} + +void NTPClient::sendNTPPacket() { + // set all bytes in the buffer to 0 + memset(this->_packetBuffer, 0, NTP_PACKET_SIZE); + // Initialize values needed to form NTP request + // (see URL above for details on the packets) + this->_packetBuffer[0] = 0b11100011; // LI, Version, Mode + this->_packetBuffer[1] = 0; // Stratum, or type of clock + this->_packetBuffer[2] = 6; // Polling Interval + this->_packetBuffer[3] = 0xEC; // Peer Clock Precision + // 8 bytes of zero for Root Delay & Root Dispersion + this->_packetBuffer[12] = 0x49; + this->_packetBuffer[13] = 0x4E; + this->_packetBuffer[14] = 0x49; + this->_packetBuffer[15] = 0x52; + + // all NTP fields have been given values, now + // you can send a packet requesting a timestamp: + this->_udp->beginPacket(this->_poolServerName, 123); //NTP requests are to port 123 + this->_udp->write(this->_packetBuffer, NTP_PACKET_SIZE); + this->_udp->endPacket(); +} + +void NTPClient::setEpochTime(unsigned long secs) { + this->_currentEpoc = secs; +} diff --git a/lib/NTPClient-master/NTPClient.h b/lib/NTPClient-master/NTPClient.h new file mode 100644 index 0000000..ad45070 --- /dev/null +++ b/lib/NTPClient-master/NTPClient.h @@ -0,0 +1,105 @@ +#pragma once + +#include "Arduino.h" + +#include + +#define SEVENZYYEARS 2208988800UL +#define NTP_PACKET_SIZE 48 +#define NTP_DEFAULT_LOCAL_PORT 1337 +#define LEAP_YEAR(Y) ( (Y>0) && !(Y%4) && ( (Y%100) || !(Y%400) ) ) + + +class NTPClient { + private: + UDP* _udp; + bool _udpSetup = false; + + const char* _poolServerName = "pool.ntp.org"; // Default time server + int _port = NTP_DEFAULT_LOCAL_PORT; + int _timeOffset = 0; + + unsigned long _updateInterval = 60000; // In ms + + unsigned long _currentEpoc = 0; // In s + unsigned long _lastUpdate = 0; // In ms + + byte _packetBuffer[NTP_PACKET_SIZE]; + + void sendNTPPacket(); + bool isValid(byte * ntpPacket); + + public: + NTPClient(UDP& udp); + NTPClient(UDP& udp, int timeOffset); + NTPClient(UDP& udp, const char* poolServerName); + NTPClient(UDP& udp, const char* poolServerName, int timeOffset); + NTPClient(UDP& udp, const char* poolServerName, int timeOffset, unsigned long updateInterval); + + /** + * Starts the underlying UDP client with the default local port + */ + void begin(); + + /** + * Starts the underlying UDP client with the specified local port + */ + void begin(int port); + + /** + * This should be called in the main loop of your application. By default an update from the NTP Server is only + * made every 60 seconds. This can be configured in the NTPClient constructor. + * + * @return true on success, false on failure + */ + bool update(); + + /** + * This will force the update from the NTP Server. + * + * @return true on success, false on failure + */ + bool forceUpdate(); + + int getDay(); + int getHours(); + int getMinutes(); + int getSeconds(); + + /** + * Changes the time offset. Useful for changing timezones dynamically + */ + void setTimeOffset(int timeOffset); + + /** + * Set the update interval to another frequency. E.g. useful when the + * timeOffset should not be set in the constructor + */ + void setUpdateInterval(unsigned long updateInterval); + + /** + * @return secs argument (or 0 for current time) formatted like `hh:mm:ss` + */ + String getFormattedTime(unsigned long secs = 0); + + /** + * @return time in seconds since Jan. 1, 1970 + */ + unsigned long getEpochTime(); + + /** + * @return secs argument (or 0 for current date) formatted to ISO 8601 + * like `2004-02-12T15:19:21+00:00` + */ + String getFormattedDate(unsigned long secs = 0); + + /** + * Stops the underlying UDP client + */ + void end(); + + /** + * Replace the NTP-fetched time with seconds since Jan. 1, 1970 + */ + void setEpochTime(unsigned long secs); +}; diff --git a/lib/NTPClient-master/README.md b/lib/NTPClient-master/README.md new file mode 100644 index 0000000..6c8c07a --- /dev/null +++ b/lib/NTPClient-master/README.md @@ -0,0 +1,47 @@ +# NTPClient + +[![Build Status](https://travis-ci.org/arduino-libraries/NTPClient.svg?branch=master)](https://travis-ci.org/arduino-libraries/NTPClient) + +Connect to a NTP server, here is how: + +```cpp +#include +// change next line to use with another board/shield +#include +//#include // for WiFi shield +//#include // for WiFi 101 shield or MKR1000 +#include + +const char *ssid = ""; +const char *password = ""; + +WiFiUDP ntpUDP; + +// By default 'pool.ntp.org' is used with 60 seconds update interval and +// no offset +NTPClient timeClient(ntpUDP); + +// You can specify the time server pool and the offset, (in seconds) +// additionaly you can specify the update interval (in milliseconds). +// NTPClient timeClient(ntpUDP, "europe.pool.ntp.org", 3600, 60000); + +void setup(){ + Serial.begin(115200); + WiFi.begin(ssid, password); + + while ( WiFi.status() != WL_CONNECTED ) { + delay ( 500 ); + Serial.print ( "." ); + } + + timeClient.begin(); +} + +void loop() { + timeClient.update(); + + Serial.println(timeClient.getFormattedTime()); + + delay(1000); +} +``` diff --git a/lib/NTPClient-master/examples/Advanced/Advanced.ino b/lib/NTPClient-master/examples/Advanced/Advanced.ino new file mode 100644 index 0000000..2559508 --- /dev/null +++ b/lib/NTPClient-master/examples/Advanced/Advanced.ino @@ -0,0 +1,37 @@ +#include +// change next line to use with another board/shield +#include +//#include // for WiFi shield +//#include // for WiFi 101 shield or MKR1000 +#include + +const char *ssid = ""; +const char *password = ""; + +WiFiUDP ntpUDP; + +// You can specify the time server pool and the offset (in seconds, can be +// changed later with setTimeOffset() ). Additionaly you can specify the +// update interval (in milliseconds, can be changed using setUpdateInterval() ). +NTPClient timeClient(ntpUDP, "europe.pool.ntp.org", 3600, 60000); + +void setup(){ + Serial.begin(115200); + + WiFi.begin(ssid, password); + + while ( WiFi.status() != WL_CONNECTED ) { + delay ( 500 ); + Serial.print ( "." ); + } + + timeClient.begin(); +} + +void loop() { + timeClient.update(); + + Serial.println(timeClient.getFormattedTime()); + + delay(1000); +} diff --git a/lib/NTPClient-master/examples/Basic/Basic.ino b/lib/NTPClient-master/examples/Basic/Basic.ino new file mode 100644 index 0000000..f0a2a7c --- /dev/null +++ b/lib/NTPClient-master/examples/Basic/Basic.ino @@ -0,0 +1,33 @@ +#include +// change next line to use with another board/shield +#include +//#include // for WiFi shield +//#include // for WiFi 101 shield or MKR1000 +#include + +const char *ssid = ""; +const char *password = ""; + +WiFiUDP ntpUDP; +NTPClient timeClient(ntpUDP); + +void setup(){ + Serial.begin(115200); + + WiFi.begin(ssid, password); + + while ( WiFi.status() != WL_CONNECTED ) { + delay ( 500 ); + Serial.print ( "." ); + } + + timeClient.begin(); +} + +void loop() { + timeClient.update(); + + Serial.println(timeClient.getFormattedTime()); + + delay(1000); +} diff --git a/lib/NTPClient-master/keywords.txt b/lib/NTPClient-master/keywords.txt new file mode 100644 index 0000000..1430d04 --- /dev/null +++ b/lib/NTPClient-master/keywords.txt @@ -0,0 +1,20 @@ +####################################### +# Datatypes (KEYWORD1) +####################################### + +NTPClient KEYWORD1 + +####################################### +# Methods and Functions (KEYWORD2) +####################################### + +begin KEYWORD2 +end KEYWORD2 +update KEYWORD2 +forceUpdate KEYWORD2 +getDay KEYWORD2 +getHours KEYWORD2 +getMinutes KEYWORD2 +getSeconds KEYWORD2 +getFormattedTime KEYWORD2 +getEpochTime KEYWORD2 diff --git a/lib/NTPClient-master/library.json b/lib/NTPClient-master/library.json new file mode 100644 index 0000000..d6249c1 --- /dev/null +++ b/lib/NTPClient-master/library.json @@ -0,0 +1,24 @@ +{ + "name": "NTPClient", + "keywords": "ntp, client, time", + "description": "A NTPClient to connect to a time server", + "authors": + [ + { + "name": "Fabrice Weinberg", + "email": "fabrice@weinberg.me" + }, + { + "name": "Sandeep Mistry", + "email": "s.mistry@arduino.cc" + } + ], + "repository": + { + "type": "git", + "url": "https://github.com/arduino-libraries/NTPClient.git" + }, + "version": "3.1.0", + "frameworks": "arduino", + "platforms": "espressif" +} diff --git a/lib/NTPClient-master/library.properties b/lib/NTPClient-master/library.properties new file mode 100644 index 0000000..d4908ca --- /dev/null +++ b/lib/NTPClient-master/library.properties @@ -0,0 +1,9 @@ +name=NTPClient +version=3.1.0 +author=Fabrice Weinberg +maintainer=Fabrice Weinberg +sentence=An NTPClient to connect to a time server +paragraph=Get time from a NTP server and keep it in sync. +category=Timing +url=https://github.com/arduino-libraries/NTPClient +architectures=* diff --git a/lib/README b/lib/README new file mode 100644 index 0000000..8c9c29c --- /dev/null +++ b/lib/README @@ -0,0 +1,46 @@ + +This directory is intended for project specific (private) libraries. +PlatformIO will compile them to static libraries and link into executable file. + +The source code of each library should be placed in a an own separate directory +("lib/your_library_name/[here are source files]"). + +For example, see a structure of the following two libraries `Foo` and `Bar`: + +|--lib +| | +| |--Bar +| | |--docs +| | |--examples +| | |--src +| | |- Bar.c +| | |- Bar.h +| | |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html +| | +| |--Foo +| | |- Foo.c +| | |- Foo.h +| | +| |- README --> THIS FILE +| +|- platformio.ini +|--src + |- main.c + +and a contents of `src/main.c`: +``` +#include +#include + +int main (void) +{ + ... +} + +``` + +PlatformIO Library Dependency Finder will find automatically dependent +libraries scanning project source files. + +More information about PlatformIO Library Dependency Finder +- https://docs.platformio.org/page/librarymanager/ldf.html diff --git a/mqtt-python b/mqtt-python new file mode 100644 index 0000000..575b7ca --- /dev/null +++ b/mqtt-python @@ -0,0 +1,55 @@ +import paho.mqtt.client as mqttClient +from influxdb import InfluxDBClient +import time + +TOPIC = "test1" +broker_address= "localhost" +port = 1883 +database = "thermo-bibli" +nom_client = "capteurs1" + +def on_connect(client, userdata, flags, rc): + print("Connected with result code "+str(rc)) + client.subscribe(TOPIC, 2) + +def addData(database, time, numero_grappe, numero_capteur, temp, hum, batterie): # ajoute donnée à base de donnée influxDB + client = InfluxDBClient(host='localhost', port=8086) + client.create_database(database) + client.switch_database(database) + data = [ + { + "measurement": numero_grappe, + "tags": {"numero_capteur": numero_capteur}, + "time": time, + "fields": {"temperature": temp, "humidite": hum, "batterie": batterie} + + } + ] + client.write_points(data) + +def on_message(client, userdata, message): + message = (message.payload).decode("utf-8") # convertit type bytes en string + print("Message reçu") + tab = message.split("|") + temp = tab[2].split() + hum = tab[3].split() + batterie = tab[4] + L = len(temp) + for i in range(L): + addData(database, tab[0], tab[1], "capteur" + str(i+1), temp[i], hum[i], batterie) + +client = mqttClient.Client(nom_client, False) +client.username_pw_set(username="capteurs",password="Fablab") +client.on_connect= on_connect #callback +client.on_message= on_message #callback +client.connect(broker_address, port, 65535) +client.loop_start() + +try: + while True: + time.sleep(0.1) + +except KeyboardInterrupt: + print ("exiting") + client.disconnect() + client.loop_stop() diff --git a/platformio.ini b/platformio.ini new file mode 100644 index 0000000..fe33c49 --- /dev/null +++ b/platformio.ini @@ -0,0 +1,21 @@ +; PlatformIO Project Configuration File +; +; Build options: build flags, source filter +; Upload options: custom upload port, speed and extra flags +; Library options: dependencies, extra library storages +; Advanced options: extra scripting +; +; Please visit documentation for the other options and examples +; https://docs.platformio.org/page/projectconf.html + +[env:esp32dev] +platform = espressif32 +board = esp32dev +framework = arduino +lib_deps = + adafruit/DHT sensor library@^1.4.2 + adafruit/Adafruit Unified Sensor@^1.1.4 + knolleary/PubSubClient@^2.8 + ottowinter/ESPAsyncWebServer-esphome@^1.2.7 + ottowinter/AsyncTCP-esphome@^1.2.1 + arduino-libraries/NTPClient@^3.1.0 diff --git a/src/main.cpp b/src/main.cpp new file mode 100644 index 0000000..0268161 --- /dev/null +++ b/src/main.cpp @@ -0,0 +1,159 @@ +#include "header.h" + +using namespace std; + +DHT capteurs[NOMBRE_CAPTEUR] = {DHT(23, DHT22), DHT(22, DHT22), DHT(21, DHT22), DHT(17, DHT22), DHT(2, DHT22)}; +float temp[NOMBRE_CAPTEUR]; +float hum[NOMBRE_CAPTEUR]; + +WiFiClient wifiClient; +PubSubClient mqttClient(wifiClient); +WiFiUDP ntpUDP; +NTPClient timeClient(ntpUDP, "europe.pool.ntp.org", 0, 60000); +Pangodream_18650_CL BL(ADC_PIN, CONV_FACTOR, READS); + +//-------------------- FONCTIONS --------------------// + +void setupMQTT(const char *adresse, int port) +{ + mqttClient.setServer(adresse, port); +} + +void setupWIFI(const char *wifiName, const char *password) +{ + Serial.println('\n'); + + WiFi.begin(wifiName, password); + Serial.print("Connecting to "); + Serial.print(wifiName); + + while (WiFi.status() != WL_CONNECTED) + { + delay(500); + Serial.print('.'); + } + Serial.println('\n'); + Serial.println("Connection established!"); + Serial.print("IP address:\t"); + Serial.println(WiFi.localIP()); +} + +void reconnect(void) +{ + Serial.println("Connecting to MQTT Broker..."); + while (!mqttClient.connected()) + { + Serial.print("."); + if (mqttClient.connect(ESPNAME,MQTT_USER,MQTT_MDP)) + { + Serial.println("Connected."); + } + } +} + +void initCapteurs(DHT *capteurs, int L) +{ + int i; + for (i = 0; i < L; i++) + { + capteurs[i].begin(); + } +} + +void lireCapteurs(DHT capteurs[], float temp[], float hum[], int L) +{ + int i; + for (i = 0; i < L; i++) + { + *(temp + i) = capteurs[i].readTemperature(); + *(hum + i) = capteurs[i].readHumidity(); + } +} + +void sleep() +{ + esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR); + esp_deep_sleep_start(); +} + +//exemple d'une triple utilisation de valeur pour une fonction +std::tuple getDate() +{ + time_t rawtime = timeClient.getEpochTime(); + struct tm *ti; + ti = localtime(&rawtime); + int year = ti->tm_year + 1900; + int month = (ti->tm_mon + 1) < 10 ? 0 + (ti->tm_mon + 1) : (ti->tm_mon + 1); + int day = (ti->tm_mday) < 10 ? 0 + (ti->tm_mday) : (ti->tm_mday); + + return std::make_tuple(year, month, day); +} + +void ecrireMessage(char *txt, float *temp, float *hum, int L) +{ + int batte = BL.getBatteryChargeLevel(); + switch (L) + { + case 1: + sprintf(txt, "|%s|%0.2f|%0.2f", GRAPPE, temp[0], hum[0]); + break; + case 2: + sprintf(txt, "|%s|%0.2f %0.2f|%0.2f %0.2f", GRAPPE, temp[0], temp[1], hum[0], hum[1]); + break; + case 3: + sprintf(txt, "|%s|%0.2f %0.2f %0.2f|%0.2f %0.2f %0.2f", GRAPPE, temp[0], temp[1], temp[2], hum[0], hum[1], hum[2]); + break; + case 4: + sprintf(txt, "|%s|%0.2f %0.2f %0.2f %0.2f|%0.2f %0.2f %0.2f %0.2f", GRAPPE, temp[0], temp[1], temp[2], temp[3], hum[0], hum[1], hum[2], hum[3]); + break; + case 5: + sprintf(txt, "|%s|%0.2f %0.2f %0.2f %0.2f %0.2f|%0.2f %0.2f %0.2f %0.2f %0.2f|%d", GRAPPE, temp[0], temp[1], temp[2], temp[3], temp[4], hum[0], hum[1], hum[2], hum[3], hum[4], batte); + break; + case 6: + sprintf(txt, "|%s|%0.2f %0.2f %0.2f %0.2f %0.2f %0.2f|%0.2f %0.2f %0.2f %0.2f %0.2f %0.2f", GRAPPE, temp[0], temp[1], temp[2], temp[3], temp[4], temp[5], hum[0], hum[1], hum[2], hum[3], hum[4], hum[5]); + break; + default: + Serial.println("Erreur, temp et hum sont trop longs : trop de capteurs"); + break; + } +} + +void setup() +{ + Serial.begin(9600); + setupWIFI(SSID, PWD); + setupMQTT(MQTT_ADRESS, MQTT_PORT); + initCapteurs(capteurs, NOMBRE_CAPTEUR); + timeClient.begin(); +} + +void loop() +{ + int year, month, day; + int lenght; + char time[30]; + char date[30]; + char msg[70]; + + mqttClient.loop(); + if (!mqttClient.connected()) + { + reconnect(); + } + + lireCapteurs(capteurs, temp, hum, NOMBRE_CAPTEUR); + ecrireMessage(msg, temp, hum, NOMBRE_CAPTEUR); + + timeClient.update(); + timeClient.getFormattedTime().toCharArray(time, 30); + + tie(year, month, day) = getDate(); + lenght = sprintf(date, "%d-%d-%d ", year, month, day); + sprintf(date + lenght, time); + sprintf(date + strlen(date), msg); + mqttClient.publish(TOPIC, date); + + sleep(); + + delay(DELAI); +} diff --git a/test/README b/test/README new file mode 100644 index 0000000..e7d1588 --- /dev/null +++ b/test/README @@ -0,0 +1,11 @@ + +This directory is intended for PlatformIO Unit Testing and project tests. + +Unit Testing is a software testing method by which individual units of +source code, sets of one or more MCU program modules together with associated +control data, usage procedures, and operating procedures, are tested to +determine whether they are fit for use. Unit testing finds problems early +in the development cycle. + +More information about PlatformIO Unit Testing: +- https://docs.platformio.org/page/plus/unit-testing.html