Dateien hochladen nach „REST“

Service Files und Aktueller Stand REST
main
Thomas Hassenstein 2023-06-09 15:02:25 +02:00
parent e536afb33a
commit 33a7e1bd7d
5 changed files with 175 additions and 79 deletions

View File

@ -1,6 +1,7 @@
import os import os
import time import time
import json import json
from flask import jsonify
from smbus import SMBus from smbus import SMBus
from StartUpTest import StartUPTest from StartUpTest import StartUPTest
from TotOnline import TotOnline from TotOnline import TotOnline
@ -135,13 +136,15 @@ def analyze_data(num_numbers, bits_per_number, startup):
# Remove any empty strings # Remove any empty strings
hex_numbers = [hex_num for hex_num in hex_numbers if hex_num] hex_numbers = [hex_num for hex_num in hex_numbers if hex_num]
# Create the JSON object with the specified structure # Create the JSON object with the specified structure
data = {'randomNumbers': hex_numbers} #data = {'randomNumbers': hex_numbers}
data = hex_numbers
# Delete the temporary files # Delete the temporary files
os.unlink(filename) os.unlink(filename)
os.unlink(binary_filename) os.unlink(binary_filename)
os.unlink(hex_filename) os.unlink(hex_filename)
# Return the JSON object using Flask's jsonify function # Return the JSON object using Flask's jsonify function
return jsonify(data) #return jsonify(data)
return json.dumps(data)
else: else:
os.unlink(filename) os.unlink(filename)
@ -150,7 +153,9 @@ def analyze_data(num_numbers, bits_per_number, startup):
return False return False
# Teste den Code # Teste den Code
#result = analyze_data(50, 2560, startup=False)
#result = analyze_data(8, 8, startup=True) #result = analyze_data(8, 8, startup=True)
#print(result) #print(result)
#result = analyze_data(1, 7200000, startup=False)
#result = analyze_data(10, 100, startup=False)
#print(result)

View File

@ -4,29 +4,22 @@ import time
from flask import Flask, request, jsonify, session from flask import Flask, request, jsonify, session
from I2C_Function import analyze_data, read_data from I2C_Function import analyze_data, read_data
from flask_cors import CORS from flask_cors import CORS
from flask_session import Session
app = Flask(__name__) app = Flask(__name__)
app.config.from_pyfile('config.py')
Session(app)
CORS(app) CORS(app)
initialized = False initialized = False
@app.route('/trng/randomNum/init', methods=['GET']) @app.route('/trng/randomNum/init', methods=['GET'])
def initialize_generator(): def initialize_generator():
#quantity = 1
#bits = 1
#startup = True # Boolean-Wert für die Initialisierung
global initialized # Zugriff auf die globale Variable global initialized # Zugriff auf die globale Variable
#result = analyze_data(int(quantity), int(bits), startup=true) #parameter 1 und 2 sind default values für Tests
result = analyze_data(int(1), int(1), startup=True) result = analyze_data(int(1), int(1), startup=True)
#session['initialized'] = True
if result is True: if result is True:
initialized = True initialized = True
return jsonify({'error': 'successful operation; random number generator is ready and random numbers can be requested'}), 200 return jsonify({'message': 'successful operation; random number generator is ready and random numbers can be requested'}), 200
else: else:
return jsonify({'error': 'Unable to initialize the random number generator within a timeout of 60 seconds.'}), 555 return jsonify({'error': 'Unable to initialize the random number generator within a timeout of 60 seconds.'}), 555
@ -47,18 +40,13 @@ def get_random_numbers():
if not initialized: if not initialized:
return jsonify({'error': 'system not ready; try init'}), 432 return jsonify({'error': 'system not ready; try init'}), 432
#if 'initialized' not in session or not session['initialized']: random_numbers = analyze_data(int(quantity), int(bits), startup=False)
#return jsonify({'error': 'system not ready; try init'}), 432
#if 'initialized' not in session or not session['initialized', 'false']: if random_numbers is False:
#return jsonify({'error': 'system not ready; try init'}), 432
filename = analyze_data(int(quantity), int(bits), startup=False)
if filename is False:
return jsonify({'error': 'Unable to generate random numbers.'}), 500 return jsonify({'error': 'Unable to generate random numbers.'}), 500
if filename: if random_numbers:
return filename, 200 data = {'randomNumbers': random_numbers} # Erstellen des Datenobjekts mit dem JSON-String
return jsonify(data), 200
else: else:
return jsonify({'error': 'Unable to generate random numbers.'}), 500 return jsonify({'error': 'Unable to generate random numbers.'}), 500
@ -67,20 +55,22 @@ def shutdown_generator():
global initialized # Zugriff auf die globale Variable global initialized # Zugriff auf die globale Variable
initialized = False # Setze den Initialisierungsstatus zurück initialized = False # Setze den Initialisierungsstatus zurück
#session['initialized'] = False
# Beispielantwort # Beispielantwort
return jsonify({'message': 'Generator shutdown successfully.'}), 200 return jsonify({'message': "successful operation; random number generator has been set to 'standby mode'"}), 200
if __name__ == '__main__': if __name__ == '__main__':
# Pfade zu den SSL-Zertifikat- und Schlüsseldateien # Pfade zu den SSL-Zertifikat- und Schlüsseldateien
#cert_path = '/etc/nginx/ssl/server.crt'
#key_path = '/etc/nginx/ssl/server.key'
cert_path = '/etc/nginx/ssl/cert-gmtrom.pem' cert_path = '/etc/nginx/ssl/cert-gmtrom.pem'
key_path = '/etc/nginx/ssl/cert-gmtrom-key.pem' key_path = '/etc/nginx/ssl/cert-gmtrom-key.pem'
#alte Zertifikate self signed
#cert_path = '/etc/nginx/ssl/server.crt'
#key_path = '/etc/nginx/ssl/server.key'
# Starte die Flask-Anwendung mit SSL-Konfiguration # Starte die Flask-Anwendung mit SSL-Konfiguration
#app.run(host='172.16.78.57', port=5000, ssl_context=(cert_path, key_path))
app.run(host='0.0.0.0', ssl_context=(cert_path, key_path)) app.run(host='0.0.0.0', ssl_context=(cert_path, key_path))
#app.run(host='172.16.78.57', port=5000, ssl_context=(cert_path, key_path))
#app.run(host='0.0.0.0', ssl_context=adhoc) #app.run(host='0.0.0.0', ssl_context=adhoc)
#app.run(ssl_context=(cert_path, key_path)) #app.run(ssl_context=(cert_path, key_path))

