-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
359 lines (290 loc) · 10.5 KB
/
main.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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
"""
RSSにアクセスして記事のタイトルと概要を表示するプログラム
Copyright (c) 2023 led-mirage
"""
from machine import Pin, I2C
import gc
import io
import machine
import network
import sys
import time
import urequests
import ssd1306_mfont
from ssd1306 import SSD1306_I2C
from mfont import mfont
import ntp
from date import Date
# アプリケーション名
APP_NAME = "RSS Display 1.2\n for ESP32"
# WiFiアクセスポイント
WIFI_ACCESS_POINTS = [
{"ssid": "ssid_A", "password": "pass_A"},
{"ssid": "ssid_B", "password": "pass_B"},
]
# RSSサイト
RSS_SITES = [
{"name": "NHK主要ニュース", "url": "https://www.nhk.or.jp/rss/news/cat0.xml"},
{"name": "CNET Japan", "url": "http://feeds.japan.cnet.com/rss/cnet/all.rdf"},
{"name": "GIGAZINE", "url": "https://gigazine.net/news/rss_2.0/"},
{"name": "ITMedia 科学", "url": "https://rss.itmedia.co.jp/rss/2.0/news_technology.xml"},
{"name": "ITMedia セキュリティ", "url": "https://rss.itmedia.co.jp/rss/2.0/news_security.xml"},
{"name": "ITMedia 国内", "url": "https://rss.itmedia.co.jp/rss/2.0/news_domestic.xml"},
]
# OLED用定数(SSD1306)
I2C_ID = 0 # I2C ID
I2C_FREQ = 400000 # I2C バス速度
OLED_WIDTH = 128 # OLEDの横ドット数
OLED_HEIGHT = 64 # OLEDの縦ドット数
OLED_ADDR = 0x3c # OLEDのI2Cアドレス
OLED_SCL = 22 # OLEDのSCLピン
OLED_SDA = 21 # OLEDのSDAピン
# OLEDディスプレイのインスタンスの生成
i2c = I2C(I2C_ID, scl=Pin(OLED_SCL), sda=Pin(OLED_SDA), freq=I2C_FREQ)
oled = SSD1306_I2C(OLED_WIDTH, OLED_HEIGHT, i2c, addr=OLED_ADDR)
oled.contrast(96)
oled.invert(False)
# タクトスイッチ関係
TACT_SW_PIN = 18
tact_sw = Pin(TACT_SW_PIN, Pin.IN, Pin.PULL_UP)
tact_sw_pre_time = 0 # タクトスイッチが押された時間(システム起動時からの経過時間ms)
# フォントサイズ
font_size = 14
# アプリケーションデータファイル
APP_DATA_INDEX = "app_rss_index.txt"
APP_DATA_FONTSIZE = "app_rss_fontsize.txt"
# メイン
def main():
global font_size
# 動作周波数変更(240MHz)
machine.freq(240000000)
# カレントRSSインデックスを読み込む
current_index = read_current_index(len(RSS_SITES) - 1)
# フォントサイズを読み込む
font_size = read_font_size()
# タクトスイッチ割り込みの有効化
tact_sw.irq(trigger=Pin.IRQ_RISING, handler=tact_sw_pushed)
# アプリケーション名の表示
oled.fill(0)
oled.drawText(APP_NAME, 0, 0, font_size, 50)
time.sleep(2)
# WiFiに接続する
oled.fill(0)
oled.drawText("Connect to WiFi...", 0, 0, font_size, 50)
if wifi_connect():
oled.fill(0)
oled.drawText("Connected!", 0, 0, font_size, 50)
else:
oled.fill(0)
oled.drawText("WiFi Connect Failed!", 0, 0, font_size, 50)
oled.drawText("Application Terminated.", 0, font_size*2, font_size, 50)
sys.exit()
# NTPで時刻合わせをする
if ntp.synchronize_time():
today = Date.today()
oled.drawText(today.text(), 0, 30, font_size, 50)
time.sleep(2)
else:
oled.fill(0)
oled.drawText("NTP Connect Failed!", 0, 0, font_size, 50)
oled.drawText("Application Terminated.", 0, font_size*2, font_size, 50)
sys.exiit
# メインループ
while True:
for i in range(current_index, len(RSS_SITES)):
gc.collect()
site = RSS_SITES[i]
write_current_index(i + 1)
# RSSにアクセスする
oled.fill(0)
oled.drawText(f"Access to RSS...\n{site['name']}", 0, 0, font_size, 50)
items = read_rss(site["url"])
# タイトルと説明を表示する
today = Date.today()
for item in items:
days = today - item.date
if days <= 1:
gc.collect()
print(f"{item.title}")
oled.fill(0)
oled.drawText(site["name"], 0, 0, font_size, 0)
time.sleep(1)
oled.fill(0)
oled.drawText("★ " + item.title + "\n" + item.date.text(), 0, 0, font_size, 50)
time.sleep(3)
oled.fill(0)
oled.drawText(item.description
, 0, 0, font_size, 50)
time.sleep(5)
current_index = 0
# WiFiに接続する
def wifi_connect():
is_connected = False
try_count = 0
while is_connected == False and try_count < 10:
for point in WIFI_ACCESS_POINTS:
is_connected = wifi_connect_sub(point["ssid"], point["password"], 10)
if is_connected == True:
break
try_count += 1
return is_connected
# WiFiに接続する(サブルーチン)
def wifi_connect_sub(ssid, password, timeout):
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.disconnect()
wifi.connect(ssid, password)
print(f"WiFi({ssid}) Connecting..", end="")
count = 1
while wifi.isconnected() == False:
print(".", end="")
time.sleep(1)
count += 1
if count >= timeout:
print("Timeout")
return False
print("Connected!")
return True
# RSSからアイテムのリストを取得する
def read_rss(url):
items = []
print(f"access to {url}")
response = urequests.get(url)
stream = io.StringIO(response.text)
is_item = False
item = None
for line in stream:
line_text = line.strip()
if line_text.startswith("<item"):
item = RssItem()
is_item = True
if line_text.endswith("</item>"):
items.append(item)
is_item = False
if is_item and line_text.startswith("<title>"):
item.title = strip_tags(line_text.replace("<title>", "").replace("</title>", ""))
if is_item and line_text.startswith("<description>"):
item.description = strip_tags(line_text.replace("<description>", "").replace("</description>", ""))
if is_item and line_text.startswith("<dc:date>"):
dcDate = line_text.replace("<dc:date>", "").replace("</dc:date>", "")
item.date = convert_dcdate_to_date(dcDate)
if is_item and line_text.startswith("<pubDate>"):
pubDate = line_text.replace("<pubDate>", "").replace("</pubDate>", "")
item.date = convert_pubdate_to_date(pubDate)
return items
# 簡易HTML解析・タグを除去する
def strip_tags(html_text):
def _strip_tags(html):
clean_text = ""
if html.startswith("<![CDATA["):
html = html.replace("<![CDATA[", "")
html = html.rstrip("]>")
taglevel = 0
intag = False
endtag = False
instring = False
for c in html:
if c == "<":
intag = True
endtag = False
continue
elif c == ">":
if endtag:
taglevel -= 1
else:
taglevel += 1
intag = False
continue
elif c == '"' or c == "'":
instring = not instring
if intag:
if instring == False and c == "/":
endtag = True
continue
if taglevel == 0:
clean_text += c
clean_text = clean_text.replace("<", "<").replace(">", ">")
return clean_text
html_text = _strip_tags(html_text)
html_text = _strip_tags(html_text) # 2Pass
return html_text
# RSSのdc:date要素から年月日を取得する
def convert_dcdate_to_date(date_str):
try:
date_parts = date_str.split('T')[0]
year, month, day = date_parts.split('-')
return Date(int(year), int(month), int(day))
except:
return Date()
# RSSのpubDate要素から年月日を取得する
def convert_pubdate_to_date(date_str):
months = {
'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6,
'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12
}
try:
date_parts = date_str.split()
day, month_str, year = date_parts[1], date_parts[2], date_parts[3]
month = months.get(month_str, None)
if month is None:
raise ValueError("Invalid pubDate Format")
return Date(int(year), int(month), int(day))
except:
return Date()
# カレントのRSSサイトのインデックス番号を取得する
def read_current_index(max_index):
return read_file(APP_DATA_INDEX, maxval=max_index)
# カレントのRSSサイトのインデックス番号を書き込む
def write_current_index(index):
write_file(APP_DATA_INDEX, index)
# フォントサイズを取得する
def read_font_size():
return read_file(APP_DATA_FONTSIZE, default=14)
# フォントサイズを書き込む
def write_font_size(font_size):
write_file(APP_DATA_FONTSIZE, font_size)
# ファイルから数値を読み込む
def read_file(filename, default=0, minval=None, maxval=None):
try:
with open(filename, 'r') as file:
text = file.read()
val = int(text)
if minval != None and val < minval:
val = default
if maxval != None and val > maxval:
val = default
return val
except Exception as e:
print(e)
return default
# ファイルに数値を書き込む
def write_file(filename, val):
with open(filename, 'w') as file:
file.write(f"{val}")
# タクトスイッチ割込みハンドラ
# フォントサイズを変更する
def tact_sw_pushed(pin):
global tact_sw_pre_time, font_size
now = time.ticks_ms()
pre_font_size = font_size
if now - tact_sw_pre_time > 500: # 二度押し防止
if font_size == 12:
font_size = 14
elif font_size == 14:
font_size = 16
else:
font_size = 12
tact_sw_pre_time = now
write_font_size(font_size)
print(f"font size: {font_size}px")
oled.fill_rect(0, 0, 128, pre_font_size, 0)
oled.text(f"font:{font_size}px", 2, 2)
oled.show()
# RSSアイテムクラス
class RssItem:
def __init__(self):
self.tille = ""
self.description = ""
self.date = Date()
if __name__ == "__main__":
main()