ESP module connect and worked in PostgreSQL in Heroku - heroku

I want to put a record in the PostgreSQL database of my application, which I deploy through the Heroku website(RoR).
I need to do this with ESP-01/12 module.
I can not find any complete example of connecting and executing the sql statement on the pg database in C.
My code:
#include <ESP8266WiFi.h>
/* Wi fi */
const char* ssid = "ssid";
const char* password = "password";
/* database */
const char* host = "***.compute-1.amazonaws.com";
const char* database = "database";
const char* user = "user";
const char* streamId = "???";
const char* privateKey = "password?";
void setup() {
delay(1000);
Serial.begin(115200); delay(10); Serial.println('\n');
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password); Serial.print("Connecting to "); Serial.print(ssid); Serial.println(" ...");
int i = 0;
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(++i); Serial.print(' ');
}
Serial.println("Connection established!");
Serial.print("IP address:\t");
Serial.println(WiFi.localIP());
WiFi.printDiag(Serial);
}
void loop() {
delay(5000);
Serial.print("connecting to ");
Serial.println(host);
// Use WiFiClient class to create TCP connections
WiFiClient client;
const int httpPort = 5432;
if (client.connect(host, httpPort)) {
Serial.println("OK!");
}
client.print("psql -U user --password password? -p 5432 -h host -d database \r\n");
delay(10);
// Read all the lines of the reply from server and print them to Serial
while (client.available()) {
String line = client.readStringUntil('\r');
Serial.print(line);
}
Serial.println();
Serial.println("closing connection");
}
It seems to me that I connected to port 5432, but I do not know what to do next with the line below, to get some answer:
client.print()
I assume that after connecting to port 5432, I can send text that appears on the other side as on the command line and the psql program is available there. I made such a connection from the computer, the same line as in the code and I got access.
Help me, please get to my database from the ESP module in C. I noticed that despite entering the password after the psql command I have to give it again, but I can not register the answer of the command line coming from the other side, for example "please enter password".
Yes, I helped myself with a translator, I speak Polish.

client.print() is to write some data to the WifiClient. I think is some command on the Database. If you need to add data to the PostgreSQL Database you can create some API endpoint with the SQL queries. It will be solve your problem.
Refer this Repo
This will explains how to create a NodeJS API to capture the Data sent from ESP8266 and Write them into Firebase Database. You can clone it and change the Database part. Arduino part is same and You need to install the ArduinoJSON Library. Hope you understand.

Related

Trouble with connecting to wifi in code in Xamarin

I've been trying to connect to a specific wifi through code, but with no succcess.
This is what i've come up with:
public void ConnectToWifi(string ssid, string password)
{
WifiManager wifiManager = (WifiManager)Android.App.Application.Context.GetSystemService(Context.WifiService);
if (!wifiManager.IsWifiEnabled)
{
wifiManager.SetWifiEnabled(true);
}
string formattedSsid = $"\"{ssid}\"";
string formattedPassword = $"\"{password}\"";
WifiConfiguration wifiConfig = new WifiConfiguration
{
Ssid = formattedSsid,
PreSharedKey = formattedPassword
};
var addNetwork = wifiManager.AddNetwork(wifiConfig);
WifiConfiguration network = wifiManager.ConfiguredNetworks.FirstOrDefault(n => n.Ssid == ssid);
if (network == null)
{
Console.WriteLine($"Cannot connect to network: {ssid}");
return;
}
wifiManager.Disconnect();
bool enableNetwork = wifiManager.EnableNetwork(network.NetworkId, true);
}
I've added permissions.
When testing it does turn the wifi on atleast, so i know it works until that point. What seems not to be working is the AddNetwork part.
I appreciate any help i can get!
You are missing one key method - reconnect(). You can read more about it in the WifiManager's docs here
The important part of the documentation is:
Reconnect to the currently active access point, if we are currently disconnected.
So, what you need to do it after you have disconnected and enabled your new network, call in the end this and you will be good to go:
wifiManager.Disconnect();
wifiManager.EnableNetwork(network.NetworkId, true);
wifiManager.Reconnect(); // This is the missing method
NB: Keep in mind that most of the WifiManager's code that you are using is being obsolete starting Android 10. So, if you want to target Android 10, then you will need to write an additional code for the connectivity for devices with Android 10+.

