Reputation: 38
I am building an IOT device that accesses GPIO pins on pi to control lights fans and etc. I have used Tkinter to provide UI to the screen that is connected to pi. This has some buttons that have some variables that indicate whether the lights are on or off. This is a separate component that
The **first **problem now is that I need to create an android app that interacts with the pi GPIO pins and turns the lights on and off. This has to be done on the local host and with minimum latency.
The second problem is can I make this android app interact with the pi and the python script over the internet. This means that can the person control the GPIO operations even when he is not connected to the same network as that of the pi(not via local host).
The third problem is to update the variables in the locally hosted python script that enables the GUI. I saw some solutions explaining REST API's but as I have no knowledge about that stuff just wanted to make sure I do the right thing before I start.
import RPi.GPIO as GPIO
import time
import tkinter as tk
l1 = 1
l2 = 1
l3 = 1
lm = 1
GPIO.setmode(GPIO.BCM)
GPIO.setup(20, GPIO.OUT)
GPIO.setup(26, GPIO.OUT)
GPIO.setup(21, GPIO.OUT)
def light_1():
global l1
if l1%2 == 1:
GPIO.output(26, True)
l1 = 0
else:
GPIO.output(26, False)
l1 = 1
def light_2():
global l2
if l2%2 == 1:
GPIO.output(21, True)
l2 = 0
else:
GPIO.output(21, False)
l2 = 1
def light_3():
global l3
if l3%2 == 1:
GPIO.output(20, True)
l3 = 0
else:
GPIO.output(20, False)
l3 = 1
def master_switch():
global lm
if lm%2 == 1:
GPIO.output(20, True)
GPIO.output(26, True)
GPIO.output(21, True)
lm = 0
else:
GPIO.output(20, False)
GPIO.output(21, False)
GPIO.output(26, False)
lm = 1
top = tk.Tk()
but1 = tk.Button(top, text="Light 1", command=light_1)
but2 = tk.Button(top, text="Light 2", command=light_3)
but3 = tk.Button(top, text="Light 3", command=light_2)
but4 = tk.Button(top, text="Master", command=master_switch)
but1.pack()
but2.pack()
but3.pack()
but4.pack()
try:
while True:
top.mainloop()
finally:
GPIO.cleanup()
For example here if i need to update the state of l1/l2/l3/l4 even when the user interacts with the android app to change light states how can i do it.
Upvotes: 0
Views: 128
Reputation: 1109
When faced with similar problem when building my room automation control (using home network) I used TCP sockets to transmit data between Python script running on Pi and Qt Android app. I am sure Android API has functions to interact with TCP sockets: https://developer.android.com/reference/java/net/Socket
AS for problem no 2, I think you would need to set up port forwarding on your internet router: https://en.wikipedia.org/wiki/Port_forwarding
Upvotes: 0