server.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. import time
  2. from struct import *
  3. import ctypes
  4. import array
  5. import numpy as np
  6. import matplotlib.pyplot as plt
  7. import eel # GUI
  8. #from ADUCv2p1 import * # TO DO
  9. ###################################
  10. ## PYTHON UTILITIES
  11. ###################################
  12. last_wf_number = -1;
  13. last_timestamp = 0
  14. def save_waveform():
  15. chip = chips[state["selected_board"]]
  16. data = chip.read_data()
  17. gnd = sum(data[state["start_gnd"]:state["stop_gnd"]])/(state["stop_gnd"]-state["start_gnd"])
  18. signal = sum(data[state["start"]:state["stop"]])/(state["stop"]-state["start"])
  19. gnd_std = np.std(data[state["start_gnd"]:state["stop_gnd"]])
  20. signal_std = np.std(data[state["start"]:state["stop"]])
  21. wf_number = chip.get_wf_cnt()
  22. if(last_wf_number>0):
  23. state["board_freq"] = (timestamp - last_timestamp)/(wf_number - last_wf_number)
  24. last_wf_number, last_timestamp = wf_number, timestamp
  25. timestamp = time.time()
  26. tosave = [wf_number, timestamp, state["start"], state["stop"], state["start_gnd"], state["stop_gnd"], state["input_gain"], state["offset"], signal, gnd, signal_std, gnd_std, state["wf_len"]] + list(data)
  27. np.savetxt("data/waveforms/"+str(int(timestamp*100))+".csv", [tosave], delimiter=",", fmt='%10.5f')
  28. # Save more data for long term graphs
  29. tosave = [wf_number, timestamp, signal, gnd, signal-gnd, signal_std, gnd_std, chip.get_mode(), chip.get_out_of_lock(), chip.getVout(1), chip.getVout(2)]
  30. line = '\n'+','.join(map(str, tosave))
  31. with open('data/long_term.csv','a') as fd:
  32. fd.write(line)
  33. update_state()
  34. import datetime
  35. def clean_old_files():
  36. for dirpath, dirnames, filenames in os.walk("data/waveforms/"):
  37. for file in filenames:
  38. curpath = os.path.join(dirpath, file)
  39. file_modified = datetime.datetime.fromtimestamp(os.path.getmtime(curpath))
  40. if datetime.datetime.now() - file_modified > datetime.timedelta(hours=10):
  41. os.remove(curpath)
  42. @eel.expose
  43. def calibrate_gain():
  44. if(state["mode"]!=0):
  45. error("You must be in learn mode to calibrate the loop gain")
  46. return
  47. chip = chips[state["selected_board"]]
  48. auto_set_pga = state["auto_set_pga"]
  49. chip.set_auto_set_pga(0) #Stop it while we scan
  50. measurements = []
  51. for Vfine in range(2000, 4000, 100):
  52. chip.set_Vout(2, Vfine)
  53. time.sleep(0.1)
  54. data = chip.read_data()
  55. gnd = sum(data[state["start_gnd"]:state["stop_gnd"]])/(state["stop_gnd"]-state["start_gnd"])
  56. signal = sum(data[state["start"]:state["stop"]])/(state["stop"]-state["start"])
  57. print('Vfine', chip.get_Vout(2), 'signal', signal-gnd)
  58. measurements.append([chip.get_Vout(2), signal-gnd])
  59. chip.set_Vout(2, 3000)
  60. measurements = np.array(measurements)
  61. p = np.polyfit(measurements[:,0], measurements[:,1], deg=1)
  62. print('signal-gnd vs Vfine slope', p[0])
  63. chip.set_Gain(1/p[0])
  64. print('Gain has been set to 1/slope', 1/p[0])
  65. plt.plot(np.arange(2000, 4000, 100), measurements)
  66. plt.plot(np.range(2000, 4000, 100), np.range(2000, 4000, 100)*p[0] + p[1])
  67. plt.show()
  68. chip.set_auto_set_pga(auto_set_pga)
  69. update_state()
  70. @eel.expose
  71. def calibrate_coarse_fine_ratio():
  72. if(state["mode"]!=0):
  73. error("You must be in learn mode to calibrate the broad to fine ratio")
  74. return
  75. chip = chips[state["selected_board"]]
  76. auto_set_pga = state["auto_set_pga"]
  77. chip.set_auto_set_pga(0) #Stop it while we scan
  78. # Scan Vfine
  79. measurements = []
  80. for Vfine in range(2500, 3500, 100):
  81. chip.set_Vout(2, Vfine)
  82. time.sleep(0.1)
  83. data = chip.read_data()
  84. gnd = sum(data[state["start_gnd"]:state["stop_gnd"]])/(state["stop_gnd"]-state["start_gnd"])
  85. signal = sum(data[state["start"]:state["stop"]])/(state["stop"]-state["start"])
  86. print('Vfine', chip.get_Vout(2), 'signal', signal-gnd)
  87. measurements.append([chip.get_Vout(2), signal-gnd])
  88. chip.set_Vout(2, 3000)
  89. measurements = np.array(measurements)
  90. p = np.polyfit(measurements[:,0], measurements[:,1], deg=1)
  91. # Scan Vcoarse
  92. measurements = []
  93. low, high = state["Vlearn"]-100, state["Vlearn"]+100
  94. if(low<0):
  95. low=0
  96. if(high>4000):
  97. high=4000
  98. for Vcoarse in range(low, high, 20):
  99. chip.set_Vlearn(Vcoarse)
  100. time.sleep(0.1)
  101. data = chip.read_data()
  102. gnd = sum(data[state["start_gnd"]:state["stop_gnd"]])/(state["stop_gnd"]-state["start_gnd"])
  103. signal = sum(data[state["start"]:state["stop"]])/(state["stop"]-state["start"])
  104. print('Vcoarse', chip.get_Vlearn(), 'signal', signal-gnd)
  105. measurements.append([chip.get_Vlearn(), signal-gnd])
  106. chip.set_Vlearn(state["Vlearn"])
  107. measurements = np.array(measurements)
  108. q = np.polyfit(measurements[:,0], measurements[:,1], deg=1)
  109. # Set to ratio
  110. chip.set_coarse_fine_ratio(q[0]/p[0])
  111. chip.set_auto_set_pga(auto_set_pga)
  112. update_state()
  113. @eel.expose
  114. def measure_response_function():
  115. if(state["mode"]!=0):
  116. error("You must be in learn mode to measure the response function.")
  117. return
  118. chip = chips[state["selected_board"]]
  119. auto_set_pga = state["auto_set_pga"]
  120. chip.set_auto_set_pga(0) #Stop it while we scan
  121. # Scan Vcoarse
  122. measurements = []
  123. for Vcoarse in range(0, 4000, 100):
  124. chip.set_Vlearn(Vcoarse)
  125. time.sleep(0.1)
  126. data = chip.read_data()
  127. gnd = sum(data[state["start_gnd"]:state["stop_gnd"]])/(state["stop_gnd"]-state["start_gnd"])
  128. signal = sum(data[state["start"]:state["stop"]])/(state["stop"]-state["start"])
  129. print('Vcoarse', chip.get_Vlearn(), 'signal', signal-gnd)
  130. measurements.append([chip.get_Vlearn(), signal-gnd])
  131. chip.set_Vlearn(state["Vlearn"])
  132. measurements = np.array(measurements)
  133. plt.plot(measurements[:,0], measurements[:,1])
  134. plt.xlabel('Output voltage')
  135. plt.ylabel('Photodiode signal')
  136. plt.plot()
  137. chip.set_auto_set_pga(auto_set_pga)
  138. update_state()
  139. @eel.expose
  140. def sdev_time():
  141. pass
  142. @eel.expose
  143. def noise_power_spectrum():
  144. pass
  145. ###################################
  146. ## EXPOSED GUI COMMUNICATION
  147. ###################################
  148. # Graphs
  149. from os import listdir
  150. @eel.expose
  151. def listFiles(path):
  152. return listdir(path)
  153. @eel.expose
  154. def loadFile(path):
  155. return list(np.loadtxt(path, delimiter=","))
  156. @eel.expose
  157. def loadLongTerm():
  158. li = list(np.loadtxt('data/long_term.csv', delimiter=","))
  159. if((li[-1][1]-li[0][1])/60/60 > 24 or len(li)>100000): # Time to clean up, delete until we have less than 90000 points and 20 hours of data
  160. with open('data/long_term.csv') as f, open("data/long_term_tmp.csv", "w") as out:
  161. for x in range(len(li)):
  162. if(len(li)-x>90000 or (li[-1][1]-li[x][1])/60/60 > 20):
  163. next(f)
  164. for line in f:
  165. out.write(line)
  166. os.remove("data/long_term.csv")
  167. os.rename("data/long_term_tmp.csv", "data/long_term.csv")
  168. return [list(l) for l in li]
  169. # Expose functions to GUI and do some parameter checking
  170. def error(txt):
  171. eel.error(txt)
  172. def warning(txt):
  173. eel.warning(txt)
  174. @eel.expose
  175. def set_selected_board(n):
  176. if n>len(chips):
  177. error("Selected board does not exist.")
  178. return;
  179. state["selected_board"] = n
  180. update_state()
  181. @eel.expose
  182. def set_pi_freq(freq):
  183. if(freq>100):
  184. error("The communication cannot be this fast. High values are likely to disturb the board.")
  185. return
  186. if(freq<0.2):
  187. error("Frequency must be at least 0.2Hz.")
  188. return
  189. if(freq>10):
  190. warning("High values are likely to disturb the board.")
  191. state["pi_freq"] = freq
  192. eel.renderUI(state)
  193. @eel.expose
  194. def set_remote_trigg(status):
  195. status = int(status)
  196. if status not in [0, 1]:
  197. error("remote_trigg must be set to either 0 or 1.")
  198. return
  199. return chips[state["selected_board"]].set_remote_trigg(status)
  200. update_state()
  201. @eel.expose
  202. def set_enab_gnd(status):
  203. status = int(status)
  204. if status not in [0, 1]:
  205. error("enab_gnd must be set to either 0 or 1.")
  206. return
  207. return chips[state["selected_board"]].set_enab_gnd(status)
  208. update_state()
  209. @eel.expose
  210. def set_Vlearn(Vlearn):
  211. if Vlearn>4095 or Vlearn<0:
  212. error("Vlearn must be in the range 0-4095")
  213. return
  214. if Vlearn<2000:
  215. warning("Low values of Vlearn will heavily attenuate the output. See the response curve.")
  216. if Vlearn>3500:
  217. warning("High values of Vlearn may not leave enough room for the stabilization process and may result in the board going out of loop. See the response curve.")
  218. return chips[state["selected_board"]].set_Vlearn(Vlearn)
  219. update_state()
  220. @eel.expose
  221. def set_start(start):
  222. if start>255 or start<0:
  223. error("start must be in the range 0-256")
  224. return
  225. if start>state["stop"]:
  226. error("start must be lower than stop")
  227. return
  228. if start>state["wf_len"]:
  229. error("start must be lower than the waveform length")
  230. return
  231. return chips[state["selected_board"]].set_start(start)
  232. update_state()
  233. @eel.expose
  234. def set_stop(stop):
  235. if stop>255 or stop<0:
  236. error("stop must be in the range 0-256")
  237. return
  238. if stop<state["start"]:
  239. error("start must be lower than stop")
  240. return
  241. if stop>state["wf_len"]:
  242. error("stop must be lower than the waveform length")
  243. return
  244. return chips[state["selected_board"]].set_stop(stop)
  245. update_state()
  246. @eel.expose
  247. def set_start_gnd(start_gnd):
  248. if start_gnd>255 or start_gnd<0:
  249. error("start_gnd must be in the range 0-256")
  250. return
  251. if start_gnd>state["stop_gnd"]:
  252. error("start_gnd must be lower than stop")
  253. return
  254. if start_gnd>state["wf_len"]:
  255. error("start_gnd must be lower than the waveform length")
  256. return
  257. return chips[state["selected_board"]].set_start_gnd(start_gnd)
  258. update_state()
  259. @eel.expose
  260. def set_stop_gnd(stop_gnd):
  261. if stop_gnd>255 or stop_gnd<0:
  262. error("stop_gnd must be in the range 0-256")
  263. return
  264. if stop_gnd<state["start_gnd"]:
  265. error("start must be lower than stop")
  266. return
  267. if stop_gnd>state["wf_len"]:
  268. error("stop_gnd must be lower than the waveform length")
  269. return
  270. return chips[state["selected_board"]].set_stop_gnd(stop_gnd)
  271. update_state()
  272. @eel.expose
  273. def set_wf_len(*params):
  274. if wf_len>255 or wf_len<0:
  275. error("wf_len must be in the range 0-256")
  276. return
  277. if wf_len<state["stop"] or wf_len<state["stop_gnd"]:
  278. error("wf_len must be higher than both stop and stop_gnd")
  279. return
  280. return chips[state["selected_board"]].set_wf_len(*params)
  281. update_state()
  282. @eel.expose
  283. def set_N(N):
  284. N = int(N)
  285. if N > 5:
  286. warning("Note that increasing the Number of waveforms per stabilization loop decreases the speed of the stabilization. We typically just have N=1.")
  287. return chips[state["selected_board"]].set_N(N)
  288. update_state()
  289. @eel.expose
  290. def set_step_max(step):
  291. if step>4095 or step<1:
  292. error("step_max must be in the range 0-1")
  293. return
  294. if step<50:
  295. warning("step_max seems low. This may limit the ability to react to fast power fluctuations.")
  296. return chips[state["selected_board"]].set_step_max(step)
  297. update_state()
  298. @eel.expose
  299. def set_Gain(*params):
  300. return chips[state["selected_board"]].set_Gain(*params)
  301. update_state()
  302. @eel.expose
  303. def set_auto_set_pga(status):
  304. if status not in [0, 1]:
  305. error("auto_set_pga must be set to either 0 or 1.")
  306. return
  307. return chips[state["selected_board"]].set_auto_set_pga(status)
  308. update_state()
  309. @eel.expose
  310. def set_input_gain(input_gain):
  311. if input_gain not in [1, 2, 4, 8, 16, 32, 64, 128]:
  312. error("input_gain must be one of [1, 2, 4, 8, 16, 32, 64, 128]")
  313. return
  314. return chips[state["selected_board"]].set_input_gain(input_gain)
  315. update_state()
  316. @eel.expose
  317. def set_offset(offset):
  318. if offset>4095 or offset<0:
  319. error("offset must be in the range 0-4095. 2000 corresponds to no offset.")
  320. return
  321. return chips[state["selected_board"]].set_offset(offset)
  322. update_state()
  323. @eel.expose
  324. def set_coarse_fine_ratio(coarse_fine_ratio):
  325. if coarse_fine_ratio<10 or coarse_fine_ratio>30:
  326. error("coarse_fine_ratio should be approximately 20.")
  327. return
  328. if coarse_fine_ratio<15 or coarse_fine_ratio>25:
  329. warning("coarse_fine_ratio should be approximately 20.")
  330. return chips[state["selected_board"]].set_coarse_fine_ratio(coarse_fine_ratio)
  331. update_state()
  332. # Program state
  333. state = {
  334. "n_boards": 2,
  335. "selected_board": 0,
  336. "box_address": 0x50,
  337. "mode": 0,
  338. "out_of_lock": 0,
  339. "pi_freq": 1,
  340. "board_freq": 0,
  341. "remote_trigg": 0,
  342. "enab_gnd": 1,
  343. "Vlearn": 3200,
  344. "start": 25,
  345. "stop": 100,
  346. "start_gnd": 125,
  347. "stop_gnd": 200,
  348. "wf_len": 200,
  349. "N": 1,
  350. "step_max": 200,
  351. "Gain": 10,
  352. "auto_set_pga": 1,
  353. "input_gain": 1,
  354. "offset": 2000,
  355. "coarse_fine_ratio": 20
  356. }
  357. def update_state():
  358. state["n_boards"] = len(chips)
  359. state["box_address"] = adresses[state["selected_board"]]
  360. chip = chips[state["selected_board"]]
  361. state["mode"] = chip.get_mode()
  362. state["out_of_lock"] = chip.get_out_of_lock()
  363. state["remote_trigg"] = chip.get_remote_trigg()
  364. state["enab_gnd"] = chip.get_enab_gnd()
  365. state["Vlearn"] = chip.get_Vlearn()
  366. state["start"] = chip.get_start()
  367. state["stop"] = chip.get_stop()
  368. state["start_gnd"] = chip.get_start_gnd()
  369. state["stop_gnd"] = chip.get_stop_gnd()
  370. state["wf_len"] = chip.get_wf_len()
  371. state["N"] = chip.get_N()
  372. state["step_max"] = chip.get_step_max()
  373. state["Gain"] = chip.get_Gain()
  374. state["auto_set_pga"] = chip.get_auto_set_pga()
  375. state["input_gain"] = chip.get_input_gain()
  376. state["offset"] = chip.get_offset()
  377. state["coarse_fine_ratio"] = chip.get_coarse_fine_ratio()
  378. eel.renderUI(state)
  379. ###################################
  380. ## START THE GUI
  381. ###################################
  382. my_options = {
  383. 'mode': "chrome-app", #chrome-app
  384. 'host': 'localhost',
  385. 'port': 8000 + int(np.random.rand()*1000),
  386. 'size':(710, 725),
  387. #'chromeFlags': ["--start-fullscreen", "--browser-startup-dialog"]
  388. }
  389. eel.init('web')
  390. eel.start('main.html', options=my_options, block=False)
  391. # Detect all boards
  392. import os
  393. import subprocess
  394. import re
  395. chips = []
  396. adresses = []
  397. # TO DO
  398. '''
  399. p = subprocess.Popen(['i2cdetect', '-y','1'],stdout=subprocess.PIPE,)
  400. for i in range(0,9):
  401. line = str(p.stdout.readline())[2:]
  402. for match in re.finditer("[0-9a-f]+", line):
  403. adresses.append(int(match, 16))
  404. chips.append(ADUCv2p1(int(match, 16),True))
  405. update_state()
  406. '''
  407. eel.renderUI(state)
  408. i = 0
  409. while(True):
  410. eel.renderUI(state) # TO DO
  411. # save_waveform() # TO DO
  412. eel.sleep(1/state["pi_freq"])
  413. if(i%100==0):
  414. clean_old_files()
  415. i += 1
  416. print(state)