consumerir: add test for timed length of transmit

Bug: 13080747

Change-Id: I11476be906ad4983a0698bf4a8490115abada454
diff --git a/tests/tests/hardware/src/android/hardware/consumerir/cts/ConsumerIrTest.java b/tests/tests/hardware/src/android/hardware/consumerir/cts/ConsumerIrTest.java
index cff1fc6..395a69b 100644
--- a/tests/tests/hardware/src/android/hardware/consumerir/cts/ConsumerIrTest.java
+++ b/tests/tests/hardware/src/android/hardware/consumerir/cts/ConsumerIrTest.java
@@ -20,6 +20,7 @@
 import android.hardware.ConsumerIrManager;
 import android.util.Log;
 import android.content.pm.PackageManager;
+import android.os.SystemClock;
 import android.test.AndroidTestCase;
 import java.io.IOException;
 
@@ -68,6 +69,41 @@
         }
     }
 
+    public void test_timing() {
+        if (!mHasConsumerIr) {
+            // Skip the test if consumer IR is not present.
+            return;
+        }
+
+        ConsumerIrManager.CarrierFrequencyRange[] freqs = mCIR.getCarrierFrequencies();
+        // Transmit two seconds for min and max for each frequency range
+        int[] pattern = {1111, 2222, 3333, 4444, 5555, 6666, 7777, 8888, 9999};
+        long totalXmitTime = 0; // get the length of the pattern
+        for (int slice : pattern) {
+            totalXmitTime += slice;
+        }
+        double margin = 0.1; // max fraction xmit is allowed to be off timing
+
+        for (ConsumerIrManager.CarrierFrequencyRange range : freqs) {
+            // test min freq
+            long currentTime = SystemClock.elapsedRealtimeNanos();
+            mCIR.transmit(range.getMinFrequency(), pattern);
+            long newTime = SystemClock.elapsedRealtimeNanos();
+            String msg = String.format("Pattern length pattern:%d, actual:%d",
+                    totalXmitTime, newTime - currentTime);
+            assertTrue(msg, newTime - currentTime >= totalXmitTime * (1.0 - margin));
+            assertTrue(msg, newTime - currentTime <= totalXmitTime * (1.0 + margin));
+
+            // test max freq
+            currentTime = SystemClock.elapsedRealtimeNanos();
+            mCIR.transmit(range.getMaxFrequency(), pattern);
+            newTime = SystemClock.elapsedRealtimeNanos();
+            msg = String.format("Pattern length pattern:%d, actual:%d",
+                    totalXmitTime, newTime - currentTime);
+            assertTrue(msg, newTime - currentTime >= totalXmitTime * (1.0 - margin));
+            assertTrue(msg, newTime - currentTime <= totalXmitTime * (1.0 + margin));
+        }
+    }
 
     public void test_transmit() {
         if (!mHasConsumerIr) {