<commit_before>/*
    This file is part of libkcal.
    Copyright (c) 1998 Preston Brown
    Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
    Boston, MA 02111-1307, USA.
*/

#include <kdebug.h>

#include "incidence.h"
#include "todo.h"

#include "alarm.h"

using namespace KCal;

Alarm::Alarm(Incidence *parent)
 : mParent(parent),
   mType(Invalid),
   mDescription(""),    // to make operator==() not fail
   mFile(""),           // to make operator==() not fail
   mMailSubject(""),    // to make operator==() not fail
   mAlarmSnoozeTime(5),
   mAlarmRepeatCount(0),
   mEndOffset(false),
   mHasTime(false),
   mAlarmEnabled(false)
{
}

Alarm::~Alarm()
{
}

bool Alarm::operator==( const Alarm& rhs ) const
{
  if ( mType != rhs.mType ||
       mAlarmSnoozeTime != rhs.mAlarmSnoozeTime ||
       mAlarmRepeatCount != rhs.mAlarmRepeatCount ||
       mAlarmEnabled != rhs.mAlarmEnabled ||
       mHasTime != rhs.mHasTime)
    return false;

  if (mHasTime) {
    if (mAlarmTime != rhs.mAlarmTime)
      return false;
  } else {
    if (mOffset != rhs.mOffset ||
        mEndOffset != rhs.mEndOffset)
      return false;
  }

  switch (mType) {
    case Display:
      return mDescription == rhs.mDescription;

    case Email:
      return mDescription == rhs.mDescription &&
             mMailAttachFiles == rhs.mMailAttachFiles &&
             mMailAddresses == rhs.mMailAddresses &&
             mMailSubject == rhs.mMailSubject;

    case Procedure:
      return mFile == rhs.mFile &&
             mDescription == rhs.mDescription;

    case Audio:
      return mFile == rhs.mFile;

    case Invalid:
      break;
  }
  return false;
}

void Alarm::setType(Alarm::Type type)
{
  if (type == mType)
    return;

  switch (type) {
    case Display:
      mDescription = "";
      break;
    case Procedure:
      mFile = mDescription = "";
      break;
    case Audio:
      mFile = "";
      break;
    case Email:
      mMailSubject = mDescription = "";
      mMailAddresses.clear();
      mMailAttachFiles.clear();
      break;
    case Invalid:
      break;
    default:
      return;
  }
  mType = type;
  mParent->updated();
}

Alarm::Type Alarm::type() const
{
  return mType;
}

void Alarm::setAudioAlarm(const QString &audioFile)
{
  mType = Audio;
  mFile = audioFile;
  mParent->updated();
}

void Alarm::setAudioFile(const QString &audioFile)
{
  if (mType == Audio) {
    mFile = audioFile;
    mParent->updated();
  }
}

QString Alarm::audioFile() const
{
  return (mType == Audio) ? mFile : QString::null;
}

void Alarm::setProcedureAlarm(const QString &programFile, const QString &arguments)
{
  mType = Procedure;
  mFile = programFile;
  mDescription = arguments;
  mParent->updated();
}

void Alarm::setProgramFile(const QString &programFile)
{
  if (mType == Procedure) {
    mFile = programFile;
    mParent->updated();
  }
}

QString Alarm::programFile() const
{
  return (mType == Procedure) ? mFile : QString::null;
}

void Alarm::setProgramArguments(const QString &arguments)
{
  if (mType == Procedure) {
    mDescription = arguments;
    mParent->updated();
  }
}

QString Alarm::programArguments() const
{
  return (mType == Procedure) ? mDescription : QString::null;
}

void Alarm::setEmailAlarm(const QString &subject, const QString &text,
                          const QValueList<Person> &addressees, const QStringList &attachments)
{
  mType = Email;
  mMailSubject = subject;
  mDescription = text;
  mMailAddresses = addressees;
  mMailAttachFiles = attachments;
  mParent->updated();
}

void Alarm::setMailAddress(const Person &mailAddress)
{
  if (mType == Email) {
    mMailAddresses.clear();
    mMailAddresses += mailAddress;
    mParent->updated();
  }
}

void Alarm::setMailAddresses(const QValueList<Person> &mailAddresses)
{
  if (mType == Email) {
    mMailAddresses = mailAddresses;
    mParent->updated();
  }
}

void Alarm::addMailAddress(const Person &mailAddress)
{
  if (mType == Email) {
    mMailAddresses += mailAddress;
    mParent->updated();
  }
}

QValueList<Person> Alarm::mailAddresses() const
{
  return (mType == Email) ? mMailAddresses : QValueList<Person>();
}

void Alarm::setMailSubject(const QString &mailAlarmSubject)
{
  if (mType == Email) {
    mMailSubject = mailAlarmSubject;
    mParent->updated();
  }
}

QString Alarm::mailSubject() const
{
  return (mType == Email) ? mMailSubject : QString::null;
}

void Alarm::setMailAttachment(const QString &mailAttachFile)
{
  if (mType == Email) {
    mMailAttachFiles.clear();
    mMailAttachFiles += mailAttachFile;
    mParent->updated();
  }
}

void Alarm::setMailAttachments(const QStringList &mailAttachFiles)
{
  if (mType == Email) {
    mMailAttachFiles = mailAttachFiles;
    mParent->updated();
  }
}

void Alarm::addMailAttachment(const QString &mailAttachFile)
{
  if (mType == Email) {
    mMailAttachFiles += mailAttachFile;
    mParent->updated();
  }
}

QStringList Alarm::mailAttachments() const
{
  return (mType == Email) ? mMailAttachFiles : QStringList();
}

void Alarm::setMailText(const QString &text)
{
  if (mType == Email) {
    mDescription = text;
    mParent->updated();
  }
}

QString Alarm::mailText() const
{
  return (mType == Email) ? mDescription : QString::null;
}

void Alarm::setDisplayAlarm(const QString &text)
{
  mType = Display;
  mDescription = text;
  mParent->updated();
}

void Alarm::setText(const QString &text)
{
  if (mType == Display) {
    mDescription = text;
    mParent->updated();
  }
}

QString Alarm::text() const
{
  return (mType == Display) ? mDescription : QString::null;
}

void Alarm::setTime(const QDateTime &alarmTime)
{
  mAlarmTime = alarmTime;
  mHasTime = true;

  mParent->updated();
}

QDateTime Alarm::time() const
{
  if ( hasTime() )
    return mAlarmTime;
  else
  {
    if (mParent->type()=="Todo") {
      Todo *t = static_cast<Todo*>(mParent);
      return mOffset.end( t->dtDue() );
    } else if (mEndOffset) {
      return mOffset.end( mParent->dtEnd() );
    } else {
      return mOffset.end( mParent->dtStart() );
    }
  }
}

bool Alarm::hasTime() const
{
  return mHasTime;
}

void Alarm::setSnoozeTime(int alarmSnoozeTime)
{
  if (alarmSnoozeTime > 0) {
    mAlarmSnoozeTime = alarmSnoozeTime;
    mParent->updated();
  }
}

int Alarm::snoozeTime() const
{
  return mAlarmSnoozeTime;
}

void Alarm::setRepeatCount(int alarmRepeatCount)
{
  if (alarmRepeatCount >= 0) {
    mAlarmRepeatCount = alarmRepeatCount;
    mParent->updated();
  }
}

int Alarm::repeatCount() const
{
  return mAlarmRepeatCount;
}

int Alarm::duration() const
{
  return mAlarmRepeatCount * mAlarmSnoozeTime * 60;
}

QDateTime Alarm::nextRepetition(const QDateTime& preTime) const
{
  // This method is coded to avoid 32-bit integer overflow using
  // QDateTime::secsTo(), which occurs with time spans > 68 years.
  QDateTime at = time();
  if (at > preTime)
    return at;
  if (!mAlarmRepeatCount)
    return QDateTime();   // there isn't an occurrence after the specified time
  int snoozeSecs = mAlarmSnoozeTime * 60;
  QDateTime lastRepetition = at.addSecs(mAlarmRepeatCount * snoozeSecs);
  if (lastRepetition <= preTime)
    return QDateTime();    // all repetitions have finished before the specified time
  int repetition = (at.secsTo(preTime) + snoozeSecs) / snoozeSecs;
  return at.addSecs(repetition * snoozeSecs);
}

QDateTime Alarm::previousRepetition(const QDateTime& afterTime) const
{
  // This method is coded to avoid 32-bit integer overflow using
  // QDateTime::secsTo(), which occurs with time spans > 68 years.
  QDateTime at = time();
  if (at >= afterTime)
    return QDateTime();    // alarm's first/only time is at/after the specified time
  if (!mAlarmRepeatCount)
    return at;
  int snoozeSecs = mAlarmSnoozeTime * 60;
  QDateTime lastRepetition = at.addSecs(mAlarmRepeatCount * snoozeSecs);
  if (lastRepetition < afterTime)
    return lastRepetition;   // all repetitions have finished before the specified time
  int repetition = (at.secsTo(afterTime) - 1) / snoozeSecs;
  return at.addSecs(repetition * snoozeSecs);
}

QDateTime Alarm::endTime() const
{
  if (mAlarmRepeatCount)
    return time().addSecs(mAlarmRepeatCount * mAlarmSnoozeTime * 60);
  else
    return time();
}

void Alarm::toggleAlarm()
{
  mAlarmEnabled = !mAlarmEnabled;
  mParent->updated();
}

void Alarm::setEnabled(bool enable)
{
  mAlarmEnabled = enable;
  mParent->updated();
}

bool Alarm::enabled() const
{
  return mAlarmEnabled;
}

void Alarm::setStartOffset( const Duration &offset )
{
  mOffset = offset;
  mEndOffset = false;
  mHasTime = false;
  mParent->updated();
}

Duration Alarm::startOffset() const
{
  return (mHasTime || mEndOffset) ? 0 : mOffset;
}

bool Alarm::hasStartOffset() const
{
  return !mHasTime && !mEndOffset;
}

bool Alarm::hasEndOffset() const
{
  return !mHasTime && mEndOffset;
}

void Alarm::setEndOffset( const Duration &offset )
{
  mOffset = offset;
  mEndOffset = true;
  mHasTime = false;
  mParent->updated();
}

Duration Alarm::endOffset() const
{
  return (mHasTime || !mEndOffset) ? 0 : mOffset;
}

void Alarm::setParent( Incidence *parent )
{
  mParent = parent;
}
<commit_msg>Relax checks on repeat count value<commit_after>/*
    This file is part of libkcal.
    Copyright (c) 1998 Preston Brown
    Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
    Boston, MA 02111-1307, USA.
*/

#include <kdebug.h>

#include "incidence.h"
#include "todo.h"

#include "alarm.h"

using namespace KCal;

Alarm::Alarm(Incidence *parent)
 : mParent(parent),
   mType(Invalid),
   mDescription(""),    // to make operator==() not fail
   mFile(""),           // to make operator==() not fail
   mMailSubject(""),    // to make operator==() not fail
   mAlarmSnoozeTime(5),
   mAlarmRepeatCount(0),
   mEndOffset(false),
   mHasTime(false),
   mAlarmEnabled(false)
{
}

Alarm::~Alarm()
{
}

bool Alarm::operator==( const Alarm& rhs ) const
{
  if ( mType != rhs.mType ||
       mAlarmSnoozeTime != rhs.mAlarmSnoozeTime ||
       mAlarmRepeatCount != rhs.mAlarmRepeatCount ||
       mAlarmEnabled != rhs.mAlarmEnabled ||
       mHasTime != rhs.mHasTime)
    return false;

  if (mHasTime) {
    if (mAlarmTime != rhs.mAlarmTime)
      return false;
  } else {
    if (mOffset != rhs.mOffset ||
        mEndOffset != rhs.mEndOffset)
      return false;
  }

  switch (mType) {
    case Display:
      return mDescription == rhs.mDescription;

    case Email:
      return mDescription == rhs.mDescription &&
             mMailAttachFiles == rhs.mMailAttachFiles &&
             mMailAddresses == rhs.mMailAddresses &&
             mMailSubject == rhs.mMailSubject;

    case Procedure:
      return mFile == rhs.mFile &&
             mDescription == rhs.mDescription;

    case Audio:
      return mFile == rhs.mFile;

    case Invalid:
      break;
  }
  return false;
}

void Alarm::setType(Alarm::Type type)
{
  if (type == mType)
    return;

  switch (type) {
    case Display:
      mDescription = "";
      break;
    case Procedure:
      mFile = mDescription = "";
      break;
    case Audio:
      mFile = "";
      break;
    case Email:
      mMailSubject = mDescription = "";
      mMailAddresses.clear();
      mMailAttachFiles.clear();
      break;
    case Invalid:
      break;
    default:
      return;
  }
  mType = type;
  mParent->updated();
}

Alarm::Type Alarm::type() const
{
  return mType;
}

void Alarm::setAudioAlarm(const QString &audioFile)
{
  mType = Audio;
  mFile = audioFile;
  mParent->updated();
}

void Alarm::setAudioFile(const QString &audioFile)
{
  if (mType == Audio) {
    mFile = audioFile;
    mParent->updated();
  }
}

QString Alarm::audioFile() const
{
  return (mType == Audio) ? mFile : QString::null;
}

void Alarm::setProcedureAlarm(const QString &programFile, const QString &arguments)
{
  mType = Procedure;
  mFile = programFile;
  mDescription = arguments;
  mParent->updated();
}

void Alarm::setProgramFile(const QString &programFile)
{
  if (mType == Procedure) {
    mFile = programFile;
    mParent->updated();
  }
}

QString Alarm::programFile() const
{
  return (mType == Procedure) ? mFile : QString::null;
}

void Alarm::setProgramArguments(const QString &arguments)
{
  if (mType == Procedure) {
    mDescription = arguments;
    mParent->updated();
  }
}

QString Alarm::programArguments() const
{
  return (mType == Procedure) ? mDescription : QString::null;
}

void Alarm::setEmailAlarm(const QString &subject, const QString &text,
                          const QValueList<Person> &addressees, const QStringList &attachments)
{
  mType = Email;
  mMailSubject = subject;
  mDescription = text;
  mMailAddresses = addressees;
  mMailAttachFiles = attachments;
  mParent->updated();
}

void Alarm::setMailAddress(const Person &mailAddress)
{
  if (mType == Email) {
    mMailAddresses.clear();
    mMailAddresses += mailAddress;
    mParent->updated();
  }
}

void Alarm::setMailAddresses(const QValueList<Person> &mailAddresses)
{
  if (mType == Email) {
    mMailAddresses = mailAddresses;
    mParent->updated();
  }
}

void Alarm::addMailAddress(const Person &mailAddress)
{
  if (mType == Email) {
    mMailAddresses += mailAddress;
    mParent->updated();
  }
}

QValueList<Person> Alarm::mailAddresses() const
{
  return (mType == Email) ? mMailAddresses : QValueList<Person>();
}

void Alarm::setMailSubject(const QString &mailAlarmSubject)
{
  if (mType == Email) {
    mMailSubject = mailAlarmSubject;
    mParent->updated();
  }
}

QString Alarm::mailSubject() const
{
  return (mType == Email) ? mMailSubject : QString::null;
}

void Alarm::setMailAttachment(const QString &mailAttachFile)
{
  if (mType == Email) {
    mMailAttachFiles.clear();
    mMailAttachFiles += mailAttachFile;
    mParent->updated();
  }
}

void Alarm::setMailAttachments(const QStringList &mailAttachFiles)
{
  if (mType == Email) {
    mMailAttachFiles = mailAttachFiles;
    mParent->updated();
  }
}

void Alarm::addMailAttachment(const QString &mailAttachFile)
{
  if (mType == Email) {
    mMailAttachFiles += mailAttachFile;
    mParent->updated();
  }
}

QStringList Alarm::mailAttachments() const
{
  return (mType == Email) ? mMailAttachFiles : QStringList();
}

void Alarm::setMailText(const QString &text)
{
  if (mType == Email) {
    mDescription = text;
    mParent->updated();
  }
}

QString Alarm::mailText() const
{
  return (mType == Email) ? mDescription : QString::null;
}

void Alarm::setDisplayAlarm(const QString &text)
{
  mType = Display;
  mDescription = text;
  mParent->updated();
}

void Alarm::setText(const QString &text)
{
  if (mType == Display) {
    mDescription = text;
    mParent->updated();
  }
}

QString Alarm::text() const
{
  return (mType == Display) ? mDescription : QString::null;
}

void Alarm::setTime(const QDateTime &alarmTime)
{
  mAlarmTime = alarmTime;
  mHasTime = true;

  mParent->updated();
}

QDateTime Alarm::time() const
{
  if ( hasTime() )
    return mAlarmTime;
  else
  {
    if (mParent->type()=="Todo") {
      Todo *t = static_cast<Todo*>(mParent);
      return mOffset.end( t->dtDue() );
    } else if (mEndOffset) {
      return mOffset.end( mParent->dtEnd() );
    } else {
      return mOffset.end( mParent->dtStart() );
    }
  }
}

bool Alarm::hasTime() const
{
  return mHasTime;
}

void Alarm::setSnoozeTime(int alarmSnoozeTime)
{
  if (alarmSnoozeTime > 0) {
    mAlarmSnoozeTime = alarmSnoozeTime;
    mParent->updated();
  }
}

int Alarm::snoozeTime() const
{
  return mAlarmSnoozeTime;
}

void Alarm::setRepeatCount(int alarmRepeatCount)
{
  mAlarmRepeatCount = alarmRepeatCount;
  mParent->updated();
}

int Alarm::repeatCount() const
{
  return mAlarmRepeatCount;
}

int Alarm::duration() const
{
  return mAlarmRepeatCount * mAlarmSnoozeTime * 60;
}

QDateTime Alarm::nextRepetition(const QDateTime& preTime) const
{
  // This method is coded to avoid 32-bit integer overflow using
  // QDateTime::secsTo(), which occurs with time spans > 68 years.
  QDateTime at = time();
  if (at > preTime)
    return at;
  if (!mAlarmRepeatCount)
    return QDateTime();   // there isn't an occurrence after the specified time
  int snoozeSecs = mAlarmSnoozeTime * 60;
  QDateTime lastRepetition = at.addSecs(mAlarmRepeatCount * snoozeSecs);
  if (lastRepetition <= preTime)
    return QDateTime();    // all repetitions have finished before the specified time
  int repetition = (at.secsTo(preTime) + snoozeSecs) / snoozeSecs;
  return at.addSecs(repetition * snoozeSecs);
}

QDateTime Alarm::previousRepetition(const QDateTime& afterTime) const
{
  // This method is coded to avoid 32-bit integer overflow using
  // QDateTime::secsTo(), which occurs with time spans > 68 years.
  QDateTime at = time();
  if (at >= afterTime)
    return QDateTime();    // alarm's first/only time is at/after the specified time
  if (!mAlarmRepeatCount)
    return at;
  int snoozeSecs = mAlarmSnoozeTime * 60;
  QDateTime lastRepetition = at.addSecs(mAlarmRepeatCount * snoozeSecs);
  if (lastRepetition < afterTime)
    return lastRepetition;   // all repetitions have finished before the specified time
  int repetition = (at.secsTo(afterTime) - 1) / snoozeSecs;
  return at.addSecs(repetition * snoozeSecs);
}

QDateTime Alarm::endTime() const
{
  if (mAlarmRepeatCount)
    return time().addSecs(mAlarmRepeatCount * mAlarmSnoozeTime * 60);
  else
    return time();
}

void Alarm::toggleAlarm()
{
  mAlarmEnabled = !mAlarmEnabled;
  mParent->updated();
}

void Alarm::setEnabled(bool enable)
{
  mAlarmEnabled = enable;
  mParent->updated();
}

bool Alarm::enabled() const
{
  return mAlarmEnabled;
}

void Alarm::setStartOffset( const Duration &offset )
{
  mOffset = offset;
  mEndOffset = false;
  mHasTime = false;
  mParent->updated();
}

Duration Alarm::startOffset() const
{
  return (mHasTime || mEndOffset) ? 0 : mOffset;
}

bool Alarm::hasStartOffset() const
{
  return !mHasTime && !mEndOffset;
}

bool Alarm::hasEndOffset() const
{
  return !mHasTime && mEndOffset;
}

void Alarm::setEndOffset( const Duration &offset )
{
  mOffset = offset;
  mEndOffset = true;
  mHasTime = false;
  mParent->updated();
}

Duration Alarm::endOffset() const
{
  return (mHasTime || !mEndOffset) ? 0 : mOffset;
}

