Ошибка памяти после получения данных из API Matrix Portal M4Python

Программы на Python
Ответить
Anonymous
 Ошибка памяти после получения данных из API Matrix Portal M4

Сообщение Anonymous »

Я работаю над проектом, используя Adafruit Matrix Portal M4. Цель состоит в том, чтобы получить данные из API MBTA и отобразить на светодиодной плате время ожидания следующих прибывающих поездов.
Я использую исходный код из: https://github.com/jegamboafuentes/Trai ... 25/current Software.git, и в настоящее время застрял в выяснении ошибки распределения памяти:
Считывание на последовательном мониторе это:
Adafruit CircuitPython 10.0.3 on 2025-10-17; Adafruit Matrix Portal M4 with samd51j19
>>>
soft reboot

Auto-reload is on. Simply save files over USB to run them or enter REPL to disable.
code.py output:
Warning: outlined_label.OutlinedLabel is deprecated, adafruit_display_text.bitmap_label.Label now supports outline functionality with the same API, it should be used instead.
Connecting to mywifi
Getting time from IP address
2025-12-29 15:32:05
Data source: https://www.mbta.com/schedules/finder_a ... irection=0
Free memory before variable: 22304 bytes
Retrieving data...Reply is OK!
Traceback (most recent call last):
File "code.py", line 181, in
File "code.py", line 52, in get_arrival_times2
File "adafruit_portalbase/network.py", line 638, in fetch_data
File "adafruit_portalbase/network.py", line 670, in _parse_data
File "adafruit_portalbase/network.py", line 735, in process_json
MemoryError: memory allocation failed, allocating 680 bytes

Code done running.

Код, который выполняется в данный момент — слегка изменен для отладки от этого создателя https://github.com/jegamboafuentes, приведен ниже:
Ошибка возникает в функции get_arrival_times2() при stop_trains = network.fetch_data(DATA_SOURCE2)
Казалось бы, перед выборкой достаточно памяти данные из API??? Я уже пробовал добавлять в код некоторые операторы gc.collect() и удалил все ненужные библиотеки и файлы растровых изображений, чтобы ограничить объем, хранимый на устройстве....
Любая информация о том, что здесь происходит и как обойти эту ошибку, будем очень признательны!
#August 25 2023
#V2
#Jorge Enrique Gamboa Fuentes
#Subway schedule board - single direction
#Data from: Boston - MBTA
# .l. - .l. - .l. - .l. - .l. - .l. - .l. - .l. - .l. - .l. - .l. - .l. - .l. - .l. - .l. - .l. -

import time
import microcontroller
from board import NEOPIXEL
import displayio
import adafruit_display_text.label
from adafruit_datetime import datetime
from adafruit_bitmap_font import bitmap_font
from adafruit_matrixportal.matrix import Matrix
from adafruit_matrixportal.network import Network
import json
import gc
#CONFIGURABLE PARAMETERS
#-*-/-*-\-*--*-/-*-\-*--*-/-*-\-*--*-/-*-\-*--*-/-*-\-*--*-/-*-\-*--*-/-*-\-*--*-/-*-\-*-

BOARD_TITLE = 'Bowdoin'
STOP_ID = 'place-wondl'
DIRECTION_ID = '0'
ROUTE = 'Blue'
BACKGROUND_IMAGE = 'Tred-dashboard.bmp'
PAGE_LIMIT = '3'
DATA_SOURCE = 'https://api-v3.mbta.com/predictions?fil ... rture_time'
DATA_SOURCE2 = 'https://www.mbta.com/schedules/finder_a ... irection=0'

UPDATE_DELAY = 15
SYNC_TIME_DELAY = 30
MINIMUM_MINUTES_DISPLAY = 9
ERROR_RESET_THRESHOLD = 3
#-*-/-*-\-*--*-/-*-\-*--*-/-*-\-*--*-/-*-\-*--*-/-*-\-*--*-/-*-\-*--*-/-*-\-*--*-/-*-\-*-

def get_arrival_in_minutes_from_now(now, date_str):
train_date = datetime.fromisoformat(date_str).replace(tzinfo=None) # Remove tzinfo to be able to diff dates
return round((train_date-now).total_seconds()/60.0)

#New 8/25/23 - this function gets directly the time from the API
def get_arrival_times2():
now = datetime.now()
print(now)
print("Data source: "+DATA_SOURCE2)
print("Free memory before variable: {} bytes".format(gc.mem_free()))
stop_trains = network.fetch_data(DATA_SOURCE2)
print(stop_trains)
res = json.loads(stop_trains)
print(res)
times = []
for entry in res:
try:
time = entry['realtime']['prediction']['time']
print(entry['realtime']['prediction']['time'])
if time[0] == 'arriving':
times.append('brding')
else:
times.append("{:02}".format(int(time[0])) + ' ' + time[2])
except KeyError:
continue
if len(times) == 3:
break
return times

def text_formating(trainMinutes):
textFormated = ""
if(trainMinutes last_time_sync + SYNC_TIME_DELAY:
# Sync clock to minimize time drift
network.get_local_time()
last_time_sync = time.monotonic()
arrivals = get_arrival_times2()
update_text2(*arrivals)
except (ValueError, RuntimeError) as e:
print("Some error occured, retrying! -", e)
error_counter = error_counter + 1
if error_counter > ERROR_RESET_THRESHOLD:
microcontroller.reset()

time.sleep(UPDATE_DELAY)


Подробнее здесь: https://stackoverflow.com/questions/798 ... -portal-m4
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Python»