Skip to content

Instantly share code, notes, and snippets.

@KatsuhiroMorishita
Last active January 25, 2018 14:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KatsuhiroMorishita/f7be2461d390a29706e6ff4b2b9c3874 to your computer and use it in GitHub Desktop.
Save KatsuhiroMorishita/f7be2461d390a29706e6ff4b2b9c3874 to your computer and use it in GitHub Desktop.
Blynkのnotifyは一度送信すると15秒ほど不感知となり、送信リクエストが失われます。 そこで、リクエストされたメッセージを取りこぼすことなく送信するためのクラスを作成しました。実際に利用する際はクラスを.cppファイルとしてご利用ください。なお、その場合は#include<Arduino.h>の追記が必要です。
/*************************
blynkのnotifyは一度送信すると10秒ほど不感知となり、送信リクエストが失われます。
そこで、リクエストされたメッセージを取りこぼすことなく送信するためのクラスを作成しました。
author: Katsuhiro Morishita
created: 2018-01-25
lisence: MIT
**************************/
#include <Blynk.h>
#include <BlynkSimpleStream.h>
// blynkにnotifyを送るためのクラス
// http://docs.blynk.cc/#widgets-notifications
class blynk_queue
{
private:
long time; // 送信時刻
int wp; // メッセージを書き込むアドレス(リングバッファ方式とする)
int rp; // メッセージを読み込むアドレス
static const int size_ = 5; // 送信待ちできるメッセージの数
static const int len = 50; // 1回当たりのメッセージのサイズ(最後にヌル文字を格納するので、文字数はlen-1)
char buff[size_][len]; // メッセージを格納する2次元配列
BlynkStream* _blynk;
public:
// 送信して欲しい文字列を渡す(受け付けられると1を返す)
int set_msg(char msg[]) {
if ((this->wp + 1) % this->size_ == this->rp) return 0;
int k = 0;
for (; k < len - 1; k++) { // 引数の中身をコピーする
char c = msg[k];
if (c == 0) break;
this->buff[this->wp][k] = c;
}
this->buff[this->wp][k] = 0; // 最後にヌル文字を格納
this->wp = (this->wp + 1) % this->size_; // 次の書き込みアドレスを計算
return 1;
}
// 送信していないメッセージが残っていて、且つ前回より10秒経っていれば送信する
void run() {
if (this->wp == this->rp) return; // no request
if (millis() - this->time < 15000) return; // 前回の送信から時間が経っていない
char temp_buff[len]; // データのコピー
for (int k = 0; k < len; k++) {
char c = this->buff[this->rp][k];
temp_buff[k] = c;
}
//Serial.print("print from queue: "); // for test
//Serial.println(temp_buff);
this->_blynk->notify(temp_buff);
this->rp = (this->rp + 1) % this->size_; // 次の読み出しアドレスを計算する
this->time = millis();
}
// コンストラクタ(初期化する関数)
blynk_queue(BlynkStream* blynk_obj) {
this->time = millis();
this->wp = 0;
this->rp = 0;
this->_blynk = blynk_obj;
for (int i = 0; i < this->size_; i++) {
for (int k = 0; k < this->len; k++) {
this->buff[i][k] = 0;
}
}
}
};
char auth[] = "*************";
blynk_queue queue(&Blynk);
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
Blynk.begin(Serial, auth);
}
void loop() {
// put your main code here, to run repeatedly:
String t = String(millis());
char fuga[50];
t.toCharArray(fuga, 50);
queue.set_msg(fuga);
queue.run();
delay(1000);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment