initial commit last working from congress

This commit is contained in:
interfisch 2018-01-06 17:49:16 +01:00
commit 6b277eba38
29 changed files with 575 additions and 0 deletions

195
matrix.py Normal file
View File

@ -0,0 +1,195 @@
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
import _thread
import socket
import pygame
import math
import random
import numpy as np
from pygame.locals import *
import serial #pip3 install pyserial
import time
HEIGHT=24
WIDTH=160
class FlipdotSim():
def __init__(self,
imageSize = (160,48), #80,16
pixelSize = 10,
udpPort = 2323,
ser=None):
self.udpPort = udpPort
self.flipdotMatrixSimulatorWidget=None #deactivate simulator
#self.flipdotMatrixSimulatorWidget = FlipdotMatrixSimulatorWidget(imageSize, pixelSize) #comment out if no simulator needed
self.udpHostSocket = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
self.udpHostSocket.bind(("", self.udpPort))
self.ser=ser
def run(self):
self.RunServer()
def RunServer(self):
try:
while True:
rawData = self.udpHostSocket.recv(4096)
#print(rawData)
imageArray = ImageArrayAdapter().convertPacketToImageArray(rawData)
#print("Image array")
#print(imageArray)
if self.flipdotMatrixSimulatorWidget is not None:
self.flipdotMatrixSimulatorWidget.show(imageArray)
self.sendToMatrix(imageArray[0: int(WIDTH*HEIGHT) ],0)
self.sendToMatrix(imageArray[int(WIDTH*HEIGHT): ],1)
finally:
self.udpHostSocket.close()
def sendToMatrix(self,imageArray,displayid=0):
data=np.zeros(int(WIDTH*HEIGHT/8),dtype=np.uint8)
imageArray=np.hstack( (np.array(imageArray,dtype=np.uint8),np.zeros(len(data)*8-len(imageArray),dtype=np.uint8) ))
print("imageArray size="+str(len(imageArray)))
numberofbytes=int(len(imageArray)/8)
print("numberofbytes="+str(numberofbytes))
# 477 ist oben links
# 474 ist rechts daneben
for i in range(numberofbytes):
# j=numberofbytes+1 - ( int(i/3)+(2-i%3)+3)
# j=(numberofbytes-3) # Erste Stelle oben links
j=(numberofbytes-3)-(i*3)+int(i/160)*480+1*(int(i/160))
#j=(numberofbytes-3)-(i*3)+int(i/(numberofbytes/3))*numberofbytes+1*(int(i/(numberofbytes/3)))
# 417 ist zweite Zeile, ganz links oben
data[j] = int( ''.join(str(e)[::-1] for e in imageArray[i*8:(i+1)*8]) ,2)
#data[59]=255
matrixSetup(ser,displayid)
ser.write(bytearray(fixMatrixBits(data)))
matrixEnd(ser)
class ImageArrayAdapter():
def __init__(self):
self.arrayOfBinaryInts = []
def convertPacketToImageArray(self, udpPacketStr):
self.arrayOfBinaryInts = []
byteArray = bytearray(udpPacketStr)
#Fix for other format. Not Used
#byteArray = udpPacketStr.translate(None, b'\r\n').decode().replace('[','').replace(']','').replace(' ','').split(',')
#byteArray = [int(x) for x in byteArray]
#print("rawtype="+str(type(byteArray)))
#print(byteArray)
for byte in byteArray:
#print("byte:"+str(byte))
self.__appendByteToArrayOfBinaryInts(byte)
return self.arrayOfBinaryInts
def __appendByteToArrayOfBinaryInts(self, byte):
byteValue = int(byte)
for i in range(8):
if math.floor(byteValue/(2**(7-i))) > 0:
self.arrayOfBinaryInts.append(1)
#print("append 1")
else:
self.arrayOfBinaryInts.append(0)
#print("append 0")
byteValue = byteValue%(2**(7-i))
class FlipdotMatrixSimulatorWidget():
BLACKCOLOR = 0
WHITECOLOR = 1
def __init__(self,
imageSize = (160,48),
pixelSize = 10):
self.imageSize = imageSize
self.pixelSize = pixelSize
pygame.init()
self.screen = pygame.display.set_mode((imageSize[0]*pixelSize, imageSize[1]*pixelSize))
self.screen.fill((255,255,255))
_thread.start_new_thread(self.watchCloseThread, ())
def watchCloseThread(self):
while True:
for event in pygame.event.get():
if event.type in (QUIT, QUIT):
import os
os.kill(os.getpid(), 9)
pygame.time.delay(500)
def show(self, imageArray):
for yValue in range(self.imageSize[1]):
for xValue in range(self.imageSize[0]):
i = self.imageSize[0]*yValue + xValue
color = imageArray[i]
self.updatePixel(xValue, yValue, color)
pygame.display.update()
def clearPixels(self):
for xValue in range(self.imageSize[0]):
for yValue in range(self.imageSize[1]):
self.updatePixel(xValue, yValue, self.BLACKCOLOR)
def updatePixel(self, xValue, yValue, color):
surface = pygame.Surface((self.pixelSize-1, self.pixelSize-1))
if color == self.BLACKCOLOR:
rectcolor = (0,0,0)
else:
rectcolor = (255,255,255)
surface.fill(rectcolor)
self.screen.blit(surface, (xValue*self.pixelSize, yValue*self.pixelSize))
def matrixSetup(ser,displayid=0):
ser.write(chr(2).encode())
ser.write(b'B') #command char
if displayid==0:
ser.write(b'0') #display id 0 or 1
elif displayid==1:
ser.write(b'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):
print("data vor="+str(len(data)))
#for bi,b in enumerate(data):
bi=0
while bi <len(data):
b=data[bi]
if b==2:
data=np.hstack( (np.hstack( (data[0:bi],[27,48,50]) ), data[bi+1:] ) )
bi+=2
elif b==3:
data=np.hstack( (np.hstack( (data[0:bi],[27,48,51]) ), data[bi+1:] ) )
bi+=2
elif b==27:
data=np.hstack( (np.hstack( (data[0:bi],[27,48,66]) ), data[bi+1:] ) )
bi+=2
bi+=1
data=np.array(data,dtype=np.uint8)
return data
if __name__ == '__main__':
ser = None
ser = serial.Serial('/dev/ttyUSB0',9600) # open serial port
print(ser.name)
FlipdotSim(imageSize=(WIDTH,HEIGHT), pixelSize = 4, udpPort=2323,ser=ser).run()
#ser.close()

View File

@ -0,0 +1,232 @@
from PIL import Image, ImageDraw, ImageFont
import socket
import binascii
import io
import time
import re
import numpy as np
import PIL.ImageOps
class FlipdotSender(object):
'''
classdocs
'''
C_BLACK = 0
C_WHITE = 255
global threadrunning
threadrunning=False
lastimgmap = []
def __init__(self, udphost, udpport, img_size=(160,48), font_size=9, font_size_scroll=12,
font_offset1=(0,0), font_offset2=(0,8),
#font_family='/usr/share/fonts/gnu-free/FreeMono.ttf',
#font_family='/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',
font_family='freefont/FreeMono.ttf',
chars_per_line=11):
'''
Constructor
'''
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._font_size = font_size
self._font_size_scroll = font_size_scroll
self._font_offset1 = font_offset1
self._font_offset2 = font_offset2
self._font_family = font_family
self._chars_per_line = chars_per_line
self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
def stopAnimation(self):
global threadrunning
threadrunning=False #tried to stop a running animation
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 _send(self, image): #old function, backup
imgmap = []
for pixel in image.getdata():
r, g, b, a = pixel
if r == FlipdotSender.C_WHITE:
imgmap.append(1)
else:
imgmap.append(0)
lastimgmap=imgmap
packet = self._array2packet(imgmap)
self._sock.sendto(bytes(packet), (self._udphost, self._udpport))'''
def _send(self, image,fadespeed=0,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
if r >= 127:
if invert:
imgmap.append(0)
else:
imgmap.append(1)
else:
if invert:
imgmap.append(1)
else:
imgmap.append(0)
imgmaptmp=FlipdotSender.lastimgmap
if fadespeed>0:
threadrunning=True
#diff=np.sum(np.array(imgmaptmp) != np.array(imgmap)) #different pixels
pixelchangeind=np.arange(self._img_size[0]*self._img_size[1])
np.random.shuffle(pixelchangeind)
for _i,ind in enumerate(pixelchangeind):
if threadrunning==False:
break #stop this for
if ind<len(imgmaptmp): #imgmaptmp is not empty (normally at first run)
imgmaptmp[ind]=imgmap[ind]
if _i%fadespeed==0:
packet = self._array2packet(imgmaptmp)
self._sock.sendto(bytes(packet), (self._udphost, self._udpport))
time.sleep(0.2)
if threadrunning==True: #if animation hasnt been cancelled
self.sendPacket(imgmap) #send packet and save last-imagemap
threadrunning=False
else:
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))
FlipdotSender.lastimgmap=imgmap
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))
def send_text(self, text,fadespeed=0):
image = Image.new("RGBA", self._img_size, FlipdotSender.C_BLACK)
draw = ImageDraw.Draw(image)
draw.fontmode = "1" # No AA
font = ImageFont.truetype(self._font_family, self._font_size)
cut = self._chars_per_line
splitted_text = text.split("|")
draw.text(self._font_offset1, splitted_text[0], font=font, fill=FlipdotSender.C_WHITE)
if len(splitted_text)>1:
draw.text(self._font_offset2, splitted_text[1], font=font, fill=FlipdotSender.C_WHITE)
self._send(image,fadespeed)
def send_textFull(self, text,fadespeed=0):
image = Image.new("RGBA", self._img_size, FlipdotSender.C_BLACK)
draw = ImageDraw.Draw(image)
draw.fontmode = "1" # No AA
l=1000 #init very high
splitpoint=40 #very high
currentfontsize=12+1 #init with max font size
font = ImageFont.truetype(self._font_family, currentfontsize)
while(l>80): #while text too long and font not too small
if currentfontsize>8:
currentfontsize=currentfontsize-1 #reduce size and try if fits
else: #if fontsize too small, try cutting sentence (2 lines)
splitpoint=splitpoint-1
font = ImageFont.truetype(self._font_family, currentfontsize)
l=draw.textsize(text[0:splitpoint], font=font)[0]
print("Textlength="+str(l)+" split="+str(splitpoint))
if splitpoint==40: #not splitted
draw.text((0,int((16-currentfontsize)/2) ), text, font=font, fill=FlipdotSender.C_WHITE)
else:
draw.text((0,-1), text[0:splitpoint], font=font, fill=FlipdotSender.C_WHITE)
draw.text((0,-1+currentfontsize), text[splitpoint:], font=font, fill=FlipdotSender.C_WHITE)
self._send(image,fadespeed)
def send_marquee(self, str, speed=3):
global threadrunning
threadrunning=True
offset = self._img_size[0]
font = ImageFont.truetype(self._font_family, self._font_size_scroll)
while offset >= -font.getsize(str)[0]-speed and threadrunning==True:
image = Image.new("RGBA", self._img_size, FlipdotSender.C_BLACK)
draw = ImageDraw.Draw(image)
draw.fontmode = "1" # No AA
draw.text((offset,0), str, font=font, fill=FlipdotSender.C_WHITE)
self._send(image)
offset -= speed
time.sleep(0.15)
threadrunning=False
def send_img_from_filename(self, imgfilename,invert=False):
background = Image.new("RGBA", self._img_size, FlipdotSender.C_BLACK)
image = Image.open(imgfilename)
image = image.convert(mode='RGBA')
image = image.resize(self._img_size)
image.save('/tmp/send2.png', 'PNG')
background.paste(image, box=(0,0), mask=None)
background.save('/tmp/send.png', 'PNG')
self._send(background,0,invert)
def send_img(self, img):
background = Image.new("RGBA", self._img_size, FlipdotSender.C_BLACK)
stream = io.BytesIO(img)
image = Image.open(stream)
image = image.convert(mode='RGBA')
image = image.resize(self._img_size)
image.save('/tmp/send2.jpeg', 'JPEG')
background.paste(image, box=(0,0), mask=None)
background.save('/tmp/send.jpeg', 'JPEG')
self._send(background)

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 368 B

Binary file not shown.

BIN
printtext_dfi/black.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 179 B

BIN
printtext_dfi/chaoswest.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 712 B

BIN
printtext_dfi/ctdo_logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 474 B

Binary file not shown.

BIN
printtext_dfi/kirby.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

BIN
printtext_dfi/kirbyboss.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1006 B

BIN
printtext_dfi/mario.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 530 B

BIN
printtext_dfi/nyancat.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 904 B

View File

@ -0,0 +1,38 @@
#!/usr/bin/env python3
import time
from FlipdotSender import FlipdotSender
import time
import sys
from random import randint
flipdot = FlipdotSender("localhost", 2323,(160,48),40)
#text=sys.argv[1]
#flipdot.send_text(text)
#flipdot.send_marquee(text)
while(True):
flipdot.send_img_from_filename("troll.png",randint(0,1)==0)
time.sleep(randint(5,20))
flipdot.send_img_from_filename("kirbyboss.png",randint(0,1)==0)
time.sleep(randint(5,20))
flipdot.send_img_from_filename("kirby.png",randint(0,1)==0)
time.sleep(randint(5,20))
flipdot.send_img_from_filename("pokemon_wildpidgey.png",randint(0,1)==0)
time.sleep(randint(5,20))
flipdot.send_img_from_filename("tetris.png",randint(0,1)==0)
time.sleep(randint(5,20))
flipdot.send_img_from_filename("zelda.png",randint(0,1)==0)
time.sleep(randint(5,20))
flipdot.send_img_from_filename("mario.png",randint(0,1)==0)
time.sleep(randint(5,20))
flipdot.send_img_from_filename("chaoswest.png",randint(0,1)==0)
time.sleep(randint(5,20))
flipdot.send_img_from_filename("ctdo_logo.png",randint(0,1)==0)
time.sleep(randint(5,20))
flipdot.send_img_from_filename("tuwat.png",randint(0,1)==0)
time.sleep(randint(5,20))
flipdot.send_img_from_filename("nyancat.png",randint(0,1)==0)
time.sleep(randint(5,20))
flipdot.send_img_from_filename("Spaceinvaders.png",randint(0,1)==0)
time.sleep(randint(5,20))

Binary file not shown.

After

Width:  |  Height:  |  Size: 80 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 52 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 98 KiB

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 81 KiB

BIN
printtext_dfi/schlange.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 656 B

BIN
printtext_dfi/tetris.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 986 B

BIN
printtext_dfi/troll.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

BIN
printtext_dfi/tuwat.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 494 B

BIN
printtext_dfi/white.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 232 B

BIN
printtext_dfi/zelda.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

110
testmatrix.py Normal file
View File

@ -0,0 +1,110 @@
#!/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()