chr
2026-04-05 fe750b791d5b517cc4e9bc8e99a9a75139a0cfba
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
//            Copyright Keysight Technologies 2012-2019
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, you can obtain one at http://mozilla.org/MPL/2.0/.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
 
namespace OpenTap
{
    /// <summary>
    /// Utility class for SCPI communication.
    /// </summary>
    public static class Scpi
    {
        /// <summary>
        /// Enum converter for converting Enums to SCPI strings. use the GetEnumConv to get a converter.
        /// </summary>
        class ScpiEnum
        {
            // Remembers how to convert types.
            static readonly ConcurrentDictionary<Type, ScpiEnum> converters = new ConcurrentDictionary<Type, ScpiEnum>();
 
            /// <summary> Get an enum converter for a specific enum type. </summary>
            /// <param name="t">Must be a enum type!</param>
            /// <returns></returns>
            public static ScpiEnum GetEnumConv(Type t)
            {
                return converters.GetOrAdd(t, t2 => new ScpiEnum(t2));
            }
 
            readonly ImmutableDictionary<string, Enum> convertBack;
            readonly ImmutableDictionary<Enum, string> convert;
 
            /// <summary> String to Enum. </summary>
            /// <param name="input"></param>
            /// <returns></returns>
            public Enum FromString(string input)
            {
                return convertBack[input];
            }
 
            /// <summary>
            /// Enum to string.
            /// </summary>
            /// <param name="item"></param>
            /// <returns></returns>
            public string ToString(Enum item)
            {
                return convert[item];
            }
 
            ScpiEnum(Type type)
            {
                // collect enum values and string conversions.
                var enumValues = Enum.GetValues(type);
                
                var enum2String = new Dictionary<Enum, string>();
                var string2Enum = new Dictionary<string, Enum>();
                foreach (Enum val in enumValues)
                {
                    var member = type.GetMember(val.ToString())[0];
                    var scpiName = member.GetCustomAttribute<ScpiAttribute>()?.ScpiString ?? val.ToString();
                    enum2String[val] = scpiName;
                    string2Enum[scpiName] = val;
                }
 
                convert = enum2String.ToImmutableDictionary();
                convertBack = string2Enum.ToImmutableDictionary();
            }
        }
 
        static string valueToScpiString(object propertyValue)
        {
            var type = propertyValue.GetType();
            string value;
            if (type == typeof(bool))
            {
                value = (bool)propertyValue ? "ON" : "OFF";
            }
            else if (type.IsEnum)
            {
                value = ScpiEnum.GetEnumConv(type).ToString((Enum)propertyValue);
            }
            else if (type.IsArray)
            {
                var Props = (Array)propertyValue;
 
                string[] PropStrings = new string[Props.Length];
                for (int i = 0; i < Props.Length; i++)
                    PropStrings[i] = valueToScpiString(Props.GetValue(i));
 
                value = string.Join(",", PropStrings);
            }
            else
            {
                value = Convert.ToString(propertyValue, CultureInfo.InvariantCulture);
            }
 
            return value;
        }
 
        /// <summary>
        /// Similar to <see cref="string.Format(string,object[])"/>, but makes args SCPI compatible. Bools are ON/OFF formatted. Enum values uses <see cref="ScpiAttribute.ScpiString"/>.
        /// Arrays will have their elements formatted and separated by commas if available; if not they are converted using <see cref="string.ToString()"/>.
        /// </summary>
        /// <param name="command"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        public static string Format(string command, params object[] args)
        {
            if (command == null)
                throw new ArgumentNullException("command");
            if (args == null)
                throw new ArgumentNullException("args");
            string[] stringArgs = new string[args.Length];
            for (int i = 0; i < args.Length; i++)
            {
                stringArgs[i] = args[i] == null ? "" : valueToScpiString(args[i]);
            }
            return string.Format(command, stringArgs);
        }
 
        /// <summary>
        /// Extension method that checks whether a given char is a IEEE488.2 whitespace (7.4.1.2).
        /// </summary>
        private static bool IsScpiWhitespace(this char c)
        {
            return (
                ((((int)c) >= 0) && (((int)c) <= 9)) ||
                ((((int)c) >= 11) && (((int)c) <= 32))
            );
        }
 
        private static int FindStringEnd(string Resp, int Start)
        {
            int stop = Resp.IndexOf("\"", Start + 1);
 
            if (stop < 0)
                return -1;
            // Skip inserted quotes
            while ((stop < (Resp.Length - 1)) && (Resp.Substring(stop, 2) == "\"\""))
            {
                stop = Resp.IndexOf("\"", stop + 2);
                if (stop < 0)
                    return -1;
            }
 
            return stop;
        }
 
