Skip to content

Commit

Permalink
Merge pull request #5 from pyreiz/develop
Browse files Browse the repository at this point in the history
Develop set_response and target_index
  • Loading branch information
agricolab committed Feb 3, 2020
2 parents ce221e6 + e5aa65b commit accf835
Show file tree
Hide file tree
Showing 10 changed files with 81 additions and 46 deletions.
12 changes: 8 additions & 4 deletions .github/workflows/pytest.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,20 @@ jobs:
pip install -U pip
pip install git+https://github.com/labstreaminglayer/liblsl-Python.git
pip install -r requirements.txt
pip install coverage==4.5.4
pip install pytest-cov
pip install pytest
pip install .
- name: Test with pytest
run: |
pip install coverage
pip install pytest-cov
pip install pytest
pytest
- name: Submit coverage report
env:
COVERALLS_REPO_TOKEN: ${{ secrets.COVERALL_SECRET }}
run: |
pip install coveralls
coveralls
coveralls
- name: Static type checking
run: |
pip install mypy
mypy
2 changes: 1 addition & 1 deletion localite/__init__.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
__path__ = __import__("pkgutil").extend_path(__path__, __name__)
# __path__ = __import__("pkgutil").extend_path(__path__, __name__)

27 changes: 22 additions & 5 deletions localite/coil.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from localite.flow.mrk import Receiver
from typing import Tuple, Dict, Any, Union
import json

from time import sleep