void Alarm::setParent( Incidence *parent )
{
  mParent = parent;
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2015 Michal Parusinski <mparusinski@gmail.com>.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QPointer>

#include "controller/backendengineinterface.h"

int main(int argc, char *argv[])
{
	typedef QPointer<controller::BackendEngineInterface> BackendEngineInterfacePtr;
    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/sailfish-postbox-desktop.qml")));

    BackendEngineInterfacePtr backendEngineInterface =
    	new controller::BackendEngineInterface;

    if (!backendEngineInterface->initialize()) {
        // TODO: REPORT MEMORY ALLOCATION PROBLEM
    	return -1;
    }

    if (!backendEngineInterface->startNetworkingServices()) {
        // TODO: REPORT NETWORKING PROBLEM
        return -1;
    }

    QQmlContext * rootCtx = engine.rootContext();
    rootCtx->setContextProperty("backendEngineInterface", backendEngineInterface);

    return app.exec();
}
<commit_msg>Added comment in sailfish-postbox-desktop.cpp<commit_after>/*
 * Copyright (c) 2015 Michal Parusinski <mparusinski@gmail.com>.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QPointer>

#include "controller/backendengineinterface.h"

/*
 * Main function for the Desktop application
 */
int main(int argc, char *argv[])
{
	typedef QPointer<controller::BackendEngineInterface> BackendEngineInterfacePtr;
    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/sailfish-postbox-desktop.qml")));

    BackendEngineInterfacePtr backendEngineInterface =
    	new controller::BackendEngineInterface;

    if (!backendEngineInterface->initialize()) {
        // TODO: REPORT MEMORY ALLOCATION PROBLEM
    	return -1;
    }

    if (!backendEngineInterface->startNetworkingServices()) {
        // TODO: REPORT NETWORKING PROBLEM
        return -1;
    }

    QQmlContext * rootCtx = engine.rootContext();
    rootCtx->setContextProperty("backendEngineInterface", backendEngineInterface);

    return app.exec();
}
<|endoftext|>


<commit_before>#include "simplesp.h"
#include "spex/spcv.h"

using namespace sp;

void sample(cv::Mat &cvimg, const int key);

int main(){
    cv::VideoCapture cap(0);
    if (cap.isOpened() == false){
        printf("could not find USB camera\n");
        exit(0);
    }

    printf("'s' key : switch center pose / markers pose\n");
    printf("'ESC' key : exit\n");

    int key = 0;

    // 27 = 'ESC' key
    while ((key = cv::waitKey(1)) != 27){

        // capture
        cv::Mat cvimg;
        cap >> cvimg;

        sample(cvimg, key);

        cv::imshow("bitmarker", cvimg);
    }

    cv::destroyAllWindows();
    return 0;
}

void sample(cv::Mat &cvimg, const int key){
    Mem2<Col3> img;

    // convert data type
    cvCnvImg(img, cvimg);

    // markers parameter
    Mem1<BitMarkerParam> mrks;

    // set marker info
    {
        const int dsize[2] = { 4, 3 };
        const int block = 3;
        const double length = 60.0;
        const double interval = 5.0;

        //const int dsize[2] = { 8, 6 };
        //const int block = 3;
        //const double length = 28.0;
        //const double interval = 5.0;

        mrks = getBitMarkerParam(0, block, length, dsize[0], dsize[1], interval);

        SP_ONCE(saveBitMarkerParamSVG("mrks.svg", 0, block, length, dsize[0], dsize[1], interval));
    }

    // detector class
    BitMarker bitMarker;

    static bool flag = true;
    if (key == 's') flag ^= true;

    // detect marker
    if(flag){

        bitMarker.addMrks(mrks);

        bitMarker.execute(img);
    }
    else {
        for (int i = 0; i < mrks.size(); i++) {
            mrks[i].offset = zeroPose();
            bitMarker.addMrks(mrks[i]);
        }

        bitMarker.execute(img);
    }

    // render
    {
        for (int i = 0; i < bitMarker.size(); i++) {
            if (bitMarker.getPose(i) == NULL) continue;

            const Mem1<Vec2> &cpixs = *bitMarker.getCrspPixs(i);
            renderPoint(img, cpixs, getCol(0, 255, 255), 3);

            renderAxis(img, bitMarker.getCam(), *bitMarker.getPose(i), 30.0, 2);
        }
    }

    cvCnvImg(cvimg, img);
}

<commit_msg>refactoring<commit_after>#include "simplesp.h"
#include "spex/spcv.h"

using namespace sp;

void sample(cv::Mat &cvimg, const int key);

int main(){
    cv::VideoCapture cap(0);
    if (cap.isOpened() == false){
        printf("could not find USB camera\n");
        exit(0);
    }

    printf("'s' key : switch center pose / each poses\n");
    printf("'ESC' key : exit\n");

    int key = 0;

    // 27 = 'ESC' key
    while ((key = cv::waitKey(1)) != 27){

        // capture
        cv::Mat cvimg;
        cap >> cvimg;

        sample(cvimg, key);

        cv::imshow("bitmarker", cvimg);
    }

    cv::destroyAllWindows();
    return 0;
}

void sample(cv::Mat &cvimg, const int key){
    Mem2<Col3> img;

    // convert data type
    cvCnvImg(img, cvimg);

    // markers parameter
    Mem1<BitMarkerParam> mrks;

    // set marker info
    {
        const int dsize[2] = { 4, 3 };
        const int block = 3;
        const double length = 60.0;
        const double interval = 5.0;

        //const int dsize[2] = { 8, 6 };
        //const int block = 3;
        //const double length = 28.0;
        //const double interval = 5.0;

        mrks = getBitMarkerParam(0, block, length, dsize[0], dsize[1], interval);

        SP_ONCE(saveBitMarkerParamSVG("mrks.svg", 0, block, length, dsize[0], dsize[1], interval));
    }

    // detector class
    BitMarker bitMarker;

    static bool mode = true;
    if (key == 's') mode ^= true;

    // detect marker
    if(mode){
        // center pose

        bitMarker.addMrks(mrks);

        bitMarker.execute(img);
    }
    else {
        // each poses

        for (int i = 0; i < mrks.size(); i++) {
            mrks[i].offset = zeroPose();
            bitMarker.addMrks(mrks[i]);
        }

        bitMarker.execute(img);
    }

    // render
    {
        for (int i = 0; i < bitMarker.size(); i++) {
            if (bitMarker.getPose(i) == NULL) continue;

            const Mem1<Vec2> &cpixs = *bitMarker.getCrspPixs(i);
            renderPoint(img, cpixs, getCol(0, 255, 255), 3);

            renderAxis(img, bitMarker.getCam(), *bitMarker.getPose(i), 30.0, 2);
        }
    }

    cvCnvImg(cvimg, img);
}

<|endoftext|>


<commit_before>#include <algorithm>
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <map>
#include <vector>
#include <tr1/functional>

#include "Scheduler.hpp"
#include "DP/taskScheduling.hpp"
#include "compSet/ca_ts.hpp"
#include "nnet/nnetmultitask.hpp"
#include "ParseCommandLine.hpp"
#include "VoltageTable.hpp"

using namespace std;
using namespace std::tr1;

int hees_parse_command_line(int argc, char *argv[]);

static double randomRatio;
extern double ratio_runtime_and_deadline;

static const size_t pxaVoltageLevel = 4;
static const double pxaVoltageTable[pxaVoltageLevel] = {0.75, 1.0, 1.3, 1.6};

int main(int argc, char *argv[]) {

	hees_parse_command_line(argc, argv);
	randomRatio = ratio_runtime_and_deadline;
	cout << randomRatio << endl;
	generateSchedule();
	return 0;
}

VoltageTable vt(vector<double>(syntheticVoltageTable, syntheticVoltageTable+syntheticVoltageLevel), 1.0);
vector<TaskVoltageTable> vec_tvt;

int generateSchedule() {

	int m_numOfVolt;
	double m_deadline;
	vector<double> m_inputDuration, m_inputEnergy;

	// dummyTaskSetGenerator(int &m_numOfTask, int &m_numOfVolt, double &m_deadline, vector<double> &m_inputDuration, vector<double> &m_inputEnergy);
	randomTaskSetGenerator(number_of_tasks, m_numOfVolt, m_deadline, m_inputDuration, m_inputEnergy);

	// Baseline policy
	minEnergySchedule(number_of_tasks, m_numOfVolt, m_deadline, m_inputDuration, m_inputEnergy);
	m_deadline = minEnergyScheduleFixed(number_of_tasks, m_numOfVolt, m_deadline, m_inputDuration, m_inputEnergy, vec_tvt);

	// Then use dynamic programming to generate optimal schedule
	dynProg taskSet1(number_of_tasks, vector<double>(syntheticVoltageTable, syntheticVoltageTable+syntheticVoltageLevel), m_deadline, m_inputDuration, m_inputEnergy);
	taskSet1.dynamicProgrammingWithIdleTasks();
	m_deadline = taskSet1.getDeadline();
	m_deadline /= 10.0;

	return 0;
}

void randomTaskSetGenerator(int &m_numOfTask, int &m_numOfVolt, double &m_deadline, vector<double> &m_inputDuration, vector<double> &m_inputEnergy) {
	// Generate 10 tasks
	m_deadline = 0;
	m_numOfVolt = 5;

    vector<double> InDuration;
    vector<double> InEnergy;
    vector<double> InPower;
	ofstream outfile;
	// Random the seed
	srand(time(NULL));
	for (int i = 0; i < m_numOfTask; ++i) {
		// Each task is between [10 100] with a timestamp 10
		int tasklen = (1 + rand() % 9);
		// Each task power is between 0.6 ~ 2.0
		double taskpower = min_task_power + (rand() % 100) * (max_task_power - min_task_power) / 100.0;
		double taskEnergy = tasklen * taskpower;
		InDuration.push_back(tasklen);
		InEnergy.push_back(taskEnergy);
		InPower.push_back(taskpower);

		m_deadline += tasklen;

		vec_tvt.push_back(TaskVoltageTable(vt, taskpower, tasklen));

	}
	outfile.open("TasksOrigNoSorting.txt");
	if (!outfile) {
		cerr << "Can not open TasksOrigNoSorting.txt for write!" << endl;
	}
	for (size_t i = 0; i < InEnergy.size(); ++i) {
		outfile << InDuration[i] << " "
		<< InPower[i] << " "
		<< InEnergy[i] << endl;
	}
	outfile.close();

	// highPowerLongTask(InDuration, InEnergy, InPower);
	outfile.open("TasksOrig.txt");
	if (!outfile) {
		cerr << "Can not open TasksOrig.txt for write!" << endl;
	}
	for (size_t i = 0; i < InEnergy.size(); ++i) {
		outfile << InDuration[i] << " "
		<< InPower[i] << " "
		<< InEnergy[i] << endl;
	}
	outfile.close();

	m_deadline /= randomRatio;
	m_inputDuration = InDuration;
	m_inputEnergy = InEnergy;

	return;
}

void dummyTaskSetGenerator(int &m_numOfTask, int &m_numOfVolt, double &m_deadline, vector<double> &m_inputDuration, vector<double> &m_inputEnergy) {

    m_deadline = 25;
    m_numOfTask = 3;
	m_numOfVolt = 5;

    vector<double>InDuration;
    InDuration.push_back(6.0);
    InDuration.push_back(7.0);
    InDuration.push_back(8.0);

	m_inputDuration = InDuration;

    vector<double>InEnergy;
    InEnergy.push_back(6.0);
    InEnergy.push_back(7.0);
    InEnergy.push_back(8.0);

	m_inputEnergy = InEnergy;

	return;
}

void highPowerLongTask(vector<double> &m_taskDuration, vector<double> &m_taskEnergy, vector<double> &m_taskPower) {
	vector<double> taskDuration(m_taskDuration);
	vector<double> taskPower(m_taskPower);
	map<double, double> taskMap;

	// Sort the task len and power vector in descending order
	sort(taskDuration.begin(), taskDuration.end(), greater<double>());
	sort(taskPower.begin(), taskPower.end(), greater<double>());

	for (size_t i = 0; i < taskDuration.size(); ++i) {
		taskMap[taskDuration[i]] = taskPower[i];
	}

	for (size_t i = 0; i < taskDuration.size(); ++i) {
		m_taskEnergy[i] = taskMap[m_taskDuration[i]] * m_taskDuration[i];
		m_taskPower[i] = taskMap[m_taskDuration[i]];
	}

	return;
}
<commit_msg>Updates on Scheduler.cpp<commit_after>#include <algorithm>
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <map>
#include <vector>
#include <tr1/functional>

#include "Scheduler.hpp"
#include "DP/taskScheduling.hpp"
#include "compSet/ca_ts.hpp"
#include "nnet/nnetmultitask.hpp"
#include "ParseCommandLine.hpp"
#include "VoltageTable.hpp"

using namespace std;
using namespace std::tr1;

int hees_parse_command_line(int argc, char *argv[]);

static double randomRatio;
extern double ratio_runtime_and_deadline;

static const size_t pxaVoltageLevel = 4;
static const double pxaVoltageTable[pxaVoltageLevel] = {0.75, 1.0, 1.3, 1.6};

int main(int argc, char *argv[]) {

	hees_parse_command_line(argc, argv);
	randomRatio = ratio_runtime_and_deadline;
	cout << randomRatio << endl;
	generateSchedule();
	return 0;
}

vector<TaskVoltageTable> vec_tvt;

int generateSchedule() {

	int m_numOfVolt;
	double m_deadline;
	vector<double> m_inputDuration, m_inputEnergy;

	randomTaskSetGenerator(number_of_tasks, m_numOfVolt, m_deadline, m_inputDuration, m_inputEnergy);

	// Baseline policy
	minEnergyScheduleFixed(number_of_tasks, m_numOfVolt, m_deadline, m_inputDuration, m_inputEnergy, vec_tvt);

	// Then use dynamic programming to generate optimal schedule
	dynProg taskSet1(vec_tvt.size(), m_deadline, vec_tvt);
	taskSet1.dynamicProgrammingWithIdleTasks();
	m_deadline = taskSet1.getDeadline();
	m_deadline /= 10.0;

	return 0;
}

void randomTaskSetGenerator(int &m_numOfTask, int &m_numOfVolt, double &m_deadline, vector<double> &m_inputDuration, vector<double> &m_inputEnergy) {
	// Generate 10 tasks
	m_deadline = 0;
	m_numOfVolt = 5;

    vector<double> InDuration;
    vector<double> InEnergy;
    vector<double> InPower;
	ofstream outfile;
	// Random the seed
	srand(time(NULL));
	for (int i = 0; i < m_numOfTask; ++i) {
		// Each task is between [10 100] with a timestamp 10
		int tasklen = (10 + rand() % 200);
		// Each task power is between 0.6 ~ 2.0
		double taskpower = min_task_power + (rand() % 100) * (max_task_power - min_task_power) / 100.0;
		double taskEnergy = tasklen * taskpower;
		InDuration.push_back(tasklen);
		InEnergy.push_back(taskEnergy);
		InPower.push_back(taskpower);

		m_deadline += tasklen;

		vec_tvt.push_back(TaskVoltageTable(syntheticCPUVoltageTable, taskpower, tasklen));

	}
	outfile.open("TasksOrigNoSorting.txt");
	if (!outfile) {
		cerr << "Can not open TasksOrigNoSorting.txt for write!" << endl;
	}
	for (size_t i = 0; i < InEnergy.size(); ++i) {
		outfile << InDuration[i] << " "
		<< InPower[i] << " "
		<< InEnergy[i] << endl;
	}
	outfile.close();

	// highPowerLongTask(InDuration, InEnergy, InPower);
	outfile.open("TasksOrig.txt");
	if (!outfile) {
		cerr << "Can not open TasksOrig.txt for write!" << endl;
	}
	for (size_t i = 0; i < InEnergy.size(); ++i) {
		outfile << InDuration[i] << " "
		<< InPower[i] << " "
		<< InEnergy[i] << endl;
	}
	outfile.close();

	m_deadline /= randomRatio;
	m_inputDuration = InDuration;
	m_inputEnergy = InEnergy;

	return;
}

void dummyTaskSetGenerator(int &m_numOfTask, int &m_numOfVolt, double &m_deadline, vector<double> &m_inputDuration, vector<double> &m_inputEnergy) {

    m_deadline = 25;
    m_numOfTask = 3;
	m_numOfVolt = 5;

    vector<double>InDuration;
    InDuration.push_back(6.0);
    InDuration.push_back(7.0);
    InDuration.push_back(8.0);

	m_inputDuration = InDuration;

    vector<double>InEnergy;
    InEnergy.push_back(6.0);
    InEnergy.push_back(7.0);
    InEnergy.push_back(8.0);

	m_inputEnergy = InEnergy;

	return;
}

void highPowerLongTask(vector<double> &m_taskDuration, vector<double> &m_taskEnergy, vector<double> &m_taskPower) {
	vector<double> taskDuration(m_taskDuration);
	vector<double> taskPower(m_taskPower);
	map<double, double> taskMap;

	// Sort the task len and power vector in descending order
	sort(taskDuration.begin(), taskDuration.end(), greater<double>());
	sort(taskPower.begin(), taskPower.end(), greater<double>());

	for (size_t i = 0; i < taskDuration.size(); ++i) {
		taskMap[taskDuration[i]] = taskPower[i];
	}

	for (size_t i = 0; i < taskDuration.size(); ++i) {
		m_taskEnergy[i] = taskMap[m_taskDuration[i]] * m_taskDuration[i];
		m_taskPower[i] = taskMap[m_taskDuration[i]];
	}

	return;
}
<|endoftext|>


<commit_before><commit_msg>INTEGRATION: CWS pagefields (1.2.334); FILE MERGED 2003/12/05 13:57:32 nn 1.2.334.1: #i22164# page field handling<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: undotab.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: nn $ $Date: 2001-12-05 22:02:44 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef SC_UNDOTAB_HXX
#define SC_UNDOTAB_HXX

#ifndef SC_UNDOBASE_HXX
#include "undobase.hxx"
#endif
#ifndef SC_MARKDATA_HXX
#include "markdata.hxx"
#endif

#ifndef _SVSTDARR_USHORTS

#define _SVSTDARR_USHORTS
#include <svtools/svstdarr.hxx>

#endif

#ifndef _SVSTDARR_STRINGS

#define _SVSTDARR_STRINGS
#include <svtools/svstdarr.hxx>

#endif

class ScDocShell;
class ScDocument;
class SdrUndoAction;
class ScPrintRangeSaver;
class SdrObject;

//----------------------------------------------------------------------------

class ScUndoInsertTab : public ScSimpleUndo
{
public:
                    TYPEINFO();
                    ScUndoInsertTab(
                            ScDocShell* pNewDocShell,
                            USHORT nTabNum,
                            BOOL bApp,
                            const String& rNewName);
    virtual         ~ScUndoInsertTab();

    virtual void    Undo();
    virtual void    Redo();
    virtual void    Repeat(SfxRepeatTarget& rTarget);
    virtual BOOL    CanRepeat(SfxRepeatTarget& rTarget) const;

    virtual String  GetComment() const;

private:
    String          sNewName;
    SdrUndoAction*  pDrawUndo;
    ULONG           nEndChangeAction;
    USHORT          nTab;
    BOOL            bAppend;

    void            SetChangeTrack();
};

class ScUndoInsertTables : public ScSimpleUndo
{
public:
                    TYPEINFO();
                    ScUndoInsertTables(
                            ScDocShell* pNewDocShell,
                            USHORT nTabNum,
                            BOOL bApp,
                            SvStrings *pNewNameList);
    virtual         ~ScUndoInsertTables();

    virtual void    Undo();
    virtual void    Redo();
    virtual void    Repeat(SfxRepeatTarget& rTarget);
    virtual BOOL    CanRepeat(SfxRepeatTarget& rTarget) const;

    virtual String  GetComment() const;

private:

    SdrUndoAction*  pDrawUndo;
    SvStrings*      pNameList;
    ULONG           nStartChangeAction;
    ULONG           nEndChangeAction;
    USHORT          nTab;
    BOOL            bAppend;

    void            SetChangeTrack();
};

class ScUndoDeleteTab: public ScMoveUndo    // Draw vom Move fuer geloeschte Tabelle
{
public:
                    TYPEINFO();
                    ScUndoDeleteTab(
                            ScDocShell* pNewDocShell,
                            const SvUShorts &theTabs,       //USHORT nNewTab,
                            ScDocument* pUndoDocument,
                            ScRefUndoData* pRefData );
    virtual         ~ScUndoDeleteTab();

    virtual void    Undo();
    virtual void    Redo();
    virtual void    Repeat(SfxRepeatTarget& rTarget);
    virtual BOOL    CanRepeat(SfxRepeatTarget& rTarget) const;

    virtual String  GetComment() const;

private:
    SvUShorts   theTabs;
    ULONG           nStartChangeAction;
    ULONG           nEndChangeAction;

    void            SetChangeTrack();
};

class ScUndoRenameTab: public ScSimpleUndo
{
public:
                    TYPEINFO();
                    ScUndoRenameTab(
                            ScDocShell* pNewDocShell,
                            USHORT nT,
                            const String& rOldName,
                            const String& rNewName);
    virtual         ~ScUndoRenameTab();

    virtual void    Undo();
    virtual void    Redo();
    virtual void    Repeat(SfxRepeatTarget& rTarget);
    virtual BOOL    CanRepeat(SfxRepeatTarget& rTarget) const;

    virtual String  GetComment() const;

private:
    USHORT  nTab;
    String  sOldName;
    String  sNewName;

    void DoChange( USHORT nTab, const String& rName ) const;
};

class ScUndoMoveTab: public ScSimpleUndo
{
public:
                    TYPEINFO();
                    ScUndoMoveTab( ScDocShell* pNewDocShell,
                                  const SvUShorts &aOldTab,
                                  const SvUShorts &aNewTab);
    virtual         ~ScUndoMoveTab();

    virtual void    Undo();
    virtual void    Redo();
    virtual void    Repeat(SfxRepeatTarget& rTarget);
    virtual BOOL    CanRepeat(SfxRepeatTarget& rTarget) const;

    virtual String  GetComment() const;

private:
    SvUShorts   theOldTabs;
    SvUShorts   theNewTabs;

    void DoChange( BOOL bUndo ) const;
};

class ScUndoCopyTab: public ScSimpleUndo
{
public:
                    TYPEINFO();
                    ScUndoCopyTab(ScDocShell* pNewDocShell,
                                  const SvUShorts &aOldTab,
                                  const SvUShorts &aNewTab);

    virtual         ~ScUndoCopyTab();

    virtual void    Undo();
    virtual void    Redo();
    virtual void    Repeat(SfxRepeatTarget& rTarget);
    virtual BOOL    CanRepeat(SfxRepeatTarget& rTarget) const;

    virtual String  GetComment() const;

private:
    SdrUndoAction*  pDrawUndo;
    SvUShorts   theOldTabs;
    SvUShorts   theNewTabs;

    void DoChange() const;
};

class ScUndoMakeScenario: public ScSimpleUndo
{
public:
                    TYPEINFO();
                    ScUndoMakeScenario(
                            ScDocShell* pNewDocShell,
                            USHORT nSrc, USHORT nDest,
                            ScDocument* pUndo,
                            const String& rN, const String& rC,
                            const Color& rCol, USHORT nF,
                            const ScMarkData& rMark );
    virtual         ~ScUndoMakeScenario();

    virtual void    Undo();
    virtual void    Redo();
    virtual void    Repeat(SfxRepeatTarget& rTarget);
    virtual BOOL    CanRepeat(SfxRepeatTarget& rTarget) const;

    virtual String  GetComment() const;

private:
    USHORT      nSrcTab;
    USHORT      nDestTab;
    ScDocument* pUndoDoc;
    String      aName;
    String      aComment;
    Color       aColor;
    USHORT      nFlags;
    ScMarkData  aMarkData;
};

class ScUndoImportTab : public ScSimpleUndo
{
public:
                    TYPEINFO();
                    ScUndoImportTab(
                            ScDocShell* pShell,
                            USHORT nNewTab, USHORT nNewCount,
                            BOOL bNewLink );
    virtual         ~ScUndoImportTab();

    virtual void    Undo();
    virtual void    Redo();
    virtual void    Repeat(SfxRepeatTarget& rTarget);
    virtual BOOL    CanRepeat(SfxRepeatTarget& rTarget) const;

    virtual String  GetComment() const;

private:
    USHORT      nTab;
    USHORT      nCount;
    BOOL        bLink;
    ScDocument* pRedoDoc;
    SdrUndoAction*  pDrawUndo;

    void DoChange() const;
};

class ScUndoRemoveLink : public ScSimpleUndo
{
public:
                    TYPEINFO();
                    ScUndoRemoveLink(               // vor dem Loeschen aufrufen!
                            ScDocShell* pShell,
                            const String& rDoc );
    virtual         ~ScUndoRemoveLink();

    virtual void    Undo();
    virtual void    Redo();
    virtual void    Repeat(SfxRepeatTarget& rTarget);
    virtual BOOL    CanRepeat(SfxRepeatTarget& rTarget) const;

    virtual String  GetComment() const;

private:
    String  aDocName;
    String  aFltName;
    String  aOptions;
    ULONG   nRefreshDelay;
    USHORT  nCount;
    USHORT* pTabs;
    BYTE*   pModes;
    String* pTabNames;

    void DoChange( BOOL bLink ) const;
};

class ScUndoShowHideTab : public ScSimpleUndo
{
public:
                    TYPEINFO();
                    ScUndoShowHideTab(
                            ScDocShell* pShell,
                            USHORT nNewTab, BOOL bNewShow );
    virtual         ~ScUndoShowHideTab();

    virtual void    Undo();
    virtual void    Redo();
    virtual void    Repeat(SfxRepeatTarget& rTarget);
    virtual BOOL    CanRepeat(SfxRepeatTarget& rTarget) const;

    virtual String  GetComment() const;

private:
    USHORT  nTab;
    BOOL    bShow;

    void DoChange( BOOL bShow ) const;
};

class ScUndoProtect : public ScSimpleUndo
{
public:
                    TYPEINFO();
                    ScUndoProtect( ScDocShell* pShell, USHORT nNewTab,
                                    BOOL bNewProtect, const com::sun::star::uno::Sequence<sal_Int8>& rNewPassword );
    virtual         ~ScUndoProtect();

    virtual void    Undo();
    virtual void    Redo();
    virtual void    Repeat(SfxRepeatTarget& rTarget);
    virtual BOOL    CanRepeat(SfxRepeatTarget& rTarget) const;

    virtual String  GetComment() const;

private:
    USHORT  nTab;
    BOOL    bProtect;
    com::sun::star::uno::Sequence<sal_Int8> aPassword;

    void    DoProtect( BOOL bDo );
};

class ScUndoPrintRange : public ScSimpleUndo
{
public:
                    TYPEINFO();
                    ScUndoPrintRange( ScDocShell* pShell, USHORT nNewTab,
                                        ScPrintRangeSaver* pOld, ScPrintRangeSaver* pNew );
    virtual         ~ScUndoPrintRange();

    virtual void    Undo();
    virtual void    Redo();
    virtual void    Repeat(SfxRepeatTarget& rTarget);
    virtual BOOL    CanRepeat(SfxRepeatTarget& rTarget) const;

    virtual String  GetComment() const;

private:
    USHORT              nTab;
    ScPrintRangeSaver*  pOldRanges;
    ScPrintRangeSaver*  pNewRanges;

    void DoChange( BOOL bUndo );
};

class ScUndoScenarioFlags: public ScSimpleUndo
{
public:
                    TYPEINFO();
                    ScUndoScenarioFlags(
                            ScDocShell* pNewDocShell, USHORT nT,
                            const String& rON, const String& rNN,
                            const String& rOC, const String& rNC,
                            const Color& rOCol, const Color& rNCol,
                            USHORT nOF, USHORT nNF );

    virtual         ~ScUndoScenarioFlags();

    virtual void    Undo();
    virtual void    Redo();
    virtual void    Repeat(SfxRepeatTarget& rTarget);
    virtual BOOL    CanRepeat(SfxRepeatTarget& rTarget) const;

    virtual String  GetComment() const;

private:
    USHORT  nTab;
    String  aOldName;
    String  aNewName;
    String  aOldComment;
    String  aNewComment;
    Color   aOldColor;
    Color   aNewColor;
    USHORT  nOldFlags;
    USHORT  nNewFlags;
};

class ScUndoRenameObject: public ScSimpleUndo
{
public:
                    TYPEINFO();
                    ScUndoRenameObject(
                            ScDocShell* pNewDocShell, const String& rPN,
                            const String& rON, const String& rNN );

    virtual         ~ScUndoRenameObject();

    virtual void    Undo();
    virtual void    Redo();
    virtual void    Repeat(SfxRepeatTarget& rTarget);
    virtual BOOL    CanRepeat(SfxRepeatTarget& rTarget) const;

    virtual String  GetComment() const;

private:
    String  aPersistName;       // to find object (works only for OLE objects)
    String  aOldName;
    String  aNewName;

    SdrObject*  GetObject();
};

#endif

<commit_msg>INTEGRATION: CWS calcrtl (1.5.100); FILE MERGED 2003/07/11 10:21:10 nn 1.5.100.1: #106948# menu function to mirror sheet<commit_after>/*************************************************************************
 *
 *  $RCSfile: undotab.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: hr $ $Date: 2004-02-03 12:43:07 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef SC_UNDOTAB_HXX
#define SC_UNDOTAB_HXX

#ifndef SC_UNDOBASE_HXX
#include "undobase.hxx"
#endif
#ifndef SC_MARKDATA_HXX
#include "markdata.hxx"
#endif

#ifndef _SVSTDARR_USHORTS

#define _SVSTDARR_USHORTS
#include <svtools/svstdarr.hxx>

#endif

#ifndef _SVSTDARR_STRINGS

#define _SVSTDARR_STRINGS
#include <svtools/svstdarr.hxx>

#endif

class ScDocShell;
class ScDocument;
class SdrUndoAction;
class ScPrintRangeSaver;
class SdrObject;

//----------------------------------------------------------------------------

class ScUndoInsertTab : public ScSimpleUndo
{
public:
                    TYPEINFO();
                    ScUndoInsertTab(
                            ScDocShell* pNewDocShell,
                            USHORT nTabNum,
                            BOOL bApp,
                            const String& rNewName);
    virtual         ~ScUndoInsertTab();

    virtual void    Undo();
    virtual void    Redo();
    virtual void    Repeat(SfxRepeatTarget& rTarget);
    virtual BOOL    CanRepeat(SfxRepeatTarget& rTarget) const;

    virtual String  GetComment() const;

private:
    String          sNewName;
    SdrUndoAction*  pDrawUndo;
    ULONG           nEndChangeAction;
    USHORT          nTab;
    BOOL            bAppend;

    void            SetChangeTrack();
};

class ScUndoInsertTables : public ScSimpleUndo
{
public:
                    TYPEINFO();
                    ScUndoInsertTables(
                            ScDocShell* pNewDocShell,
                            USHORT nTabNum,
                            BOOL bApp,
                            SvStrings *pNewNameList);
    virtual         ~ScUndoInsertTables();

    virtual void    Undo();
    virtual void    Redo();
    virtual void    Repeat(SfxRepeatTarget& rTarget);
    virtual BOOL    CanRepeat(SfxRepeatTarget& rTarget) const;

    virtual String  GetComment() const;

private:

    SdrUndoAction*  pDrawUndo;
    SvStrings*      pNameList;
    ULONG           nStartChangeAction;
    ULONG           nEndChangeAction;
    USHORT          nTab;
    BOOL            bAppend;

    void            SetChangeTrack();
};

class ScUndoDeleteTab: public ScMoveUndo    // Draw vom Move fuer geloeschte Tabelle
{
public:
                    TYPEINFO();
                    ScUndoDeleteTab(
                            ScDocShell* pNewDocShell,
                            const SvUShorts &theTabs,       //USHORT nNewTab,
                            ScDocument* pUndoDocument,
                            ScRefUndoData* pRefData );
    virtual         ~ScUndoDeleteTab();

    virtual void    Undo();
    virtual void    Redo();
    virtual void    Repeat(SfxRepeatTarget& rTarget);
    virtual BOOL    CanRepeat(SfxRepeatTarget& rTarget) const;

    virtual String  GetComment() const;

private:
    SvUShorts   theTabs;
    ULONG           nStartChangeAction;
    ULONG           nEndChangeAction;

    void            SetChangeTrack();
};

class ScUndoRenameTab: public ScSimpleUndo
{
public:
                    TYPEINFO();
                    ScUndoRenameTab(
                            ScDocShell* pNewDocShell,
                            USHORT nT,
                            const String& rOldName,
                            const String& rNewName);
    virtual         ~ScUndoRenameTab();

    virtual void    Undo();
    virtual void    Redo();
    virtual void    Repeat(SfxRepeatTarget& rTarget);
    virtual BOOL    CanRepeat(SfxRepeatTarget& rTarget) const;

    virtual String  GetComment() const;

private:
    USHORT  nTab;
    String  sOldName;
    String  sNewName;

    void DoChange( USHORT nTab, const String& rName ) const;
};

class ScUndoMoveTab: public ScSimpleUndo
{
public:
                    TYPEINFO();
                    ScUndoMoveTab( ScDocShell* pNewDocShell,
                                  const SvUShorts &aOldTab,
                                  const SvUShorts &aNewTab);
    virtual         ~ScUndoMoveTab();

    virtual void    Undo();
    virtual void    Redo();
    virtual void    Repeat(SfxRepeatTarget& rTarget);
    virtual BOOL    CanRepeat(SfxRepeatTarget& rTarget) const;

    virtual String  GetComment() const;

private:
    SvUShorts   theOldTabs;
    SvUShorts   theNewTabs;

    void DoChange( BOOL bUndo ) const;
};

class ScUndoCopyTab: public ScSimpleUndo
{
public:
                    TYPEINFO();
                    ScUndoCopyTab(ScDocShell* pNewDocShell,
                                  const SvUShorts &aOldTab,
                                  const SvUShorts &aNewTab);

    virtual         ~ScUndoCopyTab();

    virtual void    Undo();
    virtual void    Redo();
    virtual void    Repeat(SfxRepeatTarget& rTarget);
    virtual BOOL    CanRepeat(SfxRepeatTarget& rTarget) const;

    virtual String  GetComment() const;

private:
    SdrUndoAction*  pDrawUndo;
    SvUShorts   theOldTabs;
    SvUShorts   theNewTabs;

    void DoChange() const;
};

class ScUndoMakeScenario: public ScSimpleUndo
{
public:
                    TYPEINFO();
                    ScUndoMakeScenario(
                            ScDocShell* pNewDocShell,
                            USHORT nSrc, USHORT nDest,
                            ScDocument* pUndo,
                            const String& rN, const String& rC,
                            const Color& rCol, USHORT nF,
                            const ScMarkData& rMark );
    virtual         ~ScUndoMakeScenario();

    virtual void    Undo();
    virtual void    Redo();
    virtual void    Repeat(SfxRepeatTarget& rTarget);
    virtual BOOL    CanRepeat(SfxRepeatTarget& rTarget) const;

    virtual String  GetComment() const;

private:
    USHORT      nSrcTab;
    USHORT      nDestTab;
    ScDocument* pUndoDoc;
    String      aName;
    String      aComment;
    Color       aColor;
    USHORT      nFlags;
    ScMarkData  aMarkData;
};

class ScUndoImportTab : public ScSimpleUndo
{
public:
                    TYPEINFO();
                    ScUndoImportTab(
                            ScDocShell* pShell,
                            USHORT nNewTab, USHORT nNewCount,
                            BOOL bNewLink );
    virtual         ~ScUndoImportTab();

    virtual void    Undo();
    virtual void    Redo();
    virtual void    Repeat(SfxRepeatTarget& rTarget);
    virtual BOOL    CanRepeat(SfxRepeatTarget& rTarget) const;

    virtual String  GetComment() const;

private:
    USHORT      nTab;
    USHORT      nCount;
    BOOL        bLink;
    ScDocument* pRedoDoc;
    SdrUndoAction*  pDrawUndo;

    void DoChange() const;
};

class ScUndoRemoveLink : public ScSimpleUndo
{
public:
                    TYPEINFO();
                    ScUndoRemoveLink(               // vor dem Loeschen aufrufen!
                            ScDocShell* pShell,
                            const String& rDoc );
    virtual         ~ScUndoRemoveLink();

    virtual void    Undo();
    virtual void    Redo();
    virtual void    Repeat(SfxRepeatTarget& rTarget);
    virtual BOOL    CanRepeat(SfxRepeatTarget& rTarget) const;

    virtual String  GetComment() const;

private:
    String  aDocName;
    String  aFltName;
    String  aOptions;
    ULONG   nRefreshDelay;
    USHORT  nCount;
    USHORT* pTabs;
    BYTE*   pModes;
    String* pTabNames;

    void DoChange( BOOL bLink ) const;
};

class ScUndoShowHideTab : public ScSimpleUndo
{
public:
                    TYPEINFO();
                    ScUndoShowHideTab(
                            ScDocShell* pShell,
                            USHORT nNewTab, BOOL bNewShow );
    virtual         ~ScUndoShowHideTab();

    virtual void    Undo();
    virtual void    Redo();
    virtual void    Repeat(SfxRepeatTarget& rTarget);
    virtual BOOL    CanRepeat(SfxRepeatTarget& rTarget) const;

    virtual String  GetComment() const;

private:
    USHORT  nTab;
    BOOL    bShow;

    void DoChange( BOOL bShow ) const;
};

class ScUndoProtect : public ScSimpleUndo
{
public:
                    TYPEINFO();
                    ScUndoProtect( ScDocShell* pShell, USHORT nNewTab,
                                    BOOL bNewProtect, const com::sun::star::uno::Sequence<sal_Int8>& rNewPassword );
    virtual         ~ScUndoProtect();

    virtual void    Undo();
    virtual void    Redo();
    virtual void    Repeat(SfxRepeatTarget& rTarget);
    virtual BOOL    CanRepeat(SfxRepeatTarget& rTarget) const;

    virtual String  GetComment() const;

private:
    USHORT  nTab;
    BOOL    bProtect;
    com::sun::star::uno::Sequence<sal_Int8> aPassword;

    void    DoProtect( BOOL bDo );
};

class ScUndoPrintRange : public ScSimpleUndo
{
public:
                    TYPEINFO();
                    ScUndoPrintRange( ScDocShell* pShell, USHORT nNewTab,
                                        ScPrintRangeSaver* pOld, ScPrintRangeSaver* pNew );
    virtual         ~ScUndoPrintRange();

    virtual void    Undo();
    virtual void    Redo();
    virtual void    Repeat(SfxRepeatTarget& rTarget);
    virtual BOOL    CanRepeat(SfxRepeatTarget& rTarget) const;

    virtual String  GetComment() const;

private:
    USHORT              nTab;
    ScPrintRangeSaver*  pOldRanges;
    ScPrintRangeSaver*  pNewRanges;

    void DoChange( BOOL bUndo );
};

class ScUndoScenarioFlags: public ScSimpleUndo
{
public:
                    TYPEINFO();
                    ScUndoScenarioFlags(
                            ScDocShell* pNewDocShell, USHORT nT,
                            const String& rON, const String& rNN,
                            const String& rOC, const String& rNC,
                            const Color& rOCol, const Color& rNCol,
                            USHORT nOF, USHORT nNF );

    virtual         ~ScUndoScenarioFlags();

    virtual void    Undo();
    virtual void    Redo();
    virtual void    Repeat(SfxRepeatTarget& rTarget);
    virtual BOOL    CanRepeat(SfxRepeatTarget& rTarget) const;

    virtual String  GetComment() const;

private:
    USHORT  nTab;
    String  aOldName;
    String  aNewName;
    String  aOldComment;
    String  aNewComment;
    Color   aOldColor;
    Color   aNewColor;
    USHORT  nOldFlags;
    USHORT  nNewFlags;
};

class ScUndoRenameObject: public ScSimpleUndo
{
public:
                    TYPEINFO();
                    ScUndoRenameObject(
                            ScDocShell* pNewDocShell, const String& rPN,
                            const String& rON, const String& rNN );

    virtual         ~ScUndoRenameObject();

    virtual void    Undo();
    virtual void    Redo();
    virtual void    Repeat(SfxRepeatTarget& rTarget);
    virtual BOOL    CanRepeat(SfxRepeatTarget& rTarget) const;

    virtual String  GetComment() const;

private:
    String  aPersistName;       // to find object (works only for OLE objects)
    String  aOldName;
    String  aNewName;

    SdrObject*  GetObject();
};

class ScUndoLayoutRTL : public ScSimpleUndo
{
public:
                    TYPEINFO();
                    ScUndoLayoutRTL( ScDocShell* pShell, USHORT nNewTab, BOOL bNewRTL );
    virtual         ~ScUndoLayoutRTL();

    virtual void    Undo();
    virtual void    Redo();
    virtual void    Repeat(SfxRepeatTarget& rTarget);
    virtual BOOL    CanRepeat(SfxRepeatTarget& rTarget) const;

    virtual String  GetComment() const;

private:
    USHORT  nTab;
    BOOL    bRTL;

    void DoChange( BOOL bNew );
};

#endif

<|endoftext|>


<commit_before>/*
The MIT License (MIT)

Copyright (c) 2016-2017 winlin

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.
*/

#include "SimpleDHT.h"

SimpleDHT::SimpleDHT() {
}

SimpleDHT::SimpleDHT(int pin) {
    setPin(pin);
}

int SimpleDHT::read(byte* ptemperature, byte* phumidity, byte pdata[40]) {
    int ret = SimpleDHTErrSuccess;

    if (pin == -1) {
        return SimpleDHTErrNoPin;
    }

    float temperature = 0;
    float humidity = 0;
    if ((ret = read2(&temperature, &humidity, pdata)) != SimpleDHTErrSuccess) {
        return ret;
    }

    if (ptemperature) {
        *ptemperature = (byte)(int)temperature;
    }

    if (phumidity) {
        *phumidity = (byte)(int)humidity;
    }

    return ret;
}

int SimpleDHT::read(int pin, byte* ptemperature, byte* phumidity, byte pdata[40]) {
    setPin(pin);
    read(ptemperature, phumidity, pdata);
}

void SimpleDHT::setPin(int pin) {
    this->pin = pin;
#ifdef __AVR
    // (only AVR) - set low level properties for configured pin
    bitmask = digitalPinToBitMask(pin);
    port = digitalPinToPort(pin);
#endif
}

int SimpleDHT::getBitmask() {
    return bitmask;
}

int SimpleDHT::getPort() {
    return port;
}

long SimpleDHT::levelTime(byte level, int firstWait, int interval) {
    unsigned long time_start = micros();
    long time = 0;

#ifdef __AVR
    uint8_t portState = level ? bitmask : 0;
#endif

    bool loop = true;
    for (int i = 0 ; loop; i++) {
        if (time < 0 || time > levelTimeout) {
            return -1;
        }

        if (i == 0) {
            if (firstWait > 0) {
                delayMicroseconds(firstWait);
            }
        } else if (interval > 0) {
            delayMicroseconds(interval);
        }

        // for an unsigned int type, the difference have a correct value
        // even if overflow, explanation here:
        //     https://arduino.stackexchange.com/questions/33572/arduino-countdown-without-using-delay
        time = micros() - time_start;

#ifdef __AVR
        loop = ((*portInputRegister(port) & bitmask) == portState);
#else
        loop = (digitalRead(pin) == level);
#endif
    }

    return time;
}

byte SimpleDHT::bits2byte(byte data[8]) {
    byte v = 0;
    for (int i = 0; i < 8; i++) {
        v += data[i] << (7 - i);
    }
    return v;
}

int SimpleDHT::parse(byte data[40], short* ptemperature, short* phumidity) {
    short humidity = bits2byte(data);
    short humidity2 = bits2byte(data + 8);
    short temperature = bits2byte(data + 16);
    short temperature2 = bits2byte(data + 24);
    byte check = bits2byte(data + 32);
    byte expect = (byte)humidity + (byte)humidity2 + (byte)temperature + (byte)temperature2;
    if (check != expect) {
        return SimpleDHTErrDataChecksum;
    }

    *ptemperature = temperature<<8 | temperature2;
    *phumidity = humidity<<8 | humidity2;

    return SimpleDHTErrSuccess;
}

SimpleDHT11::SimpleDHT11() {
}

SimpleDHT11::SimpleDHT11(int pin) : SimpleDHT (pin) {
}

int SimpleDHT11::read2(float* ptemperature, float* phumidity, byte pdata[40]) {
    int ret = SimpleDHTErrSuccess;

    if (pin == -1) {
        return SimpleDHTErrNoPin;
    }

    byte data[40] = {0};
    if ((ret = sample(data)) != SimpleDHTErrSuccess) {
        return ret;
    }

    short temperature = 0;
    short humidity = 0;
    if ((ret = parse(data, &temperature, &humidity)) != SimpleDHTErrSuccess) {
        return ret;
    }

    if (pdata) {
        memcpy(pdata, data, 40);
    }
    if (ptemperature) {
        *ptemperature = (int)(temperature>>8);
    }
    if (phumidity) {
        *phumidity = (int)(humidity>>8);
    }

    // For example, when remove the data line, it will be success with zero data.
    if (temperature == 0 && humidity == 0) {
        return SimpleDHTErrZeroSamples;
    }

    return ret;
}

int SimpleDHT11::read2(int pin, float* ptemperature, float* phumidity, byte pdata[40]) {
    setPin(pin);
    read2(ptemperature, phumidity, pdata);
}

int SimpleDHT11::sample(byte data[40]) {
    // empty output data.
    memset(data, 0, 40);

    // According to protocol: [1] https://akizukidenshi.com/download/ds/aosong/DHT11.pdf
    // notify DHT11 to start:
    //    1. PULL LOW 20ms.
    //    2. PULL HIGH 20-40us.
    //    3. SET TO INPUT.
    // Changes in timing done according to:
    //  [2] https://www.mouser.com/ds/2/758/DHT11-Technical-Data-Sheet-Translated-Version-1143054.pdf
    // - original values specified in code
    // - since they were not working (MCU-dependent timing?), replace in code with
    //   _working_ values based on measurements done with levelTimePrecise()
    pinMode(pin, OUTPUT);
    digitalWrite(pin, LOW);            // 1.
    delay(20);                         // specs [2]: 18us

    // Pull high and set to input, before wait 40us.
    // @see https://github.com/winlinvip/SimpleDHT/issues/4
    // @see https://github.com/winlinvip/SimpleDHT/pull/5
    digitalWrite(pin, HIGH);           // 2.
    pinMode(pin, INPUT);
    delayMicroseconds(25);             // specs [2]: 20-40us

    // DHT11 starting:
    //    1. PULL LOW 80us
    //    2. PULL HIGH 80us
    long t = levelTime(LOW);          // 1.
    if (t < 30) {                    // specs [2]: 80us
        return simpleDHTCombileError(t, SimpleDHTErrStartLow);
    }

    t = levelTime(HIGH);             // 2.
    if (t < 50) {                    // specs [2]: 80us
        return simpleDHTCombileError(t, SimpleDHTErrStartHigh);
    }

    // DHT11 data transmite:
    //    1. 1bit start, PULL LOW 50us
    //    2. PULL HIGH:
    //         - 26-28us, bit(0)
    //         - 70us, bit(1)
    for (int j = 0; j < 40; j++) {
          t = levelTime(LOW);          // 1.
          if (t < 24) {                    // specs says: 50us
              return simpleDHTCombileError(t, SimpleDHTErrDataLow);
          }

          // read a bit
          t = levelTime(HIGH);              // 2.
          if (t < 11) {                     // specs say: 20us
              return simpleDHTCombileError(t, SimpleDHTErrDataRead);
          }
          data[ j ] = (t > 40 ? 1 : 0);     // specs: 26-28us -> 0, 70us -> 1
    }

    // DHT11 EOF:
    //    1. PULL LOW 50us.
    t = levelTime(LOW);                     // 1.
    if (t < 24) {                           // specs say: 50us
        return simpleDHTCombileError(t, SimpleDHTErrDataEOF);
    }

    return SimpleDHTErrSuccess;
}

SimpleDHT22::SimpleDHT22() {
}

SimpleDHT22::SimpleDHT22(int pin) : SimpleDHT (pin) {
}

int SimpleDHT22::read2(float* ptemperature, float* phumidity, byte pdata[40]) {
    int ret = SimpleDHTErrSuccess;

    if (pin == -1) {
        return SimpleDHTErrNoPin;
    }

    byte data[40] = {0};
    if ((ret = sample(data)) != SimpleDHTErrSuccess) {
        return ret;
    }

    short temperature = 0;
    short humidity = 0;
    if ((ret = parse(data, &temperature, &humidity)) != SimpleDHTErrSuccess) {
        return ret;
    }

    if (pdata) {
        memcpy(pdata, data, 40);
    }
    if (ptemperature) {
        *ptemperature = (float)((temperature & 0x8000 ? -1 : 1) * (temperature & 0x7FFF)) / 10.0;
    }
    if (phumidity) {
        *phumidity = (float)humidity / 10.0;
    }

    return ret;
}

int SimpleDHT22::read2(int pin, float* ptemperature, float* phumidity, byte pdata[40]) {
    setPin(pin);
    read2(ptemperature, phumidity, pdata);
}

int SimpleDHT22::sample(byte data[40]) {
    // empty output data.
    memset(data, 0, 40);

    // According to protocol: http://akizukidenshi.com/download/ds/aosong/AM2302.pdf
    // notify DHT11 to start:
    //    1. T(be), PULL LOW 1ms(0.8-20ms).
    //    2. T(go), PULL HIGH 30us(20-200us), use 40us.
    //    3. SET TO INPUT.
    pinMode(pin, OUTPUT);
    digitalWrite(pin, LOW);
    delayMicroseconds(1000);
    // Pull high and set to input, before wait 40us.
    // @see https://github.com/winlinvip/SimpleDHT/issues/4
    // @see https://github.com/winlinvip/SimpleDHT/pull/5
    digitalWrite(pin, HIGH);
    pinMode(pin, INPUT);
    delayMicroseconds(40);

    // DHT11 starting:
    //    1. T(rel), PULL LOW 80us(75-85us).
    //    2. T(reh), PULL HIGH 80us(75-85us).
    long t = 0;
    if ((t = levelTime(LOW)) < 30) {
        return simpleDHTCombileError(t, SimpleDHTErrStartLow);
    }
    if ((t = levelTime(HIGH)) < 50) {
        return simpleDHTCombileError(t, SimpleDHTErrStartHigh);
    }

    // DHT11 data transmite:
    //    1. T(LOW), 1bit start, PULL LOW 50us(48-55us).
    //    2. T(H0), PULL HIGH 26us(22-30us), bit(0)
    //    3. T(H1), PULL HIGH 70us(68-75us), bit(1)
    for (int j = 0; j < 40; j++) {
          t = levelTime(LOW);          // 1.
          if (t < 24) {                    // specs says: 50us
              return simpleDHTCombileError(t, SimpleDHTErrDataLow);
          }

          // read a bit
          t = levelTime(HIGH);              // 2.
          if (t < 11) {                     // specs say: 26us
              return simpleDHTCombileError(t, SimpleDHTErrDataRead);
          }
          data[ j ] = (t > 40 ? 1 : 0);     // specs: 22-30us -> 0, 70us -> 1
    }

    // DHT11 EOF:
    //    1. T(en), PULL LOW 50us(45-55us).
    t = levelTime(LOW);
    if (t < 24) {
        return simpleDHTCombileError(t, SimpleDHTErrDataEOF);
    }

    return SimpleDHTErrSuccess;
}
<commit_msg>Fix #24, Support none AVR boards<commit_after>/*
The MIT License (MIT)

Copyright (c) 2016-2017 winlin

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.
*/

#include "SimpleDHT.h"

SimpleDHT::SimpleDHT() {
}

SimpleDHT::SimpleDHT(int pin) {
    setPin(pin);
}

int SimpleDHT::read(byte* ptemperature, byte* phumidity, byte pdata[40]) {
    int ret = SimpleDHTErrSuccess;

    if (pin == -1) {
        return SimpleDHTErrNoPin;
    }

    float temperature = 0;
    float humidity = 0;
    if ((ret = read2(&temperature, &humidity, pdata)) != SimpleDHTErrSuccess) {
        return ret;
    }

    if (ptemperature) {
        *ptemperature = (byte)(int)temperature;
    }

    if (phumidity) {
        *phumidity = (byte)(int)humidity;
    }

    return ret;
}

int SimpleDHT::read(int pin, byte* ptemperature, byte* phumidity, byte pdata[40]) {
    setPin(pin);
    read(ptemperature, phumidity, pdata);
}

void SimpleDHT::setPin(int pin) {
    this->pin = pin;
#ifdef __AVR
    // (only AVR) - set low level properties for configured pin
    bitmask = digitalPinToBitMask(pin);
    port = digitalPinToPort(pin);
#endif
}

#ifdef __AVR
int SimpleDHT::getBitmask() {
    return bitmask;
}

int SimpleDHT::getPort() {
    return port;
}
#endif

long SimpleDHT::levelTime(byte level, int firstWait, int interval) {
    unsigned long time_start = micros();
    long time = 0;

#ifdef __AVR
    uint8_t portState = level ? bitmask : 0;
#endif

    bool loop = true;
    for (int i = 0 ; loop; i++) {
        if (time < 0 || time > levelTimeout) {
            return -1;
        }

        if (i == 0) {
            if (firstWait > 0) {
                delayMicroseconds(firstWait);
            }
        } else if (interval > 0) {
            delayMicroseconds(interval);
        }

        // for an unsigned int type, the difference have a correct value
        // even if overflow, explanation here:
        //     https://arduino.stackexchange.com/questions/33572/arduino-countdown-without-using-delay
        time = micros() - time_start;

#ifdef __AVR
        loop = ((*portInputRegister(port) & bitmask) == portState);
#else
        loop = (digitalRead(pin) == level);
#endif
    }

    return time;
}

byte SimpleDHT::bits2byte(byte data[8]) {
    byte v = 0;
    for (int i = 0; i < 8; i++) {
        v += data[i] << (7 - i);
    }
    return v;
}

int SimpleDHT::parse(byte data[40], short* ptemperature, short* phumidity) {
    short humidity = bits2byte(data);
    short humidity2 = bits2byte(data + 8);
    short temperature = bits2byte(data + 16);
    short temperature2 = bits2byte(data + 24);
    byte check = bits2byte(data + 32);
    byte expect = (byte)humidity + (byte)humidity2 + (byte)temperature + (byte)temperature2;
    if (check != expect) {
        return SimpleDHTErrDataChecksum;
    }

    *ptemperature = temperature<<8 | temperature2;
    *phumidity = humidity<<8 | humidity2;

    return SimpleDHTErrSuccess;
}

SimpleDHT11::SimpleDHT11() {
}

SimpleDHT11::SimpleDHT11(int pin) : SimpleDHT (pin) {
}

int SimpleDHT11::read2(float* ptemperature, float* phumidity, byte pdata[40]) {
    int ret = SimpleDHTErrSuccess;

    if (pin == -1) {
        return SimpleDHTErrNoPin;
    }

    byte data[40] = {0};
    if ((ret = sample(data)) != SimpleDHTErrSuccess) {
        return ret;
    }

    short temperature = 0;
    short humidity = 0;
    if ((ret = parse(data, &temperature, &humidity)) != SimpleDHTErrSuccess) {
        return ret;
    }

    if (pdata) {
        memcpy(pdata, data, 40);
    }
    if (ptemperature) {
        *ptemperature = (int)(temperature>>8);
    }
    if (phumidity) {
        *phumidity = (int)(humidity>>8);
    }

    // For example, when remove the data line, it will be success with zero data.
    if (temperature == 0 && humidity == 0) {
        return SimpleDHTErrZeroSamples;
    }

    return ret;
}

int SimpleDHT11::read2(int pin, float* ptemperature, float* phumidity, byte pdata[40]) {
    setPin(pin);
    read2(ptemperature, phumidity, pdata);
}

int SimpleDHT11::sample(byte data[40]) {
    // empty output data.
    memset(data, 0, 40);

    // According to protocol: [1] https://akizukidenshi.com/download/ds/aosong/DHT11.pdf
    // notify DHT11 to start:
    //    1. PULL LOW 20ms.
    //    2. PULL HIGH 20-40us.
    //    3. SET TO INPUT.
    // Changes in timing done according to:
    //  [2] https://www.mouser.com/ds/2/758/DHT11-Technical-Data-Sheet-Translated-Version-1143054.pdf
    // - original values specified in code
    // - since they were not working (MCU-dependent timing?), replace in code with
    //   _working_ values based on measurements done with levelTimePrecise()
    pinMode(pin, OUTPUT);
    digitalWrite(pin, LOW);            // 1.
    delay(20);                         // specs [2]: 18us

    // Pull high and set to input, before wait 40us.
    // @see https://github.com/winlinvip/SimpleDHT/issues/4
    // @see https://github.com/winlinvip/SimpleDHT/pull/5
    digitalWrite(pin, HIGH);           // 2.
    pinMode(pin, INPUT);
    delayMicroseconds(25);             // specs [2]: 20-40us

    // DHT11 starting:
    //    1. PULL LOW 80us
    //    2. PULL HIGH 80us
    long t = levelTime(LOW);          // 1.
    if (t < 30) {                    // specs [2]: 80us
        return simpleDHTCombileError(t, SimpleDHTErrStartLow);
    }

    t = levelTime(HIGH);             // 2.
    if (t < 50) {                    // specs [2]: 80us
        return simpleDHTCombileError(t, SimpleDHTErrStartHigh);
    }

    // DHT11 data transmite:
    //    1. 1bit start, PULL LOW 50us
    //    2. PULL HIGH:
    //         - 26-28us, bit(0)
    //         - 70us, bit(1)
    for (int j = 0; j < 40; j++) {
          t = levelTime(LOW);          // 1.
          if (t < 24) {                    // specs says: 50us
              return simpleDHTCombileError(t, SimpleDHTErrDataLow);
          }

          // read a bit
          t = levelTime(HIGH);              // 2.
          if (t < 11) {                     // specs say: 20us
              return simpleDHTCombileError(t, SimpleDHTErrDataRead);
          }
          data[ j ] = (t > 40 ? 1 : 0);     // specs: 26-28us -> 0, 70us -> 1
    }

    // DHT11 EOF:
    //    1. PULL LOW 50us.
    t = levelTime(LOW);                     // 1.
    if (t < 24) {                           // specs say: 50us
        return simpleDHTCombileError(t, SimpleDHTErrDataEOF);
    }

    return SimpleDHTErrSuccess;
}

SimpleDHT22::SimpleDHT22() {
}

SimpleDHT22::SimpleDHT22(int pin) : SimpleDHT (pin) {
}

int SimpleDHT22::read2(float* ptemperature, float* phumidity, byte pdata[40]) {
    int ret = SimpleDHTErrSuccess;

    if (pin == -1) {
        return SimpleDHTErrNoPin;
    }

    byte data[40] = {0};
    if ((ret = sample(data)) != SimpleDHTErrSuccess) {
        return ret;
    }

    short temperature = 0;
    short humidity = 0;
    if ((ret = parse(data, &temperature, &humidity)) != SimpleDHTErrSuccess) {
        return ret;
    }

    if (pdata) {
        memcpy(pdata, data, 40);
    }
    if (ptemperature) {
        *ptemperature = (float)((temperature & 0x8000 ? -1 : 1) * (temperature & 0x7FFF)) / 10.0;
    }
    if (phumidity) {
        *phumidity = (float)humidity / 10.0;
    }

    return ret;
}

int SimpleDHT22::read2(int pin, float* ptemperature, float* phumidity, byte pdata[40]) {
    setPin(pin);
    read2(ptemperature, phumidity, pdata);
}

int SimpleDHT22::sample(byte data[40]) {
    // empty output data.
    memset(data, 0, 40);

    // According to protocol: http://akizukidenshi.com/download/ds/aosong/AM2302.pdf
    // notify DHT11 to start:
    //    1. T(be), PULL LOW 1ms(0.8-20ms).
    //    2. T(go), PULL HIGH 30us(20-200us), use 40us.
    //    3. SET TO INPUT.
    pinMode(pin, OUTPUT);
    digitalWrite(pin, LOW);
    delayMicroseconds(1000);
    // Pull high and set to input, before wait 40us.
    // @see https://github.com/winlinvip/SimpleDHT/issues/4
    // @see https://github.com/winlinvip/SimpleDHT/pull/5
    digitalWrite(pin, HIGH);
    pinMode(pin, INPUT);
    delayMicroseconds(40);

    // DHT11 starting:
    //    1. T(rel), PULL LOW 80us(75-85us).
    //    2. T(reh), PULL HIGH 80us(75-85us).
    long t = 0;
    if ((t = levelTime(LOW)) < 30) {
        return simpleDHTCombileError(t, SimpleDHTErrStartLow);
    }
    if ((t = levelTime(HIGH)) < 50) {
        return simpleDHTCombileError(t, SimpleDHTErrStartHigh);
    }

    // DHT11 data transmite:
    //    1. T(LOW), 1bit start, PULL LOW 50us(48-55us).
    //    2. T(H0), PULL HIGH 26us(22-30us), bit(0)
    //    3. T(H1), PULL HIGH 70us(68-75us), bit(1)
    for (int j = 0; j < 40; j++) {
          t = levelTime(LOW);          // 1.
          if (t < 24) {                    // specs says: 50us
              return simpleDHTCombileError(t, SimpleDHTErrDataLow);
          }

          // read a bit
          t = levelTime(HIGH);              // 2.
          if (t < 11) {                     // specs say: 26us
              return simpleDHTCombileError(t, SimpleDHTErrDataRead);
          }
          data[ j ] = (t > 40 ? 1 : 0);     // specs: 22-30us -> 0, 70us -> 1
    }

    // DHT11 EOF:
    //    1. T(en), PULL LOW 50us(45-55us).
    t = levelTime(LOW);
    if (t < 24) {
        return simpleDHTCombileError(t, SimpleDHTErrDataEOF);
    }

    return SimpleDHTErrSuccess;
}
<|endoftext|>


<commit_before><commit_msg>correction in speed<commit_after><|endoftext|>