Skip to content

Commit

Permalink
clean: Some minor changes for convinence
Browse files Browse the repository at this point in the history
  • Loading branch information
rexmagnusdavid committed May 15, 2024
1 parent e8d27e8 commit e72b1fc
Show file tree
Hide file tree
Showing 7 changed files with 50 additions and 60 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ The MTA's BusTime feeds require an API key, which you can obtain [here](http://w

## Configuration

The configuration file is located in `app/config.ts`. It is currently set to stops located near The Bronx High School of Science, but this file is meant to be edited to display any stop in the MTA network. Stops can be added (either subway or bus) with `StopConfig` objects, which is explained in depth below.
The configuration file is located in `config.ts`. It is currently set to stops located near The Bronx High School of Science, but this file is meant to be edited to display any stop in the MTA network. Stops can be added (either subway or bus) with `StopConfig` objects, which is explained in depth below.

### `stop_ids`

Expand Down
14 changes: 6 additions & 8 deletions app/components/Message.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,12 @@ export function Message(props: { routes: Record<string, Route>; name: string; he
<h1 className="line-clamp-4 text-pretty font-semibold 2xl:text-5xl 2xl:leading-tight">
{props.headers[props.index].split(/(\[.*?\])/).map((text) => {
if (text.length == 0) return;
if (text.substring(0, 1) == "[" && text.substring(text.length - 1) == "]") {
return (
<div className="mx-1 inline-flex -translate-y-1.5" key={Math.random()}>
<Bullet route={props.routes[text.substring(1, text.length - 1)]} size={42} />
</div>
);
}
return text;
if (text.substring(0, 1) != "[" || text.substring(text.length - 1) != "]") return text;
return (
<div className="mx-1 inline-flex -translate-y-1.5" key={Math.random()}>
<Bullet route={props.routes[text.substring(1, text.length - 1)]} size={42} />
</div>
);
})}
</h1>
</div>
Expand Down
65 changes: 25 additions & 40 deletions app/page.tsx
Original file line number Diff line number Diff line change
@@ -1,24 +1,22 @@
"use client";

import { Alert } from "@/types/Alert";
import { config } from "@/config";
import { Export } from "@/types/Export";
import { Import } from "@/types/Import";
import { Route } from "@/types/Route";
import { Stop } from "@/types/Stop";
import Image from "next/image";
import { useEffect, useState } from "react";
import { Bulletin } from "./components/Bulletin";
import { Countdown } from "./components/Countdown";
import { Message } from "./components/Message";
import { config } from "./config";

export default function Home() {
const [time, setTime] = useState<string>("");
const [status, setStatus] = useState(false);
const [importConfig, setImportConfig] = useState<Import>({
stops_realtime: {},
service_alerts_realtime: [],
routes_static: {},
});
const [serviceAlerts, setServiceAlerts] = useState<Array<string>>([]);
const [stops, setStops] = useState<Record<string, Stop>>({});
const [routes, setRoutes] = useState<Record<string, Route>>({});
const [headers, setHeaders] = useState<Array<string>>([]);
const [index, setIndex] = useState(0);

useEffect(() => {
Expand All @@ -28,37 +26,39 @@ export default function Home() {
setStatus(true);
console.log("Websocket opened.");

let exportConfig: Export = { subway: [], bus: [] };
const message: Export = { subway: [], bus: [] };

Object.values(config.subway).forEach((value) => {
exportConfig.subway.push(value.stop_ids);
message.subway.push(value.stop_ids);
});

Object.values(config.bus).forEach((value) => {
exportConfig.bus.push(value.stop_ids);
message.bus.push(value.stop_ids);
});

ws.send(JSON.stringify(exportConfig));
console.log(message);

ws.send(JSON.stringify(message));
};

ws.onmessage = (event) => {
setStatus(true);
console.log("Message recieved.");

const message: Import = JSON.parse(event.data);
setImportConfig(message);
setStops(message.stops_realtime);
setRoutes(message.routes_static);

const headers: Array<string> = [];
const serviceData: Array<Alert> = message.service_alerts_realtime;
serviceData
message.service_alerts_realtime
.slice()
.reverse()
.forEach((alert) => {
if (headers.indexOf(alert.header_text) != -1) return;
if (alert.sort_order < 22) return;
headers.push(alert.header_text);
});
setServiceAlerts(headers);
setHeaders(headers);
headers.length > 0 ? setIndex((i) => ((i % headers.length) + headers.length) % headers.length) : setIndex(0);
};

Expand Down Expand Up @@ -87,17 +87,15 @@ export default function Home() {
}),
);

if (serviceAlerts.length > 0) {
setIndex((i) => (((i + 1) % serviceAlerts.length) + serviceAlerts.length) % serviceAlerts.length);
} else {
setIndex(0);
}
headers.length > 0
? setIndex((i) => (((i + 1) % headers.length) + headers.length) % headers.length)
: setIndex(0);
}, 5000);

return () => {
clearInterval(loop);
};
}, [serviceAlerts.length]);
});

