Skip to content

Commit

Permalink
Merge pull request #1 from augustin64/horaires-js
Browse files Browse the repository at this point in the history
Horaires js
  • Loading branch information
augustin64 authored Aug 8, 2021
2 parents d3998b4 + a043071 commit 254fead
Show file tree
Hide file tree
Showing 8 changed files with 169 additions and 110 deletions.
6 changes: 3 additions & 3 deletions modules/schedules.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,10 @@
home = str(Path.home())
configpath = PurePath(home).joinpath('.config/reflect-o-bus/')

configParser = configparser.ConfigParser()

if not os.path.isfile(configpath.joinpath('config')) :
os.makedirs(configpath, exist_ok=True)
shutil.copy('./examples/default',configpath.joinpath('config'))


class Configuration():
def __init__(self):
configParser.read(configpath.joinpath('config'))
Expand Down Expand Up @@ -138,6 +135,9 @@ def get_schedules(config):

class Schedules():
def __init__(self):
global configParser
configParser = configparser.ConfigParser()

self.config = Configuration()
self.config.update()
print(" * Config Initialized")
Expand Down
119 changes: 63 additions & 56 deletions reflectobus.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,16 @@
# On initialise le serveur Flask
app = Flask(__name__)

def get_ip() :
localip = "127.0.0.1"
if not offline: # We open a socket to get our ip on the local network
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
localip = (s.getsockname()[0])
s.close()

return localip

def fake_schedules(datatype="object"):
# Générateur de fausses lignes de bus, gagnerait à être amélioré

Expand Down Expand Up @@ -146,26 +156,60 @@ def get_horaires():
data['config'] = {}

data['config']['refresh_time'] = configParser['ADVANCED']['refresh_time']
data['config']['background_color'] = configParser['ADVANCED']['background_color']
data['config']['font_size'] = eval(configParser['ADVANCED']['font_size'])
data['config']['hide_category'] = eval(configParser['ADVANCED']['hide_category'])

if configParser['ADVANCED']['background_type'] == "image" :
data['config']['background_url'] = configParser['ADVANCED']['background_url']
data['config']['pass_colors'] = eval(configParser['ADVANCED']['pass_colors'])
data['config']['lines_color'] = configParser['ADVANCED']['lines_color']
data['config']['localip'] = get_ip()

if not offline :
global config_changed
global schedules_object
if config_changed :
schedules_object = schedules.Schedules()
config_changed = False
data['schedule'] = schedules_object.__main__()
print(data['schedule'])
return (data)
schedules_data = schedules_object.__main__()
data["schedule"] = {}
print(schedules_data.keys())

for category in schedules_data.keys() :
data['schedule'][category] = []
for hour in schedules_data[category] :
data["schedule"][category].append({
'name':hour[0].name,
'id':hour[0].id,
'Carrier':hour[0].Carrier,
'Operator':hour[0].Operator,
'PublicCode':hour[0].PublicCode,
'TypeOfLine':hour[0].TypeOfLine,
'VehicleType':hour[0].VehicleType,
'night':hour[0].night,
'lepiloteId':hour[0].lepiloteId,
'color':hour[0].color,
'sqliType':hour[0].sqliType,
'hour':hour[1],
'isRealTime':hour[2]
})


return ({"data":data, "content":"Horaires"})

else:
data['schedule'] = fake_schedules(datatype="JSON")
return ({"data":data, "content":None})
return ({"data":data, "content":"Horaires"})

def get_look():
data = {}

data['background_color'] = configParser['ADVANCED']['background_color']
data['font_size'] = eval(configParser['ADVANCED']['font_size'])
data['refresh_time'] = eval(configParser['ADVANCED']['refresh_time'])

if configParser['ADVANCED']['background_type'] == "image" :
data['background_url'] = configParser['ADVANCED']['background_url']

return ({"data":data,"content":"look"})



def set_wlan(data):
# NotImplementedError
Expand Down Expand Up @@ -200,67 +244,25 @@ def index():

@app.route("/boot")
def boot():
localip = "127.0.0.1"
if not offline: # We open a socket to get our ip on the local network
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
localip = (s.getsockname()[0])
s.close()

data = {"version":ver,
"rtm_version":rtm_ver,
"boot_time":configParser['ADVANCED']['boot_time'],
"local_ip":localip
"local_ip":get_ip()
}
data['background_color'] = configParser['ADVANCED']['background_color']
return render_template('boot.html', data=data)

@app.route("/horaires")
def horaires():
data={}
# fetching parsed data

if not offline :
global config_changed
global schedules_object
if config_changed :
schedules_object = schedules.Schedules()
config_changed = False
data['schedule'] = schedules_object.__main__()

else : # We create fake Lines to be able to test the app when offline
data['schedule'] = fake_schedules(datatype="object")

data['refresh_time'] = configParser['ADVANCED']['refresh_time']
data['background_color'] = configParser['ADVANCED']['background_color']
data['font_size'] = eval(configParser['ADVANCED']['font_size'])
data['hide_category'] = eval(configParser['ADVANCED']['hide_category'])

if configParser['ADVANCED']['background_type'] == "image" :
data['background_url'] = configParser['ADVANCED']['background_url']

data['total_schedules'] = 0
for i in data['schedule'].keys():
data['total_schedules'] += len(data['schedule'][i])

if data['total_schedules'] == 0 :
localip = "127.0.0.1"
if not offline:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
localip = (s.getsockname()[0])
s.close()

data['localip'] = localip

return render_template('horaires.html',data=data)
return render_template('horaires.html')

# not in use yet
@app.route('/get')
def get():
actions = {
"config":get_config,
"horaires":get_horaires,
"look":get_look,
}
content = request.args.get("content")
if content in actions.keys():
Expand Down Expand Up @@ -298,7 +300,8 @@ def get_logs():
with zipfile.ZipFile(data, mode='w') as zf:
for file in Path(logs_path).rglob('*'): # Cette solution supprime
zf.write(file, file.name) # la possibilité d'utiliser des dossiers dans
data.seek(0) # les logs, mais ce n'est pas quelque chose de nécessaire
data.seek(0) # les logs, car elle prend tous les fichiers
# sans différencier leur chemin d'accès

return send_file(
data,
Expand Down Expand Up @@ -343,7 +346,11 @@ def view_logs():
@app.errorhandler(500)
def server_error_handler(e):
print("error:",e)
return render_template('error_500.html',data=e)
print(request.base_url)
if request.is_json or request.base_url.split('/')[-1] == "get":
return(e)
else:
return render_template('error_500.html',data=e)


# Development option to run tests without internet access
Expand Down
93 changes: 91 additions & 2 deletions static/js/horaires.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,97 @@
var onLoad = function () {
var getSchedules = function (fontSize=1) {
getJSON("/get?content=horaires", function(data){
data = data["data"];
// Variables initialisation dependingnon the request content
var numberOfCategories = Object.keys( data["schedule"] ).length;
var numberOfSchedules = 0;
for (var category of Object.keys( data["schedule"] ) ) {
numberOfSchedules += data["schedule"][category].length;
}
if (numberOfSchedules == 0) {
// If no schedules are available, we set te text to this sentence
document.body.innerHTML = "<center>Aucun horaire en temps réel n'est disponible,<br/>Configurez cela à l'URL suivante : <a href=\"http://"+data["config"]["localip"]+":5000\">http://"+data["config"]["localip"]+":5000</a></center>";
} else {
section = "<section style='padding-left:5%;'>"
for (var category of Object.keys( data["schedule"] ) ) {
// We set the beginning of the section
section += "<div class='schedule' style='width:"+90/numberOfCategories+"%;'>"
if ( ! data["config"]["hide_category"]){
// If the variable hide_category is set to
// true, we don't display the title
section += "<h3>"+category+"</h3>"
}
if ( data["schedule"][category].length > 0 ) {
for (var schedule of data["schedule"][category]) {
section += "<div id='squircle' style='background-color: "
if (data['config']['pass_colors']) {
// We set the squircle color to
// the parameters
section += schedule["color"]
} else {
section += data['config']['lines_color']
}
section += ";'>"
section += "<p>"+schedule["PublicCode"]+"</p></div>";
section += "<span style='font-size:"+fontSize+"rem;' class='time";
if ( schedule["isRealTime"] ) {
section += " realtime"
}
if (schedule['hour'] == 0) {
section += "'>En Vue</span>"
} else {
section += "'>"+schedule["hour"]+"min</span>"
}
}
} else {
section += "Il n'y a pas d'horaires disponibles pour cette catégorie"
}
section += "</div>"
}
section += "</select>"
document.body.innerHTML = section
}
}, error_handler=function(err){
document.body.innerHTML=err;
console.log(err);
setTimeout(() => {document.location=document.location},1000)
});
// On remplace les horaires "0min" par "En Vue"
for (var i of document.getElementsByClassName('time')) {
if (i.innerHTML == "0min") { i.innerHTML = "En Vue"}
}
}

onLoad()
var loadLook = function() {
getJSON("/get?content=look", function(data){
data = data["data"];

if (typeof data["background_url"] != "undefined") {
document.body.style.background = "url(/static/walls/"+data["background_url"]+")";
} else {
document.body.style.background = "url(/not_an_image.png)"
}
document.body.style.backgroundColor = data["background_color"];

for (element of document.getElementsByClassName("time")) {
element.style.fontSize = data["font_size"]+"rem";
}
if (window.cpt == 3) {
getSchedules(fontSize=data["font_size"]);
window.cpt = 0;
} else {
window.cpt += 1;
}
setTimeout(() => { loadLook("loadLook"); }, data["refresh_time"]/3 );
});
}

var onLoad = function() {
getSchedules();
loadLook()
}

window.cpt = 0;
onLoad()


// N'affiche pas Internal Server Error si c'est le cas
4 changes: 2 additions & 2 deletions static/js/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,11 @@ function sendJSON(data,callback){
xhr.send(data);
}

var getJSON = function(url, callback) {
var getJSON = function(url, callback, error_handler=function(err){throw err}) {
fetch(url)
.then(res => res.json())
.then((out) => {
callback(out);
})
.catch(err => { throw err });
.catch(err => { error_handler(err) });
}
2 changes: 1 addition & 1 deletion static/styles/main.css
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
line-height:3rem;
width:3rem;
height:3rem;
font-size:2rem;
font-size:1.6rem;
transition:color .333s;
}
#squircle::after {
Expand Down
5 changes: 5 additions & 0 deletions static/styles/mirror.css
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,9 @@
background-size: 0.8125rem;
display: inline-block;
padding-right: 0.8125rem;
background-image: url("/static/src/realtime.gif");
}

.time {
font-size:1rem;
}
2 changes: 1 addition & 1 deletion templates/config.html
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,6 @@

</div>
Durée de l'écran de démarrage <input id="boot_time">(ms)<br/>
<button onclick="getWifi()">Changer les paramètres sans fil</button>
<div>
Cacher les noms de catégories:
<select id="hide_category">
Expand All @@ -67,6 +66,7 @@
</select><br/>
Taille d'affichage des horaires <input id="font_size"><br/>
</div>
<button onclick="getWifi()">Changer les paramètres sans fil</button>
</div>
</section>
<button onclick="sendConfig()">Mettre à jour la configuration</button>
Expand Down
Loading

0 comments on commit 254fead

Please # to comment.