Go Down

Topic: Help on socket connection to Arduino (Read 5780 times) previous topic - next topic

mrk_b

Hy everybody,
I need some help in writing a python script that run on my pc and sends request to the yun.
Starting form the Bridge example, I edited it in a way that it prints on the serial every string that it recieve, here it is:
Code: [Select]

#include <Bridge.h>
#include <YunServer.h>
#include <YunClient.h>
YunServer server;
String rec;

// Listen on default port 5555, the webserver on the Yun
// will forward there all the HTTP requests for us.

void setup() {
  Serial.begin(9600);
  // Bridge startup
  pinMode(13,OUTPUT);
  digitalWrite(13, LOW);
  Bridge.begin();
  digitalWrite(13, HIGH);
  // Listen for incoming connection only from localhost
  // (no one from the external network could connect)
  server.listenOnLocalhost();
  server.begin();
}

void loop() {
  // Get clients coming from server
  YunClient client = server.accept();

  // There is a new client?
  if (client) {
    client.setTimeout(5);
    // Process request
    rec = client.readStringUntil('\n');;
    // Close connection and free resources.
    client.stop();
    Serial.println(rec);
  }
delay(5);
}

This code is ok because if on the browser I launch let say the url "http://192.168.240.1/arduino/hello" on the serial monitor i read "hello".
Now, as the comment on the example sketch says, the YunServer listens on default port 5555, so i guess that if i'm connected to the arduino wifi network, it is possible to open a socket connection to the arduino's ip (192.168.240.1) and forward the request trough the 5555 port.
Am I right?
If I am, i writed this tiny python script:
Code: [Select]

#!/usr/bin/env python
import socket
arduino = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
arduino.connect(('192.168.240.1', 5555))
arduino.send("Hello!")

but it does not work.
When i execute it i recive this error:
Quote
[WinError 10061] No connection could be made because the target machine actively refused it

I seen similar python code even for the wifi shild on arduino uno, so i'm expecting it should work...
What i'm doing wrong?
Can someone hel me in order to make it work?
Thank you!!

mamu

Make the following changes to the YunServer in your sketch:
Declare YunServer server(5555);
And change listenOnLocalhost() to noListenOnLocalhost() in your setup method.

mrk_b

This made the connection work!
Thank you!
But now i recieve another error, but is python stuff this time:
Quote
TypeError: 'str' does not support the buffer interface

mamu

For testing purpose: have you tried sending a simple digit to arduino? Looks like the str type of "Hello" could make the problem here

mrk_b

The last error was because in python string are unicode strings and send want byte string.
changing the last row like this:
Code: [Select]
arduino.send(b"Hello!")
made the script work!
Thank you so much for the support!

Go Up