dfi-led-matrix/client_sw/matrixSender.py

94 lines
2.4 KiB
Python

from PIL import Image, ImageDraw, ImageFont
import socket
import binascii
import io
import time
import re
import numpy as np
import PIL.ImageOps
class MatrixSender(object):
C_BLACK = 0
C_WHITE = 255
global threadrunning
threadrunning=False
def __init__(self, udphost, udpport, img_size=(160,48), bitsperpixel=1):
self._udphost = udphost
if not type(udpport) is int or udpport > 65536:
raise TypeError('port has to be int and > 65536 !!')
self._udpport = udpport
self._img_size = img_size
self.bitsperpixel=bitsperpixel
self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
def _list2byte(self, l):
byte = 0
i = 0
for i in range(8):
byte += 2**(7-i) if l[i] else 0
return byte
def _array2packet(self, a):
return [self._list2byte(a[i*8:i*8+8]) for i in range(int(len(a)/8))]
def _intToBitlist(self,number): #convert integer number to list of bits, exampe: 1-> [0,1], 2->[1,0]
bitlistvaryinglength=[x for x in "{0:b}".format(number)]
bitlist=np.zeros(self.bitsperpixel,dtype=int)
bitlist[self.bitsperpixel-len(bitlistvaryinglength):]=bitlistvaryinglength
return bitlist
def send(self, image,invert=False): #changes slowly 'fadespeed'-pixels at a time
global threadrunning
#if fadespeed=0 -> change instant.
#time to change= 1280/25*0.2
imgmap = []
for pixel in image.getdata():
r, g, b, a = pixel
pixelbrightness=int( (r+g+b)/3 *(pow(2,self.bitsperpixel)-1) /255 +0.5)
if invert:
pixelbrightness=pow(2,self.bitsperpixel)-1-pixelbrightness
for b in self._intToBitlist(pixelbrightness):
imgmap.append(b)
self.sendPacket(imgmap) #send packet and save last-imagemap
def sendPacket(self, imgmap):
packet = self._array2packet(imgmap)
self._sock.sendto(bytes(packet), (self._udphost, self._udpport))
def send_bytes(self, img):
imgmap = []
for pixel in img:
if pixel == "1":
imgmap.append(1)
else:
imgmap.append(0)
if len(img) < 1280:
imgmap = np.hstack((imgmap, np.zeros(1280-len(img), dtype=int)))
packet = self._array2packet(imgmap)
self._sock.sendto(bytes(packet), (self._udphost, self._udpport))