Compare commits
No commits in common. "master" and "diego" have entirely different histories.
|
@ -1,3 +1 @@
|
|||
data/
|
||||
images
|
||||
*pycache*
|
||||
data/*
|
|
@ -0,0 +1,20 @@
|
|||
# Usa una imagen base de Python
|
||||
FROM python:3.8
|
||||
|
||||
# Establece el directorio de trabajo en el contenedor
|
||||
WORKDIR /app
|
||||
|
||||
# Copia el archivo requirements.txt al contenedor
|
||||
COPY requirements.txt requirements.txt
|
||||
|
||||
# Instala las dependencias
|
||||
RUN pip install -r requirements.txt
|
||||
|
||||
# Copia el archivo de configuración de Jupyter
|
||||
COPY jupyter_notebook_config.py /root/.jupyter/
|
||||
|
||||
# Expone el puerto 8888 para Jupyter Notebook
|
||||
EXPOSE 8888
|
||||
|
||||
# Ejecuta Jupyter Notebook cuando el contenedor se inicie
|
||||
CMD ["jupyter", "notebook", "--ip=0.0.0.0", "--port=8888", "--no-browser", "--allow-root"]
|
|
@ -1,15 +0,0 @@
|
|||
# Usa una imagen base de Python
|
||||
FROM python:3.8
|
||||
|
||||
# Establece el directorio de trabajo en el contenedor
|
||||
WORKDIR /app
|
||||
|
||||
# Copia el archivo requirements.txt al contenedor
|
||||
COPY requirements.txt requirements.txt
|
||||
COPY app.py app.py
|
||||
|
||||
# Instala las dependencias
|
||||
RUN pip install -r requirements.txt --no-cache-dir
|
||||
|
||||
# Ejecuta app.py
|
||||
CMD ["python", "app.py"]
|
|
@ -1,43 +0,0 @@
|
|||
# Generación de Póster de Bus
|
||||
En el directorio raiz del respositorio pasamos al carpeta:
|
||||
|
||||
```bash
|
||||
cd GenPoster
|
||||
```
|
||||
|
||||
## Construir la Imagen Docker
|
||||
Primero, construye la imagen Docker que contiene todas las dependencias necesarias:
|
||||
|
||||
```bash
|
||||
docker build -t bus_poster .
|
||||
```
|
||||
|
||||
## Ejecutar el Contenedor Docker
|
||||
Utiliza el script ```run_container.sh``` para ejecutar el contenedor. Este script monta las carpetas locales necesarias y inicia el contenedor. El contenedor se eliminará automáticamente después de su ejecución debido al parámetro ```--rm```.
|
||||
|
||||
```bash
|
||||
./run_container.sh
|
||||
```
|
||||
|
||||
Nota: Asegúrate de que el script ```run_container.sh``` tenga permisos de ejecución. Si no es así, ejecuta:
|
||||
```bash
|
||||
chmod +x run_container.sh
|
||||
```
|
||||
|
||||
## Generación y Almacenamiento del Póster
|
||||
Al ejecutar el contenedor, el script ```app.py``` se iniciará automáticamente y realizará lo siguiente:
|
||||
|
||||
- Calcula el tiempo restante hasta la llegada del autobús.
|
||||
- Genera visualizaciones con los detalles del autobús y el tiempo restante.
|
||||
- Guarda la imagen generada en una carpeta local mapeada al contenedor.
|
||||
|
||||
Por el momento esta funcionando con datos de prueba, eventualmente se usará como datos de entrada las respuestas del endpoint.
|
||||
|
||||
## Acceso a la Imagen Generada
|
||||
La imagen del póster se guardará en la carpeta local especificada en el script ```run_container.sh```. Puedes acceder a ella directamente desde esta carpeta en tu máquina local.
|
||||
|
||||
## Ejemplo de Imagen Generada
|
||||
|
||||
Actualmente se están generando imagenes para alimentar un arreglo de pantallas P4 de 2x1, por lo tanto se ajustaron las dimensiones para esa configuración.
|
||||
|
||||

|
213
GenPoster/app.py
|
@ -1,213 +0,0 @@
|
|||
from scripts.Poster.MyDraw import MyDraw
|
||||
from scripts.Poster.BusPoster import BusPoster
|
||||
from scripts.Poster.TimeAnnouncement import TimeAnnouncement
|
||||
import numpy as np
|
||||
from datetime import datetime, timedelta
|
||||
from import_data import export_data
|
||||
from PIL import Image
|
||||
import subprocess
|
||||
from getData import Paradero
|
||||
import os
|
||||
import time
|
||||
|
||||
os.environ['TZ'] = 'America/Santiago'
|
||||
time.tzset()
|
||||
|
||||
def reescalar_imagen(input_path, output_path, nuevo_ancho, nuevo_alto):
|
||||
try:
|
||||
# Abrir la imagen original
|
||||
imagen = Image.open(input_path)
|
||||
|
||||
# Reescalar la imagen
|
||||
imagen_redimensionada = imagen.resize((nuevo_ancho, nuevo_alto))
|
||||
|
||||
# Guardar la imagen redimensionada en el nuevo archivo
|
||||
imagen_redimensionada.save(output_path)
|
||||
# print("Imagen redimensionada y guardada con éxito en", output_path)
|
||||
|
||||
except:
|
||||
import traceback
|
||||
print(traceback.format_exc())
|
||||
|
||||
def aprox(n):
|
||||
return int(np.round(n))
|
||||
|
||||
def approx_km(data):
|
||||
distance_meters = data["distance"]
|
||||
distance_km = distance_meters / 100 # Convert meters to kilometers
|
||||
approx_km = int(np.round(distance_km)) # Take only the integer part of the distance in kilometers
|
||||
approx_km = approx_km/10.0
|
||||
return approx_km
|
||||
|
||||
def calc_remaining_time(data):
|
||||
arrival_time = data["timeLabel"][:-3]
|
||||
target_time = datetime.strptime(arrival_time, "%H:%M").time()
|
||||
current_time = datetime.now().time()
|
||||
|
||||
if current_time < target_time:
|
||||
remaining_time = datetime.combine(datetime.today(), target_time) - datetime.combine(datetime.today(), current_time)
|
||||
else:
|
||||
remaining_time = datetime.combine(datetime.today() + timedelta(days=1), target_time) - datetime.combine(datetime.today(), current_time)
|
||||
|
||||
remaining_minutes = int(remaining_time.total_seconds() // 60)
|
||||
return remaining_minutes
|
||||
|
||||
def obtain_min_max_time(remaining_time):
|
||||
if type(remaining_time) != int:
|
||||
return "N/A", "N/A"
|
||||
elif remaining_time == 1:
|
||||
return 0, 1
|
||||
elif remaining_time == 2:
|
||||
return 1, 2
|
||||
elif 2 <= remaining_time <= 5:
|
||||
return 2, 5
|
||||
elif remaining_time > 5 and remaining_time <= 7:
|
||||
return 5, 7
|
||||
elif remaining_time > 7 and remaining_time <= 10:
|
||||
return 7, 10
|
||||
else:
|
||||
return 10, remaining_time
|
||||
|
||||
###################################################################
|
||||
# Parametros para generar la imagen
|
||||
# "direction": "R", Indicador de la dirección en la que va el bus
|
||||
# "distance": 1948.575483806973. Distancia en m
|
||||
# "licensePlate": "LJHA57", Patente del bus
|
||||
# "route": "401", Linea de bus
|
||||
# "timeLabel": "09:49", Hora de llegada al paradero
|
||||
|
||||
# theme: Tema de la pantalla "day/night"
|
||||
# 'number_background_color': 'yellow', Color del fondo para el numero
|
||||
# 'letter_background_color': 'green', Color del fondo para la letra
|
||||
|
||||
def main():
|
||||
bus_stop = Paradero()
|
||||
|
||||
data = bus_stop.get_data()
|
||||
if data is not None:
|
||||
data1 = data[0]
|
||||
data2 = data[1]
|
||||
|
||||
# print(data)
|
||||
|
||||
# Calcula el tiempo restante a la llegada
|
||||
remaining_time1 = data1['timeRemaining']
|
||||
remaining_time2 = data2['timeRemaining']
|
||||
# Obtiene valores máximos y mínimo de rangos para desplegar en pantalla
|
||||
min_time1, max_time1 = obtain_min_max_time(remaining_time1)
|
||||
min_time2, max_time2 = obtain_min_max_time(remaining_time2)
|
||||
ruta1 = data1['route']
|
||||
direccion1 = data1['direction']
|
||||
ruta2 = data2['route']
|
||||
direccion2 = data2['direction']
|
||||
|
||||
else:
|
||||
remaining_time1 = 'N/A'
|
||||
remaining_time2 = 'N/A'
|
||||
min_time1 = 'N/A'
|
||||
min_time2 = 'N/A'
|
||||
max_time1 = 'N/A'
|
||||
max_time2 = 'N/A'
|
||||
ruta1 = "00"
|
||||
direccion1 = "X"
|
||||
ruta2 = "99"
|
||||
direccion2 = "Y"
|
||||
|
||||
# Selecciona el tema
|
||||
theme = 'night'
|
||||
|
||||
# Alto y ancho de la imagen en pixeles
|
||||
#height, width = 40, 160
|
||||
height, width = 200, 800
|
||||
|
||||
# Inicia el dibujo y setea el tema
|
||||
full_panel = MyDraw(height=height, width=width)
|
||||
full_panel.set_theme(theme)
|
||||
full_panel.start_draw()
|
||||
|
||||
# Agrega el anuncio de los minutos restante al arribo
|
||||
time_anmc1 = TimeAnnouncement(aprox((2/5)*height), aprox((2/5)*width))
|
||||
time_anmc1.set_theme(theme)
|
||||
time_anmc1.start_draw()
|
||||
# time_anmc1.set_background()
|
||||
# time_anmc1.set_base_text()
|
||||
time_anmc1.set_remaining_text(data[0]['timeRemaining'])
|
||||
|
||||
# Agrega el anuncio de los minutos restante al arribo
|
||||
time_anmc2 = TimeAnnouncement(aprox((2/5)*height), aprox((2/5)*width))
|
||||
time_anmc2.set_theme(theme)
|
||||
time_anmc2.start_draw()
|
||||
# time_anmc2.set_background()
|
||||
# time_anmc2.set_base_text()
|
||||
# time_anmc2.set_min_max_text(min_time=min_time2, max_time=max_time2)
|
||||
time_anmc2.set_remaining_text(data[1]['timeRemaining'])
|
||||
|
||||
# Genera la imagen de la linea del bus
|
||||
poster1 = BusPoster(aprox(1.1*(1/3)*height), aprox(1.1*(1/3)*width))
|
||||
poster1.set_theme(theme)
|
||||
poster1.start_draw()
|
||||
|
||||
bus_announcement_1 = {
|
||||
'proportion': 0.6,
|
||||
'width_border': 3,
|
||||
# 'font_size': 11,
|
||||
'font_size': 80,
|
||||
'number_background_color': 'yellow',
|
||||
'letter_background_color': data[0]['number_background_color'],
|
||||
}
|
||||
|
||||
# Se setean los parametros
|
||||
poster1.set_params(bus_announcement_1)
|
||||
poster1.load_barlow()
|
||||
poster1.set_colors()
|
||||
|
||||
# Se setea la ruta y la direccion en la que va
|
||||
poster1.set_bus_number(bus_number=ruta1)
|
||||
poster1.set_bus_letter(bus_letter=direccion1)
|
||||
|
||||
# Genera la imagen de la linea del bus
|
||||
poster2 = BusPoster(aprox(1.1*(1/3)*height), aprox(1.1*(1/3)*width))
|
||||
poster2.set_theme(theme)
|
||||
poster2.start_draw()
|
||||
|
||||
bus_announcement_2 = {
|
||||
'proportion': 0.6,
|
||||
'width_border': 3,
|
||||
# 'font_size': 11,
|
||||
'font_size': 80,
|
||||
'number_background_color': 'yellow',
|
||||
'letter_background_color': data[1]['number_background_color'],
|
||||
}
|
||||
|
||||
# Se setean los parametros
|
||||
poster2.set_params(bus_announcement_2)
|
||||
poster2.load_barlow()
|
||||
poster2.set_colors()
|
||||
# Se setea la ruta y la direccion en la que va
|
||||
poster2.set_bus_number(bus_number=ruta2)
|
||||
poster2.set_bus_letter(bus_letter=direccion2)
|
||||
|
||||
# Se agregan todas las imagenes al canvas
|
||||
full_panel.add_image(time_anmc1, (aprox((0.55)*width), aprox(0.05*height)))
|
||||
full_panel.add_image(time_anmc2, (aprox((0.55)*width), aprox(0.45*height)))
|
||||
full_panel.add_image(poster1, (aprox((0.05)*width), aprox((0.1)*height)))
|
||||
full_panel.add_image(poster2, (aprox((0.05)*width), aprox((0.5)*height)))
|
||||
#full_panel.add_image(bm, (aprox(0.02*width),aprox((1/6)*height)))
|
||||
full_panel.get_image()
|
||||
full_panel.save_image('/srv/ledram/poster.png')
|
||||
|
||||
nuevo_alto = 40 # Reemplaza con el alto deseado en píxeles
|
||||
nuevo_ancho = 160 # Reemplaza con el ancho deseado en píxeles
|
||||
input_path = f'/srv/ledram/poster.png'
|
||||
output_path = '/srv/ledram/next.png'
|
||||
|
||||
reescalar_imagen(input_path, output_path, nuevo_ancho, nuevo_alto)
|
||||
subprocess.run(['cp', output_path, '/srv/ledram/current.png'])
|
||||
|
||||
|
||||
from apscheduler.schedulers.blocking import BlockingScheduler
|
||||
|
||||
if __name__ == '__main__':
|
||||
sched = BlockingScheduler()
|
||||
sched.add_job(main, 'interval', seconds=15)
|
||||
sched.start()
|
Before Width: | Height: | Size: 14 KiB |
Before Width: | Height: | Size: 14 KiB |
Before Width: | Height: | Size: 3.0 KiB |
|
@ -1,122 +0,0 @@
|
|||
#!/usr/bin/env python3
|
||||
|
||||
import requests
|
||||
import pytz
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
|
||||
class Paradero:
|
||||
def __init__(self):
|
||||
# Dispositivo
|
||||
self.id = "panel-pruebas-2"
|
||||
|
||||
# Autentificación data
|
||||
self.url_auth = 'https://gestion.tdt-dev.ilab.cl/api/auth/'
|
||||
self.rut = "11111111-1"
|
||||
self.password = "usuario1"
|
||||
|
||||
# Token obtenido luego del 'login'
|
||||
self.token = self.__get_token()
|
||||
# print(self.token)
|
||||
|
||||
# URL de la API para obtener los datos de los recorridos
|
||||
self.url_getinfodevice = 'https://gestion.tdt-dev.ilab.cl/api/dispositivos/getInfoDevice/'
|
||||
self.data = None
|
||||
self.bus_list = []
|
||||
self.servicios = ["12Q", "56O"]
|
||||
|
||||
|
||||
def __get_token(self):
|
||||
auth = '''{
|
||||
"rut": "11111111-1",
|
||||
"password": "usuario1"
|
||||
}'''
|
||||
|
||||
response = requests.post(self.url_auth, data=auth)
|
||||
|
||||
# Estado de la respuesta
|
||||
if response.status_code == 200:
|
||||
return response.json()['token']
|
||||
else:
|
||||
# print(response)
|
||||
return None
|
||||
|
||||
def get_data(self):
|
||||
# Datos para la solicitud
|
||||
data_getinfodevice = {
|
||||
"GetInfoDevice": {
|
||||
"idDispositivo": self.id,
|
||||
"KeyAuthorizacion": "tokenSinUso" #Autentificacion de mentira sisisi
|
||||
}
|
||||
}
|
||||
|
||||
if self.token is not None:
|
||||
#Aquí se ingresa el token obtenido anteriormente
|
||||
headers_getinfodevice = {
|
||||
'Authorization': f'Bearer {self.token}',
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
|
||||
# Request
|
||||
response = requests.post(self.url_getinfodevice, json=data_getinfodevice, headers=headers_getinfodevice)
|
||||
|
||||
self.data = self.__serialize_data(response)
|
||||
return self.data
|
||||
|
||||
def __generate_bus_list(self, info):
|
||||
data_main = {}
|
||||
zona_horaria_santiago = pytz.timezone('America/Santiago')
|
||||
hora_actual_santiago = datetime.now(zona_horaria_santiago).time()
|
||||
|
||||
for i in range(len(info["GetInfoDeviceResponse"]["DetalleLineas"])):
|
||||
|
||||
data = info["GetInfoDeviceResponse"]["DetalleLineas"][i]
|
||||
if data["Descripcion"] not in self.servicios:
|
||||
continue
|
||||
|
||||
bus_info = {}
|
||||
if len(data['Llegadas']) > 0 and data["Llegadas"][0]["DistanciaGPS"] is not None:
|
||||
bus_info["distance"] = data["Llegadas"][0]["DistanciaGPS"]
|
||||
bus_info["timeLabel"] = data["Llegadas"][0]["EstimadaGPS"]
|
||||
bus_info["patente"] = data["Llegadas"][0]["patente"]
|
||||
bus_hour = datetime.strptime(bus_info["timeLabel"], "%H:%M:%S").time().hour if datetime.strptime(bus_info["timeLabel"], "%H:%M:%S").time().hour != 0 else 24
|
||||
diff = timedelta(
|
||||
hours = bus_hour - hora_actual_santiago.hour,
|
||||
minutes = datetime.strptime(bus_info["timeLabel"], "%H:%M:%S").time().minute - hora_actual_santiago.minute,
|
||||
seconds=datetime.strptime(bus_info["timeLabel"], "%H:%M:%S").time().second - hora_actual_santiago.second
|
||||
)
|
||||
# print(diff.total_seconds())
|
||||
bus_info["timeLabel"] = "m"
|
||||
|
||||
if data['Llegadas'][0]['textoLlegada'].startswith("Entre"):
|
||||
data['Llegadas'][0]['textoLlegada'] = data['Llegadas'][0]['textoLlegada'][5:]
|
||||
cut = data['Llegadas'][0]['textoLlegada'].index("min")+3
|
||||
bus_info["timeRemaining"] = data['Llegadas'][0]['textoLlegada'][:cut]
|
||||
else:
|
||||
bus_info["distance"] = "-"
|
||||
bus_info["timeLabel"] = "Sin Info"
|
||||
bus_info["timeRemaining"] = "Sin Dato"
|
||||
|
||||
bus_info["route"] = data["Descripcion"][:-1] if data["Descripcion"] is not None else "-"
|
||||
bus_info["direction"] = data["Descripcion"][-1] if data["Descripcion"] is not None else "-"
|
||||
bus_info["number_background_color"] = "#{}".format(data["colorFondo"])
|
||||
bus_info["letter_background_color"] = "#{}".format(data["colorTexto"])
|
||||
|
||||
data_main[data["Descripcion"]] = bus_info
|
||||
|
||||
# data_main = sorted(data_main, key=lambda x: x['timeRemaining'])
|
||||
salida = []
|
||||
for servicio in self.servicios:
|
||||
if servicio in data_main:
|
||||
salida.append(data_main[servicio])
|
||||
|
||||
self.bus_list = salida
|
||||
|
||||
# for d in data_main:
|
||||
# print(d['timeRemaining'], d['timeLabel'])
|
||||
|
||||
def __serialize_data(self, response):
|
||||
data = response.json()
|
||||
self.__generate_bus_list(data)
|
||||
|
||||
return self.bus_list
|
|
@ -1,98 +0,0 @@
|
|||
#!/usr/bin/env python3
|
||||
|
||||
import requests
|
||||
import json
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
def api_request():
|
||||
# URL de la API para "autentificación"
|
||||
url_auth = 'https://transporte.hz.kursor.cl/api/auth/'
|
||||
|
||||
# Datos para autentificar
|
||||
auth = '''{
|
||||
"username": "usuario1",
|
||||
"password": "usuario1"
|
||||
}'''
|
||||
|
||||
# Request
|
||||
token = requests.post(url_auth, data=auth)
|
||||
token = token.json()['token']
|
||||
|
||||
# URL de la API para info del paradero
|
||||
url_whoami = 'https://transporte.hz.kursor.cl/api/dispositivos/whoami/'
|
||||
|
||||
# Datos de la solicitud
|
||||
data_whoami = {
|
||||
"whoami": {
|
||||
"idDispositivo": "pled30-gtr",
|
||||
"KeyAuthorizacion": "token"
|
||||
}
|
||||
}
|
||||
|
||||
#Aquí se ingresa el token obtenido anteriormente
|
||||
headers_whoami = {
|
||||
'Authorization': f'Bearer {token}',
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
|
||||
response_whoami = requests.post(url_whoami, json=data_whoami, headers=headers_whoami) #Request
|
||||
Paradero = response_whoami.json()
|
||||
|
||||
url_getinfodevice = 'https://transporte.hz.kursor.cl/api/dispositivos/getInfoDevice/' # URL de la API para obtener los datos de los recorridos
|
||||
|
||||
# Datos para la solicitud
|
||||
data_getinfodevice = {
|
||||
"GetInfoDevice": {
|
||||
"idDispositivo": "00000000160f3b42b8:27:eb:0f:3b:42",
|
||||
"KeyAuthorizacion": "tokenSinUso"
|
||||
}
|
||||
}
|
||||
|
||||
#Aquí se ingresa el token obtenido anteriormente
|
||||
headers_getinfodevice = {
|
||||
'Authorization': f'Bearer {token}',
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
|
||||
# Request
|
||||
response_getinfodevice = requests.post(url_getinfodevice, json=data_getinfodevice, headers=headers_getinfodevice)
|
||||
info = response_getinfodevice.json()
|
||||
|
||||
return info
|
||||
|
||||
#--------------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
#Haciendo una lista de todos los buses de este paradero
|
||||
|
||||
def lista_buses(info):
|
||||
data_main = []
|
||||
hora_actual = datetime.now().time()
|
||||
|
||||
for i in range(len(info["GetInfoDeviceResponse"]["DetalleLineas"])):
|
||||
|
||||
data = info["GetInfoDeviceResponse"]["DetalleLineas"][i]
|
||||
|
||||
bus_info = {}
|
||||
bus_info["distance"] = data["Llegadas"][0]["DistanciaGPS"] if data["Llegadas"][0]["DistanciaGPS"] is not None else "-"
|
||||
bus_info["timeLabel"] = data["Llegadas"][0]["EstimadaGPS"] if data["Llegadas"][0]["EstimadaGPS"] is not None else "-"
|
||||
bus_info["route"] = data["Descripcion"][:-1] if data["Descripcion"] is not None else "-"
|
||||
bus_info["direction"] = data["Descripcion"][-1] if data["Descripcion"] is not None else "-"
|
||||
bus_info["number_background_color"] = data["colorFondo"]
|
||||
bus_info["letter_background_color"] = data["colorTexto"]
|
||||
bus_info["patente"] = data["Llegadas"][0]["patente"]
|
||||
diff = timedelta(hours = datetime.strptime(bus_info["timeLabel"], "%H:%M:%S").time().hour - hora_actual.hour,minutes = datetime.strptime(bus_info["timeLabel"], "%H:%M:%S").time().minute - hora_actual.minute,seconds=datetime.strptime(bus_info["timeLabel"], "%H:%M:%S").time().second - hora_actual.second)
|
||||
bus_info["timeRemaining"] = int(abs(diff.total_seconds() // 60))
|
||||
data_main.append(bus_info)
|
||||
|
||||
return data_main
|
||||
|
||||
#--------------------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
#Exportando datos
|
||||
def export_data():
|
||||
X = api_request()
|
||||
data_main = lista_buses(X)
|
||||
data_time = sorted(data_main, key=lambda x: x['timeRemaining'],reverse=True)
|
||||
|
||||
data_x = (data_time[0],data_time[1])
|
||||
return data_x
|
|
@ -1,28 +0,0 @@
|
|||
#!/bin/bash
|
||||
|
||||
if [ "$EUID" -ne 0 ]; then
|
||||
echo "Este script requiere permisos de root."
|
||||
exit
|
||||
fi
|
||||
|
||||
# set pwd to current directory
|
||||
cd "$(dirname "$0")"
|
||||
|
||||
#limpia el contenido del directorio de trabajo
|
||||
rm -rf /srv/parada*
|
||||
|
||||
mkdir /srv/parada_led
|
||||
|
||||
cp -rf *.py assets scripts /srv/parada_led
|
||||
|
||||
#Crea el servicio
|
||||
cp -rf parada_led.service /etc/systemd/system/parada_led.service
|
||||
|
||||
# Recarga e inicia automaticamente al prender.
|
||||
systemctl daemon-reload
|
||||
systemctl unmask parada_led.service
|
||||
systemctl enable parada_led.service
|
||||
|
||||
# Mensajes de salida
|
||||
echo "Debe reiniciar la Raspberry para que el servicio pueda iniciarse"
|
||||
echo "Luego para actualizar, solo debe modificar el el archivo '/srv/ledram/current.png' para actualizar la pantalla"
|
|
@ -1,12 +0,0 @@
|
|||
[Unit]
|
||||
Description=WebService Datos Parada
|
||||
After=local-fs.target
|
||||
|
||||
[Service]
|
||||
User=root
|
||||
WorkingDirectory=/srv/parada_led
|
||||
ExecStart=/usr/bin/python3 /srv/parada_led/app.py
|
||||
Restart=always
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
|
@ -1,5 +0,0 @@
|
|||
matplotlib
|
||||
requests
|
||||
Pillow
|
||||
numpy
|
||||
pytz
|
|
@ -1,11 +0,0 @@
|
|||
#!/bin/bash
|
||||
|
||||
# Rutas absolutas a las carpetas locales
|
||||
project_folder_path=$(pwd)
|
||||
data_path=$project_folder_path/data
|
||||
scripts_path=$project_folder_path/scripts
|
||||
assets_path=$project_folder_path/assets
|
||||
|
||||
# Ejecuta el contenedor con el enlace de carpeta local
|
||||
# docker run --rm -d -p 8888:8888 --name make_poster -v $data_path:/app/data -v $assets_path:/app/assets -v $scripts_path:/app/scripts -v $project_folder_path:/app bus_poster
|
||||
docker run --rm -d --name make_poster -v $project_folder_path:/app bus_poster
|
|
@ -1,195 +0,0 @@
|
|||
from MyDraw import MyDraw
|
||||
from BusPoster import BusPoster
|
||||
from TimeAnnouncement import TimeAnnouncement
|
||||
from DistanceAnnouncement import DistanceAnnouncement
|
||||
from BusPlate import BusPlate
|
||||
from BusImage import BusImage
|
||||
|
||||
import numpy as np
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
|
||||
def aprox(n):
|
||||
return int(np.round(n))
|
||||
|
||||
def load_data():
|
||||
data = {
|
||||
"direction": "R",
|
||||
"distance": 1948.575483806973,
|
||||
"epochTime": 1674650956,
|
||||
"latitude": -33.43729782104492,
|
||||
"licensePlate": "LJHA57",
|
||||
"longitude": -70.52730560302734,
|
||||
"realtime": True,
|
||||
"route": "401",
|
||||
"routeId": "401",
|
||||
"timeLabel": "09:49",
|
||||
"tripId": "401-I-L-005"
|
||||
}
|
||||
return data
|
||||
|
||||
def approx_km(data):
|
||||
distance_meters = data["distance"]
|
||||
distance_km = distance_meters / 100 # Convert meters to kilometers
|
||||
approx_km = int(np.round(distance_km)) # Take only the integer part of the distance in kilometers
|
||||
approx_km = approx_km/10.0
|
||||
return approx_km
|
||||
|
||||
def calc_remaining_time(data):
|
||||
arrival_time = data["timeLabel"]
|
||||
target_time = datetime.strptime(arrival_time, "%H:%M").time()
|
||||
current_time = datetime.now().time()
|
||||
|
||||
if current_time < target_time:
|
||||
remaining_time = datetime.combine(datetime.today(), target_time) - datetime.combine(datetime.today(), current_time)
|
||||
else:
|
||||
remaining_time = datetime.combine(datetime.today() + timedelta(days=1), target_time) - datetime.combine(datetime.today(), current_time)
|
||||
|
||||
remaining_minutes = int(remaining_time.total_seconds() // 60)
|
||||
return remaining_minutes
|
||||
|
||||
def obtain_min_max_time(remaining_time):
|
||||
if remaining_time == 1:
|
||||
return 0, 1
|
||||
elif remaining_time == 2:
|
||||
return 1, 2
|
||||
elif 2 <= remaining_time <= 5:
|
||||
return 2, 5
|
||||
elif remaining_time > 5 and remaining_time <= 7:
|
||||
return 5, 7
|
||||
elif remaining_time > 7 and remaining_time <= 10:
|
||||
return 7, 10
|
||||
else:
|
||||
return 10, remaining_time
|
||||
|
||||
###################################################################
|
||||
# Parametros para generar la imagen
|
||||
# "direction": "R", Indicador de la dirección en la que va el bus
|
||||
# "distance": 1948.575483806973. Distancia en m
|
||||
# "licensePlate": "LJHA57", Patente del bus
|
||||
# "route": "401", Linea de bus
|
||||
# "timeLabel": "09:49", Hora de llegada al paradero
|
||||
|
||||
# theme: Tema de la pantalla "day/night"
|
||||
# 'number_background_color': 'yellow', Color del fondo para el numero
|
||||
# 'letter_background_color': 'green', Color del fondo para la letra
|
||||
|
||||
def main():
|
||||
# Carga los datos
|
||||
data = load_data()
|
||||
|
||||
# Calcula distancia aproximada en km
|
||||
distance = approx_km(data)
|
||||
|
||||
# Calcula el tiempo restante a la llegada
|
||||
remaining_time = calc_remaining_time(data)
|
||||
# Obtiene valores máximos y mínimo de rangos para desplegar en pantalla
|
||||
min_time, max_time = obtain_min_max_time(remaining_time)
|
||||
|
||||
# Selecciona el tema
|
||||
theme = 'day'
|
||||
|
||||
# Alto y ancho de la imagen en pixeles
|
||||
height, width = 40, 160
|
||||
|
||||
# Inicia el dibujo y setea el tema
|
||||
full_panel = MyDraw(height=height, width=width)
|
||||
full_panel.set_theme(theme)
|
||||
full_panel.start_draw()
|
||||
# full_panel.preview()
|
||||
|
||||
# Con el dato de la patente se agrega al dibujo
|
||||
bp = BusPlate()
|
||||
plate = data["licensePlate"]
|
||||
bp.request_bus_plate(bus_plate=plate)
|
||||
bp.generate_image()
|
||||
bp.resize_image(target_height=aprox((3/10)*height))
|
||||
|
||||
# Agrega la distancia al paradero
|
||||
dist_anmc = DistanceAnnouncement(aprox((2/5)*height), aprox((1/3)*width))
|
||||
dist_anmc.set_theme(theme)
|
||||
dist_anmc.start_draw()
|
||||
# dist_anmc.set_background()
|
||||
# dist_anmc.set_base_text()
|
||||
dist_anmc.set_distance_text(distance=distance)
|
||||
|
||||
# Agrega el anuncio de los minutos restante al arribo
|
||||
time_anmc1 = TimeAnnouncement(aprox((2/5)*height), aprox((1/3)*width))
|
||||
time_anmc1.set_theme(theme)
|
||||
time_anmc1.start_draw()
|
||||
# time_anmc1.set_background()
|
||||
# time_anmc1.set_base_text()
|
||||
time_anmc1.set_min_max_text(min_time=min_time, max_time=max_time)
|
||||
|
||||
# Agrega el anuncio de los minutos restante al arribo
|
||||
time_anmc2 = TimeAnnouncement(aprox((2/5)*height), aprox((1/3)*width))
|
||||
time_anmc2.set_theme(theme)
|
||||
time_anmc2.start_draw()
|
||||
# time_anmc2.set_background()
|
||||
# time_anmc2.set_base_text()
|
||||
time_anmc2.set_min_max_text(min_time=3, max_time=5)
|
||||
|
||||
|
||||
# Genera la imagen de la linea del bus
|
||||
poster1 = BusPoster(aprox(1.1*(1/3)*height), aprox(1.1*(1/3)*width))
|
||||
poster1.set_theme(theme)
|
||||
poster1.start_draw()
|
||||
|
||||
poster_params = {
|
||||
'proportion': 0.6,
|
||||
'width_border': 2,
|
||||
'font_size': 11,
|
||||
'number_background_color': 'yellow',
|
||||
'letter_background_color': 'green',
|
||||
}
|
||||
|
||||
# Se setean los parametros
|
||||
poster1.set_params(poster_params)
|
||||
poster1.load_barlow()
|
||||
poster1.set_colors()
|
||||
# Se setea la ruta y la direccion en la que va
|
||||
poster1.set_bus_number(bus_number=data["route"])
|
||||
poster1.set_bus_letter(bus_letter=data["direction"])
|
||||
|
||||
# Genera la imagen de la linea del bus
|
||||
poster2 = BusPoster(aprox(1.1*(1/3)*height), aprox(1.1*(1/3)*width))
|
||||
poster2.set_theme(theme)
|
||||
poster2.start_draw()
|
||||
|
||||
poster_params = {
|
||||
'proportion': 0.6,
|
||||
'width_border': 2,
|
||||
'font_size': 11,
|
||||
'number_background_color': 'yellow',
|
||||
'letter_background_color': 'blue',
|
||||
}
|
||||
|
||||
# Se setean los parametros
|
||||
poster2.set_params(poster_params)
|
||||
poster2.load_barlow()
|
||||
poster2.set_colors()
|
||||
# Se setea la ruta y la direccion en la que va
|
||||
poster2.set_bus_number(bus_number="16")
|
||||
poster2.set_bus_letter(bus_letter="I")
|
||||
|
||||
# Se agrega la imagen del bus
|
||||
bm = BusImage()
|
||||
bm.set_theme(theme)
|
||||
bm.load_image_from_url()
|
||||
bm.crop_image(top_cut=165, bottom_cut=165)
|
||||
bm.resize_image(target_width=aprox((1/3)*width))
|
||||
|
||||
# Se agregan todas las imagenes al canvas
|
||||
# full_panel.add_image(bp, (aprox(0*width), aprox((0)*height)))
|
||||
# full_panel.add_image(dist_anmc, (aprox((3/8)*width), aprox(0.1*height)))
|
||||
full_panel.add_image(time_anmc1, (aprox((0.6)*width), aprox(0.05*height)))
|
||||
full_panel.add_image(time_anmc2, (aprox((0.6)*width), aprox(0.45*height)))
|
||||
full_panel.add_image(poster1, (aprox((0.05)*width), aprox((0.1)*height)))
|
||||
full_panel.add_image(poster2, (aprox((0.05)*width), aprox((0.5)*height)))
|
||||
# full_panel.add_image(bm, (aprox(0.02*width),aprox((1/6)*height)))
|
||||
full_panel.get_image()
|
||||
full_panel.save_image('/app/data/output.png')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
|
@ -1,77 +0,0 @@
|
|||
# Guía de configuración para Modulo LED
|
||||
|
||||
## Materiales Necesarios
|
||||
|
||||
- Raspberry Pi, versión 3 o superior.
|
||||
- Hat de conexión HUB75
|
||||
- Paneles LED P4 con I/O HUB75
|
||||
- Fuente de alimentación con salida 5V/3A
|
||||
- Cables de Alimentación 4-pin 5V/3A
|
||||
- Cables de datos con conexión HUB75
|
||||
|
||||
## Configuración inicial
|
||||
|
||||
### Conexionado
|
||||
|
||||
Para las conexiones de datos, se utilizan cables hembra HUB75 de 16-pines, estos se conectan en un extremo al HAT HUB75 para Raspberry PI. En caso de tener un HAT con multiples conexiones de HUB75, siempre utilizar la salida TOP para la primera fila del conjunto de paneles, y usar el resto de las salidas para las filas inferiores. El extremo opuesto del cable de datos debe conectarse en el "input" del panel, estos modulos tienen etiquetada su entrada y salida en la parte posterior. Ver las imagenes mostradas como referencia visual.
|
||||
|
||||
Para la conexión electrica, cada uno de los paneles LED tiene una entrada de cuatro pines para cables de alimentación. Es necesario tener una fuente de poder con salida de 5V y un minimo de 3A, para cumplir con los criterios de alimentación en los modulos LED.
|
||||
|
||||
  
|
||||
|
||||
|
||||
A continuación, se presenta un diagrama de conexiones, tanto para los datos como para la alimentación. Notar que la referencia (0,0) corresponde a la orientación superior izquierda de las gráficas que se deseen desplegar en el módulo, también se señala la orientación de las entradas y salidas de cada panel en la configuración.
|
||||
|
||||

|
||||
|
||||
### Configuración de Raspberry Pi
|
||||
|
||||
Luego de haber descargado los datos almancenados en este reposotorio. En el directorio ModuloLED, encontrará un script llamado `MenuPantalla.sh`, en este menú se puede hacer dos acciones en concreto:
|
||||
|
||||
- Configurar parámetros de la implementación, modificando variables del codigo base.
|
||||
- Desplegar una imagen a partir de un archivo imagen jpg o png almacenada en el sistema.
|
||||
|
||||
#### Configuración de Parámetros
|
||||
|
||||
Entre las opciones de configuración en el codigo base para el funcionamiento del panel se muestran en la siguiente tabla:
|
||||
|
||||
| Parámetro | Variable código base | Rango de valores |
|
||||
| ------------ | ------------ | ------------ |
|
||||
| N° de filas de pixeles en un panel. | `options.rows` | PANEL |
|
||||
| N° de columnas de pixeles en un panel. | `options.col` | PANEL |
|
||||
| N° de filas de paneles montados | `options.parallel` | 1 - 3 |
|
||||
| N° de columnas de paneles montados | `options.chain_length` | 1 - 3 |
|
||||
| Brillo | `options.brightness` | 0 - 100 |
|
||||
| Mapeo GPIO para HAT | `options.hardware_mapping` | `regular`, ver otras opciones [aquí](https://github.com/hzeller/rpi-rgb-led-matrix/blob/master/wiring.md#alternative-hardware-mappings) |
|
||||
| Multiplexación | `options.multiplexing` | 1 (por defecto) - 17|
|
||||
| Retardo GPIO | `options.gpio_slowdown` | 1 - 5 |
|
||||
|
||||
**PANEL: Dado por el fabricante del panel comprado.**
|
||||
|
||||
## Despliegue de imagenes
|
||||
|
||||
Al seleccionar esta opción, se mostrarán todos los archivos de imagen guardados en el sistema de la Raspberry Pi. Se recomienda utilizar imagenes con la mimsa relacion de aspecto que la resolución de la pantalla montada para el despliegue. De lo contrario, la pantalla tendrá espacios en negro.
|
||||
|
||||
### Variables del Sistema Operativo
|
||||
|
||||
Se propone un Sub-sistema que se encargue de manera dedicada al renderizado en la Matriz LED en forma continua. Para eso se implementa un *demonio* de Linux que esta continuamente dibujando en el display.
|
||||
|
||||
Para ello se reserva el procesador 3, entregandoselele la `CPUAffinity=3` al proceso, de manera de garantizar el recurso computacional. Adicionalmente se modifica el Sistema Operativo para que quite el procesador del itineradoe usando `isocpus=3` en la variable de inicio `/boot/cmdline.txt`.
|
||||
|
||||
Además se monta un directorio de `/srv/ledram` que tiene un tamaño de 32MB para disponer una *memoria de video* en RAM que permita a otros procesos actualizar el contenido que se despliega en el display. Para ello se modifica el `/etc/fstab` para que se cree el recurso automaticamente al iniciarse la Raspberry.
|
||||
|
||||
#### Sub-sistema de renderizado
|
||||
|
||||
Se define el directorio `/srv` donde se aloja el sub-sistema de renderizado. Esta compuesto del script `/srv/subsystem/led-driver.py` que es iniciado en forma automática por `systemd`.
|
||||
|
||||
El script ve la hora de modificación del archivo `/srv/ledram/current.png` para determinar si debe o no actualizar la imagen que se está desplegando actualmente en el display cada 100 ms.
|
||||
|
||||
De esta manera, cualquier usuario o proceso (`chmod 666`) puede escribir ese archivo. Siendo este sub sistema el encargado de leer el contenido de la imagen y renderizarlo en el display led en forma permanente.
|
||||
|
||||
#### Instalación como servicio
|
||||
|
||||
Todos estos pasos están automatizados en el script `install-service.sh` que debe ser ejecutado como `root`.
|
||||
|
||||
#### TODO
|
||||
|
||||
Falta que el script detecte cuando se le solicita salir, para que elimine el archivo `/srv/ledram/current.png`, de tal manera de poder `systemctl stop led-driver.service` y `systemctl start led-driver.service` sin depender que la imagen se elimine en forma automatica al ser un directorio volatil
|
Before Width: | Height: | Size: 26 KiB |
|
@ -1,44 +0,0 @@
|
|||
#!/bin/bash
|
||||
|
||||
if [ "$EUID" -ne 0 ]; then
|
||||
echo "Este script requiere permisos de root."
|
||||
exit
|
||||
fi
|
||||
|
||||
# set pwd to current directory
|
||||
cd "$(dirname "$0")"
|
||||
|
||||
#limpia el contenido del directorio de trabajo
|
||||
rm -rf /srv/ledram/*
|
||||
rm -rf /srv/*
|
||||
|
||||
# Configura un directorio `/srv/ledram` como buffer de video
|
||||
sed -i -e '/srv/d' /etc/fstab
|
||||
sed -i -e '$a/tmpfs /srv/ledram tmpfs rw,nosuid,nodev,size=32m 0 0' /etc/fstab
|
||||
|
||||
# Crea directorio donde se almacena el buffer de video
|
||||
mkdir /srv/ledram
|
||||
|
||||
# Desocupa el tercer procesador para ser usado exclusivamente por el sub-proceso de renderizado
|
||||
sed -i -e 's/ isocpus=3//g' /boot/cmdline.txt
|
||||
sed -i -e 's/$/ isocpus=3/' /boot/cmdline.txt
|
||||
|
||||
#copia la biblioteca al directorio de trabajo
|
||||
cp -R /home/raspi/rpi-rgb-led-matrix/bindings/python/rgbmatrix /srv/rgbmatrix
|
||||
|
||||
#copia el sub-sistema de renderizado
|
||||
mkdir /srv/subsystem
|
||||
cp -rf init.png /srv
|
||||
cp -rf led-driver.py /srv/subsystem
|
||||
|
||||
#Crea el servicio
|
||||
cp -rf led-driver.service /etc/systemd/system/led-driver.service
|
||||
|
||||
# Recarga e inicia automaticamente al prender.
|
||||
systemctl daemon-reload
|
||||
systemctl unmask led-driver.service
|
||||
systemctl enable led-driver.service
|
||||
|
||||
# Mensajes de salida
|
||||
echo "Debe reiniciar la Raspberry para que el servicio pueda iniciarse"
|
||||
echo "Luego para actualizar, solo debe modificar el el archivo '/srv/ledram/current.png' para actualizar la pantalla"
|
|
@ -1,56 +0,0 @@
|
|||
#!/usr/bin/env python
|
||||
import time
|
||||
import sys
|
||||
import os
|
||||
import shutil
|
||||
|
||||
from rgbmatrix import RGBMatrix, RGBMatrixOptions
|
||||
from PIL import Image
|
||||
|
||||
# Configuration for the matrix
|
||||
options = RGBMatrixOptions()
|
||||
options.rows = 40
|
||||
options.cols = 80
|
||||
options.chain_length = 2
|
||||
options.parallel = 1
|
||||
options.gpio_slowdown = 4
|
||||
#options.row_address_type = 0
|
||||
|
||||
options.hardware_mapping = 'regular' # If you have an Adafruit HAT: 'adafruit-hat'
|
||||
options.multiplexing = 1
|
||||
options.brightness = 100
|
||||
#options.pwm_lsb_nanoseconds = 300
|
||||
#options.pwm_bits = 11
|
||||
|
||||
matrix = RGBMatrix(options = options)
|
||||
|
||||
#Bufer que se copia en la pantalla led
|
||||
img_path='/srv/ledram/current.png'
|
||||
#imagen por defecto a mostrar al inicializarla
|
||||
init_file='/srv/init.png'
|
||||
|
||||
# Revisa si el bufer existe, si no existe lo crea
|
||||
# y si existe sale ya que hay otro proceso que lo
|
||||
if not os.path.isfile(img_path):
|
||||
shutil.copy(init_file, img_path)
|
||||
os.chmod(img_path, 0o666)
|
||||
else:
|
||||
print("El archivo de buffer ya existe!")
|
||||
exit(1)
|
||||
|
||||
#guarda el tiempo de modificación
|
||||
tstam = os.stat(img_path).st_mtime
|
||||
|
||||
with Image.open(img_path) as image:
|
||||
matrix.SetImage(image.convert('RGB'))
|
||||
|
||||
#matrix.SetImage(Image.open(img_path).convert('RGB'))
|
||||
|
||||
while True:
|
||||
time.sleep(0.1)
|
||||
ntstam = os.stat(img_path).st_mtime
|
||||
#si el bufer fue modificado, lo carga en la pantalla led
|
||||
if ntstam > tstam:
|
||||
with Image.open(img_path) as image:
|
||||
matrix.SetImage(image.convert('RGB'))
|
||||
tstam = ntstam
|
|
@ -1,14 +0,0 @@
|
|||
[Unit]
|
||||
Description=LED Rendering Service
|
||||
After=local-fs.target
|
||||
|
||||
[Service]
|
||||
User=root
|
||||
CPUAffinity=3
|
||||
Nice=-20
|
||||
WorkingDirectory=/srv
|
||||
ExecStart=/usr/bin/python3 /srv/subsystem/led-driver.py
|
||||
Restart=always
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
71
README.md
|
@ -1,60 +1,49 @@
|
|||
# Configurar la RPI
|
||||
# Visualización para pantallas LED de paradas de bus
|
||||
|
||||
### Instalar el software para inicializar tarjetas SD
|
||||
Este repositorio contiene los archivos necesarios para ejecutar una aplicación Jupyter Notebook con ciertas bibliotecas de visualización y procesamiento de imágenes.
|
||||
|
||||
`apt install rpi-imager`
|
||||
## Contenido
|
||||
|
||||
### Instalar la imagen Raspbian 64 bit Lite
|
||||
- `Dockerfile`: Define cómo construir la imagen Docker para ejecutar la aplicación.
|
||||
- `requirements.txt`: Lista las bibliotecas y dependencias necesarias para la aplicación.
|
||||
|
||||
Copiar la versión lite:
|
||||
https://downloads.raspberrypi.com/raspios_lite_arm64/images/raspios_lite_arm64-2023-12-11/2023-12-11-raspios-bookworm-arm64-lite.img.xz
|
||||
## Dockerfile
|
||||
|
||||
### Configurar la imagen
|
||||
### Descripción
|
||||
|
||||
`rpi-imager` permite habilitar SSH, cambiar el nombre al dispositivo, configurar una cuenta de usuario, etc.
|
||||
El `Dockerfile` especifica cómo construir una imagen Docker basada en Python 3.8 que tiene todas las dependencias necesarias para ejecutar la aplicación.
|
||||
|
||||
Para mas información revisar: http://rptl.io/newuser
|
||||
### Instrucciones
|
||||
|
||||
1. **Imagen base**: Utiliza Python 3.8.
|
||||
2. **Directorio de trabajo**: Establece `/app` como el directorio de trabajo en el contenedor.
|
||||
3. **Instalación de dependencias**: Copia y utiliza `requirements.txt` para instalar las bibliotecas necesarias.
|
||||
4. **Configuración de Jupyter**: Copia el archivo de configuración de Jupyter al contenedor.
|
||||
5. **Puerto**: Expone el puerto 8888 para Jupyter Notebook.
|
||||
6. **Comando de inicio**: Al iniciar el contenedor, se ejecuta Jupyter Notebook en el puerto 8888.
|
||||
|
||||
## Preparacipon de ambientes y dispositivo
|
||||
## requirements.txt
|
||||
|
||||
Este presupone que se usa la cuenta de soporte y el directorio principal `/home/soporte`
|
||||
### Descripción
|
||||
|
||||
### Quitar la tarjeta de sonido para habilitar
|
||||
El archivo `requirements.txt` lista las bibliotecas y dependencias que se requieren para la aplicación.
|
||||
|
||||
`cat "blacklist snd_bcm2835" | sudo tee /etc/modprobe.d/blacklist-rgb-matrix.conf `
|
||||
### Bibliotecas y dependencias
|
||||
|
||||
`sudo update-initramfs -u`
|
||||
- `matplotlib`: Biblioteca de visualización de datos.
|
||||
- `seaborn`: Biblioteca de visualización de datos basada en matplotlib.
|
||||
- `plotly`: Biblioteca para gráficos interactivos.
|
||||
- `opencv-python`: Biblioteca de procesamiento de imágenes y visión por computadora.
|
||||
- `jupyter`: Entorno de desarrollo interactivo.
|
||||
|
||||
`sudo reboot`
|
||||
## Cómo ejecutar
|
||||
|
||||
### Preparación de paquetes
|
||||
1. Construye la imagen Docker:
|
||||
|
||||
`sudo apt-get update`
|
||||
`docker build -t bus_stop_visualization .`
|
||||
|
||||
paquetes basicos:
|
||||
2. Ejecuta el contenedor:
|
||||
|
||||
`sudo apt-get install git python3-pip -y `
|
||||
`docker run -d --name bus_stop_vis -v /scripts:/app/scripts -p 8888:8888 bus_stop_visualization`
|
||||
|
||||
Requerimientos del LED-MATRIX
|
||||
|
||||
`sudo apt-get install python3-dev python3-pillow -y`
|
||||
|
||||
Requerimientos de pantallas led:
|
||||
|
||||
`sudo apt-get install python3-matplotlib python3-requests python3-numpy python3-pytzdata python3-apscheduler -y`
|
||||
|
||||
### Clonar los repositorios
|
||||
|
||||
`git clone https://dev.ilab.cl/TDTP/pantallas-led`
|
||||
|
||||
`git clone https://github.com/hzeller/rpi-rgb-led-matrix/`
|
||||
|
||||
`cd rpi-rgb-led-matrix/bindings/python`
|
||||
|
||||
|
||||
`make build-python PYTHON=$(command -v python3)`
|
||||
|
||||
`sudo make install-python PYTHON=$(command -v python3)`
|
||||
|
||||
Return to the folder and proceed with the installation
|
||||
3. Abre un navegador y accede a `http://localhost:8888` para comenzar a usar Jupyter Notebook.
|
12
autorun.sh
|
@ -1,12 +0,0 @@
|
|||
#!/bin/bash
|
||||
|
||||
IMAGE=$HOME/pantallas-led/GenPoster/example/poster.png
|
||||
|
||||
#sudo python3 testapi_full.py
|
||||
cd pantallas-led/GenPoster
|
||||
#docker build -t bus_poster .
|
||||
./run_container.sh
|
||||
|
||||
cd $HOME/rpi-rgb-led-matrix/bindings/python/samples/
|
||||
|
||||
sudo python3 image-viewer.py $IMAGE
|
After Width: | Height: | Size: 7.7 KiB |
After Width: | Height: | Size: 20 KiB |
|
@ -0,0 +1,93 @@
|
|||
Copyright 2017 The Barlow Project Authors (https://github.com/jpt/barlow)
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
http://scripts.sil.org/OFL
|
||||
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
|
@ -0,0 +1,638 @@
|
|||
// Copyright 2015 The GTFS Specifications Authors.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
// Protocol definition file for GTFS Realtime.
|
||||
//
|
||||
// GTFS Realtime lets transit agencies provide consumers with realtime
|
||||
// information about disruptions to their service (stations closed, lines not
|
||||
// operating, important delays etc), location of their vehicles and expected
|
||||
// arrival times.
|
||||
//
|
||||
// This protocol is published at:
|
||||
// https://github.com/google/transit/tree/master/gtfs-realtime
|
||||
|
||||
syntax = "proto2";
|
||||
|
||||
package transit_realtime;
|
||||
|
||||
option java_package = "com.google.transit.realtime";
|
||||
|
||||
// The contents of a feed message.
|
||||
// A feed is a continuous stream of feed messages. Each message in the stream is
|
||||
// obtained as a response to an appropriate HTTP GET request.
|
||||
// A realtime feed is always defined with relation to an existing GTFS feed.
|
||||
// All the entity ids are resolved with respect to the GTFS feed.
|
||||
// Note that "required" and "optional" as stated in this file refer to Protocol
|
||||
// Buffer cardinality, not semantic cardinality. See reference.md at
|
||||
// https://github.com/google/transit/tree/master/gtfs-realtime for field
|
||||
// semantic cardinality.
|
||||
message FeedMessage {
|
||||
// Metadata about this feed and feed message.
|
||||
required FeedHeader header = 1;
|
||||
|
||||
// Contents of the feed.
|
||||
repeated FeedEntity entity = 2;
|
||||
|
||||
// The extensions namespace allows 3rd-party developers to extend the
|
||||
// GTFS Realtime specification in order to add and evaluate new features and
|
||||
// modifications to the spec.
|
||||
extensions 1000 to 1999;
|
||||
}
|
||||
|
||||
// Metadata about a feed, included in feed messages.
|
||||
message FeedHeader {
|
||||
// Version of the feed specification.
|
||||
// The current version is 2.0.
|
||||
required string gtfs_realtime_version = 1;
|
||||
|
||||
// Determines whether the current fetch is incremental. Currently,
|
||||
// DIFFERENTIAL mode is unsupported and behavior is unspecified for feeds
|
||||
// that use this mode. There are discussions on the GTFS Realtime mailing
|
||||
// list around fully specifying the behavior of DIFFERENTIAL mode and the
|
||||
// documentation will be updated when those discussions are finalized.
|
||||
enum Incrementality {
|
||||
FULL_DATASET = 0;
|
||||
DIFFERENTIAL = 1;
|
||||
}
|
||||
optional Incrementality incrementality = 2 [default = FULL_DATASET];
|
||||
|
||||
// This timestamp identifies the moment when the content of this feed has been
|
||||
// created (in server time). In POSIX time (i.e., number of seconds since
|
||||
// January 1st 1970 00:00:00 UTC).
|
||||
optional uint64 timestamp = 3;
|
||||
|
||||
// The extensions namespace allows 3rd-party developers to extend the
|
||||
// GTFS Realtime specification in order to add and evaluate new features and
|
||||
// modifications to the spec.
|
||||
extensions 1000 to 1999;
|
||||
}
|
||||
|
||||
// A definition (or update) of an entity in the transit feed.
|
||||
message FeedEntity {
|
||||
// The ids are used only to provide incrementality support. The id should be
|
||||
// unique within a FeedMessage. Consequent FeedMessages may contain
|
||||
// FeedEntities with the same id. In case of a DIFFERENTIAL update the new
|
||||
// FeedEntity with some id will replace the old FeedEntity with the same id
|
||||
// (or delete it - see is_deleted below).
|
||||
// The actual GTFS entities (e.g. stations, routes, trips) referenced by the
|
||||
// feed must be specified by explicit selectors (see EntitySelector below for
|
||||
// more info).
|
||||
required string id = 1;
|
||||
|
||||
// Whether this entity is to be deleted. Relevant only for incremental
|
||||
// fetches.
|
||||
optional bool is_deleted = 2 [default = false];
|
||||
|
||||
// Data about the entity itself. Exactly one of the following fields must be
|
||||
// present (unless the entity is being deleted).
|
||||
optional TripUpdate trip_update = 3;
|
||||
optional VehiclePosition vehicle = 4;
|
||||
optional Alert alert = 5;
|
||||
|
||||
// The extensions namespace allows 3rd-party developers to extend the
|
||||
// GTFS Realtime Specification in order to add and evaluate new features and
|
||||
// modifications to the spec.
|
||||
extensions 1000 to 1999;
|
||||
}
|
||||
|
||||
//
|
||||
// Entities used in the feed.
|
||||
//
|
||||
|
||||
// Realtime update of the progress of a vehicle along a trip.
|
||||
// Depending on the value of ScheduleRelationship, a TripUpdate can specify:
|
||||
// - A trip that proceeds along the schedule.
|
||||
// - A trip that proceeds along a route but has no fixed schedule.
|
||||
// - A trip that have been added or removed with regard to schedule.
|
||||
//
|
||||
// The updates can be for future, predicted arrival/departure events, or for
|
||||
// past events that already occurred.
|
||||
// Normally, updates should get more precise and more certain (see
|
||||
// uncertainty below) as the events gets closer to current time.
|
||||
// Even if that is not possible, the information for past events should be
|
||||
// precise and certain. In particular, if an update points to time in the past
|
||||
// but its update's uncertainty is not 0, the client should conclude that the
|
||||
// update is a (wrong) prediction and that the trip has not completed yet.
|
||||
//
|
||||
// Note that the update can describe a trip that is already completed.
|
||||
// To this end, it is enough to provide an update for the last stop of the trip.
|
||||
// If the time of that is in the past, the client will conclude from that that
|
||||
// the whole trip is in the past (it is possible, although inconsequential, to
|
||||
// also provide updates for preceding stops).
|
||||
// This option is most relevant for a trip that has completed ahead of schedule,
|
||||
// but according to the schedule, the trip is still proceeding at the current
|
||||
// time. Removing the updates for this trip could make the client assume
|
||||
// that the trip is still proceeding.
|
||||
// Note that the feed provider is allowed, but not required, to purge past
|
||||
// updates - this is one case where this would be practically useful.
|
||||
message TripUpdate {
|
||||
// The Trip that this message applies to. There can be at most one
|
||||
// TripUpdate entity for each actual trip instance.
|
||||
// If there is none, that means there is no prediction information available.
|
||||
// It does *not* mean that the trip is progressing according to schedule.
|
||||
required TripDescriptor trip = 1;
|
||||
|
||||
// Additional information on the vehicle that is serving this trip.
|
||||
optional VehicleDescriptor vehicle = 3;
|
||||
|
||||
// Timing information for a single predicted event (either arrival or
|
||||
// departure).
|
||||
// Timing consists of delay and/or estimated time, and uncertainty.
|
||||
// - delay should be used when the prediction is given relative to some
|
||||
// existing schedule in GTFS.
|
||||
// - time should be given whether there is a predicted schedule or not. If
|
||||
// both time and delay are specified, time will take precedence
|
||||
// (although normally, time, if given for a scheduled trip, should be
|
||||
// equal to scheduled time in GTFS + delay).
|
||||
//
|
||||
// Uncertainty applies equally to both time and delay.
|
||||
// The uncertainty roughly specifies the expected error in true delay (but
|
||||
// note, we don't yet define its precise statistical meaning). It's possible
|
||||
// for the uncertainty to be 0, for example for trains that are driven under
|
||||
// computer timing control.
|
||||
message StopTimeEvent {
|
||||
// Delay (in seconds) can be positive (meaning that the vehicle is late) or
|
||||
// negative (meaning that the vehicle is ahead of schedule). Delay of 0
|
||||
// means that the vehicle is exactly on time.
|
||||
optional int32 delay = 1;
|
||||
|
||||
// Event as absolute time.
|
||||
// In Unix time (i.e., number of seconds since January 1st 1970 00:00:00
|
||||
// UTC).
|
||||
optional int64 time = 2;
|
||||
|
||||
// If uncertainty is omitted, it is interpreted as unknown.
|
||||
// If the prediction is unknown or too uncertain, the delay (or time) field
|
||||
// should be empty. In such case, the uncertainty field is ignored.
|
||||
// To specify a completely certain prediction, set its uncertainty to 0.
|
||||
optional int32 uncertainty = 3;
|
||||
|
||||
// The extensions namespace allows 3rd-party developers to extend the
|
||||
// GTFS Realtime Specification in order to add and evaluate new features
|
||||
// and modifications to the spec.
|
||||
extensions 1000 to 1999;
|
||||
}
|
||||
|
||||
// Realtime update for arrival and/or departure events for a given stop on a
|
||||
// trip. Updates can be supplied for both past and future events.
|
||||
// The producer is allowed, although not required, to drop past events.
|
||||
message StopTimeUpdate {
|
||||
// The update is linked to a specific stop either through stop_sequence or
|
||||
// stop_id, so one of the fields below must necessarily be set.
|
||||
// See the documentation in TripDescriptor for more information.
|
||||
|
||||
// Must be the same as in stop_times.txt in the corresponding GTFS feed.
|
||||
optional uint32 stop_sequence = 1;
|
||||
// Must be the same as in stops.txt in the corresponding GTFS feed.
|
||||
optional string stop_id = 4;
|
||||
|
||||
optional StopTimeEvent arrival = 2;
|
||||
optional StopTimeEvent departure = 3;
|
||||
|
||||
// The relation between this StopTime and the static schedule.
|
||||
enum ScheduleRelationship {
|
||||
// The vehicle is proceeding in accordance with its static schedule of
|
||||
// stops, although not necessarily according to the times of the schedule.
|
||||
// At least one of arrival and departure must be provided. If the schedule
|
||||
// for this stop contains both arrival and departure times then so must
|
||||
// this update.
|
||||
SCHEDULED = 0;
|
||||
|
||||
// The stop is skipped, i.e., the vehicle will not stop at this stop.
|
||||
// Arrival and departure are optional.
|
||||
SKIPPED = 1;
|
||||
|
||||
// No data is given for this stop. The main intention for this value is to
|
||||
// give the predictions only for part of a trip, i.e., if the last update
|
||||
// for a trip has a NO_DATA specifier, then StopTimes for the rest of the
|
||||
// stops in the trip are considered to be unspecified as well.
|
||||
// Neither arrival nor departure should be supplied.
|
||||
NO_DATA = 2;
|
||||
}
|
||||
optional ScheduleRelationship schedule_relationship = 5
|
||||
[default = SCHEDULED];
|
||||
|
||||
// The extensions namespace allows 3rd-party developers to extend the
|
||||
// GTFS Realtime Specification in order to add and evaluate new features
|
||||
// and modifications to the spec.
|
||||
extensions 1000 to 1999;
|
||||
}
|
||||
|
||||
// Updates to StopTimes for the trip (both future, i.e., predictions, and in
|
||||
// some cases, past ones, i.e., those that already happened).
|
||||
// The updates must be sorted by stop_sequence, and apply for all the
|
||||
// following stops of the trip up to the next specified one.
|
||||
//
|
||||
// Example 1:
|
||||
// For a trip with 20 stops, a StopTimeUpdate with arrival delay and departure
|
||||
// delay of 0 for stop_sequence of the current stop means that the trip is
|
||||
// exactly on time.
|
||||
//
|
||||
// Example 2:
|
||||
// For the same trip instance, 3 StopTimeUpdates are provided:
|
||||
// - delay of 5 min for stop_sequence 3
|
||||
// - delay of 1 min for stop_sequence 8
|
||||
// - delay of unspecified duration for stop_sequence 10
|
||||
// This will be interpreted as:
|
||||
// - stop_sequences 3,4,5,6,7 have delay of 5 min.
|
||||
// - stop_sequences 8,9 have delay of 1 min.
|
||||
// - stop_sequences 10,... have unknown delay.
|
||||
repeated StopTimeUpdate stop_time_update = 2;
|
||||
|
||||
// Moment at which the vehicle's real-time progress was measured. In POSIX
|
||||
// time (i.e., the number of seconds since January 1st 1970 00:00:00 UTC).
|
||||
optional uint64 timestamp = 4;
|
||||
|
||||
// The current schedule deviation for the trip. Delay should only be
|
||||
// specified when the prediction is given relative to some existing schedule
|
||||
// in GTFS.
|
||||
//
|
||||
// Delay (in seconds) can be positive (meaning that the vehicle is late) or
|
||||
// negative (meaning that the vehicle is ahead of schedule). Delay of 0
|
||||
// means that the vehicle is exactly on time.
|
||||
//
|
||||
// Delay information in StopTimeUpdates take precedent of trip-level delay
|
||||
// information, such that trip-level delay is only propagated until the next
|
||||
// stop along the trip with a StopTimeUpdate delay value specified.
|
||||
//
|
||||
// Feed providers are strongly encouraged to provide a TripUpdate.timestamp
|
||||
// value indicating when the delay value was last updated, in order to
|
||||
// evaluate the freshness of the data.
|
||||
//
|
||||
// NOTE: This field is still experimental, and subject to change. It may be
|
||||
// formally adopted in the future.
|
||||
optional int32 delay = 5;
|
||||
|
||||
// The extensions namespace allows 3rd-party developers to extend the
|
||||
// GTFS Realtime Specification in order to add and evaluate new features and
|
||||
// modifications to the spec.
|
||||
extensions 1000 to 1999;
|
||||
}
|
||||
|
||||
// Realtime positioning information for a given vehicle.
|
||||
message VehiclePosition {
|
||||
// The Trip that this vehicle is serving.
|
||||
// Can be empty or partial if the vehicle can not be identified with a given
|
||||
// trip instance.
|
||||
optional TripDescriptor trip = 1;
|
||||
|
||||
// Additional information on the vehicle that is serving this trip.
|
||||
optional VehicleDescriptor vehicle = 8;
|
||||
|
||||
// Current position of this vehicle.
|
||||
optional Position position = 2;
|
||||
|
||||
// The stop sequence index of the current stop. The meaning of
|
||||
// current_stop_sequence (i.e., the stop that it refers to) is determined by
|
||||
// current_status.
|
||||
// If current_status is missing IN_TRANSIT_TO is assumed.
|
||||
optional uint32 current_stop_sequence = 3;
|
||||
// Identifies the current stop. The value must be the same as in stops.txt in
|
||||
// the corresponding GTFS feed.
|
||||
optional string stop_id = 7;
|
||||
|
||||
enum VehicleStopStatus {
|
||||
// The vehicle is just about to arrive at the stop (on a stop
|
||||
// display, the vehicle symbol typically flashes).
|
||||
INCOMING_AT = 0;
|
||||
|
||||
// The vehicle is standing at the stop.
|
||||
STOPPED_AT = 1;
|
||||
|
||||
// The vehicle has departed and is in transit to the next stop.
|
||||
IN_TRANSIT_TO = 2;
|
||||
}
|
||||
// The exact status of the vehicle with respect to the current stop.
|
||||
// Ignored if current_stop_sequence is missing.
|
||||
optional VehicleStopStatus current_status = 4 [default = IN_TRANSIT_TO];
|
||||
|
||||
// Moment at which the vehicle's position was measured. In POSIX time
|
||||
// (i.e., number of seconds since January 1st 1970 00:00:00 UTC).
|
||||
optional uint64 timestamp = 5;
|
||||
|
||||
// Congestion level that is affecting this vehicle.
|
||||
enum CongestionLevel {
|
||||
UNKNOWN_CONGESTION_LEVEL = 0;
|
||||
RUNNING_SMOOTHLY = 1;
|
||||
STOP_AND_GO = 2;
|
||||
CONGESTION = 3;
|
||||
SEVERE_CONGESTION = 4; // People leaving their cars.
|
||||
}
|
||||
optional CongestionLevel congestion_level = 6;
|
||||
|
||||
// The degree of passenger occupancy of the vehicle. This field is still
|
||||
// experimental, and subject to change. It may be formally adopted in the
|
||||
// future.
|
||||
enum OccupancyStatus {
|
||||
// The vehicle is considered empty by most measures, and has few or no
|
||||
// passengers onboard, but is still accepting passengers.
|
||||
EMPTY = 0;
|
||||
|
||||
// The vehicle has a relatively large percentage of seats available.
|
||||
// What percentage of free seats out of the total seats available is to be
|
||||
// considered large enough to fall into this category is determined at the
|
||||
// discretion of the producer.
|
||||
MANY_SEATS_AVAILABLE = 1;
|
||||
|
||||
// The vehicle has a relatively small percentage of seats available.
|
||||
// What percentage of free seats out of the total seats available is to be
|
||||
// considered small enough to fall into this category is determined at the
|
||||
// discretion of the feed producer.
|
||||
FEW_SEATS_AVAILABLE = 2;
|
||||
|
||||
// The vehicle can currently accommodate only standing passengers.
|
||||
STANDING_ROOM_ONLY = 3;
|
||||
|
||||
// The vehicle can currently accommodate only standing passengers
|
||||
// and has limited space for them.
|
||||
CRUSHED_STANDING_ROOM_ONLY = 4;
|
||||
|
||||
// The vehicle is considered full by most measures, but may still be
|
||||
// allowing passengers to board.
|
||||
FULL = 5;
|
||||
|
||||
// The vehicle is not accepting additional passengers.
|
||||
NOT_ACCEPTING_PASSENGERS = 6;
|
||||
}
|
||||
optional OccupancyStatus occupancy_status = 9;
|
||||
|
||||
// The extensions namespace allows 3rd-party developers to extend the
|
||||
// GTFS Realtime Specification in order to add and evaluate new features and
|
||||
// modifications to the spec.
|
||||
extensions 1000 to 1999;
|
||||
}
|
||||
|
||||
// An alert, indicating some sort of incident in the public transit network.
|
||||
message Alert {
|
||||
// Time when the alert should be shown to the user. If missing, the
|
||||
// alert will be shown as long as it appears in the feed.
|
||||
// If multiple ranges are given, the alert will be shown during all of them.
|
||||
repeated TimeRange active_period = 1;
|
||||
|
||||
// Entities whose users we should notify of this alert.
|
||||
repeated EntitySelector informed_entity = 5;
|
||||
|
||||
// Cause of this alert.
|
||||
enum Cause {
|
||||
UNKNOWN_CAUSE = 1;
|
||||
OTHER_CAUSE = 2; // Not machine-representable.
|
||||
TECHNICAL_PROBLEM = 3;
|
||||
STRIKE = 4; // Public transit agency employees stopped working.
|
||||
DEMONSTRATION = 5; // People are blocking the streets.
|
||||
ACCIDENT = 6;
|
||||
HOLIDAY = 7;
|
||||
WEATHER = 8;
|
||||
MAINTENANCE = 9;
|
||||
CONSTRUCTION = 10;
|
||||
POLICE_ACTIVITY = 11;
|
||||
MEDICAL_EMERGENCY = 12;
|
||||
}
|
||||
optional Cause cause = 6 [default = UNKNOWN_CAUSE];
|
||||
|
||||
// What is the effect of this problem on the affected entity.
|
||||
enum Effect {
|
||||
NO_SERVICE = 1;
|
||||
REDUCED_SERVICE = 2;
|
||||
|
||||
// We don't care about INsignificant delays: they are hard to detect, have
|
||||
// little impact on the user, and would clutter the results as they are too
|
||||
// frequent.
|
||||
SIGNIFICANT_DELAYS = 3;
|
||||
|
||||
DETOUR = 4;
|
||||
ADDITIONAL_SERVICE = 5;
|
||||
MODIFIED_SERVICE = 6;
|
||||
OTHER_EFFECT = 7;
|
||||
UNKNOWN_EFFECT = 8;
|
||||
STOP_MOVED = 9;
|
||||
}
|
||||
optional Effect effect = 7 [default = UNKNOWN_EFFECT];
|
||||
|
||||
// The URL which provides additional information about the alert.
|
||||
optional TranslatedString url = 8;
|
||||
|
||||
// Alert header. Contains a short summary of the alert text as plain-text.
|
||||
optional TranslatedString header_text = 10;
|
||||
|
||||
// Full description for the alert as plain-text. The information in the
|
||||
// description should add to the information of the header.
|
||||
optional TranslatedString description_text = 11;
|
||||
|
||||
// The extensions namespace allows 3rd-party developers to extend the
|
||||
// GTFS Realtime Specification in order to add and evaluate new features
|
||||
// and modifications to the spec.
|
||||
extensions 1000 to 1999;
|
||||
}
|
||||
|
||||
//
|
||||
// Low level data structures used above.
|
||||
//
|
||||
|
||||
// A time interval. The interval is considered active at time 't' if 't' is
|
||||
// greater than or equal to the start time and less than the end time.
|
||||
message TimeRange {
|
||||
// Start time, in POSIX time (i.e., number of seconds since January 1st 1970
|
||||
// 00:00:00 UTC).
|
||||
// If missing, the interval starts at minus infinity.
|
||||
optional uint64 start = 1;
|
||||
|
||||
// End time, in POSIX time (i.e., number of seconds since January 1st 1970
|
||||
// 00:00:00 UTC).
|
||||
// If missing, the interval ends at plus infinity.
|
||||
optional uint64 end = 2;
|
||||
|
||||
// The extensions namespace allows 3rd-party developers to extend the
|
||||
// GTFS Realtime Specification in order to add and evaluate new features and
|
||||
// modifications to the spec.
|
||||
extensions 1000 to 1999;
|
||||
}
|
||||
|
||||
// A position.
|
||||
message Position {
|
||||
// Degrees North, in the WGS-84 coordinate system.
|
||||
required float latitude = 1;
|
||||
|
||||
// Degrees East, in the WGS-84 coordinate system.
|
||||
required float longitude = 2;
|
||||
|
||||
// Bearing, in degrees, clockwise from North, i.e., 0 is North and 90 is East.
|
||||
// This can be the compass bearing, or the direction towards the next stop
|
||||
// or intermediate location.
|
||||
// This should not be direction deduced from the sequence of previous
|
||||
// positions, which can be computed from previous data.
|
||||
optional float bearing = 3;
|
||||
|
||||
// Odometer value, in meters.
|
||||
optional double odometer = 4;
|
||||
// Momentary speed measured by the vehicle, in meters per second.
|
||||
optional float speed = 5;
|
||||
|
||||
// The extensions namespace allows 3rd-party developers to extend the
|
||||
// GTFS Realtime Specification in order to add and evaluate new features and
|
||||
// modifications to the spec.
|
||||
extensions 1000 to 1999;
|
||||
}
|
||||
|
||||
// A descriptor that identifies an instance of a GTFS trip, or all instances of
|
||||
// a trip along a route.
|
||||
// - To specify a single trip instance, the trip_id (and if necessary,
|
||||
// start_time) is set. If route_id is also set, then it should be same as one
|
||||
// that the given trip corresponds to.
|
||||
// - To specify all the trips along a given route, only the route_id should be
|
||||
// set. Note that if the trip_id is not known, then stop sequence ids in
|
||||
// TripUpdate are not sufficient, and stop_ids must be provided as well. In
|
||||
// addition, absolute arrival/departure times must be provided.
|
||||
message TripDescriptor {
|
||||
// The trip_id from the GTFS feed that this selector refers to.
|
||||
// For non frequency-based trips, this field is enough to uniquely identify
|
||||
// the trip. For frequency-based trip, start_time and start_date might also be
|
||||
// necessary.
|
||||
optional string trip_id = 1;
|
||||
|
||||
// The route_id from the GTFS that this selector refers to.
|
||||
optional string route_id = 5;
|
||||
|
||||
// The direction_id from the GTFS feed trips.txt file, indicating the
|
||||
// direction of travel for trips this selector refers to. This field is
|
||||
// still experimental, and subject to change. It may be formally adopted in
|
||||
// the future.
|
||||
optional uint32 direction_id = 6;
|
||||
|
||||
// The initially scheduled start time of this trip instance.
|
||||
// When the trip_id corresponds to a non-frequency-based trip, this field
|
||||
// should either be omitted or be equal to the value in the GTFS feed. When
|
||||
// the trip_id corresponds to a frequency-based trip, the start_time must be
|
||||
// specified for trip updates and vehicle positions. If the trip corresponds
|
||||
// to exact_times=1 GTFS record, then start_time must be some multiple
|
||||
// (including zero) of headway_secs later than frequencies.txt start_time for
|
||||
// the corresponding time period. If the trip corresponds to exact_times=0,
|
||||
// then its start_time may be arbitrary, and is initially expected to be the
|
||||
// first departure of the trip. Once established, the start_time of this
|
||||
// frequency-based trip should be considered immutable, even if the first
|
||||
// departure time changes -- that time change may instead be reflected in a
|
||||
// StopTimeUpdate.
|
||||
// Format and semantics of the field is same as that of
|
||||
// GTFS/frequencies.txt/start_time, e.g., 11:15:35 or 25:15:35.
|
||||
optional string start_time = 2;
|
||||
// The scheduled start date of this trip instance.
|
||||
// Must be provided to disambiguate trips that are so late as to collide with
|
||||
// a scheduled trip on a next day. For example, for a train that departs 8:00
|
||||
// and 20:00 every day, and is 12 hours late, there would be two distinct
|
||||
// trips on the same time.
|
||||
// This field can be provided but is not mandatory for schedules in which such
|
||||
// collisions are impossible - for example, a service running on hourly
|
||||
// schedule where a vehicle that is one hour late is not considered to be
|
||||
// related to schedule anymore.
|
||||
// In YYYYMMDD format.
|
||||
optional string start_date = 3;
|
||||
|
||||
// The relation between this trip and the static schedule. If a trip is done
|
||||
// in accordance with temporary schedule, not reflected in GTFS, then it
|
||||
// shouldn't be marked as SCHEDULED, but likely as ADDED.
|
||||
enum ScheduleRelationship {
|
||||
// Trip that is running in accordance with its GTFS schedule, or is close
|
||||
// enough to the scheduled trip to be associated with it.
|
||||
SCHEDULED = 0;
|
||||
|
||||
// An extra trip that was added in addition to a running schedule, for
|
||||
// example, to replace a broken vehicle or to respond to sudden passenger
|
||||
// load.
|
||||
ADDED = 1;
|
||||
|
||||
// A trip that is running with no schedule associated to it, for example, if
|
||||
// there is no schedule at all.
|
||||
UNSCHEDULED = 2;
|
||||
|
||||
// A trip that existed in the schedule but was removed.
|
||||
CANCELED = 3;
|
||||
}
|
||||
optional ScheduleRelationship schedule_relationship = 4;
|
||||
|
||||
// The extensions namespace allows 3rd-party developers to extend the
|
||||
// GTFS Realtime Specification in order to add and evaluate new features and
|
||||
// modifications to the spec.
|
||||
extensions 1000 to 1999;
|
||||
}
|
||||
|
||||
// Identification information for the vehicle performing the trip.
|
||||
message VehicleDescriptor {
|
||||
// Internal system identification of the vehicle. Should be unique per
|
||||
// vehicle, and can be used for tracking the vehicle as it proceeds through
|
||||
// the system.
|
||||
optional string id = 1;
|
||||
|
||||
// User visible label, i.e., something that must be shown to the passenger to
|
||||
// help identify the correct vehicle.
|
||||
optional string label = 2;
|
||||
|
||||
// The license plate of the vehicle.
|
||||
optional string license_plate = 3;
|
||||
|
||||
// The extensions namespace allows 3rd-party developers to extend the
|
||||
// GTFS Realtime Specification in order to add and evaluate new features and
|
||||
// modifications to the spec.
|
||||
extensions 1000 to 1999;
|
||||
}
|
||||
|
||||
// A selector for an entity in a GTFS feed.
|
||||
message EntitySelector {
|
||||
// The values of the fields should correspond to the appropriate fields in the
|
||||
// GTFS feed.
|
||||
// At least one specifier must be given. If several are given, then the
|
||||
// matching has to apply to all the given specifiers.
|
||||
optional string agency_id = 1;
|
||||
optional string route_id = 2;
|
||||
// corresponds to route_type in GTFS.
|
||||
optional int32 route_type = 3;
|
||||
optional TripDescriptor trip = 4;
|
||||
optional string stop_id = 5;
|
||||
|
||||
// The extensions namespace allows 3rd-party developers to extend the
|
||||
// GTFS Realtime Specification in order to add and evaluate new features and
|
||||
// modifications to the spec.
|
||||
extensions 1000 to 1999;
|
||||
}
|
||||
|
||||
// An internationalized message containing per-language versions of a snippet of
|
||||
// text or a URL.
|
||||
// One of the strings from a message will be picked up. The resolution proceeds
|
||||
// as follows:
|
||||
// 1. If the UI language matches the language code of a translation,
|
||||
// the first matching translation is picked.
|
||||
// 2. If a default UI language (e.g., English) matches the language code of a
|
||||
// translation, the first matching translation is picked.
|
||||
// 3. If some translation has an unspecified language code, that translation is
|
||||
// picked.
|
||||
message TranslatedString {
|
||||
message Translation {
|
||||
// A UTF-8 string containing the message.
|
||||
required string text = 1;
|
||||
// BCP-47 language code. Can be omitted if the language is unknown or if
|
||||
// no i18n is done at all for the feed. At most one translation is
|
||||
// allowed to have an unspecified language tag.
|
||||
optional string language = 2;
|
||||
|
||||
// The extensions namespace allows 3rd-party developers to extend the
|
||||
// GTFS Realtime Specification in order to add and evaluate new features and
|
||||
// modifications to the spec.
|
||||
extensions 1000 to 1999;
|
||||
}
|
||||
// At least one translation must be provided.
|
||||
repeated Translation translation = 1;
|
||||
|
||||
// The extensions namespace allows 3rd-party developers to extend the
|
||||
// GTFS Realtime Specification in order to add and evaluate new features and
|
||||
// modifications to the spec.
|
||||
extensions 1000 to 1999;
|
||||
}
|
|
@ -0,0 +1,28 @@
|
|||
[
|
||||
{
|
||||
"direction": "I",
|
||||
"distance": 1948.575483806973,
|
||||
"epochTime": 1674650956,
|
||||
"latitude": -33.43729782104492,
|
||||
"licensePlate": "LJHX57",
|
||||
"longitude": -70.52730560302734,
|
||||
"realtime": true,
|
||||
"route": "C",
|
||||
"routeId": "C",
|
||||
"timeLabel": "09:49",
|
||||
"tripId": "C-I-L-005"
|
||||
},
|
||||
{
|
||||
"direction": "R",
|
||||
"distance": 1948.575483806973,
|
||||
"epochTime": 1674650956,
|
||||
"latitude": -33.43729782104492,
|
||||
"licensePlate": "LJHA57",
|
||||
"longitude": -70.52730560302734,
|
||||
"realtime": true,
|
||||
"route": "401",
|
||||
"routeId": "401",
|
||||
"timeLabel": "09:49",
|
||||
"tripId": "401-I-L-005"
|
||||
}
|
||||
]
|
After Width: | Height: | Size: 8.9 KiB |
After Width: | Height: | Size: 5.1 KiB |
After Width: | Height: | Size: 5.6 KiB |
After Width: | Height: | Size: 6.4 KiB |
|
@ -1,43 +0,0 @@
|
|||
#!/bin/bash
|
||||
|
||||
# Función para verificar el código de retorno
|
||||
verificar_codigo_retorno() {
|
||||
if [ $1 -eq 0 ]; then
|
||||
echo "[OK]"
|
||||
# Agrega aquí el código para el siguiente paso
|
||||
else
|
||||
echo "Hubo un error en el comando. Abortando el script."
|
||||
exit 1 # Termina el script con un código de retorno no exitoso
|
||||
fi
|
||||
}
|
||||
|
||||
echo -n "Instalando librerias necesarias "
|
||||
sudo apt update > /dev/null 2>&1
|
||||
sudo apt-get install python3-dev python3-pillow -y > /dev/null 2>&1
|
||||
|
||||
# Verificar el código de retorno llamando a la función
|
||||
verificar_codigo_retorno $?
|
||||
|
||||
echo -n "Entrando al repositorio "
|
||||
cd $HOME/rpi-rgb-led-matrix/bindings/python
|
||||
|
||||
# Verificar el código de retorno llamando a la función
|
||||
verificar_codigo_retorno $?
|
||||
|
||||
echo -n "Instalando rpi-rgb-led-matrix "
|
||||
make build-python PYTHON=$(command -v python3) > /dev/null 2>&1
|
||||
sudo make install-python PYTHON=$(command -v python3) > /dev/null 2>&1
|
||||
|
||||
# Verificar el código de retorno llamando a la función
|
||||
verificar_codigo_retorno $?
|
||||
|
||||
echo -n "Clonando repositorio FIC "
|
||||
cd $HOME
|
||||
git clone https://github.com/diegoalrv/pantallas-led > /dev/null 2>&1
|
||||
cd pantallas-led
|
||||
|
||||
# Verificar el código de retorno llamando a la función
|
||||
verificar_codigo_retorno $?
|
||||
|
||||
|
||||
|
BIN
esquema-repo.png
Before Width: | Height: | Size: 73 KiB |
|
@ -1,52 +0,0 @@
|
|||
#!/bin/bash
|
||||
|
||||
# Función para verificar el código de retorno
|
||||
verificar_codigo_retorno() {
|
||||
if [ $1 -eq 0 ]; then
|
||||
echo "[OK]"
|
||||
# Agrega aquí el código para el siguiente paso
|
||||
else
|
||||
echo "Hubo un error en el comando. Abortando el script."
|
||||
exit 1 # Termina el script con un código de retorno no exitoso
|
||||
fi
|
||||
}
|
||||
|
||||
# Instalación de bibliotecas
|
||||
echo -n "Actualizando repositorios "
|
||||
sudo apt update > /dev/null 2>&1
|
||||
|
||||
# Verificar el código de retorno llamando a la función
|
||||
verificar_codigo_retorno $?
|
||||
|
||||
echo -n "Instalando git "
|
||||
sudo apt install git -y > /dev/null 2>&1
|
||||
|
||||
# Verificar el código de retorno llamando a la función
|
||||
verificar_codigo_retorno $?
|
||||
|
||||
echo -n "Clonando repo de la matriz led "
|
||||
git clone https://github.com/hzeller/rpi-rgb-led-matrix.git > /dev/null 2>&1
|
||||
|
||||
# Verificar el código de retorno llamando a la función
|
||||
verificar_codigo_retorno $?
|
||||
|
||||
echo -n "Desactivando tarjeta de sonido "
|
||||
cat <<EOF | sudo tee /etc/modprobe.d/blacklist-rgb-matrix.conf > /dev/null 2>&1
|
||||
blacklist snd_bcm2835
|
||||
EOF
|
||||
sudo update-initramfs -u > /dev/null 2>&1
|
||||
|
||||
# Verificar el código de retorno llamando a la función
|
||||
verificar_codigo_retorno $?
|
||||
|
||||
tiempo=5
|
||||
|
||||
echo "El equipo se apagará en: "
|
||||
while [ $tiempo -gt 0 ]; do
|
||||
echo $tiempo
|
||||
sleep 1
|
||||
tiempo=$((tiempo-1))
|
||||
done
|
||||
|
||||
echo "¡Apagando el equipo ahora!"
|
||||
shutdown -h now
|
|
@ -0,0 +1,3 @@
|
|||
c = get_config()
|
||||
from notebook.auth import passwd
|
||||
c.NotebookApp.password = passwd("...")
|
|
@ -0,0 +1,5 @@
|
|||
matplotlib
|
||||
seaborn
|
||||
plotly
|
||||
opencv-python
|
||||
jupyter
|
|
@ -5,7 +5,7 @@ from PIL import ImageDraw, ImageFont
|
|||
from PIL import Image, ImageDraw, ImageFont
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
from .MyDraw import MyDraw
|
||||
from MyDraw import MyDraw
|
||||
|
||||
class BusPoster(MyDraw):
|
||||
|
||||
|
@ -37,12 +37,10 @@ class BusPoster(MyDraw):
|
|||
def set_bus_number(self, bus_number="11"):
|
||||
text_color = 'black'
|
||||
width_border = self.prms['width_border']
|
||||
# width_border = 0
|
||||
text_bbox = self.font.getbbox(str(bus_number))
|
||||
font_width, font_height = text_bbox[2] - text_bbox[0], text_bbox[3] - text_bbox[1]
|
||||
offset_width = np.round((self.prms['proportion']*self.width-width_border)/2) - np.round(font_width/2)
|
||||
# offset_width = 0
|
||||
text_position = (offset_width,-15)
|
||||
text_position = (offset_width,0)
|
||||
self.draw.text(
|
||||
text_position,
|
||||
bus_number,
|
||||
|
@ -59,7 +57,7 @@ class BusPoster(MyDraw):
|
|||
text_bbox = self.font.getbbox(str(bus_letter))
|
||||
font_width, font_height = text_bbox[2] - text_bbox[0], text_bbox[3] - text_bbox[1]
|
||||
offset_width = np.round((proportion*self.width-width_border)) + 0.75*np.round(font_width/2)
|
||||
text_position = (1.1*offset_width,-15)
|
||||
text_position = (offset_width,0)
|
||||
self.draw.text(
|
||||
text_position,
|
||||
bus_letter,
|
|
@ -65,8 +65,7 @@ class MyDraw():
|
|||
|
||||
def load_barlow(self, font_size=None):
|
||||
# Ruta a la fuente TTF personalizada
|
||||
# font_path = "../../assets/fonts/Barlow-Medium.ttf"
|
||||
font_path = "assets/fonts/Barlow-Medium.ttf"
|
||||
font_path = "/app/data/Barlow-Medium.ttf"
|
||||
# Carga la fuente
|
||||
if font_size is None:
|
||||
self.font = ImageFont.truetype(font_path, self.prms['font_size'])
|
|
@ -5,7 +5,7 @@ from PIL import ImageDraw, ImageFont
|
|||
from PIL import Image, ImageDraw, ImageFont
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
from .MyDraw import MyDraw
|
||||
from MyDraw import MyDraw
|
||||
|
||||
class TimeAnnouncement(MyDraw):
|
||||
|
||||
|
@ -45,49 +45,24 @@ class TimeAnnouncement(MyDraw):
|
|||
|
||||
text = "Tiempo aprox"
|
||||
text_color = self.theme_params['text_color']
|
||||
self.load_barlow(font_size=70)
|
||||
self.load_barlow(font_size=11)
|
||||
text_bbox = self.font.getbbox(text)
|
||||
base_font_width, base_font_height = text_bbox[2] - text_bbox[0], text_bbox[3] - text_bbox[1]
|
||||
|
||||
try:
|
||||
if (int(max_time) <= 1):
|
||||
text = "< 1 min"
|
||||
elif (int(min_time) >= 10):
|
||||
print(max_time)
|
||||
text = f"> {max_time} min"
|
||||
else:
|
||||
text = f'{min_time} a {max_time} min'
|
||||
except:
|
||||
text = 'N/A'
|
||||
|
||||
self.load_barlow(font_size=70)
|
||||
if (int(max_time) <= 1):
|
||||
text = "< 1 min"
|
||||
elif (int(min_time) >= 10):
|
||||
text = "> 10 min"
|
||||
else:
|
||||
text = f'{min_time} a {max_time} min'
|
||||
|
||||
self.load_barlow(font_size=18)
|
||||
text_bbox = self.font.getbbox(text)
|
||||
font_width, font_height = text_bbox[2] - text_bbox[0], text_bbox[3] - text_bbox[1]
|
||||
# print(font_width, font_height)
|
||||
offset_width = (np.round((self.width-self.border)) - np.round(font_width))/2
|
||||
offset_height = (np.round((self.height-self.border)) - np.round(base_font_height))/2
|
||||
# text_position = (offset_width,5+offset_height)
|
||||
text_position = (offset_width,offset_height-10)
|
||||
# text_position = (0, 0)
|
||||
self.draw.text(
|
||||
text_position,
|
||||
text,
|
||||
fill=text_color,
|
||||
font=self.font,
|
||||
align ="center"
|
||||
)
|
||||
|
||||
def set_remaining_text(self, text):
|
||||
|
||||
text_color = self.theme_params['text_color']
|
||||
self.load_barlow(font_size=70)
|
||||
text_bbox = self.font.getbbox(text)
|
||||
font_width, font_height = text_bbox[2] - text_bbox[0], text_bbox[3] - text_bbox[1]
|
||||
# print(font_width, font_height)
|
||||
offset_width = (np.round((self.width-self.border)) - np.round(font_width))/2
|
||||
offset_height = (np.round((self.height-self.border)) - np.round(font_height))/2
|
||||
# text_position = (offset_width,5+offset_height)
|
||||
text_position = (offset_width,offset_height-10)
|
||||
text_position = (offset_width,5+offset_height)
|
||||
# text_position = (0, 0)
|
||||
self.draw.text(
|
||||
text_position,
|
152
testapi_full.py
|
@ -1,152 +0,0 @@
|
|||
#!/usr/bin/env python3
|
||||
|
||||
import requests
|
||||
import json
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
# URL de la API para "autentificación"
|
||||
url_auth = 'https://transporte.hz.kursor.cl/api/auth/'
|
||||
|
||||
# Datos para autentificar
|
||||
auth = '''{
|
||||
"username": "usuario1",
|
||||
"password": "usuario1"
|
||||
}'''
|
||||
|
||||
# Request
|
||||
token = requests.post(url_auth, data=auth)
|
||||
|
||||
# Estado de la respuesta
|
||||
if token.status_code == 200:
|
||||
# solicitud exitosa
|
||||
print('Respuesta de token exitosa!')
|
||||
else:
|
||||
# Error en la solicitud
|
||||
print('Error en la solicitud del token:', token.status_code, token.text)
|
||||
|
||||
token = token.json()['token']
|
||||
|
||||
print('-----------------------------------------------------')
|
||||
print('Token Obtenido: ' + token)
|
||||
print('-----------------------------------------------------')
|
||||
|
||||
#--------------------------------------------------------
|
||||
|
||||
# URL de la API para info del paradero
|
||||
url_whoami = 'https://transporte.hz.kursor.cl/api/dispositivos/whoami/'
|
||||
|
||||
# Datos de la solicitud
|
||||
data_whoami = {
|
||||
"whoami": {
|
||||
"idDispositivo": "pled30-gtr", #Aquí dejaron esta id por defecto....
|
||||
"KeyAuthorizacion": "token" #Autentificacion de mentira sisisi (la real está comenta después de esta variable
|
||||
}
|
||||
}
|
||||
|
||||
#Aquí se ingresa el token obtenido anteriormente
|
||||
headers_whoami = {
|
||||
'Authorization': f'Bearer {token}',
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
|
||||
# Request
|
||||
response_whoami = requests.post(url_whoami, json=data_whoami, headers=headers_whoami)
|
||||
|
||||
# Estado de la respuesta
|
||||
if response_whoami.status_code == 200:
|
||||
# Solicitud exitosa
|
||||
print('Respuesta API "whoami" exitosa')
|
||||
else:
|
||||
# Error en la solicitud
|
||||
print('Error en la solicitud de API "whoami": ', response_whoami.status_code, response_whoami.text)
|
||||
|
||||
|
||||
Paradero = response_whoami.json()
|
||||
#print(json.dumps(Paradero, indent=4, ensure_ascii=False, sort_keys=True))
|
||||
|
||||
print('-----------------------------------------------------')
|
||||
|
||||
|
||||
# URL de la API para obtener los datos de los recorridos
|
||||
url_getinfodevice = 'https://transporte.hz.kursor.cl/api/dispositivos/getInfoDevice/'
|
||||
|
||||
# Datos para la solicitud
|
||||
data_getinfodevice = {
|
||||
"GetInfoDevice": {
|
||||
"idDispositivo": "00000000160f3b42b8:27:eb:0f:3b:42", #Para esta solicitud, pusieron la id del equipo que les dimos
|
||||
"KeyAuthorizacion": "tokenSinUso" #Autentificacion de mentira sisisi
|
||||
}
|
||||
}
|
||||
|
||||
#Aquí se ingresa el token obtenido anteriormente
|
||||
headers_getinfodevice = {
|
||||
'Authorization': f'Bearer {token}',
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
|
||||
# Request
|
||||
response_getinfodevice = requests.post(url_getinfodevice, json=data_getinfodevice, headers=headers_getinfodevice)
|
||||
|
||||
# Estado de la respuesta
|
||||
if response_getinfodevice.status_code == 200:
|
||||
# Solicitud exitosa
|
||||
print('Respuesta API "GetInfoDevice" exitosa')
|
||||
else:
|
||||
# Error en la solicitud
|
||||
print('Error en la solicitud de API "GetInfoDevice": ', response_getinfodevice.status_code, response_getinfodevice.text)
|
||||
|
||||
info = response_getinfodevice.json()
|
||||
#print(json.dumps(info, indent=4, ensure_ascii=False, sort_keys=True))
|
||||
|
||||
print(info)
|
||||
|
||||
print("----------------------------------------------------------")
|
||||
print("Cantidad de buses con llegada registrada en este paradero:", len(info["GetInfoDeviceResponse"]["DetalleLineas"]))
|
||||
print("----------------------------------------------------------")
|
||||
|
||||
#Haciendo una lista de todos los buses de este paradero
|
||||
|
||||
data_main = []
|
||||
hora_actual = datetime.now().time()
|
||||
|
||||
for i in range(len(info["GetInfoDeviceResponse"]["DetalleLineas"])):
|
||||
|
||||
data = info["GetInfoDeviceResponse"]["DetalleLineas"][i]
|
||||
|
||||
bus_info = {}
|
||||
bus_info["distance"] = data["Llegadas"][0]["DistanciaGPS"] if data["Llegadas"][0]["DistanciaGPS"] is not None else "-"
|
||||
bus_info["timeLabel"] = data["Llegadas"][0]["EstimadaGPS"] if data["Llegadas"][0]["EstimadaGPS"] is not None else "-"
|
||||
bus_info["route"] = data["Descripcion"][:-1] if data["Descripcion"] is not None else "-"
|
||||
bus_info["direction"] = data["Descripcion"][-1] if data["Descripcion"] is not None else "-"
|
||||
bus_info["number_background_color"] = data["colorFondo"]
|
||||
bus_info["letter_background_color"] = data["colorTexto"]
|
||||
bus_info["patente"] = data["Llegadas"][0]["patente"]
|
||||
diff = timedelta(hours = datetime.strptime(bus_info["timeLabel"], "%H:%M:%S").time().hour - hora_actual.hour,minutes = datetime.strptime(bus_info["timeLabel"], "%H:%M:%S").time().minute - hora_actual.minute,seconds = datetime.strptime(bus_info["timeLabel"], "%H:%M:%S").time().second - hora_actual.second)
|
||||
bus_info["timeRemaining"] = int(abs(diff.total_seconds() // 60))
|
||||
data_main.append(bus_info)
|
||||
|
||||
#Cálculo del tiempo estimado de llegada para cada bus
|
||||
|
||||
data_time = sorted(data_main, key=lambda x: x['timeRemaining'])
|
||||
#data_time = data_main
|
||||
|
||||
print("Buses ordenados según hora de llegada:\n")
|
||||
print("Hora Actual (CL): ", datetime.now().strftime("%H:%M:%S"))
|
||||
print("Paradero N°", Paradero["WhoamiResponse"]["NroParadero"], Paradero["WhoamiResponse"]["NombreParadero"],"\n")
|
||||
|
||||
for n in data_time:
|
||||
#print(n)
|
||||
print("Recorrido:",n["route"],n["direction"],"| Patente:",n["patente"],"| Tiempo restante de llegada:", n["timeRemaining"],"minutos.")
|
||||
|
||||
print("--------------------------------------------------------------")
|
||||
|
||||
#Exportando datos
|
||||
|
||||
#def export_data():
|
||||
# data_x = (data_time[0],data_time[1])
|
||||
# return data_x
|
||||
|
||||
#data_x = (data_time[0],data_time[1])
|
||||
#print(data_x)
|
||||
|
||||
|