Fork of the espurna firmware for `mhsw` switches
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

599 lines
18 KiB

8 years ago
8 years ago
6 years ago
7 years ago
7 years ago
6 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
  1. /*
  2. MQTT MODULE
  3. Copyright (C) 2016-2018 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #if MQTT_SUPPORT
  6. #include <ESP8266WiFi.h>
  7. #include <ESP8266mDNS.h>
  8. #include <ArduinoJson.h>
  9. #include <vector>
  10. #include <Ticker.h>
  11. #if MQTT_USE_ASYNC // Using AsyncMqttClient
  12. #include <AsyncMqttClient.h>
  13. AsyncMqttClient _mqtt;
  14. #else // Using PubSubClient
  15. #include <PubSubClient.h>
  16. PubSubClient _mqtt;
  17. bool _mqtt_connected = false;
  18. WiFiClient _mqtt_client;
  19. #if ASYNC_TCP_SSL_ENABLED
  20. WiFiClientSecure _mqtt_client_secure;
  21. #endif // ASYNC_TCP_SSL_ENABLED
  22. #endif // MQTT_USE_ASYNC
  23. bool _mqtt_enabled = MQTT_ENABLED;
  24. bool _mqtt_use_json = false;
  25. unsigned long _mqtt_reconnect_delay = MQTT_RECONNECT_DELAY_MIN;
  26. unsigned char _mqtt_qos = MQTT_QOS;
  27. bool _mqtt_retain = MQTT_RETAIN;
  28. unsigned char _mqtt_keepalive = MQTT_KEEPALIVE;
  29. String _mqtt_topic;
  30. String _mqtt_setter;
  31. String _mqtt_getter;
  32. bool _mqtt_forward;
  33. char *_mqtt_user = 0;
  34. char *_mqtt_pass = 0;
  35. char *_mqtt_will;
  36. char *_mqtt_clientid;
  37. #if MQTT_SKIP_RETAINED
  38. unsigned long _mqtt_connected_at = 0;
  39. #endif
  40. std::vector<mqtt_callback_f> _mqtt_callbacks;
  41. typedef struct {
  42. char * topic;
  43. char * message;
  44. } mqtt_message_t;
  45. std::vector<mqtt_message_t> _mqtt_queue;
  46. Ticker _mqtt_flush_ticker;
  47. // -----------------------------------------------------------------------------
  48. // Public API
  49. // -----------------------------------------------------------------------------
  50. bool mqttConnected() {
  51. return _mqtt.connected();
  52. }
  53. void mqttDisconnect() {
  54. if (_mqtt.connected()) {
  55. DEBUG_MSG_P(PSTR("[MQTT] Disconnecting\n"));
  56. _mqtt.disconnect();
  57. }
  58. }
  59. bool mqttForward() {
  60. return _mqtt_forward;
  61. }
  62. String mqttSubtopic(char * topic) {
  63. String response;
  64. String t = String(topic);
  65. if (t.startsWith(_mqtt_topic) && t.endsWith(_mqtt_setter)) {
  66. response = t.substring(_mqtt_topic.length(), t.length() - _mqtt_setter.length());
  67. }
  68. return response;
  69. }
  70. void mqttSendRaw(const char * topic, const char * message) {
  71. if (_mqtt.connected()) {
  72. #if MQTT_USE_ASYNC
  73. unsigned int packetId = _mqtt.publish(topic, _mqtt_qos, _mqtt_retain, message);
  74. DEBUG_MSG_P(PSTR("[MQTT] Sending %s => %s (PID %d)\n"), topic, message, packetId);
  75. #else
  76. _mqtt.publish(topic, message, _mqtt_retain);
  77. DEBUG_MSG_P(PSTR("[MQTT] Sending %s => %s\n"), topic, message);
  78. #endif
  79. }
  80. }
  81. String getTopic(const char * topic, bool set) {
  82. String output = _mqtt_topic + String(topic);
  83. if (set) output += _mqtt_setter;
  84. return output;
  85. }
  86. String getTopic(const char * topic, unsigned int index, bool set) {
  87. char buffer[strlen(topic)+5];
  88. snprintf_P(buffer, sizeof(buffer), PSTR("%s/%d"), topic, index);
  89. return getTopic(buffer, set);
  90. }
  91. void _mqttFlush() {
  92. if (_mqtt_queue.size() == 0) return;
  93. DynamicJsonBuffer jsonBuffer;
  94. JsonObject& root = jsonBuffer.createObject();
  95. for (unsigned char i=0; i<_mqtt_queue.size(); i++) {
  96. mqtt_message_t element = _mqtt_queue[i];
  97. root[element.topic] = element.message;
  98. }
  99. #if NTP_SUPPORT
  100. if (ntpConnected()) root[MQTT_TOPIC_TIME] = ntpDateTime();
  101. #endif
  102. root[MQTT_TOPIC_HOSTNAME] = getSetting("hostname");
  103. root[MQTT_TOPIC_IP] = getIP();
  104. String output;
  105. root.printTo(output);
  106. String path = _mqtt_topic + String(MQTT_TOPIC_JSON);
  107. mqttSendRaw(path.c_str(), output.c_str());
  108. for (unsigned char i = 0; i < _mqtt_queue.size(); i++) {
  109. mqtt_message_t element = _mqtt_queue[i];
  110. free(element.topic);
  111. free(element.message);
  112. }
  113. _mqtt_queue.clear();
  114. }
  115. void mqttSend(const char * topic, const char * message, bool force) {
  116. bool useJson = force ? false : _mqtt_use_json;
  117. if (useJson) {
  118. if (_mqtt_queue.size() >= MQTT_QUEUE_MAX_SIZE) _mqttFlush();
  119. mqtt_message_t element;
  120. element.topic = strdup(topic);
  121. element.message = strdup(message);
  122. _mqtt_queue.push_back(element);
  123. _mqtt_flush_ticker.once_ms(MQTT_USE_JSON_DELAY, _mqttFlush);
  124. } else {
  125. String path = _mqtt_topic + String(topic) + _mqtt_getter;
  126. mqttSendRaw(path.c_str(), message);
  127. }
  128. }
  129. void mqttSend(const char * topic, const char * message) {
  130. mqttSend(topic, message, false);
  131. }
  132. void mqttSend(const char * topic, unsigned int index, const char * message, bool force) {
  133. char buffer[strlen(topic)+5];
  134. snprintf_P(buffer, sizeof(buffer), PSTR("%s/%d"), topic, index);
  135. mqttSend(buffer, message, force);
  136. }
  137. void mqttSend(const char * topic, unsigned int index, const char * message) {
  138. mqttSend(topic, index, message, false);
  139. }
  140. void mqttSubscribeRaw(const char * topic) {
  141. if (_mqtt.connected() && (strlen(topic) > 0)) {
  142. #if MQTT_USE_ASYNC
  143. unsigned int packetId = _mqtt.subscribe(topic, _mqtt_qos);
  144. DEBUG_MSG_P(PSTR("[MQTT] Subscribing to %s (PID %d)\n"), topic, packetId);
  145. #else
  146. _mqtt.subscribe(topic, _mqtt_qos);
  147. DEBUG_MSG_P(PSTR("[MQTT] Subscribing to %s\n"), topic);
  148. #endif
  149. }
  150. }
  151. void mqttSubscribe(const char * topic) {
  152. String path = _mqtt_topic + String(topic) + _mqtt_setter;
  153. mqttSubscribeRaw(path.c_str());
  154. }
  155. void mqttUnsubscribeRaw(const char * topic) {
  156. if (_mqtt.connected() && (strlen(topic) > 0)) {
  157. #if MQTT_USE_ASYNC
  158. unsigned int packetId = _mqtt.unsubscribe(topic);
  159. DEBUG_MSG_P(PSTR("[MQTT] Unsubscribing to %s (PID %d)\n"), topic, packetId);
  160. #else
  161. _mqtt.unsubscribe(topic);
  162. DEBUG_MSG_P(PSTR("[MQTT] Unsubscribing to %s\n"), topic);
  163. #endif
  164. }
  165. }
  166. void mqttRegister(mqtt_callback_f callback) {
  167. _mqtt_callbacks.push_back(callback);
  168. }
  169. // -----------------------------------------------------------------------------
  170. // Callbacks
  171. // -----------------------------------------------------------------------------
  172. #if WEB_SUPPORT
  173. void _mqttWebSocketOnSend(JsonObject& root) {
  174. root["mqttVisible"] = 1;
  175. root["mqttStatus"] = mqttConnected();
  176. root["mqttEnabled"] = mqttEnabled();
  177. root["mqttServer"] = getSetting("mqttServer", MQTT_SERVER);
  178. root["mqttPort"] = getSetting("mqttPort", MQTT_PORT);
  179. root["mqttUser"] = getSetting("mqttUser");
  180. root["mqttClientID"] = getSetting("mqttClientID");
  181. root["mqttPassword"] = getSetting("mqttPassword");
  182. root["mqttKeep"] = _mqtt_keepalive;
  183. root["mqttRetain"] = _mqtt_retain;
  184. root["mqttQoS"] = _mqtt_qos;
  185. #if ASYNC_TCP_SSL_ENABLED
  186. root["mqttsslVisible"] = 1;
  187. root["mqttUseSSL"] = getSetting("mqttUseSSL", 0).toInt() == 1;
  188. root["mqttFP"] = getSetting("mqttFP");
  189. #endif
  190. root["mqttTopic"] = getSetting("mqttTopic", MQTT_TOPIC);
  191. root["mqttUseJson"] = getSetting("mqttUseJson", MQTT_USE_JSON).toInt() == 1;
  192. }
  193. #endif
  194. void _mqttCallback(unsigned int type, const char * topic, const char * payload) {
  195. if (type == MQTT_CONNECT_EVENT) {
  196. // Subscribe to internal action topics
  197. mqttSubscribe(MQTT_TOPIC_ACTION);
  198. // Send heartbeat messages
  199. heartbeat();
  200. }
  201. if (type == MQTT_MESSAGE_EVENT) {
  202. // Match topic
  203. String t = mqttSubtopic((char *) topic);
  204. // Actions
  205. if (t.equals(MQTT_TOPIC_ACTION)) {
  206. if (strcmp(payload, MQTT_ACTION_RESET) == 0) {
  207. deferredReset(100, CUSTOM_RESET_MQTT);
  208. }
  209. }
  210. }
  211. }
  212. void _mqttOnConnect() {
  213. DEBUG_MSG_P(PSTR("[MQTT] Connected!\n"));
  214. _mqtt_reconnect_delay = MQTT_RECONNECT_DELAY_MIN;
  215. #if MQTT_SKIP_RETAINED
  216. _mqtt_connected_at = millis();
  217. #endif
  218. // Clean subscriptions
  219. mqttUnsubscribeRaw("#");
  220. // Send connect event to subscribers
  221. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  222. (_mqtt_callbacks[i])(MQTT_CONNECT_EVENT, NULL, NULL);
  223. }
  224. }
  225. void _mqttOnDisconnect() {
  226. DEBUG_MSG_P(PSTR("[MQTT] Disconnected!\n"));
  227. // Send disconnect event to subscribers
  228. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  229. (_mqtt_callbacks[i])(MQTT_DISCONNECT_EVENT, NULL, NULL);
  230. }
  231. }
  232. void _mqttOnMessage(char* topic, char* payload, unsigned int len) {
  233. if (len == 0) return;
  234. char message[len + 1];
  235. strlcpy(message, (char *) payload, len + 1);
  236. #if MQTT_SKIP_RETAINED
  237. if (millis() - _mqtt_connected_at < MQTT_SKIP_TIME) {
  238. DEBUG_MSG_P(PSTR("[MQTT] Received %s => %s - SKIPPED\n"), topic, message);
  239. return;
  240. }
  241. #endif
  242. DEBUG_MSG_P(PSTR("[MQTT] Received %s => %s\n"), topic, message);
  243. // Send message event to subscribers
  244. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  245. (_mqtt_callbacks[i])(MQTT_MESSAGE_EVENT, topic, message);
  246. }
  247. }
  248. void mqttEnabled(bool status) {
  249. _mqtt_enabled = status;
  250. setSetting("mqttEnabled", status ? 1 : 0);
  251. }
  252. bool mqttEnabled() {
  253. return _mqtt_enabled;
  254. }
  255. void mqttConnect() {
  256. // Do not connect if disabled
  257. if (!_mqtt_enabled) return;
  258. // Do not connect if already connected
  259. if (_mqtt.connected()) return;
  260. // Check reconnect interval
  261. static unsigned long last = 0;
  262. if (millis() - last < _mqtt_reconnect_delay) return;
  263. last = millis();
  264. // Increase the reconnect delay
  265. _mqtt_reconnect_delay += MQTT_RECONNECT_DELAY_STEP;
  266. if (_mqtt_reconnect_delay > MQTT_RECONNECT_DELAY_MAX) {
  267. _mqtt_reconnect_delay = MQTT_RECONNECT_DELAY_MAX;
  268. }
  269. char * host = strdup(getSetting("mqttServer", MQTT_SERVER).c_str());
  270. if (strlen(host) == 0) return;
  271. unsigned int port = getSetting("mqttPort", MQTT_PORT).toInt();
  272. if (_mqtt_user) free(_mqtt_user);
  273. if (_mqtt_pass) free(_mqtt_pass);
  274. if (_mqtt_will) free(_mqtt_will);
  275. if (_mqtt_clientid) free(_mqtt_clientid);
  276. _mqtt_user = strdup(getSetting("mqttUser", MQTT_USER).c_str());
  277. _mqtt_pass = strdup(getSetting("mqttPassword", MQTT_PASS).c_str());
  278. _mqtt_will = strdup((_mqtt_topic + MQTT_TOPIC_STATUS).c_str());
  279. _mqtt_clientid = strdup(getSetting("mqttClientID", getIdentifier()).c_str());
  280. DEBUG_MSG_P(PSTR("[MQTT] Connecting to broker at %s:%d\n"), host, port);
  281. #if MQTT_USE_ASYNC
  282. _mqtt.setServer(host, port);
  283. _mqtt.setClientId(_mqtt_clientid);
  284. _mqtt.setKeepAlive(_mqtt_keepalive);
  285. _mqtt.setCleanSession(false);
  286. _mqtt.setWill(_mqtt_will, _mqtt_qos, _mqtt_retain, "0");
  287. if ((strlen(_mqtt_user) > 0) && (strlen(_mqtt_pass) > 0)) {
  288. DEBUG_MSG_P(PSTR("[MQTT] Connecting as user %s\n"), _mqtt_user);
  289. _mqtt.setCredentials(_mqtt_user, _mqtt_pass);
  290. }
  291. #if ASYNC_TCP_SSL_ENABLED
  292. bool secure = getSetting("mqttUseSSL", MQTT_SSL_ENABLED).toInt() == 1;
  293. _mqtt.setSecure(secure);
  294. if (secure) {
  295. DEBUG_MSG_P(PSTR("[MQTT] Using SSL\n"));
  296. unsigned char fp[20] = {0};
  297. if (sslFingerPrintArray(getSetting("mqttFP", MQTT_SSL_FINGERPRINT).c_str(), fp)) {
  298. _mqtt.addServerFingerprint(fp);
  299. } else {
  300. DEBUG_MSG_P(PSTR("[MQTT] Wrong fingerprint\n"));
  301. }
  302. }
  303. #endif // ASYNC_TCP_SSL_ENABLED
  304. DEBUG_MSG_P(PSTR("[MQTT] Client ID: %s\n"), _mqtt_clientid);
  305. DEBUG_MSG_P(PSTR("[MQTT] QoS: %d\n"), _mqtt_qos);
  306. DEBUG_MSG_P(PSTR("[MQTT] Retain flag: %d\n"), _mqtt_retain ? 1 : 0);
  307. DEBUG_MSG_P(PSTR("[MQTT] Will topic: %s\n"), _mqtt_will);
  308. _mqtt.connect();
  309. #else // not MQTT_USE_ASYNC
  310. bool response = true;
  311. #if ASYNC_TCP_SSL_ENABLED
  312. bool secure = getSetting("mqttUseSSL", MQTT_SSL_ENABLED).toInt() == 1;
  313. if (secure) {
  314. DEBUG_MSG_P(PSTR("[MQTT] Using SSL\n"));
  315. if (_mqtt_client_secure.connect(host, port)) {
  316. char fp[60] = {0};
  317. if (sslFingerPrintChar(getSetting("mqttFP", MQTT_SSL_FINGERPRINT).c_str(), fp)) {
  318. if (_mqtt_client_secure.verify(fp, host)) {
  319. _mqtt.setClient(_mqtt_client_secure);
  320. } else {
  321. DEBUG_MSG_P(PSTR("[MQTT] Invalid fingerprint\n"));
  322. response = false;
  323. }
  324. _mqtt_client_secure.stop();
  325. yield();
  326. } else {
  327. DEBUG_MSG_P(PSTR("[MQTT] Wrong fingerprint\n"));
  328. response = false;
  329. }
  330. } else {
  331. DEBUG_MSG_P(PSTR("[MQTT] Client connection failed\n"));
  332. response = false;
  333. }
  334. } else {
  335. _mqtt.setClient(_mqtt_client);
  336. }
  337. #else // not ASYNC_TCP_SSL_ENABLED
  338. _mqtt.setClient(_mqtt_client);
  339. #endif // ASYNC_TCP_SSL_ENABLED
  340. if (response) {
  341. _mqtt.setServer(host, port);
  342. if ((strlen(_mqtt_user) > 0) && (strlen(_mqtt_pass) > 0)) {
  343. DEBUG_MSG_P(PSTR("[MQTT] Connecting as user %s\n"), _mqtt_user);
  344. response = _mqtt.connect(_mqtt_clientid, _mqtt_user, _mqtt_pass, _mqtt_will, _mqtt_qos, _mqtt_retain, "0");
  345. } else {
  346. response = _mqtt.connect(_mqtt_clientid, _mqtt_will, _mqtt_qos, _mqtt_retain, "0");
  347. }
  348. DEBUG_MSG_P(PSTR("[MQTT] Client ID: %s\n"), _mqtt_clientid);
  349. DEBUG_MSG_P(PSTR("[MQTT] QoS: %d\n"), _mqtt_qos);
  350. DEBUG_MSG_P(PSTR("[MQTT] Retain flag: %d\n"), _mqtt_retain ? 1 : 0);
  351. DEBUG_MSG_P(PSTR("[MQTT] Will topic: %s\n"), _mqtt_will);
  352. }
  353. if (response) {
  354. _mqttOnConnect();
  355. } else {
  356. DEBUG_MSG_P(PSTR("[MQTT] Connection failed\n"));
  357. }
  358. #endif // MQTT_USE_ASYNC
  359. free(host);
  360. }
  361. void mqttConfigure() {
  362. // Replace identifier
  363. _mqtt_topic = getSetting("mqttTopic", MQTT_TOPIC);
  364. _mqtt_topic.replace("{identifier}", getSetting("hostname"));
  365. if (!_mqtt_topic.endsWith("/")) _mqtt_topic = _mqtt_topic + "/";
  366. // Getters and setters
  367. _mqtt_setter = getSetting("mqttSetter", MQTT_USE_SETTER);
  368. _mqtt_getter = getSetting("mqttGetter", MQTT_USE_GETTER);
  369. _mqtt_forward = !_mqtt_getter.equals(_mqtt_setter);
  370. // MQTT options
  371. _mqtt_qos = getSetting("mqttQoS", MQTT_QOS).toInt();
  372. _mqtt_retain = getSetting("mqttRetain", MQTT_RETAIN).toInt() == 1;
  373. _mqtt_keepalive = getSetting("mqttKeep", MQTT_KEEPALIVE).toInt();
  374. if (getSetting("mqttClientID").length() == 0) delSetting("mqttClientID");
  375. // Enable
  376. if (getSetting("mqttServer", MQTT_SERVER).length() == 0) {
  377. mqttEnabled(false);
  378. } else {
  379. _mqtt_enabled = getSetting("mqttEnabled", MQTT_ENABLED).toInt() == 1;
  380. }
  381. _mqtt_use_json = (getSetting("mqttUseJson", MQTT_USE_JSON).toInt() == 1);
  382. _mqtt_reconnect_delay = MQTT_RECONNECT_DELAY_MIN;
  383. }
  384. void mqttSetBroker(IPAddress ip, unsigned int port) {
  385. setSetting("mqttServer", ip.toString());
  386. setSetting("mqttPort", port);
  387. mqttEnabled(MQTT_AUTOCONNECT);
  388. }
  389. void mqttSetBrokerIfNone(IPAddress ip, unsigned int port) {
  390. if (!hasSetting("mqttServer")) mqttSetBroker(ip, port);
  391. }
  392. void mqttSetup() {
  393. DEBUG_MSG_P(PSTR("[MQTT] Async %s, SSL %s, Autoconnect %s\n"),
  394. MQTT_USE_ASYNC ? "ENABLED" : "DISABLED",
  395. ASYNC_TCP_SSL_ENABLED ? "ENABLED" : "DISABLED",
  396. MQTT_AUTOCONNECT ? "ENABLED" : "DISABLED"
  397. );
  398. #if MQTT_USE_ASYNC
  399. _mqtt.onConnect([](bool sessionPresent) {
  400. _mqttOnConnect();
  401. });
  402. _mqtt.onDisconnect([](AsyncMqttClientDisconnectReason reason) {
  403. if (reason == AsyncMqttClientDisconnectReason::TCP_DISCONNECTED) {
  404. DEBUG_MSG_P(PSTR("[MQTT] TCP Disconnected\n"));
  405. }
  406. if (reason == AsyncMqttClientDisconnectReason::MQTT_IDENTIFIER_REJECTED) {
  407. DEBUG_MSG_P(PSTR("[MQTT] Identifier Rejected\n"));
  408. }
  409. if (reason == AsyncMqttClientDisconnectReason::MQTT_SERVER_UNAVAILABLE) {
  410. DEBUG_MSG_P(PSTR("[MQTT] Server unavailable\n"));
  411. }
  412. if (reason == AsyncMqttClientDisconnectReason::MQTT_MALFORMED_CREDENTIALS) {
  413. DEBUG_MSG_P(PSTR("[MQTT] Malformed credentials\n"));
  414. }
  415. if (reason == AsyncMqttClientDisconnectReason::MQTT_NOT_AUTHORIZED) {
  416. DEBUG_MSG_P(PSTR("[MQTT] Not authorized\n"));
  417. }
  418. #if ASYNC_TCP_SSL_ENABLED
  419. if (reason == AsyncMqttClientDisconnectReason::TLS_BAD_FINGERPRINT) {
  420. DEBUG_MSG_P(PSTR("[MQTT] Bad fingerprint\n"));
  421. }
  422. #endif
  423. _mqttOnDisconnect();
  424. });
  425. _mqtt.onMessage([](char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
  426. _mqttOnMessage(topic, payload, len);
  427. });
  428. _mqtt.onSubscribe([](uint16_t packetId, uint8_t qos) {
  429. DEBUG_MSG_P(PSTR("[MQTT] Subscribe ACK for PID %d\n"), packetId);
  430. });
  431. _mqtt.onPublish([](uint16_t packetId) {
  432. DEBUG_MSG_P(PSTR("[MQTT] Publish ACK for PID %d\n"), packetId);
  433. });
  434. #else // not MQTT_USE_ASYNC
  435. _mqtt.setCallback([](char* topic, byte* payload, unsigned int length) {
  436. _mqttOnMessage(topic, (char *) payload, length);
  437. });
  438. #endif // MQTT_USE_ASYNC
  439. mqttConfigure();
  440. mqttRegister(_mqttCallback);
  441. #if WEB_SUPPORT
  442. wsOnSendRegister(_mqttWebSocketOnSend);
  443. wsOnAfterParseRegister(mqttConfigure);
  444. #endif
  445. }
  446. void mqttLoop() {
  447. if (WiFi.status() != WL_CONNECTED) return;
  448. #if MQTT_USE_ASYNC
  449. mqttConnect();
  450. #else // not MQTT_USE_ASYNC
  451. if (_mqtt.connected()) {
  452. _mqtt.loop();
  453. } else {
  454. if (_mqtt_connected) {
  455. _mqttOnDisconnect();
  456. _mqtt_connected = false;
  457. }
  458. mqttConnect();
  459. }
  460. #endif
  461. }
  462. #endif // MQTT_SUPPORT