|
| 1 | +import struct |
| 2 | +import time |
1 | 3 | import unittest
|
| 4 | +from datetime import datetime |
| 5 | +from unittest.mock import patch |
2 | 6 |
|
3 | 7 | import canopen
|
| 8 | +import canopen.timestamp |
4 | 9 |
|
5 | 10 |
|
6 | 11 | class TestTime(unittest.TestCase):
|
7 | 12 |
|
| 13 | + def test_epoch(self): |
| 14 | + """Verify that the epoch matches the standard definition.""" |
| 15 | + epoch = datetime.strptime( |
| 16 | + "1984-01-01 00:00:00 +0000", "%Y-%m-%d %H:%M:%S %z" |
| 17 | + ).timestamp() |
| 18 | + self.assertEqual(int(epoch), canopen.timestamp.OFFSET) |
| 19 | + |
8 | 20 | def test_time_producer(self):
|
9 | 21 | network = canopen.Network()
|
10 | 22 | network.NOTIFIER_SHUTDOWN_TIMEOUT = 0.0
|
11 | 23 | network.connect(interface="virtual", receive_own_messages=True)
|
12 | 24 | producer = canopen.timestamp.TimeProducer(network)
|
13 |
| - producer.transmit(1486236238) |
| 25 | + |
| 26 | + # Provide a specific time to verify the proper encoding |
| 27 | + producer.transmit(1_927_999_438) # 2031-02-04T19:23:58+00:00 |
14 | 28 | msg = network.bus.recv(1)
|
15 |
| - network.disconnect() |
16 | 29 | self.assertEqual(msg.arbitration_id, 0x100)
|
17 | 30 | self.assertEqual(msg.dlc, 6)
|
18 | 31 | self.assertEqual(msg.data, b"\xb0\xa4\x29\x04\x31\x43")
|
19 | 32 |
|
| 33 | + # Test again with the current time as implicit timestamp |
| 34 | + current = time.time() |
| 35 | + with patch("canopen.timestamp.time.time", return_value=current): |
| 36 | + current_from_epoch = current - canopen.timestamp.OFFSET |
| 37 | + producer.transmit() |
| 38 | + msg = network.bus.recv(1) |
| 39 | + self.assertEqual(msg.arbitration_id, 0x100) |
| 40 | + self.assertEqual(msg.dlc, 6) |
| 41 | + ms, days = struct.unpack("<LH", msg.data) |
| 42 | + self.assertEqual(days, int(current_from_epoch) // 86400) |
| 43 | + self.assertEqual(ms, int(current_from_epoch % 86400 * 1000)) |
| 44 | + |
| 45 | + network.disconnect() |
| 46 | + |
20 | 47 |
|
21 | 48 | if __name__ == "__main__":
|
22 | 49 | unittest.main()
|
0 commit comments