Skip to content

Commit

Permalink
Make changes to support HitL testing.
Browse files Browse the repository at this point in the history
  • Loading branch information
haydenroche5 committed Aug 8, 2023
1 parent b52e7bb commit 9c106bb
Show file tree
Hide file tree
Showing 10 changed files with 1,108 additions and 71 deletions.
10 changes: 5 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -136,11 +136,11 @@ The documentation for this library can be found
The [examples](examples/) directory contains examples for using this
library with:

- [Serial](examples/notecard-basics/serial-example.py)
- [I2C](examples/notecard-basics/i2c-example.py)
- [RaspberryPi](examples/notecard-basics/rpi-example.py)
- [CircuitPython](examples/notecard-basics/cpy-example.py)
- [MicroPython](examples/notecard-basics/mpy-example.py)
- [Serial](examples/notecard-basics/serial_example.py)
- [I2C](examples/notecard-basics/i2c_example.py)
- [RaspberryPi](examples/notecard-basics/rpi_example.py)
- [CircuitPython](examples/notecard-basics/cpy_example.py)
- [MicroPython](examples/notecard-basics/mpy_example.py)

## Contributing

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,7 @@
import time
import notecard

productUID = "com.your-company.your-project"

# Choose either UART or I2C for Notecard
use_uart = True

if sys.implementation.name != 'circuitpython':
if sys.implementation.name != "circuitpython":
raise Exception("Please run this example in a CircuitPython environment.")

import board # noqa: E402
Expand All @@ -30,18 +25,18 @@ def NotecardExceptionInfo(exception):
"""
name = exception.__class__.__name__
return sys.platform + ": " + name \
+ ": " + ' '.join(map(str, exception.args))
+ ": " + " ".join(map(str, exception.args))


def configure_notecard(card):
def configure_notecard(card, product_uid):
"""Submit a simple JSON-based request to the Notecard.
Args:
card (object): An instance of the Notecard class
"""
req = {"req": "hub.set"}
req["product"] = productUID
req["product"] = product_uid
req["mode"] = "continuous"

try:
Expand Down Expand Up @@ -76,41 +71,38 @@ def get_temp_and_voltage(card):
return temp, voltage


def main():
def run_example(product_uid, use_uart=True):
"""Connect to Notcard and run a transaction test."""
print("Opening port...")
try:
if use_uart:
port = busio.UART(board.TX, board.RX, baudrate=9600)
else:
port = busio.I2C(board.SCL, board.SDA)
except Exception as exception:
raise Exception("error opening port: "
+ NotecardExceptionInfo(exception))
if use_uart:
port = busio.UART(board.TX, board.RX, baudrate=9600)
else:
port = busio.I2C(board.SCL, board.SDA)

print("Opening Notecard...")
try:
if use_uart:
card = notecard.OpenSerial(port, debug=True)
else:
card = notecard.OpenI2C(port, 0, 0, debug=True)
except Exception as exception:
raise Exception("error opening notecard: "
+ NotecardExceptionInfo(exception))
if use_uart:
card = notecard.OpenSerial(port, debug=True)
else:
card = notecard.OpenI2C(port, 0, 0, debug=True)

# If success, configure the Notecard and send some data
configure_notecard(card)
configure_notecard(card, product_uid)
temp, voltage = get_temp_and_voltage(card)

req = {"req": "note.add"}
req["sync"] = True
req["body"] = {"temp": temp, "voltage": voltage}

try:
card.Transaction(req)
except Exception as exception:
print("Transaction error: " + NotecardExceptionInfo(exception))
time.sleep(5)
card.Transaction(req)

# Developer note: do not modify the line below, as we use this as to signify
# that the example ran successfully to completion. We then use that to
# determine pass/fail for certain tests that leverage these examples.
print("Example complete.")


main()
if __name__ == "__main__":
product_uid = "com.your-company.your-project"
# Choose either UART or I2C for Notecard
use_uart = True
run_example(product_uid, use_uart)
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,12 @@
import time
import notecard

productUID = "com.your-company.your-project"

# Choose either UART or I2C for Notecard
use_uart = True

if sys.implementation.name != 'micropython':
if sys.implementation.name != "micropython":
raise Exception("Please run this example in a MicroPython environment.")

from machine import UART # noqa: E402
from machine import I2C # noqa: E402
from machine import Pin


def NotecardExceptionInfo(exception):
Expand All @@ -30,18 +26,18 @@ def NotecardExceptionInfo(exception):
"""
name = exception.__class__.__name__
return sys.platform + ": " + name + ": " \
+ ' '.join(map(str, exception.args))
+ " ".join(map(str, exception.args))


def configure_notecard(card):
def configure_notecard(card, product_uid):
"""Submit a simple JSON-based request to the Notecard.
Args:
card (object): An instance of the Notecard class
"""
req = {"req": "hub.set"}
req["product"] = productUID
req["product"] = product_uid
req["mode"] = "continuous"

try:
Expand Down Expand Up @@ -76,43 +72,44 @@ def get_temp_and_voltage(card):
return temp, voltage


def main():
def run_example(product_uid, use_uart=True):
"""Connect to Notcard and run a transaction test."""
print("Opening port...")
try:
if use_uart:
port = UART(2, 9600)
port.init(9600, bits=8, parity=None, stop=1,
timeout=3000, timeout_char=100)
if use_uart:
port = UART(2, 9600)
port.init(9600, bits=8, parity=None, stop=1,
timeout=3000, timeout_char=100)
else:
# If you"re using an ESP32, connect GPIO 22 to SCL and GPIO 21 to SDA.
if "ESP32" in sys.implementation._machine:
port = I2C(1, scl=Pin(22), sda=Pin(21))
else:
port = I2C()
except Exception as exception:
raise Exception("error opening port: "
+ NotecardExceptionInfo(exception))

print("Opening Notecard...")
try:
if use_uart:
card = notecard.OpenSerial(port, debug=True)
else:
card = notecard.OpenI2C(port, 0, 0, debug=True)
except Exception as exception:
raise Exception("error opening notecard: "
+ NotecardExceptionInfo(exception))
if use_uart:
card = notecard.OpenSerial(port, debug=True)
else:
card = notecard.OpenI2C(port, 0, 0, debug=True)

# If success, configure the Notecard and send some data
configure_notecard(card)
configure_notecard(card, product_uid)
temp, voltage = get_temp_and_voltage(card)

req = {"req": "note.add"}
req["sync"] = True
req["body"] = {"temp": temp, "voltage": voltage}

try:
card.Transaction(req)
except Exception as exception:
print("Transaction error: " + NotecardExceptionInfo(exception))
time.sleep(5)
card.Transaction(req)

# Developer note: do not modify the line below, as we use this as to signify
# that the example ran successfully to completion. We then use that to
# determine pass/fail for certain tests that leverage these examples.
print("Example complete.")


main()
if __name__ == "__main__":
product_uid = "com.your-company.your-project"
# Choose either UART or I2C for Notecard
use_uart = True
run_example(product_uid, use_uart)
File renamed without changes.
File renamed without changes.
2 changes: 2 additions & 0 deletions pytest.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[pytest]
addopts = --ignore=test/hitl/
101 changes: 101 additions & 0 deletions test/hitl/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
from pathlib import Path
import shutil
import sys

# Add the 'deps' folder to the path so we can import the pyboard module from
# it.
deps_path = str(Path(__file__).parent / 'deps')
sys.path.append(deps_path)
import pyboard # noqa: E402


def mkdir_on_host(pyb, dir):
pyb.enter_raw_repl()
try:
pyb.fs_mkdir(dir)
except pyboard.PyboardError as e:
already_exists = ["EEXIST", "File exists"]
if any([keyword in str(e) for keyword in already_exists]):
# If the directory already exists, that's fine.
pass
else:
raise
finally:
pyb.exit_raw_repl()


def copy_files_to_host(pyb, files, dest_dir):
pyb.enter_raw_repl()
try:
for f in files:
pyb.fs_put(f, f'{dest_dir}/{f.name}', chunk_size=4096)
finally:
pyb.exit_raw_repl()


def copy_file_to_host(pyb, file, dest):
pyb.enter_raw_repl()
try:
pyb.fs_put(file, dest, chunk_size=4096)
finally:
pyb.exit_raw_repl()


def setup_host(port, platform):
pyb = pyboard.Pyboard(port, 115200)
# Get the path to the root of the note-python repository.
note_python_root_dir = Path(__file__).parent.parent.parent
notecard_dir = note_python_root_dir / 'notecard'
# Get a list of all the .py files in note-python/notecard/.
notecard_files = list(notecard_dir.glob('*.py'))

mkdir_on_host(pyb, '/lib')
mkdir_on_host(pyb, '/lib/notecard')
copy_files_to_host(pyb, notecard_files, '/lib/notecard')

# Copy over mpy_example.py. We'll run this example code on the MicroPython
# host to 1) verify that the host is able to use note-python to communicate
# with the Notecard and 2) verify that the example isn't broken.
if platform == 'circuitpython':
example_file = 'cpy_example.py'
else:
example_file = 'mpy_example.py'
examples_dir = note_python_root_dir / 'examples'
example_file_path = examples_dir / 'notecard-basics' / example_file
copy_file_to_host(pyb, example_file_path, '/example.py')

pyb.close()


def pytest_addoption(parser):
parser.addoption(
'--port',
required=True,
help='The serial port of the CircuitPython host (e.g. /dev/ttyACM0).'
)
parser.addoption(
'--platform',
required=True,
help='Choose the platform to run the tests on.',
choices=["circuitpython", "micropython"]
)
parser.addoption(
'--productuid',
required=True,
help='The ProductUID to set on the Notecard.'
)
parser.addoption(
"--skipsetup",
action="store_true",
help="Skip host setup (copying over note-python, etc.) (default: False)"
)


def pytest_configure(config):
config.port = config.getoption("port")
config.platform = config.getoption("platform")
config.product_uid = config.getoption("productuid")
config.skip_setup = config.getoption("skipsetup")

if not config.skip_setup:
setup_host(config.port, config.platform)
Loading

0 comments on commit 9c106bb

Please sign in to comment.