I have an Arduino with an Ethernet shield, it connected to the same hub with my computer.
I tried to let this Arduino send some HTTP Request Get to my web server written in Python.
I fixed the IP for my computer at 192.168.1.2 and the Arduino will get its IP automatically through a DHCP server or if it fails to get a new IP, it would get a static IP.
Web server part: I tested my Web server and it worked as whenever I called that request, it would save for me the record into the database(I am using mongodb as my database)
Arduino part: I tested and I saw it could connect to my DHCP server, not my web server as it sent a Request and get a Response from the DHCP server.
How to config so my DHCP server can transfer Arduino's request directly to my web server? Or other solution like let my Arduino send data directly to my web server?
Small code of my web server:
#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
from bottle import *
from pymongo import *
import datetime
#route('/hello')
def hello():
return "Hello World!"
#get('/receiver', method = 'GET')
def receiver():
# Get data from http request and save it into db
print 'Inserting data'
receiver_id = request.query.getall('id')
broadcaster_id = request.query.getall('bid')
signal_strength = request.query.getall('s')
client = MongoClient('localhost', 27017)
db = client['arduino']
collection = db['arduino']
record = {'receiver_id':receiver_id,
'broadcaster_id':broadcaster_id,
'signal_strength':signal_strength,
'date': datetime.datetime.utcnow()}
print record
collection.insert_one(record)
return template('Record: {{record}}', record = record)
#get('/db')
def db():
# Display all data
client = MongoClient('localhost', 27017)
db = client['arduino']
collection = db['arduino']
for record in collection.find():
return template('<div>{{receiver_id}}</div>',receiver_id = record)
#error(404)
def error404(error):
return 'Something wrong, try again!'
run(host='localhost', port=80, debug=True)
Small code of my Arduino program:
/*
Connect to Ethernet Using DHCP
Author:- Embedded Laboratory
*/
#include <SPI.h>
#include <Ethernet.h>
#define ETH_CS 10
#define SD_CS 4
// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = {0xCA,0xFE,0x00,0x00,0x00,0x15};
IPAddress ip(192,168,1,15);
IPAddress server(192,168,1,2);
//char server[] = "localhost";
EthernetClient client;
void setup()
{
Serial.begin(9600);
Serial.println("Starting Ethernet Connection");
pinMode(ETH_CS,OUTPUT);
pinMode(SD_CS,OUTPUT);
digitalWrite(ETH_CS,LOW); // Select the Ethernet Module.
digitalWrite(SD_CS,HIGH); // De-Select the internal SD Card
if (Ethernet.begin(mac) == 0) // Start in DHCP Mode
{
Serial.println("Failed to configure Ethernet using DHCP, using Static Mode");
// If DHCP Mode failed, start in Static Mode
Ethernet.begin(mac, ip);
}
Serial.print("My IP address: ");
for (byte thisByte = 0; thisByte < 4; thisByte++)
{
// print the value of each byte of the IP address:
Serial.print(Ethernet.localIP()[thisByte], DEC);
Serial.print(".");
}
Serial.println();
// give the Ethernet shield a second to initialize:
delay(1000);
Serial.println("connecting...");
for(int i =1; i < 6; i++){
Serial.print("Test number ");
Serial.println(i);
// if you get a connection, report back via serial:
if (client.connect(server, 80))
{
Serial.println("connected");
// Make a HTTP request:
//client.println("GET /receiver?id=4&bid=3&s=70 HTTP/1.1");
client.println("GET / HTTP/1.1");
client.println("Host: localhost");
client.println("Connection: close");
client.println();
delay(1000);
}
else
{
// if you didn't get a connection to the server:
Serial.println("connection failed");
}
}
}
void loop()
{
// if there are incoming bytes available
// from the server, read them and print them:
if (client.available())
{
char c = client.read();
client.write(c);
Serial.print("Read the client:");
Serial.print(c);
}
// as long as there are bytes in the serial queue,
// read them and send them out the socket if it's open:
while (Serial.available() > 0)
{
char inChar = Serial.read();
if (client.connected())
{
client.print(inChar);
}
}
// if the server's disconnected, stop the client:
if (!client.connected()) {
Serial.println();
Serial.println("disconnecting.");
client.stop();
// do nothing:
while(true);
}
}
Related
I am trying to connect my Arduino Nano Connect RP2040 with my machine using Python (3.8.8). I want to use WiFi communication protocol and I am currently working on a client-server socket.
Since I am not so familiar with this communication protocol I am following this thread which looks to perform good results. Of course, this thread talks about Ethernet and I am readapting using WiFiNina library which has been developed by Arduino in order to use the module.
Here the code I am running on Arduino:
#include <SPI.h>
#include <WiFiNINA.h>
#include <ArduinoJson.h>
// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {
0x08, 0x3A, 0xF2, 0xB1, 0x9D, 0xE0 };
IPAddress ip(192,168,43,98);
// Enter the IP address of the server you're connecting to:
IPAddress server(192,168,0,4);
// Initialize the WiFi client library
// with the IP address and port of the server
WiFiClient client;
char ssid[] = "xxxxx"; // the name of your network
char username[] = "xxxxxxx";
char pass[] = "xxxxxxx";
void setup() {
// start the Wifi connection:
WiFi.beginEnterprise(ssid, username, pass);
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
// give the Ethernet shield a second to initialize:
delay(1000);
Serial.println("connecting...");
// if you get a connection, report back via serial:
if (client.connect(server, 13380)) {
Serial.println("connected");
}
else {
// if you didn't get a connection to the server:
Serial.println("connection failed");
}
}
void loop()
{
//JSON stuff
StaticJsonBuffer<200> jsonBuffer;
JsonObject& root = jsonBuffer.createObject();
root["sensor"] = "gps";
root["time"] = 42;
JsonArray& data = root.createNestedArray("data");
data.add(48.756080);
data.add(2.302038);
char json[100];
root.printTo(json);
Serial.print(json);
// if there are incoming bytes available
// from the server, read them and print them:
if (client.available()) {
char c = client.read();
Serial.print(c);
}
// as long as there are bytes in the serial queue,
// read them and send them out the socket if it's open:
if (client.connected()) {
client.print(json);
}
// if the server's disconnected, stop the client:
if (!client.connected()) {
Serial.println();
Serial.println("disconnecting.");
client.stop();
// do nothing:
while(true);
}
}
I have used some functions from WiFiNina (for example .beginEnterprise() in order to connect Arduino to the network).
For what server concerns, here the code in Python:
import socket
import sys
import json
# host = '127.0.0.1'
host = '192.168.0.4'
port = 13380
address = (host, port)
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(address)
server_socket.listen(5)
# server_socket.connect(address)
print ("waiting for a connection . . .")
conn, address = server_socket.accept()
print ("Connection established: "), address
while True:
output = conn.recv(84048);
if output.strip() == "disconnect":
conn.close()
sys.exit("Disconnect message received - terminate the connection")
conn.send("dack")
elif output:
print(output)
data = json.load(output)
print(data)
I am not interested in sending JSON data, like I have already mentioned I am just readapt the code in thread. I actually need to send data in real-time, but step-by-step :-)
The problem is that I cannot establish the connection between Arduino (client) and Python (server).
From server part, I actually got this error:
Traceback (most recent call last):
File "server_arduino.py", line 18, in <module>
server_socket.bind(address)
OSError: [WinError 10049] The requested address is not valid in its context
For some reasons which I actually did not understand yet, if I would change host in 127.0.0.1 (following suggestions here) the server part starts to work, and it stucks in waiting for a connection . . . printed in my console, because it needs a client to connect.
At this stage, running my Arduino code I got this:
connecting...
connection failed
{"sensor":"gps","time":42,"data":[48.75608,2.302038]}
disconnecting.
So, it does mean to me that I was able to connect to WiFi, but not to server.
Does anyone give me any suggestions?
I know I am really beginner and any suggestions would be really appreciated.
I am trying to build a WebSocket client in python that connects to an Arduino Uno every second via an Ethernet cable, that has a WebSocket server on it, based on the mWebSocket library. The working Arduino code is shown below:
#include <WebSocketServer.h>
using namespace net;
// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[]{0xA8, 0x61, 0x0A, 0xAE, 0x69, 0x13};
IPAddress ip(198, 162, 1, 177);
IPAddress gateway(0,0,0,0);
IPAddress DNSserver(0,0,0,0);
IPAddress subnet(255,255,255,0);
constexpr uint16_t port = 80;
WebSocketServer wss{port};
void setup() {
// You can use Ethernet.init(pin) to configure the CS pin
Ethernet.init(10); // Most Arduino shields
//Ethernet.init(5); // MKR ETH shield
//Ethernet.init(0); // Teensy 2.0
//Ethernet.init(20); // Teensy++ 2.0
//Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet
//Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
Serial.println("Ethernet WebServer Example");
// start the Ethernet connection and the server:
Ethernet.begin(mac,ip,DNSserver,gateway,subnet);
// Check for Ethernet hardware present
if (Ethernet.hardwareStatus() == EthernetNoHardware) {
Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :(");
while (true) {
delay(1); // do nothing, no point running without Ethernet hardware
}
}
if (Ethernet.linkStatus() == LinkOFF) {
Serial.println("Ethernet cable is not connected.");
}
// start the server
Serial.print("server is at ");
Serial.println(Ethernet.localIP());
wss.onConnection([](WebSocket & ws) {
const auto protocol = ws.getProtocol();
if (protocol) {
Serial.print(F("Client protocol: "));
Serial.println(protocol);
}
ws.onMessage([](WebSocket & ws, const WebSocket::DataType dataType,
const char *message, uint16_t length) {
switch (dataType) {
case WebSocket::DataType::TEXT:
Serial.print(F("Received: "));
Serial.println(message);
break;
case WebSocket::DataType::BINARY:
Serial.println(F("Received binary data"));
break;
}
ws.send(dataType, message, length);
});
ws.onClose([](WebSocket &, const WebSocket::CloseCode, const char *,
uint16_t) {
Serial.println(F("Disconnected"));
});
Serial.print(F("New client: "));
Serial.println(ws.getRemoteIP());
const char message[] {"Hello from Arduino server!"};
ws.send(WebSocket::DataType::TEXT, message, strlen(message));
});
wss.begin();
Serial.println(Ethernet.localIP());
}
void loop() {
wss.listen();
}
I have constructed a python socket client to interact with this Arduino and hopefully print the message "Hello from Arduino server!" to the client with every connection.
#!/usr/bin/python3
import asyncio
import websockets
import socket
import time
import datetime
import struct
starttime = time.time() # start value for timed data acquisition
# setup socket 1
s1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s1.connect(("198.162.1.177",80))
s1.sendall(b'GET / HTTP/1.1 400')
if True:
print('Connected')
def acquire():
data = s1.recv(10000)
print(data)
while True:
acquire()
time.sleep(1.0 - ((time.time() - starttime) % 1.0)) # continue every (2.0 seconds)
s1.close()
However, when I run the above code. I obtain:
Connected
b'H'
b'TTP/1.1 400 Bad Request\r\n'
b''
b''
b''
b''
b''
What am I missing here, I presume that the connection is not being fully made, even though I can ping the Arduino from my PC. Do I need to account for a HTTP header in a different way for a WebSocket client?
Websocket connection is made by a HTTP request with upgrade headers which specifies that the connecting client want's to upgrade to a websocket protocol. When the server receives this message and finding the upgrade headers in the request it validates if the upgrade it supported on it's end and upgrades the underlying connection to a websocket connection. This is the thing that seems to be missing from your end.
Also, as you are importing websockets in your client code. You can use the library functions which does this work for you and you just make a GET request with "ws/wss" specified in your request URL.
I'm trying to set up communication through a TCP/IP connection and are having problems with connecting the C# client to the Python Server.
It throws a SocketException:
System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it
I'm pretty sure that it is happening at the line where it tries to connect to the Python server: sender.Connect(remoteEP);
What I've tried
Before I used the IPv4 protocol and Pythons socket.AF_INET but I discovered that it seems like that my parsing of the IP Address in C# makes it an IPv6 address so that's what I'm using now but that didn't resolve the problem.
I also tried using IPAddress.Parse(ip) instead of getting the host first with Dns.GetHostEntry(ip) but that didn't seem to do anything.
The code
The C# code:
using UnityEngine;
using System;
using System.Net;
using System.Net.Sockets;
using System.Collections;
using System.Text;
public class PyCommunicator : MonoBehaviour {
private string ip = "::1"; // Localhost
private int port = 14654;
public string dataStringToSend
{
get { return dataStringToSend; }
set { dataStringToSend = value; }
}
private void Start()
{
StartCoroutine(RequestServerCoroutine());
}
IEnumerator RequestServerCoroutine()
{
while (true)
{
RequestServer();
yield return new WaitForSecondsRealtime(10);
}
}
public void RequestServer()
{
byte[] bytes = new byte[1024]; // 1 KiloByte
try
{
// Connect to a Remote server,
// and get host IP Address that is used to establish a connection.
// In this case, we get one IP address of localhost that is IPv6 : ::1
// If a host has multiple addresses, you will get a list of addresses
IPHostEntry host = Dns.GetHostEntry(ip);
IPAddress ipAddress = host.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
// Create a TCP/IP socket.
Socket sender = new Socket(AddressFamily.InterNetworkV6,
SocketType.Stream, ProtocolType.Tcp);
// Connect the socket to the remote endpoint. Catch any errors.
try
{
// Connect to Remote EndPoint
sender.Connect(remoteEP);
Debug.Log("Successfully established a connection between Unity and Python.");
// Encode the data string into a byte array.
dataStringToSend = "Test from C#";
if (dataStringToSend != "")
{
byte[] msg = Encoding.ASCII.GetBytes(dataStringToSend);
// Send the data through the socket.
int bytesSent = sender.Send(msg);
// Reset.
dataStringToSend = "";
}
// Receive the response from the remote device.
int bytesRec = sender.Receive(bytes);
Debug.LogFormat("Echoed test = {0}",
Encoding.ASCII.GetString(bytes, 0, bytesRec));
// Release the socket.
sender.Shutdown(SocketShutdown.Both);
sender.Close();
}
catch (ArgumentNullException ane)
{
Debug.LogFormat("ArgumentNullException: {0}", ane.ToString());
}
catch (SocketException se)
{
Debug.LogFormat("SocketException: {0}", se.ToString());
}
catch (Exception e)
{
Debug.LogFormat("Unexpected exception: {0}", e.ToString());
}
}
catch (Exception e)
{
Debug.LogFormat("Exception from setup: {0}", e.ToString());
}
}
}
The C# code was taken from this link from the client section and modified for my own use.
Python code:
import socket
from time import sleep
class Communicator():
def __init__(self, ip, port):
self.ip = ip
self.port = port
self.data_to_send = None
self.socket = None
self.socket_conn = None
self.socket_addr = None
# Start listening right away.
self.start()
def start(self):
"""Start listening and accept connection."""
self.socket = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
self.socket.bind((self.ip, self.port))
# Begin listening for 1 connection.
self.socket.listen(1)
print("Socket is listening on ip (" + str(self.ip) + ") and port " + str(self.port))
self.socket_conn, self.socket_addr = self.socket.accept()
print("Connection between Unity and Python established. Unity-C# is at: " + str(self.socket_addr))
sleep(5) # TESTING PURPOSES
# Receive.
result = ""
chunk_counter = 0
while True:
# Allow the server to read up to 1024 bytes.
data = self.conn.recv(1024)
chunk_counter += 1
# To minimize lag, read guess in chunks.
if chunk_counter < 5:
result += data.decode()
# If reading the guess is done,
# break out of loop.
if not data:
break
# Send.
self.socket.send("Test from python".encode())
# Close
self.socket.close()
def send_data(self):
"""Send data"""
pass
def receive_data(self):
"""Receive data"""
pass
Communicator('::1', 14654)
It seems like I didn't search the StackOverflow forum enough.
I found a solution in the code and answer given in this StackOverflow answer.
I didn't need to use the actual localhost loopback address and instead needed to get the HOSTNAME address through C#'s DNS function:
Dns.GetHostName()
I also used socket.gethostname() in Python so that they would have same addresses when connecting.
I also changed the whole thing to use IPv4 addresses and found out in the answer of the linked question that the first element in host.AddressList contains IPv6 addresses while the second AND last element contained IPv4 addresses, and that was the missing piece.
UPDATED CODE
C# Code:
using UnityEngine;
using System;
using System.Net;
using System.Net.Sockets;
using System.Collections;
using System.Text;
public class PyCommunicator : MonoBehaviour {
private int port = 14654;
public string dataStringToSend
{
get { return dataStringToSend; }
set { dataStringToSend = value; }
}
private void Start()
{
StartCoroutine(RequestServerCoroutine());
}
IEnumerator RequestServerCoroutine()
{
while (true)
{
RequestServer();
yield return new WaitForSecondsRealtime(10);
}
}
public void RequestServer()
{
byte[] bytes = new byte[1024]; // 1 KiloByte
try
{
// Connect to a Remote server,
// and get host IP Address that is used to establish a connection.
// In this case, we get one IP address of localhost that is IP : 127.0.0.1
// If a host has multiple addresses, you will get a list of addresses
IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = host.AddressList[1];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
// Create a TCP/IP socket.
Socket sender = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
// Connect the socket to the remote endpoint. Catch any errors.
try
{
// Connect to Remote EndPoint
sender.Connect(remoteEP);
Debug.Log("Successfully established a connection between Unity and Python.");
// Encode the data string into a byte array.
dataStringToSend = "Test from C#";
if (dataStringToSend != "")
{
byte[] msg = Encoding.ASCII.GetBytes(dataStringToSend);
// Send the data through the socket.
int bytesSent = sender.Send(msg);
// Reset.
dataStringToSend = "";
}
// Receive the response from the remote device.
int bytesRec = sender.Receive(bytes);
Debug.LogFormat("Echoed test = {0}",
Encoding.ASCII.GetString(bytes, 0, bytesRec));
// Release the socket.
sender.Shutdown(SocketShutdown.Both);
sender.Close();
}
catch (ArgumentNullException ane)
{
Debug.LogFormat("ArgumentNullException: {0}", ane.ToString());
}
catch (SocketException se)
{
Debug.LogFormat("SocketException: {0}", se.ToString());
}
catch (Exception e)
{
Debug.LogFormat("Unexpected exception: {0}", e.ToString());
}
}
catch (Exception e)
{
Debug.LogFormat("Exception from setup: {0}", e.ToString());
}
}
}
Python Code:
import socket
from time import sleep
class Communicator():
def __init__(self, ip, port):
self.ip = ip
self.port = port
self.data_to_send = None
self.socket = None
self.socket_conn = None
self.socket_addr = None
# Start listening right away.
self.start()
def start(self):
"""Start listening and accept connection."""
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.bind((self.ip, self.port))
# Begin listening for 1 connection.
self.socket.listen(1)
print("Socket is listening on ip (" + str(self.ip) + ") and port " + str(self.port))
self.socket_conn, self.socket_addr = self.socket.accept()
print("Connection between Unity and Python established. Unity-C# is at: " + str(self.socket_addr))
sleep(5) # TESTING PURPOSES
# Receive.
result = ""
chunk_counter = 0
while True:
# Allow the server to read up to 1024 bytes.
data = self.conn.recv(1024)
chunk_counter += 1
# To minimize lag, read guess in chunks.
if chunk_counter < 5:
result += data.decode()
# If reading the guess is done,
# break out of loop.
if not data:
break
# Send.
self.socket.send("Test from python".encode())
# Close
self.socket.close()
def send_data(self):
"""Send data"""
pass
def receive_data(self):
"""Receive data"""
pass
Communicator(socket.gethostname(), 14654)
I am trying to establish a connection between an android phone(as server) and my computer(client in python) to send messages from the android phone to PC.
My Problem is that the app keeps crashing and I don't really know how to set the ip's.
So what I do is when the app opens I give it the computers IP and the port at which I need to send the message and then I click "send button".
Down below I have given the code that I have tried but the app crashes at the socket.send(sendPacket);
Android Code
public class MainActivity extends Activity {
private EditText ipInput;
private EditText portInput;
private EditText messageInput;
private Button sendButton;
private DatagramSocket socket;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ipInput = (EditText) findViewById(R.id.address);
portInput = (EditText) findViewById(R.id.port);
messageInput = (EditText) findViewById(R.id.message);
sendButton = (Button) findViewById(R.id.send);
sendButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String message = messageInput.getText().toString();
Log.e("TAG",message);
sendPacket(message);
}
});
}
private void sendPacket(String message) {
byte[] messageData = message.getBytes();
try {
InetAddress addr = InetAddress.getByName(ipInput.getText().toString());
int port = Integer.parseInt(portInput.getText().toString());
DatagramPacket sendPacket = new DatagramPacket(messageData, 0, messageData.length, addr, port);
if (socket != null) {
socket.disconnect();
socket.close();
return;
}
socket = new DatagramSocket(port);
socket.send(sendPacket);
} catch (UnknownHostException e) {
Log.e("MainActivity sendPacket", "getByName failed");
} catch (IOException e) {
Log.e("MainActivity sendPacket", "send failed");
}
}
#Override
public void onDestroy() {
super.onDestroy();
socket.disconnect();
socket.close();
}
}
Python Code:
My python code is also there, I bind the IP at 0.0.0.0 so I can get packet from anyone trying to communicate.
from socket import *
PORT = 7000
IP = "0.0.0.0"
sock = socket(AF_INET, SOCK_DGRAM) # SOCK_DGRAM means UDP socket
sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
sock.bind((IP, PORT))
while True:
print "Waiting for data..."
data, addr = sock.recvfrom(1024) # blocking
print "received: " + data
To sum it all up. I really need help with setting ip's, whose ip should I give to the android phone(the phone's or the laptops) and whose ip should I give to the laptop in the python code.
Secondly why does the app crash at "socket.send(sendPacket);" inside the send packet method.
If you need more details let me know in the comments.
So I can't answer you why the app is crashing but I can answer the IP question.
The client (laptop) needs the servers ip (in the same network its 192.168.X.XXX).
The server (phone) might also need his own ip.
The client might also need his own ip.
But notice that the server doesn't need the clients ip, it's open for all connections (except you want to white/black-list certain ip´s).
I did the same things with just some ip differences, works for me.
I have an app on which i press a button and it should turn on/off an led on a raspberry pi.
the code on android studio looks like this :
onPressed: () async {
setState(() {
instruction = power;
power = power == 'on' ? 'off' : 'on';
print('$instruction');
});
int port = 9999;
final socket = await EasyUDPSocket.bindBroadcast(port);
if (socket != null) {
socket.send(ascii.encode('$instruction'), '192.168.0.105', port);
final resp = await socket.receive();
print('Client $port received: $resp');
// `close` method of EasyUDPSocket is awaitable.
await socket.close();
print('Client $port closed');
}
},
the '192.168.0.105' is the ipv4 address of the raspberry pi(this can be found by typing "ipconfig" for windows in cmd and by "ifconfig" in an rpi)
the python code on the rpi or any pc will be
from socket import *
s = socket(AF_INET, SOCK_DGRAM)
print("socket created")
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
s.bind(("192.168.0.105",9999))
while True:
print("Waiting for data...")
data, addr = s.recvfrom(1024) # blocking
instruction = data.decode("utf-8")
if instruction == 'off':
print('turn off the led')
else:
print("turn on the led")
the python code is a bit customized for the led purpose but i'm sure you'll understand how to work with it!
I'm using an arduino ethernet to read data form sensors, and then would like to send data to a computer in another building to drive the logic/control in a piece of python software. I decided to sketch up a simple sketch in python/arduino that just sends text from the arduino to my python program over ethernet:
The arduino client code is mostly taken from the EthernetClient example:
#include <SPI.h>
#include <Ethernet.h>
byte mac[] = {0x90, 0xA2, 0xDA, 0x0E, 0x40, 0x9F};
byte ip[] = {192, 168, 0, 172};
byte server[] = {192,168,0,17};
int port = 1700;
EthernetClient client;
void setup() {
Serial.begin(9600);
while (!Serial) {
;
}
Ethernet.begin(mac, ip);
delay(1000);
Serial.println("connecting...");
// if you get a connection, report back via serial:
if (client.connect(server, port)) {
Serial.println("connected.");
//print text to the server
client.println("This is a request from the client.");
}
else {
// if you didn't get a connection to the server:
Serial.println("connection failed");
}
}
void loop()
{
// if there are incoming bytes available
// from the server, read them and print them:
if (client.available()) {
char c = client.read();
Serial.print(c);
}
// if the server's disconnected, stop the client:
if (!client.connected()) {
Serial.println();
Serial.println("disconnecting.");
client.stop();
// do nothing forevermore:
while(true);
}
}
And then my python code:
import socket
host = ''
port = 1700
address = (host, port)
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((address))
server_socket.listen(5)
print "Listening for client . . ."
conn, address = server_socket.accept()
print "Connected to client at ", address
//pick a large output buffer size because i don't necessarily know how big the incoming packet is
output = conn.recv(2048);
print "Message received from client:"
print output
conn.send("This is a response from the server.")
conn.close()
print "Test message sent and connection closed."
The response from the server is what i expect:
Listening for client . . .
Connected to client at ('192.168.0.172', 1025)
Message received from client:
This is a request from the client.
Test message sent and connection closed.
But the client receives:
connecting...
connected.
This
disconnecting.
And seems to stop receiving the text from my server after the stream. Why is that?
Another question: Why is it that I asked my arduino to connect on port 1700, but python claims that it's receiving a request from port 1025?
thanks!