Arduino Ethernet Shield connection to socket server - sockets

I'm using an ethernet shield for Arduino to connect it to a socket server (different computer) so that I can receive messages from it to activate some routine. Here is my code:
#include <Ethernet.h>
#include <SPI.h>
byte mac[] = { 0x90, 0xA2, 0xDA, 0x0F, 0x5A, 0x21 };
byte ip[] = { 192,168,1,11 }; //ip shield
byte server[] = { 192,168,1,7 }; // ip server
EthernetClient client;
String readString;
int ledPins[] = {19, 17, 2,3, 5, 6, 7, 8, 9}; // leds pins
int pinCount = 8;// number of leds
int const PINEYES = 9; //pin for different led
int const TIMERLEDS = 1000;
int const TIMERTOOFF= 3000;
//--------------------------------------------------------------------------
void setup() {
turnOffLeds();
Ethernet.begin(mac, ip);
Serial.begin(9600);
delay(1000);
Serial.println("connecting...");
if (client.connect(server, 1400)) {
Serial.println("connected");
client.println();
} else {
Serial.println("connection failed");
}
pinMode(PINEYES, OUTPUT);
int thisPin;
for (int thisPin = 0; thisPin < pinCount; thisPin++) {
pinMode(ledPins[thisPin], OUTPUT);
}
}
//--------------------------------------------------------------------------
void loop() {
if (client.available()) {
char c = client.read();
if (readString.length() < 30) {
if(c!='|')
readString.concat(c);
else {
client.flush();
//if (readString == "START_SENSATIONS") {
if (readString == "on") {
Serial.println("recebi");
client.stop();
turnOnMaya();
}
resetString();
}
}
Serial.println(readString);
}
if (!client.connected()) {
Serial.println();
Serial.println("disconnecting.");
client.stop();
for(;;)
;
}
}
//--------------------------------------------------------------------------
void turnOnMaya(){
turnOnLeds();
for (int thisPin = 0; thisPin < pinCount; thisPin++) {
delay(TIMERLEDS);
digitalWrite(ledPins[thisPin], LOW);
}
turnOnEyes();
delay(TIMERTOOFF);
turnOffLeds();
digitalWrite(PINEYES, LOW);
client.connect(server, 1400);
}
//--------------------------------------------------------------------------
void turnOnLeds(){
for (int thisPin = 0; thisPin < pinCount; thisPin++) {
digitalWrite(ledPins[thisPin], HIGH);
}
}
//--------------------------------------------------------------------------
void turnOffLeds(){
for (int thisPin = 0; thisPin < pinCount; thisPin++) {
digitalWrite(ledPins[thisPin], LOW);
}
}
//--------------------------------------------------------------------------
void turnOnEyes(){
digitalWrite(PINEYES, 255);
}
//--------------------------------------------------------------------------
void resetString() {
readString = "";
}
The problem is, when my server stops or is not available for some moments, I need my Arduino to keep on trying to connect to it until it is available again. But I can't make this work.
I tried this:
while(!client.available()){
Serial.println("connection failed, trying again...");
client.connect(server, 1400);
delay(1000);
}
But it doesn't work. It just prints "connection failed, trying again..." forever. How can I do this?
Thanks!

I'm assuming that the server in your PC is a normal java or c (or any other standard tcp server)
But your arduino client doesn't specify that it is TCP. So either change your server or the client(like in here - this uses wifi connection).
If your server is in java, it could be like this:
int port=9999;
try{
System.out.println("Starting server...");
ServerSocket ss=new ServerSocket(port);
Socket clientSocket=ss.accept();
System.out.println("Connection has been established...");
PrintWriter out=new PrintWriter(clientSocket.getOutputStream(),true);
BufferedReader br=new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine;
System.out.println("Listening.....");
while((inputLine=br.readLine())!=null)
System.out.println(inputLine);
}catch(Exception e){System.out.println(e.getMessage());}

Related

Serial communication with jSerialComm not sending anything

