SinricPro Library
Loading...
Searching...
No Matches
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#pragma once
9
10#if defined ESP8266
11 #include <ESP8266WiFi.h>
12#endif
13#if defined ESP32
14 #include <WiFi.h>
15#endif
16
17#include <WiFiUdp.h>
18#include "SinricProQueue.h"
19#include "SinricProConfig.h"
20#include "SinricProDebug.h"
21
22#include "SinricProNamespace.h"
23namespace SINRICPRO_NAMESPACE {
24
25class UdpListener {
26 public:
27 void begin(SinricProQueue_t* receiveQueue);
28 void handle();
29 void sendMessage(String &message);
30 void stop();
31
32 private:
33 WiFiUDP _udp;
34 SinricProQueue_t* receiveQueue;
35};
36
37void UdpListener::begin(SinricProQueue_t* receiveQueue) {
38 this->receiveQueue = receiveQueue;
39 #if defined ESP8266
40 _udp.beginMulticast(WiFi.localIP(), UDP_MULTICAST_IP, UDP_MULTICAST_PORT);
41 #endif
42 #if defined ESP32
43 _udp.beginMulticast(UDP_MULTICAST_IP, UDP_MULTICAST_PORT);
44 #endif
45}
46
47void UdpListener::handle() {
48 int len = _udp.parsePacket();
49 if (!len) return;
50
51 if (len) {
52 char* buf = (char*) malloc(len+1);
53 memset(buf, 0, len+1);
54 _udp.read(buf, len);
55 SinricProMessage* request = new SinricProMessage(IF_UDP, buf);
56 DEBUG_SINRIC("[SinricPro:UDP]: receiving request\r\n%s\r\n", buf);
57 free(buf);
58 receiveQueue->push(request);
59 }
60}
61
62void UdpListener::sendMessage(String &message) {
63 _udp.beginPacket(_udp.remoteIP(), _udp.remotePort());
64 _udp.print(message);
65 _udp.endPacket();
66 // restart UDP??
67 #if defined ESP8266
68 _udp.beginMulticast(WiFi.localIP(), UDP_MULTICAST_IP, UDP_MULTICAST_PORT);
69 #endif
70 #if defined ESP32
71 _udp.beginMulticast(UDP_MULTICAST_IP, UDP_MULTICAST_PORT);
72 #endif
73}
74
75void UdpListener::stop() {
76 _udp.stop();
77}
78
79} // SINRICPRO_NAMESPACE