reasoncodes.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. # *******************************************************************
  2. # Copyright (c) 2017, 2019 IBM Corp.
  3. #
  4. # All rights reserved. This program and the accompanying materials
  5. # are made available under the terms of the Eclipse Public License v2.0
  6. # and Eclipse Distribution License v1.0 which accompany this distribution.
  7. #
  8. # The Eclipse Public License is available at
  9. # http://www.eclipse.org/legal/epl-v20.html
  10. # and the Eclipse Distribution License is available at
  11. # http://www.eclipse.org/org/documents/edl-v10.php.
  12. #
  13. # Contributors:
  14. # Ian Craggs - initial implementation and/or documentation
  15. # *******************************************************************
  16. from __future__ import annotations
  17. import functools
  18. import warnings
  19. from types import MappingProxyType
  20. from typing import Any
  21. from .packettypes import PacketTypes
  22. @functools.total_ordering
  23. class ReasonCode:
  24. """MQTT version 5.0 reason codes class.
  25. See ReasonCode.names for a list of possible numeric values along with their
  26. names and the packets to which they apply.
  27. """
  28. names: MappingProxyType | dict = MappingProxyType(
  29. {
  30. 0: {
  31. "Success": [
  32. PacketTypes.CONNACK,
  33. PacketTypes.PUBACK,
  34. PacketTypes.PUBREC,
  35. PacketTypes.PUBREL,
  36. PacketTypes.PUBCOMP,
  37. PacketTypes.UNSUBACK,
  38. PacketTypes.AUTH,
  39. ],
  40. "Normal disconnection": [PacketTypes.DISCONNECT],
  41. "Granted QoS 0": [PacketTypes.SUBACK],
  42. },
  43. 1: {"Granted QoS 1": [PacketTypes.SUBACK]},
  44. 2: {"Granted QoS 2": [PacketTypes.SUBACK]},
  45. 4: {"Disconnect with will message": [PacketTypes.DISCONNECT]},
  46. 16: {"No matching subscribers": [PacketTypes.PUBACK, PacketTypes.PUBREC]},
  47. 17: {"No subscription found": [PacketTypes.UNSUBACK]},
  48. 24: {"Continue authentication": [PacketTypes.AUTH]},
  49. 25: {"Re-authenticate": [PacketTypes.AUTH]},
  50. 128: {
  51. "Unspecified error": [PacketTypes.CONNACK, PacketTypes.PUBACK, PacketTypes.PUBREC, PacketTypes.SUBACK, PacketTypes.UNSUBACK, PacketTypes.DISCONNECT],
  52. },
  53. 129: {"Malformed packet": [PacketTypes.CONNACK, PacketTypes.DISCONNECT]},
  54. 130: {"Protocol error": [PacketTypes.CONNACK, PacketTypes.DISCONNECT]},
  55. 131: {
  56. "Implementation specific error": [
  57. PacketTypes.CONNACK,
  58. PacketTypes.PUBACK,
  59. PacketTypes.PUBREC,
  60. PacketTypes.SUBACK,
  61. PacketTypes.UNSUBACK,
  62. PacketTypes.DISCONNECT,
  63. ],
  64. },
  65. 132: {"Unsupported protocol version": [PacketTypes.CONNACK]},
  66. 133: {"Client identifier not valid": [PacketTypes.CONNACK]},
  67. 134: {"Bad user name or password": [PacketTypes.CONNACK]},
  68. 135: {
  69. "Not authorized": [PacketTypes.CONNACK, PacketTypes.PUBACK, PacketTypes.PUBREC, PacketTypes.SUBACK, PacketTypes.UNSUBACK, PacketTypes.DISCONNECT],
  70. },
  71. 136: {"Server unavailable": [PacketTypes.CONNACK]},
  72. 137: {"Server busy": [PacketTypes.CONNACK, PacketTypes.DISCONNECT]},
  73. 138: {"Banned": [PacketTypes.CONNACK]},
  74. 139: {"Server shutting down": [PacketTypes.DISCONNECT]},
  75. 140: {"Bad authentication method": [PacketTypes.CONNACK, PacketTypes.DISCONNECT]},
  76. 141: {"Keep alive timeout": [PacketTypes.DISCONNECT]},
  77. 142: {"Session taken over": [PacketTypes.DISCONNECT]},
  78. 143: {"Topic filter invalid": [PacketTypes.SUBACK, PacketTypes.UNSUBACK, PacketTypes.DISCONNECT]},
  79. 144: {"Topic name invalid": [PacketTypes.CONNACK, PacketTypes.PUBACK, PacketTypes.PUBREC, PacketTypes.DISCONNECT]},
  80. 145: {"Packet identifier in use": [PacketTypes.PUBACK, PacketTypes.PUBREC, PacketTypes.SUBACK, PacketTypes.UNSUBACK]},
  81. 146: {"Packet identifier not found": [PacketTypes.PUBREL, PacketTypes.PUBCOMP]},
  82. 147: {"Receive maximum exceeded": [PacketTypes.DISCONNECT]},
  83. 148: {"Topic alias invalid": [PacketTypes.DISCONNECT]},
  84. 149: {"Packet too large": [PacketTypes.CONNACK, PacketTypes.DISCONNECT]},
  85. 150: {"Message rate too high": [PacketTypes.DISCONNECT]},
  86. 151: {
  87. "Quota exceeded": [PacketTypes.CONNACK, PacketTypes.PUBACK, PacketTypes.PUBREC, PacketTypes.SUBACK, PacketTypes.DISCONNECT],
  88. },
  89. 152: {"Administrative action": [PacketTypes.DISCONNECT]},
  90. 153: {"Payload format invalid": [PacketTypes.PUBACK, PacketTypes.PUBREC, PacketTypes.DISCONNECT]},
  91. 154: {"Retain not supported": [PacketTypes.CONNACK, PacketTypes.DISCONNECT]},
  92. 155: {"QoS not supported": [PacketTypes.CONNACK, PacketTypes.DISCONNECT]},
  93. 156: {"Use another server": [PacketTypes.CONNACK, PacketTypes.DISCONNECT]},
  94. 157: {"Server moved": [PacketTypes.CONNACK, PacketTypes.DISCONNECT]},
  95. 158: {"Shared subscription not supported": [PacketTypes.SUBACK, PacketTypes.DISCONNECT]},
  96. 159: {"Connection rate exceeded": [PacketTypes.CONNACK, PacketTypes.DISCONNECT]},
  97. 160: {"Maximum connect time": [PacketTypes.DISCONNECT]},
  98. 161: {"Subscription identifiers not supported": [PacketTypes.SUBACK, PacketTypes.DISCONNECT]},
  99. 162: {"Wildcard subscription not supported": [PacketTypes.SUBACK, PacketTypes.DISCONNECT]},
  100. }
  101. )
  102. def __init__(self, packetType: int, aName: str = "Success", identifier: int = -1):
  103. """
  104. packetType: the type of the packet, such as PacketTypes.CONNECT that
  105. this reason code will be used with. Some reason codes have different
  106. names for the same identifier when used a different packet type.
  107. aName: the String name of the reason code to be created. Ignored
  108. if the identifier is set.
  109. identifier: an integer value of the reason code to be created.
  110. """
  111. self.names = dict(type(self).names)
  112. self.packetType = packetType
  113. if identifier == -1:
  114. if packetType == PacketTypes.DISCONNECT and aName == "Success":
  115. aName = "Normal disconnection"
  116. self.set(aName)
  117. else:
  118. self.value = identifier
  119. self.getName() # check it's good
  120. def __getName__(self, packetType: int, identifier: int) -> str:
  121. """
  122. Get the reason code string name for a specific identifier.
  123. The name can vary by packet type for the same identifier, which
  124. is why the packet type is also required.
  125. Used when displaying the reason code.
  126. """
  127. if identifier not in self.names:
  128. raise KeyError(identifier)
  129. names = self.names[identifier]
  130. namelist = [name for name in names if packetType in names[name]]
  131. if len(namelist) != 1:
  132. raise ValueError(f"Expected exactly one name, found {namelist!r}")
  133. return namelist[0]
  134. def getId(self, name: str) -> int:
  135. """
  136. Get the numeric id corresponding to a reason code name.
  137. Used when setting the reason code for a packetType
  138. check that only valid codes for the packet are set.
  139. """
  140. for code in self.names:
  141. if name in self.names[code] and self.packetType in self.names[code][name]:
  142. return code
  143. raise KeyError(f"Reason code name not found: {name}")
  144. def set(self, name: str) -> None:
  145. self.value = self.getId(name)
  146. def unpack(self, buffer: bytes|bytearray) -> int:
  147. c = buffer[0]
  148. name = self.__getName__(self.packetType, c)
  149. self.value = self.getId(name)
  150. return 1
  151. def getName(self) -> str:
  152. """Returns the reason code name corresponding to the numeric value which is set."""
  153. return self.__getName__(self.packetType, self.value)
  154. def __eq__(self, other: object) -> bool:
  155. if isinstance(other, int):
  156. return self.value == other
  157. if isinstance(other, str):
  158. return other == str(self)
  159. if isinstance(other, ReasonCode):
  160. return self.value == other.value
  161. return False
  162. def __lt__(self, other: Any) -> bool:
  163. if isinstance(other, int):
  164. return self.value < other
  165. if isinstance(other, ReasonCode):
  166. return self.value < other.value
  167. return NotImplemented
  168. def __repr__(self) -> str:
  169. try:
  170. packet_name = PacketTypes.Names[self.packetType]
  171. except IndexError:
  172. packet_name = "Unknown"
  173. return f"ReasonCode({packet_name}, {self.getName()!r})"
  174. def __str__(self) -> str:
  175. return self.getName()
  176. def json(self) -> str:
  177. return self.getName()
  178. def pack(self) -> bytearray:
  179. return bytearray([self.value])
  180. @property
  181. def is_failure(self) -> bool:
  182. return self.value >= 0x80
  183. class _CompatibilityIsInstance(type):
  184. def __instancecheck__(self, other: Any) -> bool:
  185. return isinstance(other, ReasonCode)
  186. class ReasonCodes(ReasonCode, metaclass=_CompatibilityIsInstance):
  187. def __init__(self, *args, **kwargs):
  188. warnings.warn(
  189. "ReasonCodes is deprecated, use ReasonCode (singular) instead",
  190. category=DeprecationWarning,
  191. stacklevel=2,
  192. )
  193. super().__init__(*args, **kwargs)