Skip to content
Snippets Groups Projects
Commit f9eb37b5 authored by Zoe Pfister's avatar Zoe Pfister :speech_balloon:
Browse files

Merge branch 'espnow' into 'develop'

Espnow

See merge request !1
parents 29cb498a c537a5b6
No related branches found
No related tags found
6 merge requests!39Merge Develop into Main,!19development into master,!17Inital Host, initial Client,!10merge serial comm and sd write into espnow,!3Merge Branch `develop` into `sensor_readout`,!1Espnow
Showing
with 428 additions and 0 deletions
---
BasedOnStyle: LLVM
ColumnLimit: 120
IndentWidth: 4
TabWidth: 4
UseTab: ForIndentation
AlignEscapedNewlines: DontAlign
AllowShortFunctionsOnASingleLine: Inline
AlwaysBreakTemplateDeclarations: Yes
BreakBeforeBinaryOperators: NonAssignment
BreakBeforeBraces: Custom
BraceWrapping:
AfterFunction: true
......@@ -15,6 +15,7 @@ downloads/
eggs/
.eggs/
lib/
!client/client/lib
lib64/
parts/
sdist/
......
{
// See http://go.microsoft.com/fwlink/?LinkId=827846
// for the documentation about the extensions.json format
"recommendations": ["platformio.platformio-ide", "xaver.clang-format"]
}
{
"version": "0.1.0",
"tasks": [
{
"taskName": "clang-format-everything",
"command": "clang-format",
"args": ["-i", "*"],
"isShellCommand": true,
"isBackground": true
}
]
}
.pio
.vscode/.browse.c_cpp.db*
.vscode/c_cpp_properties.json
.vscode/launch.json
.vscode/ipch
{
// See http://go.microsoft.com/fwlink/?LinkId=827846
// for the documentation about the extensions.json format
"recommendations": [
"platformio.platformio-ide"
],
"unwantedRecommendations": [
"ms-vscode.cpptools-extension-pack"
]
}
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
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 <Foo.h>
#include <Bar.h>
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
#include "ram_caching.hpp"
RTC_DATA_ATTR int cachedAmount = -1;
RTC_DATA_ATTR ClientDataPackage backup[NUM_SENSORS];
ClientDataPackage ram_cache_pop()
{
return backup[cachedAmount--];
}
void ram_cache_push(ClientDataPackage data)
{
backup[++cachedAmount] = data;
}
bool ram_cache_is_empty()
{
return cachedAmount == -1;
}
bool ram_cache_is_full()
{
return cachedAmount == 9;
}
\ No newline at end of file
#ifndef _RAM_CACHE
#define _RAM_CACHE
#include "ClientDataPackage.hpp"
#include <ESP32Time.h>
bool ram_cache_is_empty();
bool ram_cache_is_full();
void ram_cache_push(ClientDataPackage data);
ClientDataPackage ram_cache_pop();
#endif
\ No newline at end of file
# basic usage
To send data using espnow, create a new Message object,
then use the add_data(value, identifier) method for every value
to fill the message.
when every value is added, use the send() method to send the data
to the host (fipy). If the esp client has never recieved a config
message from the host, it will instead broadcast the message.
---
right now, it is not possible to add more than 10 values.
#pragma once
#define NUM_SENSORS 10
// packing the struct without padding, makes reading it on the fipy easier
#pragma pack(1)
// having the data be a struct of basic types makes sending easier,
// otherwise we would have to serialize the data before sending
struct ClientDataPackage {
int identifiers[NUM_SENSORS];
float values[NUM_SENSORS];
int amountData;
long timestamp; // maybe make this array
};
#include "ESPNow.hpp"
uint8_t BROADCAST_MAC[] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
esp_now_peer_info_t hostInfo;
Preferences preferences;
void get_host_mac(uint8_t *destination)
{
preferences.begin("config", true);
if (preferences.isKey("host")) {
preferences.getBytes("host", destination, sizeof(uint8_t) * 6);
} else {
memcpy(destination, BROADCAST_MAC, sizeof(BROADCAST_MAC));
Serial.println("backup mac used");
}
preferences.end();
}
void on_data_sent(const uint8_t *mac_addr, esp_now_send_status_t status)
{
// go to sleep
}
void on_data_recv(const uint8_t *mac, const uint8_t *incomingData, int len)
{
Serial.println("message recieved");
config new_config;
memcpy(&new_config, incomingData, sizeof(new_config)); // TODO: check for valid mac
// put the host address in flash mem
preferences.begin("config", false);
if (!preferences.isKey("host")) {
preferences.putBytes("host", new_config.host, sizeof(new_config.host));
Serial.println("host mac saved to flash");
} // host change shouldn't be an issue
preferences.end();
// sync time
esptime::rtc.setTime(
new_config.time_millis); // see https://www.esp32.com/viewtopic.php?t=9965, maybe this needs an offset
}
esp_err_t espnow_setup()
{
esp_err_t result;
WiFi.mode(WIFI_STA);
result = esp_now_init();
if (result != ESP_OK) {
// initialization failed
return result; // not sure about this
}
get_host_mac(hostInfo.peer_addr); // check if there is a host saved in flash mem, broadcast otherwise
hostInfo.channel = 0;
hostInfo.encrypt = 0;
esp_now_add_peer(&hostInfo);
esp_now_register_recv_cb(on_data_recv);
esp_now_register_send_cb(on_data_sent);
return ESP_OK;
}
#ifndef _ESPNOW
#define _ESPNOW
#include "Message.hpp"
#include "Time.hpp"
#include "ram_caching.hpp"
#include <ClientDataPackage.hpp>
#include <ESP32Time.h>
#include <Preferences.h>
#include <WiFi.h>
#include <esp_now.h>
typedef struct config {
uint8_t host[6];
long time_millis;
} config;
esp_err_t espnow_setup();
bool is_host_defined();
void get_host_mac(uint8_t *destination);
void on_data_sent(const uint8_t *mac_addr, esp_now_send_status_t status);
void on_data_recv(const uint8_t *mac, const uint8_t *incomingData, int len);
#endif
\ No newline at end of file
#include "Message.hpp"
void Message::add_data(float value, int identifier)
{
if (data.amountData < NUM_SENSORS) {
data.values[data.amountData] = value;
data.identifiers[data.amountData] = identifier;
data.amountData++;
}
}
esp_err_t Message::send()
{
Serial.println("sending Message");
esp_err_t success;
success = esp_now_send(recipient, (uint8_t *)&data, sizeof(data));
// if(success != ESP_OK){
// if(!ram_cache_is_full()){
// ram_cache_push(*data);
// }
// }
for (int i = 0; i < data.amountData; i++) {
Serial.println(data.values[i]);
}
Serial.println((String) "time sent: " + data.timestamp);
Serial.println((String) "Send status: " + success);
Serial.println();
Serial.flush();
Serial.println("done");
return success;
}
Message ::Message()
{
// check for existing host mac address, use broadcast otherwise
get_host_mac(recipient);
data.amountData = 0;
data.timestamp = esptime::rtc.getMillis(); // I am assuming we are not sending data from Unix Epoch
}
Message ::Message(ClientDataPackage old_data)
{
data = old_data;
// memcpy(&data, &old_data, sizeof(data));
get_host_mac(recipient);
}
\ No newline at end of file
#pragma once
#include "ClientDataPackage.hpp"
#include "ESPNow.hpp"
#include "Time.hpp"
#include <Arduino.h>
#include <ESP32Time.h>
#include <esp_now.h>
// Format of the message sent from host to client
// if more things are sent from the host the name might not be accurate anymore
class Message {
public:
Message();
Message(ClientDataPackage old_data);
void add_data(float value, int identifier);
esp_err_t send();
private:
ClientDataPackage data;
uint8_t recipient[6];
};
\ No newline at end of file
#pragma once
#include <ESP32Time.h>
namespace esptime {
// internal linkage only
static ESP32Time rtc; // global variable for the RTC (i don't think this is good practice)
} // namespace esptime
// namespace esptime
; 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:esp32-c3-devkitm-1]
platform = espressif32
board = esp32-c3-devkitm-1
framework = arduino
monitor_speed = 115200
lib_deps =
fbiego/ESP32Time@^1.1.0
bblanchon/ArduinoJson@^6.19.4
#include "ESPNow.hpp"
#include "ram_caching.hpp"
#include <Arduino.h>
#include <ArduinoJson.h>
void setup()
{
// put your setup code here, to run once:
Serial.begin(115200);
while (!Serial)
;
Serial.flush();
esp_err_t result = espnow_setup();
StaticJsonDocument<96> doc;
doc["sensor"] = "gps";
doc["time"] = 1351824120;
JsonArray data = doc.createNestedArray("data");
data.add(48.75608);
data.add(2.302038);
}
int counter = 0;
void loop()
{
// put your main code here, to run repeatedly:
Message new_data = Message{};
new_data.add_data(++counter * 1.1, 0);
new_data.add_data(counter * 1.2, 1);
new_data.add_data(counter * 1.3, 2);
new_data.send();
// if(!ram_cache_is_empty()){
// ClientDataPackage old_data = ram_cache_pop();
// Message* resend_message = new Message(old_data);
// resend_message->send();
// delete resend_message;
// }
delay(5000);
}
\ No newline at end of file
This directory is intended for PlatformIO Test Runner 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/en/latest/advanced/unit-testing/index.html
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment