commit 0df24df3cd1cf9d543c2b4631169c69676a23f76 Author: smathis Date: Tue Nov 25 08:40:59 2025 +0100 Initial commit for common MIDAS webpages diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c795b05 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +build \ No newline at end of file diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..55ece19 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,14 @@ +cmake_minimum_required(VERSION 3.3) + +project(common_pages VERSION 1.0) + +if (NOT DEFINED ENV{MIDASSYS}) + message(FATAL_ERROR "The system variable MIDASSYS is not defined.") +endif (NOT DEFINED ENV{MIDASSYS}) + +set(install_path $ENV{MIDASSYS}/Custom) + +install( + DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/pages/ DESTINATION ${install_path} +) + diff --git a/README.md b/README.md new file mode 100644 index 0000000..7b9ea0a --- /dev/null +++ b/README.md @@ -0,0 +1,33 @@ +# Common pages + +Custom MIDAS webpages shared across multiple SuS experiments. + +This repository is meant to be included as a submodule in the +instrument-specific pages repository such as +. + +## Installation + +As a prerequisite, the system variable `MIDASSYS` needs to be defined and point +to the MIDAS installation. Then, run: + +```bash +cmake -S "$(pwd)" -B +cmake --install +``` + +The first step generates the build rules into ``. This is +a temporary directory which is recommended to be `$(pwd)/build` (a folder called +"build" in the repository root). The second step then copies everything in +`pages` into `$MIDASSYS/Custom`, the standard location for MIDAS custom pages. +Because the installation does not require compiling any source code, no +build step is needed. + +## Contact +Flame: +; +LEM: +, +, + + diff --git a/pages/Graph.ico b/pages/Graph.ico new file mode 100644 index 0000000..2af9c00 Binary files /dev/null and b/pages/Graph.ico differ diff --git a/pages/MuSRFit.png b/pages/MuSRFit.png new file mode 100644 index 0000000..42cdcea Binary files /dev/null and b/pages/MuSRFit.png differ diff --git a/pages/Mudas.css b/pages/Mudas.css new file mode 100644 index 0000000..a41f3c2 --- /dev/null +++ b/pages/Mudas.css @@ -0,0 +1,398 @@ +html { font-size: 100%;} + +* { + box-sizing: border-box; +} + +td { + white-space: nowrap; +/* font-size: 10vw;*/ +} + +.guitable { + background-color: #DDDDDD; + border: 0px; + width: 100%; + /* border-collapse: collapse; */ + border-radius: 10px; + border: none; + border-spacing: 0px; + padding: 5px; + margin-left: auto; + margin-right: auto; + margin-top: 0px; + margin-bottom: 0px; +} +.guitable tr:last-child td:first-child { +/* font-size: 10vw;*/ + border-bottom-left-radius: 12px; +} +.guitable tr:last-child td:last-child { + border-bottom-right-radius: 12px; +} +.guitable tr:first-child td:first-child { + border-top-left-radius: 12px; +} +.guitable tr:first-child td:last-child { + border-top-right-radius: 12px; +} +.guitable tr:nth-child(odd) { + background-color: #DDDDDD; +} +.guitable tr:nth-child(even) { + background-color: #DDDDDD; +} + +.oddeven tr:nth-child(odd) { + background-color: #DDDDDD; +} +.oddeven tr:nth-child(even) { + background-color: #F2F2F2; +} + +/* For mobile phones: */ +[class*="col-"] { + width: 100%; + padding: 5px; + margin-left: auto; + margin-right: auto; + margin-top: 0px; + margin-bottom: 0px; + float: left; + padding: 5px; + overflow:hidden; + border: none; +} + + +@media only screen and (min-width: 990px) { + /* For desktop: */ + .col-1 {width: 50%;background-color: #F2F2F2;} + .col-2 {width: 50%;background-color: #F2F2F2;} + .col-full {width: 100%;background-color: #F2F2F2;} +} + +.row::after { + content: ""; + clear: both; + display: table; +} + +.group_name { + padding-left:1em; + padding-right:1em; + font-size:1.05rem; + font-weight:bold; + width: 1%; + white-space: nowrap; + /* text-align: center; */ +} +.yellow_td { + padding-left:1em; + padding-right:1em; + background-color: yellow; + width: 1%; + white-space: nowrap; + font-size: 1rem; +} +.gray_td { + padding-left:1em; + padding-right:1em; + background-color: gray; + width: 1%; + white-space: nowrap; +} +.nocol_td { + padding-left:1em; + padding-right:1em; + width: 1%; + min-width: 9rem; + white-space: nowrap; +} + +/* Style the tab */ +.tab { + overflow: hidden; + border: 1px solid #ccc; + background-color: #f1f1f1; +} + +.active { + background-color: #11f1f1; +} + +/* Style the buttons that are used to open the tab content */ +.tab button { + background-color: inherit; + float: left; + border: none; + outline: none; + cursor: pointer; + padding: 14px 16px; + transition: 10.3s; + font-size:1.1rem; + font-weight:bold; +} + +/* Style the tab content */ +.tabcontent { + display: none; + padding: 6px 12px; + border: 1px solid #ccc; + border-top: none; +} + +.tabcontent { + animation: fadeEffect 1s; /* Fading effect takes 1 second */ +} + +/* Go from zero to full opacity */ +@keyframes fadeEffect { + from {opacity: 0;} + to {opacity: 1;} +} + +.scaler_head_left { + text-align:left; + padding-left:1em; + padding-right:1em; +} +.scaler_head_right { + text-align:right; + padding-left:1em; + padding-right:1em; +} +.scaler_name { + padding-left:1em; + padding-right:1em; +} +.scaler_val { + text-align:right; + padding-right:1em; +} + + +/* For the AutoRun tab */ +.lar_label { + text-align:left; + padding-left:1em; + padding-right:1em; +} +.lar_label_right { + text-align:right; + padding-left:1em; + padding-right:1em; +} +.lar_value { + text-align:left; + padding-left:1em; + padding-right:1em; +} +.lar_script { + text-align:left; + font-family:Fixed; + font-size: 1rem; + line-height:1.25; +} +.lar_fatal { + background-color: #FF0000; + font-weight: bold; +} +.lar_err { + background-color: #FF8800; + font-weight: bold; +} +.lar_msg { + background-color: #11FF11; + font-weight: bold; +} +.lar_current_cmd { + background-color: #FFFF00; + font-weight: bold; +} +.lar_comment { + color: grey; + font-style: italic; +} + +/*LOOP_ WAIT TITLE START TOF FIELD TEMP */ +.lar_command { + color: #C81A1C; + font-weight: bold; +} + +/*ODB_TAG ALIAS */ +.lar_tag { + color: #0A6E2B; + font-weight: bold; +} + +/*ODB_TAG ALIAS */ +.lar_ntag { + color: #8E0F7E; +} + +/*ODB_TAG ALIAS */ +.lar_otag { + color: #9F4511; +} + +/*ODB_PARAM ALIAS */ +.lar_par { + color: #1817A2; + font-style: italic; +} + +.lar_odb { + color: #D3AF37; +} + +.lar_loop { + color: #8E0F7E; + font-weight: bold; +} + +.lar_area { + max-width:90vw; + width:100%; + height:40vh; + overflow:auto; + resize:both; + background-color:white; + overflow-wrap: break-word; + caret-color: red; + padding: 5px 10px 5px 10px; + white-space: pre; + font-family: monospace; + display: block; +} + +/* Red/Green Mode */ +#PulsOn { + width: 15px; + height: 15px; + background-color: red; + position: relative; + -webkit-animation-name: example; /* Chrome, Safari, Opera */ + -webkit-animation-duration: 2s; /* Chrome, Safari, Opera */ + -webkit-animation-iteration-count: infinite; /* Chrome, Safari, Opera */ + animation-name: example; + animation-duration: 3s; + animation-iteration-count: infinite; +} + +/* Chrome, Safari, Opera */ +@-webkit-keyframes example { + 0% {background-color:red; left:20px; top:0px;} + 25% {background-color:orange; left:25px; top:0px;} + 50% {background-color:green; left:30px; top:0px;} + 75% {background-color:orange; left:25px; top:0px;} + 100% {background-color:red; left:20px; top:0px;} +} + +/* Standard syntax */ +@keyframes example { + 0% {background-color:red; left:20px; top:0px;} + 25% {background-color:orange; left:25px; top:0px;} + 50% {background-color:green; left:30px; top:0px;} + 75% {background-color:orange; left:25px; top:0px;} + 100% {background-color:red; left:20px; top:0px;} +} + +/* HV table highlight */ +.tdSelectable:hover { + background-color: yellow; +} + +.tdSelected { + background: yellow; +} + +.tdIgnorable:hover { + background-color: red; +} + +.tdIgnored { + background: red; +} + +/* Proposal ID checks */ +.propIDcorrect { + background: red; +} + + +/* Vacuum related */ +.chamber { + stroke: #000000; + stroke-width: 2px; + fill: #E0E0E0; +} +.pump_line { + stroke: #505050; + stroke-width: 5px; + fill: none; +} + +/* The switch - the box around the slider */ +.switch { + position: relative; + display: inline-block; + width: 30px; + height: 17px; +} + +/* Hide default HTML checkbox */ +.switch input { + opacity: 0; + width: 0; + height: 0; +} + +/* The slider */ +.slider { + position: absolute; + cursor: pointer; + top: 0; + left: 0; + right: 0; + bottom: 0; + background-color: #ccc; + -webkit-transition: .4s; + transition: .4s; +} + +.slider:before { + position: absolute; + content: ""; + height: 13px; + width: 13px; + left: 2px; + bottom: 2px; + background-color: white; + -webkit-transition: .4s; + transition: .4s; +} + +input:checked + .slider { + background-color: green; +} + +input:focus + .slider { + box-shadow: 0 0 1px #2196F3; +} + +input:checked + .slider:before { + -webkit-transform: translateX(13px); + -ms-transform: translateX(13px); + transform: translateX(13px); +} + +/* Rounded sliders */ +.slider.round { + border-radius: 17px; +} + +.slider.round:before { + border-radius: 50%; +} diff --git a/pages/Mudas.js b/pages/Mudas.js new file mode 100644 index 0000000..e619a6a --- /dev/null +++ b/pages/Mudas.js @@ -0,0 +1,4506 @@ +//**************************************************************************// +// Copyright (C) 2020-2025 by Zaher Salman // +// zaher.salman@psi.ch // +// jonas.krieger@psi.ch // +//**************************************************************************// + +//**************************************************************************// +// Generic functions for midas // +//**************************************************************************// + +// Bypass dlg shit +function dlgMessage(title, string, modal, error, callback, param) { + let d = document.createElement("div"); + // Redirect the message to the console + if (string) { + console.log("dlgMessage: ",string); +} + // Return an empty
+ return d; +} + +// Function to stop an ongoing run +function stopRun() { + let flag = confirm('Are you sure you want to stop the run?'); + if (flag == true) { + mjsonrpc_call("cm_transition", {"transition": "TR_STOP"}).then(function (rpc) { + if (rpc.result.status !== 1) { + throw new Error("Cannot stop run, cm_transition() status " + rpc.result.status + ", see MIDAS messages"); + } + }).catch(function (error) { + console.error(error); + }); + } +} + +// Function to pause an ongoing run +function pauseRun() { + let flag = confirm('Are you sure you want to pause the run?'); + if (flag == true) { + mjsonrpc_call("cm_transition", {"transition": "TR_PAUSE"}).then(function (rpc) { + if (rpc.result.status !== 1) { + throw new Error("Cannot pause run, cm_transition() status " + rpc.result.status + ", see MIDAS messages"); + } + }).catch(function (error) { + console.error(error); + }); + } +} + +// Function to resume a paused run +function resumeRun() { + let flag = confirm('Are you sure you want to resume the run?'); + if (flag == true) { + mjsonrpc_call("cm_transition", {"transition": "TR_RESUME"}).then(function (rpc) { + if (rpc.result.status !== 1) { + throw new Error("Cannot resume run, cm_transition() status " + rpc.result.status + ", see MIDAS messages"); + } + }).catch(function (error) { + console.error(error); + }); + } +} + +// Function to start a run +function startRun() { + let flag = confirm('Are you sure you want to start the run?'); + if (flag == true) { + mjsonrpc_call("cm_transition", {"transition": "TR_START"}).then(function (rpc) { + if (rpc.result.status !== 1) { + throw new Error("Cannot start run, cm_transition() status " + rpc.result.status + ", see MIDAS messages"); + } + }).catch(function (error) { + console.error(error); + }); + } +} + + +//**************************************************************************// +// Generic functions JS // +//**************************************************************************// + +// Function to remove element by id +function removeElement(elementId) { + var element = document.getElementById(elementId); + if (element) element.parentNode.removeChild(element); +} + +// Function to check whether an element exists or not +function existElement(elementId) { + var element = document.getElementById(elementId); + if (element) + return true; + else + return false; +} + +// Function to add element in parent +function addElement(parentId, elementTag, elementId, html) { + var p = document.getElementById(parentId); + var newElement = document.createElement(elementTag); + newElement.setAttribute('id', elementId); + newElement.innerHTML = html; + p.appendChild(newElement); +} + +// Function to change content of element id +function setIfChanged(id, text) +{ + var e = document.getElementById(id); + if (e) { + if (e.innerHTML != text) { + e.innerHTML = text; + } + } +} + +//**************************************************************************// +// Functions for general Mudas use // +//**************************************************************************// + +// Global variables +var updateTimerId = 0; +var updatePeriod = 1000; // in msec +var startupCount = 0; + +// Function to run onload to setup needed options and update period of GUI +// Called only once, onload. +function Mudas_init_once() { + // update run state + runStatus(); + // Configure setup + setupInit(); + // hide side menu + // mhttpd_show_menu(0); + // Check proposal ID against DUO + propODB(0); + // Setup APD page + showSegment(); + // Update link to musrfit + updateFitLink(); + // Update cryostat page + updateSamcryo(); + // Transport options + selColl("none"); + // HV settings + mkEquipmentTable("HV",0,15,"HVTable"); + mkEquipmentTable("Beamline",0,39,"blTable"); + // add event listiners to lar editor area + checkSyntaxEvent(); + //init variables by name + mvar_init(); + frappy_enum_init() +} + +// Function to run onload to setup needed options and update period of GUI +// Called periodically +function Mudas_init() { + // HIPA status update + document.getElementById("HIPAimg").src = "https://gfa-status.web.psi.ch/hipa-info-1024x768.png" + "?" + Date(); + + // AutoRun update + load_lar(); + + // Check alarms + triggerAlarms(); + + // Vacuum update + update_vacuum(); + + // Running time update + // This is a workaround, needed only for running time + runStatus(); + + // timing update + clearTimeout(updateTimerId); + if (updatePeriod > 0) { + if (updatePeriod == 500) { + startupCount++; + if (startupCount > 2) + updatePeriod = 3000; + } + updateTimerId = setTimeout('Mudas_init()', updatePeriod); + } +} + +// This function fills the modbvalue tags with the appropriate data_odb_path +// The ODBs should be defined in instrODB ([INSTR]init.js) +function fillODBs() { + for (let key in instrODB) { + var element = document.getElementById(key); + if (element) { + // if the element exists then fill the correct path + element.setAttribute("data-odb-path",instrODB[key]); + } + } + + // Elog link + let elogElem = document.getElementById("elogLink"); + if (elogLink == "") { + // hide Elog field + elogElem.style.visibility = "hidden"; + } else { + // set the correct link + elogElem.setAttribute("href",elogLink); + } + + // Title of page and instumenat name/color + document.title = instrName + " Mudas"; + let instrBanner = document.getElementById("instrName"); + instrBanner.innerHTML = "Mudas "+instrName+""; + let mTables = document.getElementsByClassName("mtable"); + for (const mTable of mTables) { + mTable.style.border = '6px solid ' + instrColor; + } +} + +// This function fills the tabs according to the init file +// The tabs should be defined in instrTabs ([INSTR]init.js) +function fillTabs() { + // create two containers + let tabBtns = document.getElementById("tabBtns"); + let tabMenu = document.getElementById("tabMenu"); + let tabFrames = document.getElementById("tabFrames"); + let beforeMenu = document.getElementById("beforeMenu"); + let HIPA = document.getElementById("100"); + // tab counter + let iTab=0; + for (let key in instrTabs) { + iTab++; + let d = document.createElement("div"); + d.id = "Tab" + iTab; + d.className = "tabcontent"; + let f = ""; + d.innerHTML= f; + let b = document.createElement("button"); + if (instrTabs[key].style == "Menu") { + b = document.createElement("a"); + } + b.id = iTab; + b.className = "w3-bar-item w3-button w3-round"; + b.setAttribute("onclick","openTab(event,this.id);" + instrTabs[key].addFunc); + b.innerHTML = "" + instrTabs[key].label + ""; + //b.onload = "openTab(event,this.id);" + instrTabs[key].addFunc; + + // Append elements + if (instrTabs[key].style == "Tab") { + tabBtns.insertBefore(b,beforeMenu); + } else { + tabMenu.insertBefore(b,HIPA); + } + tabFrames.appendChild(d); + } +} + +// This function checks for triggered alarms and add them to Mudas +function triggerAlarms() { + mjsonrpc_db_get_values(["/Alarms"]).then(function(rpc) { + alarm = rpc.result.data[0]; + //console.log(alarm); + //console.log(alarm['alarm system active']); + if (alarm["alarm system active"]) { + var allAlarms = alarm["alarms"] + for (var element in allAlarms) { + if (allAlarms[element]["triggered"] && allAlarms[element]["active"]) { + if (document.getElementById(element + "Alarm") === null) { + var newAlarm = document.getElementById("alarmsTable").insertRow(0); + var bgcol = "red"; + if (allAlarms[element]["alarm class"] == "Warning") { + bgcol = "orange"; + } else if (allAlarms[element]["alarm class"] == "Message") { + bgcol = "green"; + } + newAlarm.id = element + "Alarm"; + newAlarm.className = "alarmRow"; + newAlarm.style.backgroundColor = bgcol; + let alarmHTML = "\n"+allAlarms[element]["alarm class"]+":"+allAlarms[element]["alarm message"]; + alarmHTML += "\n\n"; + newAlarm.innerHTML = alarmHTML; + } + } else { + if (document.getElementById(element + "Alarm") != null) { + document.getElementById(element + "Alarm").remove(); + } + } + } + } + }).catch(function(error){console.error(error);}); +} + +//**************************************************************************// +// Functions for Run Control tab // +//**************************************************************************// + +// Function to check run state and adjust controls accordingly +// run_state = -2 check ODB and adjust accordingly +// 1 run is stopped +// 2 run is paused +// 3 run is ongoing +function runStatus(run_state) { + mjsonrpc_db_get_values([instrODB["runStatus"]]).then(function(rpc) { + run_state = rpc.result.data[0]; + // Change accordingly in GUI + // due to strange behaviour of mjsonrpc I have to send action to different function + if (run_state == 1) { + // Stopped + runStatus_action(1); + } else if (run_state == 2) { + // Paused + runStatus_action(2); + } else if (run_state == 3) { + // Running + runStatus_action(3); + } + }).catch(function(error){console.error(error);}); +} + +// Function to set the buttons visibility according to run status +// run_state = 1 run is stopped +// 2 run is pauseden +// 3 run is ongoing +function runStatus_action(run_state) { + // No buttons to adjust + if (!document.getElementById("startButton")) return; + + let common_style = 'padding: 0.3em 0.5em 0.3em 0.5em;border-radius:10px;box-shadow: 5px 5px 5px grey;' + if (document.getElementById("runStatusBanner")) { + document.getElementById("runStatusBanner").innerHTML = ''; + } + let statText = ""; + let statCol = ""; + // Change accordingly in GUI + if (run_state == 1) { + // Stopped - red, make only Start visible + document.getElementById("startButton").disabled = false; + document.getElementById("stopButton").disabled = true; + document.getElementById("pauseButton").disabled = true; + document.getElementById("resumeButton").disabled = true; + document.getElementById("writeButton").disabled = true; + statCol = 'red'; + statText = 'Stopped'; + // Insert stop time + document.getElementById("stopTimetd").innerHTML = 'Stop time: '; + } else if (run_state == 2) { + // Paused - orange, make Stop and Resume visible + document.getElementById("startButton").disabled = true; + document.getElementById("stopButton").disabled = false; + document.getElementById("pauseButton").disabled = true; + document.getElementById("resumeButton").disabled = false; + document.getElementById("writeButton").disabled = false; + statCol = 'orange'; + statText = 'Paused'; + // Insert running time + document.getElementById("stopTimetd").innerHTML = 'Run time: '; + runningTime(run_state); + } else if (run_state == 3) { + // Running - green, make Stop and Pause visible + document.getElementById("startButton").disabled = true; + document.getElementById("stopButton").disabled = false; + document.getElementById("pauseButton").disabled = false; + document.getElementById("resumeButton").disabled = true; + document.getElementById("writeButton").disabled = false; + statCol = 'green'; + statText = 'Running'; + // Insert running time time + document.getElementById("stopTimetd").innerHTML = 'Run time: '; + runningTime(run_state); + } + let statusText = document.getElementById("statusText"); + statusText.style.backgroundColor = statCol; + statusText.innerHTML = statText; +} + +// Function to set the running time field +// run_state = 1 run is stopped +// 2 run is pauseden +// 3 run is ongoing +function runningTime(run_state) { + let stopTime = document.getElementById("stopTime"); + // If running or paused + if (run_state != 1) { + // hide stopped time + stopTime.style.visibility = "hidden"; + // show running time + mjsonrpc_db_get_values(["/Runinfo"]).then(function(rpc) { + runinfo = rpc.result.data[0]; + time = runinfo['start time binary/last_written']; + difftime = Math.round(new Date().getTime() / 1000) - time; + h = Math.floor(difftime / 3600); + m = Math.floor(difftime % 3600 / 60); + s = Math.floor(difftime % 60); + runTime = h + "h" + ((m<10)?"0"+m:m) + "m" + ((s<10)?"0"+s:s) + "s"; + document.getElementById("vstopTimetd").innerHTML = runTime; + }).catch(function(error){console.error(error);}); + } else { + // show stopped time + stopTime.style.visibility = "visible"; + } +} + +// Function to make link to musrfit +function updateFitLink() { + // ToDo: check measurement geometry and guess function/histos + let aelement = document.getElementById("musrfitRun"); + let fitlink = "http://musruser.psi.ch/cgi-bin/musrfit.cgi?"; + let belement = document.getElementById("SearchDBlink"); + let dblink = "http://musruser.psi.ch/cgi-bin/SearchDB.cgi?"; + let year = new Date().getFullYear(); + fitlink += "YEAR="+year; + fitlink += "&BeamLine="+instrName.split("-")[0]; + dblink += "YEAR="+year; + dblink += "&AREA="+instrName.split("-")[0]; + mjsonrpc_db_get_values([instrODB["runNumber"],instrODB["sampleName"]]).then(function(rpc) { + let runNumber = rpc.result.data[0]; + let sampleName = rpc.result.data[1]; + if (window.location.href.includes("/CS/Mudas")) + sampleName = sampleName.substring(0,9); + sampleName= sampleName.replaceAll("(","\\(").replaceAll(")","\\)"); + sampleName= sampleName.replaceAll("[","\\[").replaceAll("]","\\]"); + fitlink += "&RunNumbers="+runNumber; + dblink += "&Phrases="+ sampleName +"&go=Search"; + aelement.setAttribute("href",fitlink); + belement.setAttribute("href",dblink); + }).catch(function(error){console.error(error);}); +} + + + +//**************************************************************************// +// End of Run Control tab // +//**************************************************************************// + + +//**************************************************************************// +// Function for general use // +//**************************************************************************// + + +// Function to toggele div visible/hidden +function showHide(iddiv,sender) { + let totoggle = document.getElementById(iddiv); + if (totoggle === null) return; + let state = totoggle.style.display; + + if (state == 'none') { + totoggle.style.display = "block"; + } else { + totoggle.style.display = "none"; + } + + let symbol = sender.innerHTML; + if (symbol == "-") { + sender.innerHTML = "+"; + sender.title = "Show information row"; + } else if (symbol == "+") { + sender.innerHTML = "-"; + sender.title = "Hide information row"; + } else if (iddiv == "infoRow" && symbol == "🗖") { + sender.innerHTML = "🗗"; + sender.title = "Restore"; + } else if (iddiv == "infoRow" && symbol == "🗗") { + sender.innerHTML = "🗖"; + sender.title = "Maximize"; + } +} + +// Function to swap iddiv1 and iddiv2 positions +function swapDiv(iddiv1,iddiv2,arrow) { + let element1 = document.getElementById(iddiv1); + let element2 = document.getElementById(iddiv2); + + if (arrow.innerHTML == "\u2191") { + element1.parentNode.insertBefore(element1,element2); + arrow.innerHTML = "↓"; + arrow.title = "Move down"; + } else { + element2.parentNode.insertBefore(element2,element1); + arrow.innerHTML = "↑"; + arrow.title = "Move up"; + } +} + +// Function to compare proposal ID with DUO schedule +// TODO: if not matching highlight in red with option to change +function compProp(prop_odb,proposer_odb,pgrp_odb,flag) { + // flag = 0 - check values and highlight only + // = 1 - check, highlight and change on request + let fullname; + let d= new Date(); + d.setHours(d.getHours() - 6); + let curr_date = d.toISOString().slice(0,-5); + let instrument = instrName.toLowerCase(); + //let web_duo = 'https://duo.psi.ch/duo/rest.php/cal/smus/'+instrument+'/'+curr_date+'/?SECRET=change-bib-eva-grille'; + let web_duo = 'https://duo.psi.ch/duo/api.php/v1/CalendarInfos/scheduled/smus?beamline='+instrument+'&SECRET=change-bib-eva-grille'; + // let web_duo = 'https://duo.psi.ch/duo/rest.php/cal/smus/lem/'+curr_date+'/?SECRET=change-bib-eva-grille'; + console.log(web_duo); + fetch(web_duo,{method:'POST'}) + .then( data => data.json(), console.error) + .then( data => { + //console.log(data[0]); + let proposer_duo = "Thomas Prokscha"; + let prop_duo = "20210284"; + let pgrp_duo = "p18973"; + let extratxt = "\ndoes not match the empty schedule!\nShould I use the default values?"; + if (data[0] !== undefined) { + proposer_duo = data[0].firstname+" "+data[0].lastname; + prop_duo = data[0].proposal; + pgrp_duo = data[0].pgroup; + extratxt = "\ndoes NOT match schedule!\n"+prop_duo+"/"+proposer_duo+"/"+pgrp_duo+"\nShould I take the details from DUO?"; + } + if ((prop_odb != prop_duo) || (proposer_odb != proposer_duo) || (pgrp_odb != pgrp_duo)) { + //console.log('why am i here?', 'in:'+fullname,' out:'+proposer_odb ); + document.getElementById("propID").className = "propIDcorrect"; + document.getElementById("propGRP").className = "propIDcorrect"; + document.getElementById("propPI").className = "propIDcorrect"; + document.getElementById("propFromDuo").style.visibility = "visible"; + if (flag) { + if (confirm("Proposal ID\n"+prop_odb+"/"+proposer_odb+"/"+pgrp_odb+extratxt)) { + modbset(instrODB["pID"],prop_duo); + modbset(instrODB["pPI"],proposer_duo); + modbset(instrODB["pGRP"],pgrp_duo); + // Then reset highlights/button + document.getElementById("propID").className = ""; + document.getElementById("propGRP").className = ""; + document.getElementById("propPI").className = ""; + document.getElementById("propFromDuo").style.visibility = "hidden"; + } + } + } else { + document.getElementById("propID").className = ""; + document.getElementById("propGRP").className = ""; + document.getElementById("propPI").className = ""; + document.getElementById("propFromDuo").style.visibility = "hidden"; + } + // console.log('proper_duo:', data.firstname+" "+data.lastname); + }); +} + +// Function to check proposal ID against DUO schedule. +// If not matching highlight in red and show button +function propODB(flag) { + // flag = 0 - check values and highlight only + // = 1 - check, highlight and change on request + mjsonrpc_db_get_values([instrODB["pID"],instrODB["pPI"],instrODB["pGRP"]]) + .then(function(rpc) { + let prop_odb = rpc.result.data[0]; + let proposer_odb = rpc.result.data[1]; + let pgrp_odb = rpc.result.data[2]; + compProp(prop_odb,proposer_odb,pgrp_odb,flag); + }); +} + +// Function to change to selected tab +function openTab(evt, tab) { + // Declare all variables + var i, tabcontent, tablinks; + + // Get all elements with class="tabcontent" and hide them + tabcontent = document.getElementsByClassName("tabcontent"); + for (i = 0; i < tabcontent.length; i++) { + tabcontent[i].style.display = "none"; + } + + // Get all elements with class="tablinks" and remove the class "active" + tablinks = document.getElementsByClassName("w3-bar-item"); + for (i = 0; i < tablinks.length; i++) { + tablinks[i].className = tablinks[i].className.replace(" active", ""); + tablinks[i].className = tablinks[i].className.replace(" w3-gray", ""); + } + + // Default tab + if (tab === undefined) tab = 1; + let tabName = "Tab"+tab; + // Show the current tab, and add an "active" class to the button that opened the tab + document.getElementById(tabName).style.display = "block"; + evt.currentTarget.className += " active"; + evt.currentTarget.className += " w3-gray"; + + let reg = /tab=\d+/; + let url = window.location.href; + if (url.search("tab=") == -1) { + // if tab is not in url add it but check which version of midas we are dealing with + if (url.includes("/CS/Mudas")) { + url += "?tab="+tab; + } else { + url += "&tab="+tab; + } + } else { + // otherwise replace with new tab value + url = url.replace(reg,"tab="+tab) + } + if (url !== window.location.href) { + window.history.replaceState({}, "Mudas", url); + } + getVars["tab"] = tab; +} +//**************************************************************************// +// End general use // +//**************************************************************************// + + +//**************************************************************************// +// Function for AutoRun tab // +//**************************************************************************// +// Global variables +const LAR_STATE_STOPPED = 0; +const LAR_STATE_PAUSED = 1; +const LAR_STATE_STARTING = 2; +const LAR_STATE_RUNNING = 3; +const LAR_STATE_LOAD = 4; +const LAR_STATE_LOADING = 5; +const LAR_STATE_NEXT = 6; + +const LAR_TT_IDLE = 0; +const LAR_TT_FINISHED = 1; +const LAR_TT_ABORTED = 2; +const LAR_TT_WARMUP = 3; + +var larObj = {}; +var liveData = {}; +var larState; +var prevRunState = -1; +var transitionTag = LAR_TT_IDLE; +var firstValidRunState = true; +var larStateCol = 'red'; +var larStateText = 'Stopped'; + + +// Function to update AutoRun tab +function load_lar() { + // get autorun data from ODB + mjsonrpc_db_get_values(["/AutoRun"]).then(function(rpc) { + larObj = rpc.result.data[0]; + }).catch (function (error) { + console.error(error); + }); + + larState = larObj['run state']; + liveData = larObj['livedata']; + + if ((larState !== undefined) && firstValidRunState) { + firstValidRunState = false; + prevRunState = larState; + load_buttons(); + } + // check if the run state has changed + if (prevRunState != larState) { + prevRunState = larState; + load_buttons(); + // speed up update period at larState change + updatePeriod = 500; + startupCount = 0; + } + + if (liveData) { + transitionTag = liveData['transitiontag']; + update_lar_script(liveData, larObj['show comments']); + } +} + +// Function to parse AutoRun script into html +function update_lar_script(liveData, showComment) { + var errIdx=-1; + var num = ""; + var content="", str="", msg=""; + // This holds the autorun text + var lar = liveData['autorun']; + var errorNo = liveData['errorinline']; + var errorMsg = liveData['errormsg']; + var foundError = false; + var isComment = false; + + // check for fatal-errors without lar-script (e.g. missing, ...) + if (errorNo[0] == 0) { + content = "" + errorMsg[0] + ""; + document.getElementById('lar').innerHTML = content; + return; + } + if (errorNo[0] != -1) + foundError = true; + + // add sequence only loaded info + if ((liveData['currentlineno'] == -1) && (errorNo[0] == -1)) { + content = ">> SEQUENCE LOADED ONLY, PRESS START AUTORUN BOTTOM IF YOU WANT TO START IT <<\n"; + } + // in case there are errors display a prominent message at the begining + if (errorNo[0] != -1) { + content = ">> ERRORS ENTCOUNTERED, PLEASE FIX IT! <<\n"; + } + + // Send lar to syntax highlighting + lar = syntax_lar(lar); + + // normal lar-script handling + for (var i=0; i"; + + // check if it is the current line -> highlight + if ((liveData['currentlineno'] == (i+1)) && !foundError && (liveData['currentlineno'] <= lar.length)) { + if (transitionTag == LAR_TT_ABORTED) { + content += num + lar[i] + "\n"; + content += " ^--- AutoRun aborted here.\n"; + } else { + if (liveData['loopval'] == "empty") + content += "" + num + lar[i] + "\n"; + else + content += "" + num + lar[i] + " (LOOP_ELEMENT=" + liveData['loopval'] + ")\n"; + } + } else { + if (isComment) { + content += "" + num + lar[i] + "\n"; + } else { + if (liveData['loopval'] == "empty") + content += num + lar[i] + "\n"; + else + content += num + lar[i] + "\n"; + } + } + + // check for errors + errIdx = check_for_error(i, errorNo); + if (errIdx != -1) { + content += " ^---" + errorMsg[errIdx] + "\n"; + } + } + // Add autorun status + switch (transitionTag) { + case LAR_TT_FINISHED: + msg = ">> Autorun finished ...\n"; + str = content; + content = msg.concat(str); + content += msg; + break; + case LAR_TT_ABORTED: + msg = ">> Autorun aborted ...\n"; + str = content; + content = msg.concat(str); + content += msg; + break; + case LAR_TT_WARMUP: + msg = ">> Autorun finished ...\n"; + str = content; + content = msg.concat(str); + content += msg; + break; + default: + break; + } + // Fill html of script in appropriate div + document.getElementById('lar').innerHTML = content; + // Now you need to scrill to current line + // scrollToCurr(); +} + +function check_for_error(idx, errorNo) { + for (var i=0; i"+pars[i]+""); + } + + // Loops group + for (i=0;i"+loops[i]+""); + } + + + // Commands group + for (i=0;i"+cmds[i]+""); + } + + // Secondary Commands group + for (i=0;i"+cmdssec[i]+""); + } + + // These needs line by line treatment + for (j=0;j 0; } ); + // the first lar_tag + lar_text = lar_text.replaceAll(words[0],""+words[0]+""); + lar_text = lar_text.replaceAll(words[1],""+words[1]+""); + lar_text = lar_text.replaceAll(words[2],""+words[2]+""); + } + } + + // Break lines and handle one by one + lar = lar_text.split("\n"); + // Loop backwards, remove empty lines at end keeping only one + // then restore comment lines with no highlighting + let isEmpty = 1; + for (j=lar.length-3;j>=0;j--) { + let line = lar[j].trim(); + // Empty line skip it + if (line == "" & isEmpty == 1) { + // Remove empty lines (optional) + //lar.splice(j,1); + // Replace empty lines with
+ //lar[j] = "
"; + } else { + isEmpty = 0; + // Restore comment lines with no highlighting + if (line.startsWith("%")) { + lar[j]=lar_org[j]; + } + } + } + return lar; +} + +function scrollToCurr() { + // Clear any highlighted lines + let currLine = document.getElementsByClassName("lar_current_cmd"); + if (currLine[0]) { + currLine[0].scrollIntoView({ block: "center" }); + } +} + +function hlLine(line) { + let lineNum = line.split(",")[0]; + let lineId = "sline"+lineNum; + + // Clear any highlighted lines + let hlLines = []; + hlLines = [...document.getElementsByClassName("lar_current_cmd")]; + for (let i=0; i/First failed', where is the frontend name. +// 'First failed' == 0 means that the frontend is running. +// return value of the function: 1 if running, 0 otherwise. +function feIsRunning(frontend,elemID) { + mjsonrpc_call("cm_exist", { "name": frontend, "unique":true}).then(function(rpc) { + let state = (rpc.result.status === 1) ? 1 : 0; + let e = document.getElementById(elemID); + if (e) e.checked = (state === 1); + return state; + }).catch (function(error) { + console.error(error); + }); +} + +// This function starts/stops front end +// name - fronend name, e.g. "K2400_SC" +// action - Can be "start"/1 or "stop"/0 action +function eqStart (name,action) { + if (action.toLowerCase() === "start" || action === 1) { + console.log(Starting,name); + mjsonrpc_start_program(name); + } else if (action.toLowerCase() === "stop" || action === 0) { + console.log(Stopping,name); + mjsonrpc_stop_program(name); + } +} + +function cryoSetup(cryo) { + // Get new value from argument + // first compare to ODB, if it is the same return + mjsonrpc_db_get_values(["/Info/Sample Cryo"]).then(function(rpc) { + if (rpc.result.data[0] == cryo) { + return 0; + } else { + // variables for hide/show FE + let hide_sc,hide_ov,hide_om; + // variables for start/stop FE + let fe_sc,fe_ov,fe_om; + + // all equipment are hidden by default + hide_sc = "y"; + hide_ov = "y"; + hide_om = "y"; + hide_tfl = "y"; + // all FEs are off by default + fe_sc = "Stop"; + fe_ov = "Stop"; + fe_om = "Stop"; + fe_tfl = "Stop"; + if (cryo.startsWith("Konti")) { + hide_sc = "n"; + hide_tfl = "n"; + fe_sc = "Start"; + fe_tfl = "Start"; + } else if (cryo.startsWitt("LowTemp")) { + hide_sc = "n"; + fe_sc = "Start"; + } else if (cryo.startsWitt("Omega")) { + hide_om = "n"; + fe_om = "Start"; + } + + // Hide/Show SampleCryo/Oven/Omega + modbset("/Equipment/SampleCryo/Common/Hidden", hide_sc); + modbset("/Equipment/TFL/Common/Hidden", hide_tfl); + modbset("/Equipment/Omega/Common/Hidden", hide_om); + // The corresponding FE should be started/stopped + if (fe_sc == "Stop") { + mjsonrpc_stop_program("Sample_SC"); + } else if (fe_sc == "Start") { + mjsonrpc_start_program("Sample_SC"); + } + + if (fe_om == "Stop" && feIsRunning("Omega SC") != 0) { // only stop frontend if already running + eqStart("Omega SC",fe_om); + } else if (fe_om == "Start" && feIsRunning("Omega SC") == 0) { // only start frontend if not already running + eqStart("Omega SC",fe_om); + } + + if (fe_tfl == "Stop" && feIsRunning("TFL_SC") != 0) { // only stop frontend if already running + eqStart("TFL_SC",fe_tfl); + } else if (fe_tfl == "Start" && feIsRunning("TFL_SC") == 0) { // only start frontend if not already running + eqStart("TFL_SC",fe_tfl); + } + + // change the cryo setup string + modbset("/Info/Sample Cryo", cryo); + console.log("Setting cryostat to: " + cryo); + } + }).catch (function (error) {console.error(error);}); +} + + +function cs_ra_pulsing(val) +{ + // write RA pulsing state to the ODB + if (val) { + document.getElementById("PulsOn").style.visibility = "visible"; + } else { + document.getElementById("PulsOn").style.visibility = "hidden"; + } +} + +// This function disables/enables equipment +function eqEnable(element) +{ + let val = element.id; + // We expect the that val is the name of the Equipment in ODB + // /Equipment/val/... + //console.log("eqEnable: " + val); + + // The assumption is that the FronEnd Program is in "/Equipment/val/Common/Frontend name" + let feProgramODB = "/Equipment/"+val+"/Common/Frontend name"; + mjsonrpc_db_get_values([feProgramODB]).then(function(rpc) { + let feProgram = rpc.result.data[0]; + // toggle selection + onoff = document.getElementById(val).checked; + if ( onoff ) { + document.getElementById(val).checked = true; + // Make it visible on the Status page + modbset("/Equipment/"+val+"/Common/Hidden", "n"); + // If FronEnd is not running, then start it + if (feIsRunning(feProgram) == 0) { + eqStart(feProgram,"Start"); + } + } else { + document.getElementById(val).checked = false; + // Hide it on the Status page + modbset("/Equipment/"+val+"/Common/Hidden", "y"); + eqStart (feProgram,"Stop"); + } + }).catch (function (error) {mjsonrpc_error_alert(error);}); +} + + + +// For setting magnetic field +function setFieldCurrent(val,element) +{ + // Which magnet are we using? + // Get all calibration parameters to convert from Gauss to A + let sel_mag = ""; + console.log("Set Field ",val,"G"); + // First confirm the change + if (confirm('Are you sure you want to change the field?\nSet Field '+val+' G')) { + mjsonrpc_db_get_values(["/Info/LEM_Setup_Parameter/WEW", + "/Info/LEM_Setup_Parameter/Bpar", + "/Info/Magnet_Parameter/WEW", + "/Info/Magnet_Parameter/Bpar"]).then(function(rpc) { + let wew = rpc.result.data[0]; + let bpar = rpc.result.data[1]; + let pWEW = rpc.result.data[2]; + let pBpar = rpc.result.data[3]; + let Bcurrent = 0; + if (wew && !bpar) { + sel_mag = "WEW"; + console.log("Selected magnet is "+sel_mag); + Bcurrent = (val-pWEW[0])/pWEW[1]; + console.log("Set current: "+Bcurrent); + // Field higher than 100G, ba careful and check RA + if (val > 100) { + if (!confirm("The applied field is > 100G, is the RA off?")) { + // Bail out + return true; + } + } + if (Bcurrent > 40) { + // Uses WEWH + // WEWL 0 Cmd/1 Current + // WEWH 2 Cmd/3 Current + modbset("/Equipment/WEW/Variables/Output[1]",0); + modbset("/Equipment/WEW/Variables/Output[0]",0); + modbset("/Equipment/WEW/Variables/Output[2]",1); + modbset("/Equipment/WEW/Variables/Output[3]",Bcurrent); + console.log("Set WEWH ",Bcurrent); + } else { + // Uses WEWL + modbset("/Equipment/WEW/Variables/Output[3]",0); + modbset("/Equipment/WEW/Variables/Output[2]",0); + modbset("/Equipment/WEW/Variables/Output[0]",1); + modbset("/Equipment/WEW/Variables/Output[1]",Bcurrent); + consile.log("Set WEWL ",Bcurrent); + } + } else if (!wew && bpar) { + sel_mag = "Bpar"; + console.log("Selected magnet is "+sel_mag); + Bcurrent = (val-pBpar[0])/pBpar[1]; + console.log("Set Bpar "+Bcurrent); + modbset("/Equipment/Danfysik/Variables/Output[2]",Bcurrent); + } else if (!wew && !bpar) { + sel_mag = "none"; + console.log("Selected magnet is "+sel_mag); + console.log("Set current: "+Bcurrent); + } + }).catch (function (error) { console.error(error);}); + } + return true; +} + +function get_field_current() +{ + // Which magnet are we using? + // Get all calibration parameters to convert from A to Gauss + let sel_mag = ""; + mjsonrpc_db_get_values(["/Info/LEM_Setup_Parameter/WEW", + "/Info/LEM_Setup_Parameter/Bpar", + "/Info/Magnet_Parameter/WEW", + "/Info/Magnet_Parameter/Bpar", + "/Equipment/WEW/Variables/Output[1]", + "/Equipment/WEW/Variables/Output[3]", + "/Equipment/Danfysik/Variables/Output[2]"]).then(function(rpc) { + let wew = rpc.result.data[0]; + let bpar = rpc.result.data[1]; + let pWEW = rpc.result.data[2]; + let pBpar = rpc.result.data[3]; + let Bgauss = 0; + let Ival = 0; + let message = ""; + if (wew && !bpar) { + Ival = rpc.result.data[4]; + Bgauss = pWEW[1]*Ival+pWEW[0]; + message += "WEW="; + return Bgauss; + } else if (!wew && bpar) { + Ival = rpc.result.data[6]; + Bgauss = pBpar[1]*Ival+pBpar[0]; + return Bgauss; + } + }).catch (function (error) { console.error(error);}); +} + +function histRefresh() { + let allHists = document.getElementsByClassName("mjshistory"); + for (let i =0; i < allHists.length; i++) { + allHists[i].innerHTML= ""; + mhistory_init(allHists[i]); + } +} + +function Konti_Params() +{ + let Parameters = [ + '', + 'NV=%', + ' bar', + 'BH=', + ' l/min', + '%', + 'T= K', + 'Heater=%', + 'HV= kV', + 'E= keV', + 'B= G', + 'p= mbar'].join('\n'); + document.getElementById('Parameters').innerHTML = Parameters; +} + +function LowTemp_Params() +{ + let Parameters = [ + '', + ' l/min', + ' bar', + '%', + 'BH1=', + 'BH2=', + ' l/min', + ' mbar', + ' mbar', + 'T= K', + //'T= K', + 'Heater=%', + //'Heater=%', + 'HV= kV', + 'E= keV', + 'B= G', + 'p= mbar'].join('\n'); + document.getElementById('Parameters').innerHTML = Parameters; +} + +function Omega_Params() +{ + let Parameters = [ + '', + 'T= K', + 'HV= kV', + 'E= keV', + 'B= G', + 'p= mbar'].join('\n'); + document.getElementById('Parameters').innerHTML = Parameters; +} + +function Konti_Ctrl() +{ + let Konti_CTRL = [ + 'Sample Temperature: (K) |', + 'Ramp Rate: (K/min) |', + 'He Flow (BH): |', + 'Needle Valve: '].join(' '); + document.getElementById('Controls').innerHTML = Konti_CTRL; + document.getElementById('Controls').setAttribute("name","Konti"); + document.getElementById('Controls').style.textAlign = "center"; + document.getElementById('samplecryosvg').setAttribute("viewBox","2500 1200 23000 9000"); + + // Also show needle valve row from Run Control + if (document.getElementById('NVRow')) { + document.getElementById('NVRow').style.display = ''; + } +} + +function Konti_Histos() +{ + // let size= 'width: 360px; height: 200px;border: 1px solid black;'; + let size= 'width: 100%; height: 23vh;min-height: 200px;'; + let Hist3='
'; + let Hist2='
'; + let Hist1='
'; + document.getElementById('Hist1').innerHTML = Hist1; + document.getElementById('Hist2').innerHTML = Hist2; + document.getElementById('Hist3').innerHTML = Hist3; + //document.getElementById('Hist1').classList.add("w3-border"); + //document.getElementById('Hist2').classList.add("w3-border"); + //document.getElementById('Hist3').classList.add("w3-border"); +} + + +function LowTemp_Histos() +{ + // let size= 'width: 360px; height: 200px;border: 1px solid black;'; + let size= 'width: 100%; height: 23vh;min-height: 200px;'; + let Hist3 = '
'; + let Hist2 = '
'; + let Hist1 = '
'; + document.getElementById('Hist1').innerHTML = Hist1; + document.getElementById('Hist2').innerHTML = Hist2; + document.getElementById('Hist3').innerHTML = Hist3; + //document.getElementById('Hist1').classList.add("w3-border"); + //document.getElementById('Hist2').classList.add("w3-border"); + //document.getElementById('Hist3').classList.add("w3-border"); +} + +function LowTemp_Ctrl() +{ + let LowTemp_CTRL = [ + 'Sample Temperature: (K) |', + //'Sample Temperature: (K) |', + 'Ramp Rate: (K/min) |', + //'Ramp Rate: (K/min) |', + 'He Flow (BH1): |', + ' / (BH2): '].join('\n'); + document.getElementById('Controls').innerHTML = LowTemp_CTRL; + document.getElementById('Controls').setAttribute("name","LowTemp"); + document.getElementById('Controls').style.textAlign = "center"; + document.getElementById('samplecryosvg').setAttribute("viewBox","500 1200 25500 10000"); +} + +function Omega_Histos() +{ + // let size= 'width: 360px; height: 200px;border: 1px solid black;'; + let size= 'width: 100%; height: 23vh;min-height: 200px;'; + let Hist2 = '
'; + document.getElementById('Hist1').innerHTML = ""; + document.getElementById('Hist3').innerHTML = ""; + document.getElementById('Hist2').innerHTML = Hist2; + //document.getElementById('Hist1').classList.remove("w3-border"); + //document.getElementById('Hist3').classList.remove("w3-border"); + //document.getElementById('Hist2').classList.add("w3-border"); +} + +function Omega_Ctrl() +{ + let Omega_CTRL = [ + 'Sample Temperature: (C)/ (K)'].join('\n'); + document.getElementById('Controls').innerHTML = Omega_CTRL; + document.getElementById('Controls').setAttribute("name","Omega"); + document.getElementById('Controls').style.textAlign = "center"; + document.getElementById('samplecryosvg').setAttribute("viewBox","4000 1200 19500 6000"); + //document.getElementById('samplecryosvg').style.maxWidth = "60vw"; + //document.getElementById('samplecryosvg').style.maxHeight = "30vh"; +} + +function NoCryo() +{ + mjsonrpc_db_get_values(["/Info/LEM_Setup","/Info/Sample Cryo"]).then(function(rpc) { + let lem_setup = rpc.result.data[0]; + let lem_sample_cryo = rpc.result.data[1]; + let NoCryo = 'Not a Cryo Setup: lem_setup='+lem_setup+', lem_sample_cryo='+lem_sample_cryo; + document.getElementById('SVGholder').innerHTML = NoCryo; + }).catch (function (error) {mjsonrpc_error_alert(error);}); +} + + +function Konti_SVG() +{ + let KontiSVG = [ + '', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + '', + '', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ACP28', + ' ', + '', + '', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + '', + + '', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' He recovery', + ' ', + ' ', + ' ', + ' ', + ' ', + ''].join(''); + document.getElementById('SVGholder').innerHTML = KontiSVG; +} + +function LowTemp_SVG() +{ + let LowTempSVG = [ + '', + ' ', + '', + '', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ACP28', + ' ', + '', + '', + ' ', + ' ACP120', + ' ', + ' ', + ' ', + ' ', + ' ', + '', + '', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + '', + '', + '', + '', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' He recovery', + ' ', + ' ', + ' ', + ' ', + ' ', + ''].join(''); + document.getElementById('SVGholder').innerHTML = LowTempSVG; +} + +function Omega_SVG() +{ + let OmegaSVG = [ + '', + ' ', + ' N2 Line In', + '', + '', + ' ', + ' N2 Line Out', + '', + '', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ''].join(''); + document.getElementById('SVGholder').innerHTML = OmegaSVG; +} + +function Bpar_SVG(cryo) +{ + let coordinates = "26200,5300"; //26200,2300 + if (cryo == "Omega") { + coordinates = "16500,5000"; + } + let FieldSVG = [ + '', + ' ⊗', + ''].join(''); + let FieldSVGin = [ + '', + ' ⊙', + ''].join(''); + document.getElementById('FieldHolder').innerHTML = FieldSVG; +} + + +function Bperp_SVG(cryo) +{ + // translate(15500,4500) for Oven + // translate(18500,4500) for Konti/LT2 + let coordinates = "18500,4500"; + if (cryo == "Omega") { + coordinates = "15500,4500"; + } + let FieldSVG = [ + '', + ' ', + ''].join(''); + document.getElementById('FieldHolder').innerHTML = FieldSVG; +} + +function Muon_SVG() +{ + mjsonrpc_db_get_values(["/Info/SpinRot_Parameter/RotationAngle","/Info/Sample Cryo"]).then(function(rpc) { + let spinangle = rpc.result.data[0]; + let lem_sample_cryo = rpc.result.data[1]; + if (lem_sample_cryo.startsWith("Konti")) { + var coord = '(20000,2721)'; + } else if (lem_sample_cryo == "LowTemp-2") { + var coord = '(20800,3000)'; + } else if (lem_sample_cryo == "Omega") { + var coord = '(17000,2800)'; + } else { + var coord = '(20000,3000)'; + } + transform = 'translate'+coord+' rotate('+spinangle+',350,350)'; + let MuonSVG = [ + '', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ''].join('\n'); + if (document.getElementById('MuonHolder')) { + document.getElementById('MuonHolder').innerHTML = MuonSVG; + } + }).catch(function(error){console.error(error);}); +} + +function updateSamcryo() { + mjsonrpc_db_get_values(["/Info/Sample Cryo","/Info/LEM_Setup"]).then(function(rpc) { + let lem_sample_cryo = rpc.result.data[0]; + let lem_setup = rpc.result.data[1]; + // Check if Controls exists if not return + if (!document.getElementById("Controls")) return; + if (lem_sample_cryo.includes("Konti-")) { + if (document.getElementById("Controls").attributes["name"].value != "Konti") { + Konti_Ctrl(); + Konti_SVG(); + } + Konti_Histos(); + Konti_Params(); + } else if (lem_sample_cryo == "LowTemp-2") { + if (document.getElementById("Controls").attributes["name"].value != "LowTemp") { + LowTemp_Ctrl(); + LowTemp_SVG(); + } + LowTemp_Histos(); + LowTemp_Params(); + } else if (lem_sample_cryo == "Omega" || lem_sample_cryo == "Oven") { + if (document.getElementById("Controls").attributes["name"].value != "Omega") { + Omega_Ctrl(); + Omega_SVG(); + } + Omega_Histos(); + Omega_Params(); + } else { + NoCryo(); + } + + if (lem_setup == "Sample, Bpar") { + Bpar_SVG(lem_sample_cryo); + } else if (lem_setup == "Sample, WEW") { + Bperp_SVG(lem_sample_cryo); + } + histRefresh(); + }).catch(function(error){console.error(error);}); + + Muon_SVG(); +} + +// Begin: Functions for the APD calibration page +function turnoffon(Ch1,Ch2,Ch3) { + // store values in slots + storeODBvalue(Ch1); + storeODBvalue(Ch2); + storeODBvalue(Ch3); + + // set values to zero + modbset('/Equipment/HV Detectors/Variables/Demand['+Ch1+']', 0); + modbset('/Equipment/HV Detectors/Variables/Demand['+Ch2+']', 0); + modbset('/Equipment/HV Detectors/Variables/Demand['+Ch3+']', 0); +} + +function restoreVset(Ch1,Ch2,Ch3,Ch4) { + // get old values + let Vset1= document.getElementById("slot"+Ch1).innerHTML; + let Vset2= document.getElementById("slot"+Ch2).innerHTML; + let Vset3= document.getElementById("slot"+Ch3).innerHTML; + let Vset4= document.getElementById("slot"+Ch4).innerHTML; + + // set values to zero + if (Vset1 != 0) modbset('/Equipment/HV Detectors/Variables/Demand['+Ch1+']', Vset1); + if (Vset2 != 0) modbset('/Equipment/HV Detectors/Variables/Demand['+Ch2+']', Vset2); + if (Vset3 != 0) modbset('/Equipment/HV Detectors/Variables/Demand['+Ch3+']', Vset3); + if (Vset4 != 0) modbset('/Equipment/HV Detectors/Variables/Demand['+Ch4+']', Vset4); + + // clear old values + document.getElementById("slot"+Ch1).innerHTML = ""; + document.getElementById("slot"+Ch2).innerHTML = ""; + document.getElementById("slot"+Ch3).innerHTML = ""; + document.getElementById("slot"+Ch4).innerHTML = ""; +} + +function showSegment() { + // get segment name + let segName = document.getElementById("segments").value; + let tmp = document.getElementById("storage").value; + document.getElementById("storage").value = segName; + var chSeg = {}; + // These are the channel numbers in each segment + // Left + chSeg["LDI"]=[9,13,17,21]; + chSeg["LDO"]=[10,14,18,22]; + chSeg["LUI"]=[11,15,19,23]; + chSeg["LUO"]=[12,16,20,24]; + // Right + chSeg["RDI"]=[41,45,49,53]; + chSeg["RDO"]=[42,46,50,54]; + chSeg["RUI"]=[43,47,51,55]; + chSeg["RUO"]=[44,48,52,56]; + // Bottom + chSeg["BDI"]=[25,29,33,37]; + chSeg["BDO"]=[26,30,34,38]; + chSeg["BUI"]=[27,31,35,39]; + chSeg["BUO"]=[28,32,36,40]; + // Top + chSeg["TDI"]=[57,61,1,5]; + chSeg["TDO"]=[58,62,2,6]; + chSeg["TUI"]=[59,63,3,7]; + chSeg["TUO"]=[60,64,4,8]; + + // Now generate html code for the selected segment + let ch1=chSeg[segName][0]; + let ch2=chSeg[segName][1]; + let ch3=chSeg[segName][2]; + let ch4=chSeg[segName][3]; + let ch1odb=chSeg[segName][0]+29; + let ch2odb=chSeg[segName][1]+29; + let ch3odb=chSeg[segName][2]+29; + let ch4odb=chSeg[segName][3]+29; + // turn these off + let off1= ch2odb+','+ch3odb+','+ch4odb; + let off2= ch1odb+','+ch3odb+','+ch4odb; + let off3= ch1odb+','+ch2odb+','+ch4odb; + let off4= ch1odb+','+ch2odb+','+ch3odb; + let allCh= ch1odb+','+ch2odb+','+ch3odb+','+ch4odb; + let segHtml= ''; + document.getElementById("chSegment").innerHTML = segHtml; + let voltages = 'V (V)'; + document.getElementById("chVoltages").innerHTML = voltages; + let currents = 'I (uA)'; + document.getElementById("chCurrents").innerHTML = currents; + let vset = 'Restore ↑' + document.getElementById("Vsetstorage").innerHTML = vset; +} + +function chDemand(i) { + var xmlDoc; + var xmlFile = 'tabs/APD_ZF.xml'; + xmlhttp=new XMLHttpRequest(); + xmlhttp.open("GET",xmlFile,false); + if (xmlhttp.overrideMimeType){ + xmlhttp.overrideMimeType('text/xml'); + } + xmlhttp.send(); + xmlDoc=xmlhttp.responseXML; + var nNodes=xmlDoc.getElementsByTagName("hvCh")[i-30].childNodes; + var nCh=xmlDoc.getElementsByTagName("hvCh")[i-30].firstChild; + while (nCh.nodeName != "hvDemand") { + nCh = nCh.nextSibling; + } + var chDemand = nCh.firstChild.nodeValue * 1.0; + console.log('Demand value should be: '+chDemand); + showSegment("LDI"); + return(chDemand); +} + + +function readXml(xmlFile){ + var xmlDoc; + xmlhttp=new XMLHttpRequest(); + xmlhttp.open("GET",xmlFile,false); + if (xmlhttp.overrideMimeType){ + xmlhttp.overrideMimeType('text/xml'); + } + xmlhttp.send(); + xmlDoc=xmlhttp.responseXML; + var nNodes=xmlDoc.getElementsByTagName("hvCh")[0].childNodes; + var nCh=xmlDoc.getElementsByTagName("hvCh"); + + for (k = 0; k < nCh.length; k++) { + y = xmlDoc.getElementsByTagName("hvCh")[k].firstChild; + for (i = 0; i < nNodes.length; i++) //looping xml childnodes + { + if (y.nodeType == 1) { + console.log(y.nodeName + ":" + y.firstChild.nodeValue); + } + y = y.nextSibling; + } + console.log("-------------------"); + } +} + +function storeODBvalue (nCh) { + let ODBpath = "/Equipment/HV Detectors/Variables/Demand["+nCh+"]"; + let slot = "slot"+nCh; + mjsonrpc_db_get_values([ODBpath]).then(function(rpc) { + value = rpc.result.data[0]; + document.getElementById(slot).innerHTML = value.toFixed(2); + return value; + }) +} + +// End: Functions for the APD calibration page + +function mkEquipmentTable(equipment,starti = -1,endi = -1, tableID) { + // Create a html table of voltages + const names = "/Equipment/"+equipment+"/Settings/Names"; + const vardemand = "/Equipment/"+equipment+"/Variables/Demand"; + const varmeas = "/Equipment/"+equipment+"/Variables/Measured"; + const curr = "/Equipment/"+equipment+"/Variables/Current"; + const currlimit = "/Equipment/"+equipment+"/Settings/Current Limit"; + let eqFlag = 1; + // Place holders for demand and readback + const modb_edit = ""; + const modb_read = ""; + let table = "\n"; + + // Check which ODB keys are available + mjsonrpc_db_key([names,vardemand,varmeas,curr,currlimit]).then(function (rpc) { + // The usual number of columns of the table + let ncols = 3; + if (rpc.result.status[3] == 1 && rpc.result.status[4] == 1) { + // need extra columns + ncols = 5; + table += "\n"; + } else { + table += "\n"; + } + if (starti == -1) { + starti = 0; + //console.log(rpc.result.keys); + if (rpc.result.keys[0] !== null) { + endi = rpc.result.keys[0].num_values - 1; + } else { + eqFlag = 0; + } + } + + if (eqFlag) { + for (var i=starti;i"+odbName+"\n"; + row += "\n"; + row += "\n"; + if (ncols == 5) { + let odbCurr = modb_read.replace("dataODBPath",curr + "[" + i + "]"); + row += "\n"; + let odbCurrLim = modb_edit.replace("dataODBPath",currlimit + "[" + i + "]"); + row += "\n"; + } + table += "\n" + row + "\n"; + } + table += "
NameDemandMeasuredCurrentCurrent limit
NameDemandMeasured
"+odbDemand+""+odbMeasured+""+odbCurr+""+odbCurrLim+"
\n"; + } else { + let statusTable = loadAscii("/?cmd=eqtable&eq=" + equipment,1); + const parser = new DOMParser(); + const doc = parser.parseFromString(statusTable, "text/html"); + + const trElements = doc.querySelectorAll("tr"); + table = ""; + for (let i = 2; i< trElements.length; i++) { + table += trElements[i].outerHTML; + }; + table += "
"; + } + document.getElementById(tableID).innerHTML=table; + // return as promise ... + //return table; + }).catch(function (error) { + console.log(error); + }); +} + +// Begin: Functions for the HV Edit page + +// ToDo this function should check that the set value is within the limits +function checkEqLimit(value, element) { + return true; + console.log("value=",value); + console.log("element=",element); + let dataODBPath = element.getAttribute("data-odb-path"); + console.log("data-odb-path=",dataODBPath); +} + +function showHVtable() { + // get HV table name + let tableName = document.getElementById("HVSettings").value; + // Default is FUG + let equipment = "HV"; + let starti = 0; + let endi = 15; + if (tableName == "NHR") { + equipment = "HV Detectors"; + starti = 0; + endi = 7; + } else if (tableName == "PHVR400") { + equipment = "HV Detectors"; + starti = 8; + endi = 10; + } else if (tableName == "NHR400") { + equipment = "HV Detectors"; + starti = 20; + endi = 27; + } else if (tableName == "HPP30_107") { + equipment = "HV Detectors"; + starti = 28; + endi = 28; + } else if (tableName == "HPN30_107") { + equipment = "HV Detectors"; + starti = 29; + endi = 29; + } else if (tableName == "APD") { + equipment = "HV Detectors"; + starti = 30; + endi = 93; + } else if (tableName == "hvr80flame") { + equipment = "HV Detectors"; + starti = 0; + endi = 31; + } + mkEquipmentTable(equipment,starti,endi,"HVTable"); +} + +function openFile(event) { + let input = event.target; + let reader = new FileReader(); + reader.onload = function(){ + let text = reader.result; + let table = xmlToTable(text); + popModal("popPrompt"); + document.getElementById("popHTML").innerHTML = table; + document.getElementById("popButton").textContent = "Load"; + document.getElementById("popButton").addEventListener("click",loadHV); + document.getElementById("popButton").addEventListener("click",closeModal); + }; + reader.readAsText(input.files[0]); +} + +function xmlToTable(text) { + var parser = new DOMParser(); + var xmlDoc = parser.parseFromString(text,"text/xml"); + // Get device name and switch to it, otherwise loading will be a problem + let device = xmlDoc.getElementsByTagName("hvDeviceName")[0].innerHTML.trim(); + let description = xmlDoc.getElementsByTagName("description")[0].innerHTML.trim(); + // Take possible options and selected index + let HVoptions = document.getElementById("HVSettings").options; + let selDevice = document.getElementById("HVSettings").selectedIndex; + + // if the loaded field does not match selected device adjust + if (HVoptions[selDevice].value != device) { + console.log("changing from",HVoptions[selDevice].value," to ",device); + document.getElementById("HVSettings").value=device; + showHVtable(); + } + + // Parse XML file for settings + let names = xmlDoc.getElementsByTagName("name"); + let demands = xmlDoc.getElementsByTagName("hvDemand"); + let limits = xmlDoc.getElementsByTagName("currentLimit"); + + // Create preload table + var table = "\n"; + + table += "
"; + table += "\n"; + table += "\n" + for (let i=0; i"+name+"\n"; + table += "\n"; + table += "\n"; + table += "\n"; + } + table += "
NameDemandCurrent limit
  ☓    ☓  
Highlight (  ☓  ) cell to ignore.


Comment
"; + return table; +} + +// This function is used to toggle the highlight of selected cells +// in the HV and Beamline tables +function toggleColor(element) { + if (element.className == "tdSelectable") { + element.className = "tdSelected"; + } else if (element.className == "tdSelected") { + element.className = "tdSelectable"; + } else if (element.className == "tdIgnorable") { + element.className = "tdIgnored"; + } else if (element.className == "tdIgnored") { + element.className = "tdIgnorable"; + } +} + +// This function is used to toggle the highlight of all cells +// in the HV tables +// newState - all/none toggled to state +function toggleAll(tableID,newState) { + let selCells = []; + if (tableID) { + selCells = [...document.getElementById(tableID).getElementsByClassName("tdSelectable"), ...document.getElementById(tableID).getElementsByClassName("tdSelected")]; + } else { + selCells = [...document.getElementsByClassName("tdSelectable"), ...document.getElementsByClassName("tdSelected")]; + } + let curState = selCells[0].className; + + if (newState == "" || newState == undefined || newState == null) { + if (curState == "tdSelectable") { + var newState = "tdSelected"; + } else { + var newState = "tdSelectable"; + } + } + + // Loop over cells and set to new state + for (let i=0; i\n'; + doc += ' ' + (i+1) + '\n'; + doc += ' ' + odbname + '\n'; + doc += ' ' + odbdemand + '\n'; + doc += ' ' + odblimit + '\n'; + doc += '\n'; + } + doc += '\n'; + table = xmlToTable(doc); + download(doc,"HV.xml","text/plain"); + }).catch(function(error){console.error(error);}); + } +} + +function saveFileXML() { + // doc.appendChild(HVelem); + // xmlDoc.createElement("description"); + + // get HV device name + let device = document.getElementById("HVSettings").value; + + // Read HV details from ODB + // Default is FUG + let equipment = "HV"; + let starti = 0; + let endi = 15; + if (device == "NHR") { + equipment = "HV Detectors"; + starti = 0; + endi = 7; + } else if (device == "PHVR400") { + equipment = "HV Detectors"; + starti = 8; + endi = 10; + } else if (device == "NHR400") { + equipment = "HV Detectors"; + starti = 20; + endi = 27; + } else if (device == "HPP30_107") { + equipment = "HV Detectors"; + starti = 28; + endi = 28; + } else if (device == "HPN30_107") { + equipment = "HV Detectors"; + starti = 29; + endi = 29; + } else if (device == "APD") { + equipment = "HV Detectors"; + starti = 30; + endi = 93; + }else if (device == "hvr80flame") { + equipment = "hvr80flame0"; + starti = 0; + endi = 31; + } + + // Set correct odb paths + var names = "/Equipment/"+equipment+"/Settings/Names"; + var currlimit = "/Equipment/"+equipment+"/Settings/Current Limit"; + var vardemand = "/Equipment/"+equipment+"/Variables/Demand"; + + var doc = document.implementation.createDocument("http://nemu.web.psi.ch/HV", "", null); + var HVElem = doc.createElement("HV"); + + var commElem = doc.createElement("comment"); + var commtext = doc.createTextNode("this is a comment"); + commElem.appendChild(commtext); + HVElem.appendChild(commElem); + + var descElem = doc.createElement("description"); + var desctext = doc.createTextNode("this is a description"); + descElem.appendChild(desctext); + HVElem.appendChild(descElem); + + var devElem = doc.createElement("hvDeviceName"); + var devtext = doc.createTextNode(device); + devElem.appendChild(devtext); + HVElem.appendChild(devElem); + + for (let i=starti;i response.json()).then(data => { + // `data` contains the parsed JSON object + const path = data["/ODB path"]; + const names = data.Settings.Names; + const demands = data.Variables.Demand; + + // Create preload table + var table = "\n"; + table += "
"; + table += "\n"; + for (let i=0; i"+name+"\n"; + table += "\n"; + table += "\n"; + } + table += "
  ☓  
Highlight (  ☓  ) cell to ignore.
"; + + // Show table in dialog + popModal("popPrompt"); + document.getElementById("popHTML").innerHTML = table; + document.getElementById("popButton").textContent = "Load"; + document.getElementById("popButton").addEventListener("click",loadBL); + document.getElementById("popButton").addEventListener("click",closeModal); + }); +} + + + +// Function to load standard HV setting from server +function serverHVSet(filename){ + if (!filename) { + filename = document.getElementById("serverHVSet").value; + } + document.getElementById("curTransport").innerHTML = filename; + file_load_ascii(filename,function(content) { + //console.log(content); + let table = xmlToTable(content); + popModal("popPrompt"); + document.getElementById("popHTML").innerHTML = table; + document.getElementById("popButton").textContent = "Load"; + document.getElementById("popButton").addEventListener("click",loadHV); + document.getElementById("popButton").addEventListener("click",closeModal); + }); + // Change value back to none + document.getElementById("serverHVSet").value = "none"; +} + +function selColl(coll) { + let fillTrOpts = ` + + + + + + + + + + + + `; + if (coll == "1.5cm") { + fillTrOpts = ` + + + + + + `; + } else if (coll == "1.0cm") { + fillTrOpts = ` + + + + + + `; + } + document.getElementById("serverHVSet").innerHTML = fillTrOpts; +} + + +// End: Functions for the HV Edit page + +function highlight(e) { + let text= e.currentTarget.textContent; + let text_array = text.split("\n"); + let new_text = syntax_lar(text_array); + // var tex=element.innerHTML; + console.log(new_text); + e.currentTarget.innerHTML=new_text; + +} + +var mjsonvalue; +function modbget(path) { + mjsonrpc_db_get_value(path).then(function(rpc){ + mjsonvalue = rpc.result.data[0]; + // console.log("inside=",mjsonvalue); + }).catch (function (error) { console.error(error);}); +} + +// Function for RunLog +// ToDo: get the runlog file name from the ODB +// Path: /Logger/Data dir +// File name: ?? + +function LoadFile() { + var oFrame = document.getElementById("frmFile"); + var strRawContents = oFrame.contentWindow.document.body.childNodes[0].innerHTML; + // Get tne number of requested lines to show + var nlines = document.getElementById("numlines").value; + var dispLines = ""; + var tabLines = "RunStart Date::Time --- DurationStatisticsRun Title --- Propsal Number"; + // Clean up file if needed + while (strRawContents.indexOf("\r") >= 0) strRawContents = strRawContents.replace("\r", ""); + // Split file into lines + var arrLines = strRawContents.split("\n"); + console.log("number of lines in file ="+arrLines.length); + // The number of requested lines should not be larger than the actual number of lines + if (nlines > arrLines.length) { + nlines=arrLines.length-2; + document.getElementById("numlines").value = nlines; + } + for (var i = arrLines.length-2; i > arrLines.length-2-nlines; i--) { + var curLine = arrLines[i]; + var words = curLine.split('\t'); + var tabLine = "" + words[0] + "" + words[1] + "" + words[2] + "" + words[3] + ""; + dispLines = [dispLines,curLine].join('
\n'); + tabLines = [tabLines,tabLine].join('\n'); + } + document.getElementById('runlogtable').innerHTML = tabLines; +} + +function goSearchDB() { + var fromRun = document.getElementById("fromrun").value; + var toRun = document.getElementById("torun").value; + var year = new Date().getFullYear(); + if (fromRun > 0 && toRun > 0) { + // send to SearchDB.cgi + // http://musruser.psi.ch/cgi-bin/SearchDB.cgi?AREA=LEM&YEAR=2020&AFTER=&BEFORE=&RUN=&Rmin=100&Rmax=200&Phrases=&go=Search + var url = "http://musruser.psi.ch/cgi-bin/SearchDB.cgi?AREA=LEM&YEAR=" + year + "&AFTER=&BEFORE=&RUN=&Rmin=" + fromRun + "&Rmax=" + toRun + "&Phrases=&go=Search"; + window.open(url); + } +} + + + +// Function for Vacuum +// decoding bits for pump and valve states +const LV_BIT0=0x0100; +const LV_BIT1=0x0200; +const LV_BIT2=0x0400; +const LV_BIT3=0x0800; +const LV_BIT4=0x1000; +const LV_BIT5=0x2000; +const LV_BIT6=0x4000; +const LV_BIT7=0x8000; +const LV_BIT8=0x0001; +const LV_BIT9=0x0002; +const LV_BIT10=0x0004; +const LV_BIT11=0x0008; +const LV_BIT12=0x0010; +const LV_BIT13=0x0020; +const LV_BIT14=0x0040; +const LV_BIT15=0x0080; + +var lemvac_data_in = []; +var lemvac_data_out = []; +var lemvac_fe_state = -1; + + +function update_vacuum() { + + // get input/output data from ODB + mjsonrpc_db_get_values(["Equipment/LEMVAC/Variables/Input","Equipment/LEMVAC/Variables/Output"]).then(function(rpc) { + lemvac_data_in = rpc.result.data[0]; + lemvac_data_out = rpc.result.data[1]; + }).catch (function (error) { + mjsonrpc_error_alert(error); + }); + + // get state of the frontend + mjsonrpc_call("cm_exist", "{ \"name\": \"LEMVAC_SC\" }").then(function(rpc) { + lemvac_fe_state = rpc.result.status; + }).catch (function(error) { + mjsonrpc_error_alert(error); + }); + + lemvac(); + update_pressure_values(); + update_pressure_gauge_states(); + update_valve_states(); + update_pump_states(); +} + +function update_pressure_values() { + // piranni underneath the MC turbo + if (lemvac_data_in.length === 0) { + document.getElementById('MC_buffer_gauge_pressure').innerHTML = "undef"; + } else if (lemvac_data_in[1] <= 1.0e-4) { + document.getElementById('MC_buffer_gauge_pressure').innerHTML = "underrange"; + } else { + var val = lemvac_data_in[1].toExponential(2); + document.getElementById('MC_buffer_gauge_pressure').innerHTML = val + "mbar"; + } + // piranni MC + if (lemvac_data_in.length === 0) { + document.getElementById('MC_G1_high_pressure').innerHTML = "undef"; + } else if (lemvac_data_in[2] <= 1.0e-4) { + document.getElementById('MC_G1_high_pressure').innerHTML = "underrange"; + } else { + var val = lemvac_data_in[2].toExponential(2); + document.getElementById('MC_G1_high_pressure').innerHTML = val + "mbar"; + } + // 1st penning MC + if (lemvac_data_in.length === 0) { + document.getElementById('MC_G1_low_pressure').innerHTML = "undef"; + } else if (lemvac_data_in[3] <= 1.0e-11) { + if (lemvac_data_in[2] >= 1.0e-4) { // piranni above 1e-4 mbar + document.getElementById('MC_G1_low_pressure').innerHTML = "off"; + } else { + document.getElementById('MC_G1_low_pressure').innerHTML = "underrange"; + } + } else if (lemvac_data_in[3] > 1.0e-1) { + document.getElementById('MC_G1_low_pressure').innerHTML = "off"; + } else { + var val = lemvac_data_in[3].toExponential(2); + document.getElementById('MC_G1_low_pressure').innerHTML = val + "mbar"; + } + // 2nd penning MC + if (lemvac_data_in.length === 0) { + document.getElementById('MC_G2_low_pressure').innerHTML = "undef"; + } else if (lemvac_data_in[4] <= 1.0e-11) { + if (lemvac_data_in[2] >= 1.0e-4) { // piranni above 1e-4 mbar + document.getElementById('MC_G2_low_pressure').innerHTML = "off"; + } else { + document.getElementById('MC_G2_low_pressure').innerHTML = "underrange"; + } + } else if (lemvac_data_in[4] > 1.0e-1) { + document.getElementById('MC_G2_low_pressure').innerHTML = "off"; + } else { + var val = lemvac_data_in[4].toExponential(2); + document.getElementById('MC_G2_low_pressure').innerHTML = val + "mbar"; + } + + // piranni underneath the TC turbo + if (lemvac_data_in.length === 0) { + document.getElementById('TC_buffer_gauge_pressure').innerHTML = "undef"; + } else if (lemvac_data_in[5] <= 1.0e-4) { + document.getElementById('TC_buffer_gauge_pressure').innerHTML = "underrange"; + } else { + var val = lemvac_data_in[5].toExponential(2); + document.getElementById('TC_buffer_gauge_pressure').innerHTML = val + "mbar"; + } + // piranni TC + if (lemvac_data_in.length === 0) { + document.getElementById('TC_G1_high_pressure').innerHTML = "undef"; + } else if (lemvac_data_in[6] <= 1.0e-4) { + document.getElementById('TC_G1_high_pressure').innerHTML = "underrange"; + } else { + var val = lemvac_data_in[6].toExponential(2); + document.getElementById('TC_G1_high_pressure').innerHTML = val + "mbar"; + } + // 1st penning TC + if (lemvac_data_in.length === 0) { + document.getElementById('TC_G1_low_pressure').innerHTML = "undef"; + } else if (lemvac_data_in[7] <= 1.0e-11) { + if (lemvac_data_in[6] >= 1.0e-4) { // piranni above 1e-4 mbar + document.getElementById('TC_G1_low_pressure').innerHTML = "off"; + } else { + document.getElementById('TC_G1_low_pressure').innerHTML = "underrange"; + } + } else if (lemvac_data_in[7] > 1.0e-1) { + document.getElementById('TC_G1_low_pressure').innerHTML = "off"; + } else { + var val = lemvac_data_in[7].toExponential(2); + document.getElementById('TC_G1_low_pressure').innerHTML = val + "mbar"; + } + // 2nd penning TC + if (lemvac_data_in.length === 0) { + document.getElementById('TC_G2_low_pressure').innerHTML = "undef"; + } else if (lemvac_data_in[8] <= 1.0e-11) { + if (lemvac_data_in[6] >= 1.0e-4) { // piranni above 1e-4 mbar + document.getElementById('TC_G2_low_pressure').innerHTML = "off"; + } else { + document.getElementById('TC_G2_low_pressure').innerHTML = "underrange"; + } + } else if (lemvac_data_in[8] > 1.0e-1) { + document.getElementById('TC_G2_low_pressure').innerHTML = "off"; + } else { + var val = lemvac_data_in[8].toExponential(2); + document.getElementById('TC_G2_low_pressure').innerHTML = val + "mbar"; + } + + // piranni underneath the SC turbo + if (lemvac_data_in.length === 0) { + document.getElementById('SC_buffer_gauge_pressure').innerHTML = "undef"; + } else if (lemvac_data_in[9] <= 1.0e-4) { + document.getElementById('SC_buffer_gauge_pressure').innerHTML = "underrange"; + } else { + var val = lemvac_data_in[9].toExponential(2); + document.getElementById('SC_buffer_gauge_pressure').innerHTML = val + "mbar"; + } + // piranni SC + if (lemvac_data_in.length === 0) { + document.getElementById('SC_G1_high_pressure').innerHTML = "undef"; + } else if (lemvac_data_in[10] <= 1.0e-4) { + document.getElementById('SC_G1_high_pressure').innerHTML = "underrange"; + } else { + var val = lemvac_data_in[10].toExponential(2); + document.getElementById('SC_G1_high_pressure').innerHTML = val + "mbar"; + } + // 1st penning SC + if (lemvac_data_in.length === 0) { + document.getElementById('SC_G1_low_pressure').innerHTML = "undef"; + } else if (lemvac_data_in[11] <= 1.0e-11) { + if (lemvac_data_in[10] >= 1.0e-4) { // piranni above 1e-4 mbar + document.getElementById('SC_G1_low_pressure').innerHTML = "off"; + } else { + document.getElementById('SC_G1_low_pressure').innerHTML = "underrange"; + } + } else if (lemvac_data_in[11] > 1.0e-1) { + document.getElementById('SC_G1_low_pressure').innerHTML = "off"; + } else { + var val = lemvac_data_in[11].toExponential(2); + document.getElementById('SC_G1_low_pressure').innerHTML = val + "mbar"; + } + // 2nd penning TC + if (lemvac_data_in.length === 0) { + document.getElementById('SC_G2_low_pressure').innerHTML = "undef"; + } else if (lemvac_data_in[12] <= 1.0e-11) { + if (lemvac_data_in[10] >= 1.0e-4) { // piranni above 1e-4 mbar + document.getElementById('SC_G2_low_pressure').innerHTML = "off"; + } else { + document.getElementById('SC_G2_low_pressure').innerHTML = "underrange"; + } + } else if (lemvac_data_in[12] > 1.0e-1) { + document.getElementById('SC_G2_low_pressure').innerHTML = "off"; + } else { + var val = lemvac_data_in[12].toExponential(2); + document.getElementById('SC_G2_low_pressure').innerHTML = val + "mbar"; + } + + // piranni party line + if (lemvac_data_in.length === 0) { + document.getElementById('C_buffer_gauge_pressure').innerHTML = "undef"; + } else if (lemvac_data_in[13] <= 1.0e-4) { + document.getElementById('C_buffer_gauge_pressure').innerHTML = "underrange"; + } else { + var val = lemvac_data_in[13].toExponential(2); + document.getElementById('C_buffer_gauge_pressure').innerHTML = val + "mbar"; + } +} + +function update_pressure_gauge_states() { + if (lemvac_data_in.length === 0) { // no data yet + return; + } + + // piranni underneath the MC turbo + let val = lemvac_data_in[1]; + if (val <= 1.0e-4) { + lemvac_gauge('MC_buffer_gauge', 3); + } else if (val < 1.0e-2) { + lemvac_gauge('MC_buffer_gauge', 2); + } else if (val < 1.0) { + lemvac_gauge('MC_buffer_gauge', 1); + } else { + lemvac_gauge('MC_buffer_gauge', 0); + } + + // piranni/penning gauge state MC + val = lemvac_data_in[2]; + if (val <= 1.0e-4) { + lemvac_gauge('MC_G1', 3); + lemvac_gauge('MC_G2', 3); + } else { + var gj = lemvac_data_in[3]; + var gj2 = lemvac_data_in[4]; + if ((gj > 1.0e-11) && (gj < 1.0e-4) && (gj2 > 1.0e-11) && (gj2 < 1.0e-4)) { + lemvac_gauge('MC_G1', 3); + lemvac_gauge('MC_G2', 3); + } else if (val < 1.0e-2) { + lemvac_gauge('MC_G1', 2); + lemvac_gauge('MC_G2', 2); + } else if (val < 1.0) { + lemvac_gauge('MC_G1', 1); + lemvac_gauge('MC_G2', 1); + } else { + lemvac_gauge('MC_G1', 0); + lemvac_gauge('MC_G2', 0); + } + } + + // piranni underneath the TC turbo + val = lemvac_data_in[5]; + if (val <= 1.0e-4) { + lemvac_gauge('TC_buffer_gauge', 3); + } else if (val < 1.0e-2) { + lemvac_gauge('TC_buffer_gauge', 2); + } else if (val < 1.0) { + lemvac_gauge('TC_buffer_gauge', 1); + } else { + lemvac_gauge('TC_buffer_gauge', 0); + } + + // piranni/penning gauge state TC + val = lemvac_data_in[6]; + if (val <= 1.0e-4) { + lemvac_gauge('TC_G1', 3); + lemvac_gauge('TC_G2', 3); + } else { + var gj = lemvac_data_in[7]; + var gj2 = lemvac_data_in[8]; + if ((gj > 1.0e-11) && (gj < 1.0e-4) && (gj2 > 1.0e-11) && (gj2 < 1.0e-4)) { + lemvac_gauge('TC_G1', 3); + lemvac_gauge('TC_G2', 3); + } else if (val < 1.0e-2) { + lemvac_gauge('TC_G1', 2); + lemvac_gauge('TC_G2', 2); + } else if (val < 1.0) { + lemvac_gauge('TC_G1', 1); + lemvac_gauge('TC_G2', 1); + } else { + lemvac_gauge('TC_G1', 0); + lemvac_gauge('TC_G2', 0); + } + } + + // piranni underneath the SC turbo + val = lemvac_data_in[9]; + if (val <= 1.0e-4) { + lemvac_gauge('SC_buffer_gauge', 3); + } else if (val < 1.0e-2) { + lemvac_gauge('SC_buffer_gauge', 2); + } else if (val < 1.0) { + lemvac_gauge('SC_buffer_gauge', 1); + } else { + lemvac_gauge('SC_buffer_gauge', 0); + } + + // piranni/penning gauge state SC + val = lemvac_data_in[9]; + if (val <= 1.0e-4) { + lemvac_gauge('SC_G1', 3); + lemvac_gauge('SC_G2', 3); + } else { + var gj = lemvac_data_in[10]; + var gj2 = lemvac_data_in[11]; + if ((gj > 1.0e-11) && (gj < 1.0e-4) && (gj2 > 1.0e-11) && (gj2 < 1.0e-4)) { + lemvac_gauge('SC_G1', 3); + lemvac_gauge('SC_G2', 3); + } else if (val < 1.0e-2) { + lemvac_gauge('SC_G1', 2); + lemvac_gauge('SC_G2', 2); + } else if (val < 1.0) { + lemvac_gauge('SC_G1', 1); + lemvac_gauge('SC_G2', 1); + } else { + lemvac_gauge('SC_G1', 0); + lemvac_gauge('SC_G2', 0); + } + } + + // piranni of the party line + val = lemvac_data_in[13]; + if (val <= 1.0e-4) { + lemvac_gauge('C_buffer_gauge', 3); + } else if (val < 1.0e-2) { + lemvac_gauge('C_buffer_gauge', 2); + } else if (val < 1.0) { + lemvac_gauge('C_buffer_gauge', 1); + } else { + lemvac_gauge('C_buffer_gauge', 0); + } + +} + +function update_valve_states() { + if (lemvac_data_in.length === 0) { // no data yet + return; + } + + // BPVX + let val = lemvac_data_in[25]; + if (val & LV_BIT3) { // valve closed + lemvac_valve('BPVX', 1); + } else if ((val & LV_BIT4) && (val & LV_BIT2)) { // open AND enabled + lemvac_valve('BPVX', 0); + } else if ((val & LV_BIT4) && !(val & LV_BIT2)) { // open AND NOT enabled + lemvac_valve('BPVX', 3); + } else { + lemvac_valve('BPVX', 4); + } + + // BPVY + val = lemvac_data_in[26]; + if (val & LV_BIT3) { // valve closed + lemvac_valve('BPVY', 1); + } else if ((val & LV_BIT4) && (val & LV_BIT2)) { // open AND enabled + lemvac_valve('BPVY', 0); + } else if ((val & LV_BIT4) && !(val & LV_BIT2)) { // open AND NOT enabled + lemvac_valve('BPVY', 3); + } else { + lemvac_valve('BPVY', 4); + } + + // MC main valve + val = lemvac_data_in[14]; + if ((!(val & LV_BIT5) && !(val & LV_BIT6)) || + ((val & LV_BIT5) && (val & LV_BIT6))) { // valve state uncertain + lemvac_valve('MC_GV', 4); + } else if (val & LV_BIT5) { // valve closed + lemvac_valve('MC_GV', 1); + } else if (val & LV_BIT6) { // valve open + lemvac_valve('MC_GV', 0); + } else if (val & LV_BIT4) { // valve locked + lemvac_valve('MC_GV', 3); + } + + // MC fore valve + if ((!(val & LV_BIT7) && !(val & LV_BIT8)) || + ((val & LV_BIT7) && (val & LV_BIT8))) { // valve state uncertain + lemvac_valve('MC_BFV', 4); + } else if (val & LV_BIT7) { // valve closed + lemvac_valve('MC_BFV', 1); + } else if (val & LV_BIT8) { // valve open + lemvac_valve('MC_BFV', 0); + } + + // MC bypass valve + if ((!(val & LV_BIT9) && !(val & LV_BIT10)) || + ((val & LV_BIT9) && (val & LV_BIT10))) { // valve state uncertain + lemvac_valve('MC_BV', 4); + } else if (val & LV_BIT9) { // valve closed + lemvac_valve('MC_BV', 1); + } else if (val & LV_BIT10) { // valve open + lemvac_valve('MC_BV', 0); + } + + // MC venting valve + val = lemvac_data_in[15]; + if ((!(val & LV_BIT13) && !(val & LV_BIT14)) || + ((val & LV_BIT13) && (val & LV_BIT14))){ // valve state uncertain + lemvac_valve('MC_VV', 4); + } else if (val & LV_BIT13) { // valve closed + lemvac_valve('MC_VV', 1); + } else if (val & LV_BIT14) { // valve open + lemvac_valve('MC_VV', 0); + } + + // TC main valve + val = lemvac_data_in[17]; + if ((!(val & LV_BIT5) && !(val & LV_BIT6)) || + ((val & LV_BIT5) && (val & LV_BIT6))) { // valve state uncertain + lemvac_valve('TC_GV', 4); + } else if (val & LV_BIT5) { // valve closed + lemvac_valve('TC_GV', 1); + } else if (val & LV_BIT6) { // valve open + lemvac_valve('TC_GV', 0); + } else if (val & LV_BIT4) { // valve locked + lemvac_valve('TC_GV', 3); + } + + // TC fore valve + if ((!(val & LV_BIT7) && !(val & LV_BIT8)) || + ((val & LV_BIT7) && (val & LV_BIT8))) { // valve state uncertain + lemvac_valve('TC_BFV', 4); + } else if (val & LV_BIT7) { // valve closed + lemvac_valve('TC_BFV', 1); + } else if (val & LV_BIT8) { // valve open + lemvac_valve('TC_BFV', 0); + } + + // TC bypass valve + if ((!(val & LV_BIT9) && !(val & LV_BIT10)) || + ((val & LV_BIT9) && (val & LV_BIT10))) { // valve state uncertain + lemvac_valve('TC_BV', 4); + } else if (val & LV_BIT9) { // valve closed + lemvac_valve('TC_BV', 1); + } else if (val & LV_BIT10) { // valve open + lemvac_valve('TC_BV', 0); + } + + // TC venting valve + val = lemvac_data_in[18]; + if ((!(val & LV_BIT13) && !(val & LV_BIT14)) || + ((val & LV_BIT13) && (val & LV_BIT14))) { // valve state uncertain + lemvac_valve('TC_VV', 4); + } else if (val & LV_BIT13) { // valve closed + lemvac_valve('TC_VV', 1); + } else if (val & LV_BIT14) { // valve open + lemvac_valve('TC_VV', 0); + } + + // SC main valve + val = lemvac_data_in[20]; + if ((!(val & LV_BIT5) && !(val & LV_BIT6)) || + ((val & LV_BIT5) && (val & LV_BIT6))) { // valve state uncertain + lemvac_valve('SC_GV', 4); + } else if (val & LV_BIT5) { // valve closed + lemvac_valve('SC_GV', 1); + } else if (val & LV_BIT6) { // valve open + lemvac_valve('SC_GV', 0); + } else if (val & LV_BIT4) { // valve locked + lemvac_valve('SC_GV', 3); + } + + // SC fore valve + if ((!(val & LV_BIT7) && !(val & LV_BIT8)) || + ((val & LV_BIT7) && (val & LV_BIT8))) { // valve state uncertain + lemvac_valve('SC_BFV', 4); + } else if (val & LV_BIT7) { // valve closed + lemvac_valve('SC_BFV', 1); + } else if (val & LV_BIT8) { // valve open + lemvac_valve('SC_BFV', 0); + } + + // SC bypass valve + if ((!(val & LV_BIT9) && !(val & LV_BIT10)) || + ((val & LV_BIT9) && (val & LV_BIT10))) { // valve state uncertain + lemvac_valve('SC_BV', 4); + } else if (val & LV_BIT9) { // valve closed + lemvac_valve('SC_BV', 1); + } else if (val & LV_BIT10) { // valve open + lemvac_valve('SC_BV', 0); + } + + // SC venting valve + val = lemvac_data_in[21]; + if ((!(val & LV_BIT13) && !(val & LV_BIT14)) || + ((val & LV_BIT13) && (val & LV_BIT14))){ // valve state uncertain + lemvac_valve('SC_VV', 4); + } else if (val & LV_BIT13) { // valve closed + lemvac_valve('SC_VV', 1); + } else if (val & LV_BIT14) { // valve open + lemvac_valve('SC_VV', 0); + } + + // valve PZR1 + val = lemvac_data_in[23]; + if ((!(val & LV_BIT2) && !(val & LV_BIT3)) || + ((val & LV_BIT2) && (val & LV_BIT3))) { // valve state uncertain + lemvac_valve('RP1V', 4); + } else if (val & LV_BIT2) { // valve open + lemvac_valve('RP1V', 0); + } else if (val & LV_BIT3) { // valve closed + lemvac_valve('RP1V', 1); + } + + // valve PZR2 + if ((!(val & LV_BIT11) && !(val & LV_BIT12)) || + ((val & LV_BIT11) && (val & LV_BIT12))) { // valve state uncertain + lemvac_valve('RP2V', 4); + } else if (val & LV_BIT11) { // valve open + lemvac_valve('RP2V', 0); + } else if (val & LV_BIT12) { // valve closed + lemvac_valve('RP2V', 1); + } +} + +function update_pump_states() { + if (lemvac_data_in.length === 0) { // no data yet + return; + } + + // MC turbo pump + let val = lemvac_data_in[14]; + if ((val & LV_BIT0) && (val & LV_BIT3)) { // pump on and running > 80% + lemvac_turbo('mod_turbo', 0); + } else if (val & LV_BIT1) { // pump off + lemvac_turbo('mod_turbo', 1); + } else if (val & LV_BIT2) { // pumping running high < 80% + lemvac_turbo('mod_turbo', 3); + } else if (!(val & LV_BIT2) && (val & LV_BIT0) && !(val & LV_BIT3)) { + lemvac_turbo('mod_turbo', 4); // i.e. on, <80%, not running high + } + if (val & LV_BIT0) { // MC pump station manually off + // string to be placed, AS35 STILL MISSING + } else if (val & LV_BIT3) { // MC TCP turbo controller error + // string to be placed, AS35 STILL MISSING + } else if (val & LV_BIT4) { // MC turbo pump error + lemvac_turbo('mod_turbo', 2); // turbo pump error + } + + // TC turbo pump + val = lemvac_data_in[17]; + if ((val & LV_BIT0) && (val & LV_BIT3)) { // pump on and running > 80% + lemvac_turbo('trigger_turbo', 0); + } else if (val & LV_BIT1) { // pump off + lemvac_turbo('trigger_turbo', 1); + } else if (val & LV_BIT2) { // pumping running high < 80% + lemvac_turbo('trigger_turbo', 3); + } else if (!(val & LV_BIT2) && (val & LV_BIT0) && !(val & LV_BIT3)) { + lemvac_turbo('trigger_turbo', 4); // i.e. on, <80%, not running high + } + if (val & LV_BIT0) { // TC pump station manually off + // string to be placed, AS35 STILL MISSING + } else if (val & LV_BIT3) { // TC TCP turbo controller error + // string to be placed, AS35 STILL MISSING + } else if (val & LV_BIT4) { // TC turbo pump error + lemvac_turbo('trigger_turbo', 2); // turbo pump error + } + + // SC turbo pump + val = lemvac_data_in[20]; + if ((val & LV_BIT0) && (val & LV_BIT3)) { // pump on and running > 80% + lemvac_turbo('sample_turbo', 0); + } else if (val & LV_BIT1) { // pump off + lemvac_turbo('sample_turbo', 1); + } else if (val & LV_BIT2) { // pumping running high < 80% + lemvac_turbo('sample_turbo', 3); + } else if (!(val & LV_BIT2) && (val & LV_BIT0) && !(val & LV_BIT3)) { + lemvac_turbo('sample_turbo', 4); // i.e. on, <80%, not running high + } + if (val & LV_BIT0) { // SC pump station manually off + // string to be placed, AS35 STILL MISSING + } else if (val & LV_BIT3) { // SC TCP turbo controller error + // string to be placed, AS35 STILL MISSING + } else if (val & LV_BIT4) { // SC turbo pump error + lemvac_turbo('sample_turbo', 2); // turbo pump error + } + + // rough pump 1 + val = lemvac_data_in[23]; + if (val & LV_BIT0) { // pump on + lemvac_rough('rough_pump_1', 0); + } else { + lemvac_rough('rough_pump_1', 1); + } + // rough pump 2 + if (val & LV_BIT9) { // pump on + lemvac_rough('rough_pump_2', 0); + } else { + lemvac_rough('rough_pump_2', 1); + } +} + +function lemvac_turbo(name, state) { + let st = '#dfdf00'; + let fi = '#000000'; + let st_w = 2; + // select the proper colors depending on the state + switch (state) { + case 0: // > 80% + st = '#000000'; + fi = '#00af00'; + break; + case 1: // off + st = '#dfdf00'; + fi = '#000000'; + break; + case 2: // error + st = '#000000'; + fi = '#cf0000'; + break; + case 3: // < 80% + st = '#000000'; + fi = '#f0d000'; + break; + case 4: // < running out + st = '#000000'; + fi = '#00c8f0'; + break; + default: + break; + } + let el = document.getElementsByClassName(name); + for (let i=0; i 1 mbar + st = '#000000'; + fi = '#ef0000'; + break; + case 1: // p < 1 mbar + st = '#000000'; + fi = '#f0d000'; + break; + case 2: // p < 1e-2 mbar + st = '#000000'; + fi = '#00af00'; + break; + case 3: // p < 1e-4 mbar + st = '#000000'; + fi = '#3030ff'; + break; + default: + break; + } + document.getElementById(name).style.fill = fi; + document.getElementById(name).style.stroke = st; + document.getElementById(name).style.strokeWidth = st_w; +} + +function bpv_toggle(valve) { + if (valve == 0) { // BPVX + if (lemvac_data_out[0] == 1) { + if (confirm("Do you really want to toggle the BPVX state?")) { // yes + modbset("Equipment/LEMVAC/Variables/Output[1]", 1); + } + } + } else if (valve == 1) { // BPVY + if (lemvac_data_out[2] == 1) { + if (confirm("Do you really want to toggle the BPVY state?")) { // yes + modbset("Equipment/LEMVAC/Variables/Output[3]", 1); + } + } + } +} + +function lemvac() { + lemvac_turbo('mod_turbo', 0); + lemvac_turbo('trigger_turbo', 0); + lemvac_turbo('sample_turbo', 1); + lemvac_rough('rough_pump_1', 1); + lemvac_rough('rough_pump_2', 0); + lemvac_valve('BPVX', 1); + lemvac_valve('BPVY', 0); + lemvac_valve('MC_GV', 1); + lemvac_valve('MC_BV', 1); + lemvac_valve('MC_BFV', 1); + lemvac_valve('MC_VV', 1); + lemvac_gauge('MC_G1', 3); + lemvac_gauge('MC_G2', 3); + lemvac_gauge('MC_buffer_gauge', 1); + lemvac_valve('TC_GV', 1); + lemvac_valve('TC_BV', 1); + lemvac_valve('TC_BFV', 1); + lemvac_valve('TC_VV', 1); + lemvac_gauge('TC_G1', 3); + lemvac_gauge('TC_G2', 3); + lemvac_gauge('TC_buffer_gauge', 1); + lemvac_valve('SC_GV', 1); + lemvac_valve('SC_BV', 1); + lemvac_valve('SC_BFV', 1); + lemvac_valve('SC_VV', 1); + lemvac_gauge('SC_G1', 3); + lemvac_gauge('SC_G2', 3); + lemvac_gauge('SC_buffer_gauge', 1); + lemvac_valve('RP1V', 1); + lemvac_valve('RP2V', 0); + lemvac_gauge('C_buffer_gauge', 1); +} + +// Functions for autorun editor + +// Insert block into autorun +function insertLARBlock(element) { + let elId = element.id; + let larEditor = document.getElementById("larEditor"); + let enablePop = document.getElementById("enablePop").checked; + let text; + let html = "

"; + if (elId == "tempLoop") { + // Sample temperature loop + text = "LOOP_START\n"; + text += " LOOP_LIST [tempValues]\n"; + text += " LOOP_TEMP LOOP_ELEMENT, tempTol, tempTimeout, tempRate\n"; + text += " TITLE titleVal\n"; + text += " START stats\n"; + text += "LOOP_END\n"; + // Prompt for values + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + } else if (elId == "hvLoop") { + // Sample HV loop + text = "LOOP_START\n"; + text += " LOOP_LIST [hvValues]\n"; + text += " LOOP_SAMPLE_HV LOOP_ELEMENT\n"; + text += " TITLE titleVal\n"; + text += " START stats\n"; + text += "LOOP_END\n"; + // Prompt for values + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + } else if (elId == "setTemp") { + // Set temperature command + text = "TEMP tempVal, tempTol, tempTimeout, tempRate\n"; + // Prompt for values + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + } else if (elId == "setField") { + // Set temperature command + text = "FIELD fieldVal G\n"; + // Prompt for values + html += ""; + html += ""; + } else if (elId == "degMagnet") { + // Set temperature command + text = "DEGAUSS_MAGNET\n"; + // No need for pop + enablePop = false; + } else if (elId == "setSR") { + // Set temperature command + text = "SPIN_ROT srVal\n"; + // Prompt for values + html += ""; + html += ""; + } else if (elId == "setSamHV") { + // Set temperature command + text = "SAMPLE_HV hvVal\n"; + // Prompt for values + html += ""; + html += ""; + } else if (elId == "setRA") { + // Set temperature command + text = "RA_HV raLVal,raRVal,raTVal,raBVal\n"; + // Prompt for values + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + } else if (elId == "setODB") { + // Set temperature command + text = "ODB_SET_DATA odbPath, odbVal\n"; + // Prompt for values + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + } else if (elId == "warmupDate") { + // Set temperature command + text = "WARMUP dateVal, timeVal, vent\n"; + // Prompt for values + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + } else if (elId == "trHV") { + // Set temperature command + text = "TRANSPORT_HV xml_filename\n"; + // Prompt for values + html += ""; + html += ""; + html += ""; + // fillxmlHVSel('/home/nemu/nemu/midas/experiment/nemu/hv_settings','*.xml','xmlHVSel','xml_filename'); + } else if (elId == "setTitle") { + // Set temperature command + text = "TITLE titleVal\n"; + text += "START stats\n"; + // Prompt for values + html += ""; + html += ""; + html += ""; + html += ""; + } + + + // Finish html block + html += "
Temperature list (comma separated or from:step:to)
K
Tolerance: K
Time Out: sec
Rate: K/min
Title:
Stats: Events
Sample HV list (comma separated or from:step:to)
kV
Title:
Stats: Events
Temperature: K
Tolerance: K
Time Out: sec
Rate: K/min
Field: G
SR Angle:°
Sample HV: kV
Left: kV
Right: kV
Top: kV
Bottom: kV
ODB Path:
Set Value:
Date:
Time:
Vent:
Transport filename:
Title:
Stats: Events

