#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
import math
import random
import numpy as np
import serial #pip3 install pyserial
import time

HEIGHT=24
WIDTH=160

def matrixSetup(ser):
    ser.write(chr(2).encode())
    ser.write(b'B') #command char
    ser.write(b'0') #display id  0 or 1
    #ser.write(b'00000000000')
    ser.write(b'00000000000') #alignment
    ser.write(chr(27).encode()) #oneB
    ser.write(b'1')

def matrixEnd(ser):
    #ser.write(chr(151).encode())
    ser.write(chr(3).encode()) #END cmd

def fixMatrixBits(data):
    for bi,b in enumerate(data):
        if b==2:
            data=np.hstack(  (np.hstack( (data[0:bi],[27,48,50]) ), data[bi+1:] ) )
        elif b==3:
            data=np.hstack(  (np.hstack( (data[0:bi],[27,48,51]) ), data[bi+1:] ) )
        elif b==27:
            data=np.hstack(  (np.hstack( (data[0:bi],[27,48,66]) ), data[bi+1:] ) )

    data=np.array(data,dtype=np.uint8)
    return data


if __name__ == '__main__':

    '''things:
    2 - clears buffer
    3 - ends at current position
    27 - also ends at cur. pos.

    to display 2:  27,48,50
    to display 3:  27,48,51
    to display 27: 27,48,66
    '''

    ser = None
    ser = serial.Serial('/dev/ttyUSB0',9600)  # open serial port



    matrixSetup(ser)
    data=np.zeros(int(160*24/8),dtype=np.uint8)
    data[:]=0
    ser.write(bytearray(data))
    matrixEnd(ser)

    time.sleep(2)


    '''
    matrixSetup(ser)

    data=np.zeros(int(160*24/8),dtype=np.uint8)
    data[0]=255
    data[1]=3
    data[2]=255

    data=fixMatrixBits(data)

    ser.write(bytearray(data))


    matrixEnd(ser)
    '''

    for y in range(HEIGHT):
        for x in range(int(WIDTH/8)):
            matrixSetup(ser)
            data=np.zeros(int(WIDTH*HEIGHT/8),dtype=np.uint8)
            #data[int(x/8)+y*WIDTH]=math.pow(2,x%8)
            data[int(  int(x)+y*WIDTH/8 ) ]=255

            ser.write(bytearray(fixMatrixBits(data)))
            matrixEnd(ser)
            time.sleep(.1)


    '''
    for i in range(256):
        print(i)
        matrixSetup(ser)

        data=np.zeros(int(160*24/8),dtype=np.uint8)
        data[0]=255
        data[1]=27 #escape
        data[2]=48 #ascii "0"=48
        data[3]=i #ascii "2"=50
        data[4]=255

        ser.write(bytearray(data))


        matrixEnd(ser)
        time.sleep(.25)
    '''
    ser.close()