return (
<div className="flex min-h-screen flex-col">
Expand All @@ -108,24 +106,15 @@ export default function Home() {
return (
<Countdown
key={Math.random()}
stop={
importConfig.stops_realtime[value.stop_ids[0]]
? importConfig.stops_realtime[value.stop_ids[0]]
: { name: "", trips: [], destinations: {} }
}
stop={stops[value.stop_ids[0]] ? stops[value.stop_ids[0]] : { name: "", trips: [], destinations: {} }}
walk_time={value.walk_time}
routes={importConfig.routes_static}
routes={routes}
></Countdown>
);
})}
</div>
<div className="flex h-full flex-col gap-2 rounded-xl bg-black p-2">
<Message
name={"Service Alerts"}
headers={serviceAlerts}
routes={importConfig.routes_static}
index={index}
/>
<Message name={"Service Alerts"} headers={headers} routes={routes} index={index} />
</div>
</div>
<div className="flex min-h-full basis-1/3 flex-col gap-4">
Expand All @@ -134,12 +123,8 @@ export default function Home() {
return (
<Bulletin
key={Math.random()}
stop={
importConfig.stops_realtime[value.stop_ids[0]]
? importConfig.stops_realtime[value.stop_ids[0]]
: { name: "", trips: [], destinations: {} }
}
routes={importConfig.routes_static}
stop={stops[value.stop_ids[0]] ? stops[value.stop_ids[0]] : { name: "", trips: [], destinations: {} }}
routes={routes}
walk_time={value.walk_time}
></Bulletin>
);
Expand Down
File renamed without changes.
4 changes: 0 additions & 4 deletions src/import.rs → src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,6 @@ pub struct Import {
}

impl Import {
pub fn new(subway: Vec<Vec<String>>, bus: Vec<Vec<String>>) -> Self {
Self { subway, bus }
}

pub fn get_subway_handlers(&self, feed_data: Arc<RwLock<FeedHandler>>) -> Vec<SubwayStopHandler> {
self
.subway
Expand Down
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ use ts_rs::TS;
use serde::{Deserialize, Serialize};

pub mod bus_stop_handler;
pub mod config;
pub mod feed_handler;
pub mod import;
pub mod mercury_structs;
pub mod service_alert_handler;
pub mod siri_structs;
Expand Down
23 changes: 17 additions & 6 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ use std::sync::{Arc, RwLock};
use std::thread;
use std::time::Duration;

use transit_board::config::Import;
use transit_board::feed_handler::FeedHandler;
use transit_board::import::Import;
use transit_board::{Export, Route, Stop};
use tungstenite::protocol::frame::coding::CloseCode;
use tungstenite::{protocol::CloseFrame, Message};
Expand All @@ -27,17 +27,28 @@ fn main() {
let _spawn = thread::spawn(move || {
let stream = match stream {
Ok(stream) => stream,
Err(_) => return, // If stream fails to connect, don't crash
Err(_) => {
return;
} // If stream fails to connect, don't crash
};
let mut ws = match tungstenite::accept(stream) {
Ok(ws) => ws,
Err(_) => return, // if not a websocket, don't crash
Err(_) => {
return;
} // If not a websocket, don't crash
};

let import: Result<Import, serde_json::Error> = match ws.read() {
Ok(c) => serde_json::from_str(c.to_text().unwrap_or("")),
Err(_) => Ok(Import::new(Vec::new(), Vec::new())),
Ok(a) => serde_json::from_str(a.to_text().unwrap_or("")),
Err(_) => {
_ = ws.close(Some(CloseFrame {
code: CloseCode::Error,
reason: "The config that was sent is malformed".into(),
}));
return;
}
};

let import: Import = match import {
Ok(a) => a,
Err(_) => {
Expand All @@ -46,7 +57,7 @@ fn main() {
reason: "The config that was sent is malformed".into(),
}));
return;
} // Just close connection on incorrect data
}
};

let data = Arc::new(RwLock::new(FeedHandler::default()));
Expand Down

0 comments on commit e72b1fc

Please sign in to comment.