demo project

Dependencies:   AX-12A Dynamixel mbed iothub_client EthernetInterface NTPClient ConfigFile SDFileSystem iothub_amqp_transport mbed-rtos proton-c-mbed wolfSSL

Utils/Timestamp.h

Committer:
henryrawas
Date:
2016-02-04
Revision:
33:8b9dcbf6d8ec
Parent:
20:891b5270845a

File content as of revision 33:8b9dcbf6d8ec:

// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

#ifndef __TIMESTAMP_H__
#define __TIMESTAMP_H__

// use to timestamp alerts and measurements
// with seconds and milliseconds
// MS values are not real, but are intended to space out times properly
class Timestamp
{
public:
    Timestamp()
    {
        _timestamp.start();
        _stampSecs = time(NULL);
        int now = _timestamp.read_ms();
        _stampMs = ((unsigned int)now) % 1000;
        _zeroMs = _stampMs;
    };
    
    // Take a timestamp and save secs and ms
    // Note: We try to set ms to 0 for first measure, and then set ms 
    // with the difference for subsequent values with same secs
    void GetTimestamp()
    {
        time_t nowsecs = time(NULL);
        int now = _timestamp.read_ms();

        double diffsecs = difftime(nowsecs, _stampSecs);
        
        if (diffsecs > 0)
        {
            {
                _zeroMs = now;
            }
        }
        else
        {
            if (now - _zeroMs > 999)
            {
                _zeroMs = now - 999;
            }
            if (now - _zeroMs < _stampMs)
            {
                _zeroMs = now - _stampMs;
            }
        }
        // keep the ms difference for timestamp
        _stampMs = ((unsigned int)(now - _zeroMs)) % 1000;
        _stampSecs = nowsecs;
    };

    time_t GetSecs()
    {
        return _stampSecs;
    };
    
    int GetMs()
    {
        return _stampMs;
    };
    
private:

    Timer _timestamp;

    time_t _stampSecs;
    unsigned int _stampMs;
    int _zeroMs;
};

#endif