Last active
February 4, 2017 23:42
-
-
Save awendland/560490fbaab933f88673b4ce83b986da to your computer and use it in GitHub Desktop.
Raspoberry Pi + LED strip + UDP Server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import print_function | |
import datetime | |
# Setup UDP server | |
import socket | |
UDPSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) | |
listen_addr = ("", 21567) | |
UDPSock.bind(listen_addr) | |
print("Listening on port {}\n".format(listen_addr[1])) | |
print("Commands: `COMMAND PARAMS`") | |
print("Valid commands:") | |
print(" `RESET` resets the GPIO controls for the LED strip") | |
print(" `STOP` stops all PWM controllers") | |
print(" `SET List<CHANNEL:MAGNITUDE>` sets the led strip to the given values.") | |
print(" CHANNEL is {r, g, b}") | |
print(" MAGNITUDE is a float [0, 100]") | |
print(" The List should be comma delimited") | |
print(" For example: `r:100,g:0,b:100` would make the led strip purple") | |
# Setup GPIO | |
import RPi.GPIO as GPIO | |
rgbPin = {"r": 17, "g": 22, "b": 24} | |
rgbPwm = {} | |
STARTED, STOPPED = "STARTED", "STOPPED" | |
def setup_gpio(): | |
GPIO.setmode(GPIO.BCM) | |
for c, p in rgbPin.iteritems(): | |
GPIO.setup(p, GPIO.OUT) | |
rgbPwm[c] = [GPIO.PWM(p, 100), STOPPED] | |
def teardown_gpio(): | |
for _, p in rgbPin.iteritems(): | |
GPIO.output(p, GPIO.LOW) | |
GPIO.cleanup() | |
try: | |
setup_gpio() | |
# Begin listening loop | |
while True: | |
data, addr = UDPSock.recvfrom(1024) | |
try: | |
data = data.strip() | |
cmd, params = data.partition(" ")[::2] | |
if cmd == "RESET": | |
teardown_gpio() | |
setup_gpio() | |
if cmd == "STOP": | |
for c in rgbPwm: | |
rgbPwm[c][0].stop() | |
rgbPwm[c][1] = STOPPED | |
if cmd == "SET": | |
cmds = map(lambda (c, v): (c, float(v)), | |
[p.split(":") for p in params.split(",")]) | |
for c, v in cmds: | |
if 0 <= v <= 100: | |
if rgbPwm[c][1] == STOPPED: | |
rgbPwm[c][0].start(v) | |
else: | |
rgbPwm[c][0].ChangeDutyCycle(v) | |
rgbPwm[c][1] = STARTED | |
print("{} EXECUTE {} FROM {}".format(datetime.datetime.now().isoformat(), data, addr)) | |
except (ValueError, LookupError, IndexError, KeyError), e: | |
print("{} INVALID {} FROM {}".format(datetime.datetime.now().isoformat(), data, addr)) | |
print(e) | |
except KeyboardInterrupt: | |
pass | |
except: | |
raise | |
finally: | |
teardown_gpio() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment