-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmincontrol_dev.py
More file actions
executable file
·1676 lines (1534 loc) · 90.8 KB
/
mincontrol_dev.py
File metadata and controls
executable file
·1676 lines (1534 loc) · 90.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os
import re
import time
import errno
from socket import error as socket_error
import urllib2
import threading
import json
import multiprocessing
import copy
import platform
import hashlib
import MySQLdb
import configargparse
from ws4py.client.threadedclient import WebSocketClient
from thrift import Thrift
from thrift.transport import TTransport
from thrift.protocol import TCompactProtocol
from dictdiffer import diff, patch, swap, revert
import numpy as np
from twisted.internet.protocol import ReconnectingClientFactory
from autobahn.twisted.websocket import WebSocketClientProtocol, \
WebSocketClientFactory
lock = threading.Lock()
# import memcache
# Unbuffered IO
# sys.stdin = os.fdopen(sys.stdin.fileno(), 'w', 0) # MS
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 1) # MS
sys.stderr = os.fdopen(sys.stderr.fileno(), 'w', 0) # MS
global OPER
OPER = platform.system()
if OPER == 'Windows': # MS
OPER = 'windows'
elif OPER == 'Darwin':
OPER = 'osx'
else:
OPER = 'linux' # MS
print OPER # MS
config_file = script_dir = os.path.dirname(os.path.realpath('__file__' \
)) + '/' + 'minup_posix.config'
parser = \
configargparse.ArgParser(description= \
'interaction: A program to provide real time interaction for minION runs.' \
, default_config_files=[config_file])
parser.add(
'-ws',
'--websocket-host',
type=str,
dest='wshost',
required=True,
default='localhost',
help="The location of the minotour server being connected to.",
)
parser.add(
'-dbh',
'--mysql-host',
type=str,
dest='dbhost',
required=False,
default='localhost',
help="The location of the MySQL database. default is 'localhost'.",
)
parser.add(
'-dbu',
'--mysql-username',
type=str,
dest='dbusername',
required=True,
default=None,
help='The MySQL username with create & write privileges on MinoTour.'
,
)
parser.add(
'-dbp',
'--mysql-port',
type=int,
dest='dbport',
required=False,
default=3306,
help="The MySQL port number, else the default port '3306' is used."
,
)
parser.add(
'-pw',
'--mysql-password',
type=str,
dest='dbpass',
required=True,
default=None,
help='The password for the MySQL username with permission to upload to MinoTour.'
,
)
parser.add(
'-pin',
'--security-pin',
type=str,
dest='pin',
required=True,
default=None,
help='This is a security feature to prevent unauthorised remote control of a minION device. \
You need to provide a four digit pin number which must be entered on the website to remotely \
control the minION.'
,
)
parser.add(
'-ip',
'--ip-address',
type=str,
dest='ip',
required=True,
default=None,
help='The IP address of the minKNOW machine.',
)
parser.add(
'-v',
'--verbose',
action='store_true',
help='Display debugging information.',
default=False,
dest='verbose',
)
global args
args = parser.parse_args()
version = '0.3' # 9th January 2017
### test which version of python we're using
###Machine to connect to address
global ipadd
ipadd = args.ip
def bytesto(bytes, to, bsize=1024):
"""convert bytes to megabytes, etc.
sample code:
print('mb= ' + str(bytesto(314575262000000, 'm')))
sample output:
mb= 300002347.946
"""
a = {'k' : 1, 'm': 2, 'g' : 3, 't' : 4, 'p' : 5, 'e' : 6}
r = float(bytes)
for i in range(a[to]):
r = r / bsize
return r
def checkpin(dbname):
#if check_db_connection() == 1:
try:
checkpin = "select message from %s.messages where message = 'pin'" % (dbname)
print checkpin
cursor=db.query(checkpin)
#db.commit()
rows = cursor.fetchall()
return len(rows)
except Exception,err:
print "line 173 Error",err
check_db_connection()
print "Database problem"
return 0
def checkwarning(dbname):
#if check_db_connection() == 1:
try:
checkwarn = "select name from %s.alerts where name = 'minKNOWwarning'" % (dbname)
cursor=db.query(checkwarn)
#db.commit()
rows = cursor.fetchall()
return len(rows)
except Exception,err:
print "line 187 Error",err
check_db_connection()
print "Database problem"
return 0
def check_email_twitter():
#if check_db_connection() == 1:
try:
getuserinfo = "select twitnote,emailnote from Gru.users where user_name = '%s'" %(args.dbusername)
#print getuserinfo
cursor=db.query(getuserinfo)
#print cursor
#db.commit()
row=cursor.fetchone()
except Exception,err:
print "line 202 Error",err
def save_data():
print "saving data"
clean_up()
datatosave=sendingminIONdict
for thing in datatosave["DETAILS"]:
for minion in datatosave["DETAILS"][thing]:
if "detailsdata" in datatosave["DETAILS"][thing][minion]:
if "status" in datatosave["DETAILS"][thing][minion]["detailsdata"]["engine_states"]:
insert_data = 'insert into Gru.json_store (user_name,date_time,json_string,minion,runname) VALUES ("%s","%s","%s","%s","%s")' % (args.dbusername,time.time(),(MySQLdb.escape_string(str(json.dumps(datatosave)))),minion,str(datatosave["DETAILS"][thing][minion]["livedata"]["dataset"]["result"]))
try:
cursor=db.query(insert_data)
#db.commit()
except Exception,err:
check_db_connection()
print "line 219 Error",err
def check_databases():
print "CHECK DATABASES"
for minION in minIONdict: # if yes then we check each minION to see what is happening
#print minION, minIONdict[minION]["state"]
if minIONdict[minION]["state"] == "active":
#look and see if there are any active runs with this user for this minION.
#print "MinION is active - fetching databases"
fetchruns = "SELECT runname FROM Gru.minIONruns where activeflag = 1 and flowcellid = '%s' and user_name = '%s'" % (minION,args.dbusername)
print fetchruns
#if check_db_connection() == 1:
try:
cursor=db.query(fetchruns)
#db.commit()
rows = cursor.fetchall()
print rows
for row in rows:
print "ROW", row[0]
print "CHECKPIN", checkpin(row[0])
if checkpin(row[0]) < 1:
print "TRYING PIN INSERT"
#pininsert = \
#"insert into %s.messages (message,target,param1,complete) VALUES ('pin','all','%s','1')" \
#% (row[0],hashlib.md5(args.pin).hexdigest())
pininsert = \
"insert into %s.messages (message,target,param1,complete) VALUES ('pin','all','%s','1')" \
% (row[0],args.pin)
print "pininsert",pininsert
cursor=db.query(pininsert)
#db.commit()
if checkwarning(row[0]) < 1:
#print "Checking Drive Warnings from MinKNOW",type(minIONdict[minION]["livedata"]['disk_space']['result'][0]['recommend_alert'])
if minIONdict[minION]["livedata"]['disk_space']['result'][0]['recommend_alert'] == True:
warninginsert = "insert into %s.alerts (name,type,complete) VALUES ('minKNOWwarning','%s',0)" % (row[0],MySQLdb.escape_string(minIONdict[minION]["livedata"]["machine_id"]['result'])) # add in minion.livedata.machine_id.result as "type"
print warninginsert
cursor=db.query(warninginsert)
#db.commit()
print "DANGER DISK WARNING"
globalwarningdict[minION]=1
if minION in globalwarningdict.keys() and minIONdict[minION]["livedata"]['disk_space']['result'][0]['recommend_alert'] == False:
deletewarnings = "delete * from %s.alerts where name='minKNOWwarning'" %(row[0])
cursor=db.query(deletewarnings)
print "Disk Warning Removed"
globalwarningdict.pop(minION)
fetchalerts = "select * from %s.alerts" % (row[0])
#print fetchalerts
cursor=db.query(fetchalerts)
#db.commit()
rows2 = cursor.fetchall()
for row2 in rows2:
#print row2
if row2[1] == "disknotify":
#print bytesto(minIONdict[minION]["livedata"]['disk_space']['result'][0]['bytes_available'],"g")
if bytesto(minIONdict[minION]["livedata"]['disk_space']['result'][0]['bytes_available'],"g") < row2[7]:
try:
update = "update %s.alerts set end = 1, type = '%s' where alert_index = %s" % (row[0],MySQLdb.escape_string(minIONdict[minION]["livedata"]["machine_id"]['result']),row2[0])
#print update
cursor=db.query(update)
#db.commit()
except Exception,err:
print "line 267 Error",err
#check for things to stop the run...
fetchinteractions = "select * from %s.interaction where complete != 1" %(row[0])
cursor=db.query(fetchinteractions)
#db.commit()
rows3 = cursor.fetchall()
for row3 in rows3:
if row3[1] == "stop":
#print "THING TO STOP"
stoprun(minIONdict[minION]["port"])
try:
update = "update %s.interaction set complete = 1 where job_index = %s" % (row[0],row3[0])
#print update
cursor=db.query(update)
#db.commit()
except Exception,err:
print "Error",err
except Exception,err:
check_db_connection()
print "Error",err
#sys.exit()
pass
##First get the list of running minIONs
def _urlopen(url, *args):
"""Open a URL, without using a proxy for localhost.
While the no_proxy environment variable or the Windows "Bypass proxy
server for local addresses" option should be set in a normal proxy
configuration, the latter does not affect requests by IP address. This
is apparently "by design" (http://support.microsoft.com/kb/262981).
This method wraps urllib2.urlopen and disables any set proxy for
localhost addresses.
"""
try:
host = url.get_host().split(':')[0]
except AttributeError:
host = urlparse.urlparse(url).netloc.split(':')[0]
import socket
# NB: gethostbyname only supports IPv4
# this works even if host is already an IP address
addr = socket.gethostbyname(host)
#if addr.startswith('127.'):
# return _no_proxy_opener.open(url, *args)
#else:
return urllib2.urlopen(url, *args)
def execute_command_as_string(data, host=None, port=None):
host_name = host
port_number = port
#print host,port,data
url = 'http://%s:%s%s' % (host_name, port_number, '/jsonrpc')
#req = urllib2.Request(url, data=data,headers={'Authorization': 'Bearer abc','Content-Length': str(len(data)),'Content-Type': 'application/json'})
req = urllib2.Request(url, data=data,headers={'Content-Length': str(len(data)),'Content-Type': 'application/json'})
#print req
try:
f = _urlopen(req)
json_respond = json.loads(f.read())
f.close()
return json_respond
except Exception, err:
print err
err_string = \
'Fail to initialise mincontrol. Likely reasons include minKNOW not running, the wrong IP address for the minKNOW server or firewall issues.'
return
def send_message_port(message,port):
message_to_send = \
'{"id":"1", "method":"user_message","params":{"content":"%s"}}' \
% message
results=""
try:
results = execute_command_as_string(message_to_send, ipadd, port)
except Exception, err:
print "message send fail", err
return results
def send_message(message):
message_to_send = \
'{"id":"1", "method":"user_message","params":{"content":"%s"}}' \
% message
results = execute_command_as_string(message_to_send, ipadd, 8000)
return results
def startstop(command,minION):
if OPER == "osx":
p = os.popen('/Applications/MinKNOW.app/Contents/Resources/bin/mk_manager_client -i ' + minION + ' --' + command,"r")
while 1:
line = p.readline()
if not line: break
#print line
elif OPER == "windows":
p = os.popen('C:\\grouper\\binaries\\bin\\mk_manager_client.exe -i ' + minION + ' --' + command, "r")
#print 'C:\\grouper\\binaries\\bin\\mk_manager_client.exe -i ' + minION + ' --' + command, "r"
while 1:
line = p.readline()
if not line: break
#print line
elif OPER == "linux":
print "!!!!!!!!!!!!!! Sorry cannot handle linux yet."
else:
print "!!!!!!!!!!!!!! Sorry - cannot recognise your operating system."
def commands(command):
return {
'getstaticdata' : '{"id":1,"method":"get_static_data","params":null}',
'initialization_status' : '{"params": "null", "id": 5, "method": "initialization_status"}',
'get_analysis_configuration' : '{"id":1,"method":"get_analysis_configuration","params":null}',
'initialiseminion' : '{"params": {"command": "init_main_board", "parameters": []}, "id": 0, "method": "board_command_ex"}',
'shutdownminion' : '{"params": {"state_id": "status", "value": "stop"}, "id": 0, "method": "set_engine_state"}',
'startmessagenew' : '{"id":"1", "method":"user_message","params":{"content":"minoTour is now interacting with your run. This is done at your own risk. To stop minoTour interaction with minKnow disable upload of read data to minoTour."}}',
'status':'{"id":"1", "method":"get_engine_state","params":{"state_id":"status"}}',
'dataset':'{"id":"1", "method":"get_engine_state","params":{"state_id":"data_set"}}',
'startrun' :'{"id":"1", "method":"start_script","params":{"name":"MAP_Lambda_Burn_In_Run_SQK_MAP005.py"}}',
'stoprun' : '{"id":"1", "method":"stop_experiment","params":"null"}',
'stopprotocol' : '{"id":"1", "method":"stop_script","params":{"name":"MAP_48Hr_Sequencing_Run.py"}}',
'biasvoltageget' : '{"id":"1","method":"board_command_ex","params":{"command":"get_bias_voltage"}}',
'bias_voltage_gain' : '{"id":"1","method":"get_engine_state","params":{"state_id":"bias_voltage_gain"}}',
'bias_voltage_set' :'{"id":"1","method":"board_command_ex","params":{"command":"set_bias_voltage","parameters":"-120"}}',
'machine_id' :'{"id":"1","method":"get_engine_state","params":{"state_id":"machine_id"}}',
'machine_name' :'{"id":"1","method":"get_engine_state","params":{"state_id":"machine_name"}}',
'sample_id' :'{"id":"1","method":"get_engine_state","params":{"state_id":"sample_id"}}',
'flow_cell_id' : '{"id":"1","method":"get_engine_state","params":{"state_id":"flow_cell_id"}}',
'user_error' :'{"id":"1","method":"get_engine_state","params":{"state_id":"user_error"}}',
'sequenced_res' :'{"id":"1","method":"get_engine_state","params":{"state_id":"sequenced"}}',
'yield_res' : '{"id":"1","method":"get_engine_state","params":{"state_id":"yield"}}',
'current_script' : '{"id":"1","method":"get_engine_state","params":{"state_id":"current_script"}}',
'get_scripts' : '{"id":"1", "method":"get_script_info_list","params":{"state_id":"status"}}',
'disk_space' : '{"id":1,"method":"get_disk_space_info","params":null}',
'sinc_delay' : '{"id":1,"method":"sinc_delay","params":null}',
'get_seq_metrics' : '{"id":1,"method": "get_seq_metrics","params":null}',
'get_tracking_id': '{"id":1,"method": "get_tracking_id","params":null}',
'get_statistics': '{"id":1,"method": "get_statistics","params":null}',
}[command]
class HelpTheMinion(WebSocketClient):
# def __init__(self,minIONdict):
# self.minIONdict = minIONdict
def opened(self):
print "Connected to Master MinION Controller!"
def initialiseminion():
result = self.send(json.dumps({"params": "null", "id": 5, "method": "initialization_status"}))
#print result
def received_message(self, m):
##print "message received!"
for thing in ''.join(map(chr,map(ord,str(m)))).split('\n'):
#if len(thing) > 5 and "2L" not in thing and "2n" not in thing:
if len(thing) > 5 and (thing[1] == "M" or thing[1] == "G"):
if thing[1:8] not in minIONdict:
#print "INITIALISING MINIONDICT"
minIONdict[thing[1:8]]=dict()
print "minION ID:", thing[1:8]
##print map(ord,thing)
minIONports = map(lambda x:x-192+8000,filter(lambda x:x>190,map(ord,thing)))
##print minIONports
if len(minIONports) > 0:
minIONdict[thing[1:8]]["state"]="active"
port = minIONports[0]
ws_longpoll_port = minIONports[1]
ws_event_sampler_port = minIONports[2]
ws_raw_data_sampler_port = minIONports[3]
minIONdict[thing[1:8]]["port"]=port
minIONdict[thing[1:8]]["ws_longpoll_port"]=ws_longpoll_port
minIONdict[thing[1:8]]["ws_event_sampler_port"]=ws_event_sampler_port
minIONdict[thing[1:8]]["ws_raw_data_sampler_port"]=ws_raw_data_sampler_port
else:
minIONdict[thing[1:8]]["state"]="inactive"
minIONdict[thing[1:8]]["port"]=""
minIONdict[thing[1:8]]["ws_longpoll_port"]=""
minIONdict[thing[1:8]]["ws_event_sampler_port"]=""
minIONdict[thing[1:8]]["ws_raw_data_sampler_port"]=""
class CallingHome(WebSocketClient):
def opened(self):
print "Connection Success - Calling Home."
self.connected=True
self.messagesent=False
def setup(self, timeout=1):
try:
self.__init__(self.url)
self.connect()
self.connected=True
self.timeout=2
self.run_forever()
except KeyboardInterrupt:
self.connected=False
self.messagesent=False
self.close()
except:
self.connected=False
self.messagesent=False
newTimeout = timeout + 1
print("Timing out for %i seconds. . ." % newTimeout)
time.sleep(newTimeout)
print("Attempting reconnect. . .")
self.setup(newTimeout)
def received_message(self, m):
#print "message received!",m
if str(m) != "Connected - waiting for messages.":
#print "we're off"
try:
message = json.loads(str(m))
if type(message) is dict:
##print "message",m,
if message["JOB"] == "testmessage":
send_message_port("minoTour is checking communication status with "+str(message["minion"])+".",minIONdict[message["minion"]]["port"])
if message["JOB"] =="biasvoltageinc":
biasvoltsmod("inc",minIONdict[message["minion"]]["port"])
if message["JOB"] =="biasvoltagedec":
biasvoltsmod("dec",minIONdict[message["minion"]]["port"])
if message["JOB"] == "rename":
renamerun(message["NAME"],minIONdict[message["minion"]]["port"])
if message["JOB"] == "nameflowcell":
renameflowcell(message["NAME"],minIONdict[message["minion"]]["port"])
if message["JOB"] == "stopminion":
stoprun(minIONdict[message["minion"]]["port"])
if message["JOB"] == "startminion":
startrun(message["SCRIPT"],minIONdict[message["minion"]]["port"])
if message["JOB"] == "initialiseminion":
#print "Trying to initialise minION"
#result = helper.initialiseminion()
startstop('start',message["minion"])
print "Try to run the initialiseminion command now."
#execute_command_as_string(commands('initialiseminion'), ipadd,minIONdict[message["minion"]]["port"])
if message["JOB"] == "shutdownminion":
#First we need to stop the minion if it is running...
#stoprun(minIONdict[message["minion"]]["port"])
#execute_command_as_string(commands('shutdownminion'), ipadd,minIONdict[message["minion"]]["port"])
startstop('stop',message["minion"])
print "Try to shut down the minION now."
except Exception, err:
print "line 508",err,str(m)
pass
#if type(message) is dict:
# #print "message"
#try:
# #print message["JOB"]
#except:
# pass
#self.send(json.dumps("message received!", ensure_ascii=False))
def closed(self, code, reason=None):
print self.sock.fileno()
print "Closed down Home", code, reason
self.connected=False
self.messagesent=False
#self.runanalysis = True
#minIONdict=[]
time.sleep(3)
print ("Reconnecting. . .")
# self.sock.shutdown(socket.SHUT_RDWR)
#self.sock.close()
self.setup()
def startrun(script,port):
#print 'Starting the minION device.'
try:
startruncustom = \
'{"id":1, "method":"start_script","params":{"name":"' \
+ script + '"}}'
print startruncustom,ipadd,port
startresult = \
execute_command_as_string(startruncustom,
ipadd, port)
startrunmessage = 'minoTour sent a remote run start command.'
startresultmessage = send_message_port(startrunmessage,port)
except Exception, err:
print >> sys.stderr, err
def stoprun_message(port,message):
try:
stopresult = execute_command_as_string(commands('stoprun'),
ipadd, port)
stopprotocolresult = \
execute_command_as_string(commands('stopprotocol'), ipadd,
port)
stoprunmessage = 'minoTour sent a remote run stop command for %s.' % (message)
stopresultmessage = send_message_port(stoprunmessage,port)
except Exception, err:
print >> sys.stderr, err
def send_custom_message(port,message):
try:
custommessage = "minoTour: %s" % (message)
custommessageresult=send_message_port(custommessage,port)
except Exception,err:
print >> sys.stderr, err
def stoprun(port):
try:
stopresult = execute_command_as_string(commands('stoprun'),
ipadd, port)
stopprotocolresult = \
execute_command_as_string(commands('stopprotocol'), ipadd,
port)
stoprunmessage = 'minoTour sent a remote run stop command.'
stopresultmessage = send_message_port(stoprunmessage,port)
except Exception, err:
print >> sys.stderr, err
def renameflowcell(name,port):
try:
set_flowcell_id = \
'{"id":1,"method":"set_engine_state","params":{"state_id":"flow_cell_id","value":"'+name+'"}}'
set_sample_id_result = \
execute_command_as_string(set_flowcell_id,ipadd,port)
startresultmessage = \
send_message_port('minoTour renamed the flowcell to ' + name,port)
except Exception, err:
print >> sys.stderr, err
def renamerun(name,port):
try:
set_sample_id = \
'{"id":"1","method":"set_engine_state","params":{"state_id":"sample_id","value":"' \
+ name + '"}}'
set_sample_id_result = \
execute_command_as_string(set_sample_id, ipadd,
port)
startresultmessage = \
send_message_port('minoTour renamed the run to '
+ name,port)
except Exception, err:
print >> sys.stderr, err
def biasvoltsmod(direction,port):
if direction == "inc":
#print 'Incrementing Bias Voltage'
try:
biasresultmessage = \
execute_command_as_string(commands('biasvoltageget'),
ipadd, port)
biasvoltageoffset = \
execute_command_as_string(commands('bias_voltage_gain'),
ipadd, port)
curr_voltage = int(biasresultmessage['result'
]['bias_voltage']) \
* int(biasvoltageoffset['result']) + 10
bias_voltage_inc = \
'{"id":"1","method":"board_command_ex","params":{"command":"set_bias_voltage","parameters":"%s"}}' \
% curr_voltage
biasvoltagereset = \
execute_command_as_string(bias_voltage_inc,
ipadd, port)
biasresultmessage = \
execute_command_as_string(commands('biasvoltageget'),
ipadd, port)
biasvoltageoffset = \
execute_command_as_string(commands('bias_voltage_gain'),
ipadd, port)
curr_voltage = int(biasresultmessage['result'
]['bias_voltage']) \
* int(biasvoltageoffset['result'])
incmessage = 'minoTour shifted the bias voltage by +10 mV.'
incresultmessage = send_message_port(incmessage,port)
except Exception, err:
print >> sys.stderr, err
if direction == "dec":
#print 'Decreasing Bias Voltage'
try:
biasresultmessage = \
execute_command_as_string(commands('biasvoltageget'),
ipadd, port)
biasvoltageoffset = \
execute_command_as_string(commands('bias_voltage_gain'),
ipadd, port)
curr_voltage = int(biasresultmessage['result'
]['bias_voltage']) \
* int(biasvoltageoffset['result']) - 10
bias_voltage_dec = \
'{"id":"1","method":"board_command_ex","params":{"command":"set_bias_voltage","parameters":"%s"}}' \
% curr_voltage
biasvoltagereset = \
execute_command_as_string(bias_voltage_dec,
ipadd, port)
biasresultmessage = \
execute_command_as_string(commands('biasvoltageget'),
ipadd, port)
biasvoltageoffset = \
execute_command_as_string(commands('bias_voltage_gain'),
ipadd, port)
curr_voltage = int(biasresultmessage['result'
]['bias_voltage']) \
* int(biasvoltageoffset['result'])
decmessage = 'minoTour shifted the bias voltage by -10 mV.'
decresultmessage = send_message_port(decmessage,port)
except Exception, err:
print >> sys.stderr, err
class MessagesClient(WebSocketClient):
def __init__(self, *args,**kwargs):
super(MessagesClient, self).__init__(*args,**kwargs)
print "MessagesClient established!"
self.detailsdict=dict()
self.daemon=True
def init_minion(self,minion):
self.minion=minion
def opened(self):
print "MessagesClient Opened!"
def closed(self, code, reason="MessagesClient disconnected for some reason"):
print "socket",self.sock.fileno()
print "Closed down", code, reason
def received_message(self,m):
if not m.is_binary:
print m
try:
if self.minion not in minIONdict.keys():
minIONdict[self.minion]=dict()
if "messages" not in minIONdict[self.minion].keys():
minIONdict[self.minion]["messages"]=[]
minIONdict[self.minion]["messages"].append(json.loads(str(m)))
send_data()
except:
pass
class DummyClient(WebSocketClient):
def __init__(self, *args,**kwargs):
super(DummyClient, self).__init__(*args,**kwargs)
print "Client established!"
self.detailsdict=dict()
self.daemon=True
def init_minion(self,minion):
""" ejecteject has three states:
0=initisalised or sequencing finished
1=sequencing happening
2=run finish detected."""
self.minion=minion
self.ejecteject=0
self.runname=""
def opened(self):
self.send(json.dumps({'engine_states':'1','channel_states':'1','channel_info':'1'}))
def closed(self, code, reason="client disconnected for some reason"):
print "socket",self.sock.fileno()
print "Closed down", code, reason
def received_message(self, m):
if not m.is_binary:
#ejecteject=0
json_object = json.loads(str(m))
#print json_object
for element in json_object:
if element == "statistics" and json_object[element] != "null":
for element2 in json_object[element]:
if element2 == "channel_info": #element2 == "read_statistics" or
print "found ",element2
print json_object[element][element2]
if element2 != "read_statistics" and element2 != "channel_info" and json_object[element][element2] != "null":# and element2 != "read_statistics" and element2 != "completed_samples":
if element not in self.detailsdict:
self.detailsdict[element]=dict()
self.detailsdict[element][element2]=json_object[element][element2]
elif element == "engine_states" and json_object[element] != "null":
for element2 in json_object[element]:
if json_object[element][element2] != "null":
if element not in self.detailsdict:
self.detailsdict[element]=dict()
if json_object[element][element2] is not dict:
self.detailsdict[element][element2]=json_object[element][element2]
if "status" in json_object[element]:
print "engine states",json_object[element]["status"]
if json_object[element]["status"]== "finishing":
print "Looks as though a run is finishing!!!!"
self.ejecteject=2
if json_object[element]["status"]== "starting":
print "Looks as though a run is starting!!!!"
if self.ejecteject==0:
print "resetting history"
if self.minion in minIONdict and "yield_history" in minIONdict[self.minion]:
minIONdict[self.minion]["yield_history"]=[]
minIONdict[self.minion]["temp_history"]["asictemp"]=[]
minIONdict[self.minion]["temp_history"]["heatsinktemp"]=[]
minIONdict[self.minion]["temp_history"]["voltage"]=[]
minIONdict[self.minion]["pore_history"]["strand"]=[]
minIONdict[self.minion]["pore_history"]["percent"]=[]
minIONdict[self.minion]["pore_history"]["single"]=[]
if "details" in minIONdict[self.minion]["pore_history"]:
minIONdict[self.minion]["pore_history"].pop("details")
if json_object[element]["status"]=="processing" and self.ejecteject==0:
print "we're off - resetting history"
if self.minion in minIONdict and "yield_history" in minIONdict[self.minion]:
minIONdict[self.minion]["yield_history"]=[]
minIONdict[self.minion]["temp_history"]["asictemp"]=[]
minIONdict[self.minion]["temp_history"]["heatsinktemp"]=[]
minIONdict[self.minion]["temp_history"]["voltage"]=[]
minIONdict[self.minion]["pore_history"]["strand"]=[]
minIONdict[self.minion]["pore_history"]["percent"]=[]
minIONdict[self.minion]["pore_history"]["single"]=[]
if "details" in minIONdict[self.minion]["pore_history"]:
minIONdict[self.minion]["pore_history"].pop("details")
self.ejecteject=1
elif element == "channel_info" and json_object[element] != "null":
### Getting and updating channel information.
if "channels" in json_object[element].keys():
for channel in json_object[element]["channels"]:
state = "unknown"
if "state" in channel.keys():
state = channel["state"]
logitem(int(channel["name"]),self.minion,state)
for element2 in json_object[element]:
#pass
#turns out we use this data elsewhere - so need to clean it out at send point.
if json_object[element][element2] != "null":
if element not in self.detailsdict:
self.detailsdict[element]=dict()
if json_object[element][element2] is not dict:
self.detailsdict[element][element2]=json_object[element][element2]
else:
if json_object[element] != "null":
#print element
self.detailsdict[element]=json_object[element]
if self.ejecteject==2 and len(self.runname)>0:
save_data()
print "resetting history 773"
try:
if self.minion in minIONdict and "yield_history" in minIONdict[self.minion]:
minIONdict[self.minion]["yield_history"]=[]
minIONdict[self.minion]["temp_history"]["asictemp"]=[]
minIONdict[self.minion]["temp_history"]["heatsinktemp"]=[]
minIONdict[self.minion]["temp_history"]["voltage"]=[]
minIONdict[self.minion]["pore_history"]["strand"]=[]
minIONdict[self.minion]["pore_history"]["percent"]=[]
minIONdict[self.minion]["pore_history"]["single"]=[]
if "details" in minIONdict[self.minion]["pore_history"]:
minIONdict[self.minion]["pore_history"].pop("details")
self.ejecteject=0
except Exception, err:
print "Problem",err
print "Probably already popped"
def get_run_scripts(port):
#print "trying to get runscripts on port %s" %(port)
get_scripts = \
'{"id":"1", "method":"get_script_info_list","params":{"state_id":"status"}}'
results = execute_command_as_string(get_scripts, ipadd, port)
#print type(results['result'])
#print len(results['result'])
#for thing in results['result']:
# print thing
return results['result']
for key in results.keys():
print "mincontrol:", key, results[key]
scriptlist = list()
for element in results['result']:
for item in results['result'][element]:
scriptlist.append("('runscript','all','" + item['name']
+ "',1)")
class RepeatedTimer(object):
def __init__(self,interval,function,*args,**kwargs):
self._timer = None
self.interval = interval
self.function = function
self.args = args
self.kwargs = kwargs
self.is_running = False
self.start()
def _run(self):
self.is_running = False
self.start()
self.function(*self.args,**self.kwargs)
def start(self):
if not self.is_running:
self._timer = threading.Timer(self.interval,self._run)
self._timer.start()
self.is_running = True
def stop(self):
self._timer.cancel()
self.is_running = False
def process_tracked_yield():
"""
This function maintains a history of all yield values over the time of a run - it can be configured to store yields
at given intervals. It is used by the main web page to provide a history of cumulative yield.
"""
#print "Process_tracked_yield Running"
#print minIONdict
for minion in minIONdict:
if "detailsdata" in minIONdict[minion]:
if "livedata" in minIONdict[minion]:
if "yield_res" in minIONdict[minion]["livedata"]:
if "result" in minIONdict[minion]["livedata"]["yield_res"]:
try:
asictemp = float(minIONdict[minion]["detailsdata"]["engine_states"]["minion_asic_temperature"])
except:
asictemp = 0
try:
heatsinktemp = float(minIONdict[minion]["detailsdata"]["engine_states"]["minion_heatsink_temperature"])
except:
heatsinktemp = 0
if minIONdict[minion]["livedata"]["bias_voltage_gain"]["result"] != "null":
#print "!!!!!!!!STUFF!!!!!", minIONdict[minion]["livedata"]["bias_voltage_gain"]["result"]
biasvoltage = int(minIONdict[minion]["livedata"]["bias_voltage_gain"]["result"])
else:
biasvoltage = 0
if minIONdict[minion]["livedata"]["biasvoltageget"]["result"] != "null":
voltage_val = int(minIONdict[minion]["livedata"]["biasvoltageget"]["result"]["bias_voltage"])
else:
voltage_val = 0
voltage_value = voltage_val * biasvoltage
#print "volts:",voltage_value
try:
if minIONdict[minion]["livedata"]["yield_res"]["result"] != "null":
yieldval = int(minIONdict[minion]["livedata"]["yield_res"]["result"])
else:
yieldval = minIONdict[minion]["detailsdata"]["statistics"]["read_event_count"]
except:
yieldval=0
try:
meanratio = minIONdict[minion]["detailsdata"]["meanratio"]
openpore = minIONdict[minion]["detailsdata"]["openpore"]
instrand = minIONdict[minion]["detailsdata"]["instrand"]
except:
meanratio = 0
openpore = 0
instrand = 0
if "yield_history" not in minIONdict[minion]:
minIONdict[minion]["yield_history"]=[]
if "temp_history" not in minIONdict[minion]:
minIONdict[minion]["temp_history"]=dict()
if "pore_history" not in minIONdict[minion]:
minIONdict[minion]["pore_history"]=dict()
if "meanratio_history" not in minIONdict[minion]["pore_history"]:
minIONdict[minion]["pore_history"]["meanratio_history"]=[]
minIONdict[minion]["pore_history"]["openpore_history"] = []
minIONdict[minion]["pore_history"]["instrand_history"] = []
if "strand" not in minIONdict[minion]["pore_history"]:
minIONdict[minion]["pore_history"]["strand"]=[]
minIONdict[minion]["pore_history"]["percent"]=[]
minIONdict[minion]["pore_history"]["single"]=[]
if "asictemp" not in minIONdict[minion]["temp_history"]:
minIONdict[minion]["temp_history"]["asictemp"]=[]
minIONdict[minion]["temp_history"]["heatsinktemp"]=[]
minIONdict[minion]["temp_history"]["voltage"]=[]
strand = 0
single_pore = 0
if "simplesummary" in minIONdict[minion]:
#for state in minIONdict[minion]["simplesummary"].keys():
# print state,minIONdict[minion]["simplesummary"][state]
if "strand" in minIONdict[minion]["simplesummary"].keys():
strand = float(minIONdict[minion]["simplesummary"]["strand"])
if "single_pore" in minIONdict[minion]["simplesummary"].keys():
single_pore = float(minIONdict[minion]["simplesummary"]["single_pore"])
elif "good_single" in minIONdict[minion]["simplesummary"].keys():
single_pore = float(minIONdict[minion]["simplesummary"]["good_single"])
if (strand+single_pore)> 0:
percent = (strand/(strand+single_pore)*100)
else:
percent = 0
#print "testing length"
if len(minIONdict[minion]["yield_history"]) >1:
if yieldval > minIONdict[minion]["yield_history"][-1][1]:
minIONdict[minion]["yield_history"].append((minIONdict[minion]["detailsdata"]["timestamp"]*1000,yieldval))
minIONdict[minion]["temp_history"]["asictemp"].append((minIONdict[minion]["detailsdata"]["timestamp"]*1000,asictemp))
minIONdict[minion]["temp_history"]["voltage"].append((minIONdict[minion]["detailsdata"]["timestamp"]*1000,voltage_value))
minIONdict[minion]["temp_history"]["heatsinktemp"].append((minIONdict[minion]["detailsdata"]["timestamp"]*1000,heatsinktemp))
minIONdict[minion]["pore_history"]["strand"].append((minIONdict[minion]["detailsdata"]["timestamp"]*1000,strand))
minIONdict[minion]["pore_history"]["percent"].append((minIONdict[minion]["detailsdata"]["timestamp"]*1000,percent))
minIONdict[minion]["pore_history"]["single"].append((minIONdict[minion]["detailsdata"]["timestamp"]*1000,single_pore))
minIONdict[minion]["pore_history"]["meanratio_history"].append(
(minIONdict[minion]["detailsdata"]["timestamp"] * 1000, meanratio))
minIONdict[minion]["pore_history"]["openpore_history"].append(
(minIONdict[minion]["detailsdata"]["timestamp"] * 1000, openpore))
minIONdict[minion]["pore_history"]["instrand_history"].append(
(minIONdict[minion]["detailsdata"]["timestamp"] * 1000, instrand))
if "simplesummary" in minIONdict[minion]:
if "details" not in minIONdict[minion]["pore_history"].keys():
minIONdict[minion]["pore_history"]["details"]=dict()
for state in minIONdict[minion]["simplesummary"].keys():
if state not in minIONdict[minion]["pore_history"]["details"].keys():
minIONdict[minion]["pore_history"]["details"][state]=[]
#print "appending at 899"