View File

@ -0,0 +1,14 @@
[Unit]
Description=Flask App Service
After=network.target
[Service]
ExecStart=/usr/bin/python /var/www/html/app.py
WorkingDirectory=/var/www/html
StandardOutput=syslog
StandardError=syslog
Restart=always
User=adminadmin
[Install]
WantedBy=multi-user.target

View File

@ -3,7 +3,7 @@
<head> <head>
<title>GMTROM - True Random Number Generator</title> <title>GMTROM - True Random Number Generator</title>
<link rel="stylesheet" type="text/css" href="style.css"> <link rel="stylesheet" type="text/css" href="style.css">
<link rel="icon" type="image/png" href="logomiddle.png"> <link rel="icon" type="image/png href="logomiddle.png">
</head> </head>
<body> <body>
<img src="logo.png" alt="Logo" class="logo"> <img src="logo.png" alt="Logo" class="logo">
@ -14,8 +14,8 @@
<input type="number" id="quantity" name="quantity"><br><br> <input type="number" id="quantity" name="quantity"><br><br>
<label for="bits">Number of Bits per Random Number:</label> <label for="bits">Number of Bits per Random Number:</label>
<input type="number" id="bits" name="bits"><br><br> <input type="number" id="bits" name="bits"><br><br>
<input type="submit" value="Generate" id="generateButton"> <input type="button" value="Generate" id="generateButton">
<input type="submit" value="Shutdown" id="shutdownButton"> <input type="button" value="Shutdown" id="shutdownButton">
</form> </form>
<div id="status"></div> <div id="status"></div>
@ -23,23 +23,22 @@
<script> <script>
document.getElementById('initButton').addEventListener('click', function() { document.getElementById('initButton').addEventListener('click', function() {
fetch('https://172.16.78.57:5000/trng/randomNum/init') fetch('https://172.16.78.57:5000/trng/randomNum/init')
.then(response => { .then(response => {
document.getElementById('status').innerText = 'Status: ' + response.status; document.getElementById('status').innerText = 'Status: ' + response.status;
if (response.status === 200) { if (response.status === 200) {
console.log('Initialisierung erfolgreich'); document.getElementById('result').innerText = 'Successful operation; random number generator has been set to "standby mode".';
} else { console.log('Initialisierung erfolgreich');
console.log('Fehler beim Initialisieren'); } else {
} console.log('Fehler beim Initialisieren');
}) }
.catch(error => { })
console.error('Fehler beim Initialisieren:', error); .catch(error => {
}); console.error('Fehler beim Initialisieren:', error);
}); });
});
document.getElementById('generateButton').addEventListener('click', function(event) { document.getElementById('generateButton').addEventListener('click', function(event) {
event.preventDefault(); // Verhindert das Absenden des Formulars
var quantity = document.getElementById('quantity').value; var quantity = document.getElementById('quantity').value;
var bits = document.getElementById('bits').value; var bits = document.getElementById('bits').value;
@ -55,28 +54,101 @@
}) })
.then(data => { .then(data => {
var resultDiv = document.getElementById('result'); var resultDiv = document.getElementById('result');
resultDiv.innerHTML = ''; // Clear previous results
var table = document.createElement('table');
table.classList.add('table');
var thead = document.createElement('thead');
var tbody = document.createElement('tbody');
var trHead = document.createElement('tr');
var thNr = document.createElement('th');
var thCopy = document.createElement('th');
var thRandom = document.createElement('th');
var copyAllButton = document.createElement('button');
thNr.textContent = 'ID';
thCopy.textContent = ' ';
thRandom.textContent = 'Random Number';
trHead.appendChild(thNr);
trHead.appendChild(thCopy);
trHead.appendChild(thRandom);
thead.appendChild(trHead);
table.appendChild(thead);
var hexNumbers = JSON.parse(data.randomNumbers); var hexNumbers = JSON.parse(data.randomNumbers);
resultDiv.innerText = hexNumbers.join(', '); for (var i = 0; i < hexNumbers.length; i++) {
var tr = document.createElement('tr');
var tdNr = document.createElement('td');
var tdCopy = document.createElement('td');
var tdRandom = document.createElement('td');
var copyButton = document.createElement('button');
tdNr.textContent = (i + 1).toString();
tdRandom.textContent = hexNumbers[i];
copyButton.textContent = 'Copy';
copyButton.classList.add('copy-button');
copyButton.addEventListener('click', function() {
copyToClipboard(this.parentElement.nextElementSibling.textContent);
});
tdCopy.appendChild(copyButton);
tr.appendChild(tdNr);
tr.appendChild(tdCopy);
tr.appendChild(tdRandom);
tbody.appendChild(tr);
}
table.appendChild(tbody);
resultDiv.appendChild(table);
copyAllButton.textContent = 'Copy all';
copyAllButton.classList.add('copy-button');
copyAllButton.addEventListener('click', function() {
var allHexNumbers = hexNumbers.join(', ');
copyToClipboard(allHexNumbers);
});
resultDiv.insertBefore(copyAllButton, table);
}) })
.catch(error => { .catch(error => {
console.error('Fehler beim Abrufen der Daten:', error); console.error('Fehler beim Abrufen der Daten:', error);
}); });
}); });
document.getElementById('shutdownButton').addEventListener('click', function() { function copyToClipboard(text) {
fetch('https://172.16.78.57:5000/trng/randomNum/shutdown') var textArea = document.createElement('textarea');
.then(response => { textArea.value = text;
document.getElementById('status').innerText = 'Status: ' + response.status; document.body.appendChild(textArea);
if (response.status === 200) { textArea.select();
console.log('Shutdown erfolgreich'); document.execCommand('copy');
} else { document.body.removeChild(textArea);
console.log('Fehler beim Shutdown');
} // Anzeigen eines Popups zur Bestätigung der Kopie
}) window.alert('Der Text wurde in die Zwischenablage kopiert!');
.catch(error => { }
console.error('Fehler beim Shutdown:', error);
}); document.getElementById('shutdownButton').addEventListener('click', function() {
}); fetch('https://172.16.78.57:5000/trng/randomNum/shutdown')
.then(response => {
document.getElementById('status').innerText = 'Status: ' + response.status;
if (response.status === 200) {
document.getElementById('result').innerText = 'Successful operation; random number generator has been shut down.';
console.log('Shutdown erfolgreich');
//document.getElementById('quantity').value = ''; // Textfeld "Quantity" zurücksetzen
//document.getElementById('bits').value = ''; // Textfeld "Bits" zurücksetzen
//document.getElementById('status').innerText = ''; // Element "status" zurücksetzen
//document.getElementById('result').innerText = ''; // Element "result" zurücksetzen
} else {
console.log('Fehler beim Shutdown');
}
})
.catch(error => {
console.error('Fehler beim Shutdown:', error);
});
});
</script> </script>
</body> </body>
</html> </html>

15
REST/nginx.service 100644
View File

@ -0,0 +1,15 @@
[Unit]
Description=Nginx HTTP server
After=network.target
[Service]
ExecStart=/usr/sbin/nginx -g "daemon off;"
ExecReload=/usr/sbin/nginx -s reload
ExecStop=/usr/sbin/nginx -s stop
Restart=on-failure
KillMode=process
PrivateTmp=true
[Install]
WantedBy=multi-user.target