├── paho ├── __init__.py └── mqtt │ ├── __init__.py │ ├── packettypes.py │ ├── matcher.py │ ├── subscribeoptions.py │ ├── reasoncodes.py │ ├── publish.py │ ├── subscribe.py │ └── properties.py ├── .github └── FUNDING.yml ├── .gitignore ├── README.md ├── load.py ├── settings.py └── LICENSE /paho/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: [fasteddy516] 2 | -------------------------------------------------------------------------------- /paho/mqtt/__init__.py: -------------------------------------------------------------------------------- 1 | __version__ = "1.5.1" 2 | 3 | 4 | class MQTTException(Exception): 5 | pass 6 | -------------------------------------------------------------------------------- /paho/mqtt/packettypes.py: -------------------------------------------------------------------------------- 1 | """ 2 | ******************************************************************* 3 | Copyright (c) 2017, 2019 IBM Corp. 4 | 5 | All rights reserved. This program and the accompanying materials 6 | are made available under the terms of the Eclipse Public License v1.0 7 | and Eclipse Distribution License v1.0 which accompany this distribution. 8 | 9 | The Eclipse Public License is available at 10 | http://www.eclipse.org/legal/epl-v10.html 11 | and the Eclipse Distribution License is available at 12 | http://www.eclipse.org/org/documents/edl-v10.php. 13 | 14 | Contributors: 15 | Ian Craggs - initial implementation and/or documentation 16 | ******************************************************************* 17 | """ 18 | 19 | 20 | class PacketTypes: 21 | 22 | """ 23 | Packet types class. Includes the AUTH packet for MQTT v5.0. 24 | 25 | Holds constants for each packet type such as PacketTypes.PUBLISH 26 | and packet name strings: PacketTypes.Names[PacketTypes.PUBLISH]. 27 | 28 | """ 29 | 30 | indexes = range(1, 16) 31 | 32 | # Packet types 33 | CONNECT, CONNACK, PUBLISH, PUBACK, PUBREC, PUBREL, \ 34 | PUBCOMP, SUBSCRIBE, SUBACK, UNSUBSCRIBE, UNSUBACK, \ 35 | PINGREQ, PINGRESP, DISCONNECT, AUTH = indexes 36 | 37 | # Dummy packet type for properties use - will delay only applies to will 38 | WILLMESSAGE = 99 39 | 40 | Names = [ "reserved", \ 41 | "Connect", "Connack", "Publish", "Puback", "Pubrec", "Pubrel", \ 42 | "Pubcomp", "Subscribe", "Suback", "Unsubscribe", "Unsuback", \ 43 | "Pingreq", "Pingresp", "Disconnect", "Auth"] 44 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | 49 | # Translations 50 | *.mo 51 | *.pot 52 | 53 | # Django stuff: 54 | *.log 55 | local_settings.py 56 | 57 | # Flask stuff: 58 | instance/ 59 | .webassets-cache 60 | 61 | # Scrapy stuff: 62 | .scrapy 63 | 64 | # Sphinx documentation 65 | docs/_build/ 66 | 67 | # PyBuilder 68 | target/ 69 | 70 | # Jupyter Notebook 71 | .ipynb_checkpoints 72 | 73 | # pyenv 74 | .python-version 75 | 76 | # celery beat schedule file 77 | celerybeat-schedule 78 | 79 | # SageMath parsed files 80 | *.sage.py 81 | 82 | # dotenv 83 | .env 84 | 85 | # virtualenv 86 | .venv 87 | venv/ 88 | ENV/ 89 | 90 | # Spyder project settings 91 | .spyderproject 92 | .spyproject 93 | 94 | # Rope project settings 95 | .ropeproject 96 | 97 | # mkdocs documentation 98 | /site 99 | 100 | # mypy 101 | .mypy_cache/ 102 | 103 | # visual studio 104 | .vs/ 105 | 106 | # EDMC-Telemetry 107 | settings.json 108 | *.pem -------------------------------------------------------------------------------- /paho/mqtt/matcher.py: -------------------------------------------------------------------------------- 1 | class MQTTMatcher(object): 2 | """Intended to manage topic filters including wildcards. 3 | 4 | Internally, MQTTMatcher use a prefix tree (trie) to store 5 | values associated with filters, and has an iter_match() 6 | method to iterate efficiently over all filters that match 7 | some topic name.""" 8 | 9 | class Node(object): 10 | __slots__ = '_children', '_content' 11 | 12 | def __init__(self): 13 | self._children = {} 14 | self._content = None 15 | 16 | def __init__(self): 17 | self._root = self.Node() 18 | 19 | def __setitem__(self, key, value): 20 | """Add a topic filter :key to the prefix tree 21 | and associate it to :value""" 22 | node = self._root 23 | for sym in key.split('/'): 24 | node = node._children.setdefault(sym, self.Node()) 25 | node._content = value 26 | 27 | def __getitem__(self, key): 28 | """Retrieve the value associated with some topic filter :key""" 29 | try: 30 | node = self._root 31 | for sym in key.split('/'): 32 | node = node._children[sym] 33 | if node._content is None: 34 | raise KeyError(key) 35 | return node._content 36 | except KeyError: 37 | raise KeyError(key) 38 | 39 | def __delitem__(self, key): 40 | """Delete the value associated with some topic filter :key""" 41 | lst = [] 42 | try: 43 | parent, node = None, self._root 44 | for k in key.split('/'): 45 | parent, node = node, node._children[k] 46 | lst.append((parent, k, node)) 47 | # TODO 48 | node._content = None 49 | except KeyError: 50 | raise KeyError(key) 51 | else: # cleanup 52 | for parent, k, node in reversed(lst): 53 | if node._children or node._content is not None: 54 | break 55 | del parent._children[k] 56 | 57 | def iter_match(self, topic): 58 | """Return an iterator on all values associated with filters 59 | that match the :topic""" 60 | lst = topic.split('/') 61 | normal = not topic.startswith('$') 62 | def rec(node, i=0): 63 | if i == len(lst): 64 | if node._content is not None: 65 | yield node._content 66 | else: 67 | part = lst[i] 68 | if part in node._children: 69 | for content in rec(node._children[part], i + 1): 70 | yield content 71 | if '+' in node._children and (normal or i > 0): 72 | for content in rec(node._children['+'], i + 1): 73 | yield content 74 | if '#' in node._children and (normal or i > 0): 75 | content = node._children['#']._content 76 | if content is not None: 77 | yield content 78 | return rec(self._root) 79 | -------------------------------------------------------------------------------- /paho/mqtt/subscribeoptions.py: -------------------------------------------------------------------------------- 1 | """ 2 | ******************************************************************* 3 | Copyright (c) 2017, 2019 IBM Corp. 4 | 5 | All rights reserved. This program and the accompanying materials 6 | are made available under the terms of the Eclipse Public License v1.0 7 | and Eclipse Distribution License v1.0 which accompany this distribution. 8 | 9 | The Eclipse Public License is available at 10 | http://www.eclipse.org/legal/epl-v10.html 11 | and the Eclipse Distribution License is available at 12 | http://www.eclipse.org/org/documents/edl-v10.php. 13 | 14 | Contributors: 15 | Ian Craggs - initial implementation and/or documentation 16 | ******************************************************************* 17 | """ 18 | 19 | import sys 20 | 21 | 22 | class MQTTException(Exception): 23 | pass 24 | 25 | 26 | class SubscribeOptions(object): 27 | """The MQTT v5.0 subscribe options class. 28 | 29 | The options are: 30 | qos: As in MQTT v3.1.1. 31 | noLocal: True or False. If set to True, the subscriber will not receive its own publications. 32 | retainAsPublished: True or False. If set to True, the retain flag on received publications will be as set 33 | by the publisher. 34 | retainHandling: RETAIN_SEND_ON_SUBSCRIBE, RETAIN_SEND_IF_NEW_SUB or RETAIN_DO_NOT_SEND 35 | Controls when the broker should send retained messages: 36 | - RETAIN_SEND_ON_SUBSCRIBE: on any successful subscribe request 37 | - RETAIN_SEND_IF_NEW_SUB: only if the subscribe request is new 38 | - RETAIN_DO_NOT_SEND: never send retained messages 39 | """ 40 | 41 | # retain handling options 42 | RETAIN_SEND_ON_SUBSCRIBE, RETAIN_SEND_IF_NEW_SUB, RETAIN_DO_NOT_SEND = range( 43 | 0, 3) 44 | 45 | def __init__(self, qos=0, noLocal=False, retainAsPublished=False, retainHandling=RETAIN_SEND_ON_SUBSCRIBE): 46 | """ 47 | qos: 0, 1 or 2. 0 is the default. 48 | noLocal: True or False. False is the default and corresponds to MQTT v3.1.1 behavior. 49 | retainAsPublished: True or False. False is the default and corresponds to MQTT v3.1.1 behavior. 50 | retainHandling: RETAIN_SEND_ON_SUBSCRIBE, RETAIN_SEND_IF_NEW_SUB or RETAIN_DO_NOT_SEND 51 | RETAIN_SEND_ON_SUBSCRIBE is the default and corresponds to MQTT v3.1.1 behavior. 52 | """ 53 | object.__setattr__(self, "names", 54 | ["QoS", "noLocal", "retainAsPublished", "retainHandling"]) 55 | self.QoS = qos # bits 0,1 56 | self.noLocal = noLocal # bit 2 57 | self.retainAsPublished = retainAsPublished # bit 3 58 | self.retainHandling = retainHandling # bits 4 and 5: 0, 1 or 2 59 | assert self.QoS in [0, 1, 2] 60 | assert self.retainHandling in [ 61 | 0, 1, 2], "Retain handling should be 0, 1 or 2" 62 | 63 | def __setattr__(self, name, value): 64 | if name not in self.names: 65 | raise MQTTException( 66 | name + " Attribute name must be one of "+str(self.names)) 67 | object.__setattr__(self, name, value) 68 | 69 | def pack(self): 70 | assert self.QoS in [0, 1, 2] 71 | assert self.retainHandling in [ 72 | 0, 1, 2], "Retain handling should be 0, 1 or 2" 73 | noLocal = 1 if self.noLocal else 0 74 | retainAsPublished = 1 if self.retainAsPublished else 0 75 | data = [(self.retainHandling << 4) | (retainAsPublished << 3) | 76 | (noLocal << 2) | self.QoS] 77 | if sys.version_info[0] >= 3: 78 | buffer = bytes(data) 79 | else: 80 | buffer = bytearray(data) 81 | return buffer 82 | 83 | def unpack(self, buffer): 84 | b0 = buffer[0] 85 | self.retainHandling = ((b0 >> 4) & 0x03) 86 | self.retainAsPublished = True if ((b0 >> 3) & 0x01) == 1 else False 87 | self.noLocal = True if ((b0 >> 2) & 0x01) == 1 else False 88 | self.QoS = (b0 & 0x03) 89 | assert self.retainHandling in [ 90 | 0, 1, 2], "Retain handling should be 0, 1 or 2, not %d" % self.retainHandling 91 | assert self.QoS in [ 92 | 0, 1, 2], "QoS should be 0, 1 or 2, not %d" % self.QoS 93 | return 1 94 | 95 | def __repr__(self): 96 | return str(self) 97 | 98 | def __str__(self): 99 | return "{QoS="+str(self.QoS)+", noLocal="+str(self.noLocal) +\ 100 | ", retainAsPublished="+str(self.retainAsPublished) +\ 101 | ", retainHandling="+str(self.retainHandling)+"}" 102 | 103 | def json(self): 104 | data = { 105 | "QoS": self.QoS, 106 | "noLocal": self.noLocal, 107 | "retainAsPublished": self.retainAsPublished, 108 | "retainHandling": self.retainHandling, 109 | } 110 | return data 111 | -------------------------------------------------------------------------------- /paho/mqtt/reasoncodes.py: -------------------------------------------------------------------------------- 1 | """ 2 | ******************************************************************* 3 | Copyright (c) 2017, 2019 IBM Corp. 4 | 5 | All rights reserved. This program and the accompanying materials 6 | are made available under the terms of the Eclipse Public License v1.0 7 | and Eclipse Distribution License v1.0 which accompany this distribution. 8 | 9 | The Eclipse Public License is available at 10 | http://www.eclipse.org/legal/epl-v10.html 11 | and the Eclipse Distribution License is available at 12 | http://www.eclipse.org/org/documents/edl-v10.php. 13 | 14 | Contributors: 15 | Ian Craggs - initial implementation and/or documentation 16 | ******************************************************************* 17 | """ 18 | 19 | import sys 20 | from .packettypes import PacketTypes 21 | 22 | 23 | class ReasonCodes: 24 | """MQTT version 5.0 reason codes class. 25 | 26 | See ReasonCodes.names for a list of possible numeric values along with their 27 | names and the packets to which they apply. 28 | 29 | """ 30 | 31 | def __init__(self, packetType, aName="Success", identifier=-1): 32 | """ 33 | packetType: the type of the packet, such as PacketTypes.CONNECT that 34 | this reason code will be used with. Some reason codes have different 35 | names for the same identifier when used a different packet type. 36 | 37 | aName: the String name of the reason code to be created. Ignored 38 | if the identifier is set. 39 | 40 | identifier: an integer value of the reason code to be created. 41 | 42 | """ 43 | 44 | self.packetType = packetType 45 | self.names = { 46 | 0: {"Success": [PacketTypes.CONNACK, PacketTypes.PUBACK, 47 | PacketTypes.PUBREC, PacketTypes.PUBREL, PacketTypes.PUBCOMP, 48 | PacketTypes.UNSUBACK, PacketTypes.AUTH], 49 | "Normal disconnection": [PacketTypes.DISCONNECT], 50 | "Granted QoS 0": [PacketTypes.SUBACK]}, 51 | 1: {"Granted QoS 1": [PacketTypes.SUBACK]}, 52 | 2: {"Granted QoS 2": [PacketTypes.SUBACK]}, 53 | 4: {"Disconnect with will message": [PacketTypes.DISCONNECT]}, 54 | 16: {"No matching subscribers": 55 | [PacketTypes.PUBACK, PacketTypes.PUBREC]}, 56 | 17: {"No subscription found": [PacketTypes.UNSUBACK]}, 57 | 24: {"Continue authentication": [PacketTypes.AUTH]}, 58 | 25: {"Re-authenticate": [PacketTypes.AUTH]}, 59 | 128: {"Unspecified error": [PacketTypes.CONNACK, PacketTypes.PUBACK, 60 | PacketTypes.PUBREC, PacketTypes.SUBACK, PacketTypes.UNSUBACK, 61 | PacketTypes.DISCONNECT], }, 62 | 129: {"Malformed packet": 63 | [PacketTypes.CONNACK, PacketTypes.DISCONNECT]}, 64 | 130: {"Protocol error": 65 | [PacketTypes.CONNACK, PacketTypes.DISCONNECT]}, 66 | 131: {"Implementation specific error": [PacketTypes.CONNACK, 67 | PacketTypes.PUBACK, PacketTypes.PUBREC, PacketTypes.SUBACK, 68 | PacketTypes.UNSUBACK, PacketTypes.DISCONNECT], }, 69 | 132: {"Unsupported protocol version": [PacketTypes.CONNACK]}, 70 | 133: {"Client identifier not valid": [PacketTypes.CONNACK]}, 71 | 134: {"Bad user name or password": [PacketTypes.CONNACK]}, 72 | 135: {"Not authorized": [PacketTypes.CONNACK, PacketTypes.PUBACK, 73 | PacketTypes.PUBREC, PacketTypes.SUBACK, PacketTypes.UNSUBACK, 74 | PacketTypes.DISCONNECT], }, 75 | 136: {"Server unavailable": [PacketTypes.CONNACK]}, 76 | 137: {"Server busy": [PacketTypes.CONNACK, PacketTypes.DISCONNECT]}, 77 | 138: {"Banned": [PacketTypes.CONNACK]}, 78 | 139: {"Server shutting down": [PacketTypes.DISCONNECT]}, 79 | 140: {"Bad authentication method": 80 | [PacketTypes.CONNACK, PacketTypes.DISCONNECT]}, 81 | 141: {"Keep alive timeout": [PacketTypes.DISCONNECT]}, 82 | 142: {"Session taken over": [PacketTypes.DISCONNECT]}, 83 | 143: {"Topic filter invalid": 84 | [PacketTypes.SUBACK, PacketTypes.UNSUBACK, PacketTypes.DISCONNECT]}, 85 | 144: {"Topic name invalid": 86 | [PacketTypes.CONNACK, PacketTypes.PUBACK, 87 | PacketTypes.PUBREC, PacketTypes.DISCONNECT]}, 88 | 145: {"Packet identifier in use": 89 | [PacketTypes.PUBACK, PacketTypes.PUBREC, 90 | PacketTypes.SUBACK, PacketTypes.UNSUBACK]}, 91 | 146: {"Packet identifier not found": 92 | [PacketTypes.PUBREL, PacketTypes.PUBCOMP]}, 93 | 147: {"Receive maximum exceeded": [PacketTypes.DISCONNECT]}, 94 | 148: {"Topic alias invalid": [PacketTypes.DISCONNECT]}, 95 | 149: {"Packet too large": [PacketTypes.CONNACK, PacketTypes.DISCONNECT]}, 96 | 150: {"Message rate too high": [PacketTypes.DISCONNECT]}, 97 | 151: {"Quota exceeded": [PacketTypes.CONNACK, PacketTypes.PUBACK, 98 | PacketTypes.PUBREC, PacketTypes.SUBACK, PacketTypes.DISCONNECT], }, 99 | 152: {"Administrative action": [PacketTypes.DISCONNECT]}, 100 | 153: {"Payload format invalid": 101 | [PacketTypes.PUBACK, PacketTypes.PUBREC, PacketTypes.DISCONNECT]}, 102 | 154: {"Retain not supported": 103 | [PacketTypes.CONNACK, PacketTypes.DISCONNECT]}, 104 | 155: {"QoS not supported": 105 | [PacketTypes.CONNACK, PacketTypes.DISCONNECT]}, 106 | 156: {"Use another server": 107 | [PacketTypes.CONNACK, PacketTypes.DISCONNECT]}, 108 | 157: {"Server moved": 109 | [PacketTypes.CONNACK, PacketTypes.DISCONNECT]}, 110 | 158: {"Shared subscription not supported": 111 | [PacketTypes.SUBACK, PacketTypes.DISCONNECT]}, 112 | 159: {"Connection rate exceeded": 113 | [PacketTypes.CONNACK, PacketTypes.DISCONNECT]}, 114 | 160: {"Maximum connect time": 115 | [PacketTypes.DISCONNECT]}, 116 | 161: {"Subscription identifiers not supported": 117 | [PacketTypes.SUBACK, PacketTypes.DISCONNECT]}, 118 | 162: {"Wildcard subscription not supported": 119 | [PacketTypes.SUBACK, PacketTypes.DISCONNECT]}, 120 | } 121 | if identifier == -1: 122 | if packetType == PacketTypes.DISCONNECT and aName == "Success": 123 | aName = "Normal disconnection" 124 | self.set(aName) 125 | else: 126 | self.value = identifier 127 | self.getName() # check it's good 128 | 129 | def __getName__(self, packetType, identifier): 130 | """ 131 | Get the reason code string name for a specific identifier. 132 | The name can vary by packet type for the same identifier, which 133 | is why the packet type is also required. 134 | 135 | Used when displaying the reason code. 136 | """ 137 | assert identifier in self.names.keys(), identifier 138 | names = self.names[identifier] 139 | namelist = [name for name in names.keys() if packetType in names[name]] 140 | assert len(namelist) == 1 141 | return namelist[0] 142 | 143 | def getId(self, name): 144 | """ 145 | Get the numeric id corresponding to a reason code name. 146 | 147 | Used when setting the reason code for a packetType 148 | check that only valid codes for the packet are set. 149 | """ 150 | identifier = None 151 | for code in self.names.keys(): 152 | if name in self.names[code].keys(): 153 | if self.packetType in self.names[code][name]: 154 | identifier = code 155 | break 156 | assert identifier != None, name 157 | return identifier 158 | 159 | def set(self, name): 160 | self.value = self.getId(name) 161 | 162 | def unpack(self, buffer): 163 | c = buffer[0] 164 | if sys.version_info[0] < 3: 165 | c = ord(c) 166 | name = self.__getName__(self.packetType, c) 167 | self.value = self.getId(name) 168 | return 1 169 | 170 | def getName(self): 171 | """Returns the reason code name corresponding to the numeric value which is set. 172 | """ 173 | return self.__getName__(self.packetType, self.value) 174 | 175 | def __eq__(self, other): 176 | if isinstance(other, int): 177 | return self.value == other 178 | if isinstance(other, str): 179 | return self.value == str(self) 180 | if isinstance(other, ReasonCodes): 181 | return self.value == other.value 182 | return False 183 | 184 | def __str__(self): 185 | return self.getName() 186 | 187 | def json(self): 188 | return self.getName() 189 | 190 | def pack(self): 191 | return bytearray([self.value]) -------------------------------------------------------------------------------- /paho/mqtt/publish.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2014 Roger Light 2 | # 3 | # All rights reserved. This program and the accompanying materials 4 | # are made available under the terms of the Eclipse Public License v1.0 5 | # and Eclipse Distribution License v1.0 which accompany this distribution. 6 | # 7 | # The Eclipse Public License is available at 8 | # http://www.eclipse.org/legal/epl-v10.html 9 | # and the Eclipse Distribution License is available at 10 | # http://www.eclipse.org/org/documents/edl-v10.php. 11 | # 12 | # Contributors: 13 | # Roger Light - initial API and implementation 14 | 15 | """ 16 | This module provides some helper functions to allow straightforward publishing 17 | of messages in a one-shot manner. In other words, they are useful for the 18 | situation where you have a single/multiple messages you want to publish to a 19 | broker, then disconnect and nothing else is required. 20 | """ 21 | from __future__ import absolute_import 22 | 23 | import collections 24 | try: 25 | from collections.abc import Iterable 26 | except ImportError: 27 | from collections import Iterable 28 | 29 | from . import client as paho 30 | from .. import mqtt 31 | 32 | def _do_publish(client): 33 | """Internal function""" 34 | 35 | message = client._userdata.popleft() 36 | 37 | if isinstance(message, dict): 38 | client.publish(**message) 39 | elif isinstance(message, (tuple, list)): 40 | client.publish(*message) 41 | else: 42 | raise TypeError('message must be a dict, tuple, or list') 43 | 44 | 45 | def _on_connect(client, userdata, flags, rc): 46 | """Internal callback""" 47 | #pylint: disable=invalid-name, unused-argument 48 | 49 | if rc == 0: 50 | if len(userdata) > 0: 51 | _do_publish(client) 52 | else: 53 | raise mqtt.MQTTException(paho.connack_string(rc)) 54 | 55 | 56 | def _on_publish(client, userdata, mid): 57 | """Internal callback""" 58 | #pylint: disable=unused-argument 59 | 60 | if len(userdata) == 0: 61 | client.disconnect() 62 | else: 63 | _do_publish(client) 64 | 65 | 66 | def multiple(msgs, hostname="localhost", port=1883, client_id="", keepalive=60, 67 | will=None, auth=None, tls=None, protocol=paho.MQTTv311, 68 | transport="tcp", proxy_args=None): 69 | """Publish multiple messages to a broker, then disconnect cleanly. 70 | 71 | This function creates an MQTT client, connects to a broker and publishes a 72 | list of messages. Once the messages have been delivered, it disconnects 73 | cleanly from the broker. 74 | 75 | msgs : a list of messages to publish. Each message is either a dict or a 76 | tuple. 77 | 78 | If a dict, only the topic must be present. Default values will be 79 | used for any missing arguments. The dict must be of the form: 80 | 81 | msg = {'topic':"", 'payload':"", 'qos':, 82 | 'retain':} 83 | topic must be present and may not be empty. 84 | If payload is "", None or not present then a zero length payload 85 | will be published. 86 | If qos is not present, the default of 0 is used. 87 | If retain is not present, the default of False is used. 88 | 89 | If a tuple, then it must be of the form: 90 | ("", "", qos, retain) 91 | 92 | hostname : a string containing the address of the broker to connect to. 93 | Defaults to localhost. 94 | 95 | port : the port to connect to the broker on. Defaults to 1883. 96 | 97 | client_id : the MQTT client id to use. If "" or None, the Paho library will 98 | generate a client id automatically. 99 | 100 | keepalive : the keepalive timeout value for the client. Defaults to 60 101 | seconds. 102 | 103 | will : a dict containing will parameters for the client: will = {'topic': 104 | "", 'payload':", 'qos':, 'retain':}. 105 | Topic is required, all other parameters are optional and will 106 | default to None, 0 and False respectively. 107 | Defaults to None, which indicates no will should be used. 108 | 109 | auth : a dict containing authentication parameters for the client: 110 | auth = {'username':"", 'password':""} 111 | Username is required, password is optional and will default to None 112 | if not provided. 113 | Defaults to None, which indicates no authentication is to be used. 114 | 115 | tls : a dict containing TLS configuration parameters for the client: 116 | dict = {'ca_certs':"", 'certfile':"", 117 | 'keyfile':"", 'tls_version':"", 118 | 'ciphers':", 'insecure':""} 119 | ca_certs is required, all other parameters are optional and will 120 | default to None if not provided, which results in the client using 121 | the default behaviour - see the paho.mqtt.client documentation. 122 | Alternatively, tls input can be an SSLContext object, which will be 123 | processed using the tls_set_context method. 124 | Defaults to None, which indicates that TLS should not be used. 125 | 126 | transport : set to "tcp" to use the default setting of transport which is 127 | raw TCP. Set to "websockets" to use WebSockets as the transport. 128 | proxy_args: a dictionary that will be given to the client. 129 | """ 130 | 131 | if not isinstance(msgs, Iterable): 132 | raise TypeError('msgs must be an iterable') 133 | 134 | client = paho.Client(client_id=client_id, userdata=collections.deque(msgs), 135 | protocol=protocol, transport=transport) 136 | 137 | client.on_publish = _on_publish 138 | client.on_connect = _on_connect 139 | 140 | if proxy_args is not None: 141 | client.proxy_set(**proxy_args) 142 | 143 | if auth: 144 | username = auth.get('username') 145 | if username: 146 | password = auth.get('password') 147 | client.username_pw_set(username, password) 148 | else: 149 | raise KeyError("The 'username' key was not found, this is " 150 | "required for auth") 151 | 152 | if will is not None: 153 | client.will_set(**will) 154 | 155 | if tls is not None: 156 | if isinstance(tls, dict): 157 | insecure = tls.pop('insecure', False) 158 | client.tls_set(**tls) 159 | if insecure: 160 | # Must be set *after* the `client.tls_set()` call since it sets 161 | # up the SSL context that `client.tls_insecure_set` alters. 162 | client.tls_insecure_set(insecure) 163 | else: 164 | # Assume input is SSLContext object 165 | client.tls_set_context(tls) 166 | 167 | client.connect(hostname, port, keepalive) 168 | client.loop_forever() 169 | 170 | 171 | def single(topic, payload=None, qos=0, retain=False, hostname="localhost", 172 | port=1883, client_id="", keepalive=60, will=None, auth=None, 173 | tls=None, protocol=paho.MQTTv311, transport="tcp", proxy_args=None): 174 | """Publish a single message to a broker, then disconnect cleanly. 175 | 176 | This function creates an MQTT client, connects to a broker and publishes a 177 | single message. Once the message has been delivered, it disconnects cleanly 178 | from the broker. 179 | 180 | topic : the only required argument must be the topic string to which the 181 | payload will be published. 182 | 183 | payload : the payload to be published. If "" or None, a zero length payload 184 | will be published. 185 | 186 | qos : the qos to use when publishing, default to 0. 187 | 188 | retain : set the message to be retained (True) or not (False). 189 | 190 | hostname : a string containing the address of the broker to connect to. 191 | Defaults to localhost. 192 | 193 | port : the port to connect to the broker on. Defaults to 1883. 194 | 195 | client_id : the MQTT client id to use. If "" or None, the Paho library will 196 | generate a client id automatically. 197 | 198 | keepalive : the keepalive timeout value for the client. Defaults to 60 199 | seconds. 200 | 201 | will : a dict containing will parameters for the client: will = {'topic': 202 | "", 'payload':", 'qos':, 'retain':}. 203 | Topic is required, all other parameters are optional and will 204 | default to None, 0 and False respectively. 205 | Defaults to None, which indicates no will should be used. 206 | 207 | auth : a dict containing authentication parameters for the client: 208 | auth = {'username':"", 'password':""} 209 | Username is required, password is optional and will default to None 210 | if not provided. 211 | Defaults to None, which indicates no authentication is to be used. 212 | 213 | tls : a dict containing TLS configuration parameters for the client: 214 | dict = {'ca_certs':"", 'certfile':"", 215 | 'keyfile':"", 'tls_version':"", 216 | 'ciphers':", 'insecure':""} 217 | ca_certs is required, all other parameters are optional and will 218 | default to None if not provided, which results in the client using 219 | the default behaviour - see the paho.mqtt.client documentation. 220 | Defaults to None, which indicates that TLS should not be used. 221 | Alternatively, tls input can be an SSLContext object, which will be 222 | processed using the tls_set_context method. 223 | 224 | transport : set to "tcp" to use the default setting of transport which is 225 | raw TCP. Set to "websockets" to use WebSockets as the transport. 226 | proxy_args: a dictionary that will be given to the client. 227 | """ 228 | 229 | msg = {'topic':topic, 'payload':payload, 'qos':qos, 'retain':retain} 230 | 231 | multiple([msg], hostname, port, client_id, keepalive, will, auth, tls, 232 | protocol, transport, proxy_args) 233 | -------------------------------------------------------------------------------- /paho/mqtt/subscribe.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2016 Roger Light 2 | # 3 | # All rights reserved. This program and the accompanying materials 4 | # are made available under the terms of the Eclipse Public License v1.0 5 | # and Eclipse Distribution License v1.0 which accompany this distribution. 6 | # 7 | # The Eclipse Public License is available at 8 | # http://www.eclipse.org/legal/epl-v10.html 9 | # and the Eclipse Distribution License is available at 10 | # http://www.eclipse.org/org/documents/edl-v10.php. 11 | # 12 | # Contributors: 13 | # Roger Light - initial API and implementation 14 | 15 | """ 16 | This module provides some helper functions to allow straightforward subscribing 17 | to topics and retrieving messages. The two functions are simple(), which 18 | returns one or messages matching a set of topics, and callback() which allows 19 | you to pass a callback for processing of messages. 20 | """ 21 | from __future__ import absolute_import 22 | 23 | from . import client as paho 24 | from .. import mqtt 25 | 26 | def _on_connect(client, userdata, flags, rc): 27 | """Internal callback""" 28 | if rc != 0: 29 | raise mqtt.MQTTException(paho.connack_string(rc)) 30 | 31 | if isinstance(userdata['topics'], list): 32 | for topic in userdata['topics']: 33 | client.subscribe(topic, userdata['qos']) 34 | else: 35 | client.subscribe(userdata['topics'], userdata['qos']) 36 | 37 | 38 | def _on_message_callback(client, userdata, message): 39 | """Internal callback""" 40 | userdata['callback'](client, userdata['userdata'], message) 41 | 42 | 43 | def _on_message_simple(client, userdata, message): 44 | """Internal callback""" 45 | 46 | if userdata['msg_count'] == 0: 47 | return 48 | 49 | # Don't process stale retained messages if 'retained' was false 50 | if message.retain and not userdata['retained']: 51 | return 52 | 53 | userdata['msg_count'] = userdata['msg_count'] - 1 54 | 55 | if userdata['messages'] is None and userdata['msg_count'] == 0: 56 | userdata['messages'] = message 57 | client.disconnect() 58 | return 59 | 60 | userdata['messages'].append(message) 61 | if userdata['msg_count'] == 0: 62 | client.disconnect() 63 | 64 | 65 | def callback(callback, topics, qos=0, userdata=None, hostname="localhost", 66 | port=1883, client_id="", keepalive=60, will=None, auth=None, 67 | tls=None, protocol=paho.MQTTv311, transport="tcp", 68 | clean_session=True, proxy_args=None): 69 | """Subscribe to a list of topics and process them in a callback function. 70 | 71 | This function creates an MQTT client, connects to a broker and subscribes 72 | to a list of topics. Incoming messages are processed by the user provided 73 | callback. This is a blocking function and will never return. 74 | 75 | callback : function of the form "on_message(client, userdata, message)" for 76 | processing the messages received. 77 | 78 | topics : either a string containing a single topic to subscribe to, or a 79 | list of topics to subscribe to. 80 | 81 | qos : the qos to use when subscribing. This is applied to all topics. 82 | 83 | userdata : passed to the callback 84 | 85 | hostname : a string containing the address of the broker to connect to. 86 | Defaults to localhost. 87 | 88 | port : the port to connect to the broker on. Defaults to 1883. 89 | 90 | client_id : the MQTT client id to use. If "" or None, the Paho library will 91 | generate a client id automatically. 92 | 93 | keepalive : the keepalive timeout value for the client. Defaults to 60 94 | seconds. 95 | 96 | will : a dict containing will parameters for the client: will = {'topic': 97 | "", 'payload':", 'qos':, 'retain':}. 98 | Topic is required, all other parameters are optional and will 99 | default to None, 0 and False respectively. 100 | Defaults to None, which indicates no will should be used. 101 | 102 | auth : a dict containing authentication parameters for the client: 103 | auth = {'username':"", 'password':""} 104 | Username is required, password is optional and will default to None 105 | if not provided. 106 | Defaults to None, which indicates no authentication is to be used. 107 | 108 | tls : a dict containing TLS configuration parameters for the client: 109 | dict = {'ca_certs':"", 'certfile':"", 110 | 'keyfile':"", 'tls_version':"", 111 | 'ciphers':", 'insecure':""} 112 | ca_certs is required, all other parameters are optional and will 113 | default to None if not provided, which results in the client using 114 | the default behaviour - see the paho.mqtt.client documentation. 115 | Alternatively, tls input can be an SSLContext object, which will be 116 | processed using the tls_set_context method. 117 | Defaults to None, which indicates that TLS should not be used. 118 | 119 | transport : set to "tcp" to use the default setting of transport which is 120 | raw TCP. Set to "websockets" to use WebSockets as the transport. 121 | 122 | clean_session : a boolean that determines the client type. If True, 123 | the broker will remove all information about this client 124 | when it disconnects. If False, the client is a persistent 125 | client and subscription information and queued messages 126 | will be retained when the client disconnects. 127 | Defaults to True. 128 | 129 | proxy_args: a dictionary that will be given to the client. 130 | """ 131 | 132 | if qos < 0 or qos > 2: 133 | raise ValueError('qos must be in the range 0-2') 134 | 135 | callback_userdata = { 136 | 'callback':callback, 137 | 'topics':topics, 138 | 'qos':qos, 139 | 'userdata':userdata} 140 | 141 | client = paho.Client(client_id=client_id, userdata=callback_userdata, 142 | protocol=protocol, transport=transport, 143 | clean_session=clean_session) 144 | client.on_message = _on_message_callback 145 | client.on_connect = _on_connect 146 | 147 | if proxy_args is not None: 148 | client.proxy_set(**proxy_args) 149 | 150 | if auth: 151 | username = auth.get('username') 152 | if username: 153 | password = auth.get('password') 154 | client.username_pw_set(username, password) 155 | else: 156 | raise KeyError("The 'username' key was not found, this is " 157 | "required for auth") 158 | 159 | if will is not None: 160 | client.will_set(**will) 161 | 162 | if tls is not None: 163 | if isinstance(tls, dict): 164 | insecure = tls.pop('insecure', False) 165 | client.tls_set(**tls) 166 | if insecure: 167 | # Must be set *after* the `client.tls_set()` call since it sets 168 | # up the SSL context that `client.tls_insecure_set` alters. 169 | client.tls_insecure_set(insecure) 170 | else: 171 | # Assume input is SSLContext object 172 | client.tls_set_context(tls) 173 | 174 | client.connect(hostname, port, keepalive) 175 | client.loop_forever() 176 | 177 | 178 | def simple(topics, qos=0, msg_count=1, retained=True, hostname="localhost", 179 | port=1883, client_id="", keepalive=60, will=None, auth=None, 180 | tls=None, protocol=paho.MQTTv311, transport="tcp", 181 | clean_session=True, proxy_args=None): 182 | """Subscribe to a list of topics and return msg_count messages. 183 | 184 | This function creates an MQTT client, connects to a broker and subscribes 185 | to a list of topics. Once "msg_count" messages have been received, it 186 | disconnects cleanly from the broker and returns the messages. 187 | 188 | topics : either a string containing a single topic to subscribe to, or a 189 | list of topics to subscribe to. 190 | 191 | qos : the qos to use when subscribing. This is applied to all topics. 192 | 193 | msg_count : the number of messages to retrieve from the broker. 194 | if msg_count == 1 then a single MQTTMessage will be returned. 195 | if msg_count > 1 then a list of MQTTMessages will be returned. 196 | 197 | retained : If set to True, retained messages will be processed the same as 198 | non-retained messages. If set to False, retained messages will 199 | be ignored. This means that with retained=False and msg_count=1, 200 | the function will return the first message received that does 201 | not have the retained flag set. 202 | 203 | hostname : a string containing the address of the broker to connect to. 204 | Defaults to localhost. 205 | 206 | port : the port to connect to the broker on. Defaults to 1883. 207 | 208 | client_id : the MQTT client id to use. If "" or None, the Paho library will 209 | generate a client id automatically. 210 | 211 | keepalive : the keepalive timeout value for the client. Defaults to 60 212 | seconds. 213 | 214 | will : a dict containing will parameters for the client: will = {'topic': 215 | "", 'payload':", 'qos':, 'retain':}. 216 | Topic is required, all other parameters are optional and will 217 | default to None, 0 and False respectively. 218 | Defaults to None, which indicates no will should be used. 219 | 220 | auth : a dict containing authentication parameters for the client: 221 | auth = {'username':"", 'password':""} 222 | Username is required, password is optional and will default to None 223 | if not provided. 224 | Defaults to None, which indicates no authentication is to be used. 225 | 226 | tls : a dict containing TLS configuration parameters for the client: 227 | dict = {'ca_certs':"", 'certfile':"", 228 | 'keyfile':"", 'tls_version':"", 229 | 'ciphers':", 'insecure':""} 230 | ca_certs is required, all other parameters are optional and will 231 | default to None if not provided, which results in the client using 232 | the default behaviour - see the paho.mqtt.client documentation. 233 | Alternatively, tls input can be an SSLContext object, which will be 234 | processed using the tls_set_context method. 235 | Defaults to None, which indicates that TLS should not be used. 236 | 237 | transport : set to "tcp" to use the default setting of transport which is 238 | raw TCP. Set to "websockets" to use WebSockets as the transport. 239 | 240 | clean_session : a boolean that determines the client type. If True, 241 | the broker will remove all information about this client 242 | when it disconnects. If False, the client is a persistent 243 | client and subscription information and queued messages 244 | will be retained when the client disconnects. 245 | Defaults to True. 246 | 247 | proxy_args: a dictionary that will be given to the client. 248 | """ 249 | 250 | if msg_count < 1: 251 | raise ValueError('msg_count must be > 0') 252 | 253 | # Set ourselves up to return a single message if msg_count == 1, or a list 254 | # if > 1. 255 | if msg_count == 1: 256 | messages = None 257 | else: 258 | messages = [] 259 | 260 | userdata = {'retained':retained, 'msg_count':msg_count, 'messages':messages} 261 | 262 | callback(_on_message_simple, topics, qos, userdata, hostname, port, 263 | client_id, keepalive, will, auth, tls, protocol, transport, 264 | clean_session, proxy_args) 265 | 266 | return userdata['messages'] 267 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # EDMC-Telemetry 2 | 3 | Written by [Edward Wright](https://github.com/fasteddy516) for use with the [Elite: Dangerous Market Connector](https://github.com/EDCD/EDMarketConnector) (EDMC) by Jonathan Harris and the [Elite Dangerous Community Developers](https://github.com/EDCD). 4 | 5 | 6 | ## Description 7 | 8 | This plugin takes the dashboard status and/or player journal updates from Elite: Dangerous as ingested by EDMC and distributes them via the [MQTT connectivity protocol](http://mqtt.org/). Its primary use case is to provide in-game status and feedback to custom cockpits and controls. 9 | 10 | Want to build a custom flight stick and throttle with led feedback that accurately reflects the state of your hardpoints, landing gear, and cargo scoop? How about a set of backlit controls that all change colour when you toggle between combat and analysis cockpit modes? Maybe just a little LCD display that shows you how many jumps are left on your current route? EDMC-Telemetry can provide the necessary status to drive this feedback through MQTT. 11 | 12 | If you're interested in building your own controls, there are MQTT client libraries available for [just about every major programming language and platform](https://mqtt.org/software/). Of particular interest are the [Arduino Client](https://www.arduino.cc/reference/en/libraries/pubsubclient/), [CircuitPython Client](https://github.com/adafruit/Adafruit_CircuitPython_MiniMQTT/), Raspberry Pi via [Python Client](https://github.com/eclipse/paho.mqtt.python), and even [Node-Red](https://cookbook.nodered.org/mqtt/connect-to-broker). 13 | 14 | _For a detailed list of the status and events that are available, please see the [Elite Dangerous Player Journal](https://elite-journal.readthedocs.io/en/latest/File%20Format/) documentation._ 15 | 16 | 17 | ## Prerequisites 18 | 19 | * First and foremost, this plugin requires EDMC. 20 | 21 | **_As of version 0.3.0, EDMC version 5.0.0 or higher is required._** 22 | 23 | * The plugin needs somewhere to send the data, which means a correctly installed and configured MQTT broker is required. I personally use - and develop EDMC-Telemetry using - the [Eclipse Mosquitto™](https://mosquitto.org/) broker installed on a [Raspberry Pi](http://raspberrypi.org) 24 | 25 | 26 | ## Limitations 27 | 28 | EDMC-Telemetry publishes messages using MQTT v3.1.1 through raw TCP. WebSockets connections are not supported. 29 | 30 | 31 | ## Installation 32 | 33 | * On EDMC's `Plugins` settings tab press the `Open` button. This reveals the `plugins` folder where EDMC looks for plugins. 34 | * Download the [latest release](https://github.com/fasteddy516/EDMC-Telemetry/releases/latest) of this plugin. 35 | * Open the `.zip` archive that you downloaded and move the `Telemetry` folder contained inside into the `plugins` folder. 36 | 37 | _You will need to re-start EDMC for it to notice the new plugin._ 38 | 39 | 40 | ## Configuration 41 | 42 | After installing the plugin, it can be configured using the "Telemetry" tab in EDMC's "settings" dialog. The following options are available in two separate sub-tabs, *Connection* and *Data*: 43 | 44 | ### Connection Tab: 45 | 46 | **[Required Settings]** 47 | 48 | * **Broker Address**: IP Address / hostname of MQTT broker. _(default=127.0.0.1)_ 49 | 50 | * **Port**: TCP/IP port used by MQTT broker _(default=1883)_ 51 | 52 | * **QoS**: MQTT QoS setting _(0=at most once, 1=at least once, 2=exactly once, default=0)_ 53 | 54 | * **Keepalive**: MQTT keepalive in seconds _(default=60)_ 55 | 56 | * **Client ID**: MQTT client ID used when connecting to the broker. If you have multiple instances of EDMC-Telemetry connecting to the same broker, this value will have to be unique for each instance. _(default=EDMCTelemetryClient)_ 57 | 58 | **[Authentication]** 59 | 60 | * **Username**: Username for authentication with MQTT broker. _(leave blank if not required)_ 61 | 62 | * **Password**: Password for authentication with MQTT broker. _(leave blank if not required)_ 63 | 64 | **[Encryption]** 65 | 66 | * **Encrypted Connection**: Enable this option to use SSL/TLS encryption for the connection to the MQTT broker. _Enabling this option likely requires the port setting to be changed - 8883 is the standard for encrypted MQTT connections, but your broker may be configured differently._ 67 | 68 | * **Skip Certificate Verification**: Enable this option to disable verification of the server hostname in the server certificate. This can be useful for testing, and when using a dedicated broker on your local network, but it makes using encryption virtually pointless, as it makes it impossible to guarantee that the broker you are connecting to is not a malicious 3rd party device impersonating your actual broker. **_This option should absolutely not be used for connections to brokers outside of your own local network._** 69 | 70 | * **Server Certificate (CA)**: The absolute (full) path to the Certificate Authority certificate file for the server (broker). If your broker certificate is signed by a CA that is already trusted by your Operating System (i.e. Let's Encrypt, Verisign, etc.) then you should be able to leave this blank. 71 | 72 | * **Client Certificate**: The absolute (full) path to the PEM encoded client certificate. _Only required if using TLS-based authentication._ 73 | 74 | * **Client Key**: The absolute (full) path to the PEM encoded client private key. _Only required if using TLS-based authentication._ 75 | 76 | ### Data Tab: 77 | 78 | * **Root Topic**: Root topic for all MQTT messages from EDMC-Telemetry. You can include multiple topic levels here, so something like `Telemetry/CMDR1` is valid if needed. _(default=Telemetry)_ 79 | 80 | * **Convert all topics to lowercase**: If you don't like capital letters in your MQTT topics, enable this option. _(default=unchecked)_ 81 | 82 | * **Publish Dashboard**: 83 | 84 | Use the checkbox to enable/disable publishing of [dashboard](https://elite-journal.readthedocs.io/en/latest/Status%20File/) status and events. The associated drop-down menu allows selection of `Raw` or `Processed` telemetry streams. 85 | 86 | In `Raw` mode the JSON data received from the game will be published as-is to the `Telemetry/Dashboard` topic. 87 | 88 | In `Processed` mode the data is broken down and published into specific topics, i.e. `Telemetry/Dashboard/FireGroup`, `Telemetry/Dashboard/GuiFocus`, `Telemetry/Dashboard/Flags` and so on. `Pips` information is further broken down into `Telemetry/Dashboard/Pips/Eng`, `Wep` and `Sys`. `Fuel` shows up as `Telemetry/Dashboard/Fuel/Main` and `Reservoir`. Note that all dashboard topics are only published when their associated data changes. 89 | 90 | _(default=checked, Processed)_ 91 | 92 | * **Publish Journal**: 93 | 94 | Use the checkbox to enable/disable publishing of [journal](https://elite-journal.readthedocs.io/en/latest/) events. The associated drop-down menu allows selection of `Raw` or `Processed` telemetry streams. 95 | 96 | In `Raw` mode, the JSON data received from the game will be published as-is to the `Telemetry/Journal` topic. 97 | 98 | In `Processed` mode, data from journal entries is published to individual topics based on the `Event` key in each entry's JSON data, i.e. `Telemetry/Journal/Docked`, `Telemetry/Journal/FSDJump`, and so on. 99 | 100 | _(default=checked, Processed)_ 101 | 102 | * **Publish Current System/Station**: Use the checkbox to enable/disable publishing of EDMC's internally-tracked current system and station. These will be published to `Telemetry/Location/System` and `Telemetry/Location/Station`. _(default=checked)_ 103 | 104 | * **Publish EDMC State Tracking**: Use the checkbox to enable/disable publishing of EDMC's internal `state` to `Telemetry/Location/State`. **Note that this generates an almost continuous stream of very large MQTT messages which may bog down your MQTT setup - enabling this option is generally unnecessary and not recommended.** _(default=unchecked)_ 105 | 106 | 107 | ## Telemetry Status Topics 108 | 109 | Two topics are provided by EDMC-Telemetry to help determine the current state of the telemetry plugin as well as the Elite Dangerous game state. 110 | 111 | * **Telemetry/FeedActive**: `True` when the MQTT connection to the broker is active, `False` otherwise. This topic is published with the `retain` flag set to True, and is also specified as the _Last Will and Testament_ for the MQTT client, so it should always be available on the broker and reflect the state of the connection. 112 | 113 | * **Telemetry/GameRunning**: `True` when EDMC believes Elite Dangerous is running, `False` otherwise. 114 | 115 | 116 | ## Custom MQTT Topics 117 | 118 | All of EDMC-Telemetry's configuration settings are stored in the `settings.json` file located in the same folder as the plugin. (This file gets generated with default settings the first time you run EDMC after installing the plugin.) If you want to customize the MQTT topics that EDMC-Telemetry publishes to, you can do so by editing this file. 119 | 120 | The default configuration looks like this: 121 | 122 | ```json 123 | { 124 | "version": "0.4.0", 125 | "broker": "127.0.0.1", 126 | "port": 1883, 127 | "keepalive": 60, 128 | "qos": 0, 129 | "username": "", 130 | "password": "", 131 | "client_id": "EDMCTelemetryPlugin", 132 | "encryption": false, 133 | "ca_certs": "", 134 | "certfile": "", 135 | "keyfile": "", 136 | "tls_insecure": false, 137 | "dashboard": true, 138 | "dashboard_format": "Processed", 139 | "journal": true, 140 | "journal_format": "Processed", 141 | "location": true, 142 | "state": false, 143 | "lowercase_topics": false, 144 | "topics": { 145 | "root": "Telemetry", 146 | "gamerunning": "GameRunning", 147 | "feedactive": "FeedActive", 148 | "dashboard": "Dashboard", 149 | "journal": "Journal", 150 | "location": "Location", 151 | "state": "State", 152 | "system": "System", 153 | "station": "Station", 154 | "pips": "Pips", 155 | "sys": "Sys", 156 | "eng": "Eng", 157 | "wep": "Wep", 158 | "fuel": "Fuel", 159 | "fuelreservoir": "Reservoir", 160 | "fuelmain": "Main" 161 | } 162 | } 163 | ``` 164 | 165 | MQTT topics can be modified by changing the corresponding entry in the `topics` section. If you wanted to shorten the `Dashboard` topic, you could do so by modifying the corresponding line in the file to `"dashboard": "db",`, which would result in all dashboard topics being published to `Telemetry/db`. You can freely adjust the topics in the default configuration file, just make sure that you: 166 | 167 | * Only modify the *value* for the desired topic. (i.e. the part **after** the colon!) 168 | 169 | * Don't remove any of the lines that exist in the default configuration - the plugin needs these, and will crash without them. 170 | 171 | * Avoid doing silly things like specifying the same topic for multiple items. This will technically work, but likely won't be very useful. 172 | 173 | * Remember to restart EDMC after making any changes. The JSON configuration is only loaded once, when EDMC starts. 174 | 175 | * Don't mess with the other (not topic-related) settings. Everything else is configurable via the EDMC settings UI, and modifying them here to values that the plugin isn't expecting will just prevent it from running. 176 | 177 | _If you happen to mess up the configuration file and can't figure out how to fix it, just delete or rename it. A new, default file will be generated the next time you start EDMC._ 178 | 179 | In addition to the default topics that are created, you can add any other topic you like here in the same `"original_topic": "desired_topic",` format, and EDMC-Telemetry will replace any instance of `original_topic` with `desired_topic`. If you want to use a custom topic for journal `FighterDestroyed` events, you could add a line like `"fighterdestroyed": "BigBadaBoom",`, and all of those events will get published to `Telemetry/Journal/BigBadaBoom`. (assuming, of course, that you haven't also messed with your `root` and `journal` topics.) 180 | 181 | Note that topic replacement lookups are not case-sensitive. In the previous example, anything coming from the game as `FighterDestroyed`, `FIGHTERdestroyed`, `FiGhTeRdEsTrOyEd`, and similar would all get published to `BigBadaBoom`. In order for your topics to get replaced correctly, make sure that the `original_topic` part of the line is all lowercase, regardless of how the journal documentation describes the event. Incoming topics all get converted to lowercase before comparing them to items in this replacement list. 182 | 183 | 184 | ## Comments and Suggestions 185 | 186 | I welcome any comments, suggestions, or criticism (of the constructive nature) that will allow me to improve this plugin. 187 | 188 | 189 | ## License 190 | 191 | Copyright © 2021 Edward Wright. 192 | 193 | Licensed under the [GNU Public License (GPL)](http://www.gnu.org/licenses/gpl-3.0.html) version 3. -------------------------------------------------------------------------------- /load.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """Telemetry: An EDMC Plugin to relay dashboard status and journal entries via MQTT.""" 3 | 4 | # Written by Edward Wright (https://github.com/fasteddy516) 5 | # Available at https://github.com/fasteddy516/EDMC-Telemetry 6 | # 7 | # Requires Elite Dangerous Market Connector: https://github.com/EDCD/EDMarketConnector 8 | # Uses the Eclipse Paho MQTT Python Client (https://github.com/eclipse/paho.mqtt.python) 9 | # for all MQTT protocol (http://mqtt.org/) interactions. 10 | 11 | import json 12 | import logging 13 | import os 14 | import time 15 | import tkinter as tk 16 | from typing import Any, Dict, Optional, Tuple 17 | 18 | import myNotebook as nb # type: ignore (provided by EDMC) 19 | import semantic_version # type: ignore (provided by EDMC) 20 | from config import appname, appversion, config # type: ignore (provided by EDMC) 21 | from monitor import monitor # type: ignore (provided by EDMC) 22 | 23 | import paho.mqtt.client as mqtt_client 24 | from settings import Settings 25 | 26 | # plugin constants 27 | TELEMETRY_VERSION = "0.5.0" 28 | TELEMETRY_PIPS = ("sys", "eng", "wep") 29 | GAME_STATE_EVENTS = ("startup", "loadgame", "shutdown") 30 | 31 | 32 | # set up logging 33 | logger = logging.getLogger(f"{appname}.{os.path.basename(os.path.dirname(__file__))}") 34 | 35 | 36 | # Globals 37 | class Globals: 38 | """Holds module globals.""" 39 | 40 | def __init__(self): 41 | """Create and initialize module globals.""" 42 | self.status: Optional[tk.Label] = None 43 | self.status_message: str = "Initializing" 44 | self.status_color: str = "grey" 45 | self.modifying_preferences = False 46 | self.mqtt_connected: bool = False 47 | self.current_db = {} 48 | self.current_location = {"system": "N/A", "station": "N/A"} 49 | self.current_state = {} 50 | self.settings = Settings(TELEMETRY_VERSION, logger) 51 | self.mqtt = mqtt_client.Client() 52 | 53 | 54 | this = Globals() 55 | 56 | 57 | # Standard EDMC plugin functions 58 | def plugin_start3(plugin_dir: str) -> str: 59 | """Start the telemetry plugin.""" 60 | if callable(appversion) and appversion() >= semantic_version.Version("5.0.0"): 61 | connect_telemetry() 62 | else: 63 | logger.fatal("EDMC-Telemetry requires EDMC 5.0.0 or newer.") 64 | status_message(message="ERROR: EDMC < 5.0.0", color="red", immediate=True) 65 | return "Telemetry" 66 | 67 | 68 | def plugin_stop() -> None: 69 | """Stop the telemetry plugin.""" 70 | disconnect_telemetry() 71 | 72 | 73 | def plugin_app(parent: tk.Frame) -> Tuple[tk.Label, tk.Label]: 74 | """Show broker connection status on main UI.""" 75 | label = tk.Label(parent, text="Telemetry:") 76 | this.status = tk.Label(parent, anchor=tk.W, text="Initializing", foreground="grey") 77 | this.status.bind_all("<>", _update_status) 78 | status_message(immediate=True) 79 | return (label, this.status) 80 | 81 | 82 | def plugin_prefs(parent: nb.Notebook, cmdr: str, is_beta: bool) -> Optional[tk.Frame]: 83 | """Allow configuration to be modified from UI.""" 84 | this.modifying_preferences = True 85 | return this.settings.show_preferences(parent) 86 | 87 | 88 | def prefs_changed(cmdr: str, is_beta: bool) -> None: 89 | """Update settings after they've been modified in UI.""" 90 | # update_preferences() returns True if a connection reset is required 91 | if this.settings.update_preferences(): 92 | logger.info("MQTT broker settings modified, connection will now restart.") 93 | disconnect_telemetry() 94 | connect_telemetry() 95 | this.modifying_preferences = False 96 | status_message(immediate=True) 97 | 98 | 99 | def status_message(message: str = "", color: str = "", immediate=False) -> None: 100 | """Update the status message and color to be displayed on the main UI.""" 101 | if len(message): 102 | this.status_message = message 103 | if len(color): 104 | this.status_color = color 105 | if immediate: 106 | _update_status() 107 | else: 108 | if ( 109 | this.status is not None 110 | and not config.shutting_down 111 | and not this.modifying_preferences 112 | ): 113 | this.status.event_generate("<>", when="tail") 114 | 115 | 116 | def _update_status(event=None) -> None: 117 | """Post the status message to the main UI.""" 118 | if this.status is not None: 119 | this.status["text"] = this.status_message 120 | this.status["foreground"] = this.status_color 121 | 122 | 123 | def publish(topic: str, payload: str, retain: bool = False): 124 | """Publish the specified payload to the specified MQTT topic.""" 125 | topic = f"{this.settings.topic('root')}/{topic}" 126 | if this.settings.lowercase_topics: 127 | topic = topic.lower() 128 | this.mqtt.publish(topic, payload=payload, qos=this.settings.qos, retain=retain) 129 | 130 | 131 | # --- New helper function for Flags/Flags2 --- 132 | def publish_flags(base_topic: str, value: int, flag_map: Dict[int, str]): 133 | """Publish individual bits as separate MQTT topics.""" 134 | for bit, name in flag_map.items(): 135 | bit_set = 1 if (value & bit) else 0 136 | publish(f"{base_topic}/{name}", str(bit_set)) 137 | 138 | 139 | # Flag mappings 140 | FLAGS_MAP = { 141 | 1 << 0: "Docked", 142 | 1 << 1: "Landed", 143 | 1 << 2: "LandingGearDown", 144 | 1 << 3: "ShieldsUp", 145 | 1 << 4: "Supercruise", 146 | 1 << 5: "FlightAssistOff", 147 | 1 << 6: "HardpointsDeployed", 148 | 1 << 7: "InWing", 149 | 1 << 8: "LightsOn", 150 | 1 << 9: "CargoScoopDeployed", 151 | 1 << 10: "SilentRunning", 152 | 1 << 11: "ScoopingFuel", 153 | 1 << 12: "SrvHandbrake", 154 | 1 << 13: "SrvUsingTurretView", 155 | 1 << 14: "SrvTurretRetracted", 156 | 1 << 15: "SrvDriveAssist", 157 | 1 << 16: "FsdMassLocked", 158 | 1 << 17: "FsdCharging", 159 | 1 << 18: "FsdCooldown", 160 | 1 << 19: "LowFuel", 161 | 1 << 20: "OverHeating", 162 | 1 << 21: "HasLatLong", 163 | 1 << 22: "IsInDanger", 164 | 1 << 23: "BeingInterdicted", 165 | 1 << 24: "InMainShip", 166 | 1 << 25: "InFighter", 167 | 1 << 26: "InSRV", 168 | 1 << 27: "HudInAnalysisMode", 169 | 1 << 28: "NightVision", 170 | 1 << 29: "AltitudeFromAverageRadius", 171 | 1 << 30: "FsdJump", 172 | 1 << 31: "SrvHighBeam", 173 | } 174 | 175 | FLAGS2_MAP = { 176 | 1 << 0: "OnFoot", 177 | 1 << 1: "InTaxi", 178 | 1 << 2: "InMulticrew", 179 | 1 << 3: "OnFootInStation", 180 | 1 << 4: "OnFootOnPlanet", 181 | 1 << 5: "AimDownSight", 182 | 1 << 6: "LowOxygen", 183 | 1 << 7: "LowHealth", 184 | 1 << 8: "Cold", 185 | 1 << 9: "Hot", 186 | 1 << 10: "VeryCold", 187 | 1 << 11: "VeryHot", 188 | 1 << 12: "GlideMode", 189 | 1 << 13: "OnFootInHangar", 190 | 1 << 14: "OnFootSocialSpace", 191 | 1 << 15: "OnFootExterior", 192 | 1 << 16: "BreathableAtmosphere", 193 | 1 << 17: "TelepresenceMulticrew", 194 | 1 << 18: "PhysicalMulticrew", 195 | 1 << 19: "FsdHyperdriveCharging", 196 | } 197 | 198 | 199 | def dashboard_entry(cmdr: str, is_beta: bool, entry: Dict[str, Any]) -> None: 200 | """Publish dashboard status via MQTT.""" 201 | if not this.settings.dashboard: 202 | return 203 | 204 | if not this.mqtt_connected: 205 | return 206 | 207 | dashboard_topic = this.settings.topic("dashboard") 208 | 209 | if this.settings.dashboard_format == "Raw": 210 | publish(dashboard_topic, payload=json.dumps(entry)) 211 | else: 212 | for key in entry: 213 | # always ignore these keys 214 | if key.lower() == "timestamp" or key.lower() == "event": 215 | continue 216 | 217 | # publish any updated dashboard data 218 | if key not in this.current_db or this.current_db[key] != entry[key]: 219 | topic = f"{dashboard_topic}/{this.settings.topic(key)}" 220 | 221 | # additional processing for pip updates 222 | if key.lower() == "pips": 223 | for i, pips in enumerate(entry[key]): 224 | publish( 225 | f"{topic}/{this.settings.topic(TELEMETRY_PIPS[i])}", 226 | payload=str(pips), 227 | ) 228 | 229 | # additional processing for fuel updates 230 | elif key.lower() == "fuel": 231 | for tank in entry[key]: 232 | publish( 233 | f"{topic}/{this.settings.topic(tank)}", 234 | payload=str(entry[key][tank]), 235 | ) 236 | 237 | # additional processing for Flags 238 | elif key.lower() == "flags": 239 | publish_flags(topic, entry[key], FLAGS_MAP) 240 | 241 | elif key.lower() == "flags2": 242 | publish_flags(topic, entry[key], FLAGS2_MAP) 243 | 244 | # standard processing for most status updates 245 | else: 246 | publish(topic, payload=str(entry[key])) 247 | 248 | # update internal tracking variable (used to filter unnecessary updates) 249 | this.current_db[key] = entry[key] 250 | 251 | 252 | def journal_entry( 253 | cmdr: str, 254 | is_beta: bool, 255 | system: str, 256 | station: str, 257 | entry: Dict[str, Any], 258 | state: Dict[str, Any], 259 | ) -> None: 260 | """Process player journal entries.""" 261 | if not this.mqtt_connected: 262 | return 263 | 264 | if this.settings.location: 265 | if this.current_location["system"] != system: 266 | publish( 267 | f"{this.settings.topic('location')}/{this.settings.topic('system')}", 268 | payload="" if system is None else system, 269 | ) 270 | this.current_location["system"] = system 271 | 272 | if this.current_location["station"] != station: 273 | publish( 274 | f"{this.settings.topic('location')}/{this.settings.topic('station')}", 275 | payload="" if station is None else station, 276 | ) 277 | this.current_location["station"] = station 278 | 279 | if this.settings.state: 280 | if this.current_state != state: 281 | new_state = state.copy() 282 | if "Friends" in new_state and isinstance(new_state["Friends"], set): 283 | new_state["Friends"] = list(new_state["Friends"]) 284 | publish(this.settings.topic("state"), payload=json.dumps(new_state)) 285 | this.current_state = state.copy() 286 | 287 | if str(entry["event"]).lower() in GAME_STATE_EVENTS: 288 | publish( 289 | topic=this.settings.topic("gamerunning"), 290 | payload=str(monitor.game_running()), 291 | ) 292 | 293 | if not this.settings.journal: 294 | return 295 | 296 | topic = this.settings.topic("journal") 297 | 298 | if this.settings.journal_format == "Raw": 299 | data = entry 300 | else: 301 | topic = f"{topic}/{this.settings.topic(entry['event'])}" 302 | data = entry.copy() 303 | del data["event"] 304 | del data["timestamp"] 305 | 306 | publish(topic, payload=json.dumps(data)) 307 | 308 | 309 | def connect_telemetry() -> None: 310 | """Establish a connection with the MQTT broker.""" 311 | status_message(message="Connecting", color="steel blue") 312 | this.mqtt.reinitialise(client_id=this.settings.client_id) 313 | this.mqtt.on_connect = mqttCallback_on_connect 314 | this.mqtt.on_disconnect = mqttCallback_on_disconnect 315 | this.mqtt.username_pw_set(this.settings.username, this.settings.password) 316 | this.mqtt.will_set( 317 | topic=f"{this.settings.topic('root')}/{this.settings.topic('feedactive')}", 318 | payload="False", 319 | qos=0, 320 | retain=True, 321 | ) 322 | try: 323 | if this.settings.encryption: 324 | ca_certs_arg = ( 325 | this.settings.ca_certs if len(this.settings.ca_certs) else None 326 | ) 327 | certfile_arg = ( 328 | this.settings.certfile if len(this.settings.certfile) else None 329 | ) 330 | keyfile_arg = this.settings.keyfile if len(this.settings.keyfile) else None 331 | this.mqtt.tls_set( 332 | ca_certs=ca_certs_arg, 333 | certfile=certfile_arg, 334 | keyfile=keyfile_arg, 335 | ) 336 | this.mqtt.tls_insecure_set(this.settings.tls_insecure) 337 | 338 | this.mqtt.connect_async( 339 | this.settings.broker, 340 | this.settings.port, 341 | this.settings.keepalive, 342 | ) 343 | this.mqtt.loop_start() 344 | 345 | except Exception as e: 346 | status_message(message="CONFIG ERROR", color="red") 347 | logger.error(f"MQTT configuration error - check your connection settings. {e}") 348 | 349 | 350 | def disconnect_telemetry() -> None: 351 | """Break connection to the MQTT broker.""" 352 | status_message(message="Disconnecting", color="steel blue") 353 | if this.mqtt_connected: 354 | publish(topic=this.settings.topic("feedactive"), payload="False", retain=True) 355 | time.sleep(0.5) 356 | this.mqtt.disconnect() 357 | start = time.monotonic() 358 | while this.mqtt_connected: 359 | time.sleep(0.1) 360 | if (time.monotonic() - start) >= 5.0: 361 | logger.error("Timeout waiting for MQTT to disconnect.") 362 | break 363 | this.mqtt.loop_stop() 364 | 365 | 366 | def mqttCallback_on_connect(client, userdata, flags, rc): 367 | """Run this callback when connection to a broker is established.""" 368 | this.current_db = {} 369 | this.current_location["system"] = "N/A" 370 | this.current_location["station"] = "N/A" 371 | this.current_state = {} 372 | if this.mqtt_connected is False: 373 | logger.info("Connected to MQTT Broker") 374 | this.mqtt_connected = True 375 | status_message(message="Online", color="dark green") 376 | publish(topic=this.settings.topic("feedactive"), payload="True", retain=True) 377 | publish( 378 | topic=this.settings.topic("gamerunning"), payload=str(monitor.game_running()) 379 | ) 380 | 381 | 382 | def mqttCallback_on_disconnect(client, userdata, rc): 383 | """Run this callback when the connection to the broker is lost.""" 384 | if this.mqtt_connected is True: 385 | logger.info("Disconnected from MQTT Broker") 386 | this.mqtt_connected = False 387 | status_message(message="Offline", color="orange red") 388 | -------------------------------------------------------------------------------- /paho/mqtt/properties.py: -------------------------------------------------------------------------------- 1 | """ 2 | ******************************************************************* 3 | Copyright (c) 2017, 2019 IBM Corp. 4 | 5 | All rights reserved. This program and the accompanying materials 6 | are made available under the terms of the Eclipse Public License v1.0 7 | and Eclipse Distribution License v1.0 which accompany this distribution. 8 | 9 | The Eclipse Public License is available at 10 | http://www.eclipse.org/legal/epl-v10.html 11 | and the Eclipse Distribution License is available at 12 | http://www.eclipse.org/org/documents/edl-v10.php. 13 | 14 | Contributors: 15 | Ian Craggs - initial implementation and/or documentation 16 | ******************************************************************* 17 | """ 18 | 19 | import sys, struct 20 | 21 | from .packettypes import PacketTypes 22 | 23 | 24 | class MQTTException(Exception): 25 | pass 26 | 27 | 28 | class MalformedPacket(MQTTException): 29 | pass 30 | 31 | 32 | def writeInt16(length): 33 | # serialize a 16 bit integer to network format 34 | return bytearray(struct.pack("!H", length)) 35 | 36 | 37 | def readInt16(buf): 38 | # deserialize a 16 bit integer from network format 39 | return struct.unpack("!H", buf[:2])[0] 40 | 41 | 42 | def writeInt32(length): 43 | # serialize a 32 bit integer to network format 44 | return bytearray(struct.pack("!L", length)) 45 | 46 | 47 | def readInt32(buf): 48 | # deserialize a 32 bit integer from network format 49 | return struct.unpack("!L", buf[:4])[0] 50 | 51 | 52 | def writeUTF(data): 53 | # data could be a string, or bytes. If string, encode into bytes with utf-8 54 | if sys.version_info[0] < 3: 55 | data = bytearray(data, 'utf-8') 56 | else: 57 | data = data if type(data) == type(b"") else bytes(data, "utf-8") 58 | return writeInt16(len(data)) + data 59 | 60 | 61 | def readUTF(buffer, maxlen): 62 | if maxlen >= 2: 63 | length = readInt16(buffer) 64 | else: 65 | raise MalformedPacket("Not enough data to read string length") 66 | maxlen -= 2 67 | if length > maxlen: 68 | raise MalformedPacket("Length delimited string too long") 69 | buf = buffer[2:2+length].decode("utf-8") 70 | # look for chars which are invalid for MQTT 71 | for c in buf: # look for D800-DFFF in the UTF string 72 | ord_c = ord(c) 73 | if ord_c >= 0xD800 and ord_c <= 0xDFFF: 74 | raise MalformedPacket("[MQTT-1.5.4-1] D800-DFFF found in UTF-8 data") 75 | if ord_c == 0x00: # look for null in the UTF string 76 | raise MalformedPacket("[MQTT-1.5.4-2] Null found in UTF-8 data") 77 | if ord_c == 0xFEFF: 78 | raise MalformedPacket("[MQTT-1.5.4-3] U+FEFF in UTF-8 data") 79 | return buf, length+2 80 | 81 | 82 | def writeBytes(buffer): 83 | return writeInt16(len(buffer)) + buffer 84 | 85 | 86 | def readBytes(buffer): 87 | length = readInt16(buffer) 88 | return buffer[2:2+length], length+2 89 | 90 | 91 | class VariableByteIntegers: # Variable Byte Integer 92 | """ 93 | MQTT variable byte integer helper class. Used 94 | in several places in MQTT v5.0 properties. 95 | 96 | """ 97 | 98 | @staticmethod 99 | def encode(x): 100 | """ 101 | Convert an integer 0 <= x <= 268435455 into multi-byte format. 102 | Returns the buffer convered from the integer. 103 | """ 104 | assert 0 <= x <= 268435455 105 | buffer = b'' 106 | while 1: 107 | digit = x % 128 108 | x //= 128 109 | if x > 0: 110 | digit |= 0x80 111 | if sys.version_info[0] >= 3: 112 | buffer += bytes([digit]) 113 | else: 114 | buffer += bytes(chr(digit)) 115 | if x == 0: 116 | break 117 | return buffer 118 | 119 | @staticmethod 120 | def decode(buffer): 121 | """ 122 | Get the value of a multi-byte integer from a buffer 123 | Return the value, and the number of bytes used. 124 | 125 | [MQTT-1.5.5-1] the encoded value MUST use the minimum number of bytes necessary to represent the value 126 | """ 127 | multiplier = 1 128 | value = 0 129 | bytes = 0 130 | while 1: 131 | bytes += 1 132 | digit = buffer[0] 133 | buffer = buffer[1:] 134 | value += (digit & 127) * multiplier 135 | if digit & 128 == 0: 136 | break 137 | multiplier *= 128 138 | return (value, bytes) 139 | 140 | 141 | class Properties(object): 142 | """MQTT v5.0 properties class. 143 | 144 | See Properties.names for a list of accepted property names along with their numeric values. 145 | 146 | See Properties.properties for the data type of each property. 147 | 148 | Example of use: 149 | 150 | publish_properties = Properties(PacketTypes.PUBLISH) 151 | publish_properties.UserProperty = ("a", "2") 152 | publish_properties.UserProperty = ("c", "3") 153 | 154 | First the object is created with packet type as argument, no properties will be present at 155 | this point. Then properties are added as attributes, the name of which is the string property 156 | name without the spaces. 157 | 158 | """ 159 | 160 | def __init__(self, packetType): 161 | self.packetType = packetType 162 | self.types = ["Byte", "Two Byte Integer", "Four Byte Integer", "Variable Byte Integer", 163 | "Binary Data", "UTF-8 Encoded String", "UTF-8 String Pair"] 164 | 165 | self.names = { 166 | "Payload Format Indicator": 1, 167 | "Message Expiry Interval": 2, 168 | "Content Type": 3, 169 | "Response Topic": 8, 170 | "Correlation Data": 9, 171 | "Subscription Identifier": 11, 172 | "Session Expiry Interval": 17, 173 | "Assigned Client Identifier": 18, 174 | "Server Keep Alive": 19, 175 | "Authentication Method": 21, 176 | "Authentication Data": 22, 177 | "Request Problem Information": 23, 178 | "Will Delay Interval": 24, 179 | "Request Response Information": 25, 180 | "Response Information": 26, 181 | "Server Reference": 28, 182 | "Reason String": 31, 183 | "Receive Maximum": 33, 184 | "Topic Alias Maximum": 34, 185 | "Topic Alias": 35, 186 | "Maximum QoS": 36, 187 | "Retain Available": 37, 188 | "User Property": 38, 189 | "Maximum Packet Size": 39, 190 | "Wildcard Subscription Available": 40, 191 | "Subscription Identifier Available": 41, 192 | "Shared Subscription Available": 42 193 | } 194 | 195 | self.properties = { 196 | # id: type, packets 197 | # payload format indicator 198 | 1: (self.types.index("Byte"), [PacketTypes.PUBLISH, PacketTypes.WILLMESSAGE]), 199 | 2: (self.types.index("Four Byte Integer"), [PacketTypes.PUBLISH, PacketTypes.WILLMESSAGE]), 200 | 3: (self.types.index("UTF-8 Encoded String"), [PacketTypes.PUBLISH, PacketTypes.WILLMESSAGE]), 201 | 8: (self.types.index("UTF-8 Encoded String"), [PacketTypes.PUBLISH, PacketTypes.WILLMESSAGE]), 202 | 9: (self.types.index("Binary Data"), [PacketTypes.PUBLISH, PacketTypes.WILLMESSAGE]), 203 | 11: (self.types.index("Variable Byte Integer"), 204 | [PacketTypes.PUBLISH, PacketTypes.SUBSCRIBE]), 205 | 17: (self.types.index("Four Byte Integer"), 206 | [PacketTypes.CONNECT, PacketTypes.CONNACK, PacketTypes.DISCONNECT]), 207 | 18: (self.types.index("UTF-8 Encoded String"), [PacketTypes.CONNACK]), 208 | 19: (self.types.index("Two Byte Integer"), [PacketTypes.CONNACK]), 209 | 21: (self.types.index("UTF-8 Encoded String"), 210 | [PacketTypes.CONNECT, PacketTypes.CONNACK, PacketTypes.AUTH]), 211 | 22: (self.types.index("Binary Data"), 212 | [PacketTypes.CONNECT, PacketTypes.CONNACK, PacketTypes.AUTH]), 213 | 23: (self.types.index("Byte"), 214 | [PacketTypes.CONNECT]), 215 | 24: (self.types.index("Four Byte Integer"), [PacketTypes.WILLMESSAGE]), 216 | 25: (self.types.index("Byte"), [PacketTypes.CONNECT]), 217 | 26: (self.types.index("UTF-8 Encoded String"), [PacketTypes.CONNACK]), 218 | 28: (self.types.index("UTF-8 Encoded String"), 219 | [PacketTypes.CONNACK, PacketTypes.DISCONNECT]), 220 | 31: (self.types.index("UTF-8 Encoded String"), 221 | [PacketTypes.CONNACK, PacketTypes.PUBACK, PacketTypes.PUBREC, 222 | PacketTypes.PUBREL, PacketTypes.PUBCOMP, PacketTypes.SUBACK, 223 | PacketTypes.UNSUBACK, PacketTypes.DISCONNECT, PacketTypes.AUTH]), 224 | 33: (self.types.index("Two Byte Integer"), 225 | [PacketTypes.CONNECT, PacketTypes.CONNACK]), 226 | 34: (self.types.index("Two Byte Integer"), 227 | [PacketTypes.CONNECT, PacketTypes.CONNACK]), 228 | 35: (self.types.index("Two Byte Integer"), [PacketTypes.PUBLISH]), 229 | 36: (self.types.index("Byte"), [PacketTypes.CONNACK]), 230 | 37: (self.types.index("Byte"), [PacketTypes.CONNACK]), 231 | 38: (self.types.index("UTF-8 String Pair"), 232 | [PacketTypes.CONNECT, PacketTypes.CONNACK, 233 | PacketTypes.PUBLISH, PacketTypes.PUBACK, 234 | PacketTypes.PUBREC, PacketTypes.PUBREL, PacketTypes.PUBCOMP, 235 | PacketTypes.SUBSCRIBE, PacketTypes.SUBACK, 236 | PacketTypes.UNSUBSCRIBE, PacketTypes.UNSUBACK, 237 | PacketTypes.DISCONNECT, PacketTypes.AUTH, PacketTypes.WILLMESSAGE]), 238 | 39: (self.types.index("Four Byte Integer"), 239 | [PacketTypes.CONNECT, PacketTypes.CONNACK]), 240 | 40: (self.types.index("Byte"), [PacketTypes.CONNACK]), 241 | 41: (self.types.index("Byte"), [PacketTypes.CONNACK]), 242 | 42: (self.types.index("Byte"), [PacketTypes.CONNACK]), 243 | } 244 | 245 | def allowsMultiple(self, compressedName): 246 | return self.getIdentFromName(compressedName) in [11, 38] 247 | 248 | def getIdentFromName(self, compressedName): 249 | # return the identifier corresponding to the property name 250 | result = -1 251 | for name in self.names.keys(): 252 | if compressedName == name.replace(' ', ''): 253 | result = self.names[name] 254 | break 255 | return result 256 | 257 | def __setattr__(self, name, value): 258 | name = name.replace(' ', '') 259 | privateVars = ["packetType", "types", "names", "properties"] 260 | if name in privateVars: 261 | object.__setattr__(self, name, value) 262 | else: 263 | # the name could have spaces in, or not. Remove spaces before assignment 264 | if name not in [aname.replace(' ', '') for aname in self.names.keys()]: 265 | raise MQTTException( 266 | "Property name must be one of "+str(self.names.keys())) 267 | # check that this attribute applies to the packet type 268 | if self.packetType not in self.properties[self.getIdentFromName(name)][1]: 269 | raise MQTTException("Property %s does not apply to packet type %s" 270 | % (name, PacketTypes.Names[self.packetType])) 271 | if self.allowsMultiple(name): 272 | if type(value) != type([]): 273 | value = [value] 274 | if hasattr(self, name): 275 | value = object.__getattribute__(self, name) + value 276 | object.__setattr__(self, name, value) 277 | 278 | def __str__(self): 279 | buffer = "[" 280 | first = True 281 | for name in self.names.keys(): 282 | compressedName = name.replace(' ', '') 283 | if hasattr(self, compressedName): 284 | if not first: 285 | buffer += ", " 286 | buffer += compressedName + " : " + \ 287 | str(getattr(self, compressedName)) 288 | first = False 289 | buffer += "]" 290 | return buffer 291 | 292 | def json(self): 293 | data = {} 294 | for name in self.names.keys(): 295 | compressedName = name.replace(' ', '') 296 | if hasattr(self, compressedName): 297 | data[compressedName] = getattr(self, compressedName) 298 | return data 299 | 300 | def isEmpty(self): 301 | rc = True 302 | for name in self.names.keys(): 303 | compressedName = name.replace(' ', '') 304 | if hasattr(self, compressedName): 305 | rc = False 306 | break 307 | return rc 308 | 309 | def clear(self): 310 | for name in self.names.keys(): 311 | compressedName = name.replace(' ', '') 312 | if hasattr(self, compressedName): 313 | delattr(self, compressedName) 314 | 315 | def writeProperty(self, identifier, type, value): 316 | buffer = b"" 317 | buffer += VariableByteIntegers.encode(identifier) # identifier 318 | if type == self.types.index("Byte"): # value 319 | if sys.version_info[0] < 3: 320 | buffer += chr(value) 321 | else: 322 | buffer += bytes([value]) 323 | elif type == self.types.index("Two Byte Integer"): 324 | buffer += writeInt16(value) 325 | elif type == self.types.index("Four Byte Integer"): 326 | buffer += writeInt32(value) 327 | elif type == self.types.index("Variable Byte Integer"): 328 | buffer += VariableByteIntegers.encode(value) 329 | elif type == self.types.index("Binary Data"): 330 | buffer += writeBytes(value) 331 | elif type == self.types.index("UTF-8 Encoded String"): 332 | buffer += writeUTF(value) 333 | elif type == self.types.index("UTF-8 String Pair"): 334 | buffer += writeUTF(value[0]) + writeUTF(value[1]) 335 | return buffer 336 | 337 | def pack(self): 338 | # serialize properties into buffer for sending over network 339 | buffer = b"" 340 | for name in self.names.keys(): 341 | compressedName = name.replace(' ', '') 342 | if hasattr(self, compressedName): 343 | identifier = self.getIdentFromName(compressedName) 344 | attr_type = self.properties[identifier][0] 345 | if self.allowsMultiple(compressedName): 346 | for prop in getattr(self, compressedName): 347 | buffer += self.writeProperty(identifier, 348 | attr_type, prop) 349 | else: 350 | buffer += self.writeProperty(identifier, attr_type, 351 | getattr(self, compressedName)) 352 | return VariableByteIntegers.encode(len(buffer)) + buffer 353 | 354 | def readProperty(self, buffer, type, propslen): 355 | if type == self.types.index("Byte"): 356 | value = buffer[0] 357 | valuelen = 1 358 | elif type == self.types.index("Two Byte Integer"): 359 | value = readInt16(buffer) 360 | valuelen = 2 361 | elif type == self.types.index("Four Byte Integer"): 362 | value = readInt32(buffer) 363 | valuelen = 4 364 | elif type == self.types.index("Variable Byte Integer"): 365 | value, valuelen = VariableByteIntegers.decode(buffer) 366 | elif type == self.types.index("Binary Data"): 367 | value, valuelen = readBytes(buffer) 368 | elif type == self.types.index("UTF-8 Encoded String"): 369 | value, valuelen = readUTF(buffer, propslen) 370 | elif type == self.types.index("UTF-8 String Pair"): 371 | value, valuelen = readUTF(buffer, propslen) 372 | buffer = buffer[valuelen:] # strip the bytes used by the value 373 | value1, valuelen1 = readUTF(buffer, propslen - valuelen) 374 | value = (value, value1) 375 | valuelen += valuelen1 376 | return value, valuelen 377 | 378 | def getNameFromIdent(self, identifier): 379 | rc = None 380 | for name in self.names: 381 | if self.names[name] == identifier: 382 | rc = name 383 | return rc 384 | 385 | def unpack(self, buffer): 386 | if sys.version_info[0] < 3: 387 | buffer = bytearray(buffer) 388 | self.clear() 389 | # deserialize properties into attributes from buffer received from network 390 | propslen, VBIlen = VariableByteIntegers.decode(buffer) 391 | buffer = buffer[VBIlen:] # strip the bytes used by the VBI 392 | propslenleft = propslen 393 | while propslenleft > 0: # properties length is 0 if there are none 394 | identifier, VBIlen = VariableByteIntegers.decode( 395 | buffer) # property identifier 396 | buffer = buffer[VBIlen:] # strip the bytes used by the VBI 397 | propslenleft -= VBIlen 398 | attr_type = self.properties[identifier][0] 399 | value, valuelen = self.readProperty( 400 | buffer, attr_type, propslenleft) 401 | buffer = buffer[valuelen:] # strip the bytes used by the value 402 | propslenleft -= valuelen 403 | propname = self.getNameFromIdent(identifier) 404 | compressedName = propname.replace(' ', '') 405 | if not self.allowsMultiple(compressedName) and hasattr(self, compressedName): 406 | raise MQTTException( 407 | "Property '%s' must not exist more than once" % property) 408 | setattr(self, propname, value) 409 | return self, propslen + VBIlen 410 | -------------------------------------------------------------------------------- /settings.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """Code related to settings for the EDMC-Telemetry plugin.""" 3 | 4 | import json 5 | import logging 6 | import tkinter as tk 7 | from pathlib import Path 8 | from tkinter import ttk 9 | from typing import Any 10 | 11 | import myNotebook as nb # type: ignore (provided by EDMC) 12 | import semantic_version # type: ignore (provided by EDMC) 13 | from ttkHyperlinkLabel import HyperlinkLabel # type: ignore (provided by EDMC) 14 | 15 | from paho.mqtt import __version__ as mqtt_version 16 | 17 | 18 | class Settings: 19 | """Handles storage, retrieval and access to EDMC-Telemetry settings.""" 20 | 21 | # Base name to use for the .json settings file (default is 'settings'). 22 | _FILE: str = "settings" 23 | 24 | # Folder location of .json settings file (default is in plugin folder). 25 | _FOLDER: Path = Path(__file__).parent 26 | 27 | # Minimal default configuration. 28 | _DEFAULT: dict[str, Any] = { 29 | "version": None, 30 | "broker": "127.0.0.1", 31 | "port": 1883, 32 | "keepalive": 60, 33 | "qos": 0, 34 | "username": "", 35 | "password": "", 36 | "client_id": "EDMCTelemetryPlugin", 37 | "encryption": False, 38 | "ca_certs": "", 39 | "certfile": "", 40 | "keyfile": "", 41 | "tls_insecure": False, 42 | "dashboard": True, 43 | "dashboard_format": "Processed", 44 | "journal": True, 45 | "journal_format": "Processed", 46 | "location": True, 47 | "state": False, 48 | "lowercase_topics": False, 49 | "topics": { 50 | "root": "Telemetry", 51 | "gamerunning": "GameRunning", 52 | "feedactive": "FeedActive", 53 | "dashboard": "Dashboard", 54 | "journal": "Journal", 55 | "location": "Location", 56 | "state": "State", 57 | "system": "System", 58 | "station": "Station", 59 | "pips": "Pips", 60 | "sys": "Sys", 61 | "eng": "Eng", 62 | "wep": "Wep", 63 | "fuel": "Fuel", 64 | "fuelreservoir": "Reservoir", 65 | "fuelmain": "Main", 66 | }, 67 | } 68 | 69 | # Setters and getters - settings should be accessed through these properties rather 70 | # than via the _options dictionary directly. 71 | @property 72 | def plugin_version(self) -> semantic_version: 73 | """Version of the EDMC-Telemetry plugin.""" 74 | return semantic_version.Version(self._version) 75 | 76 | @property 77 | def file_version(self) -> semantic_version: 78 | """Version of the EDMC-Telemetry plugin used to create settings.json.""" 79 | return semantic_version.Version(self._options["version"]) 80 | 81 | @property 82 | def broker(self) -> str: 83 | """Address of the MQTT broker.""" 84 | return self._options["broker"] 85 | 86 | @broker.setter 87 | def broker(self, new_value: str) -> None: 88 | self._options["broker"] = new_value 89 | self._broker_tk.set(new_value) 90 | 91 | @property 92 | def port(self) -> int: 93 | """Port used to communicate with the MQTT broker.""" 94 | return self._options["port"] 95 | 96 | @port.setter 97 | def port(self, new_value: int) -> None: 98 | self._options["port"] = new_value 99 | self._port_tk.set(new_value) 100 | 101 | @property 102 | def keepalive(self) -> int: 103 | """MQTT keepalive period in seconds.""" 104 | return self._options["keepalive"] 105 | 106 | @keepalive.setter 107 | def keepalive(self, new_value: int) -> None: 108 | self._options["keepalive"] = new_value 109 | self._keepalive_tk.set(new_value) 110 | 111 | @property 112 | def qos(self) -> int: 113 | """MQTT quality of service level for publishing to broker.""" 114 | return self._options["qos"] 115 | 116 | @qos.setter 117 | def qos(self, new_value: int) -> None: 118 | self._options["qos"] = new_value 119 | self._qos_tk.set(new_value) 120 | 121 | @property 122 | def username(self) -> str: 123 | """Username for connecting to MQTT broker.""" 124 | return self._options["username"] 125 | 126 | @username.setter 127 | def username(self, new_value: str) -> None: 128 | self._options["username"] = new_value 129 | self._username_tk.set(new_value) 130 | 131 | @property 132 | def password(self) -> str: 133 | """Password for connecting to MQTT broker.""" 134 | return self._options["password"] 135 | 136 | @password.setter 137 | def password(self, new_value: str) -> None: 138 | self._options["password"] = new_value 139 | self._password_tk.set(new_value) 140 | 141 | @property 142 | def client_id(self) -> str: 143 | """Client ID to use for connection to the MQTT broker.""" 144 | return self._options["client_id"] 145 | 146 | @client_id.setter 147 | def client_id(self, new_value: str) -> None: 148 | self._options["client_id"] = new_value 149 | self._client_id_tk.set(new_value) 150 | 151 | @property 152 | def encryption(self) -> bool: 153 | """Determine if TLS/SSL connection to the MQTT broker should be used.""" 154 | return self._options["encryption"] 155 | 156 | @encryption.setter 157 | def encryption(self, new_value: bool) -> None: 158 | self._options["encryption"] = new_value 159 | self._encryption_tk.set(new_value) 160 | 161 | @property 162 | def ca_certs(self) -> str: 163 | """Return a string path to trusted CA certificate files.""" 164 | return self._options["ca_certs"] 165 | 166 | @ca_certs.setter 167 | def ca_certs(self, new_value: str) -> None: 168 | self._options["ca_certs"] = new_value 169 | self._ca_certs_tk.set(new_value) 170 | 171 | @property 172 | def certfile(self) -> str: 173 | """Return a string path to the client certificate used for authentication.""" 174 | return self._options["certfile"] 175 | 176 | @certfile.setter 177 | def certfile(self, new_value: str) -> None: 178 | self._options["certfile"] = new_value 179 | self._certfile_tk.set(new_value) 180 | 181 | @property 182 | def keyfile(self) -> str: 183 | """Return a string path to the client private key used for authentication.""" 184 | return self._options["keyfile"] 185 | 186 | @keyfile.setter 187 | def keyfile(self, new_value: str) -> None: 188 | self._options["keyfile"] = new_value 189 | self._keyfile_tk.set(new_value) 190 | 191 | @property 192 | def tls_insecure(self) -> bool: 193 | """If enabled, server identity verification will be bypassed.""" 194 | return self._options["tls_insecure"] 195 | 196 | @tls_insecure.setter 197 | def tls_insecure(self, new_value: bool) -> None: 198 | self._options["tls_insecure"] = new_value 199 | self._tls_insecure_tk.set(new_value) 200 | 201 | @property 202 | def root_topic(self) -> str: 203 | """Root MQTT topic that all other topics will be published under.""" 204 | return self._options["topics"]["root"] 205 | 206 | @root_topic.setter 207 | def root_topic(self, new_value: str) -> None: 208 | self._options["topics"]["root"] = new_value 209 | self._root_topic_tk.set(new_value) 210 | 211 | @property 212 | def dashboard(self) -> bool: 213 | """Enable/disable publishing of dashboard telemetry.""" 214 | return self._options["dashboard"] 215 | 216 | @dashboard.setter 217 | def dashboard(self, new_value: bool) -> None: 218 | self._options["dashboard"] = new_value 219 | self._dashboard_tk.set(new_value) 220 | 221 | @property 222 | def dashboard_format(self) -> str: 223 | """Format of published dashboard telemetry.""" 224 | return self._options["dashboard_format"] 225 | 226 | @dashboard_format.setter 227 | def dashboard_format(self, new_value: str) -> None: 228 | self._options["dashboard_format"] = new_value 229 | self._dashboard_format_tk.set(new_value) 230 | 231 | @property 232 | def journal(self) -> bool: 233 | """Enable/disable publishing of journal telemetry.""" 234 | return self._options["journal"] 235 | 236 | @journal.setter 237 | def journal(self, new_value: bool) -> None: 238 | self._options["journal"] = new_value 239 | self._journal_tk.set(new_value) 240 | 241 | @property 242 | def journal_format(self) -> str: 243 | """Format of published journal telemetry.""" 244 | return self._options["journal_format"] 245 | 246 | @journal_format.setter 247 | def journal_format(self, new_value: str) -> None: 248 | self._options["journal_format"] = new_value 249 | self._journal_format_tk.set(new_value) 250 | 251 | @property 252 | def location(self) -> bool: 253 | """Enable/disable publishing of EDMC-generated location telemetry.""" 254 | return self._options["location"] 255 | 256 | @location.setter 257 | def location(self, new_value: bool) -> None: 258 | self._options["location"] = new_value 259 | self._location_tk.set(new_value) 260 | 261 | @property 262 | def state(self) -> bool: 263 | """Enable/disable publishing of EDMC-generated state telemetry.""" 264 | return self._options["state"] 265 | 266 | @state.setter 267 | def state(self, new_value: bool) -> None: 268 | self._options["state"] = new_value 269 | self._state_tk.set(new_value) 270 | 271 | @property 272 | def lowercase_topics(self) -> bool: 273 | """Enable/disable forcing of all topics to lowercase.""" 274 | return self._options["lowercase_topics"] 275 | 276 | @lowercase_topics.setter 277 | def lowercase_topics(self, new_value: bool) -> None: 278 | self._options["lowercase_topics"] = new_value 279 | self._lowercase_topics_tk.set(new_value) 280 | 281 | # This one isn't a 'property' but is grouped with the other properties because it is 282 | # used like a getter. 283 | def topic(self, requested_topic: str) -> str: 284 | """Safely retrieves MQTT topics from the _options dictionary.""" 285 | if requested_topic.lower() in self._options["topics"]: 286 | return self._options["topics"][requested_topic.lower()] 287 | else: 288 | return requested_topic 289 | 290 | def __init__(self, telemetry_version: str, logger: logging.Logger) -> None: 291 | """Initialize a telemetry settings object.""" 292 | Settings._DEFAULT["version"] = telemetry_version 293 | self._version = telemetry_version 294 | self._logger = logger 295 | self._options = {} 296 | self._load() 297 | 298 | def _load(self) -> None: 299 | """Read telemetry settings from a file, creating a new file if needed.""" 300 | settings_file = Settings._FOLDER / f"{Settings._FILE}.json" 301 | 302 | if settings_file.exists(): 303 | with open(settings_file, mode="r", encoding="utf-8") as file: 304 | self._options = json.loads(file.read()) 305 | self._logger.info(f"Loaded settings file <{settings_file}>") 306 | 307 | # Upgrade the settings file if it is out-of-date. 308 | if self.plugin_version > self.file_version: 309 | self._upgrade() 310 | 311 | # Generate a warning if settings are from a newer version of the plugin. 312 | elif self.plugin_version < self.file_version: 313 | self._logger.warn( 314 | "JSON settings file was created by a newer version of the " 315 | + f"telemetry plugin (v{self.file_version})." 316 | ) 317 | else: 318 | self._options = Settings._DEFAULT.copy() 319 | self._save() 320 | 321 | # create tkinter variables for preferences that can be modified through the UI. 322 | self._broker_tk = tk.StringVar(value=self.broker) 323 | self._port_tk = tk.IntVar(value=self.port) 324 | self._keepalive_tk = tk.IntVar(value=self.keepalive) 325 | self._qos_tk = tk.IntVar(value=self.qos) 326 | self._username_tk = tk.StringVar(value=self.username) 327 | self._password_tk = tk.StringVar(value=self.password) 328 | self._client_id_tk = tk.StringVar(value=self.client_id) 329 | self._encryption_tk = tk.BooleanVar(value=self.encryption) 330 | self._ca_certs_tk = tk.StringVar(value=self.ca_certs) 331 | self._certfile_tk = tk.StringVar(value=self.certfile) 332 | self._keyfile_tk = tk.StringVar(value=self.keyfile) 333 | self._tls_insecure_tk = tk.BooleanVar(value=self.tls_insecure) 334 | self._dashboard_tk = tk.BooleanVar(value=self.dashboard) 335 | self._dashboard_format_tk = tk.StringVar(value=self.dashboard_format) 336 | self._journal_tk = tk.BooleanVar(value=self.journal) 337 | self._journal_format_tk = tk.StringVar(value=self.journal_format) 338 | self._location_tk = tk.BooleanVar(value=self.location) 339 | self._state_tk = tk.BooleanVar(value=self.state) 340 | self._root_topic_tk = tk.StringVar(value=self.root_topic) 341 | self._lowercase_topics_tk = tk.BooleanVar(value=self.lowercase_topics) 342 | 343 | def _save(self, is_backup: bool = False) -> None: 344 | """Write telemetry settings to a file.""" 345 | if is_backup: 346 | filename = f"{Settings._FILE}_backup_{self.file_version}.json" 347 | else: 348 | filename = f"{Settings._FILE}.json" 349 | settings_file = Settings._FOLDER / filename 350 | 351 | with open(settings_file, mode="w", encoding="utf-8") as file: 352 | file.write(json.dumps(self._options, indent=4)) 353 | 354 | if is_backup: 355 | self._logger.info(f"Backed up settings file to <{settings_file}>") 356 | else: 357 | self._logger.info(f"Saved settings file <{settings_file}>") 358 | 359 | def _upgrade(self) -> None: 360 | """Upgrades the telemetry settings file and saves a backup of the original.""" 361 | # The upgrade process should definitely start by backing up existing data. 362 | self._save(is_backup=True) 363 | 364 | # Set the settings version to the current plugin version. 365 | self._options["version"] = self._version 366 | 367 | # Add/update settings as needed. 368 | for key in Settings._DEFAULT: 369 | 370 | # If the key is missing, add it. 371 | if key not in self._options: 372 | self._options[key] = Settings._DEFAULT[key] 373 | 374 | # More processing is needed if the key already exists. 375 | else: 376 | # Reset to default if type has changed (i.e. int to bool, etc.). 377 | if type(self._options[key]) != type(Settings._DEFAULT[key]): 378 | self._options[key] = Settings._DEFAULT[key] 379 | self._logger.debug(f"'{key}' was reset to its new default value.") 380 | 381 | # Make sure all required entries are in topics dictionary. 382 | elif key == "topics": 383 | for topic in Settings._DEFAULT[key]: 384 | if topic not in self._options[key]: 385 | self._options[key][topic] = Settings._DEFAULT[key][topic] 386 | self._logger.debug(f"Added missing topic '{topic}'.") 387 | 388 | # Remove old/invalid/deprecated settings. 389 | keys_to_remove = list() 390 | for key in self._options: 391 | if key not in Settings._DEFAULT: 392 | keys_to_remove.append(key) 393 | 394 | for key in keys_to_remove: 395 | del self._options[key] 396 | self._logger.debug(f"'{key}' is invalid and has been removed.") 397 | 398 | # Once the settings upgrade is complete, do a normal save. 399 | self._save() 400 | self._logger.info(f"Settings upgraded for EDMC-Telemetry {self.plugin_version}") 401 | 402 | def show_preferences(self, parent: nb.Notebook) -> tk.Frame: 403 | """Display preferences tab in UI.""" 404 | # set up the primary frame for our assigned notebook tab 405 | frame = nb.Frame(parent) 406 | frame.columnconfigure(1, weight=1) 407 | frame.rowconfigure(1, weight=1) 408 | 409 | # create a style that will be used for telemetry's settings notebook 410 | style = ttk.Style() 411 | style.configure("TNB.TNotebook", background=nb.Label().cget("background")) 412 | style.configure("TNB.TLabelFrame", background=nb.Label().cget("background")) 413 | PADX = 10 414 | PADY = 2 415 | 416 | # add our own notebook to hold all the telemetry options 417 | tnb = ttk.Notebook(frame, style="TNB.TNotebook") 418 | tnb.grid(columnspan=2, padx=8, sticky=tk.NSEW) 419 | tnb.columnconfigure(1, weight=1) 420 | 421 | # broker connection settings 422 | tnb_comm = nb.Frame(tnb) 423 | tnb_comm.columnconfigure(1, weight=1) 424 | row = 0 425 | 426 | row += 1 427 | nb.Label(tnb_comm, text="[Required Settings]").grid( 428 | padx=PADX, row=row, sticky=tk.W 429 | ) 430 | 431 | # mqtt broker address 432 | row += 1 433 | nb.Label(tnb_comm, text="Broker Address:").grid(padx=PADX, row=row, sticky=tk.E) 434 | nb.Entry(tnb_comm, textvariable=self._broker_tk).grid( 435 | padx=PADX, pady=PADY, row=row, column=1, sticky=tk.EW 436 | ) 437 | 438 | # mqtt broker port 439 | row += 1 440 | nb.Label(tnb_comm, text="Port:").grid(padx=PADX, row=row, sticky=tk.E) 441 | nb.Entry(tnb_comm, textvariable=self._port_tk).grid( 442 | padx=PADX, pady=PADY, row=row, column=1, sticky=tk.EW 443 | ) 444 | 445 | # mqtt qos 446 | row += 1 447 | nb.Label(tnb_comm, text="QoS:").grid(padx=PADX, row=row, sticky=tk.E) 448 | nb.OptionMenu(tnb_comm, self._qos_tk, self._qos_tk.get(), 0, 1, 2).grid( 449 | padx=PADX, pady=PADY, row=row, column=1, sticky=tk.W 450 | ) 451 | 452 | # mqtt broker keepalive 453 | row += 1 454 | nb.Label(tnb_comm, text="Keepalive:").grid(padx=PADX, row=row, sticky=tk.E) 455 | nb.Entry(tnb_comm, textvariable=self._keepalive_tk).grid( 456 | padx=PADX, pady=PADY, row=row, column=1, sticky=tk.EW 457 | ) 458 | 459 | # mqtt client id 460 | row += 1 461 | nb.Label(tnb_comm, text="Client ID:").grid(padx=PADX, row=row, sticky=tk.E) 462 | nb.Entry(tnb_comm, textvariable=self._client_id_tk).grid( 463 | padx=PADX, pady=PADY, row=row, column=1, sticky=tk.EW 464 | ) 465 | 466 | # broker auth settings 467 | row += 1 468 | ttk.Separator(tnb_comm, orient=tk.HORIZONTAL).grid( 469 | columnspan=4, padx=PADX, pady=PADY * 4, sticky=tk.EW, row=row 470 | ) 471 | row += 1 472 | nb.Label(tnb_comm, text="[Authentication]").grid( 473 | padx=PADX, row=row, sticky=tk.W 474 | ) 475 | 476 | # mqtt username 477 | row += 1 478 | nb.Label(tnb_comm, text="Username:").grid(padx=PADX, row=row, sticky=tk.E) 479 | nb.Entry(tnb_comm, textvariable=self._username_tk).grid( 480 | padx=PADX, pady=PADY, row=row, column=1, sticky=tk.EW 481 | ) 482 | 483 | # mqtt password 484 | row += 1 485 | nb.Label(tnb_comm, text="Password:").grid(padx=PADX, row=row, sticky=tk.E) 486 | nb.Entry(tnb_comm, textvariable=self._password_tk).grid( 487 | padx=PADX, pady=PADY, row=row, column=1, sticky=tk.EW 488 | ) 489 | 490 | # broker encryption settings 491 | row += 1 492 | ttk.Separator(tnb_comm, orient=tk.HORIZONTAL).grid( 493 | columnspan=4, padx=PADX, pady=PADY * 4, sticky=tk.EW, row=row 494 | ) 495 | row += 1 496 | nb.Label(tnb_comm, text="[Encryption]").grid(padx=PADX, row=row, sticky=tk.W) 497 | 498 | # encryption 499 | row += 1 500 | nb.Checkbutton( 501 | tnb_comm, 502 | text="Encrypted Connection", 503 | variable=self._encryption_tk, 504 | command="", 505 | ).grid(padx=PADX, row=row, column=1, sticky=tk.W) 506 | 507 | # skip validation 508 | row += 1 509 | nb.Checkbutton( 510 | tnb_comm, 511 | text="Skip Certificate Verification", 512 | variable=self._tls_insecure_tk, 513 | command="", 514 | ).grid(padx=PADX, row=row, column=1, sticky=tk.W) 515 | 516 | # server ca certificate 517 | row += 1 518 | nb.Label(tnb_comm, text="Server Certificate (CA)").grid( 519 | padx=PADX, row=row, sticky=tk.E 520 | ) 521 | nb.Entry(tnb_comm, textvariable=self._ca_certs_tk).grid( 522 | padx=PADX, pady=PADY, row=row, column=1, sticky=tk.EW 523 | ) 524 | 525 | # client certificate 526 | row += 1 527 | nb.Label(tnb_comm, text="Client Certificate").grid( 528 | padx=PADX, row=row, sticky=tk.E 529 | ) 530 | nb.Entry(tnb_comm, textvariable=self._certfile_tk).grid( 531 | padx=PADX, pady=PADY, row=row, column=1, sticky=tk.EW 532 | ) 533 | 534 | # client key 535 | row += 1 536 | nb.Label(tnb_comm, text="Client Key").grid(padx=PADX, row=row, sticky=tk.E) 537 | nb.Entry(tnb_comm, textvariable=self._keyfile_tk).grid( 538 | padx=PADX, pady=PADY, row=row, column=1, sticky=tk.EW 539 | ) 540 | 541 | # topic settings 542 | tnb_data = nb.Frame(tnb) 543 | tnb_data.columnconfigure(1, weight=1) 544 | row = 0 545 | 546 | # mqtt root topic 547 | row += 1 548 | nb.Label(tnb_data, text="Root Topic").grid(padx=PADX, row=row, sticky=tk.W) 549 | nb.Entry(tnb_data, textvariable=self._root_topic_tk).grid( 550 | padx=PADX, pady=PADY, row=row, column=1, sticky=tk.EW 551 | ) 552 | 553 | # lowercase topics 554 | row += 1 555 | nb.Checkbutton( 556 | tnb_data, 557 | text="Convert all topics to lowercase", 558 | variable=self._lowercase_topics_tk, 559 | command="", 560 | ).grid(padx=PADX, row=row, sticky=tk.W) 561 | 562 | # dashboard 563 | row += 1 564 | nb.Checkbutton( 565 | tnb_data, 566 | text="Publish Dashboard", 567 | variable=self._dashboard_tk, 568 | command="", 569 | ).grid(padx=PADX, row=row, sticky=tk.W) 570 | nb.OptionMenu( 571 | tnb_data, 572 | self._dashboard_format_tk, 573 | self._dashboard_format_tk.get(), 574 | "Raw", 575 | "Processed", 576 | ).grid(padx=PADX, pady=PADY, row=row, column=1, sticky=tk.W) 577 | 578 | # journal 579 | row += 1 580 | nb.Checkbutton( 581 | tnb_data, 582 | text="Publish Journal", 583 | variable=self._journal_tk, 584 | command="", 585 | ).grid(padx=PADX, row=row, sticky=tk.W) 586 | nb.OptionMenu( 587 | tnb_data, 588 | self._journal_format_tk, 589 | self._journal_format_tk.get(), 590 | "Raw", 591 | "Processed", 592 | ).grid(padx=PADX, pady=PADY, row=row, column=1, sticky=tk.W) 593 | 594 | # location 595 | row += 1 596 | nb.Checkbutton( 597 | tnb_data, 598 | text="Publish Current System/Station", 599 | variable=self._location_tk, 600 | command="", 601 | ).grid(padx=PADX, row=row, sticky=tk.W) 602 | 603 | # state 604 | row += 1 605 | nb.Checkbutton( 606 | tnb_data, 607 | text="Publish EDMC State Tracking", 608 | variable=self._state_tk, 609 | command="", 610 | ).grid(padx=PADX, row=row, sticky=tk.W) 611 | 612 | # add the preferences tabs we've created to our assigned EDMC settings tab 613 | tnb.add(tnb_comm, text="Connection") 614 | tnb.add(tnb_data, text="Data") 615 | 616 | # plugin link and version 617 | HyperlinkLabel( 618 | frame, 619 | text="https://github.com/fasteddy516/EDMC-Telemetry/", 620 | background=nb.Label().cget("background"), 621 | url="https://github.com/fasteddy516/EDMC-Telemetry/", 622 | underline=True, 623 | ).grid(padx=PADX, pady=(1, 4), row=2, column=0, sticky=tk.W) 624 | nb.Label(frame, text=f"Plugin Version {self.plugin_version}").grid( 625 | padx=PADX, pady=(1, 4), row=2, column=1, sticky=tk.E 626 | ) 627 | 628 | # mqtt link and version 629 | HyperlinkLabel( 630 | frame, 631 | text="https://github.com/eclipse/paho.mqtt.python/", 632 | background=nb.Label().cget("background"), 633 | url="https://github.com/eclipse/paho.mqtt.python", 634 | underline=True, 635 | ).grid(padx=PADX, pady=(1, 4), row=3, column=0, sticky=tk.W) 636 | nb.Label(frame, text=f"MQTT Version {mqtt_version}").grid( 637 | padx=PADX, pady=(1, 4), row=3, column=1, sticky=tk.E 638 | ) 639 | 640 | return frame 641 | 642 | def update_preferences(self) -> bool: 643 | """Update settings when the preferences panel is closed.""" 644 | reset_connection = False 645 | 646 | # If any of these settings changed, the connection to the broker must be reset. 647 | if self.broker != self._broker_tk.get(): 648 | self.broker = self._broker_tk.get() 649 | reset_connection = True 650 | 651 | if self.port != self._port_tk.get(): 652 | self.port = self._port_tk.get() 653 | reset_connection = True 654 | 655 | if self.keepalive != self._keepalive_tk.get(): 656 | self.keepalive = self._keepalive_tk.get() 657 | reset_connection = True 658 | 659 | if self.username != self._username_tk.get(): 660 | self.username = self._username_tk.get() 661 | reset_connection = True 662 | 663 | if self.password != self._password_tk.get(): 664 | self.password = self._password_tk.get() 665 | reset_connection = True 666 | 667 | if self.client_id != self._client_id_tk.get(): 668 | self.client_id = self._client_id_tk.get() 669 | reset_connection = True 670 | 671 | if self.encryption != self._encryption_tk.get(): 672 | self.encryption = self._encryption_tk.get() 673 | reset_connection = True 674 | 675 | if self.ca_certs != self._ca_certs_tk.get(): 676 | self.ca_certs = self._ca_certs_tk.get() 677 | reset_connection = True 678 | 679 | if self.certfile != self._certfile_tk.get(): 680 | self.certfile = self._certfile_tk.get() 681 | reset_connection = True 682 | 683 | if self.keyfile != self._keyfile_tk.get(): 684 | self.keyfile = self._keyfile_tk.get() 685 | reset_connection = True 686 | 687 | if self.tls_insecure != self._tls_insecure_tk.get(): 688 | self.tls_insecure = self._tls_insecure_tk.get() 689 | reset_connection = True 690 | 691 | # The rest of these options can be adjusted on-the-fly while connected. 692 | self.root_topic = self._root_topic_tk.get() 693 | self.lowercase_topics = self._lowercase_topics_tk.get() 694 | self.qos = self._qos_tk.get() 695 | self.dashboard = self._dashboard_tk.get() 696 | self.dashboard_format = self._dashboard_format_tk.get() 697 | self.journal = self._journal_tk.get() 698 | self.journal_format = self._journal_format_tk.get() 699 | self.location = self._location_tk.get() 700 | self.state = self._state_tk.get() 701 | 702 | self._save() 703 | 704 | return reset_connection 705 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------