parent
2986004b88
commit
e536afb33a
|
@ -0,0 +1,156 @@
|
||||||
|
import os
|
||||||
|
import time
|
||||||
|
import json
|
||||||
|
from smbus import SMBus
|
||||||
|
from StartUpTest import StartUPTest
|
||||||
|
from TotOnline import TotOnline
|
||||||
|
|
||||||
|
def read_data(num_numbers, bits_per_number):
|
||||||
|
addr = 0x8
|
||||||
|
bus = SMBus(1)
|
||||||
|
|
||||||
|
# Calculate the total number of bytes required to accommodate the desired number of bits
|
||||||
|
total_bytes = (num_numbers * bits_per_number + 7) // 8
|
||||||
|
|
||||||
|
# Define the filename
|
||||||
|
filename = f'{num_numbers}numbers_{bits_per_number}bits.bin'
|
||||||
|
|
||||||
|
with open(filename, 'wb') as file:
|
||||||
|
bytes_received = 0
|
||||||
|
while bytes_received < total_bytes:
|
||||||
|
# Read a byte from the serial port
|
||||||
|
data = bus.read_byte(addr)
|
||||||
|
file.write(bytes([data]))
|
||||||
|
bytes_received += 1
|
||||||
|
time.sleep(0.0000001)
|
||||||
|
|
||||||
|
return filename
|
||||||
|
|
||||||
|
def convert_to_hex(binary_filename, num_numbers, bits_per_number):
|
||||||
|
with open(binary_filename, 'r') as f:
|
||||||
|
# Read the contents of the file
|
||||||
|
binary_content = f.read()
|
||||||
|
|
||||||
|
# Calculate the number of bits per chunk
|
||||||
|
bits_per_chunk = len(binary_content) // num_numbers
|
||||||
|
|
||||||
|
# Divide the binary content into equal chunks
|
||||||
|
binary_chunks = [binary_content[i * bits_per_chunk:(i + 1) * bits_per_chunk] for i in range(num_numbers)]
|
||||||
|
|
||||||
|
# Calculate the number of hexadecimal digits per chunk
|
||||||
|
hex_digits_per_chunk = (bits_per_chunk + 3) // 4 # Round up to the nearest integer
|
||||||
|
|
||||||
|
# Convert each binary chunk to a hexadecimal string with leading zeros
|
||||||
|
hex_chunks = [format(int(chunk, 2), f'0{hex_digits_per_chunk}X') for chunk in binary_chunks]
|
||||||
|
|
||||||
|
# Write the hex chunks to the file with separators and newlines
|
||||||
|
hex_filename = f'{num_numbers}numbers_{bits_per_number}bits.txt'
|
||||||
|
with open(hex_filename, 'w') as f:
|
||||||
|
for i in range(num_numbers):
|
||||||
|
hex_number = hex_chunks[i]
|
||||||
|
# write the separator between numbers except for the last one
|
||||||
|
if i != num_numbers - 1:
|
||||||
|
hex_number += ';'
|
||||||
|
f.write(hex_number)
|
||||||
|
|
||||||
|
return hex_filename
|
||||||
|
|
||||||
|
|
||||||
|
def convert_to_binary(filename, num_numbers, bits_per_number):
|
||||||
|
with open(filename, 'rb') as f:
|
||||||
|
# Read the contents of the file as bytes
|
||||||
|
content = f.read()
|
||||||
|
|
||||||
|
# Convert the bytes to a string of binary digits
|
||||||
|
binary_str = ''.join(format(byte, '08b') for byte in content)
|
||||||
|
|
||||||
|
# Truncate the binary string to the desired length
|
||||||
|
truncated_binary_str = binary_str[:num_numbers * bits_per_number]
|
||||||
|
|
||||||
|
# Write the truncated binary string back to the file with separators
|
||||||
|
binary_filename = f'{num_numbers}numbers_{bits_per_number}bits_binary.txt'
|
||||||
|
with open(binary_filename, 'w') as f:
|
||||||
|
for i in range(0, len(truncated_binary_str), bits_per_number):
|
||||||
|
binary_number = truncated_binary_str[i:i+bits_per_number]
|
||||||
|
f.write(binary_number)
|
||||||
|
|
||||||
|
return binary_filename
|
||||||
|
|
||||||
|
|
||||||
|
def process_data_in_chunks(data, chunk_size=1000000):
|
||||||
|
chunks = [data[i:i+chunk_size] for i in range(0, len(data), chunk_size)]
|
||||||
|
return chunks
|
||||||
|
|
||||||
|
def perform_startup_tests(filename):
|
||||||
|
with open(filename, 'rb') as f:
|
||||||
|
# Read the contents of the file as bytes
|
||||||
|
content = f.read()
|
||||||
|
|
||||||
|
#print("Run all StartUPTests")
|
||||||
|
binary_chunks = process_data_in_chunks(content)
|
||||||
|
first_chunk = binary_chunks[0]
|
||||||
|
result = StartUPTest.run_all_tests(first_chunk)
|
||||||
|
#print(result)
|
||||||
|
return result
|
||||||
|
|
||||||
|
def perform_tot_online_tests(filename):
|
||||||
|
with open(filename, 'rb') as f:
|
||||||
|
# Read the contents of the file as bytes
|
||||||
|
content = f.read()
|
||||||
|
|
||||||
|
#print("Run all TotOnline tests")
|
||||||
|
binary_chunks = process_data_in_chunks(content)
|
||||||
|
first_chunk = binary_chunks[0]
|
||||||
|
result = TotOnline.run_all_tests(first_chunk)
|
||||||
|
#print(result)
|
||||||
|
return result
|
||||||
|
|
||||||
|
def analyze_data(num_numbers, bits_per_number, startup):
|
||||||
|
|
||||||
|
if startup:
|
||||||
|
filename = read_data(10, 80000)
|
||||||
|
binary_filename = convert_to_binary(filename, 10, 80000)
|
||||||
|
perform_startup_tests(binary_filename)
|
||||||
|
perform_tot_online_tests(binary_filename)
|
||||||
|
os.unlink(filename)
|
||||||
|
os.unlink(binary_filename)
|
||||||
|
return True
|
||||||
|
else:
|
||||||
|
filename = read_data(10, 20000)
|
||||||
|
binary_filename = convert_to_binary(filename, 10, 20000)
|
||||||
|
result = perform_tot_online_tests(binary_filename)
|
||||||
|
os.unlink(filename)
|
||||||
|
os.unlink(binary_filename)
|
||||||
|
if result:
|
||||||
|
filename = read_data(num_numbers, bits_per_number)
|
||||||
|
binary_filename = convert_to_binary(filename, num_numbers, bits_per_number)
|
||||||
|
hex_filename = convert_to_hex(binary_filename, num_numbers, bits_per_number)
|
||||||
|
# Read the hex numbers from the file
|
||||||
|
with open(hex_filename, 'rb') as f:
|
||||||
|
hex_numbers_bytes = f.read()
|
||||||
|
# Decode the bytes to a string
|
||||||
|
hex_numbers_str = hex_numbers_bytes.decode('utf-8')
|
||||||
|
# Split the semicolon-separated string into a list of hex numbers
|
||||||
|
hex_numbers = hex_numbers_str.split(';')
|
||||||
|
# Remove any empty strings
|
||||||
|
hex_numbers = [hex_num for hex_num in hex_numbers if hex_num]
|
||||||
|
# Create the JSON object with the specified structure
|
||||||
|
data = {'randomNumbers': hex_numbers}
|
||||||
|
# Delete the temporary files
|
||||||
|
os.unlink(filename)
|
||||||
|
os.unlink(binary_filename)
|
||||||
|
os.unlink(hex_filename)
|
||||||
|
# Return the JSON object using Flask's jsonify function
|
||||||
|
return jsonify(data)
|
||||||
|
|
||||||
|
else:
|
||||||
|
os.unlink(filename)
|
||||||
|
os.unlink(binary_filename)
|
||||||
|
os.unlink(hex_filename)
|
||||||
|
return False
|
||||||
|
|
||||||
|
# Teste den Code
|
||||||
|
#result = analyze_data(50, 2560, startup=False)
|
||||||
|
#result = analyze_data(8, 8, startup=True)
|
||||||
|
#print(result)
|
||||||
|
|
|
@ -0,0 +1,86 @@
|
||||||
|
import subprocess
|
||||||
|
import json
|
||||||
|
import time
|
||||||
|
from flask import Flask, request, jsonify, session
|
||||||
|
from I2C_Function import analyze_data, read_data
|
||||||
|
from flask_cors import CORS
|
||||||
|
from flask_session import Session
|
||||||
|
|
||||||
|
app = Flask(__name__)
|
||||||
|
app.config.from_pyfile('config.py')
|
||||||
|
Session(app)
|
||||||
|
CORS(app)
|
||||||
|
|
||||||
|
initialized = False
|
||||||
|
|
||||||
|
@app.route('/trng/randomNum/init', methods=['GET'])
|
||||||
|
def initialize_generator():
|
||||||
|
#quantity = 1
|
||||||
|
#bits = 1
|
||||||
|
#startup = True # Boolean-Wert für die Initialisierung
|
||||||
|
global initialized # Zugriff auf die globale Variable
|
||||||
|
|
||||||
|
#result = analyze_data(int(quantity), int(bits), startup=true)
|
||||||
|
result = analyze_data(int(1), int(1), startup=True)
|
||||||
|
#session['initialized'] = True
|
||||||
|
|
||||||
|
if result is True:
|
||||||
|
initialized = True
|
||||||
|
return jsonify({'error': 'successful operation; random number generator is ready and random numbers can be requested'}), 200
|
||||||
|
else:
|
||||||
|
return jsonify({'error': 'Unable to initialize the random number generator within a timeout of 60 seconds.'}), 555
|
||||||
|
|
||||||
|
|
||||||
|
@app.route('/trng/randomNum/getRandom', methods=['GET'])
|
||||||
|
def get_random_numbers():
|
||||||
|
global initialized # Zugriff auf die globale Variable
|
||||||
|
quantity = request.args.get('quantity')
|
||||||
|
bits = request.args.get('numBits')
|
||||||
|
|
||||||
|
if not quantity.isdigit() or not bits.isdigit():
|
||||||
|
return jsonify({'error': 'Invalid input. Quantity and bits must be numeric.'}), 400
|
||||||
|
|
||||||
|
if int(quantity) <= 0 or int(bits) <= 0:
|
||||||
|
return jsonify({'error': 'Invalid input. Quantity and bits must be positive integers.'}), 400
|
||||||
|
|
||||||
|
# Überprüfe den Initialisierungsstatus
|
||||||
|
if not initialized:
|
||||||
|
return jsonify({'error': 'system not ready; try init'}), 432
|
||||||
|
|
||||||
|
#if 'initialized' not in session or not session['initialized']:
|
||||||
|
#return jsonify({'error': 'system not ready; try init'}), 432
|
||||||
|
|
||||||
|
#if 'initialized' not in session or not session['initialized', '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
|
||||||
|
if filename:
|
||||||
|
return filename, 200
|
||||||
|
else:
|
||||||
|
return jsonify({'error': 'Unable to generate random numbers.'}), 500
|
||||||
|
|
||||||
|
@app.route('/trng/randomNum/shutdown', methods=['GET'])
|
||||||
|
def shutdown_generator():
|
||||||
|
global initialized # Zugriff auf die globale Variable
|
||||||
|
|
||||||
|
initialized = False # Setze den Initialisierungsstatus zurück
|
||||||
|
#session['initialized'] = False
|
||||||
|
|
||||||
|
# Beispielantwort
|
||||||
|
return jsonify({'message': 'Generator shutdown successfully.'}), 200
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
# 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'
|
||||||
|
key_path = '/etc/nginx/ssl/cert-gmtrom-key.pem'
|
||||||
|
|
||||||
|
# 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=adhoc)
|
||||||
|
#app.run(ssl_context=(cert_path, key_path))
|
|
@ -0,0 +1,82 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<title>GMTROM - True Random Number Generator</title>
|
||||||
|
<link rel="stylesheet" type="text/css" href="style.css">
|
||||||
|
<link rel="icon" type="image/png" href="logomiddle.png">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<img src="logo.png" alt="Logo" class="logo">
|
||||||
|
<h1>GMTROM - True Random Number Generator</h1>
|
||||||
|
<form id="randomForm">
|
||||||
|
<input type="button" value="Initialize" id="initButton"><br><br>
|
||||||
|
<label for="quantity">Quantity of Random Numbers:</label>
|
||||||
|
<input type="number" id="quantity" name="quantity"><br><br>
|
||||||
|
<label for="bits">Number of Bits per Random Number:</label>
|
||||||
|
<input type="number" id="bits" name="bits"><br><br>
|
||||||
|
<input type="submit" value="Generate" id="generateButton">
|
||||||
|
<input type="submit" value="Shutdown" id="shutdownButton">
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<div id="status"></div>
|
||||||
|
<div id="result"></div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
document.getElementById('initButton').addEventListener('click', function() {
|
||||||
|
fetch('https://172.16.78.57:5000/trng/randomNum/init')
|
||||||
|
.then(response => {
|
||||||
|
document.getElementById('status').innerText = 'Status: ' + response.status;
|
||||||
|
if (response.status === 200) {
|
||||||
|
console.log('Initialisierung erfolgreich');
|
||||||
|
} else {
|
||||||
|
console.log('Fehler beim Initialisieren');
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(error => {
|
||||||
|
console.error('Fehler beim Initialisieren:', error);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
document.getElementById('generateButton').addEventListener('click', function(event) {
|
||||||
|
event.preventDefault(); // Verhindert das Absenden des Formulars
|
||||||
|
|
||||||
|
var quantity = document.getElementById('quantity').value;
|
||||||
|
var bits = document.getElementById('bits').value;
|
||||||
|
|
||||||
|
var url = 'https://172.16.78.57:5000/trng/randomNum/getRandom';
|
||||||
|
if (quantity && bits) {
|
||||||
|
url += '?quantity=' + quantity + '&numBits=' + bits;
|
||||||
|
}
|
||||||
|
|
||||||
|
fetch(url)
|
||||||
|
.then(response => {
|
||||||
|
document.getElementById('status').innerText = 'Status: ' + response.status;
|
||||||
|
return response.json();
|
||||||
|
})
|
||||||
|
.then(data => {
|
||||||
|
var resultDiv = document.getElementById('result');
|
||||||
|
var hexNumbers = JSON.parse(data.randomNumbers);
|
||||||
|
resultDiv.innerText = hexNumbers.join(', ');
|
||||||
|
})
|
||||||
|
.catch(error => {
|
||||||
|
console.error('Fehler beim Abrufen der Daten:', 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) {
|
||||||
|
console.log('Shutdown erfolgreich');
|
||||||
|
} else {
|
||||||
|
console.log('Fehler beim Shutdown');
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(error => {
|
||||||
|
console.error('Fehler beim Shutdown:', error);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
Binary file not shown.
After Width: | Height: | Size: 1.8 KiB |
Binary file not shown.
After Width: | Height: | Size: 776 B |
Loading…
Reference in New Issue