SinricPro Library
SinricProUDP.h
1 /*
2  * Copyright (c) 2019 Sinric. All rights reserved.
3  * Licensed under Creative Commons Attribution-Share Alike (CC BY-SA)
4  *
5  * This file is part of the Sinric Pro (https://github.com/sinricpro/)
6  */
7 
8 #ifndef __SINRIC_PRO_UDP_H__
9 #define __SINRIC_PRO_UDP_H__
10 
11 #if defined ESP8266
12  #include <ESP8266WiFi.h>
13 #endif
14 #if defined ESP32
15  #include <WiFi.h>
16 #endif
17 
18 #include <WiFiUdp.h>
19 #include "SinricProQueue.h"
20 
21 class udpListener {
22 public:
23  void begin(SinricProQueue_t* receiveQueue);
24  void handle();
25  void sendMessage(String &message);
26  void stop();
27 private:
28  WiFiUDP _udp;
29  SinricProQueue_t* receiveQueue;
30 };
31 
32 void udpListener::begin(SinricProQueue_t* receiveQueue) {
33  this->receiveQueue = receiveQueue;
34  #if defined ESP8266
35  _udp.beginMulticast(WiFi.localIP(), UDP_MULTICAST_IP, UDP_MULTICAST_PORT);
36  #endif
37  #if defined ESP32
38  _udp.beginMulticast(UDP_MULTICAST_IP, UDP_MULTICAST_PORT);
39  #endif
40 }
41 
42 void udpListener::handle() {
43  if (!_udp.available()) return;
44  int len = _udp.parsePacket();
45  if (len) {
46 
47  char buffer[1024];
48  int n = _udp.read(buffer, 1024);
49  buffer[n] = 0;
50  SinricProMessage* request = new SinricProMessage(IF_UDP, buffer);
51  DEBUG_SINRIC("[SinricPro:UDP]: receiving request\r\n");
52  receiveQueue->push(request);
53  }
54 }
55 
56 void udpListener::sendMessage(String &message) {
57  _udp.beginPacket(_udp.remoteIP(), _udp.remotePort());
58  _udp.print(message);
59  _udp.endPacket();
60  // restart UDP??
61  #if defined ESP8266
62  _udp.beginMulticast(WiFi.localIP(), UDP_MULTICAST_IP, UDP_MULTICAST_PORT);
63  #endif
64  #if defined ESP32
65  _udp.beginMulticast(UDP_MULTICAST_IP, UDP_MULTICAST_PORT);
66  #endif
67 }
68 
69 /*
70 void udpListener::sendMessage(String &message) {
71  WiFiUDP UDPsender;
72  UDPsender.beginPacket(_udp.remoteIP(), _udp.remotePort());
73  UDPsender.print(message);
74  UDPsender.endPacket();
75 }
76 */
77 
78 void udpListener::stop() {
79  _udp.stop();
80 }
81 
82 #endif