Skip to content

Commit 0924dc6

Browse files
authored
Merge pull request #42 from zuf/with_location
With location
2 parents 71620c3 + 9aea78a commit 0924dc6

File tree

6 files changed

+248
-35
lines changed

6 files changed

+248
-35
lines changed

README.md

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,7 @@ ESP8266 (SDK v2.6+), ESP32
102102
- [Оформление текста](#textmode)
103103
- [Отправка файлов](#files)
104104
- [Скачивание файлов](#download)
105+
- [Местоположение](#location)
105106
- [Всякие трюки](#tricks)
106107
- [Версии](#versions)
107108
- [Баги и обратная связь](#feedback)
@@ -377,6 +378,7 @@ String FB_64str(int64_t id); // перевод из int64_t в String
377378
#define FB_NO_URLENCODE // отключить конвертацию urlencode для исходящих сообщений (чуть ускорит программу)
378379
#define FB_NO_OTA // отключить поддержку OTA обновлений из чата
379380
#define FB_DYNAMIC // включить динамический режим: библиотека дольше выполняет запрос, но занимает на 10 кб меньше памяти в SRAM
381+
#define FB_WITH_LOCATION // включить дополнительное поле location (содержащее широту и долготу) в сообщении (см примеры location и sunPosition)
380382
```
381383

382384
<a id="usage"></a>
@@ -748,6 +750,32 @@ void newMsg(FB_msg& msg) {
748750
}
749751
```
750752
753+
<a id="location"></a>
754+
## Местоположение
755+
При указанной настройке `#define FB_WITH_LOCATION` бот добавляет поле `location` в обрабатываемые сообщения (FB_msg):
756+
757+
```cpp
758+
struct FB_Location {
759+
String &latitude;
760+
String &longitude;
761+
};
762+
```
763+
764+
В случае если боту прислали географическое местоположение (location), то поля latitude/longitude
765+
заполняюися координатами из полученного ботом location:
766+
767+
```cpp
768+
// обработчик сообщений
769+
void newMsg(FB_msg& msg) {
770+
if (msg.location.latitude.length() > 0 && msg.location.longitude.length() > 0) {
771+
bot.sendMessage("Lat: " + msg.location.latitude + ", Lon: " + msg.location.longitude, msg.chatID);
772+
}
773+
}
774+
```
775+
776+
См примеры `examples/location` и `examples/sunPosition`.
777+
778+
751779
<a id="tricks"></a>
752780
## Трюки
753781
### Перезагрузка

README_EN.md

Lines changed: 62 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -72,33 +72,35 @@ For comparison, a minimum example was used with sending a message to the chat an
7272
- Refresh Request: 1 second
7373

7474
## Content
75-
- [installation] (# Install)
76-
- [initialization] (#init)
77-
- [documentation] (#docs)
78-
- [use] (#usage)
79-
- [sending messages] (# SEND)
80-
- [Parsing messages] (#inbox)
81-
- [ticker] (#tick)
82-
- [Minimum example] (# Example)
83-
- [appeal to messages] (#msgid)
84-
- [System Settlement] (#sticker)
85-
- [menu] (#menu)
86-
- [ordinary menu] (# BASIC)
87-
- [Inline menu] (#inline)
88-
- [Inline menu with collbe] (#callb)
89-
- [response to collback] (# Anter)
90-
- [time module] (#unix)
91-
- [The time of receipt of the message] (#time)
92-
- [Real Time Watch] (# RTC)
93-
- [Chat firmware update] (# OTA)
94-
- [text design] (#textmode)
95-
- [Sending files] (#files)
96-
- [download files] (#download)
97-
- [all sorts of tricks] (#tricks)
98-
- [versions] (#varsions)
99-
- [bugs and feedback] (#fedback)
100-
101-
<a id="install"> </a>
75+
- [Install](#install)
76+
- [Initialization](#init)
77+
- [Documentation](#docs)
78+
- [Usage](#usage)
79+
- [Sending messages](#send)
80+
- [Message Parsing](#inbox)
81+
- [Ticker](#tick)
82+
- [Minimal Example](#example)
83+
- [Referring to messages](#msgid)
84+
- [Send stickers](#sticker)
85+
- [Menu](#menu)
86+
- [Normal menu](#basic)
87+
- [Inline menu](#inline)
88+
- [Inline menu with callback](#callb)
89+
- [Response to callback](#answer)
90+
- [Time module](#unix)
91+
- [Time to receive message](#time)
92+
- [Real Time Clock](#rtc)
93+
- [Firmware update from chat](#ota)Cranberry
94+
- [Text styling](#textmode)
95+
- [Sending files](#files)
96+
- [Download files](#download)
97+
- [Location](#location)
98+
- [All sorts of tricks](#tricks)
99+
- [Versions](#versions)
100+
- [Bugs and feedback](#feedback)
101+
102+
<a id="install"></a>
103+
102104
## Installation
103105
- The library can be found by the name ** farbot ** and installed through the library manager in:
104106
- Arduino ide
@@ -361,13 +363,14 @@ Int64_T FB_STR64 (COST String & S);// Translating from String to Int64_T
361363
String fb_64str (int64_t ID);// Translation from int64_t to string
362364

363365

364-
// ========== The defines of settings ==============
365-
// announce before connecting the library
366-
#define fb_no_unicode // Disable Unicode converting for incoming messages (slightly accelerate the program)
367-
#define fb_no_urlencode // Disable Urlencode converting for outgoing messages (slightly accelerate the program)
368-
#define fb_no_ota // Disable OTA support for updates from chat
369-
#define fb_dynamic // Turn on the dynamic mode: the library executes a query longer, but takes 10 kb less memory in SRAM
370-
`` `
366+
// ========== DEFINE SETTINGS ===========
367+
// declare BEFORE linking the library
368+
#define FB_NO_UNICODE // disable Unicode conversion for incoming messages (slightly speed up the program)
369+
#define FB_NO_URLENCODE // disable urlencode conversion for outgoing messages (slightly speeds up the program)
370+
#define FB_NO_OTA // disable support for OTA updates from chat
371+
#define FB_DYNAMIC // enable dynamic mode: the library takes longer to execute the request, but takes up 10 kb less memory in SRAM
372+
#define FB_WITH_LOCATION // enable location fields in message (FB_msg)
373+
```
371374
372375
<a id="usage"> </a>
373376
## Usage
@@ -738,7 +741,31 @@ VOID NewMSG (FB_MSG & MSG) {
738741
}
739742
`` `
740743
741-
<a id="tricks"> </a>
744+
<a id="location"></a>
745+
## Location
746+
If defined `#define FB_WITH_LOCATION` bot append `location` field into message (FB_msg):
747+
748+
```cpp
749+
struct FB_Location {
750+
String &latitude;
751+
String &longitude;
752+
};
753+
```
754+
755+
Fields latitude/longitude will be filled if bot received location from user.
756+
757+
```cpp
758+
void newMsg(FB_msg& msg) {
759+
if (msg.location.latitude.length() > 0 && msg.location.longitude.length() > 0) {
760+
bot.sendMessage("Lat: " + msg.location.latitude + ", Lon: " + msg.location.longitude, msg.chatID);
761+
}
762+
}
763+
```
764+
765+
See examples in `examples/location` and `examples/sunPosition`.
766+
767+
<a id="tricks"></a>
768+
742769
## Tricks
743770
### Reboot
744771
Messages are noted read at the next (relative to the current message processor) update in Tick (), that is, after at least a tuned timeout.

examples/location/locationBot.ino

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
// бот отправляет географические координаты в ответ на полученное местоположение (location)
2+
3+
#define WIFI_SSID "login"
4+
#define WIFI_PASS "pass"
5+
#define BOT_TOKEN "2654326546:asjhAsfAsfkllgUsaOuiz_axfkj_AsfkjhB"
6+
#define FB_WITH_LOCATION // enable location in FB_msg
7+
8+
#include <FastBot.h>
9+
FastBot bot(BOT_TOKEN);
10+
11+
void setup() {
12+
connectWiFi();
13+
14+
bot.attach(newMsg);
15+
}
16+
17+
// обработчик сообщений
18+
void newMsg(FB_msg& msg) {
19+
// выводим всю информацию о сообщении
20+
Serial.println(msg.toString());
21+
22+
// в ответ на присланное местоположение (location) бот отправляет его координаты
23+
if (msg.location.latitude.length() > 0 && msg.location.longitude.length() > 0) {
24+
bot.sendMessage("Latitude: " + msg.location.latitude + ", Longitude: " + msg.location.longitude, msg.chatID);
25+
} else {
26+
bot.sendMessage("Unknown location", msg.chatID);
27+
}
28+
}
29+
30+
void loop() {
31+
bot.tick();
32+
}
33+
34+
void connectWiFi() {
35+
delay(2000);
36+
Serial.begin(115200);
37+
Serial.println();
38+
39+
WiFi.begin(WIFI_SSID, WIFI_PASS);
40+
while (WiFi.status() != WL_CONNECTED) {
41+
delay(500);
42+
Serial.print(".");
43+
if (millis() > 15000) ESP.restart();
44+
}
45+
Serial.println("Connected");
46+
}
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
// бот отправляет в ответ на присланное местоположение (location) австрономические данные о солнце (восход, заход, длительность светового дня)
2+
// полученные с помощью библиотеки https://github.com/GyverLibs/SunPosition
3+
4+
#define WIFI_SSID "login"
5+
#define WIFI_PASS "pass"
6+
#define BOT_TOKEN "2654326546:asjhAsfAsfkllgUsaOuiz_axfkj_AsfkjhB"
7+
#define FB_WITH_LOCATION // enable location in FB_msg
8+
9+
#include <SunPosition.h> // https://github.com/GyverLibs/SunPosition
10+
#include <FastBot.h>
11+
FastBot bot(BOT_TOKEN);
12+
13+
void setup() {
14+
connectWiFi();
15+
16+
bot.attach(newMsg);
17+
}
18+
19+
String dayTimeStr(int minutesFromMidnight) {
20+
int hour = minutesFromMidnight / 60;
21+
int min = minutesFromMidnight % 60;
22+
23+
String hs(hour);
24+
String ms(min);
25+
26+
if (hour < 10) { hs = "0" + hs; }
27+
if (min < 10) { ms = "0" + ms; }
28+
29+
30+
String s = hs + ":" + ms;
31+
return s;
32+
}
33+
34+
// обработчик сообщений
35+
void newMsg(FB_msg& msg) {
36+
// выводим всю информацию о сообщении
37+
Serial.println(msg.toString());
38+
39+
// в ответ на присланное местоположение (location) бот отправляет положение солнца
40+
if (msg.location.latitude.length() > 0 && msg.location.longitude.length() > 0) {
41+
int utcOffset = 3*60; // UTC +0300 (Moscow)
42+
SunPosition sun(msg.location.latitude.toFloat(), msg.location.longitude.toFloat(), msg.unix, utcOffset);
43+
44+
String s= "Sunrise:\t" + dayTimeStr(sun.sunrise()) + "\n";
45+
s += "Sunset:\t" + dayTimeStr(sun.sunset()) + "\n";
46+
s += "Noon:\t" + dayTimeStr(sun.noon()) + "\n";
47+
s += "Daylight time:\t" + dayTimeStr(sun.daylight()) + "\n";
48+
s += "\n";
49+
s += "Location: " + msg.location.latitude + ", " + msg.location.longitude + "\n";
50+
s += "Unix time: " + String(msg.unix) + "\n\n";
51+
s += "https://github.com/GyverLibs/SunPosition";
52+
53+
bot.sendMessage(s, msg.chatID);
54+
} else {
55+
bot.sendMessage("Unknown location", msg.chatID);
56+
}
57+
}
58+
59+
void loop() {
60+
bot.tick();
61+
}
62+
63+
void connectWiFi() {
64+
delay(2000);
65+
Serial.begin(115200);
66+
Serial.println();
67+
68+
WiFi.begin(WIFI_SSID, WIFI_PASS);
69+
while (WiFi.status() != WL_CONNECTED) {
70+
delay(500);
71+
Serial.print(".");
72+
if (millis() > 15000) ESP.restart();
73+
}
74+
Serial.println("Connected");
75+
}

src/FastBot.h

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1271,6 +1271,19 @@ uint8_t editMessageMenuCallback(int32_t msgid, const String& text, const String&
12711271
String data;
12721272
find(str, data, textPos, F("\"data\":\""), '\"', IDpos);
12731273

1274+
#ifdef FB_WITH_LOCATION
1275+
bool location = find(str, F("\"location\""), textPos, IDpos);
1276+
String lat;
1277+
String lon;
1278+
FB_Location fb_location {lat, lon};
1279+
if (location) {
1280+
find(str, lat, textPos, F("\"latitude\":"), ',', IDpos);
1281+
find(str, lon, textPos, F("\"longitude\":"), '}', IDpos);
1282+
1283+
Serial.printf("Location: lat=%s, lon=%s\n", lat, lon);
1284+
}
1285+
#endif
1286+
12741287
#ifndef FB_NO_UNICODE
12751288
FB_unicode(first_name);
12761289
FB_unicode(text);
@@ -1298,6 +1311,9 @@ uint8_t editMessageMenuCallback(int32_t msgid, const String& text, const String&
12981311
first_name,
12991312
first_name,
13001313
_lastUsrMsg,
1314+
#ifdef FB_WITH_LOCATION
1315+
fb_location
1316+
#endif
13011317
};
13021318
_callback(msg);
13031319
if (_query_ptr) answer(); // отвечаем на коллбэк, если юзер не ответил

src/datatypes.h

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,13 @@ enum FB_FileType {
1010
FB_VOICE,
1111
};
1212

13+
#ifdef FB_WITH_LOCATION
14+
struct FB_Location {
15+
String &latitude;
16+
String &longitude;
17+
};
18+
#endif
19+
1320
struct FB_msg {
1421
String& userID; // ID юзера
1522
String& username; // ник (в API это first_name)
@@ -32,6 +39,10 @@ struct FB_msg {
3239
String& first_name; // имя
3340
String& last_name; // фамилия
3441
int32_t ID; // ID сообщения
42+
43+
#ifdef FB_WITH_LOCATION
44+
FB_Location location;
45+
#endif
3546

3647
// вся информация одной строкой
3748
String toString() {
@@ -80,6 +91,16 @@ struct FB_msg {
8091
s += F("unix: ");
8192
s += unix;
8293
s += '\n';
94+
95+
#ifdef FB_WITH_LOCATION
96+
s += F("location: ");
97+
s += F("lat=");
98+
s += location.latitude;
99+
s += F(", lon=");
100+
s += location.longitude;
101+
s += '\n';
102+
#endif
103+
83104
return s;
84105
}
85106
};

0 commit comments

Comments
 (0)