Reland "Reland "[autotest] Consolidate the dump audio diagnostics helper func""

This reverts commit 69199ff6df1e5695a767f13b27718155ddee38e2.

Reason for revert: <INSERT REASONING HERE>

Original change's description:
> Revert "Reland "[autotest] Consolidate the dump audio diagnostics helper func""
> 
> This reverts commit ccc3c8c9396ea3352701ca145c30cbdb3a649577.
> 
> Reason for revert: <INSERT REASONING HERE>
> 
> Original change's description:
> > Reland "[autotest] Consolidate the dump audio diagnostics helper func"
> > 
> > This is a reland of d4c5c86d0ae4f382cfed02669cb9a010937cf3c8
> > 
> > Fix the wrong dump_diagnostics to dump_audio_diagnostics in
> > audio_facade_native.py.
> > 
> > Original change's description:
> > > [autotest] Consolidate the dump audio diagnostics helper func
> > >
> > > This change is a clean up to remove duplicate and legacy codes.
> > > Removing the log_loopback_dongle_status as we have the loopback latency
> > > check in the audio_LoopbackLatency tests. We can add the jack status
> > > check into it if needed.
> > >
> > > BUG=b/142701772
> > > TEST=Manual verify all modified tests
> > >
> > > Change-Id: I8b0b49baade44438ec069259088221ba671e3798
> > > Reviewed-on: https://chromium-review.googlesource.com/c/chromiumos/third_party/autotest/+/1862360
> > > Reviewed-by: Yu-Hsuan Hsu <yuhsuan@chromium.org>
> > > Tested-by: En-Shuo Hsu <enshuo@chromium.org>
> > > Commit-Queue: En-Shuo Hsu <enshuo@chromium.org>
> > 
> > Bug=b/142701772, b/146472345
> > TEST=Run audio_AudioBasicInternalSpeaker that use dump_diagnostic
> > Change-Id: I4d410afd22111b0e0245e798bf4a343a67678765
> > Reviewed-on: https://chromium-review.googlesource.com/c/chromiumos/third_party/autotest/+/1973294
> > Tested-by: En-Shuo Hsu <enshuo@chromium.org>
> > Reviewed-by: Yu-Hsuan Hsu <yuhsuan@chromium.org>
> > Commit-Queue: En-Shuo Hsu <enshuo@chromium.org>
> 
> Change-Id: Ie2502fc12bbe4598192118590e1f34d3d064e3f6
> Reviewed-on: https://chromium-review.googlesource.com/c/chromiumos/third_party/autotest/+/1978127
> Reviewed-by: En-Shuo Hsu <enshuo@chromium.org>
> Tested-by: En-Shuo Hsu <enshuo@chromium.org>

Change-Id: I0ef869513f2330ae24b5a712cfecabbc914f310b
Reviewed-on: https://chromium-review.googlesource.com/c/chromiumos/third_party/autotest/+/1978129
Reviewed-by: En-Shuo Hsu <enshuo@chromium.org>
Commit-Queue: En-Shuo Hsu <enshuo@chromium.org>
Tested-by: En-Shuo Hsu <enshuo@chromium.org>
diff --git a/client/cros/audio/audio_helper.py b/client/cros/audio/audio_helper.py
index f283842..5404804 100644
--- a/client/cros/audio/audio_helper.py
+++ b/client/cros/audio/audio_helper.py
@@ -198,34 +198,6 @@
     else:
         return None
 
-def log_loopback_dongle_status():
-    """Log the status of the loopback dongle to make sure it is equipped."""
-    dongle_status_ok = True
-
-    # Check Mic Jack
-    mic_jack_status = get_mic_jack_status()
-    logging.info('Mic jack status: %s', mic_jack_status)
-    dongle_status_ok &= bool(mic_jack_status)
-
-    # Check Headphone Jack
-    hp_jack_status = get_hp_jack_status()
-    logging.info('Headphone jack status: %s', hp_jack_status)
-    dongle_status_ok &= bool(hp_jack_status)
-
-    # Use latency check to test if audio can be captured through dongle.
-    # We only want to know the basic function of dongle, so no need to
-    # assert the latency accuracy here.
-    latency = loopback_latency_check(n=4000)
-    if latency:
-        logging.info('Got latency measured %d, reported %d',
-                latency[0], latency[1])
-    else:
-        logging.info('Latency check fail.')
-        dongle_status_ok = False
-
-    logging.info('audio loopback dongle test: %s',
-            'PASS' if dongle_status_ok else 'FAIL')
-
 # Functions to test audio palyback.
 def play_sound(duration_seconds=None, audio_file_path=None):
     """Plays a sound file found at |audio_file_path| for |duration_seconds|.
@@ -465,22 +437,28 @@
     cras_utils.set_capture_mute(False)
 
 
-def generate_rms_postmortem():
-    """Generates postmortem for rms tests."""
+def dump_rms_postmortem(result_dir):
+    """Dumps postmortem for rms tests."""
     try:
-        logging.info('audio postmortem report')
-        log_loopback_dongle_status()
-        logging.info(get_audio_diagnostics())
+        dump_audio_diagnostics(
+                os.path.join(result_dir, "audio_diagnostics.txt"))
     except Exception:
         logging.exception('Error while generating postmortem report')
 
 
-def get_audio_diagnostics():
-    """Gets audio diagnostic results.
+def dump_audio_diagnostics(file_path=None):
+    """Dumps audio diagnostics results to a file
 
-    @returns: a string containing diagnostic results.
+    Dumps the result of audio_diagnostics to a file. Returns a string
+    containing the result if the file_path is not specified.
 
+    @returns: None if 'file_path' is specified, otherwise, a string containing
+    the audio diagnostic results.
     """
+    if file_path:
+        with open(file_path, 'w') as f:
+            return cmd_utils.execute([_AUDIO_DIAGNOSTICS_PATH], stdout=f)
+
     return cmd_utils.execute([_AUDIO_DIAGNOSTICS_PATH], stdout=subprocess.PIPE)
 
 
@@ -591,14 +569,14 @@
     trimmed_test_data, end_trimmed_length = trim_data(test_data)
 
     def to_float(samples):
-      """Casts elements in the list to float.
+        """Casts elements in the list to float.
 
       @param samples: A list of numbers.
 
       @returns: A list of original numbers casted to float.
       """
-      samples_float = [float(x) for x in samples]
-      return samples_float
+        samples_float = [float(x) for x in samples]
+        return samples_float
 
     max_cross_correlation, best_delay =  get_max_cross_correlation(
             to_float(golden_data),
@@ -789,7 +767,7 @@
 
         # Sum up the number of failed constraints in each iteration
         if sum(len(x) for x in self.failed_constraints):
-            generate_rms_postmortem()
+            dump_audio_diagnostics(test.resultsdir)
 
 
 class chrome_rms_test(_base_rms_test):
diff --git a/client/cros/multimedia/audio_facade_native.py b/client/cros/multimedia/audio_facade_native.py
index e14a4e9..c82256a 100644
--- a/client/cros/multimedia/audio_facade_native.py
+++ b/client/cros/multimedia/audio_facade_native.py
@@ -440,12 +440,8 @@
 
         @param file_path: The path to dump results.
 
-        @returns: True
-
         """
-        with open(file_path, 'w') as f:
-            f.write(audio_helper.get_audio_diagnostics())
-        return True
+        audio_helper.dump_audio_diagnostics(file_path)
 
 
     def start_counting_signal(self, signal_name):
diff --git a/client/site_tests/audio_CrasDevSwitchStress/audio_CrasDevSwitchStress.py b/client/site_tests/audio_CrasDevSwitchStress/audio_CrasDevSwitchStress.py
index 5c51a2a..4f97f75 100755
--- a/client/site_tests/audio_CrasDevSwitchStress/audio_CrasDevSwitchStress.py
+++ b/client/site_tests/audio_CrasDevSwitchStress/audio_CrasDevSwitchStress.py
@@ -72,17 +72,12 @@
             dev_id = node_pinned['Id'] >> 32
             if stream_type == _STREAM_TYPE_INPUT_APM:
                 if node_pinned['IsInput']:
-                   cmd += ['--pin_device', str(dev_id)]
-            elif not node_pinned['IsInput']:
                     cmd += ['--pin_device', str(dev_id)]
+            elif not node_pinned['IsInput']:
+                cmd += ['--pin_device', str(dev_id)]
 
         return subprocess.Popen(cmd)
 
-    def _dump_audio(self):
-        log_file = os.path.join(self.resultsdir, "audio_diagnostics.txt")
-        with open(log_file, 'w') as f:
-            f.write(audio_helper.get_audio_diagnostics())
-
     def _get_buffer_level(self, match_str, dev_id):
         """
         Gets a rough number about current buffer level.
@@ -122,7 +117,8 @@
 
         logging.debug("Max buffer level: %d on dev %d", buffer_level, dev_id)
         if buffer_level > criteria:
-            self._dump_audio()
+            audio_helper.dump_audio_diagnostics(
+                    os.path.join(self.resultsdir, "audio_diagnostics.txt"))
             raise error.TestFail('Buffer level %d drift too high on %s node'
                                  ' with dev id %d' %
                                  (buffer_level, node['Type'], dev_id))
diff --git a/client/site_tests/audio_CrasStress/audio_CrasStress.py b/client/site_tests/audio_CrasStress/audio_CrasStress.py
index 13dfdba..ec87a91 100755
--- a/client/site_tests/audio_CrasStress/audio_CrasStress.py
+++ b/client/site_tests/audio_CrasStress/audio_CrasStress.py
@@ -49,11 +49,6 @@
 
         return subprocess.Popen(cmd)
 
-    def _dump_audio(self):
-        log_file = os.path.join(self.resultsdir, "audio_diagnostics.txt")
-        with open(log_file, 'w') as f:
-            f.write(audio_helper.get_audio_diagnostics())
-
     def _check_buffer_level(self, stream_type):
 
         buffer_level = self._get_buffer_level(stream_type)
@@ -61,14 +56,16 @@
         if stream_type == _STREAM_TYPE_INPUT:
             logging.debug("Max input buffer level: %d", buffer_level)
             if buffer_level > self._INPUT_BUFFER_DRIFT_CRITERIA:
-                self._dump_audio()
+                audio_helper.dump_audio_diagnostics(
+                        os.path.join(self.resultsdir, "audio_diagnostics.txt"))
                 raise error.TestFail('Input buffer level %d drift too high' %
                                      buffer_level)
 
         if stream_type == _STREAM_TYPE_OUTPUT:
             logging.debug("Max output buffer level: %d", buffer_level)
             if buffer_level > self._OUTPUT_BUFFER_DRIFT_CRITERIA:
-                self._dump_audio()
+                audio_helper.dump_audio_diagnostics(
+                        os.path.join(self.resultsdir, "audio_diagnostics.txt"))
                 raise error.TestFail('Output buffer level %d drift too high' %
                                      buffer_level)