Skip to content

Commit

Permalink
merge http_ttl high non-zero fix w/extra wait
Browse files Browse the repository at this point in the history
  • Loading branch information
WillForan committed Feb 22, 2023
2 parents 2fb0705 + 346443f commit 02bfe25
Show file tree
Hide file tree
Showing 16 changed files with 904 additions and 596 deletions.
20 changes: 20 additions & 0 deletions habit_seeg
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
#!/usr/bin/env bash
trap '[ -n "$psiclj" ] && kill $psiclj && echo killed psiclj; test -n "$foxpid" && kill $_ && echo killed firefox;' EXIT SIGKILL
cd "$(dirname "$(readlink -f "$0")")" || exit
#./psiclj & # TODO: maybe launch in separate terminal?
java -cp psiclj.jar clojure.main -m psiclj &
psiclj=$!
echo "sleeping while java launches"
sleep 1

echo "$(tput setaf 10)manually fullscreen browser (F11, or alt+v f) and ensure zoom 120% $(tput sgr0)"
firefox http://127.0.0.1:3001/seeg.html &
foxpid=$!

echo "# launching buttonbox/keyboard bridge"
python ./http_ttl.py -v seeg

# done with everything. dont keep psiclj around
# kills run by trap
#kill $psiclj
#kill $foxpid
77 changes: 55 additions & 22 deletions http_ttl.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@
from tornado.web import RequestHandler, Application
from tornado.ioloop import IOLoop
from pynput.keyboard import Controller, Key
import os
import os.path


class Hardware():
Expand Down Expand Up @@ -85,16 +87,20 @@ def send(self, ttl, zero=True):
if zero:
self.wait_and_zero()


class TTL_Logger(Hardware):
""" log ttl code instead of sending to recording computer"""
def __init__(self, verbose=True):
tstr = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M.%S")
self.fid = open(f"{tstr}_ttllog.txt")
if not os.path.exists("log"):
os.makedirs("log")
# NB. never closed!
self.fid = open(f"log/{tstr}_ttllog.txt", "w")
self.verbose = verbose

def send(self, ttl, zero=True):
self.print_timestamp(ttl)
fid.write(f"{datetime.datetime.now()}\t{ttl}\n")
self.fid.write(f"{datetime.datetime.now()}\t{ttl}\n")