Query Oracle using .net core throws exception for Connect Identifier

I'm quite new to Oracle and never used that before, now, I'm trying to query an Oracle database from a .Net Core Web Application having nuget package oracle.manageddataaccess.core installed and using an alias as the Data Source but I'm receiving the following error:
If I use the full connection string the query will work correctly
ORA-12154: TNS:could not resolve the connect identifier specified
at OracleInternal.Network.AddressResolution..ctor(String TNSAlias, SqlNetOraConfig SNOConfig, Hashtable ObTnsHT, String instanceName, ConnectionOption CO)
at OracleInternal.Network.OracleCommunication.Resolve(String tnsAlias, ConnectionOption& CO)
at OracleInternal.ConnectionPool.PoolManager`3.ResolveTnsAlias(ConnectionString cs, Object OC)
at OracleInternal.ServiceObjects.OracleConnectionImpl.Connect(ConnectionString cs, Boolean bOpenEndUserSession, OracleConnection connRefForCriteria, String instanceName)
So, from a few links I could understand that there is a tsnnames.ora file which must contain the map between connect identifiers and connect descriptors. And that this file can be found at the machine on which the Oracle has been installed with the path ORACLE_HOME\network\admin.
Question is:
Does the alias name that I'm using in my connection string which reads as Data Source: <alias_name>; User ID=<user>; Password=<password> need to be specified in the tsnnames.ora file? I don't have access to the machine where the Oracle database resides on otherwise I would have checked it earlier.
Here's the code snippet for more info: connection string and query values are mocked out
public static string Read()
{
const string connectionString = "Data Source=TestData;User ID=User1;Password=Pass1";
const string query = "select xyz from myTable";
string result;
using (var connection = new OracleConnection(connectionString))
{
try
{
connection.Open();
var command = new OracleCommand(query) { Connection = connection, CommandType = CommandType.Text };
OracleDataReader reader = command.ExecuteReader();
reader.Read();
result = reader.GetString(0);
}
catch (Exception exception)
{
Console.WriteLine(exception);
throw;
}
}
return result;
}
Is this enough or something else needs to be added/changed in here? Or probably the issue is with the tsnNames.ora file which might not contain the alias name here?
Thanks in advance
For the Data source
Data Source=TestData;User Id=myUsername;Password=myPassword;
Your tnsnames.ora probably should have the below entry
TestData=(DESCRIPTION=
(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=MyHost) (PORT=MyPort)))
(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=MyOracleSID)))
Since
Data Source=TestData;User Id=myUsername;Password=myPassword;
is same as
Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=MyHost) (PORT=MyPort)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=MyOracleSID)));User Id=myUsername;Password=myPassword;

JSCH how to get server answer in shell, in order validate commands to unlock a luks partition remotelly [duplicate]

I'm trying to manage router via Java application using Jcraft Jsch library.
I'm trying to send Router Config via TFTP server. The problem is in my Java code because this works with PuTTY.
This my Java code:
int port=22;
String name ="R1";
String ip ="192.168.18.100";
String password ="root";
JSch jsch = new JSch();
Session session = jsch.getSession(name, ip, port);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
System.out.println("Establishing Connection...");
session.connect();
System.out.println("Connection established.");
ChannelExec channelExec = (ChannelExec)session.openChannel("exec");
InputStream in = channelExec.getInputStream();
channelExec.setCommand("enable");
channelExec.setCommand("copy run tftp : ");
//Setting the ip of TFTP server
channelExec.setCommand("192.168.50.1 : ");
// Setting the name of file
channelExec.setCommand("Config.txt ");
channelExec.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
int index = 0;
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
System.out.println(line);
}
session.disconnect();
I get
Line has an invalid autocommand '192.168.50.1'
The problem is how can I run those successive commands.
Calling ChannelExec.setCommand multiple times has no effect.
And even if it had, I'd guess that the 192.168.50.1 : and Config.txt are not commands, but inputs to the copy run tftp : command, aren't they?
If that's the case, you need to write them to the command input.
Something like this:
ChannelExec channel = (ChannelExec) session.openChannel("exec");
channelExec.setCommand("copy run tftp : ");
OutputStream out = channelExec.getOutputStream();
channelExec.connect();
out.write(("192.168.50.1 : \n").getBytes());
out.write(("Config.txt \n").getBytes());
out.flush();
In general, it's always better to check if the command has better "API" than feeding the commands to input. Commands usually have command-line arguments/switches that serve the desired purpose better.
A related question: Provide inputs to individual prompts separately with JSch.

IBM IOT C# client thowing invalid ip address exception when constructing gatewayclient

I am beginning to use the sample IBM-IOT C# sample code as per
https://github.com/ibm-watson-iot/iot-csharp/blob/master/docs/Gateway.rst
however I get "An invalid IP address was specified." thrown when the gateway constructor is called using the org id.
I'm using an orgid of 'p3wg4w' (set in config and accessed as a string property Globals.WatsonOrgID" )
my code is
private static void InitGatewayClient()
{
if (gw == null)
{
gw = new GatewayClient(Globals.WatsonOrgID,
Globals.WatsonGatewayDeviceType,
Globals.WatsonGatewayDeviceID,
Globals.WatsonAuthMethod,
Globals.WatsonToken);
gw.commandCallback += processCommand;
gw.errorCallback += processError;
gw.connect();
Console.WriteLine("Gateway connected");
Console.WriteLine("publishing gateway events..");
}
}
Has anyone seen this before ?
check if you can access or if you can:
telnet p3wg4w.messaging.internetofthings.ibmcloud.com 8883
The libraries aren't using any IP to create the connection, it is using the below vars
public static string DOMAIN = ".messaging.internetofthings.ibmcloud.com";
public static int MQTTS_PORT = 8883;
I can only think that your firewall is blocking the connection
I've used the below sample and worked just fine for me:
https://github.com/ibm-watson-iot/iot-csharp/blob/master/sample/Gateway/SampleGateway.cs

Can't Connect Node MCU esp8266 to Thingspeak

I am using this tutorial. I am also using a same Node MCU ESP8266. Ii connected it to my home network. The local ip address is also displayed but it doesn't connected to my thingspeak channel and it stuck at the waiting for the client.
I also checked that my thingspeak API is correct and my home network is also working.
It looks like you are using the Arduino IDE to program the NodeMCU. If this is the case, then all you have to do create a WiFiClient, then construct an HTTP POST request, and send it to ThingSpeak using the client.
Here are the relevant lines from my tutorial:
Before your setup add the lines:
#include <ESP8266WiFi.h>
WiFiClient client;
const char* server = "api.thingspeak.com";
String writeAPIKey = "XXXXXXXXXXXXXXXX";
In your loop, add the following lines to read A0 and send it to ThingSpeak:
if (client.connect(server, 80)) {
// Measure Analog Input (A0)
int valueA0 = analogRead(A0);
// Construct API request body
String body = "field1=";
body += String(valueA0);
Serial.print("A0: ");
Serial.println(valueA0);
client.print("POST /update HTTP/1.1\n");
client.print("Host: api.thingspeak.com\n");
client.print("Connection: close\n");
client.print("X-THINGSPEAKAPIKEY: " + writeAPIKey + "\n");
client.print("Content-Type: application/x-www-form-urlencoded\n");
client.print("Content-Length: ");
client.print(body.length());
client.print("\n\n");
client.print(body);
client.print("\n\n");
}
client.stop();
// wait 20 seconds and post again
delay(20000);
Use ESP8266HTTPClient HTTP lib to post to ThingSpeak via ESP8266. Here is an example function. Call it with a data parameter to write into your ThingSpeak channel:
#include <ESP8266HTTPClient.h>
#define TSPEAK_HOST "http://api.thingspeak.com"
#define TSPEAK_API_KEY "YOUR_THINGSPEAK_API_KEY"
#define LEN_HTTP_PATH_MAX 256
HTTPClient http;
unsigned short postThingSpeak(char* data)
{
boolean httpCode = 0;
char httpPath[LEN_HTTP_PATH_MAX];
memset(httpPath, 0, LEN_HTTP_PATH_MAX);
snprintf(httpPath, LEN_HTTP_PATH_MAX, "%s/update?api_key=%s&field1=%s", TSPEAK_HOST, TSPEAK_API_KEY, data);
Serial.printf("Path to post : %s\n", httpPath);
http.begin(httpPath);
httpCode = http.GET();
Serial.printf("Return : %d\n", httpCode);
Serial.printf("Incoming Body : %s\n", http.getString().c_str());
http.end();
return httpCode;
}

Resources