pixelreceiver.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. from __future__ import print_function, absolute_import, division
  2. print('receiver start')
  3. import sys
  4. import socket
  5. import traceback
  6. from path import Path
  7. from rgbmatrix import RGBMatrix, RGBMatrixOptions
  8. from rgbmatrix import graphics
  9. class Renderer(object):
  10. def __init__(self):
  11. o = RGBMatrixOptions()
  12. o.chain_length = 4
  13. self.matrix = RGBMatrix(options=o)
  14. self.canvas = self.matrix.CreateFrameCanvas()
  15. def swap(self):
  16. self.canvas = self.matrix.SwapOnVSync(self.canvas)
  17. self.canvas.Clear()
  18. def print_text(self, text):
  19. graphics.DrawText(self.canvas, fonts['10x20'], 0, 20, textColor, text)
  20. self.swap()
  21. def scroll_text(self, text, loop=1):
  22. pos = self.canvas.width
  23. i = 1
  24. while True:
  25. len = graphics.DrawText(self.canvas, fonts['10x20'], pos, 20, textColor, text)
  26. pos -= 1
  27. if (pos + len < 0):
  28. pos = self.canvas.width
  29. i += 1
  30. if i > loop:
  31. break
  32. time.sleep(0.02)
  33. self.swap()
  34. def fit_text(self, text, width=128):
  35. ff = reversed(sorted(fonts.items(), key=lambda e: int(e[0].split('x')[0])))
  36. temp_canvas = self.matrix.CreateFrameCanvas()
  37. for name, font in ff:
  38. w = graphics.DrawText(temp_canvas, font, 0, -100, textColor, text)
  39. if w < width:
  40. break
  41. else:
  42. print('str len %s exceeds space' % w)
  43. graphics.DrawText(self.canvas, font, 0, 20, textColor, text)
  44. self.swap()
  45. try:
  46. fonts = {}
  47. for f in Path('/matrix/fonts').files('*.bdf'):
  48. if not f.namebase.split('x')[0].isdigit() or not f.namebase[-1].isdigit():
  49. continue
  50. fo = graphics.Font()
  51. fo.LoadFont(f)
  52. fonts[f.namebase] = fo
  53. textColor = graphics.Color(96, 128, 255)
  54. r = Renderer()
  55. # Create a TCP/IP socket
  56. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  57. # Bind the socket to the port
  58. server_address = ('0.0.0.0', 10000)
  59. print('starting up on %s port %s' % server_address)
  60. sock.bind(server_address)
  61. r.fit_text('Matrix ready.')
  62. r.fit_text('111')
  63. while True:
  64. print('waiting to receive message')
  65. data, address = sock.recvfrom(4096)
  66. print('received %s bytes from %s' % (len(data), address))
  67. method = ord(data[0])
  68. data = data[1:]
  69. if method == 0:
  70. r.print_text(data.decode('utf-8'))
  71. elif method == 1:
  72. r.scroll_text(data.decode('utf-8'))
  73. elif method == 2:
  74. r.fit_text(data.decode('utf-8'))
  75. except Exception:
  76. print(traceback.format_exc())
  77. finally:
  78. print('receiver exit')