Innovenergy_trunk/csharp/App/Collector/src/Influx/LineProtocolSyntax.cs

76 lines
2.4 KiB
C#

using System.Diagnostics.CodeAnalysis;
using static System.Globalization.CultureInfo;
namespace InnovEnergy.App.Collector.Influx;
internal static class LineProtocolSyntax
{
private static readonly DateTime Origin = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
public static String EscapeName(String nameOrKey)
{
return nameOrKey
.Replace("=", "\\=")
.Replace(" ", "\\ ")
.Replace(",", "\\,");
}
[SuppressMessage("ReSharper", "RedundantVerbatimPrefix")]
public static String FormatValue(Object value)
{
return value switch
{
String @string => FormatString (@string),
Single @single => FormatFloat (@single),
Double @double => FormatFloat (@double),
Int32 @int32 => FormatInteger (@int32),
UInt32 @uInt32 => FormatInteger (@uInt32),
Int64 @int64 => FormatInteger (@int64),
UInt64 @uInt64 => FormatInteger (@uInt64),
Decimal @decimal => FormatFloat (@decimal),
Int16 @int16 => FormatInteger (@int16),
UInt16 @uInt16 => FormatInteger (@uInt16),
SByte @sByte => FormatInteger (@sByte),
Byte @byte => FormatInteger (@byte),
Boolean @boolean => FormatBoolean (@boolean),
TimeSpan @timeSpan => FormatTimespan(@timeSpan),
_ => FormatString (value.ToString())
};
}
private static String FormatInteger<T>(T i) where T: IFormattable
{
return FormatFloat(i) + "i";
}
private static String FormatFloat<T>(T f) where T: IFormattable
{
return f.ToString(format: null, InvariantCulture);
}
private static String FormatTimespan(TimeSpan timeSpan)
{
return timeSpan
.TotalMilliseconds
.ToString(InvariantCulture);
}
private static String FormatBoolean(Boolean b) => b ? "t" : "f";
private static String FormatString(Object? o)
{
var s = o?.ToString();
return s is null
? "<null>"
: "\"" + s.Replace("\"", "\\\"") + "\"";
}
public static String FormatTimestamp(DateTime utcTimestamp)
{
var t = utcTimestamp - Origin;
return (t.Ticks * 100L).ToString(InvariantCulture);
}
}