queue.ino 2.22 KB
#include "queue.h"

void insert(char *command, double start, double duration, int level) {
  struct action *ptr = head;
  // no dupes, only create new if it is scheduled
  while(ptr != NULL) {
    if (    command == T_PUMPLEVEL
         || command == T_PUMPDURATION
         || command == T_PUMPABORT
         &&
            ptr->command == T_PUMPLEVEL
         || ptr->command == T_PUMPDURATION
         ) {
      break;
    }
  }
  if ( ptr == NULL ) {
    ptr = (struct action*) malloc(sizeof(struct action));
    ptr->next = NULL;
    ptr->command = command;
    ptr->running = 0;

    // in an empty list, this is head
    if (head == NULL) {
      head = ptr;
    }

    // previous tail is not last anymore
    if (tail != NULL) {
      tail->next = ptr;
    }

    // this is now tail
    tail = ptr;
  }
  if ( command == T_PUMPABORT ) {
    ptr->end = 1;
    ptr->running = 1;
  } else {
    ptr->start = start;
    ptr->duration = duration;
    ptr->level = level;
  }
}

void loop_queue() {
  struct action *ptr = head;
  struct action *next = NULL;
  struct action *prev = NULL;
  unsigned int ut = time(NULL);

  while(ptr != NULL) {
    next=ptr->next;
    Serial.println("---------------");
    Serial.println(ptr->command);
    Serial.println(ptr->running);
    Serial.println(ut);
    Serial.println(ptr->start);
    Serial.println(ptr->end);
    Serial.println(ptr->duration);
    Serial.println("---------------");

    /////////////////////////  start action
    if ( ptr->running == 0
         && ut >= ptr->start
         ) {
      if ( pump_start(ptr) ) { // pump is blocked ?
        ptr->end = ptr->duration + ut;
        ptr->running = 1;
      } else {
        ptr->start++;
      }
    }

    /////////////////////////   action
    if ( ptr->running == 1 ) {
      pump_running(ptr);
    }

    /////////////////////////   end action
    if ( ptr->running == 1
         && ut >= ptr->end
         ) {
      pump_end(ptr);

      /* action is due to removal */

      if (prev != NULL) {
        prev->next = ptr->next;
      }

      if (ptr == head) {
        head = ptr->next;
      }

      if (ptr == tail) {
        tail = prev;
      }
      free(ptr);
    } else {
      prev = ptr;
    }
    ptr = next;
  }
}

void setup_queue() {
}