#! /usr/bin/env python3

import alsaaudio
import audioop
import board
import math
import neopixel
import time

def wheel(pos):
    # Input a value 0 to 255 to get a color value.
    # The colours are a transition r - g - b - back to r.
    if pos < 0 or pos > 255:
        r = g = b = 0
    elif pos < 85:
        r = int(pos * 3)
        g = int(255 - pos * 3)
        b = 0
    elif pos < 170:
        pos -= 85
        r = int(255 - pos * 3)
        g = 0
        b = int(pos * 3)
    else:
        pos -= 170
        r = 0
        g = int(pos * 3)
        b = int(255 - pos * 3)
    return (r, g, b)

def exec_neopixel(pixels, max):
    for i in range(0, max):
        pixels[i] = wheel(i * 255 / 300)
        # pixels.show()
    for i in range(max, 300):
        pixels[i] = (0, 0, 0)
    pixels.show()

def exec_audio():
    lo = 1E6
    hi = 5E8

    log_lo = math.log(lo)
    log_hi = math.log(hi)

    print(alsaaudio.pcms(alsaaudio.PCM_CAPTURE))
    pixels = neopixel.NeoPixel(board.D12, 300, brightness=0.1, auto_write=False)
    pixels[0] = (100, 0, 0)
    audioIn = alsaaudio.PCM(type=alsaaudio.PCM_CAPTURE, mode=alsaaudio.PCM_NORMAL, rate=48000, channels=1, format=alsaaudio.PCM_FORMAT_S32_LE, periodsize=640, device='plughw:CARD=sndrpii2scard,DEV=0')
    while True:
        length, data = audioIn.read()
        if length > 0:
            max_amp = max(audioop.max(data, 4), 1)
            log_max = math.log(float(max_amp))
            vu = (log_max - log_lo) / (log_hi - log_lo)
            led_nb = min(max(int(vu*300),0),299)
            print("max =", max_amp, ", log =", log_max, "vu = ", vu, "led =", led_nb)
            exec_neopixel(pixels, led_nb)

def test_neopixel():
    pixels = neopixel.NeoPixel(board.D12, 300, brightness=0.1, auto_write=False)
    for i in range(0, 300):
        print("Lighting", i)
        pixels[i] = (100, 0, 0)
        pixels.show()
        input()

def main():
    # test_neopixel()
    exec_audio()


if __name__ == "__main__":
	main()
