├── esp-doorbell ├── .gitignore ├── esp-doorbell-config.h.example ├── Sip.h ├── esp-doorbell.ino └── Sip.cpp ├── CHANGELOG.md ├── LICENSE.md ├── README.md └── CONTRIBUTING.md /esp-doorbell/.gitignore: -------------------------------------------------------------------------------- 1 | esp-doorbell-config.h 2 | -------------------------------------------------------------------------------- /esp-doorbell/esp-doorbell-config.h.example: -------------------------------------------------------------------------------- 1 | #define WIFI_SSID "YOUR_WIFI_SSID" 2 | #define WIFI_PASSWORD "YOUR_WIFI_PASSWORD" 3 | 4 | #define SIP_USER "YOUR_SIP_USER"; 5 | #define SIP_PASSWORD "YOUR_SIP_PASSWORD"; 6 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to `esp-doorbell` will be documented in this file 4 | 5 | ## 0.1.0 - 2020-08-26 6 | 7 | - Initial release 8 | 9 | ## 0.2.0 - 2020-08-26 10 | 11 | - Transitioning from the TR-064 protocol to the SIP protocol 12 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Lukas Müller 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Make a smart doorbell using the ESP32 2 | 3 | This repository contains the code for making an ESP32-based doorbell that initiates a SIP call. While the code currently only initiates a SIP call and thus makes your phone(s)ring, it might be extended in the future to also provide intercom functionalities. 4 | 5 | Take a look at the [Heise article](https://www.heise.de/select/ct/2018/17/1534215254552977) and the [Reichelt article](https://www.reichelt.de/magazin/how-to/smarte-tuerklingel/) to get started. Additionally, the [mikrocontroller.net thread](https://www.mikrocontroller.net/topic/442157) might be useful. 6 | These articles serve as foundation for this project. But of course there are some differences: 7 | - This project uses an ESP32 instead of an ESP8266. 8 | - This project does not reset the ESP32 every time someone rings the bell. Instead a GPIO pin is used for waking up the ESP32 from deep sleep. This ensures that the ESP32 will not be reset continuously if someone keeps ringing the doorbell. 9 | - This project does not make use of the TR-064 protocol but instead of the SIP protocol. 10 | - The code is optimized for ease of use (it requires only minimal and non-sensitive config) and performance (it buffers the WiFi settings so that connecting to the WiFi is fast). 11 | 12 | ## Tips & Tricks 13 | 14 | Here are some tips that might be handy: 15 | - In your router you only need to setup a new IP phone and obtain the credentials. 16 | - Create the [esp-doorbell-config.h](esp-doorbell/esp-doorbell-config.h) file based on the [esp-doorbell-config.h.example](esp-doorbell/esp-doorbell-config.h.example) file and add your credentials in there. 17 | - Depending on the lenght of the wire to your door bell button, you might want to use a different resistance/LED to ensure that the optocoupler works properly (especially if you use only a low supply voltage). 18 | - Make sure to add the [ESP32 board manager](https://dl.espressif.com/dl/package_esp32_index.json) and install the [TR-064-SOAP-Library](https://github.com/Aypac/Arduino-TR-064-SOAP-Library) in the Arduino IDE. 19 | 20 | ## Changelog 21 | 22 | Please see [CHANGELOG](CHANGELOG.md) for more information what has changed recently. 23 | 24 | ## Contributing 25 | 26 | Please see [CONTRIBUTING](CONTRIBUTING.md) for details. 27 | 28 | ## Security 29 | 30 | If you discover any security related issues, please email [lukas@aerdes.com](mailto:lukas@aerdes.com) instead of using the issue tracker. 31 | 32 | ## Postcardware 33 | 34 | You are free to use this sketch, but if it makes it to your production environment we highly appreciate you sending us a postcard from your hometown. The address is: Lukas Müller, Dirklangendwarsstraat 5, 2611HZ Delft, The Netherlands. 35 | 36 | ## License 37 | 38 | The MIT License (MIT). Please see [LICENSE](LICENSE.md) for more information. 39 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Contributions are **welcome** and will be fully **credited**. 4 | 5 | Please read and understand the contribution guide before creating an issue or pull request. 6 | 7 | ## Etiquette 8 | 9 | This project is open source, and as such, the maintainers give their free time to build and maintain the source code 10 | held within. They make the code freely available in the hope that it will be of use to other developers. It would be 11 | extremely unfair for them to suffer abuse or anger for their hard work. 12 | 13 | Please be considerate towards maintainers when raising issues or presenting pull requests. Let's show the 14 | world that developers are civilized and selfless people. 15 | 16 | It's the duty of the maintainer to ensure that all submissions to the project are of sufficient 17 | quality to benefit the project. Many developers have different skillsets, strengths, and weaknesses. Respect the maintainer's decision, and do not be upset or abusive if your submission is not used. 18 | 19 | ## Viability 20 | 21 | When requesting or submitting new features, first consider whether it might be useful to others. Open 22 | source projects are used by many developers, who may have entirely different needs to your own. Think about 23 | whether or not your feature is likely to be used by other users of the project. 24 | 25 | ## Procedure 26 | 27 | Before filing an issue: 28 | 29 | - Attempt to replicate the problem, to ensure that it wasn't a coincidental incident. 30 | - Check to make sure your feature suggestion isn't already present within the project. 31 | - Check the pull requests tab to ensure that the bug doesn't have a fix in progress. 32 | - Check the pull requests tab to ensure that the feature isn't already in progress. 33 | 34 | Before submitting a pull request: 35 | 36 | - Check the codebase to ensure that your feature doesn't already exist. 37 | - Check the pull requests to ensure that another person hasn't already submitted the feature or fix. 38 | 39 | ## Requirements 40 | 41 | If the project maintainer has any additional requirements, you will find them listed here. 42 | 43 | - **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date. 44 | 45 | - **Consider our release cycle** - We try to follow [SemVer v2.0.0](https://semver.org/). Randomly breaking public APIs is not an option. 46 | 47 | - **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. 48 | 49 | - **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](https://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting. 50 | 51 | **Happy coding**! 52 | -------------------------------------------------------------------------------- /esp-doorbell/Sip.h: -------------------------------------------------------------------------------- 1 | /* ==================================================================== 2 | * 3 | * Copyright (c) 2018 Juerge Liegner All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without 6 | * modification, are permitted provided that the following conditions 7 | * are met: 8 | * 9 | * 1. Redistributions of source code must retain the above copyright 10 | * notice, this list of conditions and the following disclaimer. 11 | * 12 | * 2. Redistributions in binary form must reproduce the above copyright 13 | * notice, this list of conditions and the following disclaimer in 14 | * the documentation and/or other materials provided with the 15 | * distribution. 16 | * 17 | * 3. Neither the name of the author(s) nor the names of any contributors 18 | * may be used to endorse or promote products derived from this software 19 | * without specific prior written permission. 20 | * 21 | * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) AND CONTRIBUTORS "AS IS" AND 22 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 23 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 24 | * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR(S) OR CONTRIBUTORS BE LIABLE 25 | * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 26 | * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 27 | * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 28 | * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 29 | * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 30 | * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 31 | * SUCH DAMAGE. 32 | * 33 | * ====================================================================*/ 34 | 35 | /* ==================================================================== 36 | * 37 | * edited by: Alois 38 | * created: 07.01.2020 16:56:53 39 | * 40 | * changes: DTMF via SIP INFO added 41 | * 42 | * ====================================================================*/ 43 | 44 | #ifndef _SIP_h 45 | #define _SIP_h 46 | 47 | #include 48 | #include 49 | 50 | class Sip 51 | { 52 | private: 53 | char* pbuf; 54 | size_t lbuf; 55 | char caRead[256]; 56 | 57 | const char* pSipIp; 58 | int iSipPort; 59 | const char* pSipUser; 60 | const char* pSipPassWd; 61 | const char* pMyIp; 62 | int iMyPort; 63 | const char* pDialNr; 64 | const char* pDialDesc; 65 | 66 | uint32_t callid; 67 | uint32_t tagid; 68 | uint32_t branchid; 69 | 70 | int iAuthCnt; 71 | int iTerminated; 72 | uint32_t iRingTime; 73 | uint32_t iMaxTime; 74 | int iDialRetries; 75 | int iLastCSeq; 76 | void AddSipLine(const char* constFormat, ...); 77 | bool AddCopySipLine(const char* p, const char* psearch); 78 | bool ParseParameter(char* dest, int destlen, const char* name, const char* line, char cq = '\"'); 79 | bool ParseReturnParams(const char* p); 80 | int GrepInteger(const char* p, const char* psearch); 81 | void Ack(const char* pIn); 82 | void Cancel(int seqn); 83 | void Bye(int cseq); 84 | void Ok(const char* pIn); 85 | void Invite(const char* pIn = 0); 86 | 87 | uint32_t Millis(); 88 | uint32_t Random(); 89 | int SendUdp(); 90 | void MakeMd5Digest(char* pOutHex33, char* pIn); 91 | 92 | public: 93 | Sip(); 94 | void Init(const char* SipIp, int SipPort, const char* MyIp, int MyPort, const char* SipUser, const char* SipPassWd, int MaxDialSec = 30); 95 | void Wait(); 96 | void HandleUdpPacket(const char* p); 97 | bool Dial(const char* DialNr, const char* DialDesc = ""); 98 | int iSignal; 99 | bool IsBusy() { return (iRingTime != 0 || iTerminated != 1); } 100 | static WiFiUDP Udp; 101 | }; 102 | 103 | #endif 104 | -------------------------------------------------------------------------------- /esp-doorbell/esp-doorbell.ino: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include "esp-doorbell-config.h" 7 | #include "Sip.h" 8 | 9 | // The SSID of your WLAN 10 | const char* wifi_ssid = WIFI_SSID; 11 | // The password of your WLANs 12 | const char* wifi_password = WIFI_PASSWORD; 13 | // The network name of your ESP32 14 | const char* wifi_host = "doorbell"; 15 | 16 | // The SIP user 17 | const char* sip_user = SIP_USER; 18 | // The password associated with the SIP user above 19 | const char* sip_password = SIP_PASSWORD; 20 | // The SIP port 21 | const int sip_port = 5060; 22 | 23 | // Number that the doorbell calls 24 | const char* ring_number = "**1"; 25 | // Time that the doorbell rings (in s) 26 | const int ring_time = 10; 27 | // The name that is displayed on the phones 28 | const char* ring_name = "Doorbell"; 29 | 30 | // The WLAN configuration buffer 31 | RTC_DATA_ATTR byte wifi_mac[6] = {0, 0, 0, 0, 0, 0}; 32 | RTC_DATA_ATTR byte wifi_channel = 0; 33 | RTC_DATA_ATTR char wifi_ip[16]; 34 | RTC_DATA_ATTR char wifi_gateway[16]; 35 | RTC_DATA_ATTR char wifi_mask[16]; 36 | RTC_DATA_ATTR char wifi_dns[16]; 37 | RTC_DATA_ATTR int wifi_buffered = 0; 38 | 39 | // Function to put ESP32 into deep sleep 40 | void esp_sleep(void) { 41 | Serial.println("Preparing deep sleep..."); 42 | esp_sleep_pd_config(ESP_PD_DOMAIN_RTC_PERIPH, ESP_PD_OPTION_ON); 43 | gpio_pullup_en(GPIO_NUM_33); 44 | const uint64_t mask = 1ULL << 33; 45 | esp_sleep_enable_ext1_wakeup(mask, ESP_EXT1_WAKEUP_ALL_LOW); 46 | esp_sleep_enable_timer_wakeup(21600000000); // 6 hours 47 | Serial.println("Prepared deep sleep."); 48 | 49 | Serial.println("Going to deep sleep"); 50 | Serial.println(""); 51 | esp_deep_sleep_start(); 52 | } 53 | 54 | // Function to connect to WiFi 55 | void wifi_connect(void) { 56 | Serial.println("Connecting to WiFi..."); 57 | 58 | WiFi.persistent(false); 59 | WiFi.mode(WIFI_STA); 60 | 61 | if( wifi_buffered != 0 ) { 62 | Serial.println("Found buffered WiFi config"); 63 | Serial.println("Connecting to WiFi using this config"); 64 | IPAddress temp_ip, temp_gateway, temp_mask, temp_dns; 65 | temp_ip.fromString(wifi_ip); 66 | temp_gateway.fromString(wifi_gateway); 67 | temp_mask.fromString(wifi_mask); 68 | temp_dns.fromString(wifi_dns); 69 | WiFi.config(temp_ip, temp_gateway, temp_mask, temp_dns); 70 | WiFi.begin(wifi_ssid, wifi_password, wifi_channel, wifi_mac); 71 | } else { 72 | Serial.println("Did not find buffered WiFi config"); 73 | Serial.println("Conneting to WiFi using SSID and password only"); 74 | WiFi.begin(wifi_ssid, wifi_password); 75 | } 76 | 77 | WiFi.setHostname(wifi_host); 78 | 79 | int retries = 0; 80 | int wifi_status = WiFi.status(); 81 | while( wifi_status != WL_CONNECTED ) { 82 | retries++; 83 | if( retries == 100 ) { 84 | // This is called after 5s 85 | Serial.println("Could not connect to WiFi"); 86 | Serial.println("Retrying using SSID and password only"); 87 | WiFi.disconnect(); 88 | delay(50); 89 | wifi_buffered = 0; 90 | WiFi.begin(wifi_ssid, wifi_password); 91 | } 92 | if( retries == 600 ) { 93 | // This is called after 30s 94 | Serial.println("Could not connect to WiFi"); 95 | Serial.println("Aborting"); 96 | WiFi.disconnect(true); 97 | delay(50); 98 | Serial.println("Restarting"); 99 | Serial.println(""); 100 | ESP.restart(); 101 | } 102 | delay(50); 103 | wifi_status = WiFi.status(); 104 | } 105 | 106 | Serial.println("Connected to WiFi."); 107 | } 108 | 109 | // Function to buffer WiFi config 110 | void wifi_buffer(void) { 111 | if ( wifi_buffered == 0 ) { 112 | Serial.println("Buffering WiFi config (to speedup next WiFi connection)..."); 113 | uint8_t* bssid; 114 | bssid = WiFi.BSSID(); 115 | for (uint32_t i = 0; i < sizeof(wifi_mac); i++) wifi_mac[i] = bssid[i]; 116 | WiFi.localIP().toString().toCharArray(wifi_ip, 16); 117 | WiFi.gatewayIP().toString().toCharArray(wifi_gateway, 16); 118 | WiFi.subnetMask().toString().toCharArray(wifi_mask, 16); 119 | WiFi.dnsIP().toString().toCharArray(wifi_dns, 16);; 120 | wifi_buffered = 1; 121 | Serial.println("Buffered WiFi config (to speedup next WiFi connection)."); 122 | } 123 | } 124 | 125 | // Function to initiate a SIP call 126 | void sip_init(void) { 127 | Serial.println("Initiating the SIP call..."); 128 | Sip sip_client; 129 | sip_client.Init(wifi_gateway, sip_port, wifi_ip, sip_port, sip_user, sip_password, ring_time); 130 | sip_client.Dial(ring_number, ring_name); 131 | sip_client.Wait(); 132 | Serial.println("Initiated the SIP call."); 133 | } 134 | 135 | // Main process 136 | void setup() { 137 | Serial.begin(115200); 138 | Serial.println("ESP32 has woken up"); 139 | 140 | wifi_connect(); 141 | 142 | esp_sleep_wakeup_cause_t wakeup_reason = esp_sleep_get_wakeup_cause(); 143 | if ( wakeup_reason == ESP_SLEEP_WAKEUP_EXT1 ) { 144 | // Make sure that SIP call is only initiated if the ESP is woken up by pressing the GPIO button 145 | Serial.println("Waked-up source was EXT1"); 146 | sip_init(); 147 | } else if ( wakeup_reason == ESP_SLEEP_WAKEUP_TIMER ) { 148 | // Make sure that the ESP is restarted incidentially (to avoid connection issues) 149 | Serial.println("Waked-up source was TIMER"); 150 | Serial.println("Going to restart ESP"); 151 | ESP.restart(); 152 | } 153 | 154 | wifi_buffer(); 155 | 156 | esp_sleep(); 157 | } 158 | 159 | // We will never enter the loop as we are always going to deep sleep in the setup method 160 | void loop(){ 161 | } 162 | -------------------------------------------------------------------------------- /esp-doorbell/Sip.cpp: -------------------------------------------------------------------------------- 1 | /* ==================================================================== 2 | * 3 | * Copyright (c) 2018 Juerge Liegner All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without 6 | * modification, are permitted provided that the following conditions 7 | * are met: 8 | * 9 | * 1. Redistributions of source code must retain the above copyright 10 | * notice, this list of conditions and the following disclaimer. 11 | * 12 | * 2. Redistributions in binary form must reproduce the above copyright 13 | * notice, this list of conditions and the following disclaimer in 14 | * the documentation and/or other materials provided with the 15 | * distribution. 16 | * 17 | * 3. Neither the name of the author(s) nor the names of any contributors 18 | * may be used to endorse or promote products derived from this software 19 | * without specific prior written permission. 20 | * 21 | * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) AND CONTRIBUTORS "AS IS" AND 22 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 23 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 24 | * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR(S) OR CONTRIBUTORS BE LIABLE 25 | * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 26 | * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 27 | * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 28 | * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 29 | * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 30 | * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 31 | * SUCH DAMAGE. 32 | * 33 | * ====================================================================*/ 34 | 35 | /* ==================================================================== 36 | * 37 | * edited by: Alois 38 | * created: 07.01.2020 16:56:53 39 | * 40 | * changes: DTMF via SIP INFO added 41 | * 42 | * ====================================================================*/ 43 | 44 | #include 45 | #include "Sip.h" 46 | 47 | char caSipIn[2048]; 48 | char caSipOut[2048]; 49 | 50 | Sip::Sip() 51 | { 52 | pbuf = caSipOut; 53 | lbuf = sizeof(caSipOut); 54 | pDialNr = ""; 55 | pDialDesc = ""; 56 | } 57 | 58 | bool Sip::Dial(const char* DialNr, const char* DialDesc) 59 | { 60 | if (iRingTime) 61 | return false; 62 | iTerminated = 0; 63 | iDialRetries = 0; 64 | pDialNr = DialNr; 65 | pDialDesc = DialDesc; 66 | Invite(); 67 | iDialRetries++; 68 | iRingTime = Millis(); 69 | return true; 70 | } 71 | 72 | void Sip::Cancel(int cseq) 73 | { 74 | if (caRead[0] == 0) 75 | return; 76 | pbuf[0] = 0; 77 | AddSipLine("%s sip:%s@%s SIP/2.0", "CANCEL", pDialNr, pSipIp); 78 | AddSipLine("%s", caRead); 79 | AddSipLine("CSeq: %i %s", cseq, "CANCEL"); 80 | AddSipLine("Max-Forwards: 70"); 81 | AddSipLine("User-Agent: sip-client/0.0.1"); 82 | AddSipLine("Content-Length: 0"); 83 | AddSipLine(""); 84 | SendUdp(); 85 | iSignal = 0; 86 | } 87 | 88 | void Sip::Bye(int cseq) 89 | { 90 | if (caRead[0] == 0) 91 | return; 92 | pbuf[0] = 0; 93 | AddSipLine("%s sip:%s@%s SIP/2.0", "BYE", pDialNr, pSipIp); 94 | AddSipLine("%s", caRead); 95 | AddSipLine("CSeq: %i %s", cseq, "BYE"); 96 | AddSipLine("Max-Forwards: 70"); 97 | AddSipLine("User-Agent: sip-client/0.0.1"); 98 | AddSipLine("Content-Length: 0"); 99 | AddSipLine(""); 100 | SendUdp(); 101 | iSignal = 0; 102 | } 103 | 104 | void Sip::Ack(const char* p) 105 | { 106 | char ca[32]; 107 | bool b = ParseParameter(ca, (int)sizeof(ca), "To: <", p, '>'); 108 | if (!b) 109 | return; 110 | 111 | pbuf[0] = 0; 112 | AddSipLine("ACK %s SIP/2.0", ca); 113 | AddCopySipLine(p, "Call-ID: "); 114 | int cseq = GrepInteger(p, "\nCSeq: "); 115 | AddSipLine("CSeq: %i ACK", cseq); 116 | AddCopySipLine(p, "From: "); 117 | AddCopySipLine(p, "Via: "); 118 | AddCopySipLine(p, "To: "); 119 | AddSipLine("Content-Length: 0"); 120 | AddSipLine(""); 121 | SendUdp(); 122 | } 123 | 124 | void Sip::Ok(const char* p) 125 | { 126 | pbuf[0] = 0; 127 | AddSipLine("SIP/2.0 200 OK"); 128 | AddCopySipLine(p, "Call-ID: "); 129 | AddCopySipLine(p, "CSeq: "); 130 | AddCopySipLine(p, "From: "); 131 | AddCopySipLine(p, "Via: "); 132 | AddCopySipLine(p, "To: "); 133 | AddSipLine("Content-Length: 0"); 134 | AddSipLine(""); 135 | SendUdp(); 136 | } 137 | 138 | void Sip::Init(const char* SipIp, int SipPort, const char* MyIp, int MyPort, const char* SipUser, const char* SipPassWd, int MaxDialSec) 139 | { 140 | caRead[0] = 0; 141 | pbuf[0] = 0; 142 | pSipIp = SipIp; 143 | iSipPort = SipPort; 144 | pSipUser = SipUser; 145 | pSipPassWd = SipPassWd; 146 | pMyIp = MyIp; 147 | iMyPort = MyPort; 148 | iAuthCnt = 0; 149 | iRingTime = 0; 150 | iMaxTime = MaxDialSec * 1000; 151 | Udp.begin(iSipPort); 152 | } 153 | 154 | void Sip::AddSipLine(const char* constFormat, ...) 155 | { 156 | va_list arglist; 157 | va_start(arglist, constFormat); 158 | uint16_t l = (uint16_t)strlen(pbuf); 159 | char* p = pbuf + l; 160 | vsnprintf(p, lbuf - l, constFormat, arglist); 161 | va_end(arglist); 162 | l = (uint16_t)strlen(pbuf); 163 | if (l < (lbuf - 2)) 164 | { 165 | pbuf[l] = '\r'; 166 | pbuf[l + 1] = '\n'; 167 | pbuf[l + 2] = 0; 168 | } 169 | } 170 | 171 | // call invite without or with the response from peer 172 | void Sip::Invite(const char* p) 173 | { 174 | // prevent loops 175 | if (p && iAuthCnt > 3) 176 | return; 177 | 178 | // using caRead for temp. store realm and nonce 179 | char* caRealm = caRead; 180 | char* caNonce = caRead + 128; 181 | 182 | char* haResp = 0; 183 | int cseq = 1; 184 | if (!p) 185 | { 186 | iAuthCnt = 0; 187 | if (iDialRetries == 0) 188 | { 189 | callid = Random(); 190 | tagid = Random(); 191 | branchid = Random(); 192 | } 193 | } 194 | else 195 | { 196 | cseq = 2; 197 | if (ParseParameter(caRealm, 128, " realm=\"", p) 198 | && ParseParameter(caNonce, 128, " nonce=\"", p)) 199 | { 200 | // using output buffer to build the md5 hashes 201 | // store the md5 haResp to end of buffer 202 | char* ha1Hex = pbuf; 203 | char* ha2Hex = pbuf + 33; 204 | haResp = pbuf + lbuf - 34; 205 | char* pTemp = pbuf + 66; 206 | 207 | snprintf(pTemp, lbuf - 100, "%s:%s:%s", pSipUser, caRealm, pSipPassWd); 208 | MakeMd5Digest(ha1Hex, pTemp); 209 | 210 | snprintf(pTemp, lbuf - 100, "INVITE:sip:%s@%s", pDialNr, pSipIp); 211 | MakeMd5Digest(ha2Hex, pTemp); 212 | 213 | snprintf(pTemp, lbuf - 100, "%s:%s:%s", ha1Hex, caNonce, ha2Hex); 214 | MakeMd5Digest(haResp, pTemp); 215 | } 216 | else 217 | { 218 | caRead[0] = 0; 219 | return; 220 | } 221 | } 222 | pbuf[0] = 0; 223 | AddSipLine("INVITE sip:%s@%s SIP/2.0", pDialNr, pSipIp); 224 | AddSipLine("Call-ID: %010u@%s", callid, pMyIp); 225 | AddSipLine("CSeq: %i INVITE", cseq); 226 | AddSipLine("Max-Forwards: 70"); 227 | // not needed for fritzbox 228 | // AddSipLine("User-Agent: sipdial by jl"); 229 | AddSipLine("From: \"%s\" ;tag=%010u", pDialDesc, pSipUser, pSipIp, tagid); 230 | AddSipLine("Via: SIP/2.0/UDP %s:%i;branch=%010u;rport=%i", pMyIp, iMyPort, branchid, iMyPort); 231 | AddSipLine("To: ", pDialNr, pSipIp); 232 | AddSipLine("Contact: \"%s\" ", pSipUser, pSipUser, pMyIp, iMyPort); 233 | if (p) 234 | { 235 | // authentication 236 | AddSipLine("Authorization: Digest username=\"%s\", realm=\"%s\", nonce=\"%s\", uri=\"sip:%s@%s\", response=\"%s\"", pSipUser, caRealm, caNonce, pDialNr, pSipIp, haResp); 237 | iAuthCnt++; 238 | } 239 | AddSipLine("Content-Type: application/sdp"); 240 | // not needed for fritzbox 241 | // AddSipLine("Allow: INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, NOTIFY, MESSAGE, SUBSCRIBE, INFO"); 242 | AddSipLine("Content-Length: 0"); 243 | AddSipLine(""); 244 | caRead[0] = 0; 245 | SendUdp(); 246 | } 247 | 248 | // parse parameter value from http formated string 249 | bool Sip::ParseParameter(char* dest, int destlen, const char* name, const char* line, char cq) 250 | { 251 | const char* qp; 252 | const char* r; 253 | if ((r = strstr(line, name)) != NULL) 254 | { 255 | r = r + strlen(name); 256 | qp = strchr(r, cq); 257 | int l = qp - r; 258 | if (l < destlen) 259 | { 260 | strncpy(dest, r, l); 261 | dest[l] = 0; 262 | return true; 263 | } 264 | } 265 | return false; 266 | } 267 | 268 | // search a line in response date (p) and append on 269 | // pbuf 270 | bool Sip::AddCopySipLine(const char* p, const char* psearch) 271 | { 272 | char* pa = strstr((char*)p, psearch); 273 | if (pa) 274 | { 275 | char* pe = strstr(pa, "\r"); 276 | if (pe == 0) 277 | pe = strstr(pa, "\n"); 278 | if (pe > pa) 279 | { 280 | char c = *pe; 281 | *pe = 0; 282 | AddSipLine("%s", pa); 283 | *pe = c; 284 | return true; 285 | } 286 | } 287 | return false; 288 | } 289 | 290 | int Sip::GrepInteger(const char* p, const char* psearch) 291 | { 292 | int param = -1; 293 | const char* pc = strstr(p, psearch); 294 | if (pc) 295 | { 296 | param = atoi(pc + strlen(psearch)); 297 | } 298 | return param; 299 | } 300 | 301 | // copy Call-ID, From, Via and To from response 302 | // to caRead 303 | // using later for BYE or CANCEL the call 304 | bool Sip::ParseReturnParams(const char* p) 305 | { 306 | pbuf[0] = 0; 307 | AddCopySipLine(p, "Call-ID: "); 308 | AddCopySipLine(p, "From: "); 309 | AddCopySipLine(p, "Via: "); 310 | AddCopySipLine(p, "To: "); 311 | if (strlen(pbuf) >= 2) 312 | { 313 | strcpy(caRead, pbuf); 314 | caRead[strlen(caRead) - 2] = 0; 315 | } 316 | return true; 317 | } 318 | 319 | void Sip::HandleUdpPacket(const char* p) 320 | { 321 | uint32_t iWorkTime = iRingTime ? (Millis() - iRingTime) : 0; 322 | if (iRingTime && iWorkTime > iMaxTime) 323 | { 324 | // Cancel(3); 325 | Bye(3); 326 | iRingTime = 0; 327 | } 328 | 329 | if (!p) 330 | { 331 | // max 5 dial retry when loos first invite packet 332 | if (iAuthCnt == 0 && iDialRetries < 5 && iWorkTime >(iDialRetries * 200)) 333 | { 334 | iDialRetries++; 335 | delay(30); 336 | Invite(); 337 | } 338 | return; 339 | } 340 | 341 | if (strstr(p, "SIP/2.0 401 Unauthorized") == p) 342 | { 343 | Ack(p); 344 | // call Invite with response data (p) to build auth md5 hashes 345 | Invite(p); 346 | } 347 | else if (strstr(p, "BYE") == p) 348 | { 349 | Ok(p); 350 | iRingTime = 0; 351 | } 352 | else if (strstr(p, "SIP/2.0 200") == p) // OK 353 | { 354 | ParseReturnParams(p); 355 | Ack(p); 356 | } 357 | else if (strstr(p, "SIP/2.0 183 ") == p // Session Progress 358 | || strstr(p, "SIP/2.0 180 ") == p) // Ringing 359 | { 360 | ParseReturnParams(p); 361 | } 362 | else if (strstr(p, "SIP/2.0 100 ") == p) // Trying 363 | { 364 | ParseReturnParams(p); 365 | Ack(p); 366 | } 367 | else if (strstr(p, "SIP/2.0 486 ") == p // Busy Here 368 | || strstr(p, "SIP/2.0 603 ") == p // Decline 369 | || strstr(p, "SIP/2.0 487 ") == p) // Request Terminated 370 | { 371 | Ack(p); 372 | iRingTime = 0; 373 | iTerminated = 1; 374 | } 375 | else if (strstr(p, "INFO") == p) 376 | { 377 | iLastCSeq = GrepInteger(p, "\nCSeq: "); 378 | iSignal = GrepInteger(p, "\nSignal="); 379 | Ok(p); 380 | } 381 | } 382 | 383 | int Sip::SendUdp() 384 | { 385 | Udp.beginPacket(pSipIp, iSipPort); 386 | //Udp.write(pbuf, strlen(pbuf)); 387 | Udp.write((uint8_t *) pbuf, strlen(pbuf)); 388 | Udp.endPacket(); 389 | return 0; 390 | } 391 | 392 | // generate a 30 bit random number 393 | uint32_t Sip::Random() 394 | { 395 | return esp_random(); 396 | } 397 | 398 | uint32_t Sip::Millis() 399 | { 400 | return (uint32_t)millis() + 1; 401 | } 402 | 403 | void Sip::MakeMd5Digest(char* pOutHex33, char* pIn) 404 | { 405 | MD5Builder aMd5; 406 | aMd5.begin(); 407 | aMd5.add(pIn); 408 | aMd5.calculate(); 409 | aMd5.getChars(pOutHex33); 410 | } 411 | 412 | void Sip::Wait() 413 | { 414 | while (IsBusy()) { 415 | int packetSize = Udp.parsePacket(); 416 | if (packetSize > 0) { 417 | caSipIn[0] = 0; 418 | packetSize = Udp.read(caSipIn, sizeof(caSipIn)); 419 | if (packetSize > 0) 420 | { 421 | caSipIn[packetSize] = 0; 422 | } 423 | } 424 | HandleUdpPacket((packetSize > 0) ? caSipIn : 0); 425 | } 426 | } 427 | 428 | WiFiUDP Sip::Udp; 429 | 430 | --------------------------------------------------------------------------------