Advertisement
Guest User

Untitled

a guest
Dec 19th, 2014
169
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.42 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3. '''Connect to a WirelessHART Manager and print data notifications
  4.  
  5. The connection parameters are taken from the environment variables SMSDK_HOST and SMSDK_PORT.
  6. '''
  7.  
  8. import os
  9. import sys
  10. sys.path += [
  11. os.path.join('.'), # path to directory containing SmartMeshSDK
  12. ]
  13.  
  14. import datetime
  15. import threading
  16. import pprint
  17.  
  18. import SmartMeshSDK.ApiException
  19. from SmartMeshSDK.ApiDefinition import HartMgrDefinition
  20. from SmartMeshSDK.HartMgrConnector import HartMgrConnector
  21.  
  22. # Configuration parameters
  23.  
  24. DEFAULT_HOST = '192.168.99.100'
  25. DEFAULT_PORT = 4445
  26.  
  27. pp = pprint.PrettyPrinter()
  28.  
  29.  
  30. class NotifHandler(threading.Thread):
  31. '''Get notifications from the WirelessHART Manager
  32.  
  33. This class is based on Thread, so it can be run asynchronously
  34. '''
  35.  
  36. def __init__(self, mgr):
  37. threading.Thread.__init__(self)
  38. self.mgr = mgr
  39.  
  40. def run(self):
  41. while True:
  42. notif = self.mgr.getNotification(1)
  43. if not notif:
  44. continue
  45.  
  46. # TODO: detect exit conditions
  47.  
  48. # Raw notifications
  49. #pp.pprint(notif)
  50.  
  51. # Structured data
  52. # notif[0] is the type, notif[1] is the notification
  53. # the notification time is a timestamp milliseconds
  54. notif_time = datetime.datetime.fromtimestamp(notif[1].time/1000)
  55. payload_data = ["{0:02X}".format(b) for b in notif[1].payload]
  56. fmt = "DATA: mac:{0} time:{1} payload:[{2}]\n {3}"
  57. print fmt.format(notif[1].macAddr,
  58. notif_time.isoformat(),
  59. len(notif[1].payload),
  60. " ".join(payload_data))
  61.  
  62. def main(host, port):
  63. # Initialize the WirelessHART Manager Connector
  64. mgr = HartMgrConnector.HartMgrConnector()
  65.  
  66. # Connect to the Manager over the XML API
  67. mgr.connect({'host': host, 'port': int(port), 'use_ssl': False})
  68.  
  69. # Subscribe to data notifications
  70. mgr.dn_subscribe('data')
  71.  
  72. # Create an object to receive notifications
  73. notifier = NotifHandler(mgr)
  74. notifier.run() # use notifier.start() to run in a separate thread
  75.  
  76. # Disconnect from the Manager
  77. mgr.disconnect()
  78.  
  79.  
  80. if __name__ == '__main__':
  81. try:
  82. host = os.environ['SMSDK_HOST']
  83. except KeyError:
  84. host = DEFAULT_HOST
  85. try:
  86. port = os.environ['SMSDK_PORT']
  87. except KeyError:
  88. port = DEFAULT_PORT
  89.  
  90. main(host, port)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement