<commit_before>#define CATCH_CONFIG_MAIN
#include "catch.hpp"

#include "gaf_master.h"
#include "readjsonsource.h"

#if GAF_TEST_JSON
#include "gaf_rapidjson_master.h"
#endif

using Catch::Matchers::Equals;
template<typename T>
struct Vector : public std::vector<T>
{
  Vector<T>& operator<<(const T& t) {this->push_back(t); return *this;}
};

TEST_CASE("custom vector equals works") {
  std::vector<int> a;
  a.push_back(1);
  a.push_back(2);
  a.push_back(3);

  REQUIRE_THAT(a, Equals(Vector<int>() << 1 << 2 << 3));
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// standard

TEST_CASE("std constructor") {
  Standard fb;
  REQUIRE(fb.a == 0);
  REQUIRE(fb.b == 0);
  REQUIRE(fb.c == 0);
  REQUIRE(fb.d == 0);
  REQUIRE(fb.ua == 0);
  REQUIRE(fb.ub == 0);
  REQUIRE(fb.uc == 0);
  REQUIRE(fb.ud == 0);
  REQUIRE(fb.e == 0);
  REQUIRE(fb.f == false);
  REQUIRE(fb.g == 0);
  REQUIRE(fb.h == 0);
  REQUIRE(fb.i == "");
}

#if GAF_TEST_JSON

TEST_CASE("std json") {
  Standard fb;
  const std::string load = ReadJsonSource(&fb,
    "{\
    \"a\": 1,\
    \"b\": 2,\
    \"c\": 3,\
    \"d\": 4,\
    \"ua\": 5,\
    \"ub\": 6,\
    \"uc\": 7,\
    \"ud\": 8,\
    \"e\": 9,\
    \"f\": true,\
    \"g\": 10.0,\
    \"h\": 11.0,\
    \"i\": \"dog\"}"
  );
  REQUIRE(load == "");

  REQUIRE(fb.a == 1);
  REQUIRE(fb.b == 2);
  REQUIRE(fb.c == 3);
  REQUIRE(fb.d == 4);
  REQUIRE(fb.ua == 5);
  REQUIRE(fb.ub == 6);
  REQUIRE(fb.uc == 7);
  REQUIRE(fb.ud == 8);
  REQUIRE(fb.e == 9);
  REQUIRE(fb.f == true);
  REQUIRE(fb.g == 10.0);
  REQUIRE(fb.h == 11.0);
  REQUIRE(fb.i == "dog");
}

#endif

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// arrays

TEST_CASE("array constructor") {
  Arrays fb;
  REQUIRE(fb.a.size() == 0);
  REQUIRE(fb.b.size() == 0);
  REQUIRE(fb.c.size() == 0);
  REQUIRE(fb.d.size() == 0);
  REQUIRE(fb.ua.size() == 0);
  REQUIRE(fb.ub.size() == 0);
  REQUIRE(fb.uc.size() == 0);
  REQUIRE(fb.ud.size() == 0);
  REQUIRE(fb.e.size() == 0);
  REQUIRE(fb.f.size() == 0);
  REQUIRE(fb.g.size() == 0);
  REQUIRE(fb.h.size() == 0);
  REQUIRE(fb.i.size() == 0);
  REQUIRE(fb.standard.size() == 0);
}

#if GAF_TEST_JSON

TEST_CASE("array empty json") {
  Arrays advanced;

  const std::string load = ReadJsonSource(&advanced, "{}");
  REQUIRE(load != "");
}

TEST_CASE("array basic json") {
  Arrays fb;
  const std::string load = ReadJsonSource(&fb,
    "{\
    \"a\": [],\
    \"b\": [],\
    \"c\": [],\
    \"d\": [],\
    \"ua\": [],\
    \"ub\": [],\
    \"uc\": [],\
    \"ud\": [],\
    \"e\": [],\
    \"f\": [],\
    \"g\": [],\
    \"h\": [],\
    \"i\": [],\
    \"standard\": []}"
  );
  REQUIRE(load == "");

  REQUIRE(fb.a.size() == 0);
  REQUIRE(fb.b.size() == 0);
  REQUIRE(fb.c.size() == 0);
  REQUIRE(fb.d.size() == 0);
  REQUIRE(fb.ua.size() == 0);
  REQUIRE(fb.ub.size() == 0);
  REQUIRE(fb.uc.size() == 0);
  REQUIRE(fb.ud.size() == 0);
  REQUIRE(fb.e.size() == 0);
  REQUIRE(fb.f.size() == 0);
  REQUIRE(fb.g.size() == 0);
  REQUIRE(fb.h.size() == 0);
  REQUIRE(fb.i.size() == 0);
  REQUIRE(fb.standard.size() == 0);
}

// todo: parse standard too
TEST_CASE("arrays advanced json") {
  Arrays fb;
  const std::string load = ReadJsonSource(&fb,
    "{\
    \"a\": [1, 2],\
    \"b\": [3, 4],\
    \"c\": [5, 6],\
    \"d\": [7, 8],\
    \"ua\": [9, 10],\
    \"ub\": [11, 12],\
    \"uc\": [13, 14],\
    \"ud\": [15, 16],\
    \"e\": [17, 18],\
    \"f\": [false, true],\
    \"g\": [19, 20],\
    \"h\": [21, 22],\
    \"i\": [\"cat\", \"dog\"],\
    \"standard\": []}"
  );
  REQUIRE(load == "");

  REQUIRE_THAT(fb.a, Equals(Vector<std::int8_t>()  << 1 << 2));
  REQUIRE_THAT(fb.b, Equals(Vector<std::int16_t>() << 3 << 4));
  REQUIRE_THAT(fb.c, Equals(Vector<std::int32_t>() << 5 << 6));
  REQUIRE_THAT(fb.d, Equals(Vector<std::int64_t>() << 7 << 8));

  REQUIRE_THAT(fb.ua, Equals(Vector<std::uint8_t>()   << 9 << 10));
  REQUIRE_THAT(fb.ub, Equals(Vector<std::uint16_t>() << 11 << 12));
  REQUIRE_THAT(fb.uc, Equals(Vector<std::uint32_t>() << 13 << 14));
  REQUIRE_THAT(fb.ud, Equals(Vector<std::uint64_t>() << 15 << 16));

  REQUIRE_THAT(fb.e, Equals(Vector<char>() << 17 << 18));
  REQUIRE_THAT(fb.f, Equals(Vector<bool>() << false << true));
  REQUIRE_THAT(fb.g, Equals(Vector<float>() << 19 << 20));
  REQUIRE_THAT(fb.h, Equals(Vector<double>() << 21 << 22));

  REQUIRE_THAT(fb.i, Equals(Vector<std::string>() << "cat" << "dog"));
}

#endif

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// optional

TEST_CASE("pointer constructor") {
  Foo foo;
  REQUIRE(foo.value == nullptr);

  FooRoot bar;
  REQUIRE(bar.name == nullptr);
  REQUIRE(bar.foo == nullptr);
}

TEST_CASE("optional constructor") {
  Bar foo;
  REQUIRE(foo.value == 0);

  BarRoot bar;
  REQUIRE(bar.name == "");
  REQUIRE(bar.foo.value == 0);
}

#if GAF_TEST_JSON

TEST_CASE("pointer json_basic") {
  Foo foo;
  const std::string load = ReadJsonSource(&foo, " {\"value\": 12} ");
  REQUIRE(load == "");
  REQUIRE(foo.value != nullptr);
  REQUIRE(*foo.value == 12);
}

TEST_CASE("optional json_basic") {
  Bar foo;
  const std::string load = ReadJsonSource(&foo, " {\"value\": 12} ");
  REQUIRE(load == "");
  REQUIRE(foo.value == 12);
}

TEST_CASE("pointer json_missing_foo") {
  FooRoot bar;
  const std::string load = ReadJsonSource(&bar, " {\"name\": \"good dog\"} ");
  REQUIRE(load == "");
  REQUIRE(bar.name != nullptr);
  REQUIRE(*bar.name == "good dog");
  REQUIRE(bar.foo == nullptr);
}

TEST_CASE("optional json_missing_foo") {
  BarRoot bar;
  const std::string load = ReadJsonSource(&bar, " {\"name\": \"good dog\"} ");
  REQUIRE(load == "");
  REQUIRE(bar.name == "good dog");
  REQUIRE(bar.foo.value == 0);
}

TEST_CASE("pointer json_invalid_value_for_name") {
  // optional means optional, not accept if invalid
  FooRoot bar;
  const std::string load = ReadJsonSource(&bar, " {\"name\": 3} ");
  REQUIRE(load != "");
}

TEST_CASE("optional json_invalid_value_for_name") {
  // optional means optional, not accept if invalid
  BarRoot bar;
  const std::string load = ReadJsonSource(&bar, " {\"name\": 3} ");
  REQUIRE(load != "");
}

TEST_CASE("pointer json_empty_document") {
  FooRoot bar;
  const std::string load = ReadJsonSource(&bar, "{}");
  REQUIRE(load == "");
  REQUIRE(bar.name == nullptr);
  REQUIRE(bar.foo == nullptr);
}

TEST_CASE("optional json_empty_document") {
  BarRoot bar;
  const std::string load = ReadJsonSource(&bar, "{}");
  REQUIRE(load == "");
  REQUIRE(bar.name == "");
  REQUIRE(bar.foo.value == 0);
}

TEST_CASE("pointer json_optional_struct") {
  FooRoot bar;
  const std::string load = ReadJsonSource(&bar, "{\"foo\": {\"value\": 5}}");
  REQUIRE(load == "");
  CHECK(bar.name == nullptr);
  CHECK(bar.foo != nullptr);
  CHECK(bar.foo->value != nullptr);
  CHECK(*bar.foo->value == 5);
}

TEST_CASE("optional json_optional_struct") {
  BarRoot bar;
  const std::string load = ReadJsonSource(&bar, "{\"foo\": {\"value\": 5}}");
  REQUIRE(load == "");
  CHECK(bar.name == "");
  CHECK(bar.foo.value == 5);
}

#endif

<commit_msg>fix: double/float warning<commit_after>#define CATCH_CONFIG_MAIN
#include "catch.hpp"

#include "gaf_master.h"
#include "readjsonsource.h"

#if GAF_TEST_JSON
#include "gaf_rapidjson_master.h"
#endif

using Catch::Matchers::Equals;
template<typename T>
struct Vector : public std::vector<T>
{
  Vector<T>& operator<<(const T& t) {this->push_back(t); return *this;}
};

TEST_CASE("custom vector equals works") {
  std::vector<int> a;
  a.push_back(1);
  a.push_back(2);
  a.push_back(3);

  REQUIRE_THAT(a, Equals(Vector<int>() << 1 << 2 << 3));
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// standard

TEST_CASE("std constructor") {
  Standard fb;
  REQUIRE(fb.a == 0);
  REQUIRE(fb.b == 0);
  REQUIRE(fb.c == 0);
  REQUIRE(fb.d == 0);
  REQUIRE(fb.ua == 0);
  REQUIRE(fb.ub == 0);
  REQUIRE(fb.uc == 0);
  REQUIRE(fb.ud == 0);
  REQUIRE(fb.e == 0);
  REQUIRE(fb.f == false);
  REQUIRE(fb.g == 0);
  REQUIRE(fb.h == 0);
  REQUIRE(fb.i == "");
}

#if GAF_TEST_JSON

TEST_CASE("std json") {
  Standard fb;
  const std::string load = ReadJsonSource(&fb,
    "{\
    \"a\": 1,\
    \"b\": 2,\
    \"c\": 3,\
    \"d\": 4,\
    \"ua\": 5,\
    \"ub\": 6,\
    \"uc\": 7,\
    \"ud\": 8,\
    \"e\": 9,\
    \"f\": true,\
    \"g\": 10.0,\
    \"h\": 11.0,\
    \"i\": \"dog\"}"
  );
  REQUIRE(load == "");

  REQUIRE(fb.a == 1);
  REQUIRE(fb.b == 2);
  REQUIRE(fb.c == 3);
  REQUIRE(fb.d == 4);
  REQUIRE(fb.ua == 5);
  REQUIRE(fb.ub == 6);
  REQUIRE(fb.uc == 7);
  REQUIRE(fb.ud == 8);
  REQUIRE(fb.e == 9);
  REQUIRE(fb.f == true);
  REQUIRE(fb.g == 10.0f);
  REQUIRE(fb.h == 11.0);
  REQUIRE(fb.i == "dog");
}

#endif

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// arrays

TEST_CASE("array constructor") {
  Arrays fb;
  REQUIRE(fb.a.size() == 0);
  REQUIRE(fb.b.size() == 0);
  REQUIRE(fb.c.size() == 0);
  REQUIRE(fb.d.size() == 0);
  REQUIRE(fb.ua.size() == 0);
  REQUIRE(fb.ub.size() == 0);
  REQUIRE(fb.uc.size() == 0);
  REQUIRE(fb.ud.size() == 0);
  REQUIRE(fb.e.size() == 0);
  REQUIRE(fb.f.size() == 0);
  REQUIRE(fb.g.size() == 0);
  REQUIRE(fb.h.size() == 0);
  REQUIRE(fb.i.size() == 0);
  REQUIRE(fb.standard.size() == 0);
}

#if GAF_TEST_JSON

TEST_CASE("array empty json") {
  Arrays advanced;

  const std::string load = ReadJsonSource(&advanced, "{}");
  REQUIRE(load != "");
}

TEST_CASE("array basic json") {
  Arrays fb;
  const std::string load = ReadJsonSource(&fb,
    "{\
    \"a\": [],\
    \"b\": [],\
    \"c\": [],\
    \"d\": [],\
    \"ua\": [],\
    \"ub\": [],\
    \"uc\": [],\
    \"ud\": [],\
    \"e\": [],\
    \"f\": [],\
    \"g\": [],\
    \"h\": [],\
    \"i\": [],\
    \"standard\": []}"
  );
  REQUIRE(load == "");

  REQUIRE(fb.a.size() == 0);
  REQUIRE(fb.b.size() == 0);
  REQUIRE(fb.c.size() == 0);
  REQUIRE(fb.d.size() == 0);
  REQUIRE(fb.ua.size() == 0);
  REQUIRE(fb.ub.size() == 0);
  REQUIRE(fb.uc.size() == 0);
  REQUIRE(fb.ud.size() == 0);
  REQUIRE(fb.e.size() == 0);
  REQUIRE(fb.f.size() == 0);
  REQUIRE(fb.g.size() == 0);
  REQUIRE(fb.h.size() == 0);
  REQUIRE(fb.i.size() == 0);
  REQUIRE(fb.standard.size() == 0);
}

// todo: parse standard too
TEST_CASE("arrays advanced json") {
  Arrays fb;
  const std::string load = ReadJsonSource(&fb,
    "{\
    \"a\": [1, 2],\
    \"b\": [3, 4],\
    \"c\": [5, 6],\
    \"d\": [7, 8],\
    \"ua\": [9, 10],\
    \"ub\": [11, 12],\
    \"uc\": [13, 14],\
    \"ud\": [15, 16],\
    \"e\": [17, 18],\
    \"f\": [false, true],\
    \"g\": [19, 20],\
    \"h\": [21, 22],\
    \"i\": [\"cat\", \"dog\"],\
    \"standard\": []}"
  );
  REQUIRE(load == "");

  REQUIRE_THAT(fb.a, Equals(Vector<std::int8_t>()  << 1 << 2));
  REQUIRE_THAT(fb.b, Equals(Vector<std::int16_t>() << 3 << 4));
  REQUIRE_THAT(fb.c, Equals(Vector<std::int32_t>() << 5 << 6));
  REQUIRE_THAT(fb.d, Equals(Vector<std::int64_t>() << 7 << 8));

  REQUIRE_THAT(fb.ua, Equals(Vector<std::uint8_t>()   << 9 << 10));
  REQUIRE_THAT(fb.ub, Equals(Vector<std::uint16_t>() << 11 << 12));
  REQUIRE_THAT(fb.uc, Equals(Vector<std::uint32_t>() << 13 << 14));
  REQUIRE_THAT(fb.ud, Equals(Vector<std::uint64_t>() << 15 << 16));

  REQUIRE_THAT(fb.e, Equals(Vector<char>() << 17 << 18));
  REQUIRE_THAT(fb.f, Equals(Vector<bool>() << false << true));
  REQUIRE_THAT(fb.g, Equals(Vector<float>() << 19 << 20));
  REQUIRE_THAT(fb.h, Equals(Vector<double>() << 21 << 22));

  REQUIRE_THAT(fb.i, Equals(Vector<std::string>() << "cat" << "dog"));
}

#endif

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// optional

TEST_CASE("pointer constructor") {
  Foo foo;
  REQUIRE(foo.value == nullptr);

  FooRoot bar;
  REQUIRE(bar.name == nullptr);
  REQUIRE(bar.foo == nullptr);
}

TEST_CASE("optional constructor") {
  Bar foo;
  REQUIRE(foo.value == 0);

  BarRoot bar;
  REQUIRE(bar.name == "");
  REQUIRE(bar.foo.value == 0);
}

#if GAF_TEST_JSON

TEST_CASE("pointer json_basic") {
  Foo foo;
  const std::string load = ReadJsonSource(&foo, " {\"value\": 12} ");
  REQUIRE(load == "");
  REQUIRE(foo.value != nullptr);
  REQUIRE(*foo.value == 12);
}

TEST_CASE("optional json_basic") {
  Bar foo;
  const std::string load = ReadJsonSource(&foo, " {\"value\": 12} ");
  REQUIRE(load == "");
  REQUIRE(foo.value == 12);
}

TEST_CASE("pointer json_missing_foo") {
  FooRoot bar;
  const std::string load = ReadJsonSource(&bar, " {\"name\": \"good dog\"} ");
  REQUIRE(load == "");
  REQUIRE(bar.name != nullptr);
  REQUIRE(*bar.name == "good dog");
  REQUIRE(bar.foo == nullptr);
}

TEST_CASE("optional json_missing_foo") {
  BarRoot bar;
  const std::string load = ReadJsonSource(&bar, " {\"name\": \"good dog\"} ");
  REQUIRE(load == "");
  REQUIRE(bar.name == "good dog");
  REQUIRE(bar.foo.value == 0);
}

TEST_CASE("pointer json_invalid_value_for_name") {
  // optional means optional, not accept if invalid
  FooRoot bar;
  const std::string load = ReadJsonSource(&bar, " {\"name\": 3} ");
  REQUIRE(load != "");
}

TEST_CASE("optional json_invalid_value_for_name") {
  // optional means optional, not accept if invalid
  BarRoot bar;
  const std::string load = ReadJsonSource(&bar, " {\"name\": 3} ");
  REQUIRE(load != "");
}

TEST_CASE("pointer json_empty_document") {
  FooRoot bar;
  const std::string load = ReadJsonSource(&bar, "{}");
  REQUIRE(load == "");
  REQUIRE(bar.name == nullptr);
  REQUIRE(bar.foo == nullptr);
}

TEST_CASE("optional json_empty_document") {
  BarRoot bar;
  const std::string load = ReadJsonSource(&bar, "{}");
  REQUIRE(load == "");
  REQUIRE(bar.name == "");
  REQUIRE(bar.foo.value == 0);
}

TEST_CASE("pointer json_optional_struct") {
  FooRoot bar;
  const std::string load = ReadJsonSource(&bar, "{\"foo\": {\"value\": 5}}");
  REQUIRE(load == "");
  CHECK(bar.name == nullptr);
  CHECK(bar.foo != nullptr);
  CHECK(bar.foo->value != nullptr);
  CHECK(*bar.foo->value == 5);
}

TEST_CASE("optional json_optional_struct") {
  BarRoot bar;
  const std::string load = ReadJsonSource(&bar, "{\"foo\": {\"value\": 5}}");
  REQUIRE(load == "");
  CHECK(bar.name == "");
  CHECK(bar.foo.value == 5);
}

#endif

<|endoftext|>


<commit_before>#include <rmc++.h>

void lol(int n);

void nus(rmc::atomic<int*> &a, int *p) {
    // A -> B -*-> B, needs dmb
    XEDGE_HERE(a, b);
    int *q = L(a, a);
    while (1) {
        int n = L(b, *q);
        q = p;
        lol(n);
    }
}

// this one *shouldn't* require a dmb!!
void nus2(rmc::atomic<int*> &a) {
    // A -> B -*-> B, shouldn't need dmb
    XEDGE_HERE(a, b);
    int *q = L(a, a);
    while (1) {
        int n = L(b, *q);
        lol(n);
    }
}

void nus3(rmc::atomic<int*> &a, int *p, int i) {
    // A -> C -*-> C -> B, needs dmb
    XEDGE_HERE(a, b);
    int *q = L(a, a);

    int *r;
    // r = q if we go through this loop exactly once
    // if the loop condition repeats then r = p
    do {
        r = q;
        q = p;
    } while (--i);

    int n = L(b, *r);
    lol(n);
}

void nus4(rmc::atomic<int*> &a, int *p, int i) {
    // We wish we could only insert a dmb along the branch,
    // but can't right now. Oh well.
    XEDGE_HERE(a, b);
    int *q = L(a, a);

    if (i) {
        q = p;
    }

    int n = L(b, *q);
    lol(n);
}
<commit_msg>Add another mildly tricky test<commit_after>#include <rmc++.h>

void lol(int n);

void nus(rmc::atomic<int*> &a, int *p) {
    // A -> B -*-> B, needs dmb
    XEDGE_HERE(a, b);
    int *q = L(a, a);
    while (1) {
        int n = L(b, *q);
        q = p;
        lol(n);
    }
}

// this one *shouldn't* require a dmb!!
void nus2(rmc::atomic<int*> &a) {
    // A -> B -*-> B, shouldn't need dmb
    XEDGE_HERE(a, b);
    int *q = L(a, a);
    while (1) {
        int n = L(b, *q);
        lol(n);
    }
}

void nus3(rmc::atomic<int*> &a, int *p, int i) {
    // A -> C -*-> C -> B, needs dmb
    XEDGE_HERE(a, b);
    int *q = L(a, a);

    int *r;
    // r = q if we go through this loop exactly once
    // if the loop condition repeats then r = p
    do {
        r = q;
        q = p;
    } while (--i);

    int n = L(b, *r);
    lol(n);
}

void nus4(rmc::atomic<int*> &a, int *p, int i) {
    // We wish we could only insert a dmb along the branch,
    // but can't right now. Oh well.
    XEDGE_HERE(a, b);
    int *q = L(a, a);

    if (i) {
        q = p;
    }

    int n = L(b, *q);
    lol(n);
}

void nus5(rmc::atomic<int*> &a, int *p) {
    // Should only need the one dmb.
    XEDGE(a, b);
    int *q = L(a, a);
    int n = L(b, *q);
    VEDGE(c, d); LS(c, lol(n)); LS(d, lol(n));
}
<|endoftext|>


<commit_before>/*!
    \file time_time.cpp
    \brief Time example
    \author Ivan Shynkarenka
    \date 13.07.2016
    \copyright MIT License
*/

#include "time/time.h"

#include <iostream>

void show(const CppCommon::Time& time)
{
    std::cout << "Time.year() = " << time.year() << std::endl;
    std::cout << "Time.month() = " << time.month() << std::endl;
    std::cout << "Time.day() = " << time.day() << std::endl;
    std::cout << "Time.hour() = " << time.hour() << std::endl;
    std::cout << "Time.minute() = " << time.minute() << std::endl;
    std::cout << "Time.second() = " << time.second() << std::endl;
    std::cout << "Time.millisecond() = " << time.millisecond() << std::endl;
    std::cout << "Time.microsecond() = " << time.microsecond() << std::endl;
    std::cout << "Time.nanosecond() = " << time.nanosecond() << std::endl;
    std::cout << std::endl;
}

int main(int argc, char** argv)
{
    std::cout << "UTC time:" << std::endl;
    show(CppCommon::UtcTime());

    std::cout << "Local time:" << std::endl;
    show(CppCommon::LocalTime());

    return 0;
}
<commit_msg>update<commit_after>/*!
    \file time_time.cpp
    \brief Time example
    \author Ivan Shynkarenka
    \date 13.07.2016
    \copyright MIT License
*/

#include "time/time.h"

#include <iostream>

void show(const CppCommon::Time& time)
{
    std::cout << "Time.year() = " << time.year() << std::endl;
    std::cout << "Time.month() = " << time.month() << std::endl;
    std::cout << "Time.day() = " << time.day() << std::endl;
    std::cout << "Time.hour() = " << time.hour() << std::endl;
    std::cout << "Time.minute() = " << time.minute() << std::endl;
    std::cout << "Time.second() = " << time.second() << std::endl;
    std::cout << "Time.millisecond() = " << time.millisecond() << std::endl;
    std::cout << "Time.microsecond() = " << time.microsecond() << std::endl;
    std::cout << "Time.nanosecond() = " << time.nanosecond() << std::endl;
    std::cout << std::endl;
}

int main(int argc, char** argv)
{
    std::cout << "UTC time:" << std::endl;
    show(CppCommon::UtcTime());

    std::cout << "Local time:" << std::endl;
    show(CppCommon::LocalTime());

    std::cout << "Min time:" << std::endl;
    show(CppCommon::UtcTime(CppCommon::Timestamp(0)));

    std::cout << "Max time:" << std::endl;
    show(CppCommon::UtcTime(CppCommon::Timestamp(0xFFFFFFFFFFFFFFFF)));

    return 0;
}
<|endoftext|>


<commit_before>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "QmitkOpenDicomEditorAction.h"

#include <QFileDialog>
#include <QFileInfo>

#include "mitkCoreObjectFactory.h"
#include "mitkSceneIO.h"
#include "mitkProgressBar.h"

#include <mitkDataStorageEditorInput.h>
#include <berryIEditorPart.h>
#include <berryIWorkbenchPage.h>
#include <berryIPreferencesService.h>
#include <berryIWorkbench.h>
#include <berryPlatform.h>
#include <berryFileEditorInput.h>

#include "mitkProperties.h"
#include "mitkNodePredicateData.h"
#include "mitkNodePredicateNot.h"
#include "mitkNodePredicateProperty.h"

//#include <QmitkStdMultiWidgetEditor.h>

QmitkOpenDicomEditorAction::QmitkOpenDicomEditorAction(berry::IWorkbenchWindow::Pointer window)
: QAction(0)
{
  this->init(window);
}

QmitkOpenDicomEditorAction::QmitkOpenDicomEditorAction(const QIcon & icon, berry::IWorkbenchWindow::Pointer window)
: QAction(0)
{
  this->setIcon(icon);

  this->init(window);
}

void QmitkOpenDicomEditorAction::init(berry::IWorkbenchWindow::Pointer window)
{
  m_Window = window;
  this->setParent(static_cast<QWidget*>(m_Window->GetShell()->GetControl()));
  this->setText("&DICOM");
  this->setToolTip("Open dicom tool");

  berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService();

  m_GeneralPreferencesNode = prefService->GetSystemPreferences()->Node("/General");

  this->connect(this, SIGNAL(triggered(bool)), this, SLOT(Run()));
}

void QmitkOpenDicomEditorAction::Run()
{

 // check if there is an open perspective, if not open the default perspective
  if (m_Window->GetActivePage().IsNull())
  {
    QString defaultPerspId = m_Window->GetWorkbench()->GetPerspectiveRegistry()->GetDefaultPerspective();
    m_Window->GetWorkbench()->ShowPerspective(defaultPerspId, m_Window);
  }

    //mitk::DataStorageEditorInput::Pointer editorInput;
    //mitk::DataStorage::Pointer dataStorage;
    //QmitkStdMultiWidgetEditor::Pointer multiWidgetEditor;
    //berry::IEditorPart::Pointer editor = m_Window->GetActivePage()->GetActiveEditor();

    //if (editor.Cast<QmitkStdMultiWidgetEditor>().IsNull())
    //{
    //    editorInput = new mitk::DataStorageEditorInput();
    //    dataStorage = editorInput->GetDataStorageReference()->GetDataStorage();
    //}
    //else
    //{
    //    multiWidgetEditor = editor.Cast<QmitkStdMultiWidgetEditor>();
    //    dataStorage = multiWidgetEditor->GetEditorInput().Cast<mitk::DataStorageEditorInput>()->GetDataStorageReference()->GetDataStorage();
    //}

    //if (multiWidgetEditor.IsNull())
    //{
    //    //berry::IEditorPart::Pointer editor = m_Window->GetActivePage()->OpenEditor(editorInput, QmitkStdMultiWidgetEditor::EDITOR_ID);
    //    multiWidgetEditor = editor.Cast<QmitkStdMultiWidgetEditor>();
    //}
    //else
    //{
    //    multiWidgetEditor->GetStdMultiWidget()->RequestUpdate();
    //}

    berry::IEditorInput::Pointer editorInput2(new berry::FileEditorInput(QString()));
    m_Window->GetActivePage()->OpenEditor(editorInput2, "org.mitk.editors.dicomeditor");
}

<commit_msg>Remove (commented) references to multi widget from org.mitk.gui.qt.ext and extapplication<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "QmitkOpenDicomEditorAction.h"

#include <QFileDialog>
#include <QFileInfo>

#include "mitkCoreObjectFactory.h"
#include "mitkSceneIO.h"
#include "mitkProgressBar.h"

#include <mitkDataStorageEditorInput.h>
#include <berryIEditorPart.h>
#include <berryIWorkbenchPage.h>
#include <berryIPreferencesService.h>
#include <berryIWorkbench.h>
#include <berryPlatform.h>
#include <berryFileEditorInput.h>

#include "mitkProperties.h"
#include "mitkNodePredicateData.h"
#include "mitkNodePredicateNot.h"
#include "mitkNodePredicateProperty.h"

QmitkOpenDicomEditorAction::QmitkOpenDicomEditorAction(berry::IWorkbenchWindow::Pointer window)
: QAction(0)
{
  this->init(window);
}

QmitkOpenDicomEditorAction::QmitkOpenDicomEditorAction(const QIcon & icon, berry::IWorkbenchWindow::Pointer window)
: QAction(0)
{
  this->setIcon(icon);

  this->init(window);
}

void QmitkOpenDicomEditorAction::init(berry::IWorkbenchWindow::Pointer window)
{
  m_Window = window;
  this->setParent(static_cast<QWidget*>(m_Window->GetShell()->GetControl()));
  this->setText("&DICOM");
  this->setToolTip("Open dicom tool");

  berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService();

  m_GeneralPreferencesNode = prefService->GetSystemPreferences()->Node("/General");

  this->connect(this, SIGNAL(triggered(bool)), this, SLOT(Run()));
}

void QmitkOpenDicomEditorAction::Run()
{

 // check if there is an open perspective, if not open the default perspective
  if (m_Window->GetActivePage().IsNull())
  {
    QString defaultPerspId = m_Window->GetWorkbench()->GetPerspectiveRegistry()->GetDefaultPerspective();
    m_Window->GetWorkbench()->ShowPerspective(defaultPerspId, m_Window);
  }

  berry::IEditorInput::Pointer editorInput2(new berry::FileEditorInput(QString()));
  m_Window->GetActivePage()->OpenEditor(editorInput2, "org.mitk.editors.dicomeditor");
}

<|endoftext|>


<commit_before>#include <utility.h>
#include "mbed.h"
#include "BtuLinear.h"

#define NUM_FLOATS 6
#define TIMESTEP 0.05
#define DEPTH_THRESHOLD 0.3
#define MIN_MISSION_DEPTH 0.2
#define MISSION_TIMEOUT 60.0
#define ERROR_THRESHOLD 0.125
#define SUCCESS_TIME 8.0
#define DEBRIEF_TIME_LIMIT 20.0
#define UNWOUND_POS 1.0

#define DEF_V_KC 0.5
#define DEF_V_TAUI 0
#define DEF_V_TAUD 0

#define DEF_P_KC 1
#define DEF_P_TAUI 0
#define DEF_P_TAUD 0

#define DRY_RUN 1

#define CONTROL_MODE 55
#define MISSION_MODE 66

#define FREQUENCY 20

#include "MODSERIAL/MODSERIAL.h"
#include "SerialComm/SerialComm.h"

MODSERIAL pcSerial(USBTX, USBRX);
// AnalogIn pot1(p15);
DigitalOut TestLED(LED1);
DigitalOut TestLED2(LED2);
DigitalOut inMission(LED3);
DigitalOut missionSuccess(LED4);

LocalFileSystem local("local");

// bool clk = true;
BtuLinear btu = BtuLinear();
int counter = 0;
int mode = 2;
float Kc = 1.0;
float TauI = 0.0;
float TauD = 0.0;
float floorVal;                 // temp value for mission parameters
float jumpVal;                  // temp value for mission parameters
float missionFloor;             // Lowest depth of a mission
float missionStep;              // Distance between waypoints of a mission
float setVal = 0.0;             // meters
Ticker Control;
Ticker Mission;                 // Ticker for running Mission in parallel with main loop
float timeout = 0.0;            // time in seconds since last waypoint reached
float missionTime = 0.0;        // time in seconds that mission has taken
float successTime = 0.0;        // time in seconds spent within waypoint
float missionDepth = 0.0;       // current waypoint depth
bool missionStarted = false;    // boolean detailing whether or not robot has begun automatically following mission parameters
float debriefTime = 0.0;        // amount of time spent recording log after mission has ended
bool debriefMode = false;       // boolean indicating whether in debrief mode
FILE *fp;                       // pointer for writing log
bool returnTrip = false;        // determines whether the robot is in the descending or ascending part of the mission.  true = ascending
float valueFloats[NUM_FLOATS];
bool missionMode = false;
SerialComm serialComm(&pcSerial);

// end a mission and reset the various parameters.
void terminateMission() {
    Mission.detach();           // stop running mission loop asynchronously
    fclose(fp);                 // close the file
    counter = 0;                // resets the LED mission loop counter
    TestLED = 0;                // turns off the mission loop LED
    inMission = 0;              // turns off the inMission LED
    timeout = 0.0;
    successTime = 0.0;
    missionTime = 0.0;
    missionStarted = false;
    debriefMode = false;
    debriefTime = 0.0;
    returnTrip = false;

    btu.updateAndRunCycle(VELOCITY_CTRL_MODE, UNWOUND_POS); // attempt to return to surface
}

// returns true if we're close enough to current waypoint
bool checkThreshold() {
    float error = btu.getDepth() - missionDepth;
    // float error = btu.getServoPos() - missionDepth;
    float absError = (error > 0) ? error : (-1 * error);
    return (absError <= ERROR_THRESHOLD);
}

// Main mission loop
void runMission() {
    // if in debrief mode, update timer and loop again
	if(debriefMode) {
		inMission = 0;
		missionDepth = 0;
		btu.updateAndRunCycle(VELOCITY_CTRL_MODE, UNWOUND_POS);
        // finally tidy up and kill loop if debrief time has completed
		if(debriefTime >= DEBRIEF_TIME_LIMIT) {
			terminateMission();
		}
		debriefTime += TIMESTEP;
		return;                 // start over the mission loop without checking all the later conditions
	}
    // counter just for flicking the LED every second
    counter = (counter + 1) % 20;
    if(!counter) {
        TestLED = !TestLED;
    }
    // start the mission if we're below depth threshold. Does not reset any values.  Cannot end a mission, so running it multiple times is innocuous
    if(btu.getDepth() >= DEPTH_THRESHOLD) {
        inMission = 1;
        missionStarted = true;
        btu.updateMode(DEPTH_CTRL_MODE);
    }
    // Do nothing if mission has not yet begun
    if(!missionStarted) {
        return;
    }
    // otherwise run depth controller
    btu.runCycle(missionDepth);

    // if we're close enough to our next waypoint, begin counting success time.  Otherwise, reset success time
    if(checkThreshold()) {
    	successTime += TIMESTEP;
    } else {
    	successTime = 0.0;
    }

    // if we've been near the waypoint for long enough
    if (successTime >= SUCCESS_TIME) {
        // check if we're completely done.  i.e. done surfacing on our return trip.  If so, report success and begin debriefing
        if((missionDepth <= MIN_MISSION_DEPTH) && (returnTrip == true)) {
            missionSuccess = 1;
            debriefMode = true;
            return;
        } else if(missionDepth == missionFloor) { // otherwise, check if we reached the bottom of our mission and need to begin resurfacing
            returnTrip = true;
            successTime = 0.0;
            missionDepth = utility::clip(missionDepth - missionStep, MIN_MISSION_DEPTH, missionFloor);
            timeout = 0.0;
        } else {                // otherwise, just advance the mission
        	successTime = 0.0;
            // if we're on the return trip, move up instead of down
            if(returnTrip) {
                missionDepth = utility::clip(missionDepth - missionStep, MIN_MISSION_DEPTH, missionFloor);
            } else {
                missionDepth = utility::clip(missionDepth + missionStep, MIN_MISSION_DEPTH, missionFloor);
            }
            timeout = 0.0;
        }
    }
    // mission failure.  Taken too long to reach a waypoint.  Begin resurfacing, report failure.
    if (timeout >= MISSION_TIMEOUT) {
        missionSuccess = 0;
        debriefMode = true;
        return;
    }
    // advance time
    missionTime += TIMESTEP;
    timeout += TIMESTEP;
}

// sets various mission parameters, being sure to detach a mission if it is already present.
void startMission(float kc, float taui, float taud, float setDepth, float stepDist) {
    terminateMission();
    fp = fopen("/local/log", "w");
    fprintf(fp, "MISSION START, TARGET: %.2f, STEP DISTANCE: %.2f\r\n", setDepth, stepDist);

    missionSuccess = 0;
    missionFloor = setDepth;
    missionDepth = utility::clip(stepDist, MIN_MISSION_DEPTH, missionFloor);
    missionStep = stepDist;
    returnTrip = false;
    btu.updateDepthTunings(kc, taui, taud);
    btu.updateVelTunings(DEF_V_KC, DEF_V_TAUI, DEF_V_TAUD);
    btu.updatePosTunings(DEF_P_KC, DEF_P_TAUI, DEF_P_TAUD);
    // btu.update(SPEC_POSITION_CTRL_MODE, kc, taui, taud);
    Mission.attach(&runMission, TIMESTEP);
}

void runControl() {
  counter = (counter + 1) % FREQUENCY;
  if(!counter) {
	// blink every second
    TestLED = !TestLED;
  }

  //setVal = pot1;
  //setVal = (b1-a1)*setVal+a1;

  // Update Mode and Run Cycle
  btu.updateAndRunCycle(mode, setVal);
}

void switchModes() {
	Control.detach();
	terminateMission();
	btu.stop();
	missionMode = !missionMode;
	if(!missionMode) {
		Control.attach(&runControl, TIMESTEP);
	}
}

void missionCycle() {
	// log in either mission or debrief modes
	if(inMission || debriefMode) {
		float depth = btu.getDepth();
		fprintf(fp, "m:%d, kc:%f, ti:%f, td:%f, s:%.2f, cu:%.2f %.2f, de:%.2f, depth_er:%.4f, time: %.2f, to:%.2f, rt:%d\r\n",
				btu.getMode(), btu.getDkC(), btu.getDkI(), btu.getDkD(), missionDepth, btu.getActPosition(ACT_A), btu.getActPosition(ACT_B), depth, missionDepth - depth, missionTime, timeout, returnTrip);
	} else {                  // otherwise just try to surface
		btu.updateAndRunCycle(VELOCITY_CTRL_MODE, UNWOUND_POS);
	}

	// take in serial messages to start new missions
	if(serialComm.checkIfNewMessage()) {
		serialComm.getFloats(valueFloats, NUM_FLOATS);
		if(valueFloats[0] == CONTROL_MODE) {
			switchModes();
			return;
		}
		// mode = (int) valueFloats[0];
		Kc = valueFloats[0];
		TauI = valueFloats[1];
		TauD = valueFloats[2];
		jumpVal = valueFloats[3];
		floorVal = valueFloats[4];
		btu.setDryMode(!valueFloats[5]);
		startMission(Kc, TauI, TauD, floorVal, jumpVal);
	}
}

void testCycle() {
	float depth = 0;
	depth = btu.getDepth();
	if (mode == DEPTH_CTRL_MODE) {
		pcSerial.printf("m:%d, kc:%.2f, ti:%.2f, td:%.2f, s:%.2f, cu:%.2f %.2f, de:%.2f, depth_er:%.4f\r\n",
				btu.getMode(), btu.getDkC(), btu.getDkI(), btu.getDkD(), setVal, btu.getActPosition(ACT_A), btu.getActPosition(ACT_B), depth, setVal - depth);
	} else if (mode == POSITION_CTRL_MODE) {
		pcSerial.printf("m:%d, kc:%.2f, ti:%.2f, td:%.2f, s:%.2f, cu:%.2f %.2f, de:%.2f, pos_er:%.4f %.4f\r\n",
				btu.getMode(), btu.getPkC(), btu.getPkI(), btu.getPkD(), setVal, btu.getActPosition(ACT_A), btu.getActPosition(ACT_B), depth, setVal - btu.getActPosition(ACT_A), setVal - btu.getActPosition(ACT_B));
	} else {
		pcSerial.printf("m:%d, kc:%.2f, ti:%.2f, td:%.2f, s:%.2f, cu:%.2f %.2f, de:%.2f\r\n", btu.getMode(), Kc, TauI, TauD, setVal, btu.getActPosition(ACT_A), btu.getActPosition(ACT_B), depth);
	}

	if(serialComm.checkIfNewMessage()) {
		serialComm.getFloats(valueFloats, NUM_FLOATS);

		if(valueFloats[0] == MISSION_MODE) {
			switchModes();
			return;
		}
		mode = (int) valueFloats[0];
		Kc = valueFloats[1];
		TauI = valueFloats[2];
		TauD = valueFloats[3];
		setVal = valueFloats[4];
		btu.setDryMode(!valueFloats[5]);

		// Based on Mode, update Tunings
		if(mode == VELOCITY_CTRL_MODE) {
			btu.updateVelTunings(Kc, TauI, TauD);
		} else if (mode == POSITION_CTRL_MODE){
			btu.updatePosTunings(Kc, TauI, TauD);
		} else {
			btu.updateDepthTunings(Kc, TauI, TauD);
		}
	}
}

int main() {
  pcSerial.printf("Start!\n");

  btu.init();
  pcSerial.printf("pressure at start: %.6f\r\n", btu.getPressure());
  TestLED = 0;
  Control.attach(&runControl, TIMESTEP);

  while(1) {
	  if(missionMode) {
		  missionCycle();
	  } else {
		  testCycle();
	  }
      wait_ms(1000);
      TestLED2 = !TestLED2;
  }
}
<commit_msg>adjust gains<commit_after>#include <utility.h>
#include "mbed.h"
#include "BtuLinear.h"

#define NUM_FLOATS 6
#define TIMESTEP 0.05
#define DEPTH_THRESHOLD 0.5
#define MIN_MISSION_DEPTH 0.5
#define MISSION_TIMEOUT 60.0
#define ERROR_THRESHOLD 0.125
#define SUCCESS_TIME 8.0
#define DEBRIEF_TIME_LIMIT 20.0
#define UNWOUND_POS 1.0

#define DEF_V_KC 0.5
#define DEF_V_TAUI 0
#define DEF_V_TAUD 0

#define DEF_P_KC 16
#define DEF_P_TAUI 2
#define DEF_P_TAUD 1

#define DRY_RUN 1

#define CONTROL_MODE 55
#define MISSION_MODE 66

#define FREQUENCY 20

#include "MODSERIAL/MODSERIAL.h"
#include "SerialComm/SerialComm.h"

MODSERIAL pcSerial(USBTX, USBRX);
// AnalogIn pot1(p15);
DigitalOut TestLED(LED1);
DigitalOut TestLED2(LED2);
DigitalOut inMission(LED3);
DigitalOut missionSuccess(LED4);

LocalFileSystem local("local");

// bool clk = true;
BtuLinear btu = BtuLinear();
int counter = 0;
int mode = 2;
float Kc = 1.0;
float TauI = 0.0;
float TauD = 0.0;
float floorVal;                 // temp value for mission parameters
float jumpVal;                  // temp value for mission parameters
float missionFloor;             // Lowest depth of a mission
float missionStep;              // Distance between waypoints of a mission
float setVal = 0.0;             // meters
Ticker Control;
Ticker Mission;                 // Ticker for running Mission in parallel with main loop
float timeout = 0.0;            // time in seconds since last waypoint reached
float missionTime = 0.0;        // time in seconds that mission has taken
float successTime = 0.0;        // time in seconds spent within waypoint
float missionDepth = 0.0;       // current waypoint depth
bool missionStarted = false;    // boolean detailing whether or not robot has begun automatically following mission parameters
float debriefTime = 0.0;        // amount of time spent recording log after mission has ended
bool debriefMode = false;       // boolean indicating whether in debrief mode
FILE *fp;                       // pointer for writing log
bool returnTrip = false;        // determines whether the robot is in the descending or ascending part of the mission.  true = ascending
float valueFloats[NUM_FLOATS];
bool missionMode = false;
SerialComm serialComm(&pcSerial);

// end a mission and reset the various parameters.
void terminateMission() {
    Mission.detach();           // stop running mission loop asynchronously
    fclose(fp);                 // close the file
    counter = 0;                // resets the LED mission loop counter
    TestLED = 0;                // turns off the mission loop LED
    inMission = 0;              // turns off the inMission LED
    timeout = 0.0;
    successTime = 0.0;
    missionTime = 0.0;
    missionStarted = false;
    debriefMode = false;
    debriefTime = 0.0;
    returnTrip = false;

    btu.updateAndRunCycle(VELOCITY_CTRL_MODE, UNWOUND_POS); // attempt to return to surface
}

// returns true if we're close enough to current waypoint
bool checkThreshold() {
    float error = btu.getDepth() - missionDepth;
    // float error = btu.getServoPos() - missionDepth;
    float absError = (error > 0) ? error : (-1 * error);
    return (absError <= ERROR_THRESHOLD);
}

// Main mission loop
void runMission() {
    // if in debrief mode, update timer and loop again
	if(debriefMode) {
		inMission = 0;
		missionDepth = 0;
		btu.updateAndRunCycle(VELOCITY_CTRL_MODE, UNWOUND_POS);
        // finally tidy up and kill loop if debrief time has completed
		if(debriefTime >= DEBRIEF_TIME_LIMIT) {
			terminateMission();
		}
		debriefTime += TIMESTEP;
		return;                 // start over the mission loop without checking all the later conditions
	}
    // counter just for flicking the LED every second
    counter = (counter + 1) % 20;
    if(!counter) {
        TestLED = !TestLED;
    }
    // start the mission if we're below depth threshold. Does not reset any values.  Cannot end a mission, so running it multiple times is innocuous
    if(btu.getDepth() >= DEPTH_THRESHOLD) {
        inMission = 1;
        missionStarted = true;
        btu.updateMode(DEPTH_CTRL_MODE);
    }
    // Do nothing if mission has not yet begun
    if(!missionStarted) {
        return;
    }
    // otherwise run depth controller
    btu.runCycle(missionDepth);

    // if we're close enough to our next waypoint, begin counting success time.  Otherwise, reset success time
    if(checkThreshold()) {
    	successTime += TIMESTEP;
    } else {
    	successTime = 0.0;
    }

    // if we've been near the waypoint for long enough
    if (successTime >= SUCCESS_TIME) {
        // check if we're completely done.  i.e. done surfacing on our return trip.  If so, report success and begin debriefing
        if((missionDepth <= MIN_MISSION_DEPTH) && (returnTrip == true)) {
            missionSuccess = 1;
            debriefMode = true;
            return;
        } else if(missionDepth == missionFloor) { // otherwise, check if we reached the bottom of our mission and need to begin resurfacing
            returnTrip = true;
            successTime = 0.0;
            missionDepth = utility::clip(missionDepth - missionStep, MIN_MISSION_DEPTH, missionFloor);
            timeout = 0.0;
        } else {                // otherwise, just advance the mission
        	successTime = 0.0;
            // if we're on the return trip, move up instead of down
            if(returnTrip) {
                missionDepth = utility::clip(missionDepth - missionStep, MIN_MISSION_DEPTH, missionFloor);
            } else {
                missionDepth = utility::clip(missionDepth + missionStep, MIN_MISSION_DEPTH, missionFloor);
            }
            timeout = 0.0;
        }
    }
    // mission failure.  Taken too long to reach a waypoint.  Begin resurfacing, report failure.
    if (timeout >= MISSION_TIMEOUT) {
        missionSuccess = 0;
        debriefMode = true;
        return;
    }
    // advance time
    missionTime += TIMESTEP;
    timeout += TIMESTEP;
}

// sets various mission parameters, being sure to detach a mission if it is already present.
void startMission(float kc, float taui, float taud, float setDepth, float stepDist) {
    terminateMission();
    fp = fopen("/local/log", "w");
    fprintf(fp, "MISSION START, TARGET: %.2f, STEP DISTANCE: %.2f\r\n", setDepth, stepDist);

    missionSuccess = 0;
    missionFloor = setDepth;
    missionDepth = utility::clip(stepDist, MIN_MISSION_DEPTH, missionFloor);
    missionStep = stepDist;
    returnTrip = false;
    btu.updateDepthTunings(kc, taui, taud);
    btu.updateVelTunings(DEF_V_KC, DEF_V_TAUI, DEF_V_TAUD);
    btu.updatePosTunings(DEF_P_KC, DEF_P_TAUI, DEF_P_TAUD);
    // btu.update(SPEC_POSITION_CTRL_MODE, kc, taui, taud);
    Mission.attach(&runMission, TIMESTEP);
}

void runControl() {
  counter = (counter + 1) % FREQUENCY;
  if(!counter) {
	// blink every second
    TestLED = !TestLED;
  }

  //setVal = pot1;
  //setVal = (b1-a1)*setVal+a1;

  // Update Mode and Run Cycle
  btu.updateAndRunCycle(mode, setVal);
}

void switchModes() {
	Control.detach();
	terminateMission();
	btu.stop();
	missionMode = !missionMode;
	if(!missionMode) {
		Control.attach(&runControl, TIMESTEP);
	}
}

void missionCycle() {
	// log in either mission or debrief modes
	if(inMission || debriefMode) {
		float depth = btu.getDepth();
		fprintf(fp, "m:%d, kc:%f, ti:%f, td:%f, s:%.2f, cu:%.2f %.2f, de:%.2f, depth_er:%.4f, time: %.2f, to:%.2f, rt:%d\r\n",
				btu.getMode(), btu.getDkC(), btu.getDkI(), btu.getDkD(), missionDepth, btu.getActPosition(ACT_A), btu.getActPosition(ACT_B), depth, missionDepth - depth, missionTime, timeout, returnTrip);
	} else {                  // otherwise just try to surface
		btu.updateAndRunCycle(VELOCITY_CTRL_MODE, UNWOUND_POS);
	}

	// take in serial messages to start new missions
	if(serialComm.checkIfNewMessage()) {
		serialComm.getFloats(valueFloats, NUM_FLOATS);
		if(valueFloats[0] == CONTROL_MODE) {
			switchModes();
			return;
		}
		// mode = (int) valueFloats[0];
		Kc = valueFloats[0];
		TauI = valueFloats[1];
		TauD = valueFloats[2];
		jumpVal = valueFloats[3];
		floorVal = valueFloats[4];
		btu.setDryMode(!valueFloats[5]);
		startMission(Kc, TauI, TauD, floorVal, jumpVal);
	}
}

void testCycle() {
	float depth = 0;
	depth = btu.getDepth();
	if (mode == DEPTH_CTRL_MODE) {
		pcSerial.printf("m:%d, kc:%.2f, ti:%.2f, td:%.2f, s:%.2f, cu:%.2f %.2f, de:%.2f, depth_er:%.4f\r\n",
				btu.getMode(), btu.getDkC(), btu.getDkI(), btu.getDkD(), setVal, btu.getActPosition(ACT_A), btu.getActPosition(ACT_B), depth, setVal - depth);
	} else if (mode == POSITION_CTRL_MODE) {
		pcSerial.printf("m:%d, kc:%.2f, ti:%.2f, td:%.2f, s:%.2f, cu:%.2f %.2f, de:%.2f, pos_er:%.4f %.4f\r\n",
				btu.getMode(), btu.getPkC(), btu.getPkI(), btu.getPkD(), setVal, btu.getActPosition(ACT_A), btu.getActPosition(ACT_B), depth, setVal - btu.getActPosition(ACT_A), setVal - btu.getActPosition(ACT_B));
	} else {
		pcSerial.printf("m:%d, kc:%.2f, ti:%.2f, td:%.2f, s:%.2f, cu:%.2f %.2f, de:%.2f\r\n", btu.getMode(), Kc, TauI, TauD, setVal, btu.getActPosition(ACT_A), btu.getActPosition(ACT_B), depth);
	}

	if(serialComm.checkIfNewMessage()) {
		serialComm.getFloats(valueFloats, NUM_FLOATS);

		if(valueFloats[0] == MISSION_MODE) {
			switchModes();
			return;
		}
		mode = (int) valueFloats[0];
		Kc = valueFloats[1];
		TauI = valueFloats[2];
		TauD = valueFloats[3];
		setVal = valueFloats[4];
		btu.setDryMode(!valueFloats[5]);

		// Based on Mode, update Tunings
		if(mode == VELOCITY_CTRL_MODE) {
			btu.updateVelTunings(Kc, TauI, TauD);
		} else if (mode == POSITION_CTRL_MODE){
			btu.updatePosTunings(Kc, TauI, TauD);
		} else {
			btu.updateDepthTunings(Kc, TauI, TauD);
		}
	}
}

int main() {
  pcSerial.printf("Start!\n");

  btu.init();
  pcSerial.printf("pressure at start: %.6f\r\n", btu.getPressure());
  TestLED = 0;
  Control.attach(&runControl, TIMESTEP);

  while(1) {
	  if(missionMode) {
		  missionCycle();
	  } else {
		  testCycle();
	  }
      wait_ms(1000);
      TestLED2 = !TestLED2;
  }
}
<|endoftext|>


<commit_before>#include <utility.h>
#include "mbed.h"
#include "BtuLinear.h"

#define NUM_FLOATS 6
#define TIMESTEP 0.05
#define DEPTH_THRESHOLD 0.3
#define MIN_MISSION_DEPTH 0.2
#define MISSION_TIMEOUT 60.0
#define ERROR_THRESHOLD 0.125
#define SUCCESS_TIME 8.0
#define DEBRIEF_TIME_LIMIT 20.0
#define UNWOUND_POS 1.0

#define DEF_V_KC 0.5
#define DEF_V_TAUI 0
#define DEF_V_TAUD 0

#define DEF_P_KC 1
#define DEF_P_TAUI 0
#define DEF_P_TAUD 0

#define DRY_RUN 1

#define CONTROL_MODE 55
#define MISSION_MODE 66

#define FREQUENCY 20

#include "MODSERIAL/MODSERIAL.h"
#include "SerialComm/SerialComm.h"

MODSERIAL pcSerial(USBTX, USBRX);
// AnalogIn pot1(p15);
DigitalOut TestLED(LED1);
DigitalOut TestLED2(LED2);
DigitalOut inMission(LED3);
DigitalOut missionSuccess(LED4);

LocalFileSystem local("local");

// bool clk = true;
BtuLinear btu = BtuLinear();
int counter = 0;
int mode = 2;
float Kc = 1.0;
float TauI = 0.0;
float TauD = 0.0;
float floorVal;                 // temp value for mission parameters
float jumpVal;                  // temp value for mission parameters
float missionFloor;             // Lowest depth of a mission
float missionStep;              // Distance between waypoints of a mission
float setVal = 0.0;             // meters
Ticker Control;
Ticker Mission;                 // Ticker for running Mission in parallel with main loop
float timeout = 0.0;            // time in seconds since last waypoint reached
float missionTime = 0.0;        // time in seconds that mission has taken
float successTime = 0.0;        // time in seconds spent within waypoint
float missionDepth = 0.0;       // current waypoint depth
bool missionStarted = false;    // boolean detailing whether or not robot has begun automatically following mission parameters
float debriefTime = 0.0;        // amount of time spent recording log after mission has ended
bool debriefMode = false;       // boolean indicating whether in debrief mode
FILE *fp;                       // pointer for writing log
bool returnTrip = false;        // determines whether the robot is in the descending or ascending part of the mission.  true = ascending
float valueFloats[NUM_FLOATS];
bool missionMode = false;
SerialComm serialComm(&pcSerial);

// end a mission and reset the various parameters.
void terminateMission() {
    Mission.detach();           // stop running mission loop asynchronously
    fclose(fp);                 // close the file
    counter = 0;                // resets the LED mission loop counter
    TestLED = 0;                // turns off the mission loop LED
    inMission = 0;              // turns off the inMission LED
    timeout = 0.0;
    successTime = 0.0;
    missionTime = 0.0;
    missionStarted = false;
    debriefMode = false;
    debriefTime = 0.0;
    returnTrip = false;

    btu.updateAndRunCycle(VELOCITY_CTRL_MODE, UNWOUND_POS); // attempt to return to surface
}

// returns true if we're close enough to current waypoint
bool checkThreshold() {
    float error = btu.getDepth() - missionDepth;
    // float error = btu.getServoPos() - missionDepth;
    float absError = (error > 0) ? error : (-1 * error);
    return (absError <= ERROR_THRESHOLD);
}

// Main mission loop
void runMission() {
    // if in debrief mode, update timer and loop again
	if(debriefMode) {
		inMission = 0;
		missionDepth = 0;
		btu.updateAndRunCycle(VELOCITY_CTRL_MODE, UNWOUND_POS);
        // finally tidy up and kill loop if debrief time has completed
		if(debriefTime >= DEBRIEF_TIME_LIMIT) {
			terminateMission();
		}
		debriefTime += TIMESTEP;
		return;                 // start over the mission loop without checking all the later conditions
	}
    // counter just for flicking the LED every second
    counter = (counter + 1) % 20;
    if(!counter) {
        TestLED = !TestLED;
    }
    // start the mission if we're below depth threshold. Does not reset any values.  Cannot end a mission, so running it multiple times is innocuous
    if(btu.getDepth() >= DEPTH_THRESHOLD) {
        inMission = 1;
        missionStarted = true;
        btu.updateMode(DEPTH_CTRL_MODE);
    }
    // Do nothing if mission has not yet begun
    if(!missionStarted) {
        return;
    }
    // otherwise run depth controller
    btu.runCycle(missionDepth);

    // if we're close enough to our next waypoint, begin counting success time.  Otherwise, reset success time
    if(checkThreshold()) {
    	successTime += TIMESTEP;
    } else {
    	successTime = 0.0;
    }

    // if we've been near the waypoint for long enough
    if (successTime >= SUCCESS_TIME) {
        // check if we're completely done.  i.e. done surfacing on our return trip.  If so, report success and begin debriefing
        if((missionDepth <= MIN_MISSION_DEPTH) && (returnTrip == true)) {
            missionSuccess = 1;
            debriefMode = true;
            return;
        } else if(missionDepth == missionFloor) { // otherwise, check if we reached the bottom of our mission and need to begin resurfacing
            returnTrip = true;
            successTime = 0.0;
            missionDepth = utility::clip(missionDepth - missionStep, MIN_MISSION_DEPTH, missionFloor);
            timeout = 0.0;
        } else {                // otherwise, just advance the mission
        	successTime = 0.0;
            // if we're on the return trip, move up instead of down
            if(returnTrip) {
                missionDepth = utility::clip(missionDepth - missionStep, MIN_MISSION_DEPTH, missionFloor);
            } else {
                missionDepth = utility::clip(missionDepth + missionStep, MIN_MISSION_DEPTH, missionFloor);
            }
            timeout = 0.0;
        }
    }
    // mission failure.  Taken too long to reach a waypoint.  Begin resurfacing, report failure.
    if (timeout >= MISSION_TIMEOUT) {
        missionSuccess = 0;
        debriefMode = true;
        return;
    }
    // advance time
    missionTime += TIMESTEP;
    timeout += TIMESTEP;
}

// sets various mission parameters, being sure to detach a mission if it is already present.
void startMission(float kc, float taui, float taud, float setDepth, float stepDist) {
    terminateMission();
    fp = fopen("/local/log", "w");
    fprintf(fp, "MISSION START, TARGET: %.2f, STEP DISTANCE: %.2f\r\n", setDepth, stepDist);

    missionSuccess = 0;
    missionFloor = setDepth;
    missionDepth = utility::clip(stepDist, MIN_MISSION_DEPTH, missionFloor);
    missionStep = stepDist;
    returnTrip = false;
    btu.updateDepthTunings(kc, taui, taud);
    btu.updateVelTunings(DEF_V_KC, DEF_V_TAUI, DEF_V_TAUD);
    btu.updatePosTunings(DEF_P_KC, DEF_P_TAUI, DEF_P_TAUD);
    // btu.update(SPEC_POSITION_CTRL_MODE, kc, taui, taud);
    Mission.attach(&runMission, TIMESTEP);
}

void runControl() {
  counter = (counter + 1) % FREQUENCY;
  if(!counter) {
	// blink every second
    TestLED = !TestLED;
  }

  //setVal = pot1;
  //setVal = (b1-a1)*setVal+a1;

  // Update Mode and Run Cycle
  btu.updateAndRunCycle(mode, setVal);
}

void switchModes() {
	Control.detach();
	terminateMission();
	btu.stop();
	missionMode = !missionMode;
	if(!missionMode) {
		Control.attach(&runControl, TIMESTEP);
	}
}

void missionCycle() {
	// log in either mission or debrief modes
	if(inMission || debriefMode) {
		float depth = btu.getDepth();
		fprintf(fp, "m:%d, kc:%f, ti:%f, td:%f, s:%.2f, cu:%.2f %.2f, de:%.2f, depth_er:%.4f, time: %.2f, to:%.2f, rt:%d\r\n",
				btu.getMode(), btu.getDkC(), btu.getDkI(), btu.getDkD(), missionDepth, btu.getActPosition(ACT_A), btu.getActPosition(ACT_B), depth, missionDepth - depth, missionTime, timeout, returnTrip);
	} else {                  // otherwise just try to surface
		btu.updateAndRunCycle(VELOCITY_CTRL_MODE, UNWOUND_POS);
	}

	// take in serial messages to start new missions
	if(serialComm.checkIfNewMessage()) {
		serialComm.getFloats(valueFloats, NUM_FLOATS);
		if(valueFloats[0] == CONTROL_MODE) {
			switchModes();
			return;
		}
		// mode = (int) valueFloats[0];
		Kc = valueFloats[0];
		TauI = valueFloats[1];
		TauD = valueFloats[2];
		jumpVal = valueFloats[3];
		floorVal = valueFloats[4];
		btu.setDryMode(!valueFloats[5]);
		startMission(Kc, TauI, TauD, floorVal, jumpVal);
	}
}

void testCycle() {
	float depth = 0;
	depth = btu.getDepth();
	if (mode == DEPTH_CTRL_MODE) {
		pcSerial.printf("m:%d, kc:%.2f, ti:%.2f, td:%.2f, s:%.2f, cu:%.2f %.2f, de:%.2f, depth_er:%.4f\r\n",
				btu.getMode(), btu.getDkC(), btu.getDkI(), btu.getDkD(), setVal, btu.getActPosition(ACT_A), btu.getActPosition(ACT_B), depth, setVal - depth);
	} else if (mode == POSITION_CTRL_MODE) {
		pcSerial.printf("m:%d, kc:%.2f, ti:%.2f, td:%.2f, s:%.2f, cu:%.2f %.2f, de:%.2f, pos_er:%.4f %.4f\r\n",
				btu.getMode(), btu.getPkC(), btu.getPkI(), btu.getPkD(), setVal, btu.getActPosition(ACT_A), btu.getActPosition(ACT_B), depth, setVal - btu.getActPosition(ACT_A), setVal - btu.getActPosition(ACT_B));
	} else {
		pcSerial.printf("m:%d, kc:%.2f, ti:%.2f, td:%.2f, s:%.2f, cu:%.2f %.2f, de:%.2f\r\n", btu.getMode(), Kc, TauI, TauD, setVal, btu.getActPosition(ACT_A), btu.getActPosition(ACT_B), depth);
	}

	if(serialComm.checkIfNewMessage()) {
		serialComm.getFloats(valueFloats, NUM_FLOATS);

		if(valueFloats[0] == MISSION_MODE) {
			switchModes();
			return;
		}
		mode = (int) valueFloats[0];
		Kc = valueFloats[1];
		TauI = valueFloats[2];
		TauD = valueFloats[3];
		setVal = valueFloats[4];
		btu.setDryMode(!valueFloats[5]);

		// Based on Mode, update Tunings
		if(mode == VELOCITY_CTRL_MODE) {
			btu.updateVelTunings(Kc, TauI, TauD);
		} else if (mode == POSITION_CTRL_MODE){
			btu.updatePosTunings(Kc, TauI, TauD);
		} else {
			btu.updateDepthTunings(Kc, TauI, TauD);
		}
	}
}

int main() {
  pcSerial.printf("Start!\n");

  btu.init();
  pcSerial.printf("pressure at start: %.6f\r\n", btu.getPressure());
  TestLED = 0;
  Control.attach(&runControl, TIMESTEP);

  while(1) {
	  if(missionMode) {
		  missionCycle();
	  } else {
		  testCycle();
	  }
      wait_ms(500);
      TestLED2 = !TestLED2;
  }
}
<commit_msg>fixed loop freezing issue<commit_after>#include <utility.h>
#include "mbed.h"
#include "BtuLinear.h"

#define NUM_FLOATS 6
#define TIMESTEP 0.05
#define DEPTH_THRESHOLD 0.3
#define MIN_MISSION_DEPTH 0.2
#define MISSION_TIMEOUT 60.0
#define ERROR_THRESHOLD 0.125
#define SUCCESS_TIME 8.0
#define DEBRIEF_TIME_LIMIT 20.0
#define UNWOUND_POS 1.0

#define DEF_V_KC 0.5
#define DEF_V_TAUI 0
#define DEF_V_TAUD 0

#define DEF_P_KC 1
#define DEF_P_TAUI 0
#define DEF_P_TAUD 0

#define DRY_RUN 1

#define CONTROL_MODE 55
#define MISSION_MODE 66

#define FREQUENCY 20

#include "MODSERIAL/MODSERIAL.h"
#include "SerialComm/SerialComm.h"

MODSERIAL pcSerial(USBTX, USBRX);
// AnalogIn pot1(p15);
DigitalOut TestLED(LED1);
DigitalOut TestLED2(LED2);
DigitalOut inMission(LED3);
DigitalOut missionSuccess(LED4);

LocalFileSystem local("local");

// bool clk = true;
BtuLinear btu = BtuLinear();
int counter = 0;
int mode = 2;
float Kc = 1.0;
float TauI = 0.0;
float TauD = 0.0;
float floorVal;                 // temp value for mission parameters
float jumpVal;                  // temp value for mission parameters
float missionFloor;             // Lowest depth of a mission
float missionStep;              // Distance between waypoints of a mission
float setVal = 0.0;             // meters
Ticker Control;
Ticker Mission;                 // Ticker for running Mission in parallel with main loop
float timeout = 0.0;            // time in seconds since last waypoint reached
float missionTime = 0.0;        // time in seconds that mission has taken
float successTime = 0.0;        // time in seconds spent within waypoint
float missionDepth = 0.0;       // current waypoint depth
bool missionStarted = false;    // boolean detailing whether or not robot has begun automatically following mission parameters
float debriefTime = 0.0;        // amount of time spent recording log after mission has ended
bool debriefMode = false;       // boolean indicating whether in debrief mode
FILE *fp;                       // pointer for writing log
bool returnTrip = false;        // determines whether the robot is in the descending or ascending part of the mission.  true = ascending
float valueFloats[NUM_FLOATS];
bool missionMode = false;
SerialComm serialComm(&pcSerial);

// end a mission and reset the various parameters.
void terminateMission() {
    Mission.detach();           // stop running mission loop asynchronously
    fclose(fp);                 // close the file
    counter = 0;                // resets the LED mission loop counter
    TestLED = 0;                // turns off the mission loop LED
    inMission = 0;              // turns off the inMission LED
    timeout = 0.0;
    successTime = 0.0;
    missionTime = 0.0;
    missionStarted = false;
    debriefMode = false;
    debriefTime = 0.0;
    returnTrip = false;

    btu.updateAndRunCycle(VELOCITY_CTRL_MODE, UNWOUND_POS); // attempt to return to surface
}

// returns true if we're close enough to current waypoint
bool checkThreshold() {
    float error = btu.getDepth() - missionDepth;
    // float error = btu.getServoPos() - missionDepth;
    float absError = (error > 0) ? error : (-1 * error);
    return (absError <= ERROR_THRESHOLD);
}

// Main mission loop
void runMission() {
    // if in debrief mode, update timer and loop again
	if(debriefMode) {
		inMission = 0;
		missionDepth = 0;
		btu.updateAndRunCycle(VELOCITY_CTRL_MODE, UNWOUND_POS);
        // finally tidy up and kill loop if debrief time has completed
		if(debriefTime >= DEBRIEF_TIME_LIMIT) {
			terminateMission();
		}
		debriefTime += TIMESTEP;
		return;                 // start over the mission loop without checking all the later conditions
	}
    // counter just for flicking the LED every second
    counter = (counter + 1) % 20;
    if(!counter) {
        TestLED = !TestLED;
    }
    // start the mission if we're below depth threshold. Does not reset any values.  Cannot end a mission, so running it multiple times is innocuous
    if(btu.getDepth() >= DEPTH_THRESHOLD) {
        inMission = 1;
        missionStarted = true;
        btu.updateMode(DEPTH_CTRL_MODE);
    }
    // Do nothing if mission has not yet begun
    if(!missionStarted) {
        return;
    }
    // otherwise run depth controller
    btu.runCycle(missionDepth);

    // if we're close enough to our next waypoint, begin counting success time.  Otherwise, reset success time
    if(checkThreshold()) {
    	successTime += TIMESTEP;
    } else {
    	successTime = 0.0;
    }

    // if we've been near the waypoint for long enough
    if (successTime >= SUCCESS_TIME) {
        // check if we're completely done.  i.e. done surfacing on our return trip.  If so, report success and begin debriefing
        if((missionDepth <= MIN_MISSION_DEPTH) && (returnTrip == true)) {
            missionSuccess = 1;
            debriefMode = true;
            return;
        } else if(missionDepth == missionFloor) { // otherwise, check if we reached the bottom of our mission and need to begin resurfacing
            returnTrip = true;
            successTime = 0.0;
            missionDepth = utility::clip(missionDepth - missionStep, MIN_MISSION_DEPTH, missionFloor);
            timeout = 0.0;
        } else {                // otherwise, just advance the mission
        	successTime = 0.0;
            // if we're on the return trip, move up instead of down
            if(returnTrip) {
                missionDepth = utility::clip(missionDepth - missionStep, MIN_MISSION_DEPTH, missionFloor);
            } else {
                missionDepth = utility::clip(missionDepth + missionStep, MIN_MISSION_DEPTH, missionFloor);
            }
            timeout = 0.0;
        }
    }
    // mission failure.  Taken too long to reach a waypoint.  Begin resurfacing, report failure.
    if (timeout >= MISSION_TIMEOUT) {
        missionSuccess = 0;
        debriefMode = true;
        return;
    }
    // advance time
    missionTime += TIMESTEP;
    timeout += TIMESTEP;
}

// sets various mission parameters, being sure to detach a mission if it is already present.
void startMission(float kc, float taui, float taud, float setDepth, float stepDist) {
    terminateMission();
    fp = fopen("/local/log", "w");
    fprintf(fp, "MISSION START, TARGET: %.2f, STEP DISTANCE: %.2f\r\n", setDepth, stepDist);

    missionSuccess = 0;
    missionFloor = setDepth;
    missionDepth = utility::clip(stepDist, MIN_MISSION_DEPTH, missionFloor);
    missionStep = stepDist;
    returnTrip = false;
    btu.updateDepthTunings(kc, taui, taud);
    btu.updateVelTunings(DEF_V_KC, DEF_V_TAUI, DEF_V_TAUD);
    btu.updatePosTunings(DEF_P_KC, DEF_P_TAUI, DEF_P_TAUD);
    // btu.update(SPEC_POSITION_CTRL_MODE, kc, taui, taud);
    Mission.attach(&runMission, TIMESTEP);
}

void runControl() {
  counter = (counter + 1) % FREQUENCY;
  if(!counter) {
	// blink every second
    TestLED = !TestLED;
  }

  //setVal = pot1;
  //setVal = (b1-a1)*setVal+a1;

  // Update Mode and Run Cycle
  btu.updateAndRunCycle(mode, setVal);
}

void switchModes() {
	Control.detach();
	terminateMission();
	btu.stop();
	missionMode = !missionMode;
	if(!missionMode) {
		Control.attach(&runControl, TIMESTEP);
	}
}

void missionCycle() {
	// log in either mission or debrief modes
	if(inMission || debriefMode) {
		float depth = btu.getDepth();
		fprintf(fp, "m:%d, kc:%f, ti:%f, td:%f, s:%.2f, cu:%.2f %.2f, de:%.2f, depth_er:%.4f, time: %.2f, to:%.2f, rt:%d\r\n",
				btu.getMode(), btu.getDkC(), btu.getDkI(), btu.getDkD(), missionDepth, btu.getActPosition(ACT_A), btu.getActPosition(ACT_B), depth, missionDepth - depth, missionTime, timeout, returnTrip);
	} else {                  // otherwise just try to surface
		btu.updateAndRunCycle(VELOCITY_CTRL_MODE, UNWOUND_POS);
	}

	// take in serial messages to start new missions
	if(serialComm.checkIfNewMessage()) {
		serialComm.getFloats(valueFloats, NUM_FLOATS);
		if(valueFloats[0] == CONTROL_MODE) {
			switchModes();
			return;
		}
		// mode = (int) valueFloats[0];
		Kc = valueFloats[0];
		TauI = valueFloats[1];
		TauD = valueFloats[2];
		jumpVal = valueFloats[3];
		floorVal = valueFloats[4];
		btu.setDryMode(!valueFloats[5]);
		startMission(Kc, TauI, TauD, floorVal, jumpVal);
	}
}

void testCycle() {
	float depth = 0;
	depth = btu.getDepth();
	if (mode == DEPTH_CTRL_MODE) {
		pcSerial.printf("m:%d, kc:%.2f, ti:%.2f, td:%.2f, s:%.2f, cu:%.2f %.2f, de:%.2f, depth_er:%.4f\r\n",
				btu.getMode(), btu.getDkC(), btu.getDkI(), btu.getDkD(), setVal, btu.getActPosition(ACT_A), btu.getActPosition(ACT_B), depth, setVal - depth);
	} else if (mode == POSITION_CTRL_MODE) {
		pcSerial.printf("m:%d, kc:%.2f, ti:%.2f, td:%.2f, s:%.2f, cu:%.2f %.2f, de:%.2f, pos_er:%.4f %.4f\r\n",
				btu.getMode(), btu.getPkC(), btu.getPkI(), btu.getPkD(), setVal, btu.getActPosition(ACT_A), btu.getActPosition(ACT_B), depth, setVal - btu.getActPosition(ACT_A), setVal - btu.getActPosition(ACT_B));
	} else {
		pcSerial.printf("m:%d, kc:%.2f, ti:%.2f, td:%.2f, s:%.2f, cu:%.2f %.2f, de:%.2f\r\n", btu.getMode(), Kc, TauI, TauD, setVal, btu.getActPosition(ACT_A), btu.getActPosition(ACT_B), depth);
	}

	if(serialComm.checkIfNewMessage()) {
		serialComm.getFloats(valueFloats, NUM_FLOATS);

		if(valueFloats[0] == MISSION_MODE) {
			switchModes();
			return;
		}
		mode = (int) valueFloats[0];
		Kc = valueFloats[1];
		TauI = valueFloats[2];
		TauD = valueFloats[3];
		setVal = valueFloats[4];
		btu.setDryMode(!valueFloats[5]);

		// Based on Mode, update Tunings
		if(mode == VELOCITY_CTRL_MODE) {
			btu.updateVelTunings(Kc, TauI, TauD);
		} else if (mode == POSITION_CTRL_MODE){
			btu.updatePosTunings(Kc, TauI, TauD);
		} else {
			btu.updateDepthTunings(Kc, TauI, TauD);
		}
	}
}

int main() {
  pcSerial.printf("Start!\n");

  btu.init();
  pcSerial.printf("pressure at start: %.6f\r\n", btu.getPressure());
  TestLED = 0;
  Control.attach(&runControl, TIMESTEP);

  while(1) {
	  if(missionMode) {
		  missionCycle();
	  } else {
		  testCycle();
	  }
      wait_ms(1000);
      TestLED2 = !TestLED2;
  }
}
<|endoftext|>


<commit_before>/*
 * Author: Thomas Ingleby <thomas.c.ingleby@intel.com>
 * Copyright (c) 2014 Intel Corporation.
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#pragma once

#include "common.h"
#include "types.hpp"
#include <string>

/**
 * @namespace mraa namespace
 */
namespace mraa
{

/**
 * @file
 * @brief API to common functions of MRAA
 *
 * This file defines the interface for libmraa common functions
 */

/**
 * Initialise MRAA
 *
 * Detects running platform and attempts to use included pinmap, this is run on
 * module/library init/load but is handy to rerun to check board initialised
 * correctly. MRAA_SUCCESS inidicates correct (first time) initialisation
 * whilst MRAA_ERROR_PLATFORM_ALREADY_INITIALISED indicates the board is
 * already initialised correctly
 *
 * @return Result of operation
 */
inline Result
init()
{
    return (Result) mraa_init();
}

/**
 * Get libmraa version.
 *
 * @return libmraa version (e.g. v0.4.0-20-gb408207)
 */
inline std::string
getVersion()
{
    std::string ret = mraa_get_version();
    return ret;
}

/**
 * This function attempts to set the mraa process to a given priority and the
 * scheduler to SCHED_RR. Highest * priority is typically 99 and minimum is 0.
 * This function * will set to MAX if * priority is > MAX. Function will return
 * -1 on failure.
 *
 * @param priority Value from typically 0 to 99
 * @return The priority value set
 */
inline int
setPriority(const unsigned int priority)
{
    return mraa_set_priority(priority);
}

/**
 * Get platform type, board must be initialised.
 *
 * @return mraa::platform Platform type enum
 */
inline Platform
getPlatformType()
{
    return (Platform) mraa_get_platform_type();
}

/**
 * Print a textual representation of the mraa::Result
 *
 * @param Result the Result to print
 */
inline void
printError(Result result)
{
    mraa_result_print((mraa_result_t) result);
}

/**
 * Checks if a pin is able to use the passed in mode.
 *
 * @param pin Physical Pin to be checked.
 * @param mode the mode to be tested.
 * @return boolean if the mode is supported, 0=false.
 */
inline bool
pinModeTest(int pin, Pinmodes mode)
{
    return (bool) mraa_pin_mode_test(pin, (mraa_pinmodes_t) mode);
}

/**
 * Check the board's bit size when reading the value
 *
 * @return raw bits being read from kernel module. Zero if no ADC
 */
inline unsigned int
adcRawBits()
{
    return mraa_adc_raw_bits();
}

/**
 * Return value that the raw value should be shifted to. Zero if no ADC
 *
 * @return return actual bit size the adc value should be understood as.
 */
inline unsigned int
adcSupportedBits()
{
    return mraa_adc_supported_bits();
}

/**
 * Return Platform Name. Returns NULL if no platform inited.
 *
 * @return platform name
 */
inline std::string
getPlatformName()
{
    std::string ret_val(mraa_get_platform_name());
    return ret_val;
}

/**
 * Return platform versioning info. Returns NULL if no info present.
 *
 * @param optional subplatform identifier
 * @return platform versioning info
 */
inline std::string
getPlatformVersion(int platform_offset=MRAA_MAIN_PLATFORM_OFFSET)
{
    std::string ret_val(mraa_get_platform_version(platform_offset));
    return ret_val;
}

/**
 * Return count of physical pins on the running platform
 *
 * @return uint of physical pins.
 */
inline unsigned int
getPinCount()
{
    return mraa_get_pin_count();
}

/**
 * Get platform usable I2C bus count, board must be initialised.
 *
 * @return number f usable I2C bus count on the current platform. Function will
 * return -1 on failure
 */
inline int
getI2cBusCount()
{
    return mraa_get_i2c_bus_count();
}

/**
 * Get I2C adapter number in sysfs.
 *
 * @param i2c_bus the logical I2C bus number
 * @return I2C adapter number in sysfs. Function will return -1 on failure
 */
inline int
getI2cBusId(unsigned int i2c_bus)
{
    return mraa_get_i2c_bus_id(i2c_bus);
}

/**
* Get name of pin, board must be initialised.
*
* @param pin number
*
* @return char* of pin name
*/
inline std::string
getPinName(int pin)
{
    std::string ret_val(mraa_get_pin_name(pin));
    return ret_val;
}

/**
 * Sets the log level to use from 0-7 where 7 is very verbose. These are the
 * syslog log levels, see syslog(3) for more information on the levels.
 *
 * @param level
 * @return Result of operation
 */
inline Result
setLogLevel(int level)
{
    return (Result) mraa_set_log_level(level);
}

/**
 * Detect presence of sub platform.
 *
 * @return bool true if sub platform is present and initialized, false otherwise
 */
inline bool
hasSubPlatform()
{
    return static_cast<bool>(mraa_has_sub_platform());
}

/**
 * Check if pin or bus id includes sub platform mask.
 *
 * @param int pin or bus number
 *
 * @return mraa_boolean_t 1 if pin or bus is for sub platform, 0 otherwise
 */
inline bool
isSubPlatformId(int pin_or_bus_id)
{
    return static_cast<bool>(mraa_is_sub_platform_id(pin_or_bus_id));
}

/**
 * Convert pin or bus index to corresponding sub platform id.
 *
 * @param int pin or bus index
 *
 * @return int sub platform pin or bus number
 */
inline int
getSubPlatformId(int pin_or_bus_index)
{
    return mraa_get_sub_platform_id(pin_or_bus_index);
}

/**
 * Convert pin or bus sub platform id to index.
 *
 * @param int sub platform pin or bus id
 *
 * @return int pin or bus index
 */
inline int
getSubPlatformIndex(int pin_or_bus_id)
{
    return mraa_get_sub_platform_index(pin_or_bus_id);
}

/**
 * Get default i2c bus, board must be initialised.
 *
 * @param optional subplatform identifier
 * @return default i2c bus for paltform
 */
inline int
getDefaultI2cBus(int platform_offset=MRAA_MAIN_PLATFORM_OFFSET)
{
    return mraa_get_default_i2c_bus(platform_offset);
}
}
<commit_msg>common.hpp: remove whitespace<commit_after>/*
 * Author: Thomas Ingleby <thomas.c.ingleby@intel.com>
 * Copyright (c) 2014 Intel Corporation.
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#pragma once

#include "common.h"
#include "types.hpp"
#include <string>

/**
 * @namespace mraa namespace
 */
namespace mraa
{

/**
 * @file
 * @brief API to common functions of MRAA
 *
 * This file defines the interface for libmraa common functions
 */

/**
 * Initialise MRAA
 *
 * Detects running platform and attempts to use included pinmap, this is run on
 * module/library init/load but is handy to rerun to check board initialised
 * correctly. MRAA_SUCCESS inidicates correct (first time) initialisation
 * whilst MRAA_ERROR_PLATFORM_ALREADY_INITIALISED indicates the board is
 * already initialised correctly
 *
 * @return Result of operation
 */
inline Result
init()
{
    return (Result) mraa_init();
}

/**
 * Get libmraa version.
 *
 * @return libmraa version (e.g. v0.4.0-20-gb408207)
 */
inline std::string
getVersion()
{
    std::string ret = mraa_get_version();
    return ret;
}

/**
 * This function attempts to set the mraa process to a given priority and the
 * scheduler to SCHED_RR. Highest * priority is typically 99 and minimum is 0.
 * This function * will set to MAX if * priority is > MAX. Function will return
 * -1 on failure.
 *
 * @param priority Value from typically 0 to 99
 * @return The priority value set
 */
inline int
setPriority(const unsigned int priority)
{
    return mraa_set_priority(priority);
}

/**
 * Get platform type, board must be initialised.
 *
 * @return mraa::platform Platform type enum
 */
inline Platform
getPlatformType()
{
    return (Platform) mraa_get_platform_type();
}

/**
 * Print a textual representation of the mraa::Result
 *
 * @param Result the Result to print
 */
inline void
printError(Result result)
{
    mraa_result_print((mraa_result_t) result);
}

/**
 * Checks if a pin is able to use the passed in mode.
 *
 * @param pin Physical Pin to be checked.
 * @param mode the mode to be tested.
 * @return boolean if the mode is supported, 0=false.
 */
inline bool
pinModeTest(int pin, Pinmodes mode)
{
    return (bool) mraa_pin_mode_test(pin, (mraa_pinmodes_t) mode);
}

/**
 * Check the board's bit size when reading the value
 *
 * @return raw bits being read from kernel module. Zero if no ADC
 */
inline unsigned int
adcRawBits()
{
    return mraa_adc_raw_bits();
}

/**
 * Return value that the raw value should be shifted to. Zero if no ADC
 *
 * @return return actual bit size the adc value should be understood as.
 */
inline unsigned int
adcSupportedBits()
{
    return mraa_adc_supported_bits();
}

/**
 * Return Platform Name. Returns NULL if no platform inited.
 *
 * @return platform name
 */
inline std::string
getPlatformName()
{
    std::string ret_val(mraa_get_platform_name());
    return ret_val;
}

/**
 * Return platform versioning info. Returns NULL if no info present.
 *
 * @param optional subplatform identifier
 * @return platform versioning info
 */
inline std::string
getPlatformVersion(int platform_offset=MRAA_MAIN_PLATFORM_OFFSET)
{
    std::string ret_val(mraa_get_platform_version(platform_offset));
    return ret_val;
}

/**
 * Return count of physical pins on the running platform
 *
 * @return uint of physical pins.
 */
inline unsigned int
getPinCount()
{
    return mraa_get_pin_count();
}

/**
 * Get platform usable I2C bus count, board must be initialised.
 *
 * @return number f usable I2C bus count on the current platform. Function will
 * return -1 on failure
 */
inline int
getI2cBusCount()
{
    return mraa_get_i2c_bus_count();
}

/**
 * Get I2C adapter number in sysfs.
 *
 * @param i2c_bus the logical I2C bus number
 * @return I2C adapter number in sysfs. Function will return -1 on failure
 */
inline int
getI2cBusId(unsigned int i2c_bus)
{
    return mraa_get_i2c_bus_id(i2c_bus);
}

/**
* Get name of pin, board must be initialised.
*
* @param pin number
*
* @return char* of pin name
*/
inline std::string
getPinName(int pin)
{
    std::string ret_val(mraa_get_pin_name(pin));
    return ret_val;
}

/**
 * Sets the log level to use from 0-7 where 7 is very verbose. These are the
 * syslog log levels, see syslog(3) for more information on the levels.
 *
 * @param level
 * @return Result of operation
 */
inline Result
setLogLevel(int level)
{
    return (Result) mraa_set_log_level(level);
}

/**
 * Detect presence of sub platform.
 *
 * @return bool true if sub platform is present and initialized, false otherwise
 */
inline bool
hasSubPlatform()
{
    return static_cast<bool>(mraa_has_sub_platform());
}

/**
 * Check if pin or bus id includes sub platform mask.
 *
 * @param int pin or bus number
 *
 * @return mraa_boolean_t 1 if pin or bus is for sub platform, 0 otherwise
 */
inline bool
isSubPlatformId(int pin_or_bus_id)
{
    return static_cast<bool>(mraa_is_sub_platform_id(pin_or_bus_id));
}

/**
 * Convert pin or bus index to corresponding sub platform id.
 *
 * @param int pin or bus index
 *
 * @return int sub platform pin or bus number
 */
inline int
getSubPlatformId(int pin_or_bus_index)
{
    return mraa_get_sub_platform_id(pin_or_bus_index);
}

/**
 * Convert pin or bus sub platform id to index.
 *
 * @param int sub platform pin or bus id
 *
 * @return int pin or bus index
 */
inline int
getSubPlatformIndex(int pin_or_bus_id)
{
    return mraa_get_sub_platform_index(pin_or_bus_id);
}

/**
 * Get default i2c bus, board must be initialised.
 *
 * @param optional subplatform identifier
 * @return default i2c bus for paltform
 */
inline int
getDefaultI2cBus(int platform_offset=MRAA_MAIN_PLATFORM_OFFSET)
{
    return mraa_get_default_i2c_bus(platform_offset);
}
}
<|endoftext|>


<commit_before>#include "stdafx.h"
#include "CppUnitTest.h"
#include "..\Project2\list.h"
#include "..\Project2\list.cpp"

using namespace Microsoft::VisualStudio::CppUnitTestFramework;
using namespace NP_ADT;

namespace Project2Tests
{
	TEST_CLASS(ListTests)
	{
	public:

		TEST_METHOD(TestEmptyConstructor)
		{
			CDLL<int> test = CDLL<int>();
			Assert::AreEqual(unsigned int(0), test.getSize());
			Assert::IsTrue(nullptr == test.head());
			Assert::IsTrue(nullptr == test.tail());
		}

		TEST_METHOD(TestPushFrontConnections)
		{
			CDLL<int> test = CDLL<int>();
			test.push_front(5);
			test.push_front(0);

			Assert::IsTrue(test.head() == test.head()->next->prev);
			Assert::IsTrue(test.head() == test.head()->prev->next);
			Assert::IsTrue(test.tail() == test.tail()->next->prev);
			Assert::IsTrue(test.tail() == test.tail()->prev->next);
		}

		TEST_METHOD(TestPushBackConnections)
		{
			CDLL<int> test = CDLL<int>();
			test.push_back(5);
			test.push_back(0);

			Assert::IsTrue(test.head() == test.head()->next->prev);
			Assert::IsTrue(test.head() == test.head()->prev->next);
			Assert::IsTrue(test.tail() == test.tail()->next->prev);
			Assert::IsTrue(test.tail() == test.tail()->prev->next);
		}

		TEST_METHOD(TestOnePushFrontItemList) {
			CDLL<int> test = CDLL<int>();
			test.push_front(0);

			CDLL<int>::node * thisThing = test.head();

			Assert::AreEqual(unsigned int(1), test.getSize());
			Assert::IsTrue(unsigned int(0) == test.tail()->data);

			CDLL<int>::node * ptr = test.head();
			CDLL<int>::node * nextPtr = test.head()->next;
			CDLL<int>::node * doubleNextPtr = nextPtr->next;
			CDLL<int>::node * prevPtr = test.head()->prev;
			CDLL<int>::node * doublePrevPtr = prevPtr->prev;

			Assert::IsTrue(ptr == nextPtr);
			Assert::IsTrue(nextPtr == doubleNextPtr);
			Assert::IsTrue(doubleNextPtr == prevPtr);
			Assert::IsTrue(prevPtr == doublePrevPtr);
		}

		TEST_METHOD(TestTwoPushFrontItemList) {
			CDLL<int> test = CDLL<int>();
			test.push_front(0);
			test.push_front(1);
			// <-> 1 <-> 0 <->

			CDLL<int>::node * thisThing = test.head();

			Assert::AreEqual(unsigned int(2), test.getSize());

			Assert::IsTrue(unsigned int(1) == test.head()->data);
			Assert::IsTrue(unsigned int(0) == test.tail()->data);

			CDLL<int>::node * ptr = test.head();				// == 1
			CDLL<int>::node * nextPtr = test.head()->next;		// == 0
			CDLL<int>::node * doubleNextPtr = nextPtr->next;	// == 1
			CDLL<int>::node * prevPtr = test.head()->prev;		// == 0
			CDLL<int>::node * doublePrevPtr = prevPtr->prev;	// == 1

			Assert::IsTrue(ptr == doubleNextPtr);
			Assert::IsTrue(nextPtr == prevPtr);
			Assert::IsTrue(doubleNextPtr == doublePrevPtr);
			Assert::IsTrue(ptr != nextPtr);
		}

		TEST_METHOD(TestThreePushFrontItemList) {
			CDLL<int> test = CDLL<int>();
			test.push_front(0);
			test.push_front(1);
			test.push_front(2);
			// <-> 2 <-> 1 <-> 0 <->

			CDLL<int>::node * thisThing = test.head();

			Assert::AreEqual(unsigned int(3), test.getSize());

			Assert::IsTrue(unsigned int(2) == test.head()->data);
			Assert::IsTrue(unsigned int(0) == test.tail()->data);

			CDLL<int>::node * ptr = test.head();				// == 2
			CDLL<int>::node * nextPtr = test.head()->next;		// == 1
			CDLL<int>::node * doubleNextPtr = nextPtr->next;	// == 0
			CDLL<int>::node * prevPtr = test.head()->prev;		// == 0
			CDLL<int>::node * doublePrevPtr = prevPtr->prev;	// == 1

			Assert::IsTrue(ptr == doubleNextPtr->next);
			Assert::IsTrue(nextPtr == doublePrevPtr);
			Assert::IsTrue(prevPtr == doubleNextPtr);
			Assert::IsTrue(ptr != nextPtr);
			Assert::IsTrue(nextPtr != doubleNextPtr);
		}

		TEST_METHOD(TestOnePushBackItemList) {
			CDLL<int> test = CDLL<int>();
			test.push_back(0);

			CDLL<int>::node * thisThing = test.head();

			Assert::AreEqual(unsigned int(1), test.getSize());
			Assert::IsTrue(unsigned int(0) == test.tail()->data);

			CDLL<int>::node * ptr = test.head();
			CDLL<int>::node * nextPtr = test.head()->next;
			CDLL<int>::node * doubleNextPtr = nextPtr->next;
			CDLL<int>::node * prevPtr = test.head()->prev;
			CDLL<int>::node * doublePrevPtr = prevPtr->prev;

			Assert::IsTrue(ptr == nextPtr);
			Assert::IsTrue(nextPtr == doubleNextPtr);
			Assert::IsTrue(doubleNextPtr == prevPtr);
			Assert::IsTrue(prevPtr == doublePrevPtr);
		}

		TEST_METHOD(TestTwoPushBackItemList) {
			CDLL<int> test = CDLL<int>();
			test.push_back(0);
			test.push_back(1);
			// <-> 0 <-> 1 <->

			CDLL<int>::node * thisThing = test.head();

			Assert::AreEqual(unsigned int(2), test.getSize());

			Assert::IsTrue(unsigned int(0) == test.head()->data);
			Assert::IsTrue(unsigned int(1) == test.tail()->data);

			CDLL<int>::node * ptr = test.head();				// == 0
			CDLL<int>::node * nextPtr = test.head()->next;		// == 1
			CDLL<int>::node * doubleNextPtr = nextPtr->next;	// == 0
			CDLL<int>::node * prevPtr = test.head()->prev;		// == 1
			CDLL<int>::node * doublePrevPtr = prevPtr->prev;	// == 0

			Assert::IsTrue(ptr == doubleNextPtr);
			Assert::IsTrue(nextPtr == prevPtr);
			Assert::IsTrue(doubleNextPtr == doublePrevPtr);
			Assert::IsTrue(ptr != nextPtr);
		}

		TEST_METHOD(TestThreePushBackItemList) {
			CDLL<int> test = CDLL<int>();
			test.push_back(0);
			test.push_back(1);
			test.push_back(2);
			// <-> 0 <-> 1 <-> 2 <->

			CDLL<int>::node * thisThing = test.head();

			Assert::AreEqual(unsigned int(3), test.getSize());

			Assert::IsTrue(unsigned int(0) == test.head()->data);
			Assert::IsTrue(unsigned int(2) == test.tail()->data);

			CDLL<int>::node * ptr = test.head();				// == 0
			CDLL<int>::node * nextPtr = test.head()->next;		// == 1
			CDLL<int>::node * doubleNextPtr = nextPtr->next;	// == 2
			CDLL<int>::node * prevPtr = test.head()->prev;		// == 2
			CDLL<int>::node * doublePrevPtr = prevPtr->prev;	// == 0

			Assert::IsTrue(ptr == doubleNextPtr->next);
			Assert::IsTrue(nextPtr == doublePrevPtr);
			Assert::IsTrue(prevPtr == doubleNextPtr);
			Assert::IsTrue(ptr != nextPtr);
			Assert::IsTrue(nextPtr != doubleNextPtr);
		}
	};
}<commit_msg>create tests for popping<commit_after>#include "stdafx.h"
#include "CppUnitTest.h"
#include "..\Project2\list.h"
#include "..\Project2\list.cpp"

using namespace Microsoft::VisualStudio::CppUnitTestFramework;
using namespace NP_ADT;

namespace Project2Tests
{
	TEST_CLASS(ListTests)
	{
	public:

		TEST_METHOD(TestEmptyConstructor)
		{
			CDLL<int> test = CDLL<int>();
			Assert::AreEqual(unsigned int(0), test.getSize());
			Assert::IsTrue(nullptr == test.head());
			Assert::IsTrue(nullptr == test.tail());
		}

		TEST_METHOD(TestPushFrontConnections)
		{
			CDLL<int> test = CDLL<int>();
			test.push_front(5);
			test.push_front(0);

			Assert::IsTrue(test.head() == test.head()->next->prev);
			Assert::IsTrue(test.head() == test.head()->prev->next);
			Assert::IsTrue(test.tail() == test.tail()->next->prev);
			Assert::IsTrue(test.tail() == test.tail()->prev->next);
		}

		TEST_METHOD(TestPushBackConnections)
		{
			CDLL<int> test = CDLL<int>();
			test.push_back(5);
			test.push_back(0);

			Assert::IsTrue(test.head() == test.head()->next->prev);
			Assert::IsTrue(test.head() == test.head()->prev->next);
			Assert::IsTrue(test.tail() == test.tail()->next->prev);
			Assert::IsTrue(test.tail() == test.tail()->prev->next);
		}

		TEST_METHOD(TestOnePushFrontItemList) {
			CDLL<int> test = CDLL<int>();
			test.push_front(0);

			CDLL<int>::node * thisThing = test.head();

			Assert::AreEqual(unsigned int(1), test.getSize());
			Assert::IsTrue(unsigned int(0) == test.tail()->data);

			CDLL<int>::node * ptr = test.head();
			CDLL<int>::node * nextPtr = test.head()->next;
			CDLL<int>::node * doubleNextPtr = nextPtr->next;
			CDLL<int>::node * prevPtr = test.head()->prev;
			CDLL<int>::node * doublePrevPtr = prevPtr->prev;

			Assert::IsTrue(ptr == nextPtr);
			Assert::IsTrue(nextPtr == doubleNextPtr);
			Assert::IsTrue(doubleNextPtr == prevPtr);
			Assert::IsTrue(prevPtr == doublePrevPtr);
		}

		TEST_METHOD(TestTwoPushFrontItemList) {
			CDLL<int> test = CDLL<int>();
			test.push_front(0);
			test.push_front(1);
			// <-> 1 <-> 0 <->

			CDLL<int>::node * thisThing = test.head();

			Assert::AreEqual(unsigned int(2), test.getSize());

			Assert::IsTrue(unsigned int(1) == test.head()->data);
			Assert::IsTrue(unsigned int(0) == test.tail()->data);

			CDLL<int>::node * ptr = test.head();				// == 1
			CDLL<int>::node * nextPtr = test.head()->next;		// == 0
			CDLL<int>::node * doubleNextPtr = nextPtr->next;	// == 1
			CDLL<int>::node * prevPtr = test.head()->prev;		// == 0
			CDLL<int>::node * doublePrevPtr = prevPtr->prev;	// == 1

			Assert::IsTrue(ptr == doubleNextPtr);
			Assert::IsTrue(nextPtr == prevPtr);
			Assert::IsTrue(doubleNextPtr == doublePrevPtr);
			Assert::IsTrue(ptr != nextPtr);
		}

		TEST_METHOD(TestThreePushFrontItemList) {
			CDLL<int> test = CDLL<int>();
			test.push_front(0);
			test.push_front(1);
			test.push_front(2);
			// <-> 2 <-> 1 <-> 0 <->

			CDLL<int>::node * thisThing = test.head();

			Assert::AreEqual(unsigned int(3), test.getSize());

			Assert::IsTrue(unsigned int(2) == test.head()->data);
			Assert::IsTrue(unsigned int(0) == test.tail()->data);

			CDLL<int>::node * ptr = test.head();				// == 2
			CDLL<int>::node * nextPtr = test.head()->next;		// == 1
			CDLL<int>::node * doubleNextPtr = nextPtr->next;	// == 0
			CDLL<int>::node * prevPtr = test.head()->prev;		// == 0
			CDLL<int>::node * doublePrevPtr = prevPtr->prev;	// == 1

			Assert::IsTrue(ptr == doubleNextPtr->next);
			Assert::IsTrue(nextPtr == doublePrevPtr);
			Assert::IsTrue(prevPtr == doubleNextPtr);
			Assert::IsTrue(ptr != nextPtr);
			Assert::IsTrue(nextPtr != doubleNextPtr);
		}

		TEST_METHOD(TestOnePushBackItemList) {
			CDLL<int> test = CDLL<int>();
			test.push_back(0);

			CDLL<int>::node * thisThing = test.head();

			Assert::AreEqual(unsigned int(1), test.getSize());
			Assert::IsTrue(unsigned int(0) == test.tail()->data);

			CDLL<int>::node * ptr = test.head();
			CDLL<int>::node * nextPtr = test.head()->next;
			CDLL<int>::node * doubleNextPtr = nextPtr->next;
			CDLL<int>::node * prevPtr = test.head()->prev;
			CDLL<int>::node * doublePrevPtr = prevPtr->prev;

			Assert::IsTrue(ptr == nextPtr);
			Assert::IsTrue(nextPtr == doubleNextPtr);
			Assert::IsTrue(doubleNextPtr == prevPtr);
			Assert::IsTrue(prevPtr == doublePrevPtr);
		}

		TEST_METHOD(TestTwoPushBackItemList) {
			CDLL<int> test = CDLL<int>();
			test.push_back(0);
			test.push_back(1);
			// <-> 0 <-> 1 <->

			CDLL<int>::node * thisThing = test.head();

			Assert::AreEqual(unsigned int(2), test.getSize());

			Assert::IsTrue(unsigned int(0) == test.head()->data);
			Assert::IsTrue(unsigned int(1) == test.tail()->data);

			CDLL<int>::node * ptr = test.head();				// == 0
			CDLL<int>::node * nextPtr = test.head()->next;		// == 1
			CDLL<int>::node * doubleNextPtr = nextPtr->next;	// == 0
			CDLL<int>::node * prevPtr = test.head()->prev;		// == 1
			CDLL<int>::node * doublePrevPtr = prevPtr->prev;	// == 0

			Assert::IsTrue(ptr == doubleNextPtr);
			Assert::IsTrue(nextPtr == prevPtr);
			Assert::IsTrue(doubleNextPtr == doublePrevPtr);
			Assert::IsTrue(ptr != nextPtr);
		}

		TEST_METHOD(TestThreePushBackItemList) {
			CDLL<int> test = CDLL<int>();
			test.push_back(0);
			test.push_back(1);
			test.push_back(2);
			// <-> 0 <-> 1 <-> 2 <->

			CDLL<int>::node * thisThing = test.head();

			Assert::AreEqual(unsigned int(3), test.getSize());

			Assert::IsTrue(unsigned int(0) == test.head()->data);
			Assert::IsTrue(unsigned int(2) == test.tail()->data);

			CDLL<int>::node * ptr = test.head();				// == 0
			CDLL<int>::node * nextPtr = test.head()->next;		// == 1
			CDLL<int>::node * doubleNextPtr = nextPtr->next;	// == 2
			CDLL<int>::node * prevPtr = test.head()->prev;		// == 2
			CDLL<int>::node * doublePrevPtr = prevPtr->prev;	// == 0

			Assert::IsTrue(ptr == doubleNextPtr->next);
			Assert::IsTrue(nextPtr == doublePrevPtr);
			Assert::IsTrue(prevPtr == doubleNextPtr);
			Assert::IsTrue(ptr != nextPtr);
			Assert::IsTrue(nextPtr != doubleNextPtr);
		}

		TEST_METHOD(TestPopFrontEmptyList) {
			bool exceptionThrown = false;
			auto test = CDLL<int>();
			try {
				test.pop_front();
			}
			catch (runtime_error) {
				exceptionThrown = true;
			}
			Assert::IsTrue(exceptionThrown);
		}

		TEST_METHOD(TestPopFrontAfterPushFront) {
			auto test = CDLL<int>();
			test.push_front(1);
			Assert::AreEqual(1, test.pop_front());
			Assert::IsTrue(test.head() == nullptr);
			Assert::IsTrue(test.tail() == nullptr);
		}

		TEST_METHOD(TestPopFrontAfterTwoPushFront) {
			auto test = CDLL<int>();
			test.push_front(1);
			test.push_front(2);
			Assert::AreEqual(2, test.pop_front());
			Assert::IsTrue(test.head()->next->prev == test.head());
			Assert::IsTrue(test.head()->prev->next == test.head());
			Assert::AreEqual(1, test.pop_front());
			Assert::IsTrue(test.head() == nullptr);
			Assert::IsTrue(test.tail() == nullptr);
		}

		TEST_METHOD(TestPopFrontAfterThreePushFront) {
			auto test = CDLL<int>();
			test.push_front(1);
			test.push_front(2);
			test.push_front(3);
			Assert::AreEqual(3, test.pop_front());
			Assert::IsTrue(test.head()->next->prev == test.head());
			Assert::IsTrue(test.head()->prev->next == test.head());
			Assert::AreEqual(2, test.pop_front());
			Assert::IsTrue(test.head()->next->prev == test.head());
			Assert::IsTrue(test.head()->prev->next == test.head());
			Assert::AreEqual(1, test.pop_front());
			Assert::IsTrue(test.head() == nullptr);
			Assert::IsTrue(test.tail() == nullptr);
		}

		TEST_METHOD(TestPopFrontAfterPushBack) {
			auto test = CDLL<int>();
			test.push_back(1);
			Assert::AreEqual(1, test.pop_front());
			Assert::IsTrue(test.head() == nullptr);
			Assert::IsTrue(test.tail() == nullptr);
		}

		TEST_METHOD(TestPopFrontAfterTwoPushBack) {
			auto test = CDLL<int>();
			test.push_back(1);
			test.push_back(2);
			Assert::AreEqual(1, test.pop_front());
			Assert::IsTrue(test.head()->next->prev == test.head());
			Assert::IsTrue(test.head()->prev->next == test.head());
			Assert::AreEqual(2, test.pop_front());
			Assert::IsTrue(test.head() == nullptr);
			Assert::IsTrue(test.tail() == nullptr);
		}

		TEST_METHOD(TestPopFrontAfterThreePushBack) {
			auto test = CDLL<int>();
			test.push_back(1);
			test.push_back(2);
			test.push_back(3);
			Assert::AreEqual(1, test.pop_front());
			Assert::IsTrue(test.head()->next->prev == test.head());
			Assert::IsTrue(test.head()->prev->next == test.head());
			Assert::AreEqual(2, test.pop_front());
			Assert::IsTrue(test.head()->next->prev == test.head());
			Assert::IsTrue(test.head()->prev->next == test.head());
			Assert::AreEqual(3, test.pop_front());
			Assert::IsTrue(test.head() == nullptr);
			Assert::IsTrue(test.tail() == nullptr);
		}

		TEST_METHOD(TestPopFrontRandomPushSeries) {
			auto test = CDLL<int>();
			test.push_back(1);
			test.push_front(4);
			test.push_back(3);
			test.push_front(2);
			test.push_back(5);
			test.push_back(6);

			Assert::AreEqual(2, test.pop_front());
			Assert::IsTrue(test.head()->next->prev == test.head());
			Assert::IsTrue(test.head()->prev->next == test.head());
			Assert::AreEqual(4, test.pop_front());
			Assert::IsTrue(test.head()->next->prev == test.head());
			Assert::IsTrue(test.head()->prev->next == test.head());
			Assert::AreEqual(1, test.pop_front());
			Assert::IsTrue(test.head()->next->prev == test.head());
			Assert::IsTrue(test.head()->prev->next == test.head());
			Assert::AreEqual(3, test.pop_front());
			Assert::IsTrue(test.head()->next->prev == test.head());
			Assert::IsTrue(test.head()->prev->next == test.head());
			Assert::AreEqual(5, test.pop_front());
			Assert::IsTrue(test.head()->next->prev == test.head());
			Assert::IsTrue(test.head()->prev->next == test.head());
			Assert::AreEqual(6, test.pop_front());
			Assert::IsTrue(test.head() == nullptr);
			Assert::IsTrue(test.tail() == nullptr);
		}
	};
}<|endoftext|>


<commit_before>/*
 *
 */

#include <iostream>
#include <chrono>
#include <cstdint>
#include <string>
#include <thread>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#include <comm/usb.hpp>
#include <comm/buffer.hpp>
#include <comm/util/priority.hpp>

int main (int argc, char *argv[])
{
    const uint16_t vid = 0x04b4;    // Netchip Technology, Inc
    const uint16_t pid = 0x00f1;    // Linux-USB "Gadget Zero"
    const std::string name = "/tmp/usb_to_pipe";
    const int thresh = 1;
    std::atomic<size_t> sum(0);

    comm::util::set_realtime_priority();

    comm::usb::source src(vid, pid, comm::usb::endpoint::EP6_IN);

    std::thread usb([&]{ while(true) src(); });
    usb.detach();

    std::thread throughput([&]{
        while (true)
        {
            comm::util::set_normal_priority();

            sum = 0;

            auto start = std::chrono::steady_clock::now();

            std::this_thread::sleep_for(std::chrono::seconds(1));

            auto end = std::chrono::steady_clock::now();

            std::chrono::duration<double> diff = end - start;

            std::cout << "Effective rate: " << sum / 2.0 / diff.count() / 1e6 << " Msps" << std::endl;
        }
    });
    throughput.detach();

    auto out = src.make_reader<unsigned char>();

    if (mkfifo(name.c_str(), 0666) == -1)
        throw std::runtime_error("Unable to create a named pipe");

    int fd = open(name.c_str(), O_WRONLY);
    if (fd == -1)
        throw std::runtime_error("Unable to open the named pipe");

    while (true)
    {
        out.wait(thresh);

        size_t len = out.size();

        if (write(fd, out.begin(), len) == -1)
            throw std::runtime_error("Failed to write to the named pipe");

        out.consume(len);

        sum += len;
    }

    return 0;
}
<commit_msg>app: add floating point formating<commit_after>/*
 *
 */

#include <iostream>
#include <iomanip>
#include <chrono>
#include <cstdint>
#include <string>
#include <thread>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#include <comm/usb.hpp>
#include <comm/buffer.hpp>
#include <comm/util/priority.hpp>

int main (int argc, char *argv[])
{
    const uint16_t vid = 0x04b4;    // Netchip Technology, Inc
    const uint16_t pid = 0x00f1;    // Linux-USB "Gadget Zero"
    const std::string name = "/tmp/usb_to_pipe";
    const int thresh = 1;
    std::atomic<size_t> sum(0);

    comm::util::set_realtime_priority();

    comm::usb::source src(vid, pid, comm::usb::endpoint::EP6_IN);

    std::thread usb([&]{ while(true) src(); });
    usb.detach();

    std::thread throughput([&]{
        std::cout << std::fixed << std::setprecision(2);

        while (true)
        {
            comm::util::set_normal_priority();

            sum = 0;

            auto start = std::chrono::steady_clock::now();

            std::this_thread::sleep_for(std::chrono::seconds(1));

            auto end = std::chrono::steady_clock::now();

            std::chrono::duration<double> diff = end - start;

            std::cout << "Effective rate: " << sum / 2.0 / diff.count() / 1e6 << " Msps" << std::endl;
        }
    });
    throughput.detach();

    auto out = src.make_reader<unsigned char>();

    if (mkfifo(name.c_str(), 0666) == -1)
        throw std::runtime_error("Unable to create a named pipe");

    int fd = open(name.c_str(), O_WRONLY);
    if (fd == -1)
        throw std::runtime_error("Unable to open the named pipe");

    while (true)
    {
        out.wait(thresh);

        size_t len = out.size();

        if (write(fd, out.begin(), len) == -1)
            throw std::runtime_error("Failed to write to the named pipe");

        out.consume(len);

        sum += len;
    }

    return 0;
}
<|endoftext|>