blob: 5f47430a212608ad4c4784c8a8adb6115d4235b2 [file] [log] [blame]
Sergei Trofimov4e6afe92015-10-09 09:30:04 +01001# Copyright 2015 ARM Limited
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14#
15from __future__ import division
16import os
17import csv
18import signal
19import tempfile
20import struct
21import subprocess
22
Sergei Trofimov4e6afe92015-10-09 09:30:04 +010023from devlib.instrument import Instrument, CONTINUOUS, MeasurementsCsv
24from devlib.exception import HostError
25from devlib.utils.misc import which
26
27
28class EnergyProbeInstrument(Instrument):
29
30 mode = CONTINUOUS
31
32 def __init__(self, target, resistor_values,
33 labels=None,
34 device_entry='/dev/ttyACM0',
35 ):
36 super(EnergyProbeInstrument, self).__init__(target)
37 self.resistor_values = resistor_values
38 if labels is not None:
39 self.labels = labels
40 else:
41 self.labels = ['PORT_{}'.format(i)
42 for i in xrange(len(resistor_values))]
43 self.device_entry = device_entry
44 self.caiman = which('caiman')
45 if self.caiman is None:
46 raise HostError('caiman must be installed on the host '
47 '(see https://github.com/ARM-software/caiman)')
Sergei Trofimov4e6afe92015-10-09 09:30:04 +010048 self.attributes_per_sample = 3
49 self.bytes_per_sample = self.attributes_per_sample * 4
50 self.attributes = ['power', 'voltage', 'current']
51 self.command = None
52 self.raw_output_directory = None
53 self.process = None
Brendan Jackman49b547a2017-04-26 15:07:05 +010054 self.sample_rate_hz = 10000 # Determined empirically
Sergei Trofimov4e6afe92015-10-09 09:30:04 +010055
56 for label in self.labels:
57 for kind in self.attributes:
58 self.add_channel(label, kind)
59
Sergei Trofimov390a5442016-09-02 14:03:33 +010060 def reset(self, sites=None, kinds=None, channels=None):
61 super(EnergyProbeInstrument, self).reset(sites, kinds, channels)
Sergei Trofimov4e6afe92015-10-09 09:30:04 +010062 self.raw_output_directory = tempfile.mkdtemp(prefix='eprobe-caiman-')
63 parts = ['-r {}:{} '.format(i, int(1000 * rval))
64 for i, rval in enumerate(self.resistor_values)]
65 rstring = ''.join(parts)
66 self.command = '{} -d {} -l {} {}'.format(self.caiman, self.device_entry, rstring, self.raw_output_directory)
67
68 def start(self):
69 self.logger.debug(self.command)
70 self.process = subprocess.Popen(self.command,
71 stdout=subprocess.PIPE,
72 stderr=subprocess.PIPE,
73 stdin=subprocess.PIPE,
74 preexec_fn=os.setpgrp,
75 shell=True)
76
77 def stop(self):
Brendan Jackmanfdc0c042017-03-24 13:35:00 +000078 self.process.poll()
79 if self.process.returncode is not None:
80 stdout, stderr = self.process.communicate()
81 raise HostError(
82 'Energy Probe: Caiman exited unexpectedly with exit code {}.\n'
83 'stdout:\n{}\nstderr:\n{}'.format(self.process.returncode,
84 stdout, stderr))
Leo Yana48775e2017-06-05 19:14:19 +080085 os.killpg(self.process.pid, signal.SIGINT)
Sergei Trofimov4e6afe92015-10-09 09:30:04 +010086
87 def get_data(self, outfile): # pylint: disable=R0914
88 all_channels = [c.label for c in self.list_channels()]
89 active_channels = [c.label for c in self.active_channels]
90 active_indexes = [all_channels.index(ac) for ac in active_channels]
91
92 num_of_ports = len(self.resistor_values)
93 struct_format = '{}I'.format(num_of_ports * self.attributes_per_sample)
94 not_a_full_row_seen = False
95 raw_data_file = os.path.join(self.raw_output_directory, '0000000000')
96
97 self.logger.debug('Parsing raw data file: {}'.format(raw_data_file))
98 with open(raw_data_file, 'rb') as bfile:
99 with open(outfile, 'wb') as wfh:
100 writer = csv.writer(wfh)
101 writer.writerow(active_channels)
102 while True:
103 data = bfile.read(num_of_ports * self.bytes_per_sample)
104 if data == '':
105 break
106 try:
107 unpacked_data = struct.unpack(struct_format, data)
108 row = [unpacked_data[i] / 1000 for i in active_indexes]
109 writer.writerow(row)
110 except struct.error:
111 if not_a_full_row_seen:
112 self.logger.warn('possibly missaligned caiman raw data, row contained {} bytes'.format(len(data)))
113 continue
114 else:
115 not_a_full_row_seen = True
Marc Bonnici049b2752017-08-03 16:43:32 +0100116 return MeasurementsCsv(outfile, self.active_channels, self.sample_rate_hz)