#!/bin/python3 import socket import sys import time import math import requests from json.decoder import JSONDecodeError from PIL import Image, ImageDraw, ImageFont # Create a TCP/IP socket sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) server_address = ('0.0.0.0', 2020) print('binding {} port {}'.format(*server_address)) sock.bind(server_address) N_ROWS = 5 N_COLS = 10 #font = ImageFont.truetype('5by5.ttf', 5) def req(): try: response = requests.get('https://api.ethereumdb.com/v1/timeseries?pair=ETH-EUR&range=10mi&type=line') json = response.json() print(json[0]['price']) return float(json[0]['price']) except requests.ConnectionError: print("connection error") except JSONDecodeError: print("decode error") except KeyError: print("key error") def render(txt): image = Image.new("RGB", (len(txt)*4+4,N_ROWS), (0,0,0)) draw = ImageDraw.Draw(image) draw.text((0, -1), txt, (255,255,255), font=font) image.save('image.png') return image def getBytes(price): pixels = [0] * (N_ROWS * N_COLS) digit = math.floor(math.log10(price)) for row in range(N_ROWS): val = int(price / 10**(digit)) % 10 for col in range(N_COLS): if col >= 9-val and col < 9: pixels[row*N_COLS + col] = 15 elif digit == 0 and col == 9: pixels[row*N_COLS + col] = 9 digit -= 1 pixels[49] = int(pixels[49]/2) return bytes([0x41] + pixels) client_address = None oldPing = time.time() def send(pixels): global oldPing, client_address, sock if not client_address: data, addr = sock.recvfrom(16) print('received {} from {}'.format(data, addr)) client_address = addr else: sock.sendto(pixels, client_address) if time.time() - oldPing > 30: data, addr = sock.recvfrom(16) print('received {} from {}'.format(data, addr)) client_address = addr oldPing = time.time() while True: try: price = req() pixels = getBytes(price) for i in range(20): send(pixels) time.sleep(1) except OSError: print("os error") print('closing socket') sock.close()