I built a simple Scala application and a simple Arduino script to test serial communication on the jSerialComm library. The program only finds one active port (the one the Arduino connected to), the baud rates are the same on the port and the Arduino and the code throws no exceptions while writing. The Arduino, however, receives nothing (the RX led is off).
The Scala code:
import com.fazecast.jSerialComm._
object Test extends App {
val ports = SerialPort.getCommPorts
ports.foreach(println(_))
val port: SerialPort = ports(0)
var bytes = Array[Byte]()
val toWrite: Long = 3
var a = 0
var b = 0
var c = 0
println(port.getBaudRate)
while (true) {
if (a < 3) a += 1 else a = 0
bytes = Array[Byte](a.toByte, a.toByte, a.toByte)
port.writeBytes(bytes, toWrite)
println("Sent " + bytes(0) + " to " + port.toString)
Thread.sleep(1000)
}
}
The Arduino code:
const int R = 12;
const int G = 13;
const int B = 11;
void setup() {
pinMode(R, OUTPUT);
pinMode(G, OUTPUT);
pinMode(B, OUTPUT);
Serial.begin(9600);
while(!Serial);
}
void loop() {
byte buff[3] = {0, 0, 0};
int numR = 0;
bool cont1 = false;
bool cont2 = false;
bool cont3 = false;
if(Serial.available()){
Serial.print("Found stuff");
Serial.readBytes(buff,3);
}
for(int i = 0; i < 3; i++){
if(buff[i] == 1){
cont1 = true;
}
if(buff[i] == 2){
cont2 = true;
}
if(buff[i] == 3){
cont3 = true;
}
}
if(cont1) digitalWrite(R, HIGH); else digitalWrite(R, LOW);
if(cont2) digitalWrite(G, HIGH); else digitalWrite(G, LOW);
if(cont3) digitalWrite(B, HIGH); else digitalWrite(B, LOW);
if(cont1 || cont2 || cont3) delay(1000);
}
I had forgotten to open the port with
port.openPort()
Now it works just fine

I receiving unknow data in my esp 8266

I need upload my own program on esp8266 and i tried to upload a program for test and i see esp reset maybe evry 200 ms and i am receivig a lot of data on usart but isn't my data in program .data is something like exception and some bytes about stack and some data about load and reset again
this is my test code
#include <ESP8266WiFi.h>
#define MAX_SRV_CLIENTS 1
#define TCP_PORT (23)
WiFiServer tcpServer(TCP_PORT);
WiFiClient tcpServerClients[MAX_SRV_CLIENTS];
IPAddress apIP(192, 168, 1, 1);
const char SSID[] = "TCPUARTBridge";
const char PASSWORD[] = "12345678";
#define SerialDebug Serial1
#define SerialGPS Serial
#ifndef min
#define min(x,y) ((x)<(y)?(x):(y))
#endif
void setup() {
SerialDebug.begin(115200);
SerialDebug.println("TCP <-> UART bridge");
WiFi.mode(WIFI_AP);
WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0));
WiFi.softAP(SSID, PASSWORD);
SerialGPS.begin(9600);
tcpServer.begin();
tcpServer.setNoDelay(true);
SerialDebug.print("Ready! Use 'telnet or nc ");
SerialDebug.print(WiFi.localIP());
SerialDebug.print(' ');
SerialDebug.print(TCP_PORT);
SerialDebug.println("' to connect");
}
void loop() {
uint8_t i;
char buf[1024];
int bytesAvail, bytesIn;
if (tcpServer.hasClient()) {
for (i = 0; i < MAX_SRV_CLIENTS; i++) {
if (!tcpServerClients[i] || !tcpServerClients[i].connected()) {
if (tcpServerClients[i])
tcpServerClients[i].stop();
tcpServerClients[i] = tcpServer.available();
SerialDebug.print("New client: "); SerialDebug.print(i);
continue;
}
}
WiFiClient tcpServerClient = tcpServer.available();
tcpServerClient.stop();
}
for (i = 0; i < MAX_SRV_CLIENTS; i++) {
if (tcpServerClients[i] && tcpServerClients[i].connected()) {
while ((bytesAvail = tcpServerClients[i].available()) > 0) {
bytesIn = tcpServerClients[i].readBytes(buf, min(sizeof(buf), bytesAvail));
if (bytesIn > 0) {
SerialGPS.write(buf, bytesIn);
delay(0);
}
}
}
}
while ((bytesAvail = SerialGPS.available()) > 0) {
bytesIn = SerialGPS.readBytes(buf, min(sizeof(buf), bytesAvail));
if (bytesIn > 0) {
for (i = 0; i < MAX_SRV_CLIENTS; i++) {
if (tcpServerClients[i] && tcpServerClients[i].connected()) {
tcpServerClients[i].write((uint8_t*)buf, bytesIn);
delay(0);
}
}
}
}
}
Thank you for reading this

