Skip to content

Commit 4f97e62

Browse files
author
durera
committed
More custom format fixes for samples and deviceCli
1 parent b93731d commit 4f97e62

File tree

4 files changed

+26
-21
lines changed

4 files changed

+26
-21
lines changed

samples/psutil/iotpsutil.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ def usage():
5959

6060
def commandProcessor(cmd):
6161
global interval
62-
print("Command received: %s" % cmd.payload)
62+
print("Command received: %s" % cmd.data)
6363
if cmd.command == "setInterval":
6464
if 'interval' not in cmd.data:
6565
print("Error - command is missing required information: 'interval'")

samples/psutil/psutilApp.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,7 @@ def sendMessage():
109109
global client, deviceType, deviceId
110110
message = input("Enter message to be displayed >")
111111
print("")
112-
client.publishCommand(deviceType, deviceId, "print", {'message': message})
112+
client.publishCommand(deviceType, deviceId, "print", "json", {'message': message})
113113

114114

115115
if __name__ == "__main__":

src/ibmiotf/__init__.py

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@
2929
__version__ = "0.1.2"
3030

3131
class Message:
32-
def __init__(self, data, timestamp):
32+
def __init__(self, data, timestamp=None):
3333
self.data = data
3434
self.timestamp = timestamp
3535

@@ -46,25 +46,25 @@ def __init__(self, organization, clientId, username, password, logDir=None):
4646

4747
self.messages = 0
4848
self.recv = 0
49-
49+
5050
self.clientId = clientId
5151

5252
# Configure logging
5353
self.logDir = logDir
5454

5555
self.logger = logging.getLogger(self.__module__+"."+self.__class__.__name__)
5656
self.logger.setLevel(logging.INFO)
57-
57+
5858
logFileName = '%s.log' % (clientId.replace(":", "_"))
5959
self.logFile = os.path.join(self.logDir, logFileName) if (self.logDir is not None) else logFileName
60-
60+
6161
# create file handler, set level to debug & set format
6262
fhFormatter = logging.Formatter('%(asctime)-25s %(name)-25s ' + ' %(levelname)-7s %(message)s')
6363
rfh = RotatingFileHandler(self.logFile, mode='a', maxBytes=1024000 , backupCount=0, encoding=None, delay=True)
6464
rfh.setFormatter(fhFormatter)
6565

6666
self.logger.addHandler(rfh)
67-
67+
6868
self.client = paho.Client(self.clientId, clean_session=True)
6969

7070
try:
@@ -88,21 +88,22 @@ def __init__(self, organization, clientId, username, password, logDir=None):
8888
else:
8989
self.logger.warning("Unable to encrypt messages because TLSv1.2 is unavailable (MQTT over SSL requires at least Python v2.7.9 or 3.4 and openssl v1.0.1)")
9090
self.client.username_pw_set(self.username, self.password)
91-
92-
#attach MQTT callbacks
91+
92+
# Attach MQTT callbacks
9393
self.client.on_log = self.on_log
9494
self.client.on_connect = self.on_connect
9595
self.client.on_disconnect = self.on_disconnect
9696
self.client.on_publish = self.on_publish
97-
97+
9898
# Initialize default message encoders and decoders.
9999
self.messageEncoderModules = {}
100100

101101
self.start = time.time()
102102

103+
103104
def setMessageEncoderModule(self, messageFormat, module):
104105
self.messageEncoderModules[messageFormat] = module
105-
106+
106107
def logAndRaiseException(self, e):
107108
self.logger.critical(str(e))
108109
raise e
@@ -128,7 +129,7 @@ def disconnect(self):
128129
self.client.loop_stop()
129130
#self.stats()
130131
self.logger.info("Closed connection to the IBM Internet of Things Foundation")
131-
132+
132133
def stats(self):
133134
elapsed = ((time.time()) - self.start)
134135

src/ibmiotf/device.py

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -28,16 +28,21 @@
2828
COMMAND_RE = re.compile("iot-2/cmd/(.+)/fmt/(.+)")
2929

3030

31-
class Command(Message):
32-
def __init__(self, message):
33-
result = COMMAND_RE.match(message.topic)
31+
class Command:
32+
def __init__(self, pahoMessage, messageEncoderModules):
33+
result = COMMAND_RE.match(pahoMessage.topic)
3434
if result:
35-
Message.__init__(self, message)
36-
3735
self.command = result.group(1)
3836
self.format = result.group(2)
37+
38+
if self.format in messageEncoderModules:
39+
message = messageEncoderModules[self.format].decode(pahoMessage)
40+
self.timestamp = message.timestamp
41+
self.data = message.data
42+
else:
43+
raise MissingMessageDecoderException(self.format)
3944
else:
40-
raise InvalidEventException("Received command on invalid topic: %s" % (message.topic))
45+
raise InvalidEventException("Received command on invalid topic: %s" % (pahoMessage.topic))
4146

4247

4348
class Client(AbstractClient):
@@ -140,11 +145,10 @@ def __subscribeToCommands(self):
140145
Internal callback for device command messages, parses source device from topic string and
141146
passes the information on to the registerd device command callback
142147
'''
143-
def __onCommand(self, client, userdata, message):
148+
def __onCommand(self, client, userdata, pahoMessage):
144149
self.recv = self.recv + 1
145-
146150
try:
147-
command = Command(message)
151+
command = Command(pahoMessage, self.messageEncoderModules)
148152
self.logger.debug("Received command '%s'" % (command.command))
149153
if self.commandCallback: self.commandCallback(command)
150154
except InvalidEventException as e:

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy