ether.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. #!/bin/python3
  2. import socket
  3. import sys
  4. import time
  5. import math
  6. import requests
  7. from json.decoder import JSONDecodeError
  8. from PIL import Image, ImageDraw, ImageFont
  9. # Create a TCP/IP socket
  10. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  11. server_address = ('0.0.0.0', 2020)
  12. print('binding {} port {}'.format(*server_address))
  13. sock.bind(server_address)
  14. N_ROWS = 5
  15. N_COLS = 10
  16. #font = ImageFont.truetype('5by5.ttf', 5)
  17. def req():
  18. try:
  19. response = requests.get('https://api.ethereumdb.com/v1/timeseries?pair=ETH-EUR&range=10mi&type=line')
  20. json = response.json()
  21. print(json[0]['price'])
  22. return float(json[0]['price'])
  23. except requests.ConnectionError:
  24. print("connection error")
  25. except JSONDecodeError:
  26. print("decode error")
  27. except KeyError:
  28. print("key error")
  29. def render(txt):
  30. image = Image.new("RGB", (len(txt)*4+4,N_ROWS), (0,0,0))
  31. draw = ImageDraw.Draw(image)
  32. draw.text((0, -1), txt, (255,255,255), font=font)
  33. image.save('image.png')
  34. return image
  35. def getBytes(price):
  36. pixels = [0] * (N_ROWS * N_COLS)
  37. digit = math.floor(math.log10(price))
  38. for row in range(N_ROWS):
  39. val = int(price / 10**(digit)) % 10
  40. for col in range(N_COLS):
  41. if col >= 9-val and col < 9:
  42. pixels[row*N_COLS + col] = 15
  43. elif digit == 0 and col == 9:
  44. pixels[row*N_COLS + col] = 9
  45. digit -= 1
  46. pixels[49] = int(pixels[49]/2)
  47. return bytes([0x41] + pixels)
  48. client_address = None
  49. oldPing = time.time()
  50. def send(pixels):
  51. global oldPing, client_address, sock
  52. if not client_address:
  53. data, addr = sock.recvfrom(16)
  54. print('received {} from {}'.format(data, addr))
  55. client_address = addr
  56. else:
  57. sock.sendto(pixels, client_address)
  58. if time.time() - oldPing > 30:
  59. data, addr = sock.recvfrom(16)
  60. print('received {} from {}'.format(data, addr))
  61. client_address = addr
  62. oldPing = time.time()
  63. while True:
  64. try:
  65. price = req()
  66. pixels = getBytes(price)
  67. for i in range(20):
  68. send(pixels)
  69. time.sleep(1)
  70. except OSError:
  71. print("os error")
  72. print('closing socket')
  73. sock.close()