"No Socket Available" - Wifi Shield on Arduino

I have an LDR/Photocell which sends a value 1 or 0 (depending on the value) to a text file on my web address. The code works for a few seconds then prints out No Socket available.
Any help will be appreciated; code below.
#include <SPI.h>
#include <WiFi.h>
int LDR = A0;
int LED = 11;
char ssid[] = "SSID";
char password[] = "password";
int status = WL_IDLE_STATUS;
char server[] = "www.example.com";
int value;
void setup() {
Serial.begin(9600);
pinMode(LDR, INPUT);
pinMode(LED, OUTPUT);
connectWifi();
printWifiStatus();
// postData();
}
void loop() {
value = analogRead(LDR);
postData();
delay(10000);
}
void connectWifi() {
while (status != WL_CONNECTED) {
Serial.print("Attempting to connect to ");
Serial.println(ssid);
status = WiFi.begin(ssid, password);
delay(500);
}
}
void printWifiStatus() {
// Print the SSID of the network you're attached to
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// Print your WiFi shield's IP address
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
// Print the received signal strength
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
}
void postData() {
WiFiClient client;
if (client.connect(server, 80)) {
Serial.println("Connecting...");
if (value > 350) {
Serial.println("0");
digitalWrite(LED, LOW);
String data = "value=0";
client.print("GET /example/client.php?");
client.print(data);
client.println(" HTTP/1.1");
client.println("Host: www.example.com");
client.println("Connection: close");
client.println(); client.println();
//client.stop();
} else {
Serial.println("1");
digitalWrite(LED, HIGH);
String data = "value=1";
client.print("GET /example/client.php?");
client.print(data);
client.println(" HTTP/1.1");
client.println("Host: www.example.com");
client.println("Connection: close");
client.println(); client.println();
//client.stop();
}
} else {
Serial.println("Connection failed");
client.stop();
}
}
Output:
Attempting to connect to SSID
SSID: SSID
IP Address: 255.255.255.255
signal strength (RSSI):-47 dBm
Connecting...
1
Connecting...
0
Connecting...
0
Connecting...
0
No Socket available
Connection failed
No Socket available
Connection failed
No Socket available
Connection failed
No Socket available
Actual web address omitted.
first of all, try not use "delay()" and your are calling this function "postData()" every 0,5 seconds. Try use the millis() function to do the timer thing, like this:
unsigned long timerBefore = 0;
const int timer = 1000; //1 second
now inside your loop()
unsigned long timerNow=millis();
if((unsigned long)(timerNow-timerBefore)>=timer){
postData();
timerBefore=millis();
}
that code i'll not "pause" your microcontroller and will call that function every one second.

connect two ESP8266 to one MQTT broker cause hang

