Skip to content
Commits on Source (2)
......@@ -21,34 +21,75 @@ app.threaded = True
cors = CORS(app)
import configparser
# Load the config file
config = configparser.ConfigParser()
config.read('config/api.ini')
@app.route('/all/<string:namespace>')
def get_status(namespace):
'''Build a global status for a given namespace'''
wait = float(request.args.get('wait', 0))
def get_all(namespace):
# '''Build a global status for a given namespace'''
# wait = float(request.args.get('wait', 0))
endpoints = {}
sections = []
# sorting GET priority
for section in config.sections():
if section.startswith("/"+namespace):
priority = config[section].getint('get-priority', float('inf'))
sections.append((priority, section))
# Check for ping before going to all others
power = f"/api/{namespace}/ping"
with app.test_client() as client:
res = client.get(power)
name = "-".join(power.split("/")[2:]) # "dome-ping"
endpoints[name] = res.get_json()
if "raw" in res.get_json():
if not res.get_json()["raw"]:
return endpoints
# Sort sections based on priority (higher priority first)
sections.sort()
for rule in app.url_map.iter_rules():
if rule.rule.startswith(f"/api/{namespace}/"): # "/api/dome/shutter/movement"
if "GET" in rule.methods:
with app.test_client() as client:
res = client.get(rule.rule)
name = "-".join(rule.rule.split("/")[2:]) # "dome-shutter-movement"
endpoints[name] = res.get_json()
time.sleep(wait)
for _, section in sections:
with app.test_client() as client:
print(f"getting http://fork.orsa.unige.net:5533/api{section}")
# res = requests.get(f"http://fork.orsa.unige.net:5533/api{section}")
res = client.get(section)
if res.status_code != 405: # 405 Method Not Allowed
name = "-".join(section.split("/")[2:]) # "dome-ping"
# endpoints[name] = res.json()
endpoints[name] = res.get_json()
if "raw" in res.json():
if not res.json()["raw"]:
break
elif (res.json()["response"] == "FAILED 2"):
break
return endpoints
# @app.route('/all/<string:namespace>')
# def get_status(namespace):
# '''Build a global status for a given namespace'''
# wait = float(request.args.get('wait', 0))
# endpoints = {}
# # Check for ping before going to all others
# power = f"/api/{namespace}/ping"
# with app.test_client() as client:
# res = client.get(power)
# name = "-".join(power.split("/")[2:]) # "dome-ping"
# endpoints[name] = res.get_json()
# if "raw" in res.get_json():
# if not res.get_json()["raw"]:
# return endpoints
# for rule in app.url_map.iter_rules():
# if rule.rule.startswith(f"/api/{namespace}/"): # "/api/dome/shutter/movement"
# if "GET" in rule.methods:
# with app.test_client() as client:
# res = client.get(rule.rule)
# name = "-".join(rule.rule.split("/")[2:]) # "dome-shutter-movement"
# endpoints[name] = res.get_json()
# time.sleep(wait)
# return endpoints
if __name__ == "__main__":
......
......@@ -3,15 +3,17 @@
# [/my/endpoint/name] # You choose
# resource = class implementing a CRUD operation
# device = You defined it in devices.ini
# get-priority = defines a GET hierarchy.
# #####################################################
##############
# dome
##############
[/dome/ping]
[/dome/connection]
resource = Connection
device = dom
get-priority = 1
[/dome/light]
resource = State
......@@ -49,29 +51,23 @@ device = dom
resource = PositionSync
device = dom
[/dome/connection]
resource = Connection
device = dom
##############
# telescope
##############
[/telescope/ping]
resource = State
device = cab
[/telescope/lamp]
resource = State
device = lamp
[/telescope/power]
resource = State
device = cab
get-priority = 1
[/telescope/clock]
resource = Clock
device = tel
get-priority = 2
[/telescope/lamp]
resource = State
device = lamp
[/telescope/cover]
resource = Cover
......@@ -145,13 +141,10 @@ device = rot
# camera
##############
[/camera/ping]
resource = State
device = sof
[/camera/power]
resource = State
device = sof
get-priority = 1
[/camera/frame/binning]
resource = FrameBinning
......
// Define variables for WebGL resources
var gl;
var program;
var positionLocation;
var texcoordLocation;
var positionBuffer;
var texcoordBuffer;
var texture;
var resolutionLocation;
var textureLocation; // Define texture location
function difftime(unix_timestamp){
let client_unix_time = new Date().getTime()/1000.0
var diff = client_unix_time - unix_timestamp
return diff.toFixed(3)
}
// Function to set rectangle geometry in buffer
function setRectangle(gl, x, y, width, height) {
var x1 = x;
var x2 = x + width;
var y1 = y;
var y2 = y + height;
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([x1, y1, x2, y1, x1, y2, x1, y2, x2, y1, x2, y2]), gl.STATIC_DRAW);
}
// Function to setup WebGL resources
function setupWebGL(canvasId) {
// Get the WebGL context
var canvas = document.getElementById(canvasId);
gl = canvas.getContext("webgl");
if (!gl) {
return false; // WebGL not supported
}
// Setup GLSL program
program = webglUtils.createProgramFromScripts(gl, [
"vertex-shader-2d",
"fragment-shader-2d"
]);
// Lookup attribute and uniform locations
positionLocation = gl.getAttribLocation(program, "a_position");
texcoordLocation = gl.getAttribLocation(program, "a_texCoord");
resolutionLocation = gl.getUniformLocation(program, "u_resolution");
textureLocation = gl.getUniformLocation(program, "u_texture"); // Get texture location
// Create position buffer
positionBuffer = gl.createBuffer();
// Create texcoord buffer
texcoordBuffer = gl.createBuffer();
return true;
}
// Precompute texture data offline
var precomputedTextureData = [];
function typeArray(data, dtype) {
var typedArray = [];
var maxDataValue = 65535;
if (dtype === 'float32') {
typedArray = new Float32Array(data);
} else if (dtype === 'int32') {
typedArray = new Int32Array(data);
} else if (dtype === 'int16') {
typedArray = new Int16Array(data);
maxDataValue = 32767;
} else if (dtype === 'int8' || dtype === 'uint8') {
typedArray = new Uint8Array(data);
maxDataValue = 255;
} else if (dtype === 'uint16') {
typedArray = new Uint16Array(data);
} else {
console.error('Unsupported data type:', dtype);
return;
}
return typedArray
}
function precomputeTextureData(data, width, height, dtype, is_mask=false) {
var typedArray = typeArray(data, dtype);
var maxDataValue = 65535
if (is_mask) {
for (var i = 0; i < typedArray.length; i++) {
var value = typedArray[i];
precomputedTextureData.push(0,255,255, value * 0.8);
}
} else {
for (var i = 0; i < typedArray.length; i++) {
var value = typedArray[i];
var index = Math.round((value / maxDataValue) * (viridis.length - 1));
var rgb = viridis[index];
precomputedTextureData.push(rgb[0], rgb[1], rgb[2], 255);
}
}
}
// Upload precomputed texture data to GPU
function uploadTextureDataToGPU(width, height) {
// Create a texture
texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);
// Set texture parameters
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
var type = gl.UNSIGNED_BYTE;
var level = 0;
var internalFormat = gl.RGBA;
var border = 0;
var format = gl.RGBA;
var textureData = new Uint8Array(precomputedTextureData);
gl.texImage2D(gl.TEXTURE_2D, level, internalFormat, width, height, border, format, type, textureData);
}
// Function to upload matrix data to texture
function uploadMatrixData(data, width, height, dtype, is_mask) {
precomputedTextureData = [];
precomputeTextureData(data, width, height, dtype, is_mask);
uploadTextureDataToGPU(width, height);
}
// Function to draw matrix with WebGL, scaling each value by a custom factor and starting coordinates
function drawMatrixWithWebGL(data, canvasId, scaleFactor=1, x0=0, y0=0, is_mask=false) {
// Check if WebGL resources need to be setup
if (!gl) {
if (!setupWebGL(canvasId)) {
console.error("WebGL not supported");
return;
}
}
// Clear the canvas
gl.clearColor(0, 0, 0, 0);
gl.clear(gl.COLOR_BUFFER_BIT);
// Use the shader program
gl.useProgram(program);
// Setup vertex position buffer with adjusted starting coordinates
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
setRectangle(gl, x0, y0, data.shape[0] * scaleFactor + x0, data.shape[1] * scaleFactor + y0);
gl.enableVertexAttribArray(positionLocation);
gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0);
// Setup texture coordinate buffer with scaled values
gl.bindBuffer(gl.ARRAY_BUFFER, texcoordBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
0, 0,
1, 0,
0, 1,
0, 1,
1, 0,
1, 1
]), gl.STATIC_DRAW);
gl.enableVertexAttribArray(texcoordLocation);
gl.vertexAttribPointer(texcoordLocation, 2, gl.FLOAT, false, 0, 0);
// Set the resolution uniform
gl.uniform2f(resolutionLocation, gl.canvas.width, gl.canvas.height);
// Upload matrix data to texture
uploadMatrixData(data.data, data.shape[0], data.shape[1], data.dtype, is_mask);
// Draw the rectangle with scaled dimensions
gl.drawArrays(gl.TRIANGLES, 0, 6);
}
......@@ -90,18 +90,19 @@ def send_dm():
while True:
now = Time.now()
es = requests.get("http://sharknirws.shark-nir.lbto.org:5001/api/rtc/plots/")
#es = requests.get("http://sharknirws.shark-nir.lbto.org:5001/api/rtc/plots/")
es = {"dm":"ciccio"}
if "dm" in es.json():
shape = np.array(es.json()["dm"]["shape"])
flat = np.array(es.json()["dm"]["flat"])
matrix = shape-flat
print(matrix)
print((Time.now()-now).sec, "fetched")
# shape = np.array(es.json()["dm"]["shape"])
# flat = np.array(es.json()["dm"]["flat"])
# matrix = shape-flat
# print(matrix)
# print((Time.now()-now).sec, "fetched")
dtype = "float32"
shape = (97)
#matrix = np.random.uniform(-1,1, shape)
matrix = np.random.uniform(-1,1, shape)
binary_data = matrix.astype(dtype).tobytes()#.tobytes()
data_bundle = {
"shape": matrix.shape,
......
......@@ -10,6 +10,8 @@ from datetime import datetime
# Third-party modules
from astropy.io import fits
# Custom modules
from app import app
class Status:
......
// //camera synch
// $(document).ready(function() {
// var filternumber = {
// 1: 'U',
// 2: 'B',
// 3: 'V',
// 4: 'R',
// 5: 'I',
// 6: 'Halpha',
// 7: 'Free'
// };
// var binningconversion = {
// "1,1": 1,
// "2,2": 2,
// "3,3": 3,
// "4,4": 4
// };
// function getFilterFromNumber(number) {
// return filternumber[number] || '';
// }
// function getBinningFromNumber(number) {
// return binningconversion[number] || '';
// }
// function selectOptionByValue(selectElement, value) {
// selectElement.val(value);
// }
// var CameraSection = $('#Camera');
// var cameraFilter = $('#camera-filter var');
// var cameraBinning = $('#camera-binning var');
// var filterSelect = $('#filter');
// var binningSelect = $('#binning');
// function mutationCallback(mutations) {
// mutations.forEach(function(mutation) {
// CameraSection.removeClass('disabled-section');
// if (mutation.target.nodeType === Node.ELEMENT_NODE) {
// var newValue = $(mutation.target).text();
// if (mutation.target.parentElement.id === 'camera-filter') {
// selectOptionByValue(filterSelect, getFilterFromNumber(newValue));
// observerFilter.disconnect();
// } else if (mutation.target.parentElement.id === 'camera-binning') {
// selectOptionByValue(binningSelect, getBinningFromNumber(newValue));
// observerBinning.disconnect();
// }
// }
// });
// }
// var observerFilter = new MutationObserver(mutationCallback);
// var observerBinning = new MutationObserver(mutationCallback);
// var config = { childList: true, subtree: true };
// observerFilter.observe(cameraFilter[0], config);
// observerBinning.observe(cameraBinning[0], config);
// });