def pythonize_values(v: str) -> Union[bool, None, str]:
"pythonize a dictionaries values"
Expand Down Expand Up @@ -54,11 +54,13 @@ def __init__(self, coil: int = 0, address: Tuple[str, int] = ("127.0.0.1", 6667)
self._push_loc = partial(push, fmt="loc", host=host, port=port)
self.receiver = Receiver(name="localite_marker")
self.receiver.start()
while not self.receiver.is_running.is_set():
pass
self.id = coil

def await_connection(self):
print("[", end="")
while not self.connected:
while not self.connected: # pragma no cover
print(".", end="")
print("]")

Expand Down Expand Up @@ -152,10 +154,10 @@ def target_index(self) -> int:
@target_index.setter
def target_index(self, index: int) -> int:
"set the index of the next target"
if index < 0:
raise ValueError("Index must be higher than 0")
msg = json.dumps({f"coil_{self._id}_target_index": index})
response = self._request(msg)
if type(response) is dict and "reason" in response.keys():
print(response["reason"])
self._push_loc(msg=msg)
return self.request("target_index")

@property
Expand Down Expand Up @@ -203,3 +205,18 @@ def mode(self) -> str:
"""
return self.request("stimulator_mode")["name"]

def set_response(
self, mepmaxtime: float, mepamplitude: float, mepmin: float, mepmax: float
):
key = f"coil_{self.id}_response"
msg = {
key: {
"mepmaxtime": mepmaxtime,
"mepamplitude": mepamplitude,
"mepmin": mepmin,
"mepmax": mepmax,
}
}
self._push_loc(msg=json.dumps(msg))

32 changes: 16 additions & 16 deletions localite/flow/loc.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,18 +126,17 @@ def close(self) -> None:

def write(self, msg: str) -> None:
self.socket.sendall(msg.encode("ascii"))
return self

def read(self) -> Union[None, str]:
"parse the message"
bmsg = bytearray(b" ")
while True:
try:
prt = self.socket.recv(1)
bmsg += prt
bmsg += prt
dec = bmsg.decode("ascii")
return json.dumps(json.loads(dec))
except json.JSONDecodeError: # pragma no cover
except json.JSONDecodeError: # pragma no cover
pass
except Exception as e: # pragma no cover
print("LCL:EXC:", e)
Expand All @@ -161,7 +160,7 @@ def listen_and_queue(
"""listen to the localice stream and forward to queue
"""
msg = client.listen()
if json.loads(msg) in ignore or None:
if msg is None or json.loads(msg) in ignore:
return None
else:
print("LOC:MSG", msg)
Expand All @@ -175,12 +174,12 @@ class LastMessage(Payload):

def __init__(self):
self.reset()

def reset(self):
self.expect = None
self.counter = 0
self.msg = ""

def update(self, payload: Payload):
"update the expectation"
if payload.fmt != "loc": # pragma no cover
Expand Down Expand Up @@ -223,6 +222,7 @@ def expects(self, response: Union[Dict[str, Any], None]) -> int:
print("LOC:FOUND", response)
self.reset()
return 0
return 0


class LOC(threading.Thread):
Expand Down Expand Up @@ -255,23 +255,23 @@ def run(self):
while self.is_running.is_set():
try:
payload = get_from_queue(self.inbox)
if payload is None:
if payload is None:
if "status" in lastmessage.msg:
response = listen_and_queue(
client, ignore=[], queue=self.outbox
)
else:
else:
response = listen_and_queue(
client, ignore=self.ignore, queue=self.outbox
)
flevel = lastmessage.expects(response)
#print("LOC:FRUST", flevel, response)
# if flevel:
# print("LOC:FRUST", flevel, response)
# if flevel >= 2:
# print("LOC:RESEND", lastmessage.msg)
# client.send(lastmessage.msg)
# lastmessage.counter = 0
# sometimes, the get: "target_index" is ignored.
# in these cases, resend
if "target_index" in lastmessage.msg:
flevel = lastmessage.expects(response)
if flevel >= 2:
print("LOC:RESEND", lastmessage.msg)
client.send(lastmessage.msg)
lastmessage.counter = 0
else:
print("LOC:RECV", payload)
if payload.fmt == "cmd":
Expand Down
20 changes: 11 additions & 9 deletions localite/flow/mock.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import json
import threading
import time
from typing import Dict, Union
from typing import Dict, Union, Any
from localite.flow.payload import Queue
from localite.flow.loc import localiteClient

Expand Down Expand Up @@ -49,8 +49,7 @@ def Messages():

def kill(host: str = "127.0.0.1", port=6666):
client = localiteClient(host, port)
msg = {"cmd": "poison-pill"}
msg = json.dumps(msg)
msg = json.dumps({"cmd": "poison-pill"})
client.send(msg)


Expand Down Expand Up @@ -128,7 +127,7 @@ def kill(host: str = "127.0.0.1", port=6666):
}


def create_response(msg: Dict[str, Union[str, int]]) -> Dict:
def create_response(msg: Any) -> Union[Dict, None]:
if msg is None:
return None
key = list(msg.keys())[0]
Expand All @@ -143,10 +142,13 @@ def create_response(msg: Dict[str, Union[str, int]]) -> Dict:
"coil_0_target_index",
"coil_1_target_index",
]: # set target index
if type(val) == int and val > 0:
if type(val) is int and val > 0:
return msg
else:
return {"error": msg}
return {
"request": {key: val},
"reason": f"Index value out of range. Value: {val}, Range: [0..0]",
}
elif key == "single_pulse": # trigger
if val in ["COIL_0", "COIL_1"]:
return {val.lower() + "_didt": 11}
Expand Down Expand Up @@ -199,16 +201,16 @@ def await_running(self):
pass

@staticmethod
def read_msg(client: socket.socket) -> dict:
def read_msg(client: socket.socket) -> Union[Dict, None]:
"parse the message"
client.settimeout(0.1)
msg = b" "
while True:
try:
prt = client.recv(1)
msg += prt
msg = json.loads(msg.decode("ascii"))
return msg
dmsg = json.loads(msg.decode("ascii"))
return dmsg
except json.JSONDecodeError: # pragma no cover
pass
except socket.timeout:
Expand Down
8 changes: 4 additions & 4 deletions localite/flow/mrk.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,12 @@ def get_as_list(self) -> List[Any]:


def expectation(msg: str) -> str:
msg = json.loads(msg)
key = list(msg.keys())[0]
dmsg = json.loads(msg)
key = list(dmsg.keys())[0]
if key == "get":
return msg["get"]
return dmsg["get"]
elif "single_pulse" in key:
return msg["single_pulse"].lower() + "_didt"
return dmsg["single_pulse"].lower() + "_didt"
else:
return key

Expand Down
4 changes: 4 additions & 0 deletions mypy.ini
Original file line number Diff line number Diff line change
@@ -1,2 +1,6 @@
[mypy]
mypy_path=/media/rgugg/tools/python3/pyliesl, /media/rgugg/tools/python3/pyreiz
ignore_missing_imports = True
files = localite/**/*.py
pretty = True
error_summary = True
5 changes: 3 additions & 2 deletions test/flow/test_mitm.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import time
from pytest import fixture
from subprocess import Popen, PIPE
from os import environ


@fixture(scope="module")
Expand Down Expand Up @@ -37,7 +38,7 @@ def test_setup_tear_down(mock, capsys):
def test_cli(mock):
p = start(host="127.0.0.1")
time.sleep(1)
o, e = Popen(["localite-flow", "--kill"], stdout=PIPE).communicate()
o, e = Popen(["localite-flow", "--kill"], env=environ, stdout=PIPE).communicate()
assert b"poison-pill" in o

o, e = p.communicate()
Expand All @@ -46,6 +47,6 @@ def test_cli(mock):


def test_cli_help():
out = Popen(["localite-flow"], stdout=PIPE)
out = Popen(["localite-flow"], env=environ, stdout=PIPE)
o, e = out.communicate()
assert b"usage: localite-flow [-h]" in o
7 changes: 4 additions & 3 deletions test/flow/test_mock.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import time
from subprocess import Popen, PIPE
import pytest
from os import environ


def test_message_queue():
Expand All @@ -18,7 +19,7 @@ def test_message_queue():


def test_cli():
p = Popen(["localite-mock"], stderr=PIPE, stdout=PIPE)
p = Popen(["localite-mock"], env=environ, stderr=PIPE, stdout=PIPE)
time.sleep(1)
Popen(["localite-mock", "--kill"])
time.sleep(1)
Expand All @@ -31,8 +32,8 @@ def test_create_response():
assert "error" in cr({"current_instrument": "GARBAGE"}).keys()
assert "NONE" in cr({"current_instrument": "NONE"}).values()
assert 1 in cr({"coil_0_target_index": 1}).values()
assert "error" in cr({"coil_0_target_index": -1}).keys()
assert "error" in cr({"coil_0_target_index": "T"}).keys()
assert "reason" in cr({"coil_0_target_index": -1}).keys()
assert "reason" in cr({"coil_0_target_index": "T"}).keys()
assert "coil_0_didt" in cr({"single_pulse": "COIL_0"}).keys()
assert "error" in cr({"single_pulse": "COIL_2"}).keys()
assert 1 in cr({"coil_0_amplitude": 1}).values()
Expand Down
10 changes: 8 additions & 2 deletions test/test_coil.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ def coil(mock):
def test_coil_raw_request(coil):
msg = '{"get":"coil_0_temperature"}'
coil._push_loc(msg=msg)
time.sleep(1)
assert coil.receiver.await_response(msg)[0] == {"coil_0_temperature": 35}

def test_coil_static_properties(coil):
Expand All @@ -50,15 +51,17 @@ def test_coil_static_properties(coil):
assert coil.temperature == 35
assert coil.didt == 99
assert coil.visible
assert coil.connected == True
assert coil.connected is True
with raises(AttributeError):
coil.connected = False
assert coil.position_reached is True
assert coil.model == "Mock0704 mock"

def test_coil_setable_properties(coil):
assert coil.target_index == 1
coil.target_index = 2
coil.target_index = -1
with raises(ValueError):
coil.target_index = -1
assert (coil.amplitude == 2) == False
assert coil.amplitude == 1
coil.amplitude = 0
Expand All @@ -80,6 +83,9 @@ def test_coil_setable_properties(coil):
with raises(ValueError):
coil.id = -1

def test_coil_response(coil):
coil.set_response(mepmaxtime=18, mepamplitude=40, mepmin=-20, mepmax=20)

def test_coil_trigger(coil):
coil.trigger()

Expand Down

0 comments on commit accf835

Please sign in to comment.