I have 2 ESP8266 PubSubClients who are connecting to MQTT broker installed on Raspberry PI3. I'm able to connect them and make a ON/OFF operation and its okay! but when I'm going to use both of them to operating its will be hang and stuck in reconnecting loop, when i turn one of them off, its work fine.
this is my code on ESP8266:
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
// Update these with values suitable for your network.
const char* ssid = "SSID";
const char* password = "PASSWORD";
const char* mqtt_server = "192.168.1.10";
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;
void setup() {
//pinMode(BUILTIN_LED, OUTPUT); // Initialize the BUILTIN_LED pin as an output
//Serial.begin(115200);
Serial.begin(9600);
pinMode(0, OUTPUT);
digitalWrite(0, HIGH);
pinMode(2, OUTPUT);
digitalWrite(2, HIGH);
pinMode(4, OUTPUT);
digitalWrite(4, HIGH);
pinMode(5, OUTPUT);
digitalWrite(5, HIGH);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
//1 ( pin 0 )
if (strcmp(topic,"/home/1/ard1/p1/com")==0) {
if (payload[0] == '0'){
digitalWrite(0, HIGH);
Serial.print("Turning Light ON");
delay(100);
client.publish("/home/1/ard1/p1/state","0");
}
else if (payload[0] == '1')
{
digitalWrite(0, LOW);
Serial.print("Turning Light OFF");
delay(100);
client.publish("/home/1/ard1/p1/state","1");
}
}
//2 ( pin 2 )
if (strcmp(topic,"/home/1/ard1/p2/com")==0) {
if (payload[0] == '0'){
digitalWrite(2, HIGH);
Serial.print("Turning Light ON");
delay(100);
client.publish("/home/1/ard1/p2/state","0");
}
else if (payload[0] == '1')
{
digitalWrite(2, LOW);
Serial.print("Turning Light OFF");
delay(100);
client.publish("/home/1/ard1/p2/state","1");
}
}
//3 ( pin 4 )
if (strcmp(topic,"/home/1/ard1/p3/com")==0) {
if (payload[0] == '0'){
digitalWrite(4, HIGH);
Serial.print("Turning Light ON");
delay(100);
client.publish("/home/1/ard1/p3/state","0");
}
else if (payload[0] == '1')
{
digitalWrite(4, LOW);
Serial.print("Turning Light OFF");
delay(100);
client.publish("/home/1/ard1/p3/state","1");
}
}
//4 ( pin 5 )
if (strcmp(topic,"/home/1/ard1/p4/com")==0) {
if (payload[0] == '0'){
digitalWrite(5, HIGH);
Serial.print("Turning Light ON");
delay(100);
client.publish("/home/1/ard1/p4/state","0");
}
else if (payload[0] == '1')
{
digitalWrite(5, LOW);
Serial.print("Turning Light OFF");
delay(100);
client.publish("/home/1/ard1/p4/state","1");
}
}
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("ESP8266Client")) {
Serial.println("connected");
// Once connected, publish an announcement...
client.publish("outTopic", "hello world");
client.subscribe("/home/1/ard1/#");
// ... and resubscribe
client.subscribe("inTopic");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
long now = millis();
if (now - lastMsg > 2000) {
lastMsg = now;
++value;
snprintf (msg, 75, "hello world #%ld", value);
Serial.print("Publish message: ");
Serial.println(msg);
client.publish("outTopic", msg);
}
}
I changed these below lines for one of them but the result is the same.
WiFiClient espClient;
PubSubClient client(espClient);
to:
WiFiClient espClient1;
PubSubClient client(espClient1);
Many Thanks.
Your problem is this line:
if (client.connect("ESP8266Client")) {
Every client needs a unique client id, hard coding it to ESP8266Client means that when the second client connects the broker will kick the first one off, which will then try and reconnect which will kick the second off. This just ends up stuck in a loop.

Socket Low Transfer Speed - Win7 .Net4 - CentOSx64 Mono 2.10

I have created a simple client/server app and it works great (1MB/s which is max speed i set for server to send) when i run in locally or under Lan network. But when i try to run it in one of my Dedicate Server/VPS my download speed become slow.
I am using CentOS on servers and Mono for running it, Mono version is 2.10.2 and CentOs is 64bit version. Created using framework 4.
Speed test:
Local: 1MB
Lan: 1MB
Running server on CentOS: 0~10~20 KB
My connection speed is 2Mb or ~250KB. It will give me full speed some times. But very rare and i cant see why it give my full speed sometimes and sometimes no speed at all or why sometimes only 10KB and other times only 20KB. Also, i am running client part on my Win7 Desktop. Here is code for server and client part:
Server:
class Program
{
private static BackgroundWorker _ListeningWorker;
private static BackgroundWorker _QWorker;
private static System.Net.Sockets.Socket _Server;
private static List<System.Net.Sockets.Socket> ConnectedClients = new List<System.Net.Sockets.Socket>();
static void Main(string[] args)
{
Program._ListeningWorker = new BackgroundWorker();
Program._ListeningWorker.WorkerSupportsCancellation = true;
Program._ListeningWorker.DoWork += _ListeningWorker_DoWork;
Program._QWorker = new BackgroundWorker();
Program._QWorker.WorkerSupportsCancellation = true;
Program._QWorker.DoWork += _QWorker_DoWork;
Program.Start();
while (true)
{
Console.Clear();
Console.WriteLine("1.0.0.1");
Console.WriteLine(Program.ConnectedClients.Count.ToString());
System.Threading.Thread.Sleep(1000);
}
}
public static bool Start()
{
if (!Program._ListeningWorker.IsBusy)
{
Program._Server = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, 8081);
Program._Server.Bind(ipLocal);
Program._Server.Listen(10);
Program._ListeningWorker.RunWorkerAsync();
Program._QWorker.RunWorkerAsync();
}
return true;
}
private static void _ListeningWorker_DoWork(object sender, DoWorkEventArgs e)
{
while (!Program._ListeningWorker.CancellationPending)
{
if (Program._Server.Poll(10, SelectMode.SelectRead))
{
lock (ConnectedClients)
{
Program.ConnectedClients.Add(Program._Server.Accept());
}
}
System.Threading.Thread.Sleep(1);
}
Program._Server.Close();
}
private static void _QWorker_DoWork(object sender, DoWorkEventArgs e)
{
byte[] array = new byte[1024];
Random random = new Random();
while (!Program._QWorker.CancellationPending)
{
if (ConnectedClients.Count > 0)
{
System.Net.Sockets.Socket[] st;
lock (ConnectedClients)
{
st = new System.Net.Sockets.Socket[Program.ConnectedClients.Count];
ConnectedClients.CopyTo(st);
}
foreach (System.Net.Sockets.Socket ser in st)
{
random.NextBytes(array);
try
{
ser.BeginSend(array, 0, array.Length, SocketFlags.None, (AsyncCallback)delegate(IAsyncResult ar)
{
try
{
ser.EndSend(ar);
}
catch (Exception)
{
iDissconnected(ser);
}
}, null);
}
catch (Exception)
{
iDissconnected(ser);
}
}
}
System.Threading.Thread.Sleep(1);
}
Program._Server.Close();
}
internal static void iDissconnected(System.Net.Sockets.Socket client)
{
lock (ConnectedClients)
for (int i = 0; i < ConnectedClients.Count; i++)
if (ConnectedClients[i].Equals(client))
{
ConnectedClients.RemoveAt(i);
i--;
}
}
}
Client:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter IP Address: ");
string Address = Console.ReadLine();
Console.WriteLine();
ushort Port = 8081;
System.Net.Sockets.Socket Client;
Client = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Client.Connect(Address, (int)Port);
Console.WriteLine("Connected");
int p = 0;
int t = Environment.TickCount;
while (true)
{
if (Client.Available > 0)
{
byte[] z = new byte[1024];
int r = Client.Receive(z); ;
p += r;
}
else
{
System.Threading.Thread.Sleep(10);
}
if (Environment.TickCount - t >= 1000)
{
t = Environment.TickCount;
Console.WriteLine(Program.FormatFileSizeAsString(p) + " Readed,");
p = 0;
}
}
}
public static string FormatFileSizeAsString(int len)
{
if (len < 750 && len > 0)
return "0.0 B ~";
string[] Suffix = { "B", "KB", "MB", "GB", "TB" };
int i;
double dblSByte = len;
for (i = 0; (int)(len / 1024) > 0; i++, len /= 1024)
dblSByte = len / 1024.0;
return String.Format("{0:0.0} {1}", dblSByte, Suffix[i]);
}
}
Thanks all, Please tell me what you think about possible problems.
It was some sort of limitation by ISP per each connection.
Solving was funny. I used to send a HTTP Header before my request and ISP increased my speed because of that.