class DAQ(Hardware):
Expand All @@ -105,26 +111,30 @@ class DAQ(Hardware):
NB!! binary on (>=128) or off (<128)
DOES NOT encode 0-255, but 0/1
"""
def __init__(self, verbose=False, daq_path='/home/abel/luna_habit/usb1208fs-linux-drivers/USB/python'):
# git clone https://github.com/wjasper/Linux_Drivers.git /home/abel/luna_habit/usb1208fs-linux-drivers/
def __init__(self, verbose=False, daq_path='/home/lncd/luna_habit/usb1208fs-linux-drivers/USB/python'):
# git clone https://github.com/wjasper/Linux_Drivers.git /home/lncd/luna_habit/usb1208fs-linux-drivers/
# make install usbs, add udevrules
sys.path.insert(0, daq_path)
from usb_1208FS import usb_1208FS
self.verbose = verbose
self.dev = usb_1208FS()
print('wMaxPacketSize =', self.dev.wMaxPacketSize)
#print('wMaxPacketSize =', self.dev.wMaxPacketSize)
self.dev.DConfig(self.dev.DIO_PORTA, self.dev.DIO_DIR_OUT)
self.dev.DOut(self.dev.DIO_PORTA, 0)

def send(self, ttl, zero=True):
actual_ttl = 250 # always high
# always high 250. unless 0 (low)
actual_ttl = 250 if ttl > 0 else 0
self.dev.DOut(self.dev.DIO_PORTA, actual_ttl)
# zero
# always zero. we'll only ever send hi
wait=.002
# to ID start and end, wait twice as long
if ttl in [128,129]:
wait=.005
#self.dev.DOut(self.dev.DIO_PORTA, 0)
if zero:
# to ID start and end, wait twice as long
if ttl in [128,129]:
wait=.005
else:
wait=.002
self.wait_and_zero(wait=wait)


Expand Down Expand Up @@ -192,23 +202,25 @@ async def watch(self):


class RTBox():
def __init__(self, hw, kb=None, verbose=False, lib='/home/abel/luna_habit/RTBox_py'):
def __init__(self, hw, kb=None, verbose=False, lib='/home/lncd/luna_habit/RTBox_py'):
self.run = True
self.verbose = True
self.kb = kb
self.hw = hw
self.keys = ['1', '2', '3', '4', 'S', 'L', '5', 'A']
self.sendLUR = [Key.left, Key.up, Key.right]
# numbers as they are on the button box instead of as an array
self.sendLUR = {1:Key.left, 2:Key.up, 3:Key.up, 4:Key.right}

# git clone https://github.com/xiangruili/RTBox_py /home/abel/luna_habit/RTBox_py/
# git clone https://github.com/xiangruili/RTBox_py /home/lncd/luna_habit/RTBox_py/
sys.path.insert(0, lib) # or PYTHONPATH=~/luna_habit/RTBox/python
import RTBox
box = RTBox.RTBox()
box.enable('light')
box.info()
box.threshold(4)
print(f"using threshold {box.threshold()} (1-4)")
box.close()
box.close() # switches to serial mode
self.box = box

_ser = box._ser
_ser.open()
Expand All @@ -222,17 +234,28 @@ def trigger(self, index):
# index is 0-based but keys start at 1. so add one to what we send if in range
key = None
ttl = None
if index > 5:
self.hw.send(1)
elif index > 1 and index < 4:
key = self.sendLUR[index-1]
ttl = index + 1
self.kb.push(key)
if index >= 5:
self.hw.send(1) # 1 for eeg, but 'high' for seeg
ttl = 250
self.box.disable("light")
self.box.enable("light") # WARNING: this is against the suggestion. might be noisy PD
elif index >= 0 and index < 4:
key = self.sendLUR.get(index+1, None)
# does't actually matter what we send. DAQ will send high
# but update here so verbose printing is consistant
ttl = 250 # was index + 1, but only have high and low. so always send high. will e 0'ed
self.hw.send(ttl)
self.kb.push(key)
# after a key push reset the trial. should be black screen
self.box.enable("light")
# also consider
#self.box.clear()


if self.verbose:
response = self.keys[index]
print(f"have: {response}. send key {key} and ttl {ttl}")
print(f"have: {response} (i: {index}). send key {key} and ttl {ttl}")


async def watch(self):
while self.run:
Expand Down Expand Up @@ -313,6 +336,13 @@ async def seeg(verbose=False):
http_run(logger)
await asyncio.create_task(rb.watch())

async def test_DAQ(verbose=False):
hw = DAQ(verbose=verbose)
while True:
await asyncio.sleep(1)
print(f"sending high and zeroing")
hw.send(250) # 250 just has to be non-zero


async def rtbox_test(verbose=False):
"no http server, no DAQ. just RTBox with generic hardware class"
Expand All @@ -337,7 +367,7 @@ async def fakeeeg(usekeyboard=False, verbose=False):
def parser(args):
import argparse
p = argparse.ArgumentParser(description="Intercept http queries and watch ButtonBox/PhotoDiode")
p.add_argument('place', choices=["loeff", "seeg", "test", "test_rtbox"], help='where (also how) to use button and ttl')
p.add_argument('place', choices=["loeff", "seeg", "test", "test_rtbox", "test_DAQ"], help='where (also how) to use button and ttl')
p.add_argument('-k','--keyboard', help='use keyboard (only for "test")', action='store_true', dest="usekeyboard")
p.add_argument('-v','--verbose', help='additonal printing', action='store_true', dest="verbose")
return p.parse_args(args)
Expand All @@ -352,6 +382,9 @@ def parser(args):
asyncio.run(seeg(verbose=args.verbose))
elif args.place == "test":
asyncio.run(fakeeeg(args.usekeyboard, verbose=args.verbose))
elif args.place == "test_DAQ":
asyncio.run(test_DAQ(verbose=args.verbose))

elif args.place == "test_rtbox":
asyncio.run(rtbox_test(verbose=args.verbose))
else:
Expand Down
56 changes: 56 additions & 0 deletions out/extra/seeg.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Landscape Choice Loeffler sEEG</title>
<script src="tweaks.js"> </script>
<!-- // qs, yyyymmdd, get_anchor, add_timing_choices -->

<script>


function make_url(){
let id = qs("id");
let runnum = qs("runnum");
/* important trailing slash */
return("/" + id + "/seeg_habit/" + yyyymmdd() +"/" + runnum +"/");
}

function go_url(){
let url = make_url() + get_anchor() + "&ttl=local&where=seeg&nocaptcha"
//window.location.assign(url);
popup = window.open(url,"Popup",
"toolbar=no,location=no,status=no,menubar=no,"+
"scrollbars=no,width=1920,height=1080");//,resizable=no
return(false);
}


function add_choices(){
// reorder preferend landscapes
landscapes = ['wellcoin', 'ocean', 'desert','mountain']
add_landscape_choices();
timing_choices = ['randomA','randomB']
add_timing_choices();
}
</script>
</head>
<body onload="add_choices()">
<h1> Task specifications </h1>
<form onsubmit="go_url(); return false"> <!-- return false supresses form action -->
<table id="task_setting_tweaks">
<tr><td><label for="id">ID:</label></td>
<td><input name=id type="text" size=5> </td></tr>
<tr><td><label for="run">run number:</label></td>
<td><input name="runnum" type="text" size=1 value=1> </td></tr>

</table>
<input type="submit" value="Go!">
</form>

<small style="position:absolute; bottom:0px"> redirect to
<span id="urltxt">/id/mr_habit/timepoint/run/ </span>
<a href="/">more options</a>
</small>
</body>
</html>
Loading

0 comments on commit 02bfe25

Please sign in to comment.