forked from veebch/btcticker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
btcticker.py
311 lines (274 loc) · 12.3 KB
/
btcticker.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
#!/usr/bin/python3
from PIL import Image, ImageOps
from PIL import ImageFont
from PIL import ImageDraw
import currency
import os
import sys
import logging
import RPi.GPIO as GPIO
from waveshare_epd import epd2in7
import time
import requests
import urllib, json
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import yaml
import socket
picdir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'images')
fontdir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'fonts')
configfile = os.path.join(os.path.dirname(os.path.realpath(__file__)),'config.yaml')
fonthiddenprice = ImageFont.truetype(os.path.join(fontdir,'googlefonts/Roboto-Medium.ttf'), 30)
font = ImageFont.truetype(os.path.join(fontdir,'googlefonts/Roboto-Medium.ttf'), 40)
fontHorizontal = ImageFont.truetype(os.path.join(fontdir,'googlefonts/Roboto-Medium.ttf'), 50)
font_date = ImageFont.truetype(os.path.join(fontdir,'PixelSplitter-Bold.ttf'),11)
def internet(host="8.8.8.8", port=53, timeout=3):
"""
Host: 8.8.8.8 (google-public-dns-a.google.com)
OpenPort: 53/tcp
Service: domain (DNS/TCP)
"""
try:
socket.setdefaulttimeout(timeout)
socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((host, port))
return True
except socket.error as ex:
logging.info("No internet")
return False
def getData(whichcoin,fiat):
"""
The function to update the ePaper display. There are two versions of the layout. One for portrait aspect ratio, one for landscape.
"""
# Get the week window in msec from epoch. This is used in the api calls
logging.info("Getting Data")
now_msec_from_epoch = int(round(time.time() * 1000))
days_ago = 7
endtime = now_msec_from_epoch
starttime = endtime - 1000*60*60*24*days_ago
starttimeseconds = round(starttime/1000) #CoinGecko Uses seconds
endtimeseconds = round(endtime/1000) #CoinGecko Uses seconds
# Get the price
try:
geckourl = "https://api.coingecko.com/api/v3/coins/markets?vs_currency="+fiat+"&ids="+whichcoin
logging.info(geckourl)
rawlivecoin = requests.get(geckourl).json()
liveprice= rawlivecoin[0]
pricenow= float(liveprice['current_price'])
logging.info("Got Live Data From CoinGecko")
geckourlhistorical = "https://api.coingecko.com/api/v3/coins/"+whichcoin+"/market_chart/range?vs_currency="+fiat+"&from="+str(starttimeseconds)+"&to="+str(endtimeseconds)
logging.info(geckourlhistorical)
rawtimeseries = requests.get(geckourlhistorical).json()
logging.info("Got Historical Data For Last Week from CoinGecko")
timeseriesarray = rawtimeseries['prices']
timeseriesstack = []
length=len (timeseriesarray)
i=0
while i < length:
timeseriesstack.append(float (timeseriesarray[i][1]))
i+=1
except Exception as error:
logging.info(error)
logging.info("Coingecko is unreachable - Show disconnected screen, Exit the script")
thebean = Image.open(os.path.join(picdir,'thebean.bmp'))
epd = epd2in7.EPD()
epd.Init_4Gray()
image = Image.new('L', (epd.height, epd.width), 255) # 255: clear the image with white
draw = ImageDraw.Draw(image)
image.paste(thebean, (60,15))
image = ImageOps.mirror(image)
epd.display_4Gray(epd.getbuffer_4Gray(image))
epd.sleep()
epd2in7.epdconfig.module_exit()
sys.exit()
# Add live price to timeseriesstack
timeseriesstack.append(pricenow)
return timeseriesstack
def makeSpark(pricestack):
# Subtract the mean from the sparkline to make the mean appear on the plot (it's really the x axis)
x = pricestack-np.mean(pricestack)
fig, ax = plt.subplots(1,1,figsize=(10,3))
plt.plot(x, color='k', linewidth=6)
plt.plot(len(x)-1, x[-1], color='r', marker='o')
# Remove the Y axis
for k,v in ax.spines.items():
v.set_visible(False)
ax.set_xticks([])
ax.set_yticks([])
ax.axhline(c='k', linewidth=4, linestyle=(0, (5, 2, 1, 2)))
# Save the resulting bmp file to the images directory
plt.savefig(os.path.join(picdir,'spark.png'), dpi=17)
imgspk = Image.open(os.path.join(picdir,'spark.png'))
file_out = os.path.join(picdir,'spark.bmp')
imgspk.save(file_out)
plt.clf() # Close plot to prevent memory error
def updateDisplay(config,pricestack,whichcoin,fiat):
symbolstring=currency.symbol(fiat.upper())
if fiat=="jpy":
symbolstring="¥"
pricenow = pricestack[-1]
currencythumbnail= 'currency/'+whichcoin+'.bmp'
tokenimage = Image.open(os.path.join(picdir,currencythumbnail))
sparkbitmap = Image.open(os.path.join(picdir,'spark.bmp'))
pricechange = str("%+d" % round((pricestack[-1]-pricestack[0])/pricestack[-1]*100,2))+"%"
if pricenow > 1000:
pricenowstring =format(int(pricenow),",")
else:
pricenowstring =str(float('%.5g' % pricenow))
if config['display']['orientation'] == 0 or config['display']['orientation'] == 180 :
epd = epd2in7.EPD()
epd.Init_4Gray()
image = Image.new('L', (epd.width, epd.height), 255) # 255: clear the image with white
draw = ImageDraw.Draw(image)
draw.text((110,80),"7day :",font =font_date,fill = 0)
draw.text((110,95),pricechange,font =font_date,fill = 0)
# Print price to 5 significant figures
draw.text((15,200),symbolstring+pricenowstring,font =font,fill = 0)
draw.text((10,10),str(time.strftime("%a %H:%M %d %b %Y")),font =font_date,fill = 0)
image.paste(tokenimage, (10,25))
image.paste(sparkbitmap,(10,125))
if config['display']['orientation'] == 180 :
image=image.rotate(180, expand=True)
if config['display']['orientation'] == 90 or config['display']['orientation'] == 270 :
epd = epd2in7.EPD()
epd.Init_4Gray()
image = Image.new('L', (epd.height, epd.width), 255) # 255: clear the image with white
draw = ImageDraw.Draw(image)
draw.text((100,100),"7day : "+pricechange,font =font_date,fill = 0)
# Print price to 5 significant figures
# draw.text((20,120),symbolstring,font =fonthiddenprice,fill = 0)
draw.text((10,120),symbolstring+pricenowstring,font =fontHorizontal,fill = 0)
image.paste(sparkbitmap,(80,50))
image.paste(tokenimage, (0,0))
draw.text((85,5),str(time.strftime("%a %H:%M %d %b %Y")),font =font_date,fill = 0)
if config['display']['orientation'] == 270 :
image=image.rotate(180, expand=True)
# This is a hack to deal with the mirroring that goes on in 4Gray Horizontal
image = ImageOps.mirror(image)
# If the display is inverted, invert the image usinng ImageOps
if config['display']['inverted'] == True:
image = ImageOps.invert(image)
# Send the image to the screen
epd.display_4Gray(epd.getbuffer_4Gray(image))
epd.sleep()
def main():
logging.basicConfig(level=logging.DEBUG)
try:
logging.info("epd2in7 BTC Frame")
# Get the configuration from config.yaml
with open(configfile) as f:
config = yaml.load(f, Loader=yaml.FullLoader)
logging.info(config)
GPIO.setmode(GPIO.BCM)
config['display']['orientation']=int(config['display']['orientation'])
currencystring = config['ticker']['currency']
crypto_list = currencystring.split(",")
crypto_list = [x.strip(' ') for x in crypto_list]
logging.info(crypto_list)
fiatstring=config['ticker']['fiatcurrency']
fiat_list = fiatstring.split(",")
fiat_list = [x.strip(' ') for x in fiat_list]
logging.info(fiat_list)
coinnumber = 0
CURRENCY=crypto_list[coinnumber]
FIAT=fiat_list[coinnumber]
logging.info(CURRENCY)
logging.info(FIAT)
key1 = 5
key2 = 6
key3 = 13
key4 = 19
GPIO.setup(key1, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(key2, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(key3, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(key4, GPIO.IN, pull_up_down=GPIO.PUD_UP)
# Note that there has been no data pull yet
datapulled=False
# Time of start
lastcoinfetch = time.time()
while True:
key1state = GPIO.input(key1)
key2state = GPIO.input(key2)
key3state = GPIO.input(key3)
key4state = GPIO.input(key4)
if internet():
if key1state == False:
logging.info('Cycle currencies')
# Rotate the array of currencies from config.... [a b c] becomes [b c a]
crypto_list = crypto_list[1:]+crypto_list[:1]
CURRENCY=crypto_list[0]
# Write back to config file
config['ticker']['currency']=",".join(crypto_list)
with open(configfile, 'w') as f:
data = yaml.dump(config, f)
logging.info(CURRENCY)
# get data
pricestack=getData(CURRENCY,FIAT)
# save time of last data update
lastcoinfetch = time.time()
# generate sparkline
makeSpark(pricestack)
# update display
updateDisplay(config, pricestack, CURRENCY,FIAT)
# time.sleep(0.2)
if key2state == False:
logging.info('Rotate - 90')
config['display']['orientation'] = (config['display']['orientation']+90) % 360
# update display
updateDisplay(config, pricestack, CURRENCY,FIAT)
# Write back to config file
with open(configfile, 'w') as f:
data = yaml.dump(config, f)
# time.sleep(0.2)
if key3state == False:
logging.info('Invert Display')
if config['display']['inverted'] == True:
config['display']['inverted'] = False
else:
config['display']['inverted'] = True
# update display
updateDisplay(config, pricestack, CURRENCY,FIAT)
with open(configfile, 'w') as f:
data = yaml.dump(config, f)
lastcoinfetch=time.time()
# time.sleep(0.2)
if key4state == False:
logging.info('Cycle fiat')
# Rotate the array of currencies from config.... [a b c] becomes [b c a]
fiat_list = fiat_list[1:]+fiat_list[:1]
FIAT=fiat_list[0]
# Write back to config file
config['ticker']['fiatcurrency']=",".join(fiat_list)
with open(configfile, 'w') as f:
data = yaml.dump(config, f)
logging.info(FIAT)
# get data
pricestack=getData(CURRENCY,FIAT)
# save time of last data update
lastcoinfetch = time.time()
# generate sparkline
makeSpark(pricestack)
# update display
updateDisplay(config, pricestack, CURRENCY,FIAT)
# time.sleep(0.2)
if (time.time() - lastcoinfetch > float(config['ticker']['updatefrequency'])) or (datapulled==False):
# get data
pricestack=getData(CURRENCY,FIAT)
# save time of last data update
lastcoinfetch = time.time()
# generate sparkline
makeSpark(pricestack)
# update display
updateDisplay(config, pricestack,CURRENCY,FIAT)
# Note that we've visited the internet
datapulled = True
lastcoinfetch=time.time()
except IOError as e:
logging.info(e)
except KeyboardInterrupt:
logging.info("ctrl + c:")
epd2in7.epdconfig.module_exit()
exit()
if __name__ == '__main__':
main()