Block:
"+text+"
"; + + let sel, range, newNode; + newNode = document.createElement("pre"); + newNode.id = "tmpID"; + // Cursor in editing + larEditor.focus(); + if (document.getSelection) { + sel = document.getSelection(); + // If anything is selected + if (sel.getRangeAt && sel.rangeCount) { + // Only if cursor is in larEditor + if (larEditor.contains(sel.getRangeAt(0).startContainer)) { + range = sel.getRangeAt(0); + range.deleteContents(); + range.insertNode(newNode); + } else { + alert("Cursor must be in the editing area!"); + return(0); + } + } else { + alert("Cursor must be in the editing area!"); + return(0); + } + } + + if (enablePop) { + let d = popModal("popPrompt"); + newNode.innerHTML = "
preparing ....
"; + document.getElementById("popHTML").innerHTML = html; + document.getElementById("popButton").textContent = "Submit"; + document.getElementById("popButton").addEventListener("click",promptParams); + document.getElementById("popButton").addEventListener("click",closeModal); + document.getElementById("popButton").addEventListener("click",checkSyntax); + + const observer = new MutationObserver(() => { + let preparing = document.getElementById("preparing"); + if (preparing) preparing.remove(); + }); + observer.observe(d, {attributes: true}); + } else { + // Use defaults + text = subLARDefaults(text); + newNode.innerHTML = text; + checkSyntax(); + } +} + +// Close pop modal cleanly +function closeModal() +{ + let caller = document.getElementById("popPrompt"); + if (caller) caller.remove(); +} + +// This function populates a modal with a general html +function popModal(iddiv,x,y) { + // First make sure you removed exisitng iddiv + if (document.getElementById(iddiv)) document.getElementById(iddiv).remove(); + let d = document.createElement("div"); + d.className = "dlgFrame"; + d.id = iddiv; + d.style.zIndex = "30"; + d.shouldDestroy = true; + + d.innerHTML = ` +
Mudas dialog
+
+
+ +
+ `; + document.body.appendChild(d); + dlgShow(d); + + if (x !== undefined && y !== undefined) + dlgMove(d, x, y); + + return d; +} + +// This function populates a modal with a general html +function general_dialog(html = "", iddiv = "dlgGeneral", width = 600, height = 350, x, y) { + /* general file dialog containing html code, optional parameters + iddiv - give the dialog a name + width/height - minimal width/height of dialog + x/y - initial position of dialog + */ + + // if empty html ignore + //if (html === "" || html === undefined) return; + // First make sure you removed exisitng iddiv + if (document.getElementById(iddiv)) document.getElementById(iddiv).remove(); + let d = document.createElement("div"); + d.className = "dlgFrame"; + d.id = iddiv; + d.style.zIndex = "30"; + d.style.overflow = "hidden"; + d.style.resize = "both"; + d.style.minWidth = width + "px"; + d.style.minHeight = height + "px"; + d.style.width = width + "px"; + d.style.height = height + "px"; + d.shouldDestroy = true; + + const dlgTitle = document.createElement("div"); + dlgTitle.className = "dlgTitlebar"; + dlgTitle.id = "dlgMessageTitle"; + dlgTitle.innerText = "General dialog"; + d.appendChild(dlgTitle); + + const dlgPanel = document.createElement("div"); + dlgPanel.className = "dlgPanel"; + dlgPanel.id = "dlgPanel"; + d.appendChild(dlgPanel); + + const content = document.createElement("div"); + content.id = "dlgHTML"; + content.style.overflow = "auto"; + content.innerHTML = html; + dlgPanel.appendChild(content); + + document.body.appendChild(d); + dlgShow(d); + + if (x !== undefined && y !== undefined) + dlgMove(d, x, y); + + // adjust select size when resizing modal + const resizeObs = new ResizeObserver(() => { + content.style.height = (d.offsetHeight - dlgTitle.offsetHeight - 5 ) + "px"; + }); + resizeObs.observe(d); + + return d; +} + +// Thist function extracts values from popPrompt +function promptParams() { + let parEls = document.getElementsByClassName("prompPar"); + let textBlock = document.getElementById("textBlock").innerText; + let key,value; + for (let i=0;i toT && stepT>0) || (fromT < toT && stepT<0)) {stepT = -1*stepT;} + value = fromT; + let currT = fromT; + while ((1+(currT-toT)/stepT) < 0) { + //console.log((currT-toT)/stepT); + currT = Math.round((currT + stepT)*100)/100; + value += ", "+currT; + } + } + // Special case tempRate is empty or zero + //console.log(key,value); + if (key == "tempRate" && (isNaN(value) || value == 0 )) { + key = ", tempRate"; + value = ""; + } else if (key == "ventCheck" && !parEls[i].checked) { + key = ", vent"; + value =""; + } + + textBlock = textBlock.replace(key,value); + } + let tmpID = document.getElementById("tmpID"); + tmpID.innerHTML = textBlock; + tmpID.removeAttribute('id'); +} + +// This function substitutes defaults in lar blocks +function subLARDefaults(text) { + let defaults = {tempValues : "290,200,100,50,20,10,5" , + tempVal : "100" , + tempTol : "0.5" , + tempTimeout : "1200", + ", tempRate" : "", + stats : "3e6", + hvValues : "10, 9, 8", + fieldVal : "100", + srVal : "-10" , + hvVal : "5", + raLVal : "0" , + raRVal : "0" , + raTVal : "0" , + raBVal : "0" , + titleVal : "ODB_SAMPLE, T=ODB_TEMP K, E=ODB_ENERGY keV, B=ODB_FIELD, Tr/Sa=ODB_TRANSP/ODB_HV_SAMP kV, SR=ODB_SPIN_ROT", + dateVal : "2019-09-11:", + timeVal : "07:30:00", + odbPath : "/Equipment/", + odbVal : "??"}; + + for (let key in defaults) { + let reg = new RegExp(key); + text = text.replace(key,defaults[key]); + } + return text; +} + + +// Function to detect key press in editor area +function keyPressEditor(event,element) { + let keyCode = ('which' in event) ? event.which : event.keyCode; + // console.log(keyCode); + // Space = 32, Enter = 13, Esc = 27, Tab=9 + if (keyCode === 9 ) { + return 1; + } else { + return 0; + } +} + +function getCaretIndex(element) { + let position = 0; + const isSupported = typeof window.getSelection !== "undefined"; + if (isSupported) { + const selection = window.getSelection(); + if (selection.rangeCount !== 0) { + const range = window.getSelection().getRangeAt(0); + const preCaretRange = range.cloneRange(); + preCaretRange.selectNodeContents(element); + preCaretRange.setEnd(range.endContainer, range.endOffset); + position = preCaretRange.toString().length; + } + } + return position; +} + +// Move caret to a specific point in a DOM element +function setCaretPosition(element, pos) { + // Loop through all children nodes + for (var node of element.childNodes) { + if (node.nodeType == 3) { // we have a text node + if (node.length >= pos) { + // finally add our range + var range = document.createRange(); + var sel = window.getSelection(); + range.setStart(node,pos); + range.collapse(true); + sel.removeAllRanges(); + sel.addRange(range); + return -1; // we are done + } else { + pos -= node.length; + } + } else { + pos = setCaretPosition(node,pos); + if (pos == -1) { + return -1; // no need to finish the for loop + } + } + } + return pos; // needed because of recursion stuff +} + +function checkSyntaxEvent() { + let larEditor = document.getElementById("larEditor"); + // Add even listener to editor area + document.getElementById('larEditor').addEventListener('keydown', (event) => { + if (event.key === ' ' || event.key === 'Enter' || event.key === ',') { + checkSyntax(); + } + }); +} + + +function checkSyntax() { + let larEditor = document.getElementById("larEditor"); + larEditor.focus(); + let line = larEditor.innerText.substr(larEditor.selectionStart).split("\n"); + let sel = document.getSelection(); + let range = sel.getRangeAt(0); + let pos = range.startOffset; + let posNode = range.startContainer; + let caretPos = getCaretIndex(larEditor); + //TODO: Hotfix, improve to not be Browser specific: + if (event.key === 'Enter') { + if (navigator.userAgent.toLowerCase().includes('firefox')){//if firefox + if ((window.navigator.userAgent.match(/Firefox\/([0-9]+)\./)? parseInt(match[1]) : 0 )>127){//check version + caretPos=caretPos-1;//adjust caretPosition + } + } + }// + + let text = larEditor.innerText; + if (instrName == "LEM") { + text = syntax_lar(text.split("\n")); + text = text.join("
"); + } else if (instrName == "LEYLA") { + text = syntax_msl(text.split("\n")); + text = text.join("
"); + } else { + text = syntaxSeq(text).replaceAll(/\d+:\s+/g,""); + text = text.replaceAll(/\n/g,"
") + } + larEditor.innerHTML = text; + range=document.createRange(); + sel.removeAllRanges(); + range.selectNodeContents(larEditor); + range.collapse(false); + sel.addRange(range); + larEditor.focus(); + setCaretPosition(larEditor,caretPos); +} + +function saveLAR(inFile) { + // get LAR text + let larEditor = document.getElementById("larEditor"); + let text = larEditor.innerText; + // Generate name from Sample and download file + //mjsonrpc_db_get_values(["/Info/Sample Name"]).then(function(rpc) { + // inFile = rpc.result.data[0].replaceAll("/","-")+".lar"; + download(text,inFile,"text/plain"); + // }).catch(function(error){console.error(error);}); +} + +function clearLAR() { + // get LAR text + let larEditor = document.getElementById("larEditor"); + if (confirm("Do you want to clear the sequence?")) { + larEditor.innerHTML = ""; + } +} + +// Function to load and ascii file +// async read, be careful with use +function loadAscii(file,flag){ + var xhttp,content; + if (file == "" || file == undefined || file == null) { + return 0; + } else { + // Make an HTTP request using the attribute value as the file name: + xhttp = new XMLHttpRequest(); + xhttp.onreadystatechange = function() { + if (this.readyState == 4) { + if (this.status == 404) { + console.log("File "+file+" not found."); + } + } + } + file += flag ? "" : "?" + Date(); + xhttp.open("GET", file, false); + xhttp.send(); + return(xhttp.responseText); + } +} + + +// Function to load file from client - Not used in Mudas +function loadLARFile(event) { + let input = event.target; + let reader = new FileReader(); + let larEditor = document.getElementById("larEditor"); + + reader.onload = function(){ + var text = reader.result; + larEditor.innerHTML = text; + checkSyntax(); + }; + reader.readAsText(input.files[0]); +} + +// Function to load file from server +function loadLARText(filename) { + let reader = new FileReader(); + let larEditor = document.getElementById("larEditor"); + // Split autoRunPath by '/' and take last + let path = autoRunPath.split('/').pop()+'/'; + filename = path + filename; + let text = loadAscii(filename); + larEditor.innerHTML = text; + checkSyntax(); +} + +// Save file to server, idea taken from the sequencer of Midas +function saveAsLAR() { + let larEditor = document.getElementById("larEditor"); + let script = larEditor.innerText; + let filename = document.getElementById("filenameDlg").value; + let fileext = filename.slice(-4); + // Check if filename is empty or does not have .lar extension + if (filename == "") { + alert("Illegal empty file name! Please provide a file name."); + return; + } else if (!(fileext == ".lar" || fileext == ".seq")) { + alert("Illegal file name extension '"+fileext+"'! Please try again."); + return; + } + fileext = "*" + fileext; + + document.getElementById("editFileName").innerText = filename; + // Flag for "Load as autorun" and "Set as next autorun" + let fn2autorun = false; + let fn2next = false; + if (document.getElementById("fn2autorun")) {fn2autorun = document.getElementById("fn2autorun").checked;} + if (document.getElementById("fn2next")) {fn2next = document.getElementById("fn2next").checked;} + // Check if file already exists + var reqlist = [ + mjsonrpc_make_request("db_get_values", {"paths":["/Sequencer/State/Path"]}), + mjsonrpc_make_request("any_list_files", {"subdir":"","fileext":fileext,"path":autoRunPath}), + ]; + var reqsave = [ + mjsonrpc_make_request("seq_save_script", {"filename":filename,"script":script}), + ]; + mjsonrpc_send_request(reqlist).then(function (rpc1) { + let fList = getListFiles(rpc1); + if (fList.indexOf(filename) > -1) { + // File exists, overwrite? + if (confirm("File " + filename + " exists. Overwrite it?")) { + // Yes, go ahead and overwrite + mjsonrpc_send_request(reqsave).then(function (rpc2) { + if (rpc2[0].result.status != 1) { + throw new Error("Cannot save file, error: " + rpc2[0].result.error); + } else { + // to auto run check also state + if (fn2autorun & larState == LAR_STATE_STOPPED) { + // Load sequence + setCurrentLAR(filename) + } else if (fn2next) { + if (instrName == "LEM") { + modbset("/AutoRun/Next",filename); + } else { + modbset("/AutoRun/Cmd/Next",filename); + } + } + } + return filename; + }).catch(function (error) {console.error(error);}); +} + } else { + mjsonrpc_send_request(reqsave).then(function (rpc2) { + if (rpc2[0].result.status != 1) { + throw new Error("Cannot save file, error: " + rpc2[0].result.error); + } else { + // to auto run check also state + if (fn2autorun & larState == LAR_STATE_STOPPED) { + // Load sequence + setCurrentLAR(filename); + } else if (fn2next) { + if (instrName == "LEM") { + modbset("/AutoRun/Next",filename); + } else { + modbset("/AutoRun/Cmd/Next",filename); + } + } + } + return filename; + }).catch(function (error) {console.error(error);}); + } + }).catch(function (error) {console.error(error);}); + return 0; +} + +// Save file to server, possible only in sequencer odbpath +function save_script_as() { + let html = "

"; + html += ""; + html += ""; + html += "
Save script as ...

"; + html += "
"; + // This option allowed only if there is no autorun running already + if (larState == LAR_STATE_STOPPED) { + html += "
"; + } + html += ""; + html += "
"; + popModal("popPrompt"); + document.getElementById("popHTML").innerHTML = html; + document.getElementById("popButton").textContent = "Save"; + document.getElementById("popButton").addEventListener("click",saveAsLAR); + document.getElementById("popButton").addEventListener("click",closeModal); + + let filename = document.getElementById("editFileName").innerText; + if (filename == "" || filename == "none") { + // Try to take the current autorun name + filename = document.getElementById("autoRunFN").innerText; + if (filename == "" || filename == "none") { + filename = "filename.lar"; + } + } + document.getElementById("filenameDlg").value = filename; +} + +// Function to load a file from client +// filePath - path of fiels to load +function loadFile(filePath) { + var result = null; + var xmlhttp = new XMLHttpRequest(); + xmlhttp.open("GET", filePath, true); + xmlhttp.send(); + if (xmlhttp.status==200) { + result = xmlhttp.responseText; + } + return result; +} + +// Function to load a file from server +// pathName - relative subdirectory of fiels to load +// ext - extension of files to load +// popBox - ID of div modal +// funcCall - call back function when/if file is selected +function loadFilePath(pathName,ext,popBox,funcCall) { + let html = '
'; + html += ''; + html += ''; + html += ''; + html += '
Select a file:
Directory: msg_directory
'; + popModal(popBox); + document.getElementById("popHTML").innerHTML = html; + document.getElementById("popHTML").style.overflow = "hidden"; + document.getElementById("popButton").textContent = "Load"; + document.getElementById("popButton").addEventListener("click",funcCall); + // Fucus on fileSelect so user can scroll by typing + document.getElementById("fileSelect").focus(); + let fileName = document.getElementById("editFileName").innerText; + + var req = [ + mjsonrpc_make_request("db_get_values", {"paths":["/Sequencer/State/Path"]}), + mjsonrpc_make_request("any_list_files", {"subdir":"","fileext":ext,"path":pathName}), + ]; + mjsonrpc_send_request(req).then(function (rpc) { + let fList = getListFiles(rpc); + makeSelectFiles(fList,funcCall,pathName); + }).catch(function (error) {console.error(error);}); +} + +// Callback function to load a selected script from LAR Editor +function loadScript() { + let fileName = document.getElementById("fileSelect").value; + document.getElementById("editFileName").innerText = fileName; + document.getElementById("popPrompt").remove(); + loadLARText(fileName); +} + +// Callback function to fill value in field +// iddiv - ID of field to be filled +function fileSelValue() { + let fileName = document.getElementById("fileSelect").value; + document.getElementById("xml_filename").value = document.getElementById("xml_filename").value + fileName; +} + +// Callback function to set selected sequence and load it +function setCurrentLAR(fileName) { + // if the file name is not delivered, get it from fileSelect + if (typeof fileName !== "string") { + fileName = document.getElementById("fileSelect").value; + } + if (document.getElementById("popPrompt")) document.getElementById("popPrompt").remove(); + if (instrName == "LEM") { + modbset("/AutoRun/Auto Run Sequence",fileName); + // Load sequence + set_lar_state(4) + } else if (instrName == "LEYLA") { + modbset("/Sequencer/Command/Load filename",fileName); + modbset("/Sequencer/Command/Load new file",true); + } else { + // Bulk machines + sessionStorage.setItem('AutorunFileName',fileName); + mjsonrpc_db_paste(['/Autorun/Cmd/Atransition'],[1]).then(function(rpc) { + mjsonrpc_db_paste(["/Autorun/File/File"],[sessionStorage.getItem('AutorunFileName')]).then(function(rpc) { + sessionStorage.removeItem('AutorunFileName'); + }).catch(function(error) {mjsonrpc_error_alert(error);}); + }).catch(function(error) {mjsonrpc_error_alert(error);}); + //leave Atransition on 1. + updateSeq(fileName); + } +} + +// Callback function to set selected next sequence +function setNextLAR() { + let fileName = document.getElementById("fileSelect").value; + if (instrName == "LEM") { + modbset("/AutoRun/Next",fileName); + } else { + // Bulk machines: Ignore Atransition for setting next + modbset("/Autorun/Cmd/Next",fileName); + } + if (document.getElementById("popPrompt")) document.getElementById("popPrompt").remove(); +} + + +function dragElement(elmnt) { + var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0; + if (document.getElementById(elmnt.id + "header")) { + // if present, the header is where you move the DIV from: + document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown; + } else { + // otherwise, move the DIV from anywhere inside the DIV: + elmnt.onmousedown = dragMouseDown; + } + + function dragMouseDown(e) { + e = e || window.event; + e.preventDefault(); + // get the mouse cursor position at startup: + pos3 = e.clientX; + pos4 = e.clientY; + document.onmouseup = closeDragElement; + // call a function whenever the cursor moves: + document.onmousemove = elementDrag; + } + + function elementDrag(e) { + e = e || window.event; + e.preventDefault(); + // calculate the new cursor position: + pos1 = pos3 - e.clientX; + pos2 = pos4 - e.clientY; + pos3 = e.clientX; + pos4 = e.clientY; + // set the element's new position: + elmnt.style.top = (elmnt.offsetTop - pos2) + "px"; + elmnt.style.left = (elmnt.offsetLeft - pos1) + "px"; + } + + function closeDragElement() { + // stop moving when mouse button is released: + document.onmouseup = null; + document.onmousemove = null; + } +} + +var mjsonvalue; +function test() { + // console.log("I am in test"); + //mjsonvalue = modbget("/Info/Sample Cryo"); + //console.log("value=",mjsonvalue); + //eqList(); + //console.log(eqListArray); + mjsonrpc_db_get_values(["/Equipment"]).then(function(rpc){ + //let eqListArray = Object.keys(rpc.result.data[0]) + //console.log(eqListArray); + let result = rpc.result.data[0]; + console.log(result) + /*for (let key in result) { + console.log(key); + }*/ + }); +} + +var eqListArray = []; +function eqList() { + let eqTable = ""; + // Get equipment list in array + + mjsonrpc_db_ls(["/Equipment"]).then(function (rpc) { + eqListArray = Object.keys(rpc.result.data[0]); + //console.log("Eq = ",eqListArray); + for (let i=0; i < eqListArray.length; i++) { + //console.log("Eq = ",eqListArray[i]); + eqTable += "" + eqListArray[i] + ""; + eqTable += ""; + eqTable += "test"; + } + document.getElementById("eqTable").innerHTML = eqTable; + return eqListArray; + }).catch(function (error) {console.error(error);}); +} + +function eqTable_dialog(equipment, width = 600, height = 350, x, y) { + if (equipment === undefined) + return; + + const d = document.createElement("div"); + d.className = "dlgFrame"; + d.id = "dlg" + equipment; + d.style.zIndex = "30"; + // allow resizing modal + d.style.overflow = "hidden"; + d.style.resize = "both"; + d.style.minWidth = width + "px"; + d.style.minHeight = height + "px"; + d.style.width = width + "px"; + d.style.height = height + "px"; + d.shouldDestroy = true; + + const dlgTitle = document.createElement("div"); + dlgTitle.className = "dlgTitlebar"; + dlgTitle.id = "dlgMessageTitle"; + dlgTitle.innerText = "Equipment dialog"; + d.appendChild(dlgTitle); + + const dlgPanel = document.createElement("div"); + dlgPanel.className = "dlgPanel"; + dlgPanel.id = "dlgPanel"; + d.appendChild(dlgPanel); + + const divTable = document.createElement("div"); + divTable.style.overflow = "auto"; + const eqTable = document.createElement("table"); + eqTable.className = "mtable dialogTable"; + eqTable.id = "eqTable_" + equipment; + eqTable.style.border = "none"; + eqTable.style.width = "100%"; + eqTable.style.overflow = "auto"; + + const colTitles = eqTable.createTHead(); + colTitles.innerHTML = ` + + Name + + + Modified + + + Size + + + `; + eqTable.appendChild(document.createElement("tbody")); + divTable.appendChild(eqTable); + dlgPanel.appendChild(divTable); + mkEquipmentTable(equipment,-1,-1,eqTable.id); + const fContainer = document.createElement("div"); + fContainer.id = "fContainer"; + fContainer.style.width = "100%"; + fContainer.style.paddingTop = "5px"; + fContainer.style.paddingBottom = "3px"; + dlgPanel.appendChild(fContainer); + const btnContainer = document.createElement("div"); + btnContainer.id = "btnContainer"; + btnContainer.style.paddingBottom = "3px"; + dlgPanel.appendChild(btnContainer); + + /* + const dlgButton = document.createElement("button"); + dlgButton.className = "dlgButtonDefault"; + dlgButton.id = "dlgButton"; + dlgButton.type = "button"; + btnContainer.appendChild(dlgButton); + */ + const dlgCancelBtn = document.createElement("button"); + dlgCancelBtn.className = "dlgButtonDefault"; + dlgCancelBtn.id = "dlgCancelBtn"; + dlgCancelBtn.type = "button"; + dlgCancelBtn.textContent = "Cancel"; + dlgCancelBtn.addEventListener("click", function () { + document.removeEventListener("keydown", tableClickHandler); + d.remove(); + }); + btnContainer.appendChild(dlgCancelBtn); + + document.body.appendChild(d); + dlgShow(d); + + if (x !== undefined && y !== undefined) + dlgMove(d, x, y); + + // adjust select size when resizing modal + const resizeObs = new ResizeObserver(() => { + divTable.style.height = (d.offsetHeight - dlgTitle.offsetHeight - fContainer.offsetHeight - btnContainer.offsetHeight - 5 ) + "px"; + }); + resizeObs.observe(d); + + // Add key navigation + document.addEventListener("keydown", tableClickHandler); + + return d; + +} + +/* The following functions are modifications of midas functions that will + most probably never make it to the main development branch */ +// Bypass dlg shit +function dlgMessage(title, string, modal, error, callback, param) { + let d = document.createElement("div"); + // Redirect the message to the console + if (string) { + console.log("dlgMessage: ",string); + } + // Return an empty
+ return d; +} + +function drawCloseButton(c, mark) { + if (!c.getContext) + return; + let ctx = c.getContext("2d"); + ctx.clearRect(0, 0, c.width, c.height); + ctx.lineWidth = 0.5; + ctx.beginPath(); + ctx.arc(c.width/2, c.height/2, c.width/2-1, 0, 2*Math.PI); + ctx.fillStyle = 'white'; + ctx.fill(); + ctx.strokeStyle = 'gray'; + ctx.stroke(); + if (mark) { + ctx.beginPath(); + ctx.arc(c.width/2, c.height/2, c.width/2, 0, 2*Math.PI); + ctx.fillStyle = '#FD5E59'; + ctx.fill(); + } + ctx.strokeStyle = '#000000'; + ctx.beginPath(); + ctx.lineWidth = 1; + ctx.moveTo(c.width/2-3, c.height/2-3); + ctx.lineTo(c.width/2+3, c.height/2+3); + ctx.moveTo(c.width/2+3, c.height/2-3); + ctx.lineTo(c.width/2-3, c.height/2+3); + ctx.stroke(); +} + + +//**************************************************************************// +// File: mvariables.js // +// Copyright (C) 2024 by Jonas A. Krieger // +// jonas.krieger@psi.ch // +//**************************************************************************// + +//**************************************************************************// +// Functions to address midas variables by name // +// variable must be saved under a standardized path: // +// /Equipment/EqName/Variables/Buffer[someindex] // +// with a name defined in // +// /Equipment/EqName/Settings/Names Buffer[sameindex] // +//**************************************************************************// + + +// Function to run onload to setup needed options and update period of GUI +// Called only once, onload. +function mvar_init() { + + let mvars = getMElements("mvarvalue").concat(getMElements("mvarbox"),getMElements("mvarcheckbox"), + getMElements("mvarselect")); + for (let i = 0; i < mvars.length; i++) { + let o = mvars[i]; + if (o.dataset.equipment !== undefined && o.dataset.varname !== undefined && o.dataset.buffer !== undefined ) { + var name_config="/Equipment/"+o.dataset.equipment+"/Settings/Names "+o.dataset.buffer; + //optional config + var unit_config="/Equipment/"+o.dataset.equipment+"/Settings/Unit "+o.dataset.buffer; + var format_config="/Equipment/"+o.dataset.equipment+"/Settings/Format "+o.dataset.buffer; + mjsonrpc_db_get_values([name_config,unit_config,format_config]).then(function(rpc) { + var names = rpc.result.data[0]; + var units=rpc.result.data[1]; + var formats=rpc.result.data[2]; + if (Array.isArray(names)){ + let index=names.indexOf(o.dataset.varname ); + o.setAttribute("data-odb-path","/Equipment/"+o.dataset.equipment+"/Variables/"+o.dataset.buffer+"["+index.toString()+"]"); + if (o.getAttribute('name')=='mvarvalue'){o.setAttribute("name","modbvalue");} + else if (o.getAttribute('name')=='mvarbox'){o.setAttribute("name","modbbox");} + else if (o.getAttribute('name')=='mvarcheckbox'){o.setAttribute("name","modbcheckbox");} + else if (o.getAttribute('name')=='mvarselect'){o.setAttribute("name","modbselect");} + + //optional formatting: + if (Array.isArray(formats)){ + o.setAttribute("data-format",formats[index]); + } + if (Array.isArray(units)){ + let unit = document.createElement('span'); + unit.innerHTML = ' '+ units[index]; + o.parentElement.appendChild(unit); + } + } else { + o.innerHTML = "
Variable " +o.dataset.varname +" not found.
"; + } + } ) + + } else { + o.innerHTML = "
Variable ill-defined.
"; + } + } + // trigger refresh + mhttpd_refresh(); +} + + + +function frappy_enum_init() { + + let frappynum = getMElements("frappy_enum"); + for (let i = 0; i < frappynum.length; i++) { + let o = frappynum[i]; + if (o.dataset.equipment !== undefined && o.dataset.varname !== undefined ) { + var enum_config="/Equipment/"+o.dataset.equipment+"/Settings/Devices/FrappyNode/DD/enums/"+o.dataset.varname; + mjsonrpc_db_get_values([enum_config,]).then(function(rpc) { + var config = rpc.result.data[0]; + if (config != null){ + for (key in config) { + if (! key.includes('/')){ + let opt = document.createElement('option'); + opt.value = key; + opt.innerHTML = config[key]; + o.appendChild(opt); + } + } + } else { + //configuration missing. + } + } ) + } + + } +} diff --git a/pages/MudasB.js b/pages/MudasB.js new file mode 100644 index 0000000..c5dadb6 --- /dev/null +++ b/pages/MudasB.js @@ -0,0 +1,1806 @@ +//**************************************************************************// +// Copyright (C) 2020-2025 by Zaher Salman // +// zaher.salman@psi.ch // +// jonas.krieger@psi.ch // +//**************************************************************************// + +//**************************************************************************// +// Functions for general Mudas use // +//**************************************************************************// + +var updateTimerId = 0; +var updatePeriod = 1000; // in msec +var startupCount = 0; + +// Function to run onload to setup needed options and update period of GUI +// Called only once, onload. +function Mudas_init_once() { + // update run state + runStatus(-2); + // hide side menu + // mhttpd_show_menu(0); + // Check proposal ID against DUO + try { + propODB(0); + } catch(e){} + + // Update link to musrfit + updateFitLink(); + // Update autorun page + init_seq(); + // Update runinfo this clashes with Deltat + //updateRuninfo(); + // monitoring function + //monitor(); + // add event listiners to lar editor area + //TODO: renable for sequencer + //checkSyntaxEvent(); + + //init variables by name + mvar_init(); + frappy_enum_init() + + // Issue warning for non-approved instruments + if ((instrName != "FLAME")&&(instrName != "GPS")&&(instrName != "Dolly")) { + alert("WARNING\nPlease do not use this page if you do not know what you are doing.\nThis page is under heavy development and should be used by experts only.\nBy continuing you agree to take responsibility for any damge to the experiment or loss of beam time."); + } + // Finally call function configured in the init file + if (typeof onloadFunc === 'function') + onloadFunc(); + + + // Select requested tab by clicking on it. + document.getElementById(getVars["tab"]).click(); + +} + +// Function to run onload to setup needed options and update of GUI +// this function is called periodically +function Mudas_init() { + // HIPA status update + document.getElementById("HIPAimg").src = "http://gfa-status.web.psi.ch/hipa-info-1024x768.png" + "?" + Date(); + + // AutoRun update + //load_lar(); + + // Check alarms + triggerAlarms(); + + // Running time update + // This is a workaround, needed only for running time + runStatus(-2); + + // timing update + clearTimeout(updateTimerId); + if (updatePeriod > 0) { + if (updatePeriod == 500) { + startupCount++; + if (startupCount > 2) + updatePeriod = 3000; + } + updateTimerId = setTimeout('Mudas_init()', updatePeriod); + } +} + +// My monitoring function for autorun transitions +function monitor() { + /* + mjsonrpc_db_get_values(["/muSR/td_musr/runinfo/runtitle"]).then(function (rpc) { + console.log("monitor:",rpc) + }).catch(function(error){console.error(error);}); + + mjsonrpc_db_get_values(["/Equipment/tdcv11900/"]).then(function(rpc) { + console.log("Monitor:"); + console.log(JSON.stringify(rpc.result.data[0],undefined, 2)); + }).catch(function(error){console.error(error);}); + */ +} + +// Change run title according to individual ODB of sample, temp, field and orientation +// Call manually as it can cause Deltat to crap out +function chRunTitle() { + mjsonrpc_db_get_values([instrODB["sampleName"],instrODB["sampleTemp"],instrODB["magField"],instrODB["sampleOrient"]]).then(function(rpc) { + // First turn off onchange trigger of runinfo + //if (document.getElementById("sampleNameOld")) { + // document.getElementById("sampleNameOld").removeEventListener("change",updateRuninfo); + //} + let sample = rpc.result.data[0]; + sample = sample.substring(0,10).trim(); + let temp = rpc.result.data[1]; + temp = temp.toString().substring(0,10).trim()+"K"; + if (temp.length < 11) {temp = temp.replace("K"," K");} + let field = rpc.result.data[2]; + console.log(field); + if (field == null) field = "0"; + field = field.toString().substring(0,10).trim()+"G"; + if (field.length < 11) { + field = field.replace("G"," G"); + field = field.replace("T"," T"); + } + let orient = rpc.result.data[3]; + orient = orient.substring(0,10).trim(); + let runtitle = sample.padEnd(10,' ') + temp.padEnd(10,' ') + field.padEnd(10,' ') + orient.padEnd(10,' '); + console.log("chRunTitle() --"+runtitle+"--"); + }).catch(function(error){console.error(error);}); +} + +// This function is triggered by the "Modify" button to change titles +function modRunTitle() { + // sync Mudas ODB slots with runtitle + let html = "

"; + mjsonrpc_db_get_values([instrODB["sampleNameOld"]]).then(function(rpc) { + // Take old runtitle from ODB + let sampleName = rpc.result.data[0]; + // split it into Sample, Temp, Field and Orientatin + // 4 x 10char + let sample = sampleName.substring(0,10).trim(); + // Use remove unit to fit in floats for temperatre and field + let temp = +(sampleName.substring(10,20).replace("K","").trim()); + let field = +(sampleName.substring(20,30).replace("G","").replace("T","").trim()); + let orient = sampleName.substring(30,40).trim(); + /* + // Update new odb parameters + modbset(instrODB["sampleName"],sample); + modbset(instrODB["sampleTemp"],temp); + modbset(instrODB["magField"],field); + modbset(instrODB["sampleOrient"],orient); + */ + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += "
Sample:
Temperature: K
Field: G
Orientation:

"; + let d = popModal("popPrompt"); + document.getElementById("popHTML").innerHTML = html; + document.getElementById("popButton").textContent = "Submit"; + document.getElementById("popButton").addEventListener("click", function () { + sample = document.getElementById("modSample").value; + temp = document.getElementById("modTemp").value; + field = document.getElementById("modField").value; + orient = document.getElementById("modOrient").value; + let modSample = sample.substring(0,10); + let modTemp = temp.toString().substring(0,10).trim()+"K"; + if (modTemp.length < 11) {modTemp = modTemp.replace("K"," K");} + let modField = field.toString().substring(0,10).trim()+"G"; + if (modField.length < 11) {modField = modField.replace("G"," G");} + let modOrient = orient.substring(0,10); + let runtitle = modSample.padEnd(10,' ') + modTemp.padEnd(10,' ') + modField.padEnd(10,' ') + modOrient.padEnd(10,' '); + console.log("modRunTitle(new) --"+runtitle+"--"); + console.log("modRunTitle(old) --"+sampleName+"--"); + modbset(instrODB["sampleNameOld"],runtitle); + // Update new odb parameters (for now they are synced anyway) + //modbset(instrODB["sampleName"],sample); + //modbset(instrODB["sampleTemp"],temp); + //modbset(instrODB["magField"],field); + //modbset(instrODB["sampleOrient"],orient); + }); + document.getElementById("popButton").addEventListener("click",closeModal); + }).catch(function(error){console.error(error);}); +} + +// Function to update sample/temp/field/orientation from title +// This is called once when Mudas is refreshed. +function syncRuninfo() { + mjsonrpc_db_get_values([instrODB["sampleNameOld"]]).then(function(rpc) { + // Take old runtitle from ODB + let sampleName = rpc.result.data[0]; + console.log("syncRuninfo()",sampleName); + // split it into Sample, Temp, Field and Orientatin + // 4 x 10char + let sampleODB = sampleName.substring(0,10); + // Use remove unit to fit in floats for temperatre and field + let tempODB = sampleName.substring(10,20).replace("K","").trim(); + tempODB = +(tempODB); + let fieldODB = sampleName.substring(20,30).replace("G","").replace("T","").trim(); + fieldODB = +(fieldODB); + let orientODB = sampleName.substring(30,40).trim(); + // Update new odb parameters + modbset(instrODB["sampleName"],sampleODB); + modbset(instrODB["sampleTemp"],tempODB); + modbset(instrODB["magField"],fieldODB); + modbset(instrODB["sampleOrient"],orientODB); + }).catch(function(error){console.error(error);}); +} + + + +// data-validate function to change run statistics limit. write 'LIMIT 5000000' into /Autorun/Cmd/Acmd . Length limit 128 +function chStatLimit(value,element) { + //check against malicious input: + //note: value typeof value === 'string' + if (isNaN(parseInt(value))){ + return false; + } + value=parseInt(value); + if (value<0) { + return false; + } + if (value>10000000000000) { + value=10000000000000; + element.childNodes[0].value = value; + } + //send updated runlimit to Deltat. + var AutorunCommand = "LIMIT " +value.toString(); + AutorunCommand=AutorunCommand.slice(0,127); + modbset("/Autorun/Cmd/Acmd",AutorunCommand); + return true; +} + +//**************************************************************************// +// Functions for Run Control tab // +//**************************************************************************// + +// Function to calculate GPS flow +function GPSFlow(T,spanid) +{ + let y0=1.3107; + let A1=28.91576; + let t1=6.67939; + let A2=2.1745; + let t2=44.2433; + let Flow = (1.0*(A1*Math.exp(-T/t1)+A2*Math.exp(-T/t2)+y0+0.3)).toFixed(1); + if (Flow > 18) { Flow = 18;} + if (spanid !== "") { + document.getElementById(spanid).innerHTML = Flow; + } + return Flow; +} + +// Function to interpolate thermal expansion of the Variox cryostat in Flame +function FlameVarioxHUB(T0id,HUBid,Tid,spanid) +{ + let a2= 4.76e-5; + let a1=-0.00112; + let hub0=Number(document.getElementById(HUBid).value) ; + let T=Number(document.getElementById(Tid).value) ; + let T0=Number(document.getElementById(T0id).value) ; + let a0=(1.0*(hub0-a1*T0-a2*T0*T0)); + let HUB = (1.0*(a0+a1*T+a2*T*T)).toFixed(1); + if (HUB > 60) { HUB = 60;} + if (HUB < 0) { HUB = 0;} + if (spanid !== "") { + if (T<0||T>350||T0<0||T0>350||hub0<0||hub0>60) { + document.getElementById(spanid).innerHTML = 'NaN'; + } + else{ + document.getElementById(spanid).innerHTML = HUB; + } + } + return HUB; +} + +// Function to interpolate thermal expansion of the Variox cryostat in Flame +function FlameSlitSuggestion(calib_field,calib_slits,suggested_field) +{ + // Read in variables + let Bin=Number(document.getElementById(calib_field).value); + let slitsIn=Number(document.getElementById(calib_slits).value); + let Bout=Number(document.getElementById(suggested_field).value); + + // Make sure values are sensible + if (Bin < 0) { + Bin = 0; + } + if (Bin > 35000) { + Bin = 35000; + } + if (slitsIn < 0) { + slitsIn = 0; + } + if (slitsIn > 19) { + slitsIn = 19; + } + + // Hard code fit values that allow interpolation of slit and field settings + B0 = 0.9995736651260684; + B1 = -8.99271806274571e-06; + B2 = 1.1488765115438888e-08; + B3 = -5.2056647136649e-13; + B4 = 6.577275821613439e-18; + s0 = 0.0021450000000617156; + s1 = 0.00061289473683141; + s2 = 0.005005941828255099; + s3 = -0.00011968727219710589; + + // Get change in incoming rate from the field change + let fieldChange = (B0 + B1*Bout + B2*Bout**2 + B3*Bout**3 + B4*Bout**4) / (B0 + B1*Bin + B2*Bin**2 + B3*Bin**3 + B4*Bin**4); + + // Get desired change in incoming rate needed from the slits + let slitChange = (s0 + s1*slitsIn + s2*slitsIn**2 + s3*slitsIn**3) / fieldChange; + + // If the slit setting isn't possible, set it to the maximum value + let suggestedSlits = 10; + if (slitChange > 1) { + suggestedSlits = 19; + } else { + // Numerically find the best slits for this using the Newton-Rhapson method (10 iterations is overkill, so we'll do that) + for (let i = 0; i < 10; i++) { + suggestedSlits -= (s0 - slitChange + s1*suggestedSlits + s2*suggestedSlits**2 + s3*suggestedSlits**3) / (s1 + 2*s2*suggestedSlits + 3*s3*suggestedSlits**2); + } + } + + // Set to 1 d.p. + suggestedSlits = suggestedSlits.toFixed(1) + + // Push suggestion to Mudas + document.getElementById('suggested_slits').value = suggestedSlits; +} + +// Function to calculate HAL flow +function HALJanisFlow(T,spanid) +{ + let y0=0.35343; + let A1=13.87872; + let t1=2.74724; + let A2=7.46306; + let t2=36.73725; + let Flow = (1.0*(A1*Math.exp(-T/t1)+A2*Math.exp(-T/t2)+y0+0.3)).toFixed(1); + if (Flow > 15) { Flow = 15;} + if (spanid !== "") { + document.getElementById(spanid).innerHTML = Flow; + } + return Flow; +} + + +// Function to calculate Heliox pressure +function HelioxPress(T,spanid) +{ + let Pressure = 4; + if (T >= 1 && T <= 2) { + Pressure = T * 4; + } + if (spanid) { + document.getElementById(spanid).innerHTML = Flow; + } + return Pressure; +} + +//**************************************************************************// +// End of Run Control tab // +//**************************************************************************// + + +//**************************************************************************// +// Function for general use // +//**************************************************************************// + +// Function to change content of element id +function set_if_changed(id, text) +{ + var e = document.getElementById(id); + if (e) { + if (e.innerHTML != text) { + e.innerHTML = text; + } + } +} + + +//**************************************************************************// +// End general use // +//**************************************************************************// + + +//**************************************************************************// +// Function for AutoRun tab // +//**************************************************************************// + + +// Function to produce syntax highlighted bulk sequence +function syntaxSeq(seq) { + // seq is a text of lines + let cmds = ["FIELD","TEMP","START","start","STOP","stop","set","SET"]; + let cmdssec = ["TITLE","WAIT","wait","inrange","4KOPSREADY","ATFIELD"]; + let tags = ["WEP","WEDL","WED","WEU","WEUL","WEV","FLOW","Equipment","FLC","BH Flow Setpoint"]; + let loops = ["LOOP"]; + let pars = ["magnet","Magnet","temperature","Temperature_Janis","histogram","flow", + "define","CRYOSTAT","cryostat","heliox","mcu2000","gfcflowc0"]; + let i,j; + + // Keep original + let seq_org = seq; + + // These can be done on the text in one go + // Parameters group + for (i=0;i"+pars[i]+""); + } + + // Loops group + for (i=0;i"+loops[i]+""); + } + + // tags group + for (i=0;i"+tags[i]+""); + } + + + // Commands group + for (i=0;i"+cmds[i]+""); + } + + // Secondary Commands group + for (i=0;i"+cmdssec[i]+""); + } + + + // Break lines and handle one by one + seq_lines = seq.split("\n"); + seq_lines_org = seq_org.split("\n"); + // Loop backwards, remove empty lines at end and + // restore comment lines + let isEmpty = 1; + let lCounter = 0; + for (j=seq_lines.length-1;j>=0;j--) { + let line = seq_lines[j].trim(); + // Empty line skip it + if (line == "" & isEmpty == 1) { + // Remove empty lines (optional) + //seq_lines.splice(j,1); + } else { + isEmpty = 0; + } + } + + // Now all extra lines are trimmed + for (j=0; j"; + } + seq_lines[j] = ""+lCounter+": "+seq_lines[j]+""; + } + return seq_lines.join("\n"); +} + + +//**************************************************************************// +// End AutoRun tab // +//**************************************************************************// + +//**************************************************************************// +// Functions for Setup tab // +//**************************************************************************// + + +// Instrument specific setup function: +function Dolly_updateCryoSetup() { + //find out if Fe is running: + + //document.getElementById('updateStatus').innerHTML = "R___"; + mjsonrpc_db_get_values([ "/System/Clients"]).then(function (rpc) { + var clients = rpc.result.data[0]; + var isvariox=false; + var isheliox=false; + for (var key in clients) { + var cname = clients[key].name; + if (!cname) { + continue; + } + if (cname.toLowerCase()=='MERCURY_ITCIO variox0'.toLowerCase()) {isvariox=true;} + if (cname.toLowerCase()=='MERCURY_ITCIO heliox0'.toLowerCase()) {isheliox=true;} + } + showClass('variox',isvariox && !isheliox); + showClass('heliox',!isvariox && isheliox); + showClass('nocryo',(!isvariox && !isheliox)||(isvariox && isheliox)); + + }).catch(function (error) {console.error(error);}); +} + +function Dolly_setVarioxPressureMode(pmode){ + var NVmode_sp='/Equipment/variox0/Variables/Output[10]'; + var Pmode_sp='/Equipment/mitcpressc0/Variables/Demand[6]'; + switch (pmode) { + case 0://fixed NV + mjsonrpc_db_paste([NVmode_sp,Pmode_sp],[0,0]).catch(function(error){console.error(error);}); + break; + case 1://fixed P + mjsonrpc_db_paste([NVmode_sp,Pmode_sp],[1,0]).catch(function(error){console.error(error);}); + break; + case 2://Auto + mjsonrpc_db_paste([NVmode_sp,Pmode_sp],[1,1]).catch(function(error){console.error(error);}); + break; + default: + console.error(`Unknown Pressure mode ${pmode}.`); + } +} + +function Dolly_updateVarioxPressureMode() { + //find out if Fe is running: + var NVmode_sp='/Equipment/variox0/Variables/Output[10]'; + var NVmode_rb='/Equipment/variox0/Variables/Input[26]'; + var Pmode_sp='/Equipment/mitcpressc0/Variables/Demand[6]'; + + mjsonrpc_db_get_values([ "/System/Clients",NVmode_rb,NVmode_sp,Pmode_sp]).then(function (rpc) { + var clients = rpc.result.data[0]; + var NVmodeRB = rpc.result.data[1]; //0 fixed, 1 auto + var NVmodeSP = rpc.result.data[2]; //0 fixed, 1 auto + var PmodeSP = rpc.result.data[3]; //0 fixed, 1 auto + + //check if frontend is running: + var mitcpressc_isRunning=false; + for (var key in clients) { + var cname = clients[key].name; + if (!cname) { + continue; + } + if (cname.toLowerCase()=='MITCPRESSC mitcpressc0'.toLowerCase()) {mitcpressc_isRunning=true;} + } + + //update Readback + if (NVmodeRB){ + if(mitcpressc_isRunning && PmodeSP){//Automatic + document.getElementById("VarioxPControl_RB").value = 2; + } + else{//fixed P + document.getElementById("VarioxPControl_RB").value = 1; + } + } + else{//fixed NV + document.getElementById("VarioxPControl_RB").value = 0; + } + + + //update Setpoint + if (NVmodeSP){ + if(mitcpressc_isRunning && PmodeSP){//Automatic + document.getElementById("VarioxPControl_SP").value = 2; + } + else{//fixed P + document.getElementById("VarioxPControl_SP").value = 1; + } + } + else{//fixed NV + document.getElementById("VarioxPControl_SP").value = 0; + } + + //enable/disable automatic + if(mitcpressc_isRunning){ + document.getElementById("Variox_AutoP_Option").disabled = false; + } + else{ + document.getElementById("Variox_AutoP_Option").disabled = true;} + + + }).catch(function (error) {console.error(error);}); +} + + +function popOldHist(histGroup,histPanel, width = 600, height = 480, x, y) +{ + // Form the right history window, add random number to force refresh when reloaded + let html = ` +
+
+ +
+
+ + + + + + + + + +
+
+
`; + + // Use resizable general dialog + d=general_dialog(html,histGroup+histPanel,width,height); + const dlgTitleText = d.querySelector("#dlgMessageTitle"); + dlgTitleText.innerText = "Old history dialog"; + dlgShow(d); // This is needed to get the close button + + // Adjust image size when resizing modal + const resizeObserver = new ResizeObserver((entries) => { + const img = entries[0].target.getElementsByTagName('img')[0]; + img.style.height = `${entries[0].contentRect.height - 100}px`; + img.style.width = `${entries[0].contentRect.width - 15}px`; + }); + resizeObserver.observe(d); + + // Event delegation for scale buttons + const scaleButtons = d.querySelector("#scaleButtons"); + scaleButtons.addEventListener("click", (event) => { + if (event.target.name === "scale") { + clearInterval(refreshHist); + oldHistScale(event.target.value,d); + } + }); + + // Fill it with initial scale and refresh periodically + oldHistScale("30m",d) + + return d; +} + +var refreshHist; +function oldHistScale(scale, caller) { + const hist = caller.querySelector('img'); + const newScale = `${hist.src.split("&scale=")[0]}&scale=${scale}`; + // Refresh every second, has problems with multiple open histories + refreshHist = setInterval(() => { + hist.src = `${newScale}&rand=${Math.random()}`; + }, 1000); +} + +// End: Functions for the HV Edit page +var mjsonvalue; +function test() { + //console.log("I am in test"); + //mjsonvalue = modbget("/muSR/td_musr/runinfo/runsubtitle"); + //let txt = loadFile("/CS/autorun/"); + // console.log("value=",mjsonvalue); +} + +// Insert block into autorun +function insertSeqBlock(element) { + let elId = element; + if (typeof element !== "string") { + elId = element.id; + } + let larEditor = document.getElementById("larEditor"); + let enablePop = document.getElementById("enablePop").checked; + let text = ""; + let html = "

"; + if (elId == "gpsLTLoop") { + // Sample low temperature loop + text = "set temperature tempVal tempTol tempTime 1 100 120\n"; + text += "wait temperature inrange tempTOut\n"; + text += "TITLE c=titleVal\n"; + text += "start histogram iHist stats\n"; + // Prompt for values + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + } else if (elId == "gpsHTLoop") { + // Sample high temperature loop + text = "set flow flow flowVal\n"; + text += "set temperature tempVal tempTol tempTime tempVal tempTol tempTime\n"; + text += "wait temperature inrange tempTOut\n"; + text += "TITLE c=titleVal\n"; + text += "start histogram iHist stats\n"; + // Prompt for values + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + // Add hidden flow in case of a single T value + html += ""; + } else if (elId == "cryoLoop") { + // Sample high temperature loop + text = "set cryostat tempVal tempTol tempTime tempVal tempTol tempTime 1 1 AP\n"; + text += "wait cryostat inrange tempTOut\n"; + text += "TITLE c=titleVal\n"; + text += "start histogram iHist stats\n"; + // Prompt for values + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + } else if (elId == "echoSeq") { + // Sample high temperature loop + text = "TITLE c=Echo, p4Length p1Length p2Length p3Length, p4Delay p1Delay p2Delay p3Delay, phase1 phase2\n"; + text += "# switch off DG by inverting trigger level\n"; + text += "define Equipment/dg6450/Variables/Output[8] 0.2\n"; + text += "# Pulses with channel mapping 4 1 2 3\n"; + text += "define Equipment/dg6450/Variables/Output[6] p4Delay\n"; + text += "define Equipment/dg6450/Variables/Output[7] p4Length\n"; + text += "define Equipment/dg6450/Variables/Output[0] p1Delay\n"; + text += "define Equipment/dg6450/Variables/Output[1] p1Length\n"; + text += "define Equipment/dg6450/Variables/Output[2] p2Delay\n"; + text += "define Equipment/dg6450/Variables/Output[3] p2Length\n"; + text += "define Equipment/dg6450/Variables/Output[4] p3Delay\n"; + text += "define Equipment/dg6450/Variables/Output[5] p3Length\n"; + text += "# Phases\n"; + text += "define Equipment/uwave0/Variables/Output[0] phase1\n"; + text += "define Equipment/uwave0/Variables/Output[1] phase2\n"; + text += "# switch on DG by restoring trigger level\n"; + text += "define Equipment/dg6450/Variables/Output[8] -0.2\n"; + text += "start histogram iHist stats\n"; + // Prompt for values + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + // Add hidden flow in case of a single T value + html += ""; + } else if (elId == "setEcho") { + // Sample high temperature loop + text = "TITLE c=Echo, p4Length p1Length p2Length p3Length, p4Delay p1Delay p2Delay p3Delay, phase1 phase2\n"; + text += "# switch off DG by inverting trigger level\n"; + text += "define Equipment/dg6450/Variables/Output[8] 0.2\n"; + text += "# Pulses with channel mapping 4 1 2 3\n"; + text += "define Equipment/dg6450/Variables/Output[6] p4Delay\n"; + text += "define Equipment/dg6450/Variables/Output[7] p4Length\n"; + text += "define Equipment/dg6450/Variables/Output[0] p1Delay\n"; + text += "define Equipment/dg6450/Variables/Output[1] p1Length\n"; + text += "define Equipment/dg6450/Variables/Output[2] p2Delay\n"; + text += "define Equipment/dg6450/Variables/Output[3] p2Length\n"; + text += "define Equipment/dg6450/Variables/Output[4] p3Delay\n"; + text += "define Equipment/dg6450/Variables/Output[5] p3Length\n"; + text += "# Phases\n"; + text += "define Equipment/uwave0/Variables/Output[0] phase1\n"; + text += "define Equipment/uwave0/Variables/Output[1] phase2\n"; + text += "# switch on DG by restoring trigger level\n"; + text += "define Equipment/dg6450/Variables/Output[8] -0.2\n"; + text += "start histogram iHist stats\n"; + // Prompt for values + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + // Add hidden flow in case of a single T value + html += ""; + } else if (elId == "gpsBLoop") { + // Sample field loop command + text = "set magnet selMag fieldVal fieldTime\n"; + text += "TITLE c=titleVal\n"; + text += "start histogram iHist stats\n"; + // Prompt for values + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + } else if (elId == "gpsTempHT") { + // Set high temperature command + text = "set flow flow flowVal\n"; + text += "set temperature tempVal tempTol tempTime tempVal tempTol tempTime\n"; + text += "wait temperature inrange tempTOut\n"; + // Prompt for values + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + } else if (elId == "setCryo") { + // Set high flame temperature command + text = "set cryostat tempVal tempTol tempTime tempVal tempTol tempTime 1 1 AP\n"; + // Prompt for values + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + } else if (elId == "gpsTempLT") { + // Set low temperature command + text = "set temperature tempVal tempTol tempTime 1.0 100 120\n"; + text += "wait temperature inrange tempTOut\n"; + // Prompt for values + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + } else if (elId == "gpsField") { + // Set magnet command + text = "set magnet selMag fieldVal fieldTime\n"; + // Prompt for values + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + } else if (elId == "setODB") { + // Set temperature command + text = "define odbPath odbVal\n"; + // Prompt for values + html += ""; + html += ""; + html += ""; + html += ""; + } else if (elId == "setTitle") { + // Set title command + text = "TITLE c=titleVal\n"; + // Prompt for values + html += ""; + html += ""; + } else if (elId == "gpsFlow") { + // Set flow command + text = "set flow flow flowVal\n"; + // Prompt for values + html += ""; + html += ""; + } else if (elId == "startRun") { + // Start a run command + text = "start histogram iHist stats\n"; + // Prompt for values + html += ""; + html += ""; + html += ""; + html += ""; + } else if (elId == "helioxLoop") { + // Heliox temperature loop + text = "set heliox tempVal tempTol tempTime 1 2 120 0\n"; + text += "set heliox -1 -1 -1 -1 -1 -1 -1 pressVal\n"; + text += "wait heliox inrange tempTOut\n"; + text += "wait tempTime\n"; + text += "TITLE c=titleVal\n"; + text += "start histogram iHist stats\n"; + // Prompt for values + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + } else if (elId == "varioxLTLoop") { + // Varios with sample stick temperature loop + text = "set variox tempVal tempTol tempTime 1 10 120 pressureVal\n"; + text += "wait variox inrange tempTOut\n"; + text += "wait 120\n"; + text += "TITLE c=titleVal\n"; + text += "start histogram iHist stats\n"; + // Prompt for values + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + } else if (elId == "varioxHTLoop") { + // Varios with sample stick temperature loop + text = "set variox tempVal tempTol tempTime tempVal tempTol tempTime pressureVal\n"; + text += "wait variox inrange tempTOut\n"; + text += "wait 120\n"; + text += "TITLE c=titleVal\n"; + text += "start histogram iHist stats\n"; + // Prompt for values + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + } else if (elId == "dollyField") { + // Set magnet command + text = "set magnet selMag fieldVal fieldTime\n"; + // Prompt for values + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + } else if (elId == "dollyBLoop") { + // Sample field loop command + text = "set magnet selMag fieldVal fieldTime\n"; + text += "TITLE c=titleVal\n"; + text += "start histogram iHist stats\n"; + // Prompt for values + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + } else if (elId == "varioxTemp") { + // Set variox temperature command + text = "set variox tempVal tempTol tempTime tempVal tempTol tempTime 1 1 pressureVal\n"; + text += "wait variox inrange tempTOut\n"; + // Prompt for values + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + } else if (elId == "helioxTemp") { + // Set heliox temperature command + text = "heliox tempVal tempTol tempTime 1 2 120 0\n"; + text += "set heliox -1 -1 -1 -1 -1 -1 -1 pressVal\n"; + text += "wait heliox inrange tempTOut\n"; + // Prompt for values + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + } else if (elId == "halField") { + // command description + text = "WAIT Magnet 4KOPSREADY\n"; + text += "SET Magnet fieldVal\n"; + text += "WAIT Magnet ATFIELD\n"; + text += "WAIT 300\n"; + // Prompt for values + html += ""; + html += ""; + } else if (elId == "halSlits") { + // command description + text = "MULTISET FS71 slitVal\n"; + text += "WAIT 5\n" + text += "MULTISET FS72 slitVal\n"; + text += "WAIT 60\n"; + // Prompt for values + html += ""; + html += ""; + } else if (elId == "halJanisLoop") { + // HAL temp loop with Janis cryostat + text += 'set gfcflowc0 "BH Flow Setpoint" flowJanisVal 300\n'; + text += "set Temperature_Janis tempVal tempTol tempTime tempVal tempTol tempTime\n"; + text += "set mcu2000 FLC posJanisVal 120\n"; + text += "wait Temperature_Janis inrange tempTOut\n"; + text += "wait 300\n"; + text += "TITLE c=titleVal\n"; + text += "start histogram iHist stats\n"; + // Prompt for values + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + // Add hidden flow in case of a single T value + html += ""; + html += ""; + } else if (elId == "halJanisTemp") { + // HAL temp with Janis cryostat + text += 'set gfcflowc0 "BH Flow Setpoint" flowJanisVal 300\n'; + text += "set Temperature_Janis tempVal tempTol tempTime tempVal tempTol tempTime\n"; + text += "set mcu2000 FLC posJanisVal 120\n"; + text += "wait Temperature_Janis inrange tempTOut\n"; + text += "wait 300\n"; + // Prompt for values + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + html += ""; + } else if (elId == "newcommand") { + // command description + text = "command lines\n"; + // Prompt for values + html += ""; + html += ""; + } + + // Finish html block + html += "
Temperature list (comma separated or from:step:to)
K
Use custom title
K
Tolerance: K
Stability Time: sec
Time Out: sec
Stats: Events
On Histogram #:
Temperature list (comma separated or from:step:to)
K
Use custom title
K
Tolerance: K
Stability Time: sec
Time Out: sec
Stats: Events
On Histogram #:
Temperature list (comma separated or from:step:to)
K
Use custom title
K
Tolerance: K
Stability Time: sec
Time Out: sec
Stats: Events
On Histogram #:
Use custom title
K
P4 Delay: nsP4 Length: ns
P1 Delay: nsP1 Length: ns
P2 Delay: nsP2 Length: ns
P3 Delay: nsP3 Length: ns
Phase1: degPhase2: deg
Stats: EventsOn Histogram #:
Use custom title
K
P4 Delay: nsP4 Length: ns
P1 Delay: nsP1 Length: ns
P2 Delay: nsP2 Length: ns
P3 Delay: nsP3 Length: ns
Phase1: degPhase2: deg
Stats: EventsOn Histogram #:
Field list (comma separated or from:step:to)
G
Use custom title
K
Stability Time:: sec
Select Magnet:
Stats: Events
On Histogram #:
Temperature: K
Tolerance: K
Stability Time: sec
Time Out: sec
Flow (optional): sec
Temperature: K
Tolerance: K
Stability Time: sec
Time Out: sec
Temperature: K
Tolerance: K
Stability Time: sec
Time Out: sec
Field: G
Stability Time:: sec
Select Magnet:
ODB Path:
Set Value:
Title:
Flow: sec
Stats: Events
On Histogram #:
Temperature list (comma separated or from:step:to)
K
Use custom title
K
Tolerance: K
Stability Time: sec
Time Out: sec
Stats: Events
On Histogram #:
Temperature list (comma separated or from:step:to)
K
Use custom title
K
Tolerance: K
Stability Time: sec
Time Out: sec
Pressure (AP for automatic): mbar
Stats: Events
On Histogram #:
Temperature list (comma separated or from:step:to)
K
Use custom title
K
Tolerance: K
Stability Time: sec
Time Out: sec
Pressure (AP for automatic): mbar
Stats: Events
On Histogram #:
Field: G
Stability Time:: sec
Select Magnet:
Field list (comma separated or from:step:to)
G
Use custom title
K
Stability Time:: sec
Select Magnet:
Stats: Events
On Histogram #:
Temperature: K
Tolerance: K
Stability Time: sec
Time Out: sec
Pressure (AP for automatic): mbar
Temperature: K
Tolerance: K
Stability Time: sec
Time Out: sec
Pressure (optional): mbar
Field target: T
Slits: mm
Temperature list (comma separated or from:step:to)
K
Use custom title
K
Tolerance: K
Stability Time: sec
Time Out: sec
Stats: Events
On Histogram #:
Temperature
K
Tolerance: K
Stability Time: sec
Time Out: sec
Flow (optional) l/min
Position (optional) mm
ValueName: unit

Block:
"+text+"
"; + + let sel, range, newNode; + newNode = document.createElement("pre"); + // Cursor in editing + larEditor.focus(); + if (document.getSelection) { + sel = document.getSelection(); + // If anything is selected + if (sel.getRangeAt && sel.rangeCount) { + // Only if cursor is in larEditor + if (larEditor.contains(sel.getRangeAt(0).startContainer)) { + range = sel.getRangeAt(0); + range.deleteContents(); + range.insertNode(newNode); + } else { + alert("Cursor must be in the editing area!"); + return(0); + } + } else { + alert("Cursor must be in the editing area!"); + return(0); + } + } + newNode.innerHTML = "
preparing ....
"; + + if (enablePop) { + popModal("popPrompt"); + document.getElementById("popHTML").innerHTML = html; + document.getElementById("popButton").textContent = "Submit"; + document.getElementById("popButton").addEventListener("click",promptSeqParams); + document.getElementById("popButton").addEventListener("click",closeModal); + document.getElementById("popButton").addEventListener("click",checkSyntax); + } else { + // Use defaults + text = subSeqDefaults(text); + newNode.innerHTML = text+"
"; + checkSyntax(); + } +} + + +// Close pop modal cleanly +function closeModal() +{ + let caller = document.getElementById("popPrompt"); + let preparing = document.getElementById("preparing"); + if (caller) caller.remove(); + if (preparing) preparing.remove(); +} + +// Thist function extracts values from popPrompt +function promptSeqParams() { + let parEls = document.getElementsByClassName("prompPar"); + let parAdj = document.getElementsByClassName("adjustPar"); + let textBlock = document.getElementById("textBlock").innerText; + let key; + let value,loopflag = 0,loopkey, adjustFlow,adjustTitle,adjustPress,adjustPosJanis,adjustJanisFlow = 0; + let loopValues = []; + let addFlow = 0, tempFlow; + + // Check if the block includes flows that you need to adjust to temperature + if (textBlock.toLowerCase().includes("flow")) { + adjustFlow = 1; + } + if (textBlock.toLowerCase().includes("flowjanis")) { + adjustJanisFlow = 1; + adjustFlow = 0; + } + // Check if the block includes pressure that you need to adjust to temperature + if (textBlock.toLowerCase().includes("posjanis")) { + adjustPosJanis = 1; + } + // Check if the block includes pressure that you need to adjust to temperature + if (textBlock.toLowerCase().includes("press")) { + adjustPress = 1; + } + // Check if we need to set a custom title + if (textBlock.toLowerCase().includes("title")) { + adjustTitle = 1; + } + + + for (let i=0;i toT) { + // Cooling down, take a slightly larger flow + addFlow = 0.5; + } + if ((fromT > toT && stepT>0) || (fromT < toT && stepT<0)) {stepT = -1*stepT;} + loopValues.push(fromT); + let currT = fromT; + while ((1+(currT-toT)/stepT) < 0) { + currT = Math.round((currT + stepT)*100)/100; + loopValues.push(currT); + } + } else if (value.includes(",")) { + loopflag = 1; + loopkey = key; + loopValues = value.split(","); + } else { + // assume a single value + textBlock = textBlock.replaceAll(key,value); + // keep it for the upcoming flow + tempFlow = value; + } + } else if (key == "flowVal" && value == "") { + // If the flow is empty use calibration based + // on the saved temperature in tempFlow (exclude loops) + if (!loopflag) { + value = 1*GPSFlow(tempFlow,""); + textBlock = textBlock.replaceAll(key,value); + } + } else if (key == "flowJanisVal" && value == "") { + // If the flow is empty use calibration based + // on the saved temperature in tempFlow (exclude loops) + if (!loopflag) { + value = 1*HALJanisFlow(tempFlow,""); + textBlock = textBlock.replaceAll(key,value); + } + } else if (key == "pressVal" && value == "") { + // If the pressure is empty use calibration based + // on the saved temperature (exclude loops) + if (!loopflag) { + value = HelioxPress(tempFlow); + textBlock = textBlock.replaceAll(key,value); + } + } else if (key == "posJanisVal" && value == "") { + // If the position is empty use calibration based + // on the saved temperature (exclude loops) + if (!loopflag) { + value = 76.72 - 0.0124 * tempFlow; + textBlock = textBlock.replaceAll(key,value); + } + } else if (key == "titleCheck" && !parEls[i].checked) { + textBlock = textBlock.replaceAll("TITLE","#TITLE"); + } else { + textBlock = textBlock.replaceAll(key,value); + } + } + // finished all easy keys, now check loops + // Now make a block for each loop value + let fullTextBlock = ""; + if (loopflag) { + for (let i=0; i fileB) ? 1 : 0; + }); + files.forEach(function (item) { + fList.push(item.filename); + }); + } + return fList; +} + + +// Make selection DOM and connect double click to funcCall (optional) +function makeSelectFiles(fList,funcCall,path,ext,div,idinp) { + let sel = document.getElementById("fileSelect"); + let count = 0; + + // Empty sel + sel.innerHTML = ""; + + setIfChanged("msg_directory", path); + + fList.forEach(function (item) { + let o = document.createElement("option"); + o.innerHTML = item; + o.addEventListener("click", clickScript); + // If a callback function is given fill the selection element + if (funcCall && item.substring(0,1) != "[") { + o.addEventListener("dblclick", funcCall); + } else { + let func = makeSelectFiles.caller; + let newPath = path+"/"+item.replace(/[\[\]]/g, ""); + o.addEventListener("dblclick", function() { + console.log("Clicked subdir ",item, "\nFrom ", func,"\nNew path ",newPath); + document.getElementById("xml_filename").value = document.getElementById("xml_filename").value + item.replace(/[\[\]]/g, "") + "/"; + fillxmlHVSel(newPath,ext,div,idinp); + }); + } + sel.appendChild(o); + //sel.insertBefore(o, sel.firstChild); + count++; + }); + sel.size = count+1; +} + +function clickScript() { + let fileName = document.getElementById("fileSelect").value; +} + +// Function to show or hide all elements from class +// clname - class name to toggel +// fe - frontend first failed modbvalue or just a boolean (true/false) +// Depending on FE state (first failed 0 means active) show or hide class +function showClass(clname,fe) { + let selector = "." + clname; + let flag = false; + if (typeof fe === "boolean") { + // if a boolean was sent use it to determine state + flag = fe; + } else { + // otherwise check the sate of the fe (running ot not) + flag = (fe.value == 0) ? true : false; + } + // Find all elements with the correct class and hide/show + const classEls = document.querySelectorAll(selector); + classEls.forEach((element) => { + if (flag) { + element.style.visibility = "visible"; + switch (element.nodeName){ + case "SPAN": + element.style.display = "inline";//JAK 16.5.24 to fix Dolly RunControl + //element.style.display = "inline-block"; + break; + case "TR": + element.style.display = "table-row"; break; + default: + console.log(element.nodeName); + element.style.display = "block"; + } + } else { + element.style.visibility = "hidden"; + element.style.display = "none"; + } + }); +} + + +// Function to enable/disable a class +// clname - class name to toggle +// set - string "toggle", "enable" "disable" to specify behavior +// title - optional, title to set. +// "enable" removes disabled , "disable" sets disabled and +// "toggle" changes depending on the current value. +function toggleButton(clname,set="toggle",title) { + let selector = "." + clname; + // Find all elements with the correct class and hide/show + const btnEls = document.querySelectorAll(selector); + btnEls.forEach((element) => { + switch (set) { + case "enable": + element.disabled=false; + break; + case "disable": + element.disabled=true; + break; + case "toggle": + element.disabled=!element.disabled; + break; + default: + console.log(`Error in chaning disabled value of ${element}.`); + return; + } + if (typeof title !== undefined){ + element.title=title; + } + }); +} + +// Function to change visibility of a class +// clname - class name to toggle +// set - string "toggle", "enable" "disable" to specify behavior +// "visible" sets visible , "hidden" sets hidden +// "toggle" changes depending on the current value. +function toggleVisibility(clname,set="toggle") { + let selector = "." + clname; + // Find all elements with the correct class and hide/show + const clEls = document.querySelectorAll(selector); + clEls.forEach((element) => { + switch (set) { + case "visible": + element.style.visibility='visible'; + break; + case "hidden": + element.style.visibility='hidden'; + break; + case "toggle": + if(element.style.visibility=='hidden'){ + element.style.visibility='visible'; + }else{ + element.style.visibility='hidden'; + } + break; + default: + console.log(`Error in chaning visibility of ${element}.`); + return; + } + }); +} + +function forceReload(el) { + if (el.value == -1) { + alert("Please refresh the page, Ctrl-Shift-R"); + //location.reload(true); + } +} + +// Function to pass error to console instead of alert +function mjsonrpc_error_alert(error) { + console.log("mjsonrpc_error_alert:",error); + console.log("xhr",error.xhr); +} \ No newline at end of file diff --git a/pages/SearchDB.png b/pages/SearchDB.png new file mode 100644 index 0000000..c6a49b5 Binary files /dev/null and b/pages/SearchDB.png differ diff --git a/pages/TDCconfiguration.js b/pages/TDCconfiguration.js new file mode 100644 index 0000000..27594d6 --- /dev/null +++ b/pages/TDCconfiguration.js @@ -0,0 +1,1136 @@ +//**************************************************************************// +// Copyright (C) 2020-2025 by Zaher Salman // +// zaher.salman@psi.ch // +// jonas.krieger@psi.ch // +//**************************************************************************// + +/* +//moved into init: +let instrODB.logicDir='/Equipment/TDC/Logic/'; +let instrODB.histogramDir='/Equipment/TDC/Histograms/'; +let instrODB.tdcSettingsDir='/Equipment/TDC/Settings/' +*/ + + +//global variables; +let gTDCbrowsed = false; +let gTDClastLoadfileName = ""; + +//custom style: +var readTDC_css = ` +.tdcNewVal_General{ +background-color: yellow; +float: right; +width:50%; +} + +.tdcNewVal_Channel{ +background-color: yellow; +/*overflow: hidden; +width:50%;*/ +} +`; + +const tdcstyle = document.createElement('style'); +tdcstyle.textContent = readTDC_css; +document.head.appendChild(tdcstyle); + +// Define the tdcStatus object to store the TDC status data +let tdcStatus = { + HistoName: [], + ScalerName: [], + Ch: { + Used: [], + Type: [], + } + }; + + +/* + Function to read the TDC status data and update the tdcStatus object + - modbRead is an modbvalue object +*/ +function readTDCstatus() { //shortcut wihtout promise + readTDCpromise().then(function (){}).catch(function (error) { console.error(error); }); +} + +function readTDCpromise() { + return new Promise(function(resolve,reject){ + mjsonrpc_db_get_values([instrODB.histogramDir+'Name', + instrODB.logicDir+'Channel_Name', //instrODB.histScalerDir + instrODB.logicDir+'Channel_Used', + instrODB.logicDir+'Channel_Type'] + ).then(function (rpc) { + tdcStatus['HistoName'] = rpc.result.data[0]; + tdcStatus['ScalerName'] = rpc.result.data[1]; + tdcStatus['Ch']['Used'] = rpc.result.data[2]; + tdcStatus['Ch']['Type'] = rpc.result.data[3]; + resolve(); + return; + + }).catch(function (error) { reject(error); return; }); + + }); + } + + +//required for scaling in data-formula +let TDCresolution= 0.1e-3;//default + + +/*Save time resolution in a global variable, to use it in data-formula*/ +function changedResolution(value) { + if (value>0) { + TDCresolution=value; + } +} + + + +/* + The class below defines the Locations, Keys and Data Types for objects + that correspond to content in the ODB. + + It also contains information of what elements should be put into the + ODB if the read TDC-file has empty/undefined elements. +*/ +class ODB_element_TDC { + constructor(location, key, type = '', ifUndefined = '') { + this.location = location; + this.key = key; + this.type = type; + this.ifUndefined = ifUndefined; + } + } + +/* + Each element of the array below is an object that correspond to + the Locations, Keys and Data Types for all the elements that are + being read from the TDC-file. + + OBS: Everything in the list is in the same order as the content in the TDC-file. +*/ +const ODBcontent_generalTDC = [ + // Here follows the properties for the first elements "general information" + // from the TDC-file. + new ODB_element_TDC('/Experiment/', 'Name', 'str', ''), + new ODB_element_TDC(instrODB.logicDir, 'Description', 'str', ''), + new ODB_element_TDC(instrODB.logicDir, 'Data_Window', 'int', ''), + new ODB_element_TDC(instrODB.tdcSettingsDir, 'Type', 'str', ''), + new ODB_element_TDC(instrODB.tdcSettingsDir, 'Time_Per_Bin', 'str', '0'), + new ODB_element_TDC(instrODB.logicDir, 'Muon_Delay', 'int', 0), + new ODB_element_TDC(instrODB.logicDir, 'Positron_Delay', 'int', 0), + new ODB_element_TDC(instrODB.logicDir, 'Muon_Coincidence_Window', 'int', 0), + new ODB_element_TDC(instrODB.logicDir, 'Positron_Coincidence_Window', 'int', 0), + new ODB_element_TDC(instrODB.logicDir, 'Veto Pre_Coincidence_Window', 'int', 0), + new ODB_element_TDC(instrODB.logicDir, 'Veto_Post_Coincidence_Window', 'int', 0), + new ODB_element_TDC(instrODB.logicDir, 'T0_OffSet', 'int', 0), + new ODB_element_TDC(instrODB.logicDir, 'Pre_Pileup_Window', 'int', 0), + new ODB_element_TDC(instrODB.logicDir, 'Post_Pileup_Window', 'int', 0), + ] + + const ODBcontent_channelTDC = [ + // Here follows the properties for the channels "channel lines" + // from the TDC-file. + new ODB_element_TDC(instrODB.logicDir, 'Channel_Used', 'str', ''), + new ODB_element_TDC(instrODB.logicDir, 'Channel_Name', 'str', ''), + new ODB_element_TDC(instrODB.logicDir, 'Channel_Type', 'str', ''), + new ODB_element_TDC(instrODB.tdcSettingsDir, 'Channel_OffSet', 'int', 0), + new ODB_element_TDC(instrODB.logicDir, 'Channel_Logic', 'str', ';'), + ] + + const ODBcontent_channelHisto = [ + // Here follows the properties for the channels "channel lines" + // from the TDC-file. + new ODB_element_TDC(instrODB.histogramDir, 'Number', 'int', 0), + new ODB_element_TDC(instrODB.histogramDir, 'Name', 'str', 'Ch'), + new ODB_element_TDC(instrODB.histogramDir, 'TDCchannels', 'str', ''), + new ODB_element_TDC(instrODB.histogramDir, 'T0', 'int', 0), + new ODB_element_TDC(instrODB.histogramDir, 'FirstGood', 'int', 0), + new ODB_element_TDC(instrODB.histogramDir, 'LastGood', 'int', 0), + new ODB_element_TDC(instrODB.histogramDir, 'Length', 'int', 0), + new ODB_element_TDC(instrODB.histogramDir, 'xUp', 'float', 0), + new ODB_element_TDC(instrODB.histogramDir, 'xLow', 'float', 0), + new ODB_element_TDC(instrODB.histogramDir, 'PP_correction_post_logic', 'bool', false), + ] + + /* + Form the skeleton of the HTML-tab, with hidden + placeholders that appear when reading a TDC-file. + + Read and print the current TDC-settings from the ODB. + */ + function onloadTDCtab() { + let channelTable = ` + + Ch# + Used + Name + Type + OffSet + Logic + + `; + let histoTable = ` + + Number + Name + TDC channels + T0 + FirstGood + LastGood + Length + xUp + xLow + PP corr. + + `; + + // Build Logic configuration Table + channelTable += ''; + + //check number of tdc channels + numTDCch=0 + if (tdcStatus['Ch']['Type']!=null){ + numTDCch=tdcStatus['Ch']['Type'].length; + } + + for (let i = 0; i < numTDCch; i++) { + channelTable += ''; + channelTable += '' + i + ''; + // Print the current settings from the ODB using "modbvalue". + for (let j = 0; j < ODBcontent_channelTDC.length; j++) { + channelTable += ''; + channelTable += '
' + } + channelTable += ''; + } + channelTable += ''; + document.getElementById("channelTable").innerHTML = channelTable; + + + // Build Histogram configuration Table + histoTable += ''; + + //check number of tdc channels + let numHistch=0 + if (tdcStatus['HistoName']!=null){ + numHistch=tdcStatus['HistoName'].length; + } + + for (let i = 0; i < numHistch; i++) { + histoTable += ''; + //histoTable += '' + i + ''; + // Print the current settings from the ODB using "modbvalue". + for (let j = 0; j < ODBcontent_channelHisto.length; j++) { + histoTable += ''; + histoTable += '
' + } + histoTable += ''; + } + histoTable += ''; + document.getElementById("histogramTable").innerHTML = histoTable; + + // Hide all the space holders. + toggleVisibility("tdcNewVal_General","hidden"); + + // Disable the 'Apply' and 'Reset'-button. + //document.getElementById("loadTDC").disabled = true; + //document.getElementById("resetTDC").disabled = true; + } + + + +/*Construct Settings table, reset buttons.*/ + function initTDCconfig() { + onloadTDCtab(); + gTDCbrowsed = false; + gTDClastLoadfileName=""; + editTDCconfig(false);//disable editing. + } + +/* Toggle button states depending on experiment status*/ +function disableByRunStatus() { + runStopped=document.getElementById("runStatusValue").value == 1 + //Enable only if Run stopped + if (runStopped) { + toggleButton("stoppedEditable",set="enable",""); + } else { + toggleButton("stoppedEditable",set="disable","Stop run to edit."); + //disable element editing + editTDCconfig(false); + } + // Check if browsing a TDC file: + if (gTDCbrowsed) { + toggleButton("activeBrowsed",set="enable",""); + } else { + toggleButton("activeBrowsed",set="enable","Load a file first."); + } + //special case: loading a new file needs stopped and browsed: + if (gTDCbrowsed && runStopped){ + toggleButton("loadTDC",set="enable",""); + } else { + toggleButton("loadTDC",set="disable","Stop run and load a file.."); + } + } + + +/* + Function to enable browser editing of the TDC configuration. +*/ + function editTDCconfig(enable=true){ + // Find all elements with the tdc_editable class + const cl_elements = document.querySelectorAll(".tdc_editable"); + cl_elements.forEach((element) => { + switch (enable) { + case true: + element.setAttribute("data-odb-editable","1"); + break; + case false: + element.setAttribute("data-odb-editable","0"); + break; + default: + console.log(`Error while enabling editing of TDC configuration.`); + return; + } + }); + + // Use a default fileName when editing: + if(enable==true){ + modbset(instrODB.tdcSettingsDir+'SettingsFile',"Manually edited. Please save!"); + } + //set a red background color in editing mode: + const odb_fileName=document.getElementById("TDC_ODB_FILENAME");//current fileName (should be fine without a promise.) + document.querySelectorAll(".tdc_filename").forEach((element) => { + // somebody could have forgotten saving the changes: + if (enable==true || odb_fileName.value=="Manually edited. Please save!"){ + element.style.backgroundColor="red"; + } else{ + element.style.backgroundColor=""; + } + }); +} + + + +/* + Load a preview of a new configuration + + config is a json object with the following content: + { + "Instrument": string, + "Settings": { + "Channel_OffSet": [], + "Time_Per_Bin": value, + "Type": string, + "SettingsFile": string, + }, + "Logic": { + "Description": string, + "Data_Window": value, + ... rest of odb fields of logicDir ... + "Channel_Logic": [], + }, + "Histograms": { + "Number": [], + ... rest of odb fields of histogramDir ... + "TDCchannels":[], + }, + } +*/ +function browseNewTDCconfiguration(newConfig){ + //function scope helper functions: + function DisplayLoadDict(dict) { + for (const key in dict) { + if (Array.isArray(dict[key])) { + DisplayLoadedArray(key, dict[key]); + } else { + DisplayLoadedValue(key, dict[key]); + } + } + } + //helper function + function DisplayLoadedValue(key,value) { + try { + const geninfo = document.getElementById("TDC_LOAD_" + key); + //parse hexadecimal, e.g. uint + if (typeof value ==='string' && value.startsWith("0x")){ + value=Number(value);//parse to int. + } + geninfo.innerHTML = value; + } + catch { // If ID doesn't exist. + console.error('ID does not exist: TDC_LOAD_', key); + } + } + //helper function + function DisplayLoadedArray(key,valarray) { + try { + const chaninfo = document.getElementsByClassName("TDC_LOAD_" + key); + if (valarray.legnth>chaninfo.length){ + console.error("Not enough fields to store loaded TDC settings.") + } + for(let i=0;i{ + //reset gui + initTDCconfig(); + disableByRunStatus(); + }); + + }).catch(function(error) { + console.error(error); }); + +} + + + +/*Add more rows to the histogram table. Doesn't affect odb.*/ +function addHistoDisplayChannels(addHistch) { + const histTableref = document.getElementById('histogramTable').getElementsByTagName('tbody')[0]; + for (let i = 0; i < addHistch; i++) { + const newRow = histTableref.insertRow(); + for (let j = 0; j < ODBcontent_channelHisto.length; j++) { + const newCell = newRow.insertCell(); + newCell.appendChild(document.createElement('span')); + newCell.appendChild(document.createElement('br')); + let newval_span = document.createElement('span'); + newval_span.classList.add("tdcNewVal_Channel"); + newval_span.classList.add("TDC_LOAD_" + ODBcontent_channelHisto[j].key); + newCell.appendChild(newval_span); + } + } +} + + +/* + Write the last loaded configuration (gTDClastLoadfileName) into the odb. +*/ +function applyLastTDCConfig(){ + + let extension=gTDClastLoadfileName.split('.').pop(); + + if (extension=="v1190") { + loadTDCv1190(gTDClastLoadfileName,applyNewTDCconfiguration); + return; + } + + loadTDCconfig(gTDClastLoadfileName,applyNewTDCconfiguration); +} + +/** + * Load a tdc configuration .json file and display it without writing it into the odb. + * @param {string} fileName : optional, , file name to load. using file_picker if undefined or empty "". + */ +function displayTDCconfig(fileName){ + loadTDCconfig(fileName,browseNewTDCconfiguration); +} + +/** + * + * Load a saved TDC configuration .json file. + * and pass it to the callback. + * + * @param {string} fileName file name to load. using file_picker if undefined or empty "". + * @param {function(TDCconfig)} callback will be called with a configuration .json object. + */ +function loadTDCconfig(fileName, callback){ + // if the file name is not delivered, get it from file_picker + if (typeof fileName !== "string" || fileName=="") { + file_picker("/TDC_config", "*.json", loadTDCconfig, false,callback); + return; + } + + // Save the fileName to the global variable. + gTDClastLoadfileName = fileName; + + // Fetch the TDC-file and load it as text. + file_load_ascii(fileName, function(text) { + callback(JSON.parse(text)); + }); + + +} + +/** + * + * Save the current TDC configuration to a .json file. + * + * @param {string} fileName file name to load. using file_picker if undefined or empty "". + */ +function saveTDCconfig(fileName){ + // if the file name is not delivered, get it from file_picker + if (typeof fileName !== "string" || fileName=="") { + file_picker("/TDC_config", "*.json", saveTDCconfig, true); + return; + } + + //Make a list of all the displayed variables. Don't save anything else!! + let displayedODBkeys=[] + for (elem of ODBcontent_generalTDC.concat(ODBcontent_channelTDC,ODBcontent_channelHisto)){ + displayedODBkeys.push(elem.key); + } + //function scope helper function to achieve that + function rejectAdditionalKeys(obj){ + let reto={} + for(key in obj){ + if (displayedODBkeys.includes(key)){ + reto[key]= obj[key]; + } + } + return reto; + } + + //Get a "clean" extract, without metadata: + let request=new Object(); + request.paths=["/Experiment/Name",instrODB.tdcSettingsDir,instrODB.logicDir,instrODB.histogramDir]; + request.omit_names=true; + request.omit_last_written=true; + request.omit_tid=true; + request.omit_old_timestamp=true; + request.omit_old_timestamp=true; + request.preserve_case=true;//readability + + mjsonrpc_call("db_get_values", request).then(function(rpc) { + let config={}; + config["Instrument"]=rpc.result.data[0]; + config["Settings"]=rejectAdditionalKeys(rpc.result.data[1]); + config["Logic"]=rejectAdditionalKeys(rpc.result.data[2]); + config["Histograms"]=rejectAdditionalKeys(rpc.result.data[3]); + //convert to a string + let configJson=JSON.stringify(config, null, ' '); + //save + file_save_ascii(fileName, configJson, "ODB TDC configuration saved to file \"" + fileName + "\"."); + }).catch (function (error) { + console.error(error); + }); +} + +/* + Load a historic v1190 TDC configuration file. + Highlight the chosen settings next to the current settings. + + fileName: optional, file name to load. using file_picker if undefined or empty "". + + +*/ +function displayTDCv1190(fileName){ + loadTDCv1190(fileName,browseNewTDCconfiguration); +} + +/* + Load a historic v1190 TDC configuration file. + and parse it into a configuration json object, which then gets passed to callback. + + fileName: file name to load. using file_picker if undefined or empty "". + callback: function, will be called with a configuration .json object. + + +*/ + async function loadTDCv1190(fileName,callback){ + //TODO: this function cannot deal with the On/Off channel settings. (needed?) + + if (!callback) {//check if it was provided + console.error("loadTDCv1190: missing callback.") + return;} + + // function scope helper functions, to reduce repeated code. + function HistObj_to_loadConfig(loadConfig, histNumber, main_histo_channels, ch) { + loadConfig["Histograms"]["Number"][histNumber] = histNumber + 1; + loadConfig["Histograms"]["Name"][histNumber] = main_histo_channels[ch].Name; + loadConfig["Histograms"]["T0"][histNumber] = main_histo_channels[ch].T0; + loadConfig["Histograms"]["FirstGood"][histNumber] = main_histo_channels[ch].FirstGood; + loadConfig["Histograms"]["LastGood"][histNumber] = main_histo_channels[ch].LastGood; + loadConfig["Histograms"]["TDCchannels"][histNumber] = String(ch); + for (addch of main_histo_channels[ch].addHist) { + loadConfig["Histograms"]["TDCchannels"][histNumber] += " " + String(addch); + } + } + + // Finds the first instance of a string in an array and returns its index + function findIndexTDC(array, word) { + var regex = new RegExp("\\b" + word + "\\b"); + for (var i = 0; i < array.length; i++) { + if (regex.test(array[i])) { + return i; // Return the index if the word is found + } + } + return -1; // Return -1 if the word is not found in any string + } + + function findFirstNumberedIndexTDC(string, first) { + let indexNumbering = 0; + for (let x = 0; x < string.length; x++) { + if ((string[x].charAt(0) == '!' || !isNaN(string[x].charAt(0))) && first) { + indexNumbering = x; + first = false; + } + } + return indexNumbering; + } + + + + // if the file name is not delivered, get it from file_picker + if (typeof fileName !== "string" || fileName=="") { + file_picker("/TDC_config", "*.v1190", loadTDCv1190, false, callback); + return; + } + + + // Save the fileName to the global variable. + gTDClastLoadfileName = fileName; + + // Fetch the TDC-file and load it as text. + file_load_ascii(fileName, async function(text) { + + // Split each row + let newdataTest = text.split('\n'); + + // Find the first crucial element of the TDC file which + // spererates the general information of the TDC and + // the individual channel lines. + let index = findIndexTDC(newdataTest, 'INSTRUMENT'); + + let newdata = text.split('\n').slice(index); + + // Remove all the comments and unneccesary information from the TDC-file + const charsToCheck = ['\r', '$', '', '#']; + for (let x = 0; x < newdata.length; x++) { + if (charsToCheck.includes(newdata[x])) { + newdata.splice(x, 1); + x--; + } + } + + // Remove all unneccecary indents and empty spaces in each element + newdata.forEach((element, index) => { + newdata[index] = element.replace(/^\s+|\s+$/g, '').replace(/["/]+/g, ''); + }); + + // Dividing the general information and channel lines into two arrays + let indexNumbering = findFirstNumberedIndexTDC(newdata, true); + let generalInformation = newdata.slice(0, indexNumbering); + let channelLine = newdata.slice(indexNumbering); + + // Splitting each channel with ';' + channelLine = channelLine.map(element => element.split(";").map(item => item.trim())); + generalInformation = generalInformation.map(element => element.split("=").map(item => item.trim())); + // Removing empty elements + channelLine.forEach(element => { + if (element[element.length - 1] == '') { + element.pop(); + } + }); + + // Removes space between '! #ch' so we get '!#ch'. + channelLine.forEach((element, index) => { + channelLine[index][0] = element[0].replace(/\s/g, ''); + }); + + // Replace the '!#ch' to the Channel_Used type which + // is 'n' if '!' else 'y'. + for (let i = 0; i < channelLine.length; i++) { + try { + // Here we remove the '!' from Histo_Name. + if (channelLine[i][5].charAt(0) == '!') channelLine[i][5] = channelLine[i][5].slice(1); + channelLine[i][0] = (channelLine[i][0].charAt(0) == '!' ? 'n' : 'y'); + } + catch { channelLine[i][0] = (channelLine[i][0].charAt(0) == '!' ? 'n' : 'y'); } + } + + + //parse into a json object in the new format: + //initialize containers. + let loadConfig={ + "Settings": { + "Channel_OffSet":[], + }, + "Logic": { + "Channel_Used":[], + "Channel_Name":[], + "Channel_Type":[], + "Channel_Logic":[], + }, + "Histograms": { + "Number":[], + "Name":[], + "Length":[], + "xLow":[], + "xUp":[], + "T0":[], + "FirstGood":[], + "LastGood":[], + "PP_correction_post_logic":[], + "TDCchannels":[],}, + }; + + + // parse general section: + for (let i = 0; i < generalInformation.length; i++) { + switch(generalInformation[i][0]){ + case("INSTRUMENT"): + loadConfig["Instrument"]=generalInformation[i][1]; + break; + case("DESCRIPTION"): + loadConfig["Logic"]["Description"]=generalInformation[i][1]; + break; + case("TYPE"): + loadConfig["Settings"]["Type"]=generalInformation[i][1]; + break; + case("RESOLUTION"): + loadConfig["Settings"]["Time_Per_Bin"]=generalInformation[i][1]; + break; + case("MDELAY"): + loadConfig["Logic"]["Muon_Delay"]=generalInformation[i][1]; + break; + case("PDELAY"): + loadConfig["Logic"]["Positron_Delay"]=generalInformation[i][1]; + break; + case("MCOINCIDENCEW"): + loadConfig["Logic"]["Muon_Coincidence_Window"]=generalInformation[i][1]; + break; + case("PCOINCIDENCEW"): + loadConfig["Logic"]["Positron_Coincidence_Window"]=generalInformation[i][1]; + break; + case("VCOINCIDENCEW"): + loadConfig["Logic"]["Veto_Pre_Coincidence_Window"]=generalInformation[i][1]; + loadConfig["Logic"]["Veto_Post_Coincidence_Window"]=generalInformation[i][1]; + break; + default: + console.log("Unknown tdc configuration element: ", generalInformation[i][0]); + break; + } + } + + + let histlength = await mjsonrpc_db_get_value(instrODB.logicDir+"Data_Window").then((rpc)=>{ + return Number(rpc.result.data[0])+1;//Data_Window+1 + }).catch (function (error) { console.error(error);}); + console.log(histlength); + + + //defaults for missing values in old files: + let channelLineDefaults =[ + "n", // channel used + "Ch", //channel name + "N", // Detector type + 0, // t_offset + ";", //coincidence channel+ anti coincidence channels + "Ch", // histogram name + 0, //t0 + 1,//first + histlength-1,// last + "", //add to histogram + "", // name of combined histogram + ]; + + let loaded_value=0; + + + //histograms are resulting directly from the channels + //additional combined histograms can be created and pre-pendend. + let main_histo_channels={};//TDCchannelnumber: histogram object. + let additional_histo_channels={};//TDCchannelnumber: histogram object. + + // parse channel specific section: + for (let i = 0; i =histlength){//That would not be reasonable. Default to histogram lenght. + main_histo_channels[i].LastGood=histlength-1; + }else{ + main_histo_channels[i].LastGood=loaded_value; + } + } + break; + case 9: //add to histogram + if (loaded_value== ""||loaded_value== -1){ + break;//primary histogram, nothing to do. + } + if (!(loaded_value in main_histo_channels )){ + //something went wrong, there is no positron histogram we can add to: + console.error("Unknown history channel: ", loaded_value); + //skip to next channel + continue; + } + //check if we need to make a copy of the primary channel to a seperate additional histogram: + if (main_histo_channels[loaded_value].addHist.length==0){ + additional_histo_channels[loaded_value]=structuredClone(main_histo_channels[loaded_value]); + } + main_histo_channels[loaded_value].addHist.push(i); + //copy current histogram to additional channels + additional_histo_channels[i]=structuredClone(main_histo_channels[i]); + //remove it from main channels + delete main_histo_channels[i]; + break; + case 10: // name of combined histogram + //check if it is there: + if (loaded_value!= ""&&loaded_value.toUpperCase()!= "NONE"){ + //find out where to add it to: + let addTo=channelLine[i][9]; + if ((addTo!=='undefined') &&(addTo in main_histo_channels)){ + main_histo_channels[addTo].Name=loaded_value; + } + } + break; + default: + console.log("Unknown tdc configuration element: ", channelLine[i][j]); + break; + } + + } + + } + + // parse history configuration: + let histNumber=0; + for (const ch in main_histo_channels){ + //function scope helper function + HistObj_to_loadConfig(loadConfig, histNumber, main_histo_channels, ch); + histNumber++; + + } + for (const ch in additional_histo_channels){ + //function scope helper function + HistObj_to_loadConfig(loadConfig, histNumber, additional_histo_channels, ch); + histNumber++; + } + + //add default configurations + for (let i=0;i1){//ps to mu s + loadConfig["Settings"]['Time_Per_Bin']/=1000000; + } + //NOTE: the old value for the resolution was usually only approximately correct. + //Do not load the value!! + delete loadConfig["Settings"]['Time_Per_Bin']; + + callback(loadConfig); + }); + +} + +/** separate function to handle a data-window input change, in order to avoid races + * between the set button, and hitting enter on the input field. + * Calls changeDataWindow() when necessary. + */ +function dataWindowInputChanged(){ + //try doing nothing: + return; + /* + let changeButton = document.getElementById("tdc_DatWindow_button"); + //if button is already not on set anymore: nothing to do. + console.log(changeButton.value); + if (changeButton.value!="Set"){ + return; + } + //otherwise, do the equivalent of pressing the button. + changeDataWindow();*/ +} + +/*Functionality to handle the GUI functionality of chaning the data window*/ +function changeDataWindow() { + + let valueODB = document.getElementById("tdc_DatWindow_odb"); + let valueInput = document.getElementById("tdc_DatWindow_input"); + let changeButton = document.getElementById("tdc_DatWindow_button"); + + //Determine the state of the page + //Look at style.display, which in the default state shows valueODB + let mode_changing=(valueODB.style.display!="none"); + + //switch display and text to the other mode. + if (mode_changing){ // Hide the link and display the input box + valueODB.style.display = 'none'; + changeButton.value="Set"; + valueInput.style.display = 'inline'; + valueInput.value = parseFloat(valueODB.textContent); // Set the input value to the current value + // Automatically select the input box when the "Change" button is clicked + valueInput.focus(); + } + else { + valueODB.style.display = 'inline'; + changeButton.value="Change"; + valueInput.style.display = 'none'; + + let newValue = parseFloat(valueInput.value); + // get time per bin + + mjsonrpc_db_get_value(instrODB.tdcSettingsDir+"Time_Per_Bin").then((rpc)=>{ + let time_per_bin = Number(rpc.result.data[0]);//Data_Window+1 + //Determine Data window + newValue=Math.round(newValue/time_per_bin); + // If entered value is valid + if (!isNaN(newValue)) { + updateDataWindow(newValue); + } + }).catch (function (error) { console.error(error);}); + } + } + +/** + * Update the data window and histogram lengths in the odb. + * + * Data_Window=dataWindow + * Histogram Legnth=dataWindow+1 + * xUp=dataWindow+0.5 + * LastGood=dataWindow + * Pre_Pileup_Window = dataWindow + * Post_Pileup_Window = dataWindow, unless 0. + * + * @param {Number} dataWindow in number of tdc bins. + * */ +function updateDataWindow(dataWindow){ + //change values + modbset(instrODB.logicDir+"Data_Window",dataWindow); + modbset(instrODB.logicDir+"Pre_Pileup_Window",dataWindow); + + mjsonrpc_db_get_value(instrODB.logicDir+"Post_Pileup_Window").then((rpc)=>{ + let postPileupWindow=rpc.result.data[0]; + //only update it, if it is not zero. + if (postPileupWindow!=0){ + modbset(instrODB.logicDir+"Post_Pileup_Window",dataWindow);} + }).catch (function (error) { console.error(error);}); + + //simultaneously change arrays + //determine length first + mjsonrpc_db_get_value(instrODB.histogramDir+"Length").then((rpc)=>{ + let histLenghts=rpc.result.data[0]; + if(Array.isArray(histLenghts)){ + let len=histLenghts.length-1;//last index to adress array with. + //set all array elements to the same value + modbset(instrODB.histogramDir+"Length[0-"+len+"]",dataWindow+1); + modbset(instrODB.histogramDir+"xUp[0-"+len+"]",dataWindow+0.5); + modbset(instrODB.histogramDir+"LastGood[0-"+len+"]",dataWindow); + } else{ + console.error("Unable to change Histogram lengths. Not an array.") + } + }).catch (function (error) { console.error(error);}); +}; + + +/* --------------------------------------------------------------------------------------- + * + * Functions for the TDC statistics page + * +-----------------------------------------------------------------------------------------*/ + + + +/** +* Function to read the TDC status data and update the tdcStatus object +*/ +function loadTDCstatus() { + // Histogram and Scaler table ID:s. + tableIDs = ['Histo', 'Scaler']; + for (j in tableIDs) { + let tableID = tableIDs[j]; + if (document.getElementById(tableID) == undefined) return; + let str = ''; + + + // Construct the skeleton for the Histo table + if (tableID == 'Histo') { + str = ` + H# + Name + Rate + Total + + `; + } + // Construct the skeleton for the Scalers table + else { + str = ` + Name + Rate + Total + Rejected Rate + `; + } + + //Scaler + + // Retrieve the relevant data from tdcStatus based on the tableID + const ScalerName = tdcStatus['ScalerName']; + + for (let i = 0; i < ScalerName.length; i++) { + // Only fill if channel does not start with 'Ch' and channel_used is 'true'/'y'. + if (ScalerName[i][0] !== 'C' && ScalerName[i][1] !== 'h' && tdcStatus['Ch']['Used'][i] === true) { + let tempName = ''; + if (tableID === 'Scaler') { + str += ` + ${ScalerName[i]} + + M + + `; + } + } + } + + //Histograms + + // Retrieve the relevant data from tdcStatus based on the tableID + const HistoName = tdcStatus['HistoName']; + + for (let i = 0; i < HistoName.length; i++) { + /// If table is 'Histo', add a numbered index aside the 'Name'. + if (tableID === 'Histo') { + str += ` + + ${HistoName[i]} + + M + + `; + } + + } + // Set the HTML content of the table element to the generated string + document.getElementById(tableID).innerHTML = str; + } +} diff --git a/pages/elog.png b/pages/elog.png new file mode 100644 index 0000000..f1238c9 Binary files /dev/null and b/pages/elog.png differ diff --git a/pages/seqBlocks.js b/pages/seqBlocks.js new file mode 100644 index 0000000..fd65d9a --- /dev/null +++ b/pages/seqBlocks.js @@ -0,0 +1,1437 @@ +var commandsTemplate = { + gpsLTLoop: { + text: [ + "set temperature tempVal tempTol tempTime 1 100 120", + "wait temperature inrange tempTOut", + "TITLE c=titleVal", + "start histogram iHist stats" + ], + html: { + tempVal: { + parType: "input", + parClass: "prompPar", + parValue: "300:50:10", + parLabel: "Temperature list (comma separated or from:step:to)", + numCols: 2, + parUnit: "K" + }, + titleCheck: { + parType: "checkbox", + parClass: "prompPar", + parValue: false, + parLabel: "Use custom title", + numCols: 1, + parUnit: "" + }, + titleVal: { + parType: "input", + parClass: "prompPar", + parValue: "T Scan, Tset=tempVal K", + parLabel: "Custom Title", + numCols: 2, + parUnit: "K" + }, + tempTol: { + parType: "input", + parClass: "prompPar", + parValue: "0.5", + parLabel: "Tolerance", + numCols: 1, + parUnit: "K" + }, + tempTime: { + parType: "input", + parClass: "prompPar", + parValue: "120", + parLabel: "Stability Time", + numCols: 1, + parUnit: "sec" + }, + tempTOut: { + parType: "input", + parClass: "prompPar", + parValue: "300", + parLabel: "Time Out", + numCols: 1, + parUnit: "sec" + }, + stats: { + parType: "input", + parClass: "prompPar", + parValue: "3000000", + parLabel: "Stats", + numCols: 1, + parUnit: "Events" + }, + iHist: { + parType: "input", + parClass: "prompPar", + parValue: "3", + parLabel: "On Histogram #", + numCols: 1, + parUnit: "" + } + } + }, + gpsHTLoop: { + text: [ + "set flow flow flowVal", + "set temperature tempVal tempTol tempTime tempVal tempTol tempTime", + "wait temperature inrange tempTOut", + "TITLE c=titleVal", + "start histogram iHist stats" + ], + html: { + tempVal: { + parType: "input", + parClass: "prompPar", + parValue: "300:50:10", + parLabel: "Temperature list (comma separated or from:step:to)", + numCols: 2, + parUnit: "K" + }, + titleCheck: { + parType: "checkbox", + parClass: "prompPar", + parValue: false, + parLabel: "Use custom title", + numCols: 1, + parUnit: "" + }, + titleVal: { + parType: "input", + parClass: "prompPar", + parValue: "T Scan, Tset=tempVal K", + parLabel: "Custom Title", + numCols: 2, + parUnit: "K" + }, + tempTol: { + parType: "input", + parClass: "prompPar", + parValue: "0.5", + parLabel: "Tolerance", + numCols: 1, + parUnit: "K" + }, + tempTime: { + parType: "input", + parClass: "prompPar", + parValue: "120", + parLabel: "Stability Time", + numCols: 1, + parUnit: "sec" + }, + tempTOut: { + parType: "input", + parClass: "prompPar", + parValue: "300", + parLabel: "Time Out", + numCols: 1, + parUnit: "sec" + }, + stats: { + parType: "input", + parClass: "prompPar", + parValue: "3000000", + parLabel: "Stats", + numCols: 1, + parUnit: "Events" + }, + iHist: { + parType: "input", + parClass: "prompPar", + parValue: "3", + parLabel: "On Histogram #", + numCols: 1, + parUnit: "" + }, + flowVal: { + parType: "input", + parClass: "prompPar adjustPar", + parValue: "", + parLabel: "", + numCols: 1, + parUnit: "", + visibility: "hidden", + adjustFunc : "GPSFlow" + } + } + }, + cryoLoop : { + text: [ + "set cryostat tempVal tempTol tempTime tempVal tempTol tempTime 1 1 AP", + "wait cryostat inrange tempTOut", + "TITLE c=titleVal", + "start histogram iHist stats" + ], + html: { + tempVal: { + parType: "input", + parClass: "prompPar", + parValue: "300:50:10", + parLabel: "Temperature list (comma separated or from:step:to)", + numCols: 1, + parUnit: "K" + }, + titleCheck: { + parType: "checkbox", + parClass: "prompPar", + parValue: false, + parLabel: "Use custom title", + numCols: 1, + parUnit: "" + }, + titleVal: { + parType: "input", + parClass: "prompPar", + parValue: "T Scan, Tset=tempVal K", + parLabel: "Custom Title", + numCols: 2, + parUnit: "K" + }, + tempTol: { + parType: "input", + parClass: "prompPar", + parValue: "0.5", + parLabel: "Tolerance", + numCols: 1, + parUnit: "K" + }, + tempTime: { + parType: "input", + parClass: "prompPar", + parValue: "120", + parLabel: "Stability Time", + numCols: 1, + parUnit: "sec" + }, + tempTOut: { + parType: "input", + parClass: "prompPar", + parValue: "300", + parLabel: "Time Out", + numCols: 1, + parUnit: "sec" + }, + stats: { + parType: "input", + parClass: "prompPar", + parValue: "3000000", + parLabel: "Stats", + numCols: 1, + parUnit: "Events" + }, + iHist: { + parType: "input", + parClass: "prompPar", + parValue: "3", + parLabel: "On Histogram #", + numCols: 1, + parUnit: "" + } + } + }, + gpsTempHT : { + text: [ + "set flow flow flowVal", + "set temperature tempVal tempTol tempTime tempVal tempTol tempTime" + ], + html: { + tempVal: { + parType: "input", + parClass: "prompPar", + parValue: "100", + parLabel: "Temperature", + numCols: 1, + parUnit: "K" + }, + tempTol: { + parType: "input", + parClass: "prompPar", + parValue: "0.5", + parLabel: "Tolerance", + numCols: 1, + parUnit: "K" + }, + tempTime: { + parType: "input", + parClass: "prompPar", + parValue: "120", + parLabel: "Stability Time", + numCols: 1, + parUnit: "sec" + }, + tempTOut: { + parType: "input", + parClass: "prompPar", + parValue: "300", + parLabel: "Time Out", + numCols: 1, + parUnit: "sec" + }, + flowVal: { + parType: "input", + parClass: "prompPar", + parValue: "", + parLabel: "Flow (optional)", + numCols: 1, + parUnit: "sec" + } + } + }, + setCryo : { + text: [ + "set cryostat tempVal tempTol tempTime tempVal tempTol tempTime 1 1 AP" + ], + html: { + tempVal: { + parType: "input", + parClass: "prompPar", + parValue: "100", + parLabel: "Temperature", + numCols: 1, + parUnit: "K" + }, + tempTol: { + parType: "input", + parClass: "prompPar", + parValue: "0.5", + parLabel: "Tolerance", + numCols: 1, + parUnit: "K" + }, + tempTime: { + parType: "input", + parClass: "prompPar", + parValue: "120", + parLabel: "Stability Time", + numCols: 1, + parUnit: "sec" + }, + tempTOut: { + parType: "input", + parClass: "prompPar", + parValue: "300", + parLabel: "Time Out", + numCols: 1, + parUnit: "sec" + } + } + }, + gpsTempLT : { + text: [ + "set temperature tempVal tempTol tempTime 1.0 100 120" + ], + html: { + tempVal: { + parType: "input", + parClass: "prompPar", + parValue: "1.5", + parLabel: "Temperature", + numCols: 1, + parUnit: "K" + }, + tempTol: { + parType: "input", + parClass: "prompPar", + parValue: "0.5", + parLabel: "Tolerance", + numCols: 1, + parUnit: "K" + }, + tempTime: { + parType: "input", + parClass: "prompPar", + parValue: "120", + parLabel: "Stability Time", + numCols: 1, + parUnit: "sec" + }, + tempTOut: { + parType: "input", + parClass: "prompPar", + parValue: "300", + parLabel: "Time Out", + numCols: 1, + parUnit: "sec" + } + } + }, + gpsField : { + text: [ + "set magnet selMag fieldVal fieldTime" + ], + html: { + fieldVal: { + parType: "input", + parClass: "prompPar", + parValue: "100", + parLabel: "Field", + numCols: 1, + parUnit: "G" + }, + fieldTime: { + parType: "input", + parClass: "prompPar", + parValue: "120", + parLabel: "Stability Time", + numCols: 1, + parUnit: "sec" + }, + selMag: { + parType: "select", + parClass: "prompPar", + parOptions: ["WEP", "WED", "WEDL"], + parLabel: "Select Magnet", + numCols: 1, + parUnit: "" + } + } + }, + setODB : { + text: [ + "define odbPath odbVal" + ], + html: { + odbPath: { + parType: "input", + parClass: "prompPar", + parValue: "Equipment/dg5350/Variables/Output[0]", + parLabel: "ODB Path", + numCols: 1, + parUnit: "" + }, + odbVal: { + parType: "input", + parClass: "prompPar", + parValue: "0", + parLabel: "Set Value", + numCols: 1, + parUnit: "" + } + } + }, + setTitle : { + text: [ + "TITLE c=titleVal" + ], + html: { + titleVal: { + parType: "input", + parClass: "prompPar", + parValue: "This is a title", + parLabel: "Title", + numCols: 1, + parUnit: "" + } + } + }, + gpsFlow : { + text: [ + "set flow flow flowVal" + ], + html: { + flowVal: { + parType: "input", + parClass: "prompPar", + parValue: "5", + parLabel: "Flow", + numCols: 1, + parUnit: "sec", + min: "0.5", + max: "20" + } + } + }, + startRun : { + text: [ + "start histogram iHist stats" + ], + html: { + stats: { + parType: "input", + parClass: "prompPar", + parValue: "3000000", + parLabel: "Stats", + numCols: 1, + parUnit: "Events" + }, + iHist: { + parType: "input", + parClass: "prompPar", + parValue: "3", + parLabel: "On Histogram #", + numCols: 1 + } + } + }, + helioxLoop : { + text: [ + "set heliox tempVal tempTol tempTime 1 2 120 0", + "set heliox -1 -1 -1 -1 -1 -1 -1 pressVal", + "wait heliox inrange tempTOut", + "wait tempTime", + "TITLE c=titleVal", + "start histogram iHist stats" + ], + html: { + tempVal: { + parType: "input", + parClass: "prompPar", + parValue: "0.3:0.1:1.2", + parLabel: "Temperature list (comma separated or from:step:to)", + numCols: 1, + parUnit: "K" + }, + titleCheck: { + parType: "checkbox", + parClass: "prompPar", + parLabel: "Use custom title", + numCols: 1 + }, + titleVal: { + parType: "input", + parClass: "prompPar", + parValue: "T Scan, Tset=tempVal K", + parLabel: "Custom Title", + numCols: 2 + }, + tempTol: { + parType: "input", + parClass: "prompPar", + parValue: "0.02", + parLabel: "Tolerance", + numCols: 1, + parUnit: "K" + }, + tempTime: { + parType: "input", + parClass: "prompPar", + parValue: "120", + parLabel: "Stability Time", + numCols: 1, + parUnit: "sec" + }, + tempTOut: { + parType: "input", + parClass: "prompPar", + parValue: "900", + parLabel: "Time Out", + numCols: 1, + parUnit: "sec" + }, + pressVal: { + parType: "input", + parClass: "prompPar", + parValue: "", + parLabel: "Pressure (AP for automatic)", + numCols: 1, + parUnit: "mbar" + }, + stats: { + parType: "input", + parClass: "prompPar", + parValue: "3000000", + parLabel: "Stats", + numCols: 1, + parUnit: "Events" + }, + iHist: { + parType: "input", + parClass: "prompPar", + parValue: "3", + parLabel: "On Histogram #", + numCols: 1 + } + } + }, + varioxLTLoop : { + text: [ + "set variox tempVal tempTol tempTime 1 10 120 pressureVal", + "wait variox inrange tempTOut", + "wait 120", + "TITLE c=titleVal", + "start histogram iHist stats" + ], + html: { + tempVal: { + parType: "input", + parClass: "prompPar", + parValue: "1:1:10", + parLabel: "Temperature list (comma separated or from:step:to)", + numCols: 1, + parUnit: "K" + }, + titleCheck: { + parType: "checkbox", + parClass: "prompPar", + parLabel: "Use custom title", + numCols: 1 + }, + titleVal: { + parType: "input", + parClass: "prompPar", + parValue: "T Scan, Tset=tempVal K", + parLabel: "Custom Title", + numCols: 2 + }, + tempTol: { + parType: "input", + parClass: "prompPar", + parValue: "0.5", + parLabel: "Tolerance", + numCols: 1, + parUnit: "K" + }, + tempTime: { + parType: "input", + parClass: "prompPar", + parValue: "120", + parLabel: "Stability Time", + numCols: 1, + parUnit: "sec" + }, + tempTOut: { + parType: "input", + parClass: "prompPar", + parValue: "300", + parLabel: "Time Out", + numCols: 1, + parUnit: "sec" + }, + pressureVal: { + parType: "input", + parClass: "prompPar", + parValue: "", + parLabel: "Pressure (AP for automatic)", + numCols: 1, + parUnit: "mbar" + }, + stats: { + parType: "input", + parClass: "prompPar", + parValue: "3000000", + parLabel: "Stats", + numCols: 1, + parUnit: "Events" + }, + iHist: { + parType: "input", + parClass: "prompPar", + parValue: "3", + parLabel: "On Histogram #", + numCols: 1 + } + } + }, + varioxHTLoop : { + text: [ + "set variox tempVal tempTol tempTime tempVal tempTol tempTime pressureVal", + "wait variox inrange tempTOut", + "wait 120", + "TITLE c=titleVal", + "start histogram iHist stats" + ], + html: { + tempVal: { + parType: "input", + parClass: "prompPar", + parValue: "10:50:300", + parLabel: "Temperature list (comma separated or from:step:to)", + numCols: 1, + parUnit: "K" + }, + titleCheck: { + parType: "checkbox", + parClass: "prompPar", + parLabel: "Use custom title", + numCols: 1 + }, + titleVal: { + parType: "input", + parClass: "prompPar", + parValue: "T Scan, Tset=tempVal K", + parLabel: "Custom Title", + numCols: 2 + }, + tempTol: { + parType: "input", + parClass: "prompPar", + parValue: "0.5", + parLabel: "Tolerance", + numCols: 1, + parUnit: "K" + }, + tempTime: { + parType: "input", + parClass: "prompPar", + parValue: "120", + parLabel: "Stability Time", + numCols: 1, + parUnit: "sec" + }, + tempTOut: { + parType: "input", + parClass: "prompPar", + parValue: "300", + parLabel: "Time Out", + numCols: 1, + parUnit: "sec" + }, + pressureVal: { + parType: "input", + parClass: "prompPar", + parValue: "", + parLabel: "Pressure (AP for automatic)", + numCols: 1, + parUnit: "mbar" + }, + stats: { + parType: "input", + parClass: "prompPar", + parValue: "3000000", + parLabel: "Stats", + numCols: 1, + parUnit: "Events" + }, + iHist: { + parType: "input", + parClass: "prompPar", + parValue: "3", + parLabel: "On Histogram #", + numCols: 1 + } + } + }, + dollyField : { + text: [ + "set magnet selMag fieldVal fieldTime" + ], + html: { + fieldVal: { + parType: "input", + parClass: "prompPar", + parValue: "100", + parLabel: "Field", + numCols: 1, + parUnit: "G" + }, + fieldTime: { + parType: "input", + parClass: "prompPar", + parValue: "120", + parLabel: "Stability Time", + numCols: 1, + parUnit: "sec" + }, + selMag: { + parType: "select", + parClass: "prompPar", + parOptions: ["WEU", "WEUL", "WEV"], + parLabel: "Select Magnet", + numCols: 1 + } + } + }, + dollyBLoop : { + text: [ + "set magnet selMag fieldVal fieldTime", + "TITLE c=titleVal", + "start histogram iHist stats" + ], + html: { + fieldVal: { + parType: "input", + parClass: "prompPar", + parValue: "10:10:100", + parLabel: "Field list (comma separated or from:step:to)", + numCols: 1, + parUnit: "G" + }, + titleCheck: { + parType: "checkbox", + parClass: "prompPar", + parLabel: "Use custom title", + numCols: 1 + }, + titleVal: { + parType: "input", + parClass: "prompPar", + parValue: "B Scan, B=fieldVal G", + parLabel: "Custom Title", + numCols: 2 + }, + fieldTime: { + parType: "input", + parClass: "prompPar", + parValue: "120", + parLabel: "Stability Time", + numCols: 1, + parUnit: "sec" + }, + selMag: { + parType: "select", + parClass: "prompPar", + parOptions: ["WEU", "WEUL", "WEV"], + parLabel: "Select Magnet", + numCols: 1 + }, + stats: { + parType: "input", + parClass: "prompPar", + parValue: "3000000", + parLabel: "Stats", + numCols: 1, + parUnit: "Events" + }, + iHist: { + parType: "input", + parClass: "prompPar", + parValue: "3", + parLabel: "On Histogram #", + numCols: 1 + } + } + }, + varioxTemp : { + text: [ + "set variox tempVal tempTol tempTime tempVal tempTol tempTime 1 1 pressureVal", + "wait variox inrange tempTOut" + ], + html: { + tempVal: { + parType: "input", + parClass: "prompPar", + parValue: "100", + parLabel: "Temperature", + numCols: 1, + parUnit: "K" + }, + tempTol: { + parType: "input", + parClass: "prompPar", + parValue: "0.5", + parLabel: "Tolerance", + numCols: 1, + parUnit: "K" + }, + tempTime: { + parType: "input", + parClass: "prompPar", + parValue: "120", + parLabel: "Stability Time", + numCols: 1, + parUnit: "sec" + }, + tempTOut: { + parType: "input", + parClass: "prompPar", + parValue: "300", + parLabel: "Time Out", + numCols: 1, + parUnit: "sec" + }, + pressureVal: { + parType: "input", + parClass: "prompPar", + parValue: "", + parLabel: "Pressure (AP for automatic)", + numCols: 1, + parUnit: "mbar" + } + } + }, + helioxTemp : { + text: [ + "heliox tempVal tempTol tempTime 1 2 120 0", + "set heliox -1 -1 -1 -1 -1 -1 -1 pressVal", + "wait heliox inrange tempTOut" + ], + html: { + tempVal: { + parType: "input", + parClass: "prompPar", + parValue: "0.4", + parLabel: "Temperature", + numCols: 1, + parUnit: "K" + }, + tempTol: { + parType: "input", + parClass: "prompPar", + parValue: "0.02", + parLabel: "Tolerance", + numCols: 1, + parUnit: "K" + }, + tempTime: { + parType: "input", + parClass: "prompPar", + parValue: "120", + parLabel: "Stability Time", + numCols: 1, + parUnit: "sec" + }, + tempTOut: { + parType: "input", + parClass: "prompPar", + parValue: "3000", + parLabel: "Time Out", + numCols: 1, + parUnit: "sec" + }, + pressVal: { + parType: "input", + parClass: "prompPar", + parValue: "", + parLabel: "Pressure (optional)", + numCols: 1, + parUnit: "mbar" + } + } + }, + halField : { + text: [ + "WAIT Magnet 4KOPSREADY", + "SET Magnet fieldVal", + "WAIT Magnet ATFIELD", + "WAIT 300" + ], + html: { + fieldVal: { + parType: "input", + parClass: "prompPar", + parValue: "7.0", + parLabel: "Field target", + numCols: 1, + parUnit: "T" + } + } + }, + halSlits : { + text: [ + "MULTISET FS71 slitVal", + "WAIT 5", + "MULTISET FS72 slitVal", + "WAIT 60" + ], + html: { + slitVal: { + parType: "input", + parClass: "prompPar", + parValue: "50.0", + parLabel: "Slits", + numCols: 1, + parUnit: "mm" + } + } + }, + halJanisLoop : { + text: [ + 'set gfcflowc0 "BH Flow Setpoint" flowJanisVal 300', + "set Temperature_Janis tempVal tempTol tempTime tempVal tempTol tempTime", + "set mcu2000 FLC posJanisVal 120", + "wait Temperature_Janis inrange tempTOut", + "wait 300", + "TITLE c=titleVal", + "start histogram iHist stats" + ], + html: { + tempVal: { + parType: "input", + parClass: "prompPar", + parValue: "300:50:10", + parLabel: "Temperature list (comma separated or from:step:to)", + numCols: 1, + parUnit: "K" + }, + titleCheck: { + parType: "checkbox", + parClass: "prompPar", + parLabel: "Use custom title", + numCols: 1 + }, + titleVal: { + parType: "input", + parClass: "prompPar", + parValue: "T Scan, Tset=tempVal K", + parLabel: "Custom Title", + numCols: 2 + }, + tempTol: { + parType: "input", + parClass: "prompPar", + parValue: "0.5", + parLabel: "Tolerance", + numCols: 1, + parUnit: "K" + }, + tempTime: { + parType: "input", + parClass: "prompPar", + parValue: "120", + parLabel: "Stability Time", + numCols: 1, + parUnit: "sec" + }, + tempTOut: { + parType: "input", + parClass: "prompPar", + parValue: "300", + parLabel: "Time Out", + numCols: 1, + parUnit: "sec" + }, + stats: { + parType: "input", + parClass: "prompPar", + parValue: "3000000", + parLabel: "Stats", + numCols: 1, + parUnit: "Events" + }, + iHist: { + parType: "input", + parClass: "prompPar", + parValue: "3", + parLabel: "On Histogram #", + numCols: 1 + }, + flowJanisVal: { + parType: "input", + parClass: "prompPar adjustPar", + parValue: "", + parLabel: "Flow (optional)", + numCols: 1, + parUnit: "l/min", + adjustFunc : "HALJanisFlow" + }, + posJanisVal: { + parType: "input", + parClass: "prompPar adjustPar", + parValue: "", + parLabel: "Position (optional)", + numCols: 1, + parUnit: "mm", + adjustFunc : "HALJanisPos" + }, + } + }, + halJanisTemp : { + text: [ + 'set gfcflowc0 "BH Flow Setpoint" flowJanisVal 300', + "set Temperature_Janis tempVal tempTol tempTime tempVal tempTol tempTime", + "set mcu2000 FLC posJanisVal 120", + "wait Temperature_Janis inrange tempTOut" + ], + html: { + tempVal: { + parType: "input", + parClass: "prompPar", + parValue: "300:50:10", + parLabel: "Temperature list (comma separated or from:step:to)", + numCols: 1, + parUnit: "K" + }, + tempTol: { + parType: "input", + parClass: "prompPar", + parValue: "0.5", + parLabel: "Tolerance", + numCols: 1, + parUnit: "K" + }, + tempTime: { + parType: "input", + parClass: "prompPar", + parValue: "120", + parLabel: "Stability Time", + numCols: 1, + parUnit: "sec" + }, + tempTOut: { + parType: "input", + parClass: "prompPar", + parValue: "300", + parLabel: "Time Out", + numCols: 1, + parUnit: "sec" + }, + flowJanisVal: { + parType: "input", + parClass: "prompPar", + parValue: "", + parLabel: "Flow (optional)", + numCols: 1, + parUnit: "l/min" + }, + posJanisVal: { + parType: "input", + parClass: "prompPar", + parValue: "", + parLabel: "Position (optional)", + numCols: 1, + parUnit: "mm" + } + } + }, + flameTWLLT : { + text: [ + "set flamesam0 SAM_ts_tolerance tempTol", + "set flamesam0 SAM_ts_settling_time tempTime", + "set flamesam0 SAM_ts_timeout tempTOut", + "set flamesam0 SAM_ts_target tempVal", + "wait flamesam0 SAM_ts_status <= 100 tempTOut" + ], + html: { + tempVal: { + parType: "input", + parClass: "prompPar", + parValue: "0.1", + parLabel: "Temperature", + numCols: 1, + parUnit: "K" + }, + tempTol: { + parType: "input", + parClass: "prompPar", + parValue: "0.05", + parLabel: "Tolerance", + numCols: 1, + parUnit: "K" + }, + tempTime: { + parType: "input", + parClass: "prompPar", + parValue: "180", + parLabel: "Stability Time", + numCols: 1, + parUnit: "sec" + }, + tempTOut: { + parType: "input", + parClass: "prompPar", + parValue: "1800", + parLabel: "Time Out", + numCols: 1, + parUnit: "sec" + }, + } + }, + flameWLLTLoop : { + text: [ + "set flamesam0 SAM_ts_tolerance tempTol", + "set flamesam0 SAM_ts_settling_time tempTime", + "set flamesam0 SAM_ts_timeout tempTOut", + "set flamesam0 SAM_ts_target tempVal", + "wait flamesam0 SAM_ts_status <= 100 tempTOut", + "TITLE c=titleVal", + "start histogram iHist stats" + ], + html: { + titleCheck: { + parType: "checkbox", + parClass: "prompPar", + parValue: false, + parLabel: "Use custom title", + numCols: 1, + parUnit: "" + }, + titleVal: { + parType: "input", + parClass: "prompPar", + parValue: "T Scan, Tset=tempVal K", + parLabel: "Custom Title", + numCols: 2, + parUnit: "K" + }, + tempVal: { + parType: "input", + parClass: "prompPar", + parValue: "0.1:0.1:1", + parLabel: "Temperature list (comma separated or from:step:to)", + numCols: 2, + parUnit: "K" + }, + tempTol: { + parType: "input", + parClass: "prompPar", + parValue: "0.05", + parLabel: "Tolerance", + numCols: 1, + parUnit: "K" + }, + tempTime: { + parType: "input", + parClass: "prompPar", + parValue: "180", + parLabel: "Stability Time", + numCols: 1, + parUnit: "sec" + }, + tempTOut: { + parType: "input", + parClass: "prompPar", + parValue: "1800", + parLabel: "Time Out", + numCols: 1, + parUnit: "sec" + }, + stats: { + parType: "input", + parClass: "prompPar", + parValue: "5000000", + parLabel: "Stats", + numCols: 1, + parUnit: "Events" + }, + iHist: { + parType: "input", + parClass: "prompPar", + parValue: "2", + parLabel: "On Histogram #", + numCols: 1, + parUnit: "" + }, + }, + }, + flameTWLHT : { + text: [ + "set flamesam0 SAM_ts_tolerance tempTol", + "set flamesam0 SAM_ts_settling_time tempTime", + "set flamesam0 SAM_ts_timeout tempTOut", + "set cryostat tempVal tempTol tempTime 1 300 120 1 0 MP 4.5", + "set flamesam0 SAM_ts_target tempVal", + "wait cryostat inrange tempTOut", + "WAIT flamesam0 SAM_ts_status <= 100 tempTOut" + ], + html: { + tempVal: { + parType: "input", + parClass: "prompPar", + parValue: "15", + parLabel: "Temperature", + numCols: 1, + parUnit: "K" + }, + tempTol: { + parType: "input", + parClass: "prompPar", + parValue: "0.5", + parLabel: "Tolerance", + numCols: 1, + parUnit: "K" + }, + tempTime: { + parType: "input", + parClass: "prompPar", + parValue: "180", + parLabel: "Stability Time", + numCols: 1, + parUnit: "sec" + }, + tempTOut: { + parType: "input", + parClass: "prompPar", + parValue: "1800", + parLabel: "Time Out", + numCols: 1, + parUnit: "sec" + }, + } + }, + flameWLHTLoop : { + text: [ + "set flamesam0 SAM_ts_tolerance tempTol", + "set flamesam0 SAM_ts_settling_time tempTime", + "set flamesam0 SAM_ts_timeout tempTOut", + "set cryostat tempVal tempTol tempTime 1 300 120 1 0 MP 4.5", + "set flamesam0 SAM_ts_target tempVal", + "wait cryostat inrange tempTOut", + "WAIT flamesam0 SAM_ts_status <= 100 tempTOut", + "TITLE c=titleVal", + "start histogram iHist stats" + ], + html: { + titleCheck: { + parType: "checkbox", + parClass: "prompPar", + parValue: false, + parLabel: "Use custom title", + numCols: 1, + parUnit: "" + }, + titleVal: { + parType: "input", + parClass: "prompPar", + parValue: "T Scan, Tset=tempVal K", + parLabel: "Custom Title", + numCols: 2, + parUnit: "K" + }, + tempVal: { + parType: "input", + parClass: "prompPar", + parValue: "2.5:0.5:10", + parLabel: "Temperature list (comma separated or from:step:to)", + numCols: 2, + parUnit: "K" + }, + tempTol: { + parType: "input", + parClass: "prompPar", + parValue: "0.2", + parLabel: "Tolerance", + numCols: 1, + parUnit: "K" + }, + tempTime: { + parType: "input", + parClass: "prompPar", + parValue: "180", + parLabel: "Stability Time", + numCols: 1, + parUnit: "sec" + }, + tempTOut: { + parType: "input", + parClass: "prompPar", + parValue: "1800", + parLabel: "Time Out", + numCols: 1, + parUnit: "sec" + }, + stats: { + parType: "input", + parClass: "prompPar", + parValue: "5000000", + parLabel: "Stats", + numCols: 1, + parUnit: "Events" + }, + iHist: { + parType: "input", + parClass: "prompPar", + parValue: "2", + parLabel: "On Histogram #", + numCols: 1, + parUnit: "" + }, + }, + }, + flameLT2HT : { + text: [ + "set flamedil0 DIL_dil_action_target 3", + "WAIT 120", + "set flamedil0 DIL_htr_sorb_target 350000", + "WAIT 120", + "set cryostat 20 0.3 120 1 100 120 1 0 MP 4.5", + "WAIT cryostat inrange", + "WAIT flamedil0 DIL_p_still_value <= 0.01 1800" + ], + html: {}, + } +}; + + +// Function to generate HTML form from a configuration object +function generateHTMLFromConfig(config) { + const html = []; + let objConfig = commandsTemplate[config]; + for (const paramName in objConfig.html) { + const paramConfig = objConfig.html[paramName]; + const inputType = paramConfig.parType; + const inputClass = paramConfig.parClass; + const inputValue = paramConfig.parValue; + const inputLabel = paramConfig.parLabel; + const numCols = paramConfig.numCols || 1; + const parUnit = paramConfig.parUnit || ''; + const parOptions = paramConfig.parOptions || ''; + + let inputElement = ''; + + if (inputType === 'input') { + inputElement = ``; + } else if (inputType === 'checkbox') { + inputElement = ``; + } else if (inputType === 'select') { + inputElement = `'; + } + + let inputRow = `${inputLabel}${inputElement} ${parUnit}`; + if (numCols == 2) { + inputRow = `${inputLabel}${inputElement} ${parUnit}`; + } + html.push(inputRow); + } + + return html.join(''); +} + +// Function to generate text command from a configuration object +function generateTextFromConfig(config) { + let objConfig = commandsTemplate[config]; + return objConfig.text.join('\n'); +} + + +function insertSeqBlock(element) { + let elId = element; + if (typeof element !== "string") { + elId = element.id; + } + + const larEditor = document.getElementById("larEditor"); + let enablePop = document.getElementById("enablePop").checked; + + let html = generateHTMLFromConfig(elId); + let text = generateTextFromConfig(elId) + "\n"; + if (html == "") enablePop = false; + html = "
" + html + "

Block:
"+text+"
" + + let sel, range, newNode; + newNode = document.createElement("pre"); + // Cursor in editing + larEditor.focus(); + if (document.getSelection) { + sel = document.getSelection(); + // If anything is selected + if (sel.getRangeAt && sel.rangeCount) { + // Only if cursor is in larEditor + if (larEditor.contains(sel.getRangeAt(0).startContainer)) { + range = sel.getRangeAt(0); + range.deleteContents(); + range.insertNode(newNode); + } else { + alert("Cursor must be in the editing area!"); + return(0); + } + } else { + alert("Cursor must be in the editing area!"); + return(0); + } + } + newNode.innerHTML = "
preparing ....
"; + + if (enablePop) { + d = general_dialog(html,"popPrompt"); + const button = document.getElementById("popButton"); + console.log(button); + button.textContent = "Submit"; + button.addEventListener("click",promptSeqParams); + button.addEventListener("click",closeModal); + button.addEventListener("click",checkSyntax); + } else { + // Use defaults + text = subSeqDefaults(text); + newNode.innerHTML = text+"
"; + checkSyntax(); + } + + +} diff --git a/pages/tabs/Graph.ico b/pages/tabs/Graph.ico new file mode 100644 index 0000000..2af9c00 Binary files /dev/null and b/pages/tabs/Graph.ico differ diff --git a/pages/tabs/TDCstatus_tab.html b/pages/tabs/TDCstatus_tab.html new file mode 100644 index 0000000..384df81 --- /dev/null +++ b/pages/tabs/TDCstatus_tab.html @@ -0,0 +1,32 @@ + + + + + Statistics + + + + + + + +
+
+
+ Histogram + +
+
+
+
+
+ Scalers + +
+
+
+
+
+
+ +