Skip to content

Fix the packet prefix #2

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Mar 4, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .pylintrc
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ confidence=
# no Warning level messages displayed, use"--disable=all --enable=classes
# --disable=W"
# disable=import-error,print-statement,parameter-unpacking,unpacking-in-except,old-raise-syntax,backtick,long-suffix,old-ne-operator,old-octal-literal,import-star-module-level,raw-checker-failed,bad-inline-option,locally-disabled,locally-enabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,apply-builtin,basestring-builtin,buffer-builtin,cmp-builtin,coerce-builtin,execfile-builtin,file-builtin,long-builtin,raw_input-builtin,reduce-builtin,standarderror-builtin,unicode-builtin,xrange-builtin,coerce-method,delslice-method,getslice-method,setslice-method,no-absolute-import,old-division,dict-iter-method,dict-view-method,next-method-called,metaclass-assignment,indexing-exception,raising-string,reload-builtin,oct-method,hex-method,nonzero-method,cmp-method,input-builtin,round-builtin,intern-builtin,unichr-builtin,map-builtin-not-iterating,zip-builtin-not-iterating,range-builtin-not-iterating,filter-builtin-not-iterating,using-cmp-argument,eq-without-hash,div-method,idiv-method,rdiv-method,exception-message-attribute,invalid-str-codec,sys-max-int,bad-python3-import,deprecated-string-function,deprecated-str-translate-call
disable=print-statement,parameter-unpacking,unpacking-in-except,old-raise-syntax,backtick,long-suffix,old-ne-operator,old-octal-literal,import-star-module-level,raw-checker-failed,bad-inline-option,locally-disabled,locally-enabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,apply-builtin,basestring-builtin,buffer-builtin,cmp-builtin,coerce-builtin,execfile-builtin,file-builtin,long-builtin,raw_input-builtin,reduce-builtin,standarderror-builtin,unicode-builtin,xrange-builtin,coerce-method,delslice-method,getslice-method,setslice-method,no-absolute-import,old-division,dict-iter-method,dict-view-method,next-method-called,metaclass-assignment,indexing-exception,raising-string,reload-builtin,oct-method,hex-method,nonzero-method,cmp-method,input-builtin,round-builtin,intern-builtin,unichr-builtin,map-builtin-not-iterating,zip-builtin-not-iterating,range-builtin-not-iterating,filter-builtin-not-iterating,using-cmp-argument,eq-without-hash,div-method,idiv-method,rdiv-method,exception-message-attribute,invalid-str-codec,sys-max-int,bad-python3-import,deprecated-string-function,deprecated-str-translate-call,import-error
disable=print-statement,parameter-unpacking,unpacking-in-except,old-raise-syntax,backtick,long-suffix,old-ne-operator,old-octal-literal,import-star-module-level,raw-checker-failed,bad-inline-option,locally-disabled,locally-enabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,apply-builtin,basestring-builtin,buffer-builtin,cmp-builtin,coerce-builtin,execfile-builtin,file-builtin,long-builtin,raw_input-builtin,reduce-builtin,standarderror-builtin,unicode-builtin,xrange-builtin,coerce-method,delslice-method,getslice-method,setslice-method,no-absolute-import,old-division,dict-iter-method,dict-view-method,next-method-called,metaclass-assignment,indexing-exception,raising-string,reload-builtin,oct-method,hex-method,nonzero-method,cmp-method,input-builtin,round-builtin,intern-builtin,unichr-builtin,map-builtin-not-iterating,zip-builtin-not-iterating,range-builtin-not-iterating,filter-builtin-not-iterating,using-cmp-argument,eq-without-hash,div-method,idiv-method,rdiv-method,exception-message-attribute,invalid-str-codec,sys-max-int,bad-python3-import,deprecated-string-function,deprecated-str-translate-call,import-error,bad-continuation

# Enable the message, report, category or checker with the given id(s). You can
# either give multiple identifier separated by comma (,) or put this option
Expand Down
65 changes: 46 additions & 19 deletions adafruit_radio.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,10 @@
"""
import time
import struct
import random
from micropython import const
from adafruit_ble import BLERadio
from adafruit_ble.advertising.adafruit import AdafruitRadio
from adafruit_ble.advertising import Advertisement, LazyObjectField
from adafruit_ble.advertising.standard import ManufacturerData


__version__ = "0.0.0-auto.0"
Expand All @@ -56,6 +57,42 @@
#: Amount of time to advertise a message (in seconds).
AD_DURATION = 0.5

_MANUFACTURING_DATA_ADT = const(0xFF)
_ADAFRUIT_COMPANY_ID = const(0x0822)
_RADIO_DATA_ID = const(0x0001) # TODO: check this isn't already taken.


class _RadioAdvertisement(Advertisement):
"""Broadcast arbitrary bytes as a radio message."""

prefix = struct.pack("<BBH", 0x3, 0xFF, _ADAFRUIT_COMPANY_ID)
manufacturer_data = LazyObjectField(
ManufacturerData,
"manufacturer_data",
advertising_data_type=_MANUFACTURING_DATA_ADT,
company_id=_ADAFRUIT_COMPANY_ID,
key_encoding="<H",
)

@classmethod
def matches(cls, entry):
if len(entry.advertisement_bytes) < 6:
return False
# Check the key position within the manufacturer data. We already know
# prefix matches so we don't need to check it twice.
return struct.unpack_from("<H", entry.advertisement_bytes, 5)[0] == _RADIO_DATA_ID

@property
def msg(self):
"""Raw radio data"""
if _RADIO_DATA_ID not in self.manufacturer_data.data:
return b""
return self.manufacturer_data.data[_RADIO_DATA_ID]

@msg.setter
def msg(self, value):
self.manufacturer_data.data[_RADIO_DATA_ID] = value


class Radio:
"""
Expand Down Expand Up @@ -108,21 +145,12 @@ def send_bytes(self, message):
"""
# Ensure length of message.
if len(message) > MAX_LENGTH:
raise ValueError(
"Message too long (max length = {})".format(MAX_LENGTH)
)
advertisement = AdafruitRadio()
# Channel byte.
chan = struct.pack("<B", self._channel)
# "Unique" id byte (to avoid duplication when receiving messages in
# an AD_DURATION timeframe).
uid = struct.pack("<B", self.uid)
# Increment (and reset if needed) the uid.
self.uid += 1
if self.uid > 255:
self.uid = 0
raise ValueError("Message too long (max length = {})".format(MAX_LENGTH))
advertisement = _RadioAdvertisement()
# Concatenate the bytes that make up the advertised message.
advertisement.msg = chan + uid + message
advertisement.msg = struct.pack("<BB", self._channel, self.uid) + message

self.uid = (self.uid + 1) % 255
# Advertise (block) for AD_DURATION period of time.
self.ble.start_advertising(advertisement)
time.sleep(AD_DURATION)
Expand All @@ -138,8 +166,7 @@ def receive(self):
msg = self.receive_full()
if msg:
return msg[0].decode("utf-8").replace("\x00", "")
else:
return None
return None

def receive_full(self):
"""
Expand All @@ -158,7 +185,7 @@ def receive_full(self):
"""
try:
for entry in self.ble.start_scan(
AdafruitRadio, minimum_rssi=-255, timeout=1, extended=True
_RadioAdvertisement, minimum_rssi=-255, timeout=1, extended=True
):
# Extract channel and unique message ID bytes.
chan, uid = struct.unpack("<BB", entry.msg[:2])
Expand Down
106 changes: 59 additions & 47 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,19 @@

import os
import sys
sys.path.insert(0, os.path.abspath('..'))

sys.path.insert(0, os.path.abspath(".."))

# -- General configuration ------------------------------------------------

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.intersphinx',
'sphinx.ext.napoleon',
'sphinx.ext.todo',
"sphinx.ext.autodoc",
"sphinx.ext.intersphinx",
"sphinx.ext.napoleon",
"sphinx.ext.todo",
]

# TODO: Please Read!
Expand All @@ -23,29 +24,32 @@
autodoc_mock_imports = ["digitalio", "busio", "adafruit_ble"]


intersphinx_mapping = {'python': ('https://docs.python.org/3.4', None),'CircuitPython': ('https://circuitpython.readthedocs.io/en/latest/', None)}
intersphinx_mapping = {
"python": ("https://docs.python.org/3.4", None),
"CircuitPython": ("https://circuitpython.readthedocs.io/en/latest/", None),
}

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
templates_path = ["_templates"]

source_suffix = '.rst'
source_suffix = ".rst"

# The master toctree document.
master_doc = 'index'
master_doc = "index"

# General information about the project.
project = u'Adafruit radio Library'
copyright = u'2019 Nicholas H.Tollervey'
author = u'Nicholas H.Tollervey'
project = "Adafruit radio Library"
copyright = "2019 Nicholas H.Tollervey"
author = "Nicholas H.Tollervey"

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = u'1.0'
version = "1.0"
# The full version, including alpha/beta/rc tags.
release = u'1.0'
release = "1.0"

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
Expand All @@ -57,7 +61,7 @@
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store', '.env', 'CODE_OF_CONDUCT.md']
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store", ".env", "CODE_OF_CONDUCT.md"]

# The reST default role (used for this markup: `text`) to use for all
# documents.
Expand All @@ -69,7 +73,7 @@
add_function_parentheses = True

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
pygments_style = "sphinx"

# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
Expand All @@ -84,68 +88,70 @@
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
on_rtd = os.environ.get("READTHEDOCS", None) == "True"

if not on_rtd: # only import and set the theme if we're building docs locally
try:
import sphinx_rtd_theme
html_theme = 'sphinx_rtd_theme'
html_theme_path = [sphinx_rtd_theme.get_html_theme_path(), '.']

html_theme = "sphinx_rtd_theme"
html_theme_path = [sphinx_rtd_theme.get_html_theme_path(), "."]
except:
html_theme = 'default'
html_theme_path = ['.']
html_theme = "default"
html_theme_path = ["."]
else:
html_theme_path = ['.']
html_theme_path = ["."]

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
html_static_path = ["_static"]

# The name of an image file (relative to this directory) to use as a favicon of
# the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#
html_favicon = '_static/favicon.ico'
html_favicon = "_static/favicon.ico"

# Output file base name for HTML help builder.
htmlhelp_basename = 'AdafruitRadioLibrarydoc'
htmlhelp_basename = "AdafruitRadioLibrarydoc"

# -- Options for LaTeX output ---------------------------------------------

latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',

# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',

# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',

# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'AdafruitradioLibrary.tex', u'Adafruitradio Library Documentation',
author, 'manual'),
(
master_doc,
"AdafruitradioLibrary.tex",
"Adafruitradio Library Documentation",
author,
"manual",
),
]

# -- Options for manual page output ---------------------------------------

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'Adafruitradiolibrary', u'Adafruit radio Library Documentation',
[author], 1)
(master_doc, "Adafruitradiolibrary", "Adafruit radio Library Documentation", [author], 1)
]

# -- Options for Texinfo output -------------------------------------------
Expand All @@ -154,7 +160,13 @@
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'AdafruitradioLibrary', u'Adafruit radio Library Documentation',
author, 'AdafruitradioLibrary', 'One line description of project.',
'Miscellaneous'),
(
master_doc,
"AdafruitradioLibrary",
"Adafruit radio Library Documentation",
author,
"AdafruitradioLibrary",
"One line description of project.",
"Miscellaneous",
),
]
1 change: 0 additions & 1 deletion examples/radio_simpletest.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,4 +54,3 @@
# m = r.receive()
# if m:
# print(m)

3 changes: 1 addition & 2 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
Adafruit-Blinka
adafruit_ble
adafruit-circuitpython-ble
Loading