Skip to content

Instantly share code, notes, and snippets.

@Illizian
Last active May 21, 2017 09:25
Show Gist options
  • Save Illizian/597e507568f7996f2d087ca1ca946a9d to your computer and use it in GitHub Desktop.
Save Illizian/597e507568f7996f2d087ca1ca946a9d to your computer and use it in GitHub Desktop.
Neopixel Control Server
#!/usr/bin/env python3
import math
import asyncio
import websockets
import neopixel
# Neo configuration:
LED_COUNT = 60 # Number of LED pixels.
LED_PIN = 18 # GPIO pin connected to the pixels (must support PWM!).
LED_FREQ_HZ = 800000 # LED signal frequency in hertz (usually 800khz)
LED_DMA = 5 # DMA channel to use for generating signal (try 5)
LED_BRIGHTNESS = 100 # Set to 0 for darkest and 255 for brightest
LED_INVERT = False # True to invert the signal (when using NPN transistor level shift)
neo = neopixel.Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS)
neo.begin()
def spread(strip, length):
return list(map(lambda x: strip[math.floor(x / (length / len(strip)))], range(length)));
async def router(websocket, path):
while True:
payload = await websocket.recv()
decoded = payload.split('#')
command = None
args = None
if (len(decoded) == 1):
command = decoded[0]
args = ''
elif (len(decoded) == 2):
command = decoded[0]
args = decoded[1]
if (command == None or command == ''):
print('Invalid Payload: ', payload)
continue
print(command, args)
# Python WHY U HAZ NO SWITCH
if command == 'color':
for led, color in enumerate(spread(args.split(','), LED_COUNT)):
neo.setPixelColor(led, int(color))
neo.show()
elif command == 'brightness':
neo.setBrightness(int(args))
elif command == 'clear':
for led, color in enumerate(spread([0], LED_COUNT)):
neo.setPixelColor(led, int(color))
neo.show()
else:
print('Command Not Recognised')
start_server = websockets.serve(router, '0.0.0.0', 8765)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

Neopixel Control Server

Connection

The control server hosts an RFC-6455 WebSocket on Port 8765. You can use any compliant library or (where supported) the in-built Web Sockets API to connect.

Commands

The control server accepts commands as a string with the following structure:

<$command><#?><$args?>

The following $commands are defined:

  • Color e.g. color#16711727,5308671,13631743 Set the color of each pixel to the corrosponding 24bit rgb value*. The values will be spread across the leds if the LED count does not match the amount of values.
  • Brightness e.g. brightness#50 Set the LED brightness to the value [0-255] provided. Note: This takes effect on the next use of the Color command.
  • Clear e.g. clear Sets all LEDs to 0, effectively turning them off.

Notes

  • (*) To create a 24bit rgb value in most languages: (red << 8) | (green << 16) | blue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment