Introduction: Ethernet Relay Control With Python on Windows: the Easy Way

About: Hello! My name is FuzzyPotato, I have a passion for electronics, Python programming, and DIY projects. I have always been fascinated by the way things work, and I have a love for using technology to solve prob…

In this instructable, we'll show you how to control a cheap eBay Ethernet relay using Python. Ethernet relays offer an affordable solution for remotely switching electrical circuits. By combining Python with the eBay Ethernet relay, you can establish communication between your PC and the relay module over long distances.

Whether you're a beginner or have some programming experience, this guide will walk you through the steps to create a Python application for remote control. By the end, you'll have the knowledge and skills to automate and control devices using the eBay Ethernet relay.

Let's explore the exciting possibilities of Python and the eBay Ethernet relay for remote control!

Supplies

To control the ethernet relay using Python, you'll need:


  1. Ethernet relay
  2. Ethernet cable
  3. Power supply
  4. Switch
  5. Windows computer with Python installed
  6. IDE (I'm using PyCharm)


With these supplies, you're all set to dive into the process of controlling an ethernet relay over a network. Let's get started!

Step 1: Setup

Let's kick off the setup by making all the necessary physical connections:


  1. Connect your PC to the switch.
  2. Connect the switch to the Ethernet relay.
  3. Power up the Ethernet switch.
  4. Power up the Ethernet relay.


By following these steps, you'll have a cozy little local network, with your computer and Ethernet relay all connected and powered up. It should look something like the image above.

Step 2: The Code

In this step, we will create a new Python script and populate it with code that enables us to control the Ethernet relay.


  1. Create a new Python script.
  2. Copy and paste the following code:


import socket
import time

relay_ip = "192.168.1.100" # Your relay module IP address should be the same.
relay_port = 6722

# Create a TCP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

def connect_module():
# Connect to the relay module
sock.connect((relay_ip, relay_port))

def close_relay(relay_num):
# Turn off the specified relay
command = "2" + relay_num
sock.sendall(command.encode())
print("Relay", relay_num, "turned off")
print_relay_status()

def open_relay(relay_num):
# Turn on the specified relay
command = "1" + relay_num
sock.sendall(command.encode())
print("Relay", relay_num, "turned on")
print_relay_status()

def print_relay_status():
sock.sendall("00".encode())
relay_status = sock.recv(8).decode()
print("Relay Status:", relay_status)


# Connect to the relay module
connect_module()

# Turn on relay 1
open_relay("1")
time.sleep(1) # Wait for 1 second

# Turn off relay 1
close_relay("1")
time.sleep(1) # Wait for 1 second

# Turn on relay 2
open_relay("2")
time.sleep(1) # Wait for 1 second

# Turn off relay 2
close_relay("2")
time.sleep(1) # Wait for 1 second

# Close the socket
sock.close()


This code sets up a TCP socket, establishes a connection with the relay module, and provides functions to control and monitor the relays. It allows you to turn on and off specific relays, print the relay status, and perform sequential relay control.

Step 3: Test

Now, let's put our Python code to the test and see if we can successfully control the USB relay.


Run the Python script.

The script will perform the following actions:

  1. It calls the connect_module() function to establish a connection with the relay module.
  2. It turns on relay 1 by calling the open_relay("1") function, waits for 1 second using time.sleep(1), and then turns off relay 1 by calling the close_relay("1") function.
  3. It turns on relay 2 by calling the open_relay("2") function, waits for 1 second, and then turns off relay 2 by calling the close_relay("2") function.
  4. Finally, it closes the socket connection by calling sock.close().


Observe the changes in the relay status during the script execution. If everything is working correctly, you should see and hear the relays turning on and off as expected.


With any luck, you have successfully tested the control of the Ethernet relay using Python.

Step 4: Configure

By now, your Ethernet relay should be functioning as desired. However, you might encounter situations where you need to change the IP address of the Ethernet relay or work with multiple relays. Don't worry! We will guide you through the process of changing the IP address.


Changing the Ethernet Relay IP address:

  1. Create a new Python script.
  2. Copy and paste the following code:


import socket
import re

class Sr201:
_IPV4_RE = '[.]'.join(('(?:[0-9]{1,2}|[01][0-9]{2}|2[0-4][0-9]|25[0-5])',) * 4)
PORT_CONFIG = 5111
PORT_CONTROL = 6722

def __init__(self, hostname):
self._hostname = hostname
self._port = None
self._soc = None

def open(self, port=None):
port = port or self.PORT_CONTROL
if port == self._port:
self.flush()
return
self.close()
self._soc = socket.create_connection((self._hostname, port))
self._port = port

def close(self):
if self._soc:
self.flush()
self._soc.close()
self._port = None
self._soc = None

def flush(self):
while True:
try:
data = self._soc.recv(4096)
if not data:
break
except socket.error:
break

def send(self, data):
return self._soc.send(data.encode('latin1'))

def recv(self):
response = self._soc.recv(4096).decode('latin1')
return response

def send_config(self, command, op, value):
self.open(self.PORT_CONFIG)
param = value is not None and ',' + value or ''
self.send('#' + op + '9999' + param + ';')
response = self.recv()
if (
not response or response[0] != '>' or response[-1] != ';' or
op != '1' and response != '>OK;'
):
raise Exception(f"Invalid response to {command}: {response}")
return response

def do_ip(self, command):
match = re.match('ip=(' + self._IPV4_RE + ')$', command)
if not match:
raise ValueError(f"Invalid {command}")
self.send_config(command, '2', match.group(1))

def save_and_restart(self):
self.send_config('save_and_restart', '7', '')

def change_ip_address(hostname, new_ip):
device = Sr201(hostname)
device.open()
device.do_ip(f"ip={new_ip}")
device.save_and_restart()
device.close()


# Example usage: CURRENT ADDRESS to NEW ADDRESS
change_ip_address("192.168.1.100", "192.168.1.98")


This code allows you to change the IP address of the Ethernet relay. Replace the second IP address in the last line of code with your desired address.

Congratulations! You are now ready to integrate this code into your own projects or explore further possibilities with Ethernet relays and Python programming.