Compare commits
26 Commits
e185b38222
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
| dde33ca5c3 | |||
| d12b4da065 | |||
| 3992a77c78 | |||
| 512b683d55 | |||
| fc74dc5d9b | |||
| edaac93dfd | |||
| 1b2862dea5 | |||
| 6b70140869 | |||
| 23b1863a82 | |||
| b7894ea559 | |||
| f84022b8cf | |||
| 559a314dbe | |||
| b60520009f | |||
| 618c4ff2fe | |||
| a2ccb9b761 | |||
| 8496cfd72f | |||
| 40f8c46d80 | |||
| cba2b17f57 | |||
| 0a7a425ea7 | |||
| dc368ca811 | |||
| 2957ccf1ff | |||
| a48ddfc9b7 | |||
| b9cb2ac504 | |||
| 08c028bfa8 | |||
| 74aa9e8a84 | |||
| 391380040e |
@@ -1,3 +1,4 @@
|
||||
/target
|
||||
/.vscode
|
||||
/libs
|
||||
Cargo.lock
|
||||
|
||||
+19
-6
@@ -5,16 +5,29 @@ edition = "2024"
|
||||
host = "x86_64-unknown-linux-gnu"
|
||||
|
||||
[dependencies]
|
||||
sdl3 = {version = "0.17", features = ["ttf"]}
|
||||
serde = "1.0"
|
||||
gtfs-structures = "0.47"
|
||||
chrono = "0.4"
|
||||
log = "0.4"
|
||||
zip = "8.3"
|
||||
csv = "1.4"
|
||||
gtfs-structures = "0.47"
|
||||
gtfs-realtime = "0.2"
|
||||
log = "0.4"
|
||||
prost = "0.14"
|
||||
prost-types = "0.14"
|
||||
reqwest = { version = "0.11", features = ["blocking"] }
|
||||
sdl3 = {version = "0.17", features = ["ttf"]}
|
||||
serde = { version = "1.0", features = ["derive"]}
|
||||
serde_json = "1.0"
|
||||
time-format = "1.2"
|
||||
yaml_serde = "0.10"
|
||||
zip = "8.3"
|
||||
|
||||
[profile.dev]
|
||||
opt-level = 3
|
||||
opt-level = 1
|
||||
|
||||
[profile.release]
|
||||
opt-level = 3
|
||||
|
||||
[package.metadata.appimage]
|
||||
assets = ["resources"]
|
||||
icon = "resources/icon.png"
|
||||
desktop_entry = "other/rs-dublinbus.desktop"
|
||||
auto-link=true
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
[build]
|
||||
default-target = "aarch64-unknown-linux-gnu" # use this target if none is explicitly provided
|
||||
pre-build = [ # additional commands to run prior to building the package
|
||||
"dpkg --add-architecture $CROSS_DEB_ARCH",
|
||||
"apt update",
|
||||
"apt --assume-yes install apt-utils:$CROSS_DEB_ARCH",
|
||||
"apt --assume-yes install libsdl3-dev:$CROSS_DEB_ARCH"
|
||||
]
|
||||
@@ -0,0 +1,97 @@
|
||||
# The deployment process works like this:
|
||||
# 1. Build locally just to make sure that things work
|
||||
# 2. SSH into the machine that will build the AppImage for ARM. There:
|
||||
# 2.1. run git pull to get the latest version of the code
|
||||
# 2.2. run argo appimage to build the image
|
||||
# 3. SCP the appimage back to the local machine
|
||||
# 4. SCP the files to the Raspberry Pi running the display:
|
||||
# AppImage
|
||||
# systemd service file
|
||||
# 5. SSH into the display machine as root and:
|
||||
# 5.1. Copy the AppImage file to /opt/dublinbus-display (create the directory if necessary)
|
||||
# 5.2. If the service exists, restart it and exit
|
||||
# 5.3. Copy the service file to /etc/systemd/system
|
||||
# 5.4. Enable and activate the service
|
||||
|
||||
|
||||
|
||||
# Variables
|
||||
GIT_REPO_URL="http://git.nahuellofeudo.com/nahuel/rs-dublinbus.git"
|
||||
|
||||
# For the build machine
|
||||
BUILD_MACHINE_NAME=raspi-ssd.localnet
|
||||
BUILD_MACHINE_USER=nahuel
|
||||
BUILD_MACHINE_SOURCE_DIRECTORY=/home/nahuel/Documents/sources
|
||||
|
||||
DEPLOY_MACHINE_NAME=dublinbus-display.local
|
||||
DEPLOY_MACHINE_USER=display
|
||||
DEPLOY_MACHINE_TARGET_DIRECTORY=/opt/dublinbus
|
||||
|
||||
|
||||
# 1. Build locally
|
||||
cargo appimage
|
||||
|
||||
if [[ $? -ne 0 ]]; then
|
||||
echo
|
||||
echo
|
||||
echo "-------------------------------------------------------"
|
||||
echo "\"cargo appimage\" failed. Check the logs"
|
||||
echo "-------------------------------------------------------"
|
||||
exit $?
|
||||
fi
|
||||
|
||||
echo
|
||||
echo
|
||||
echo "-------------------------------------------------------"
|
||||
echo "Local build successful "
|
||||
echo "-------------------------------------------------------"
|
||||
|
||||
|
||||
# 2. Build remotely on the ARM machine
|
||||
ssh $BUILD_MACHINE_USER@$BUILD_MACHINE_NAME << EOF
|
||||
echo Entering ${BUILD_MACHINE_SOURCE_DIRECTORY}
|
||||
cd ${BUILD_MACHINE_SOURCE_DIRECTORY}
|
||||
if [[ ! -d rs-dublinbus ]]; then
|
||||
git clone ${GIT_REPO_URL}
|
||||
cd rs-dublinbus
|
||||
else
|
||||
cd rs-dublinbus
|
||||
git reset --hard
|
||||
git pull
|
||||
fi
|
||||
|
||||
cargo appimage
|
||||
EOF
|
||||
|
||||
if [[ $? -ne 0 ]]; then
|
||||
echo
|
||||
echo
|
||||
echo "-------------------------------------------------------"
|
||||
echo "Remote build failed. Check the logs"
|
||||
echo "-------------------------------------------------------"
|
||||
exit $?
|
||||
fi
|
||||
|
||||
|
||||
echo
|
||||
echo
|
||||
echo "-------------------------------------------------------"
|
||||
echo "Remote build successful "
|
||||
echo "-------------------------------------------------------"
|
||||
|
||||
# 3. SCP the appimage back to the local machine
|
||||
scp $BUILD_MACHINE_USER@$BUILD_MACHINE_NAME:Documents/sources/rs-dublinbus/target/appimage/rs-dublinbus.AppImage /tmp
|
||||
|
||||
# 4. SCP the files to the Raspberry Pi running the display:
|
||||
scp /tmp/rs-dublinbus.AppImage $DEPLOY_MACHINE_USER@$DEPLOY_MACHINE_NAME:$DEPLOY_MACHINE_TARGET_DIRECTORY
|
||||
|
||||
# Set up the service
|
||||
ssh $DEPLOY_MACHINE_USER@$DEPLOY_MACHINE_NAME << EOF
|
||||
sudo systemctl restart dublinbus
|
||||
EOF
|
||||
|
||||
echo
|
||||
echo
|
||||
echo "-------------------------------------------------------"
|
||||
echo "Service deployed and restarted "
|
||||
echo "-------------------------------------------------------"
|
||||
@@ -3,24 +3,42 @@
|
||||
- LCD Rounded font by Jecko Development (http://www.jeckodevelopment.com)
|
||||
|
||||
|
||||
## Dependencies (Debian/Raspberry Pi OS)
|
||||
|
||||
* librust-openssl-dev
|
||||
* protobuf-compiler
|
||||
* libsdl3-dev
|
||||
* libsdl3-ttf-dev
|
||||
|
||||
## Install appimage package
|
||||
```
|
||||
cargo install cargo-appimage
|
||||
```
|
||||
|
||||
## Install ARM toolchains:
|
||||
|
||||
```
|
||||
cargo install cross
|
||||
rustup target add aarch64-unknown-linux-gnu # 64-bit Pi OS
|
||||
rustup target add armv7-unknown-linux-gnueabihf # 32-bit Pi 2/3/4 OS
|
||||
rustup target add arm-unknown-linux-gnueabihf # ARMv6 (Pi Zero/1)
|
||||
```bash
|
||||
$ rustup target add aarch64-unknown-linux-gnu
|
||||
$ rustup target add arm-unknown-linux-gnueabihf
|
||||
|
||||
sudo apt-get update
|
||||
sudo apt-get install gcc-aarch64-linux-gnu gcc-arm-linux-gnueabihf
|
||||
|
||||
$ sudo dpkg --add-architecture arm64
|
||||
$ sudo dpkg --add-architecture armhf
|
||||
|
||||
$ sudo apt update
|
||||
$ sudo apt-get install gcc-aarch64-linux-gnu gcc-arm-linux-gnueabihf \
|
||||
libc6-arm64-cross libc6-dev-arm64-cross gcc-aarch64-linux-gnu \
|
||||
libc6-armhf-cross libc6-dev-armhf-cross gcc-arm-linux-gnueabihf \
|
||||
libssl-dev libssl-dev:arm64 libsdl3-dev:arm64 libssl-dev:armhf libsdl3-dev:armhf
|
||||
```
|
||||
|
||||
## Cross-compile
|
||||
|
||||
```
|
||||
# 2) Build
|
||||
~/.cargo/bin/cross build --target aarch64-unknown-linux-gnu --release
|
||||
~/.cargo/bin/cross build --target armv7-unknown-linux-gnueabihf --release
|
||||
~/.cargo/bin/cross build --target arm-unknown-linux-gnueabihf --release
|
||||
ARM64
|
||||
```bash
|
||||
$ export PKG_CONFIG_SYSROOT_DIR=/usr/aarch64-linux-gnu/
|
||||
$ cargo build --target aarch64-unknown-linux-gnu --release
|
||||
|
||||
$ export PKG_CONFIG_SYSROOT_DIR=/usr/arm-linux-gnueabihf/
|
||||
$ cargo build --target arm-unknown-linux-gnueabihf --release
|
||||
```
|
||||
@@ -0,0 +1,13 @@
|
||||
[Unit]
|
||||
Description=Start Dublin Bus display
|
||||
After=multi-user.target
|
||||
Wants=multi-user.target
|
||||
|
||||
[Service]
|
||||
Restart=always
|
||||
Type=exec
|
||||
WorkingDirectory=/opt/dublinbus
|
||||
ExecStart=/opt/dublinbus/rs-dublinbus.AppImage
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -0,0 +1,18 @@
|
||||
screen:
|
||||
width: 1920
|
||||
height: 720
|
||||
font-path: "resources/jd-lcd-rounded.ttf"
|
||||
|
||||
gtfs:
|
||||
routes:
|
||||
- 15A
|
||||
- F1
|
||||
- F2
|
||||
stops:
|
||||
- 1114
|
||||
- 2410
|
||||
data-folder: "/tmp"
|
||||
gtfs-url: "https://www.transportforireland.ie/transitData/Data/GTFS_Realtime.zip"
|
||||
realtime-url: "https://api.nationaltransport.ie/gtfsr/v2/gtfsr"
|
||||
realtime-api-key: "aa8509902455412e886b9df11f0e21ec"
|
||||
refresh-seconds: 61
|
||||
@@ -1,132 +0,0 @@
|
||||
use gtfs_structures::{Agency, Calendar, CalendarDate, Route, Stop};
|
||||
use serde::{de::DeserializeOwned};
|
||||
use std::{collections::HashMap, fs::File};
|
||||
use zip::ZipArchive;
|
||||
|
||||
// The main GTFS struct. This is similar to (but not exactly) gtfs-structures::Gtfs because we don't need everything
|
||||
#[derive(Debug)]
|
||||
pub struct Gtfs {
|
||||
/// All agencies. They can not be read by `agency_id`, as it is not a required field
|
||||
pub agencies: Vec<Agency>,
|
||||
/// All Calendar by `service_id`
|
||||
pub calendar: HashMap<String, Calendar>,
|
||||
/// All calendar dates grouped by service_id
|
||||
pub calendar_dates: HashMap<String, Vec<CalendarDate>>,
|
||||
/// All routes by `route_id`
|
||||
pub routes: HashMap<String, Route>,
|
||||
/// All stop by `stop_id`.
|
||||
pub stops: HashMap<String, Stop>,
|
||||
}
|
||||
|
||||
// Utility function to load all records in a dataset
|
||||
fn load_all<V>(_: &V) -> bool { true }
|
||||
|
||||
// Loads a vector of the selected type
|
||||
fn load_vector<T: serde::de::DeserializeOwned>(
|
||||
destination: &mut Vec<T>,
|
||||
zip_reader: &mut ZipArchive<File>,
|
||||
table_name: &str,
|
||||
) {
|
||||
let file_reader = zip_reader.by_name(table_name).unwrap();
|
||||
let mut rdr = csv::Reader::from_reader(file_reader);
|
||||
|
||||
for row in rdr.deserialize() {
|
||||
let record: T = row.unwrap();
|
||||
destination.push(record);
|
||||
}
|
||||
}
|
||||
|
||||
// Loads a HashMap of the selected type, using the provided index function as the key
|
||||
fn load_map<'a, V: DeserializeOwned>(
|
||||
destination: &mut HashMap<String, V>,
|
||||
zip_reader: &mut ZipArchive<File>,
|
||||
table_name: &str,
|
||||
index: fn(&V) -> String,
|
||||
accept: fn(&V) -> bool,
|
||||
) {
|
||||
let file_reader = zip_reader.by_name(table_name).unwrap();
|
||||
let mut rdr = csv::Reader::from_reader(file_reader);
|
||||
|
||||
for row in rdr.deserialize() {
|
||||
let record: V = row.unwrap();
|
||||
if accept(&record) {
|
||||
let idx: String = index(&record);
|
||||
destination.insert(idx, record);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Loads a HashMap of a vector of the selected type, using the provided index function as the key
|
||||
// And a predicate as a filter
|
||||
fn load_vector_map<'a, V: DeserializeOwned + Clone>(
|
||||
destination: &mut HashMap<String, Vec<V>>,
|
||||
zip_reader: &mut ZipArchive<File>,
|
||||
table_name: &str,
|
||||
index: fn(&V) -> String,
|
||||
accept: fn(&V) -> bool,
|
||||
) {
|
||||
let file_reader = zip_reader.by_name(table_name).unwrap();
|
||||
let mut rdr = csv::Reader::from_reader(file_reader);
|
||||
|
||||
for row in rdr.deserialize() {
|
||||
let record: V = row.unwrap();
|
||||
if accept(&record) {
|
||||
let idx: String = index(&record);
|
||||
destination.entry(idx).or_insert_with(Vec::new).push(record);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn init(src_file: &str, routes: Vec<String>) -> Gtfs {
|
||||
// Open zip file
|
||||
let mut zip_reader = zip::ZipArchive::new(File::open(src_file).unwrap()).unwrap();
|
||||
|
||||
let mut gtfs: Gtfs = Gtfs {
|
||||
agencies: Vec::new(),
|
||||
calendar: HashMap::new(),
|
||||
calendar_dates: HashMap::new(),
|
||||
routes: HashMap::new(),
|
||||
stops: HashMap::new(),
|
||||
};
|
||||
|
||||
// Agencies
|
||||
load_vector(&mut gtfs.agencies, &mut zip_reader, "agency.txt");
|
||||
|
||||
// Calendars
|
||||
load_map(
|
||||
&mut gtfs.calendar,
|
||||
&mut zip_reader,
|
||||
"calendar.txt",
|
||||
|c: &Calendar| String::from(&c.id),
|
||||
load_all
|
||||
);
|
||||
|
||||
// Calendar Dates
|
||||
load_vector_map(
|
||||
&mut gtfs.calendar_dates,
|
||||
&mut zip_reader,
|
||||
"calendar_dates.txt",
|
||||
|d: &CalendarDate| String::from(&d.service_id),
|
||||
load_all
|
||||
);
|
||||
|
||||
// Stops
|
||||
load_map(&mut gtfs.stops,
|
||||
&mut zip_reader,
|
||||
"stops.txt",
|
||||
|s: &Stop| {String::from(&s.id)},
|
||||
load_all
|
||||
);
|
||||
|
||||
// Routes
|
||||
let accept_filter: fn(&Route) -> bool = (| rs: Vec<String>, r: &Route | {rs.contains(&r.short_name.unwrap())}).curry(routes);
|
||||
load_map(
|
||||
&mut gtfs.routes,
|
||||
&mut zip_reader,
|
||||
"routes.txt",
|
||||
|r: &Route| String::from(&r.id),
|
||||
accept_filter
|
||||
);
|
||||
|
||||
return gtfs;
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 2.1 KiB |
@@ -1,14 +0,0 @@
|
||||
JECKO DEVELOPMENT FONT
|
||||
|
||||
This font was created by Jecko Development (http://www.jeckodevelopment.com)
|
||||
This font has a homepage where this archive and other versions may be found ::
|
||||
http://www.jeckodevelopment.com/fonts/
|
||||
This font is released under a Creative Commons Attribution Non-commercial No Derivatives
|
||||
license (http://creativecommons.org/licenses/by-nc-nd/3.0/).
|
||||
NOTE FOR FLASH USERS: This font is optimized for
|
||||
Flash. If the font in this archive is a pixel font, it is best displayed at a
|
||||
font-size of 64.
|
||||
|
||||
Feel free to write us at info@jeckodevelopment.com or visit our website http://www.jeckodevelopment.com
|
||||
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
use crate::{gtfs, renderer};
|
||||
use serde::{Serialize, Deserialize};
|
||||
use std::fs;
|
||||
use yaml_serde;
|
||||
|
||||
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Config {
|
||||
#[serde(rename = "gtfs")]
|
||||
pub gtfs_prefs: gtfs::structs::Preferences,
|
||||
|
||||
#[serde(rename = "screen")]
|
||||
pub screen_prefs: renderer::structs::Prefs,
|
||||
}
|
||||
|
||||
#[derive (Debug)]
|
||||
pub struct Error {
|
||||
pub message: String
|
||||
}
|
||||
|
||||
|
||||
impl From<std::io::Error> for Error {
|
||||
fn from(value: std::io::Error) -> Self {
|
||||
return Error {
|
||||
message: value.to_string(),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
impl From<yaml_serde::Error> for Error {
|
||||
fn from(value: yaml_serde::Error) -> Self {
|
||||
return Error {
|
||||
message: value.to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<sdl3::Error> for Error {
|
||||
fn from(value: sdl3::Error) -> Self {
|
||||
return Error {
|
||||
message: value.to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
pub fn load_config(config_name: String) -> Result<Config, Error> {
|
||||
let config_text = fs::read_to_string(config_name)?;
|
||||
let config = yaml_serde::from_str(config_text.as_ref())?;
|
||||
return Ok(config);
|
||||
}
|
||||
+28
-12
@@ -1,31 +1,31 @@
|
||||
mod arrival;
|
||||
mod loader;
|
||||
mod utils;
|
||||
mod refresher;
|
||||
mod realtime;
|
||||
pub mod structs;
|
||||
use chrono::{DateTime, Local, Timelike};
|
||||
use log::{debug};
|
||||
use sdl3::sys::pixels::SDL_ArrayOrder;
|
||||
use std::{
|
||||
collections::{HashMap, HashSet}, fs::File, io::Error
|
||||
};
|
||||
use log::{debug, trace, warn};
|
||||
use std::{collections::{HashMap, HashSet}, fs::File };
|
||||
use gtfs_structures::{Exception, RawTrip};
|
||||
|
||||
use crate::gtfs::{loader::load_gtfs, structs::{Arrival, Gtfs, Preferences}};
|
||||
use crate::gtfs::{loader::load_gtfs, structs::{Arrival, Gtfs, Preferences, Error}};
|
||||
|
||||
|
||||
impl Gtfs {
|
||||
impl Gtfs<'_> {
|
||||
|
||||
pub fn get_next_arrivals_for(&self, target_datetime: &DateTime<Local>) -> Option<Vec<Arrival<'_>>> {
|
||||
let naive_target = target_datetime.naive_local();
|
||||
let target_date = naive_target.date();
|
||||
|
||||
// Find which calendars apply
|
||||
debug!("Looking for calendars that apply to date {:#?}", target_date);
|
||||
let mut active_service_ids: HashSet<String> = HashSet::new();
|
||||
for (id, calendar) in self.calendar.iter() {
|
||||
if calendar.valid_weekday(target_date)
|
||||
&& calendar.start_date <= target_date
|
||||
&& calendar.end_date > target_date {
|
||||
active_service_ids.insert(id.to_string());
|
||||
debug!("Matched calendar: {:#?}", calendar);
|
||||
}
|
||||
}
|
||||
debug!("Found {} services active today", active_service_ids.len());
|
||||
@@ -45,7 +45,7 @@ impl Gtfs {
|
||||
}
|
||||
}
|
||||
}
|
||||
debug!("After exceptions, there are now {} services active", active_service_ids.len());
|
||||
debug!("After exceptions, there are now {} services active: {:#?}", active_service_ids.len(), active_service_ids);
|
||||
|
||||
// Find the trips happening on these calendars
|
||||
let mut trips: HashMap<&String, &RawTrip> = HashMap::new();
|
||||
@@ -76,25 +76,41 @@ impl Gtfs {
|
||||
trip: &trip,
|
||||
departure_time: stop_timestamp.into()
|
||||
};
|
||||
debug!("Arrival to {:#?} for trip ID {:#?}.", arrival.trip.trip_headsign.as_ref().unwrap(), arrival.trip.id);
|
||||
trace!("{:#?}: Arrival to {:#?} for trip ID {:#?}.",
|
||||
format!("{:02}:{:02}", (arrival.departure_time/3600) as u32, ((arrival.departure_time / 60) % 60) as u32),
|
||||
arrival.trip.trip_headsign.as_ref().unwrap(),
|
||||
arrival.trip.id);
|
||||
arrivals.push(arrival);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
arrivals.sort();
|
||||
|
||||
debug!("Found {} arrivals", arrivals.len());
|
||||
|
||||
// Update real-time deltas
|
||||
|
||||
let realtime_result = self.realtime_update(&mut arrivals);
|
||||
if realtime_result.is_err() {
|
||||
warn!("Unable to update realtime arrivals: {:#?}", realtime_result.err().unwrap()._message)
|
||||
}
|
||||
|
||||
return Some(arrivals);
|
||||
}
|
||||
|
||||
|
||||
/// Load a GTFS structure from a zip file
|
||||
pub fn load(src_file: &str, prefs: &Preferences) -> Result<Gtfs, Error> {
|
||||
pub fn load(prefs: &Preferences) -> Result<Gtfs<'_>, Error> {
|
||||
|
||||
_ = refresher::refresh(prefs);
|
||||
|
||||
// Open zip file
|
||||
let zip_file = File::open(src_file)?;
|
||||
let zip_file = File::open(prefs.gtfs_file_path()?)?;
|
||||
let mut zip_reader = zip::ZipArchive::new(zip_file)?;
|
||||
|
||||
let mut gtfs: Gtfs = Gtfs {
|
||||
preferences: prefs,
|
||||
agencies: Vec::new(),
|
||||
calendar: HashMap::new(),
|
||||
calendar_dates: HashMap::new(),
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
use log::debug;
|
||||
/***
|
||||
* Implementation of GTFS-R polling
|
||||
*/
|
||||
use reqwest::{StatusCode, blocking::Client};
|
||||
use std::{collections::HashMap, time::Duration};
|
||||
|
||||
use crate::gtfs::{self, structs::{Arrival, Error, Gtfs}};
|
||||
|
||||
impl Gtfs<'_> {
|
||||
pub(crate) fn realtime_update (&self, arrivals: &mut Vec<Arrival<'_>>) -> Result<(), gtfs::structs::Error>{
|
||||
|
||||
// Poll GTFS-R API
|
||||
let client = Client::builder()
|
||||
.timeout(Duration::from_secs(10))
|
||||
.connect_timeout(Duration::from_secs(5))
|
||||
.build()?;
|
||||
|
||||
let response = client
|
||||
.get(&self.preferences.realtime_url)
|
||||
.header("x-api-key", &self.preferences.realtime_api_key)
|
||||
.send()?;
|
||||
|
||||
if response.status() != StatusCode::OK {
|
||||
return Err(Error {
|
||||
_message : format!("HTTP Respomse: {:#?}. Payload: \n{:#?}\n", response.status(), response.text().unwrap())
|
||||
})
|
||||
}
|
||||
|
||||
// Parse response
|
||||
let response_bytes= response.bytes()?;
|
||||
let data: Result<gtfs_realtime::FeedMessage, prost::DecodeError> = prost::Message::decode(response_bytes.as_ref());
|
||||
if data.is_err() {
|
||||
return Err(Error {
|
||||
_message : format! ("Error loading realtime prtobuf: {:#?}", data.err().unwrap())
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
// Build a map of (trip, stop) -> Arrival for faster lookup
|
||||
let mut lookup: HashMap<(String, String), usize> = HashMap::new();
|
||||
let num_arrivals = arrivals.len();
|
||||
for i in 0..num_arrivals {
|
||||
let arrival = arrivals.get(i).unwrap();
|
||||
lookup.insert((arrival.trip.id.clone(), arrival.stop.id.clone()), i);
|
||||
}
|
||||
|
||||
// Match deltas to existing arrivals
|
||||
let entities = data.unwrap().entity;
|
||||
debug!("Loaded {} entities from realtime update.", entities.len());
|
||||
for entity in entities {
|
||||
if entity.trip_update.is_some() && entity.stop.is_some() {
|
||||
let trip_update = entity.trip_update.unwrap();
|
||||
|
||||
// Look up the entry in arrivals for the current
|
||||
for stop_update in trip_update.stop_time_update {
|
||||
if stop_update.stop_id.is_none() {
|
||||
continue;
|
||||
}
|
||||
let trip_id = trip_update.trip.trip_id.clone().unwrap();
|
||||
let stop_id = stop_update.stop_id.unwrap();
|
||||
let key = (trip_id, stop_id);
|
||||
if lookup.contains_key(&key) {
|
||||
|
||||
// Update the arrival time
|
||||
let arrival_index = lookup.get(&key);
|
||||
let arrival: &mut Arrival<'_> = arrivals.get_mut(*arrival_index.unwrap()).unwrap();
|
||||
if let Some(update) = stop_update.departure.or(stop_update.arrival) {
|
||||
let new_time = (((arrival.departure_time as i64)
|
||||
+ (update.delay.unwrap_or(0) as i64))) as u32;
|
||||
debug!("Updated arrival time of {:#?} by {}s", &key, update.delay.unwrap());
|
||||
arrival.departure_time = new_time;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
use log::{debug, info};
|
||||
use time_format::format_common_utc;
|
||||
use std::{fs::{self}, time::{Duration, SystemTime, UNIX_EPOCH}};
|
||||
use crate::gtfs::structs::{Error, Preferences};
|
||||
use reqwest::{StatusCode, blocking::Client};
|
||||
|
||||
|
||||
pub(crate) fn refresh(prefs: &Preferences) -> Result<(), Error> {
|
||||
|
||||
let mut modified_timestamp: SystemTime = SystemTime::UNIX_EPOCH;
|
||||
let gtfs_file_name = prefs.gtfs_file_path()?;
|
||||
|
||||
// Obtain the GTFS zip's creation time.
|
||||
let metadata = fs::metadata(>fs_file_name);
|
||||
if metadata.is_ok() {
|
||||
modified_timestamp = metadata?.modified()?;
|
||||
}
|
||||
|
||||
let modified_seconds = modified_timestamp.duration_since(UNIX_EPOCH).unwrap().as_secs() as i64;
|
||||
let modified_header = format_common_utc(modified_seconds, time_format::DateFormat::HTTP).unwrap();
|
||||
|
||||
debug!("Using if-modified-since: {}", modified_header);
|
||||
|
||||
// request updates from the server if-modified-since last time
|
||||
let client = Client::builder()
|
||||
.timeout(Duration::from_secs(30))
|
||||
.connect_timeout(Duration::from_secs(5))
|
||||
.build()?;
|
||||
|
||||
let mut response = client
|
||||
.get(&prefs.gtfs_url)
|
||||
.header(reqwest::header::IF_MODIFIED_SINCE, modified_header)
|
||||
.send()
|
||||
.unwrap();
|
||||
|
||||
if response.status() == StatusCode::NOT_MODIFIED {
|
||||
debug!("GTFS data is still up-to-date");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if response.status() == StatusCode::OK {
|
||||
info!("Refreshing GTFS data");
|
||||
// Stream the response data into a temp file and swap them
|
||||
|
||||
let tmp_full_file_name = format!("{}.new", >fs_file_name);
|
||||
let mut tmp_file = fs::File::create(&tmp_full_file_name)?;
|
||||
|
||||
_ = response.copy_to(&mut tmp_file)?;
|
||||
drop(tmp_file);
|
||||
|
||||
if fs::exists(>fs_file_name)? {
|
||||
_ = fs::remove_file(>fs_file_name);
|
||||
}
|
||||
_ = fs::rename(&tmp_full_file_name, >fs_file_name);
|
||||
info!("GTFS data refreshed");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let errmsg = format!("GET on {} returned result code {}", prefs.gtfs_url, response.status());
|
||||
return Err(Error { _message: errmsg });
|
||||
}
|
||||
+74
-2
@@ -1,17 +1,89 @@
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use gtfs_structures::{Agency, Calendar, CalendarDate, RawStopTime, RawTrip, Route, Stop};
|
||||
use log::error;
|
||||
use serde::{Serialize, Deserialize};
|
||||
use zip::result::ZipError;
|
||||
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Error {
|
||||
pub(crate) _message: String,
|
||||
}
|
||||
|
||||
impl From<std::io::Error> for Error {
|
||||
fn from(value: std::io::Error) -> Self {
|
||||
return Error { _message: value.to_string() }
|
||||
}
|
||||
}
|
||||
|
||||
impl From<reqwest::Error> for Error {
|
||||
fn from(value: reqwest::Error) -> Self {
|
||||
return Error { _message: value.to_string() }
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ZipError> for Error {
|
||||
fn from(value: ZipError) -> Self {
|
||||
return Error { _message: value.to_string() }
|
||||
}
|
||||
}
|
||||
|
||||
impl From<serde_json::Error> for Error {
|
||||
fn from(value: serde_json::Error) -> Self {
|
||||
return Error { _message: value.to_string() }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// This is to store the preferences for the GTFS(-R) side of the code.
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Preferences {
|
||||
#[serde(rename = "routes")]
|
||||
pub route_numbers: HashSet<String>,
|
||||
|
||||
#[serde(rename = "stops")]
|
||||
pub stop_codes: HashSet<String>,
|
||||
|
||||
#[serde(rename = "data-folder")]
|
||||
pub data_folder: String,
|
||||
|
||||
#[serde(rename = "gtfs-url")]
|
||||
pub gtfs_url: String,
|
||||
|
||||
#[serde(rename = "realtime-url")]
|
||||
pub realtime_url: String,
|
||||
|
||||
#[serde(rename = "realtime-api-key")]
|
||||
pub realtime_api_key: String,
|
||||
|
||||
#[serde(rename = "refresh-seconds")]
|
||||
pub refresh_seconds: u64,
|
||||
}
|
||||
|
||||
// Utility functions
|
||||
impl Preferences {
|
||||
pub fn gtfs_file_name(&self) -> Result<String, Error> {
|
||||
let file_name_part = self.gtfs_url.split("/").last();
|
||||
if file_name_part.is_none() {
|
||||
error!("The config for gtfs-url is not a valid URL: {}", self.gtfs_url);
|
||||
return Err(Error {_message: String::from("Failed to refresh GTFS data")});
|
||||
}
|
||||
return Ok(String::from(file_name_part.unwrap()));
|
||||
}
|
||||
|
||||
pub fn gtfs_file_path(&self) -> Result<String, Error> {
|
||||
return Ok(format!("{}/{}", self.data_folder, self.gtfs_file_name()?));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
// The main GTFS struct. This is similar to (but not exactly) gtfs-structures::Gtfs because we don't need everything
|
||||
#[derive(Debug)]
|
||||
pub struct Gtfs {
|
||||
pub struct Gtfs<'a> {
|
||||
/// A copy of the preferences struct
|
||||
pub(crate) preferences: &'a Preferences,
|
||||
|
||||
/// All agencies. They can not be read by `agency_id`, as it is not a required field
|
||||
pub(crate) agencies: Vec<Agency>,
|
||||
/// All Calendar by `service_id`
|
||||
|
||||
+32
-22
@@ -1,15 +1,13 @@
|
||||
mod gtfs;
|
||||
mod renderer;
|
||||
use std::{collections::HashSet, ops::Add, process, thread::Builder, time::SystemTime};
|
||||
mod config;
|
||||
use std::{env, ops::Add, process, thread::Builder, time::SystemTime};
|
||||
use chrono::{DateTime, Duration, Local, NaiveTime};
|
||||
use log::{Metadata, Record, error, info};
|
||||
use sdl3::event::Event;
|
||||
use crate::{gtfs::structs::{Arrival, Gtfs}, renderer::structs::{DisplayData, DisplayEntry, Screen}};
|
||||
use sdl3::{event::Event};
|
||||
use crate::{config::load_config, gtfs::structs::{Arrival, Gtfs}, renderer::structs::{DisplayData, DisplayEntry, Screen}};
|
||||
|
||||
const SRC_FILE: &str = "/home/nahuel/Downloads/GTFS_Realtime.zip";
|
||||
const NUM_ARRIVALS: usize = 4;
|
||||
const UPDATE_INTERVAL_SECONDS: u64 = 62;
|
||||
|
||||
|
||||
// Custom Event to signal data refresh
|
||||
#[derive(Debug)]
|
||||
@@ -56,12 +54,15 @@ fn refresh_schedule<'a>(gtfs: &'a Gtfs, screen : &mut Screen<'a>) -> Option<Vec<
|
||||
|
||||
|
||||
fn main() {
|
||||
let args: Vec<String> = env::args().collect();
|
||||
|
||||
// Initialize logger
|
||||
static MY_LOGGER: MyLogger = MyLogger;
|
||||
|
||||
struct MyLogger;
|
||||
impl log::Log for MyLogger {
|
||||
fn enabled(&self, _metadata: &Metadata) -> bool {
|
||||
true
|
||||
return true;
|
||||
}
|
||||
|
||||
fn log(&self, record: &Record) {
|
||||
@@ -78,33 +79,42 @@ fn main() {
|
||||
print!("Error setting up the main logger:{:#?}", logger.err());
|
||||
process::exit(-1);
|
||||
}
|
||||
log::set_max_level(log::LevelFilter::Trace);
|
||||
|
||||
if args.contains(&String::from("--debug")) {
|
||||
log::set_max_level(log::LevelFilter::Trace);
|
||||
} else {
|
||||
log::set_max_level(log::LevelFilter::Warn);
|
||||
}
|
||||
|
||||
|
||||
let config_result = load_config(String::from("resources/dublinbus.yaml"));
|
||||
if config_result.is_err() {
|
||||
error!("Error loading the config file: {:#?}", config_result.err());
|
||||
process::exit(-1);
|
||||
}
|
||||
// Create preferences structures from config
|
||||
let gtfs_prefs = gtfs::structs::Preferences {
|
||||
route_numbers: HashSet::from([String::from("15A"), String::from("F1"), String::from("F2"), String::from("F3")]),
|
||||
stop_codes: HashSet::from([String::from("1114")])
|
||||
};
|
||||
|
||||
let screen_prefs = renderer::structs::Prefs {
|
||||
font_path: String::from("resources/jd_lcd_rounded/jd-lcd-rounded.ttf"),
|
||||
screen_width: 1920,
|
||||
screen_height: 720,
|
||||
};
|
||||
let config = config_result.unwrap();
|
||||
let gtfs_prefs = config.gtfs_prefs;
|
||||
let screen_prefs = config.screen_prefs;
|
||||
|
||||
// Init GTFS static info
|
||||
info!("Loading GTFS data...");
|
||||
let res = Gtfs::load(SRC_FILE, >fs_prefs);
|
||||
let res = Gtfs::load(>fs_prefs);
|
||||
|
||||
if let Err(e) = res {
|
||||
error!("Error loading GTFS data: {}", e);
|
||||
error!("Error loading GTFS data: {:#?}", e);
|
||||
process::exit(-1);
|
||||
}
|
||||
let gtfs = res.unwrap();
|
||||
|
||||
// Init screen
|
||||
info!("Initializing screen...");
|
||||
let mut screen = Screen::init(&screen_prefs);
|
||||
let screen_result = Screen::init(&screen_prefs);
|
||||
if let Err(e) = screen_result {
|
||||
error!("Error initializing video: {}", e.message);
|
||||
process::exit(-1);
|
||||
}
|
||||
let mut screen = screen_result.unwrap();
|
||||
info!("Startup done.");
|
||||
|
||||
// Register our custom event and obtain the event-related objects to interact with the event loop
|
||||
@@ -117,7 +127,7 @@ fn main() {
|
||||
.name("updater".to_string())
|
||||
.spawn(move || {
|
||||
loop {
|
||||
std::thread::sleep(std::time::Duration::new(UPDATE_INTERVAL_SECONDS,0));
|
||||
std::thread::sleep(std::time::Duration::new(gtfs_prefs.refresh_seconds,0));
|
||||
let event = RefreshDataEvent {};
|
||||
let send_result = event_sender.push_custom_event(event);
|
||||
if send_result.is_err() {
|
||||
|
||||
+26
-17
@@ -1,23 +1,24 @@
|
||||
pub mod structs;
|
||||
use std::{cmp::min};
|
||||
use log::{error, warn};
|
||||
use chrono::{Datelike, Local, Timelike};
|
||||
use log::{error, trace, warn};
|
||||
use sdl3::{Sdl, pixels::Color, rect::Rect};
|
||||
use structs::{Prefs, DisplayData};
|
||||
|
||||
use crate::renderer::structs::Screen;
|
||||
use crate::{config::Error, renderer::structs::Screen};
|
||||
|
||||
const LINE_COUNT: i32 = 5;
|
||||
const COLOR_LCD_AMBER : Color = Color::RGB(0xf4, 0xcb, 0x60);
|
||||
const COLOR_LCD_GREEN : Color = Color::RGB(0xb3, 0xff, 0x00);
|
||||
const COLOR_LCD_RED : Color = Color::RGB(0xff, 0x3a, 0x4a);
|
||||
const COLOR_BACKGROUND : Color = Color::RGB(0x0, 0x0, 0x0 );
|
||||
const COLOR_TEXT_BG : Color = Color::RGBA(0x0, 0x0, 0x0, 0x0);
|
||||
const _COLOR_TEXT_BG : Color = Color::RGBA(0x0, 0x0, 0x0, 0x0);
|
||||
const TEXT_SIZE: f32 = 160.0; // Size of the font in pixels
|
||||
|
||||
// Offsets of each part within a line
|
||||
const XOFFSET_ROUTE: u32 = 24;
|
||||
const XOFFSET_DESTINATION: u32 = 300;
|
||||
const XOFFSEET_TIME_LEFT: u32 = 1606;
|
||||
const XOFFSEET_TIME_LEFT: u32 = 1560;
|
||||
const INTER_LINE_OVERLAP: u32 = 15;
|
||||
|
||||
impl Screen<'_> {
|
||||
@@ -32,36 +33,44 @@ impl Screen<'_> {
|
||||
return COLOR_LCD_RED;
|
||||
}
|
||||
|
||||
fn format_due_for(&self, due_in: i32, departure_time: u32) -> String {
|
||||
if due_in < 60 {
|
||||
return String::from("due");
|
||||
fn format_due_for(&self, due_in_mins: i32, departure_time: u32) -> String {
|
||||
trace!("Due in mins: {:02}", due_in_mins);
|
||||
if due_in_mins <= 1 {
|
||||
return String::from("Due");
|
||||
}
|
||||
if due_in < 3600 {
|
||||
return ((due_in / 60) as i32).to_string() + "min";
|
||||
if due_in_mins < 60 {
|
||||
return due_in_mins.to_string() + " min";
|
||||
}
|
||||
return format!("{:02}:{:02}", (departure_time / 3600) as i32, ((departure_time % 3600) / 60) as i32);
|
||||
return format!("{:02}:{:02}", (departure_time / 3600) as i32, ((departure_time / 60) % 60) as i32);
|
||||
}
|
||||
|
||||
|
||||
pub fn update_information(&mut self, display_data: &DisplayData) {
|
||||
let local_time = Local::now();
|
||||
let seconds_since_midnight = local_time.num_seconds_from_midnight();
|
||||
|
||||
self.do_clear();
|
||||
|
||||
// Print status first
|
||||
self.color = COLOR_LCD_AMBER;
|
||||
if display_data.status.is_some() {
|
||||
// If the update has some information text, show it
|
||||
self.do_print_at(5, display_data.status.as_ref().unwrap(), 0);
|
||||
} else {
|
||||
// Display date and time otherwise
|
||||
self.do_print_at(5, &format!("TODO: DATE/TIME GOES HERE").to_string(), 0);
|
||||
self.do_print_at(5, &format!(" Current time: {:02}/{:02}/{:4} {:02}:{:02}",
|
||||
local_time.day(), local_time.month(), local_time.year(),
|
||||
local_time.hour(), local_time.minute()
|
||||
).to_string(), 0);
|
||||
}
|
||||
|
||||
// Then data lines from the bottom up
|
||||
// Then data lines from the bottom
|
||||
let num_arrivals: i32 = min(LINE_COUNT, display_data.lines.len() as i32);
|
||||
for index in 0..num_arrivals {
|
||||
let line: u32 = ((num_arrivals - 1) - index) as u32;
|
||||
// Compose a line of text with all the information
|
||||
let entry = display_data.lines.get(line as usize).unwrap();
|
||||
let due_in_mins = (entry.departure_time / 60) as i32;
|
||||
let due_in_mins = ((entry.departure_time - seconds_since_midnight) / 60) as i32;
|
||||
let due_color: Color = self.color_for(due_in_mins);
|
||||
let due_text = self.format_due_for(due_in_mins, entry.departure_time);
|
||||
|
||||
@@ -127,10 +136,10 @@ impl Screen<'_> {
|
||||
|
||||
/// Initialize video, allocate buffers and load fonts
|
||||
/// Based on https://github.com/vhspace/sdl3-rs/blob/master/examples/ttf-demo.rs
|
||||
pub fn init(prefs: &Prefs) -> Screen<'_> {
|
||||
pub fn init(prefs: &Prefs) -> Result<Screen<'_>, Error> {
|
||||
// Initialize the screen
|
||||
let sdl_context = sdl3::init().unwrap();
|
||||
let video_subsys = sdl_context.video().unwrap();
|
||||
let video_subsys = sdl_context.video()?;
|
||||
|
||||
let window = video_subsys
|
||||
.window("Dublin Bus", prefs.screen_width, prefs.screen_height)
|
||||
@@ -141,7 +150,7 @@ impl Screen<'_> {
|
||||
|
||||
// Load font
|
||||
let ttf_context = sdl3::ttf::init().unwrap();
|
||||
let font = ttf_context.load_font(&prefs.font_path, TEXT_SIZE).unwrap();
|
||||
let font = ttf_context.load_font(&prefs.font_path, TEXT_SIZE)?;
|
||||
|
||||
let mut screen: Screen = Screen {
|
||||
canvas: Box::new(window.into_canvas()),
|
||||
@@ -151,6 +160,6 @@ impl Screen<'_> {
|
||||
};
|
||||
|
||||
screen.clear();
|
||||
return screen;
|
||||
return Ok(screen);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
use sdl3::{Sdl, pixels::Color, render::Canvas, ttf::Font, video::Window};
|
||||
|
||||
use serde::{Serialize, Deserialize};
|
||||
|
||||
pub struct Screen<'a> {
|
||||
pub(crate) canvas: Box<Canvas<Window>>,
|
||||
@@ -8,9 +8,16 @@ pub struct Screen<'a> {
|
||||
pub(crate) context: Box<Sdl>
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Prefs {
|
||||
|
||||
#[serde(rename = "font-path")]
|
||||
pub font_path: String,
|
||||
|
||||
#[serde(rename = "width")]
|
||||
pub screen_width: u32,
|
||||
|
||||
#[serde(rename = "height")]
|
||||
pub screen_height: u32,
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user