Dear Everyone,
I have a project, where I am using two NodeMCU_v3. I'm a student and this is my first micropython project so my question may will be obvious.
In the project one ESP8266 is used to collect two light sensors data through I2C and the other ESP8266 is calculating, then set an RGB LED's brightness.
I'd like to send the data from the first ESP to the second and I have found some solutions for that in C and Lua language, but not in Micropython.
I'm learning about networks now at school and home so I think it's something that I have to connect one to the other and somehow send sockets containing the data.
I would love to get some help from you for my problem.
Thank you in advance.
Two ESP8266 talking to each other
Re: Two ESP8266 talking to each other
There are several common ways: TCP/IP(socket),HTTP(REST),MQTT
Re: Two ESP8266 talking to each other
Thank you both. I checked all options and the link and I think I would like to use TCP/IP(socket) with the link.
So one has to be configued as a server and the other one as a client. Then the server has to listen if the client asks for data.
The first thing I don't really understand is the address. Is it the IP Address of the server and on port 80?
And the other thing is how I put the data in the socket?
I found a complete solution in Lua.
http://randomnerdtutorials.com/how-to-m ... 8266-talk/
I would like to do this exactly, but in every ~10 minutes.
Thank you in advance, and sorry for my bad language skills.
So one has to be configued as a server and the other one as a client. Then the server has to listen if the client asks for data.
The first thing I don't really understand is the address. Is it the IP Address of the server and on port 80?
And the other thing is how I put the data in the socket?
I found a complete solution in Lua.
http://randomnerdtutorials.com/how-to-m ... 8266-talk/
I would like to do this exactly, but in every ~10 minutes.
Thank you in advance, and sorry for my bad language skills.
Re: Two ESP8266 talking to each other
[quote=zacsek post_id=26653 time=1522781840 user_id=3881]
The first thing I don't really understand is the address. Is it the IP Address of the server and on port 80?
And the other thing is how I put the data in the socket?
[/quote]
Generally each ESP unit would be given an IP from your router (using DHCP), however, you can certainly set them statically if it makes it easier for debugging/testing and development.
As for your port, using port 80 is fine, however, be aware that this is normally reserved for HTTP traffic and as such, most applications would expect to see HTTP requests on this port. This might be fine if you are using a basic web form for transferring data, or even a RESTful interface to send a payload, however, from what I can gather in your project, these types of services might be far too big and cumbersome to implement. I'd go with a very simple tcp socket as mentioned by @Roberthh. Very simple, light weight and doesn't need to adhere to packet structure requirements so the world is your oyster.
Just be conscious that whatever method you are using, that there has not been any chat about security (either encryption or authentication) up till this point and it's always something that should be considered (albeit, even if not implemented in this project).
Good luck with your project!
The first thing I don't really understand is the address. Is it the IP Address of the server and on port 80?
And the other thing is how I put the data in the socket?
[/quote]
Generally each ESP unit would be given an IP from your router (using DHCP), however, you can certainly set them statically if it makes it easier for debugging/testing and development.
As for your port, using port 80 is fine, however, be aware that this is normally reserved for HTTP traffic and as such, most applications would expect to see HTTP requests on this port. This might be fine if you are using a basic web form for transferring data, or even a RESTful interface to send a payload, however, from what I can gather in your project, these types of services might be far too big and cumbersome to implement. I'd go with a very simple tcp socket as mentioned by @Roberthh. Very simple, light weight and doesn't need to adhere to packet structure requirements so the world is your oyster.
Just be conscious that whatever method you are using, that there has not been any chat about security (either encryption or authentication) up till this point and it's always something that should be considered (albeit, even if not implemented in this project).
Good luck with your project!
Re: Two ESP8266 talking to each other
Okay I think it is enough information to start with.
Thank you very much.
Thank you very much.
Re: Two ESP8266 talking to each other
For those coming around this post searching for a very basic TCP client/server example for MicroPython: Simply run the following code on both of your ESPs. It will connect the ESPs using your router. Alternatively, you could also connect the ESPs directly by setting up one as AP and then connecting the other ESP to it directly. If it works you can change the code in the server() and client() function as you like.
main.py (same file on both ESPs):
Example:
main.py (same file on both ESPs):
Code: Select all
import network
from utime import sleep_ms
import usocket as socket
# Setup WiFi connection:
def connect_wifi(ssid, passwd):
ap = network.WLAN(network.AP_IF)
ap.active(False)
print("Connecting to WiFi '%s'. This takes some time..." % ssid)
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect(ssid, passwd)
while wifi.status() == network.STAT_CONNECTING:
sleep_ms(100)
if wifi.isconnected():
print("Connection established. My IP is " + str(wifi.ifconfig()[0]))
return True
else:
status = wifi.status()
if status == network.STAT_WRONG_PASSWORD:
status = "WRONG PASSWORD"
elif status == network.STAT_NO_AP_FOUND:
status = "NETWORK '%s' NOT FOUND" % ssid
else:
status = "Status code %d" % status
print("Connection failed: %s!" % status)
return False
# Echo Server:
def server(port, max_clients=1):
print("Starting server at port %d..." % port)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('', port))
sock.listen(max_clients)
print("Echo-Server started. Connect a client now!")
conn, cl_addr = sock.accept()
print("New connection from %s:%d" % cl_addr)
while True:
data = conn.recv(1024).decode()
if not data:
break
print("Received from client: " + str(data))
conn.send(data.encode())
sock.close()
print("Server stopped.")
# Simple Client:
def client(host, port):
print("Connecting to server %s:%d..." % (host, port))
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, port))
print("Connection established.")
print("Enter 'exit' to close the client.")
while True:
msg = input(">> ")
if msg.lower().strip() == "exit":
break
sock.send(msg.encode())
data = sock.recv(1024).decode()
print("Received from server: %s" % data)
sock.close()
print("Client closed.")
# Prints available WiFi networks:
def print_wlan_list(sort_by=3, sort_desc=True):
"""sort by 0 = network name, 1 = bssid, 2 = ch, 3 = signal, ..."""
from ubinascii import hexlify
wlan = network.WLAN(network.STA_IF)
prev_wlan_state = wlan.active() # restore after scan
wlan.active(True)
table_header = ("network name", "BSSID", "CH", "signal", "authmode", "visibility")
# safe all networks as tuples in a list, where [0] is a list
# containing the maximum lengths of the subitems for oled;
# - 0: network name
# - 1: bssid (hardware address)
# - 2: channel
# - 3: rssi (signal strength, the higher the better)
# - 4: authmode (most likely WPA/WPA2-PSK)
# - 5: visible/hidden
scan = [[0] * len(table_header)]
# minimum length is table header
for i in range(len(table_header)):
scan[0][i] = len(table_header[i])
# scan
for item in wlan.scan():
bssid = hexlify(item[1]).decode("ascii")
bssid = ':'.join([bssid[i:i + 2] for i in range(0, len(bssid), 2)])
new = (item[0].decode("utf-8"),
bssid,
item[2],
item[3],
("open", "WEP", "WPA-PSK", "WPA2-PSK", "WPA/WPA2-PSK")[int(item[4])],
("visible", "hidden")[int(item[5])])
scan.append(new)
for i in range(0, len(scan[0])):
len_new = len(str(new[i]))
if len_new > scan[0][i]:
scan[0][i] = len_new
wlan.active(prev_wlan_state)
# print table
def center_subitems(ituple):
retlist = []
for i in range(len(ituple)):
missing_spaces = scan[0][i] - len(str(ituple[i]))
if missing_spaces > 0:
spaces_right = int(missing_spaces / 2)
spaces_left = missing_spaces - spaces_right
retlist.append(' ' * spaces_left + str(ituple[i]) + ' ' * spaces_right)
else:
retlist.append(ituple[i])
return tuple(retlist)
header_string = "|| %s || %s | %s | %s | %s | %s ||" % center_subitems(table_header)
print('-' * len(header_string))
print(header_string)
print('-' * len(header_string))
for item in sorted(scan[1:], key=lambda x: x[sort_by], reverse=sort_desc):
print("|| %s || %s | %s | %s | %s | %s ||" % center_subitems(item))
print('-' * len(header_string))
# Interface for setting up server/client:
def main():
while True:
print()
ssid = input("Enter your WiFi name: ")
passwd = input("Enter WiFi password: ")
if connect_wifi(ssid, passwd):
break
print("Scanning for available WiFi networks...")
print_wlan_list()
while True:
cmd = input("Run server (S) or client (C)? ").lower()
if cmd == 's':
server(5678)
break
elif cmd == 'c':
ip = input("Enter the server's IP address (see other ESP): ")
try:
client(ip, 5678)
break
except OSError:
print("Connection failed. Did you already start the server on the other ESP?")
else:
print("Invalid input. Please enter 'S' or 'C'.")
main()