it is possible to control the Gpio of a raspberry pi connected by WiFi by another raspberry pi by a python script? I need to Connect\disconect some electric loads of my house switchboard, controled by a script runnig in a raspberry PI in my garage, this one manage the solar system like the charge of the baterries. Try to use a remote controle AC switch but is to far and ins't reayable.
2 Answers
You can use the SocketServer module to create a server on your pi which will make the GPIO actions. Then you can connect with your second pi as a client to that server an send your commands.
Basic exmaple from the docs:
server.py
import SocketServer
class MyTCPHandler(SocketServer.BaseRequestHandler):
"""
The RequestHandler class for our server.
It is instantiated once per connection to the server, and must
override the handle() method to implement communication to the
client.
"""
def handle(self):
# self.request is the TCP socket connected to the client
self.data = self.request.recv(1024).strip()
print "{} wrote:".format(self.client_address[0])
print self.data
self.gpio_action()
def gpio_action(self):
# do your gpio here
if __name__ == "__main__":
HOST, PORT = "", 9999
# Create the server, binding on port 9999
server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
# Activate the server; this will keep running until you
# interrupt the program with Ctrl-C
server.serve_forever()
client.py
import socket
import sys
HOST, PORT = "<ip-to-server>", 9999
data = " ".join(sys.argv[1:])
# Create a socket (SOCK_STREAM means a TCP socket)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
# Connect to server and send data
sock.connect((HOST, PORT))
sock.sendall(data + "\n")
finally:
sock.close()
print "Sent: {}".format(data)