forked from CytronTechnologies/pxt-esp8266
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtelegram.ts
85 lines (67 loc) · 2.5 KB
/
telegram.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/*******************************************************************************
* Functions for Telegram
*
* Company: Cytron Technologies Sdn Bhd
* Website: http://www.cytron.io
* Email: [email protected]
*******************************************************************************/
// Telegram API url.
const TELEGRAM_API_URL = "10.10.10.214"
namespace esp8266 {
// Flag to indicate whether the Telegram message was sent successfully.
let telegramMessageSent = false
/**
* Return true if the Telegram message was sent successfully.
*/
//% subcategory="Telegram"
//% weight=30
//% blockGap=8
//% blockId=esp8266_is_telegram_message_sent
//% block="Telegram message sent"
export function isTelegramMessageSent(): boolean {
return telegramMessageSent
}
/**
* Send Telegram message.
* @param apiKey Telegram API Key.
* @param chatId The chat ID we want to send message to.
*/
//% subcategory="Telegram"
//% weight=29
//% blockGap=8
//% blockId=esp8266_send_telegram_message
//% block="send message to Telegram:|API Key %apiKey|Chat ID %chatId|Message %message"
export function sendTelegramMessage(apiKey: string, chatId: string, message: string) {
// Reset the upload successful flag.
telegramMessageSent = false
// Make sure the WiFi is connected.
if (isWifiConnected() == false) return
// Connect to Telegram. Return if failed.
if (sendCommand("AT+CIPSTART=\"TCP\",\"" + TELEGRAM_API_URL + "\",1880", "OK", 10000) == false) return
// Construct the data to send.
let data = "POST /esp8266"
data += " HTTP/1.1\r\n"
data += "Host: " + TELEGRAM_API_URL + "\r\n"
// Send the data.
sendCommand("AT+CIPSEND=" + (data.length + 2))
sendCommand(data)
// Return if "SEND OK" is not received.
if (getResponse("SEND OK", 1000) == "") {
// Close the connection and return.
sendCommand("AT+CIPCLOSE", "OK", 1000)
return
}
// Validate the response from Telegram.
let response = getResponse("\"ok\":true", 1000)
if (response == "") {
// Close the connection and return.
sendCommand("AT+CIPCLOSE", "OK", 1000)
return
}
// Close the connection.
sendCommand("AT+CIPCLOSE", "OK", 1000)
// Set the upload successful flag and return.
telegramMessageSent = true
return
}
}