        /// <summary>
        /// Splits a string into a list of valid separated SCPI response data strings. Needed because String.Split(resp, ',') is not tolerant to " characters.
        /// </summary>
        private static List<string> SplitScpiArray(string resp, bool ThrowIfInvalid = false)
        {
            List<string> result = new List<string>();
 
            int start = 0;
            int stop = 0;
 
            while (start < (resp.Length - 1))
            {
                // Trim whitespace from the start of the string
                char c = resp[start];
                while (c.IsScpiWhitespace())
                    c = resp[++start];
                stop = start;
 
                // Test if the next character is a string quote
                if (c == '"')
                {
                    stop = FindStringEnd(resp, stop);
 
                    if (stop < 0)
                    {
                        if (ThrowIfInvalid) throw new Exception(string.Format("Unterminated SCPI response: '{0}'", resp));
                        stop = resp.Length;
                    }
                    else
                        stop++;
 
                    result.Add(resp.Substring(start, stop - start));
 
                    stop = resp.IndexOf(",", stop);
                    if (stop < 0)
                        stop = resp.Length;
                    start = stop + 1;
                }
                else
                {
                    stop = resp.IndexOf(",", start);
 
                    if (stop < 0)
                        stop = resp.Length;
 
                    result.Add(resp.Substring(start, stop - start));
                    start = stop + 1;
                }
            }
            if (start < resp.Length)
                result.Add(resp.Substring(start));
            return result;
        }
 
        /// <summary>
        /// Overloaded.  Parses the result of a SCPI query back to T, with special parsing for enums, bools and arrays. Bools support 1/0 and ON/OFF formats. 
        /// If Enums are tagged with <see cref="ScpiAttribute"/>, <see cref="ScpiAttribute.ScpiString"/> will be used instead of <see cref="string.ToString()"/> .  
        /// </summary>
        /// <param name="scpiString"></param>
        /// <param name="T"></param>
        /// <returns></returns>
        public static object Parse(string scpiString, Type T)
        {
            if (scpiString == null)
                throw new ArgumentNullException("scpiString");
            if (T == null)
                throw new ArgumentNullException("T");
            scpiString = scpiString.Trim(); // Ensure no garbage.
            if (T == typeof(bool))
            {
                return scpiString == "ON" || scpiString == "1";
            }
            else if (T.IsEnum)
            {
                return (object)ScpiEnum
                    .GetEnumConv(T)
                    .FromString(scpiString);
            }
            else if (T.IsArray)
            {
                List<string> elements = SplitScpiArray(scpiString);
                Array result = Array.CreateInstance(T.GetElementType(), elements.Count);
 
                for (int i = 0; i < elements.Count; i++)
                    result.SetValue(Parse(elements[i], T.GetElementType()), i);
 
                return result;
            }
 
            return Convert.ChangeType(scpiString, T, CultureInfo.InvariantCulture);
        }
 
        /// <summary>
        /// Parses the result of a SCPI query back to T. Special parsing for enums, bools and arrays. bools supports 1/0 and ON/OFF formats. 
        /// If Enums are tagged with <see cref="ScpiAttribute"/> <see cref="ScpiAttribute.ScpiString"/> will be used instead of <see cref="string.ToString()"/>.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="scpiString"></param>
        /// <returns></returns>
        public static T Parse<T>(string scpiString)
        {
            return (T)Parse(scpiString, typeof(T));
        }
 
        /// <summary>
        /// <see cref="GetUnescapedScpi"/>.
        /// </summary>
        /// <param name="src"></param>
        /// <param name="ScpiString"></param>
        /// <param name="property"></param>
        /// <returns></returns>
        static string getUnescapedScpi(object src, string ScpiString, PropertyInfo property)
        {
 
            if (ScpiString.Contains("%"))
            {
                string value;
                object propertyValue = property.GetValue(src, null);
                if (propertyValue == null)
                    return ScpiString;
                value = valueToScpiString(propertyValue);
 
                return ScpiString.Replace("%", value);
            }
 
            if (property.PropertyType == typeof(bool) && ScpiString.Contains("|"))
            {
                Regex rx = new Regex(".* (?<true>[^|]+)\\|(?<false>[^\\s]+)");
                Match m = rx.Match(ScpiString);
                if (m.Success)
                {
                    bool value = (bool)property.GetValue(src, null);
                    if (value == true)
                        return ScpiString.Replace("|" + m.Groups["false"], "");
                    else
                        return ScpiString.Replace(m.Groups["true"] + "|", "");
                }
            }
            return ScpiString;
        }
        /// <summary>
        /// Parses one or more items of <see cref="ScpiAttribute.ScpiString"/> 'property', replacing '%' with the value of the property given after formatting. 
        /// Note that 'property' must be a property with the <see cref="ScpiAttribute"/>, and 'src' is the object containing 'property', not the value of the property. 
        /// If property.PropertyType is bool, then from the <see cref="ScpiAttribute.ScpiString"/> value 'A|B' A is selected if true, and B is selected if false.  
        /// </summary>
        public static string[] GetUnescapedScpi(object src, PropertyInfo property)
        {
            if (property == null)
                throw new ArgumentNullException("property");
            var scpiStrings = property.GetCustomAttributes<ScpiAttribute>().Select(scpiAttr => scpiAttr.ScpiString);
            return scpiStrings.Select(str => getUnescapedScpi(src, str, property)).ToArray();
        }
    }
}