I am having trouble with the code below. I'm coding a ESP8266 wifi module so that it will register automatically to a MQTT server. To make it easy to configure I made a portal that you can access when you first connect the device. Here you can enter the API key and the IOT path name of your device. I want to load and store these configs from a json.config file. This works, expect I can't seem to pass the variables to the void setup scope. The code is stil filled with my last efforts.
Any pointers on how to fix this?
#include <ArduinoJson.h>
#include <ESP8266WebServer.h>
#include "FS.h"
ESP8266WebServer server ( 80 );
char* ssid;
char* password;
char* apikey;
char* iotpath;
void setup() {
const char* values = loadConfig();
Serial.println(values);
// declare ssid and password
//char* ssid = "xxxxxxx";
//char* password = "xxxxxxxx";
// start serial connection and SPIFFS
Serial.begin (115200);
SPIFFS.begin();
Serial.println(ssid);
Serial.println(password);
Serial.println(apikey);
Serial.println(iotpath);
// WiFi connection sequence
WiFi.begin ( ssid, password );
while ( WiFi.status() != WL_CONNECTED ) {
delay ( 500 ); Serial.print ( "." );
}
// WiFi success print
Serial.println ( "" );
Serial.print ( "Connected to " ); Serial.println ( ssid );
Serial.print ( "IP address: " ); Serial.println ( WiFi.localIP() );
// Check if SPIFSS is started
if (!SPIFFS.begin())
{
Serial.println("SPIFFS Mount failed");
} else {
Serial.println("SPIFFS Mount succesfull");
}
// check if config file was loaded
/*
if (!loadConfig()) {
Serial.println("Failed to load config");
} else {
Serial.println("Config loaded");
}*/
// Server root handling
server.serveStatic("/img", SPIFFS, "/img");
server.serveStatic("/", SPIFFS, "/index.html");
server.serveStatic("/css", SPIFFS, "/css");
server.begin();
Serial.println ( "HTTP server started" );
}
void loop() {
// put your main code here, to run repeatedly:
server.handleClient();
delay(100);
//Serial.println(".");
}
const char* loadConfig() {
File configFile = SPIFFS.open("/config.json", "r");
if (!configFile) {
Serial.println("Failed to open config file");
//return false;
}
size_t size = configFile.size();
if (size > 1024) {
Serial.println("Config file size is too large");
//return false;
}
// Allocate a buffer to store contents of the file.
std::unique_ptr<char[]> buf(new char[size]);
// We don't use String here because ArduinoJson library requires the input
// buffer to be mutable. If you don't use ArduinoJson, you may as well
// use configFile.readString instead.
configFile.readBytes(buf.get(), size);
StaticJsonBuffer<200> jsonBuffer;
JsonObject& json = jsonBuffer.parseObject(buf.get());
if (!json.success()) {
Serial.println("Failed to parse config file");
//return false;
}
const char* ssid = json["ssid"];
const char* password= json["password"];
const char* apikey = json["apikey"];
const char* iotpath = json["iotpath"];
//String ssid_string = String(ssid);
//return ssid;
}
Related
I want to open a .wav file in bytes from the sd card connected to esp32.
My code is based in this question
I just want upload a file from my sd card to a server but by the moment I can't read the file despites the file exists in the sd card:
Look this lines of code:
char *fname = "/sdcard/test.wav";
FILE *fp = fopen(fname, "rb"); // read in bytes
if(!fp) {
Serial.println("File doens't exist");
}
I don't understand why it File file = SD.open("/test.wav") works but the above code not. According to my reference I should read this file in bytes and not in a normal manner like this => File file = SD.open("/test.wav").
I would like know how I can see the full path of my sd card because the original code uses this:
char *fname = "/sdcard/test_text.txt";
FILE *fp = fopen(fname, "rb");
why that uses this path /sdcard/test_text.txt I don't know exactly. If I try to open by using:
File file = SD.open("/test.wav")
will works but some lines of code after this will throws errors because the file should be read in bytes.
I would like to see your advices guys I will appreciate any idea to fix this problem.
this is the entire code:
#include "Arduino.h"
#include "WiFi.h"
#include "SD.h"
#include "FS.h"
#include "HTTPClient.h"
//SD CARD MODULE
#define SD_CS 5
#define SPI_MOSI 23
#define SPI_MISO 19
#define SPI_SCK 18
// Wifi Credentials
const char* ssid = "XXX";
const char* password = "XXX";
void setup() {
Serial.begin(115200);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("MY IP address: ");
Serial.println(WiFi.localIP());
if (!SD.begin(SD_CS)) {
Serial.println("SD init failed!");
return;
}
Serial.println("SD init successfull!");
}
void loop()
{
WiFiClient client;
Serial.println("starting file upload");
IPAddress host(192, 168, 18, 8); //server ip
int port = 80;
if (!client.connect(host, port))
{ // check connection to host if untrue internet connection could be down
Serial.println("couldn't connect to host");
}
Serial.println("Connect to host!");
HTTPClient http;
const char* serverName = "http://192.168.18.8/upload/upload.php";
http.begin(client, serverName);
char *fname = "/sdcard/test.wav";
FILE *fp = fopen(fname, "rb"); // read in bytes
if(!fp) {
Serial.println("File doens't exist");
}
//get file size
fseek(fp, 0, SEEK_END); //send file pointer to end of file
int file_size = ftell(fp); //get end position of file
fseek(fp, 0, SEEK_SET); //send pointer back to start
int max_upload_size = 10; // array size, larger = less uploads but too large can cause memory issues
int num_of_uploads = file_size / max_upload_size; // figure out how many evenly sized upload chunks we need
int num_of_uploads_mod = file_size % max_upload_size; //find out size of remaining upload chunk if needed
int i;
//upload file in even chunks
if (num_of_uploads > 0)
{
char buff1[max_upload_size+1] = {}; // array to save file too. add 1 for end of array symbol '\n'
for (i = 0; i < num_of_uploads; i++)
{
fread(buff1, sizeof(buff1)-1, 1, fp); // -1 as don't want to count the '\n'
http.addHeader("file_name", "file_name"); //header to say what the file name is
int httpResponseCode = http.POST((uint8_t *)buff1, sizeof(buff1)-1); //send data. Datatype is (uint8_t *)
}
}
//upload any remaining data
if (num_of_uploads_mod > 0)
{
int remainder = file_size - num_of_uploads * max_upload_size;
uint8_t buff2[remainder] = {};
fread(buff2, sizeof *buff2, sizeof buff2 / sizeof *buff2, fp);
http.addHeader("file_name", "file_name");
http.addHeader("Content-Type", "application/octet-stream");
int httpResponseCode = http.POST(buff2, sizeof(buff2));
}
http.end(); // Close connection
delay(10 * 1000);
}
thanks so much.
Unfortunately, this isn't straight-forward. You can either use the SD component directly or mount the correct file system driver (typically FatFs for an SD card). To use fopen, you need to register the correct driver first, hints can be found here: https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/storage/fatfs.html#using-fatfs-with-vfs-and-sd-cards
I haven't tried this myself yet, but the magic function seems to be esp_vfs_fat_sdspi_mount that should enable the use of fopen with the SD card over SPI. The official documentation lacks a real-world example, but you might find something in this thread or via your preferred search engine. For further help, you might want to ask a question on arduino.se instead, where a number of experienced ESP32 experts are present.
I struggled myself with using SD Cards (fat32) on my ESP32.
When trying to open my file using
std::ofstream dataFile("/sdcard/data.json", std::ofstream::out);
It wouldn't create my file. a sys/stat would thus give a -1. Turned out that you really need to use the 8.3 naming convention for FAT32. There's no "MS windows-magic" That abbreviates the file to: sdcard.j~1 etc. So just use a correct file name. not "/sdcard/mylomgfilename.exotic_extention" but just a "/mpoint/12345678.123" filename like "/sdcard/data.txt".
So I have two ESP32s for this project, one sending BLE scanned device info and the other ESP32 sending the scan results to an MQTT broker. I am currently facing the issue where I cannot break the results up into multiple JSON lines and send them out to the MQTT broker line by line. Please do let me know if you have any solutions. Thank you!!
#include <WiFi.h> //Remove when not MQTT-ing using WiFi
#include <PubSubClient.h>
const char* ssid = "--------";
const char* password = "+++++++++++";
#define RXD2 16
#define TXD2 17
WiFiClient espClient;
PubSubClient client(espClient);
// MQTT Broker
const char* mqtt_broker = "broker.hivemq.com";
const char* topic = "**********";
const int mqtt_port = 1883;
void setup() {
Serial.begin(115200);
Serial2.begin(115200, SERIAL_8N1, RXD2, TXD2);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println("Connecting to WiFi..");
}
Serial.println("Connected to the WiFi network");
//connecting to a mqtt broker
client.setServer(mqtt_broker, mqtt_port);
while (!client.connected()) {
String client_id = "esp32-client-";
client_id += String(WiFi.macAddress());
Serial.printf("The client %s connects to the public mqtt broker\n", client_id.c_str());
if (client.connect(client_id.c_str())) {
Serial.println("Public hivemq broker connected");
} else {
Serial.print("failed with state ");
Serial.print(client.state());
delay(2000);
}
}
}
void loop() {
// put your main code here, to run repeatedly:
String msg = "";
msg = Serial2.readString();
//String msg = "test MQTT";
// publish
int index = msg.lastIndexOf('}');
int length = msg.length();
String subMsg = msg.substring(index, length);
client.publish(topic,subMsg.c_str());
Serial.println("Message has been sent is: ");
Serial.println(subMsg.c_str();
delay(5000);
}
This is the output that I have:
{"Device Name":"GXHGA22CF3B9","EDID":"d4:0b:dd:2c:f3:b9","RTID":"FF005802600001F","RSSI":"-77"}
{"Device Name":"","EDID":"d7:9c:0e:1d:e6:a2","RTID":"FF005802600001F","RSSI":"-71"}
{"Device Name":"Buds2","EDID":"d8:4d:72:1f:80:15","RTID":"FF005802600001F","RSSI":"-75"}
{"Device Name":"KBPro_185309","EDID":"dd:34:02:06:33:a8","RTID":"FF005802600001F","RSSI":"-87"}
{"Device Name":"GXHGA2DAEC2A","EDID":"de:1e:da:da:ec:2a","RTID":"FF005802600001F","RSSI":"-86"}
{"Device Name":"","EDID":"e9:c7:1b:79:e1:41","RTID":"FF005802600001F","RSSI":"-76"}
{"Device Name":"","EDID":"e9:f5:80:7f:c8:ea","RTID":"FF005802600001F","RSSI":"-89"}
{"Device Name":"","EDID":"ef:e0:22:b2:c6:d0","RTID":"FF005802600001F","RSSI":"-84"}
{"Device Name":"GXHGA20A5D4A","EDID":"f6:4e:4d:0a:5d:4a","RTID":"FF005802600001F","RSSI":"-84"}
{"Device Name":"","EDID":"ff:65:fa:78:7f:c1","RTID":"FF005802600001F","RSSI":"-93"}
{"Device Name":"","EDID":"00:64:0f:26:92:09","RTID":"FF005802600001F","RSSI":"-90"}
Your current code finds the last } in the message and then takes that as the starting point for a substring to the end of the message. So you will always get a } character. You need to loop through the messages in a single read and find the start and end braces, pulling out each message.
Something like this:
void loop() {
// put your main code here, to run repeatedly:
String msg = "";
msg = Serial2.readString();
int start_idx = 0 ;
while( start_idx >= 0 )
{
start_idx = msg.indexOf('{',start_idx);
if ( start_idx >= 0 )
{
int end_idx = msg.indexOf('}',start_idx+1);
String subMsg = msg.substring(start_idx, end_idx+1);
client.publish(topic,subMsg.c_str());
Serial.println("Message has been sent is: ");
Serial.println(subMsg.c_str();
start_idx = end_idx + 1;
}
}
}
Note - this assumes that the JSON doesn't contain any objects - since the internal braces will also be separated. It also assumes you get complete JSON messages with each Serial read (i.e. they're not truncated). So you may need to handle these cases - but this should give you a start.
I've also removed the delay - I don't know why you'd want to delay for 5 seconds between reads - unless this was just for testing.
i am trying to connect ESP32 with google cloude
but i am getting this error
Settings incorrect or missing a cyper for SSL
Connect with mqtt.2030.ltsapis.goog:8883
ClientId: projects/nomadic-armor-279716/locations/asia-east1/registries/iot-sample-registry/devices/esp32newD
Waiting 60 seconds, retry will likely fail
my code is divided over 4 files :
esp32main :
#include "esp32-mqtt.h"
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
pinMode(LED_BUILTIN, OUTPUT);
setupCloudIoT();
}
void loop() {
mqttClient->loop();
delay(10); // <- fixes some issues with WiFi stability
if (!mqttClient->connected()) {
connect();
}
}
ciotic_config.h
// This file contains your configuration used to connect to Cloud IoT Core
#include "credentials.h"
// Wifi newtork details.
const char *ssid = WIFI_SSID;
const char *password = WIFI_PASSWD;
// Cloud iot details.
const char *project_id = PROJECT_ID;
const char *location = REGION;
const char *registry_id = REGISTRY;
const char *device_id = DEVICE;
// Configuration for NTP
const char* ntp_primary = "pool.ntp.org";
const char* ntp_secondary = "time.nist.gov";
#ifndef LED_BUILTIN
#define LED_BUILTIN 5
#endif
// To get the private key run (where private-key.pem is the ec private key
// used to create the certificate uploaded to google cloud iot):
// openssl ec -in <private-key.pem> -noout -text
// and copy priv: part.
// The key length should be exactly the same as the key length bellow (32 pairs
// of hex digits). If it's bigger and it starts with "00:" delete the "00:". If
// it's smaller add "00:" to the start. If it's too big or too small something
// is probably wrong with your key.
const char *private_key_str =
// Replace this below string with your own, in the same format
// The below key is dummy, so using it will not help you in any way
"f3:36:fe:81:72:36:77:60:29:1d:4a:fc:21:c7:6c:"
"96:75:2c:7f:6e:52:2f:c8:cb:7d:03:c8:25:ef:28:"
"61:0b";
// Time (seconds) to expire token += 20 minutes for drift
const int jwt_exp_secs = 3600; // Maximum 24H (3600*24)
// To get the certificate for your region run:
// openssl s_client -showcerts -connect mqtt.googleapis.com:8883
// for standard mqtt or for LTS:
// openssl s_client -showcerts -connect mqtt.2030.ltsapis.goog:8883
// Copy the certificate (all lines between and including ---BEGIN CERTIFICATE---
// and --END CERTIFICATE--) to root.cert and put here on the root_cert variable.
const char *root_cert =
"-----BEGIN CERTIFICATE-----\n"
"MIIDfDCCAmSgAwIBAgIJAJB2iRjpM5OgMA0GCSqGSIb3DQEBCwUAME4xMTAvBgNV\n"
"BAsMKE5vIFNOSSBwcm92aWRlZDsgcGxlYXNlIGZpeCB5b3VyIGNsaWVudC4xGTAX\n"
"BgNVBAMTEGludmFsaWQyLmludmFsaWQwHhcNMTUwMTAxMDAwMDAwWhcNMzAwMTAx\n"
"MDAwMDAwWjBOMTEwLwYDVQQLDChObyBTTkkgcHJvdmlkZWQ7IHBsZWFzZSBmaXgg\n"
"eW91ciBjbGllbnQuMRkwFwYDVQQDExBpbnZhbGlkMi5pbnZhbGlkMIIBIjANBgkq\n"
"hkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzWJP5cMThJgMBeTvRKKl7N6ZcZAbKDVA\n"
"tNBNnRhIgSitXxCzKtt9rp2RHkLn76oZjdNO25EPp+QgMiWU/rkkB00Y18Oahw5f\n"
"i8s+K9dRv6i+gSOiv2jlIeW/S0hOswUUDH0JXFkEPKILzpl5ML7wdp5kt93vHxa7\n"
"HswOtAxEz2WtxMdezm/3CgO3sls20wl3W03iI+kCt7HyvhGy2aRPLhJfeABpQr0U\n"
"ku3q6mtomy2cgFawekN/X/aH8KknX799MPcuWutM2q88mtUEBsuZmy2nsjK9J7/y\n"
"hhCRDzOV/yY8c5+l/u/rWuwwkZ2lgzGp4xBBfhXdr6+m9kmwWCUm9QIDAQABo10w\n"
"WzAOBgNVHQ8BAf8EBAMCAqQwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMC\n"
"MA8GA1UdEwEB/wQFMAMBAf8wGQYDVR0OBBIEELsPOJZvPr5PK0bQQWrUrLUwDQYJ\n"
"KoZIhvcNAQELBQADggEBALnZ4lRc9WHtafO4Y+0DWp4qgSdaGygzS/wtcRP+S2V+\n"
"HFOCeYDmeZ9qs0WpNlrtyeBKzBH8hOt9y8aUbZBw2M1F2Mi23Q+dhAEUfQCOKbIT\n"
"tunBuVfDTTbAHUuNl/eyr78v8Egi133z7zVgydVG1KA0AOSCB+B65glbpx+xMCpg\n"
"ZLux9THydwg3tPo/LfYbRCof+Mb8I3ZCY9O6FfZGjuxJn+0ux3SDora3NX/FmJ+i\n"
"kTCTsMtIFWhH3hoyYAamOOuITpPZHD7yP0lfbuncGDEqAQu2YWbYxRixfq2VSxgv\n"
"gWbFcmkgBLYpE8iDWT3Kdluo1+6PHaDaLg2SacOY6Go=\n"
"-----END CERTIFICATE-----\n";
// In case we ever need extra topics
const int ex_num_topics = 0;
const char* ex_topics[ex_num_topics];
//const int ex_num_topics = 1;
//const char* ex_topics[ex_num_topics] = {
// "/devices/my-device/tbd/#"
//};
credentials.h
#define WIFI_SSID "Taha"
#define WIFI_PASSWD "mkt193540"
#define PROJECT_ID "nomadic-armor-279716"
#define REGION "asia-east1"
#define REGISTRY "iot-sample-registry"
#define DEVICE "esp32newD"
esp32-mqtt.h
// This file contains static methods for API requests using Wifi / MQTT
#ifndef __ESP32_MQTT_H__
#define __ESP32_MQTT_H__
#include <Client.h>
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <MQTT.h>
#include <CloudIoTCore.h>
#include <CloudIoTCoreMqtt.h>
#include "ciotc_config.h" // Update this file with your configuration
// The MQTT callback function for commands and configuration updates
// Place your message handler code here.
void messageReceived(String &topic, String &payload) {
Serial.println("incoming: " + topic + " - " + payload);
int ledonpos=payload.indexOf("ledon");
if (ledonpos != -1) {
// If yes, switch ON the ESP32 internal led
Serial.println("Switch led on");
digitalWrite(LED_BUILTIN, HIGH);
} else {
// If no, switch off the ESP32 internal led
Serial.println("Switch led off");
digitalWrite(LED_BUILTIN, LOW);
}
}
/////////////////////////////////////////////
// Initialize WiFi and MQTT for this board //
Client *netClient;
CloudIoTCoreDevice *device;
CloudIoTCoreMqtt *mqtt;
MQTTClient *mqttClient;
unsigned long iss = 0;
String jwt;
/*
///////////////////////////////
// Helpers specific to this board
///////////////////////////////
String getDefaultSensor() {
return "Wifi: " + String(WiFi.RSSI()) + "db";
}
*/
String getJwt() {
iss = time(nullptr);
Serial.println("Refreshing JWT");
jwt = device->createJWT(iss, jwt_exp_secs);
return jwt;
}
void setupWifi() {
Serial.println("Starting wifi");
WiFi.mode(WIFI_STA);
// WiFi.setSleep(false); // May help with disconnect? Seems to have been removed from WiFi
WiFi.begin(ssid, password);
Serial.println("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(100);
}
configTime(0, 0, ntp_primary, ntp_secondary);
Serial.println("Waiting on time sync...");
while (time(nullptr) < 1592336214) {
delay(10);
}
}
void connectWifi() {
Serial.print("checking wifi...");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(1000);
}
}
void connect() {
connectWifi();
mqtt->mqttConnect();
}
void setupCloudIoT() {
device = new CloudIoTCoreDevice(
project_id, location, registry_id, device_id,
private_key_str);
setupWifi();
netClient = new WiFiClientSecure();
mqttClient = new MQTTClient(512);//1024
mqttClient->setOptions(180, true, 1000); // keepAlive, cleanSession, timeout
mqtt = new CloudIoTCoreMqtt(mqttClient, netClient, device);
mqtt->setUseLts(true);
mqtt->startMQTT();
}
#endif //__ESP32_MQTT_H__
this code suppose to communicate with cloud and receive "ledon" or "ledoff" and implement the command.
First post in here. I was trying the same thing here and just got comm between my ESP8266 and GCP. I've learned three major things:
ESP32 and ESP8266 share a few libraries that are not compatible. You need to select the right one.
On root_cert you need to put the RSA_key
On private key (on firmware) you put the EC_private, while in the IoT Core you put the ec_public.
Good luck.
I want to send data from an end device to a coordinator with XBee and Arduino. But, the Arduino reboots when sending data (sending data was aborted). What could the problem be?
/* Transmit */
#include <SoftwareSerial.h>
#include <XBee.h>
int end = 1;
int alim_XbeeRS = A7;
int RX_XBee = 14;
int TX_XBee = 15;
XBee xbee = XBee();
//Allume le périphérique
void powerOn(SoftwareSerial portcom)
{
portcom.begin(57600);
digitalWrite(alim_XbeeRS, HIGH);
}
void setup ()
{
SoftwareSerial XbeeRS(RX_XBee,TX_XBee);
Serial.begin(57600);
XbeeRS.begin(57600);
pinMode(RX_XBee, INPUT); // Rx
pinMode(TX_XBee, OUTPUT); // Tx
pinMode(alim_XbeeRS, OUTPUT);
powerOn(XbeeRS);
xbee.setSerial(XbeeRS);
delay(5000);
Serial.println("XBee OP");
}
void loop()
{
if (end == 1)
{
Serial.println("sending");
ZBTxRequest _zbTx;
uint8_t payload[] = {'Y','E','S','\0'};
XBeeAddress64 address = XBeeAddress64 (0x13A200,0x4081B77C );
_zbTx = ZBTxRequest(address, payload, sizeof(payload));
Serial.println("sending");
xbee.send(_zbTx); // The program blocks here
}
else
{
Serial.println("waiting");
xbee.readPacket(100);
if (xbee.getResponse().isAvailable())
{
Serial.println("waiting 1");
if( xbee.getResponse().getApiId() == ZB_RX_RESPONSE)
{
Serial.println("waiting 2");
ZBRxResponse _rx;
xbee.getResponse().getZBRxResponse(_rx);
uint8_t* response= new uint8_t[50];
for(int i=0; i<_rx.getDataLength(); i++)
{
response[i] = _rx.getData()[i];
Serial.println(char(response[i]));
}
}
}
}
}
EDIT (additional information):
It doesn't change anything if I change the value type in the payload. About the baud rate, both of XBees are configured to 57600 baud. Here is the XBee's configuration:
ENDEVICE
COORDINATOR
The result from the serial port of this device is:
Finally, I use the Arduino ATmega 1284P. I really have no idea what kind of problem could do this.
There is some trouble :/
First, the default coordinator ADD is 0x0 0x0, so the line where
XBeeAddress64 address = XBeeAddress64 (0x13A200,0x4081B77C );
should be
XBeeAddress64 address = XBeeAddress64 (0x0,0x0 );
Then, is the Xbee at 57600 baud too?
To get an ACK, you can use:
if (xbee.readPacket(1000))
{
if (xbee.getResponse().getApiId() == ZB_TX_STATUS_RESPONSE)
{
xbee.getResponse().getZBTxStatusResponse(txStatus);
if (txStatus.getDeliveryStatus() == SUCCESS)
{
//It's sent
}
}
It could be from you payload too. You better use a hexadecimal value or int to be sure of what you send.
EDIT:
I see you don't use the last version of Xctu. Try it and test the direct communication between them to see if you can have direct contact between Coordinator and Routeur/End device.
The current problem I am facing with my project is that I do not know how to read/write files from the native node.js addon.
I have to build a type of encryption decryption ( RC6 algorithm ) program. But in order to encrypt files, i should be able to somehow read and write to them from "node-webkit". I am building the .cc file with nw-gyp, and tried multiple possibilities but none worked.
I am building my project with "grunt-node-webkit-builder" and I simply want to read/write one file from the build folder "nw" where nw.exe is located.
The Structure looks like this:
.webkitbuilds
.releases
.nw
.win
.nw
encrypt.txt
ffmpegsumo.dll
icudt.dll
libEGL.dll
libGLESv2.dll
nw.exe
nw.pak
How can I read in my c++ native node.js addon that "encrypt.txt" file.
Help ?
Edit:
Is there any way to use libuv with crypto ++ ?
EDIT 2:
I have the following code. The moment I execute it, the window freezes.
hello.cc:
#include <node.h>
#include <v8.h>
#include <stdio.h>
#include <fcntl.h>
using namespace v8;
#define __S_IREAD 0400 /* Read by owner. */
#define __S_IWRITE 0200 /* Write by owner. */
#define __S_IEXEC 0100 /* Execute by owner. */
#define S_IRUSR __S_IREAD /* Read by owner. */
uv_loop_t* loop;
uv_fs_t open_req;
void open_cb(uv_fs_t* req);
const char* path = "encrypt.txt";
void open_cb(uv_fs_t* req) {
int result = req->result;
if (result == -1) {
fprintf(stderr, "Error at opening file: %s\n",
uv_strerror(uv_last_error(loop)));
}
uv_fs_req_cleanup(req);
printf("Successfully opened file.\n");
}
char *get(v8::Local<v8::Value> value, const char *fallback = "") {
if (value->IsString()) {
v8::String::AsciiValue string(value);
char *str = (char *) malloc(string.length() + 1);
strcpy(str, *string);
return str;
}
char *str = (char *) malloc(strlen(fallback) + 1);
strcpy(str, fallback);
return str;
}
Handle<Value> Encrypt(const Arguments& args) {
HandleScope scope;
char* textToEncrypt = get(args[0], "str");
char* password = get(args[1], "str");
loop = uv_default_loop();
int r = uv_fs_open(loop, &open_req, path, O_RDONLY, S_IRUSR, open_cb);
if (r) {
fprintf(stderr, "Error at opening file: %s\n",
uv_strerror(uv_last_error(loop)));
}
uv_run(loop, UV_RUN_DEFAULT);
return scope.Close(String::New("done"));
}
void Init(Handle<Object> exports) {
exports->Set(String::NewSymbol("Encrypt"),
FunctionTemplate::New(Encrypt)->GetFunction());
}
NODE_MODULE(hello, Init)
In Javascript :
var application = require('./js/build/Release/hello');
var encrypted_data = "";
$(document).ready(function() {
$('#btn_encrypt').on('click', function() {
encrypted_data = application.Encrypt("val","val");
console.log(encrypted_data);
})
});