from machine import Pin, PWM
import time


class PixMod():
    def __init__(self, pin_nr=6):
        #ir_led = PWM(Pin("GP18"))
        self.ir_led = PWM(Pin(pin_nr))
        self.ir_led.freq(38000)
        self.ir_led.duty_u16(0)

        self.READ_DELAY_US = 10000
        self.PROCESS_DELAY_US = 30000
        # so a single frame takes roughly 200ms


    def emit_pulse(self, duration_us):
        self.ir_led.duty_u16(32768)  # 50% duty cycle
        time.sleep_us(duration_us)
        self.ir_led.duty_u16(0)      # 0% duty cycle

    def xmit_bin(self, msg_data_bin, msg_len, repeat=1):
        msg_data_bin = (msg_data_bin << 1) + 1
        msg_len += 1

        for n in range(repeat):
            self.emit_pulse(4500)
            time.sleep_us(self.PROCESS_DELAY_US)

            for i in range(msg_len-1, -1, -1):
                if(msg_data_bin & (1<<i)):
                    self.emit_pulse(1500)
                else:
                    self.emit_pulse(500)

                time.sleep_us(self.READ_DELAY_US)

            self.emit_pulse(4500)
            time.sleep_us(self.PROCESS_DELAY_US)

    def xmit_fx(self, id_effect, id_colour_fg, id_colour_bg, repeat=1):
        msg = id_effect
        msg = (msg << 4) + id_colour_fg
        msg = (msg << 4) + id_colour_bg
        msg = (msg << 2) + 0 # TODO: CRC

        self.xmit_bin(msg, 14, repeat)
