Skip to content

Commit

Permalink
Command line message as hex.
Browse files Browse the repository at this point in the history
  • Loading branch information
eerimoq committed Aug 10, 2019
1 parent 1d44bfa commit b41c5bf
Show file tree
Hide file tree
Showing 8 changed files with 36 additions and 34 deletions.
10 changes: 5 additions & 5 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ messages are printed to standard output.
.. code-block:: text
$ mqttools subscribe /test/#
Connecting to 'broker.hivemq.com:1883'.
Connecting to 'localhost:1883'.
Topic: /test
Message: 11
Expand All @@ -85,7 +85,7 @@ Connect to given MQTT broker and publish a message to a topic.
.. code-block:: text
$ mqttools publish /test/mqttools/foo bar
Connecting to 'broker.hivemq.com:1883'.
Connecting to 'localhost:1883'.
Published 1 message(s) in 0 seconds from 1 concurrent task(s).
Expand All @@ -95,7 +95,7 @@ benchmark the client and the broker.
.. code-block:: text
$ mqttools publish --count 100 /test/mqttools/foo
Connecting to 'broker.hivemq.com:1883'.
Connecting to 'localhost:1883'.
Published 100 message(s) in 0.39 seconds from 10 concurrent task(s).
Expand Down Expand Up @@ -142,7 +142,7 @@ An example connecting to an MQTT broker, subscribing to the topic
import mqttools
async def subscriber():
client = mqttools.Client('broker.hivemq.com', 1883)
client = mqttools.Client('localhost', 1883)
await client.start()
await client.subscribe('/test/#')
Expand Down Expand Up @@ -171,7 +171,7 @@ An example connecting to an MQTT broker and publishing the message
import mqttools
async def publisher():
client = mqttools.Client('broker.hivemq.com', 1883)
client = mqttools.Client('localhost', 1883)
await client.start()
client.publish('/test/mqttools/foo', b'bar')
Expand Down
10 changes: 7 additions & 3 deletions mqttools/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import enum
from io import BytesIO
import bitstruct
from binascii import hexlify
import binascii


# Connection flags.
Expand All @@ -16,6 +16,10 @@
USER_NAME_FLAG = 0x80


def hexlify(data):
return binascii.hexlify(data).decode('ascii').upper()


# Control packet types.
class ControlPacketType(enum.IntEnum):
CONNECT = 1
Expand Down Expand Up @@ -781,7 +785,7 @@ def format_connect(payload):
f' ClientId: {client_id}',
f' CleanStart: {clean_start}',
f' WillTopic: {will_topic}',
f' WillMessage: {will_message}',
f' WillMessage: {hexlify(will_message)}',
f' KeepAlive: {keep_alive_s}',
f' UserName: {user_name}',
f' Password: {password}'
Expand All @@ -808,7 +812,7 @@ def format_publish(flags, payload):
f' QoSLevel: {qos}',
f' Retain: {retain}',
f' Topic: {topic}',
f' Message: {message}',
f' Message: {hexlify(message)}',
' Properties:'
] + format_properties(properties)

Expand Down
5 changes: 0 additions & 5 deletions mqttools/subparsers/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +0,0 @@
def try_decode(data):
try:
return data.decode('utf-8')
except UnicodeDecodeError:
return data
16 changes: 5 additions & 11 deletions mqttools/subparsers/monitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from queue import Empty as QueueEmpty

from ..client import Client
from ..common import hexlify


class QuitError(Exception):
Expand Down Expand Up @@ -160,17 +161,10 @@ def try_update_message(self):

lines = []
row_length = max(1, self._ncols - 12)
message = hexlify(message)

try:
message = message.decode('utf-8')

for line in message.splitlines():
lines.extend(textwrap.wrap(line, row_length))
except UnicodeDecodeError:
message = str(message)

for i in range(0, len(message), row_length):
lines.append(message[i:i + row_length])
for i in range(0, len(message), row_length):
lines.append(message[i:i + row_length])

formatted = [' {} {}'.format(timestamp, topic)]
formatted += [11 * ' ' + line for line in lines]
Expand Down Expand Up @@ -225,7 +219,7 @@ def add_subparser(subparsers):
subparser = subparsers.add_parser('monitor',
description='Monitor given topics.')
subparser.add_argument('--host',
default='broker.hivemq.com',
default='localhost',
help='Broker host (default: %(default)s).')
subparser.add_argument('--port',
type=int,
Expand Down
19 changes: 14 additions & 5 deletions mqttools/subparsers/publish.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,20 @@
import asyncio
import time
import binascii
from humanfriendly import format_timespan

from ..client import Client
from ..common import Error


def create_message_bytes(message, size, number, fmt):
def encode_message(message):
try:
return binascii.unhexlify(message)
except ValueError:
raise Error(f"Invalid hex string '{message}'.")


def create_message(message, size, number, fmt):
if message is None:
message_bytes = fmt.format(number).encode('ascii')
extra = (size - len(message_bytes))
Expand All @@ -15,7 +24,7 @@ def create_message_bytes(message, size, number, fmt):
else:
message_bytes = message_bytes[:size]
else:
message_bytes = message.encode('ascii')
message_bytes = encode_message(message)

return message_bytes

Expand All @@ -30,7 +39,7 @@ async def publisher(host,
topic,
message):
if will_message is not None:
will_message = will_message.encode('utf-8')
will_message = encode_message(will_message)

client = Client(host,
port,
Expand All @@ -47,7 +56,7 @@ async def publisher(host,
start_time = time.time()

for number in range(count):
message_bytes = create_message_bytes(message, size, number, fmt)
message_bytes = create_message(message, size, number, fmt)
client.publish(topic, message_bytes)

elapsed_time = format_timespan(time.time() - start_time)
Expand All @@ -72,7 +81,7 @@ def add_subparser(subparsers):
subparser = subparsers.add_parser('publish',
description='Publish given topic.')
subparser.add_argument('--host',
default='broker.hivemq.com',
default='localhost',
help='Broker host (default: %(default)s).')
subparser.add_argument('--port',
type=int,
Expand Down
6 changes: 3 additions & 3 deletions mqttools/subparsers/subscribe.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import asyncio

from ..client import Client
from . import try_decode
from ..common import hexlify


async def subscriber(host, port, client_id, topic, keep_alive_s):
Expand All @@ -25,7 +25,7 @@ async def subscriber(host, port, client_id, topic, keep_alive_s):
break

print(f'Topic: {topic}')
print(f'Message: {try_decode(message)}')
print(f'Message: {hexlify(message)}')

await client.stop()

Expand All @@ -42,7 +42,7 @@ def add_subparser(subparsers):
subparser = subparsers.add_parser('subscribe',
description='Subscribe for given topic.')
subparser.add_argument('--host',
default='broker.hivemq.com',
default='localhost',
help='Broker host (default: %(default)s).')
subparser.add_argument('--port',
type=int,
Expand Down
2 changes: 1 addition & 1 deletion mqttools/version.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = '0.26.0'
__version__ = '0.27.0'
2 changes: 1 addition & 1 deletion tests/test_mqttools.py
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,7 @@ def test_command_line_publish_qos_0(self):
'--port', str(self.broker.address[1]),
'--client-id', 'mqttools_publish',
'/a/b',
'apa'
'617061'
]

stdout = StringIO()
Expand Down

0 comments on commit b41c5bf

Please sign in to comment.