Skip to content
Snippets Groups Projects
CommsBehaviours.hpp 2.23 KiB
Newer Older
Joe Revans's avatar
Joe Revans committed
#ifndef COMMS_BEHAVIOUR_h
#define COMMS_BEHAVIOUR_h
#include "Arduino.h"
#include "Behaviours.h"
Joe Revans's avatar
Joe Revans committed
#include <VizBlocks.h>
Joe Revans's avatar
Joe Revans committed

/*
 * --------------------------------------------------
 * ---------------- SendCapabilities ----------------
 * --------------------------------------------------
 */

class SendCapabilities : public Behaviour {
Joe Revans's avatar
Joe Revans committed
   VizBlocks* _node;
Joe Revans's avatar
Joe Revans committed

public:
Joe Revans's avatar
Joe Revans committed
  SendCapabilities(VizBlocks* node, String name = "SendCapabilities") :
Joe Revans's avatar
Joe Revans committed
    Behaviour(name), _node(node){ }

  String start(String args) {
    //This is where you do your stuff for a simple behaviour
    _node->announce_capabilities();
    return "SendCapabilities behaviour " + _name;
  }

};

/*
 * --------------------------------------------------
 * ---------------------- Link ----------------------
 * --------------------------------------------------
 */

class Link : public Behaviour {
Joe Revans's avatar
Joe Revans committed
  VizBlocks* _node;
Joe Revans's avatar
Joe Revans committed
  String _peerId;
  const int _timeoutInterval = 5000;
  unsigned long _t = 0;

public:
Joe Revans's avatar
Joe Revans committed
  Link(VizBlocks* node, String name = "Link") : Behaviour(name), _node(node)  { _background = true; }
Joe Revans's avatar
Joe Revans committed

  char* args() {return "<String peerId>"; };

  String start(String args) {
    _running = true;
    if (args == name() || args.indexOf(" ")>0) {
      return "Invalid args (" + args + ") in behaviour " + name();
    }

    _t = millis();

    if (args == _peerId) {
      return "Link ping from (" + _peerId + ")";
    }

    _peerId = args;

    String str = "{\"id\":\"" + String(_node->getId()) + "\",\"Link\":{\"peerId\":\"" + _peerId + "\"}}";
    _node->announce(str);

    return "New link with (" + _peerId + ")";
  }

  void update() {
    if (millis() > (_t+_timeoutInterval)) {
      String str = "{\"id\":\"" + String(_node->getId()) + "\",\"Unlink\":{\"peerId\":\"" + _peerId + "\"}}";
     _node->announce(str);
      _peerId = "";
      _running = false;
    }
  }

};

/*
 * --------------------------------------------------
 * ------------------- PingServer -------------------
 * --------------------------------------------------
 */

class PingServer : public Behaviour {
Joe Revans's avatar
Joe Revans committed
  VizBlocks* _node;
Joe Revans's avatar
Joe Revans committed
  String str;
  const int _interval = 4000;
  unsigned long _t = 0;

public:
  PingServer(VizBlocks* node, String name = "PingServer");
  String start(String args);
  void update();
Joe Revans's avatar
Joe Revans committed

};

#endif