1 /*
2  Copyright (c) 2018, MIPI Alliance, Inc.
3  All rights reserved.
4 
5  Redistribution and use in source and binary forms, with or without
6  modification, are permitted provided that the following conditions
7  are met:
8 
9  * Redistributions of source code must retain the above copyright
10    notice, this list of conditions and the following disclaimer.
11 
12  * Redistributions in binary form must reproduce the above copyright
13    notice, this list of conditions and the following disclaimer in
14    the documentation and/or other materials provided with the
15    distribution.
16 
17  * Neither the name of the copyright holder nor the names of its
18    contributors may be used to endorse or promote products derived
19    from this software without specific prior written permission.
20 
21  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 */
33 
34 /*
35  * Contributors:
36  * Norbert Schulz (Intel Corporation) - Initial API and implementation
37  */
38 
39 #include <iostream>
40 #include <fstream>
41 #include <vector>
42 #include <string>
43 #include <memory>
44 
45 #include "mipi_syst_decode.h"
46 #include "mipi_syst_guid.h"
47 
48 // print program usage banner
49 //
usage(const std::string & details)50 static void usage(const std::string& details)
51 {
52 	std::cerr << "usage: systprint [-p] [-c <collateralXML>...] [-g short-message-guid] [-o output] [inputfile(s)...]" << std::endl;
53 	std::cerr << "    -p / --payload_only         only print payload (default is CSV)" << std::endl;
54 	std::cerr << "    -c / --colateral filename   load given SyS-T collateral XML" << std::endl;
55 	std::cerr << "    -g / --short_guid guid      guid value for short messages" << std::endl;
56 	std::cerr << "    -o / --output file          output file name (default stdout)" << std::endl;
57 	std::cerr << "    inputfile(s)...             file(s) with example library platform output or '-' for stdin" << std::endl;
58 	std::cerr << std::endl;
59 
60 	if (!details.empty()) {
61 		std::cerr << details << std::endl;
62 	}
63 	exit(1);
64 }
65 
66 
67 // ASCII char -> HEX nibble value, or 0xFF if invalid
68 //
69 static const uint8_t hexCharVal[] =
70 {
71 	0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
72 	0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
73 	0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
74 	0,       1,    2,    3,    4,    5,    6,    7,    8,    9, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
75 	0xFF,   10,   11,   12,   13,   14,   15, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
76 	0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
77 	0xFF,   10,   11,   12,   13,   14,   15, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
78 	0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
79 };
80 
81 
82 // Convert ASCII hex string into byte array, fail if string is not a
83 // sequence of 0..(2*n) hex characters
84 //
hex2bin(const std::string & hexStr,std::vector<uint8_t> & dest)85 static bool hex2bin(const std::string& hexStr, std::vector<uint8_t>& dest)
86 {
87 	size_t nibbles(hexStr.size());
88 
89 	if (nibbles % 2) {         // 2 chars needed for 1 value
90 		return false;
91 	}
92 	dest.clear();
93 
94 	for(auto hexChar(hexStr.c_str()); nibbles ; nibbles -= 2)
95 	{
96 		auto high(hexCharVal[(uint8_t)*hexChar++]);
97 		auto low(hexCharVal[(uint8_t)*hexChar++]);
98 		if (high == 0xFF || low == 0xFF) {
99 			return false;
100 		}
101 		dest.push_back((high << 4) | low);
102 	}
103 	return true;
104 }
105 
106 
107 // Scan input file that is assumed to come from the SyS-T library example platform.
108 // Extract the raw event HEX data lines that look like this
109 //
110 //  SYS-T RAW DATA: 4202000B0...
111 //
112 // Then parse the hex portion of the line and try to decode it as a SyS-T message.
113 //
readAndPrint(std::istream & is,std::ostream & os,bool payload_only,const mipi::syst::decode_context * ctx,const mipi::syst::decoder & decoder)114 static void readAndPrint(std::istream& is, std::ostream& os,
115 	bool payload_only,
116 	const  mipi::syst::decode_context * ctx,
117 	 const mipi::syst::decoder& decoder)
118 {
119 	static const std::string pattern("SYS-T RAW DATA: ");
120 	std::string line;
121 
122 	while (getline(is, line)) {
123 		if (line.compare(0, pattern.size(), pattern)) {
124 			continue;  // not a raw dump of a SyS-T message
125 		}
126 
127 		// sanitize line endings
128 		//
129 		while (line.size() &&
130 		       (line[line.size()-1] == '\r' ||
131 			line[line.size()-1] == '\n'))
132 		{
133 			line.erase(line.size()-1);
134 		}
135 		std::vector<uint8_t> bytes;
136 		if (!hex2bin(line.substr(pattern.size()), bytes)) {
137 			continue;
138 		}
139 		mipi::syst::message msg;
140 
141 		decoder.decode(msg, bytes, ctx);
142 		if (payload_only) {
143 			os << msg.getPayload() << std::endl;
144 		} else {
145 			os << msg;
146 		}
147 	}
148 }
149 
150 /// Simple GUID context wrapper
151 //
152 // This class implements a trivial decode context provider by just
153 // wrapping a guid set from the command line. A real implementation would
154 // encapsulate transport information here to build client identifying
155 // information. @see mipi::syst::decode_context
156 //
157 class short_guid_context : public mipi::syst::decode_context {
158 public:
short_guid_context(const mipi::syst::guid & g)159 	short_guid_context(const mipi::syst::guid& g) : m_guid(g), m_fakeTS(0) {}
160 
getGuid() const161 	const mipi::syst::guid& getGuid() const {
162 		return m_guid;
163 	}
164 
getTS() const165 	uint64_t getTS() const {
166 		return m_fakeTS++; // replace with transport TS
167 	}
168 private:
169 	mipi::syst::guid m_guid;
170 	mutable uint64_t m_fakeTS;
171 };
172 
173 
main(int argc,char ** argv)174 int main(int argc, char ** argv)
175 {
176 	std::vector<std::string> inputs;
177 	std::string output;
178 	bool payload_only(false);
179 	std::shared_ptr<short_guid_context> short_ctx(nullptr);   // guid to use for short messages
180 
181 	mipi::syst::decoder decoder;
182 
183 	// parse & check arguments
184 	//
185 	for (auto i = 1; i < argc; ++i) {
186 		const std::string arg(argv[i]);
187 		if (arg == "-c" || arg == "--collateral") {
188 			if (++i >= argc) {
189 				usage("missing collateral file argument");
190 			}
191 			try {
192 				decoder.loadCollateral(argv[i]);
193 			}
194 			catch (std::exception& e) {
195 				std::cerr << "error loading '" << argv[i] << "': " << e.what();
196 				exit(1);
197 			}
198 		} else if (arg == "-p" || arg == "--payload_only") {
199 			payload_only = true;
200 		} else if (arg == "-g" || arg == "--short_guid") {
201 			if (++i >= argc) {
202 				usage("missing guid argument for -g/--short_guid option");
203 			}
204 			try {
205 				short_ctx = std::make_shared<short_guid_context>(
206 					mipi::syst::guid(argv[i]));
207 			} catch (std::exception& e) {
208 				std::cerr << e.what();
209 				exit(1);
210 			}
211 		} else if (arg == "-o" || arg == "--output") {
212 			if (++i >= argc) {
213 				usage("missing filename argument for -o/--output option");
214 			}
215 			output = argv[i];
216 		} else if (arg == "-") {   //stdin
217 			inputs.push_back(arg);
218 		} else if (arg[0] == '-') {
219 			usage(std::string("unknown argument : ") + arg);
220 		} else {
221 			inputs.push_back(arg);
222 		}
223 	}
224 
225 	if (inputs.empty()) {
226 		usage("no input provided");
227 	}
228 
229 	// set output destination (default stdout)
230 	//
231 	std::ostream * os(&std::cout);
232 	std::ofstream  ofs;
233 
234 	if (!output.empty()) {
235 		ofs.open(output.c_str(), std::ofstream::out);
236 		if (!ofs.is_open()) {
237 			std::cerr << "unable to open output file : " <<  output << std::endl;
238 			exit(1);
239 		}
240 		os = &ofs;
241 	}
242 
243 	if (!payload_only) {
244 		*os << mipi::syst::message::csvHeaderString << std::endl;
245 	}
246 	for (auto input : inputs) {
247 		if (input == "-") {
248 			readAndPrint(std::cin, *os, payload_only, short_ctx.get(), decoder);
249 		} else {
250 			std::ifstream ifs(input);
251 			if (!ifs.is_open()) {
252 				std::cerr << "unable to open input file : " << input << std::endl;
253 				exit(1);
254 			}
255 			readAndPrint(ifs, *os, payload_only, short_ctx.get(), decoder);
256 			ifs.close();
257 		}
258 	}
259 
260 	if (ofs.is_open()) {
261 		ofs.close();
262 	}
263 
264 	return 0;
265 }