forked from nricciar/usb_scale
-
Notifications
You must be signed in to change notification settings - Fork 0
/
UsbScale.cs
80 lines (76 loc) · 2.15 KB
/
UsbScale.cs
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
using System;
using System.Threading;
using HidLibrary;
using ScaleInterface;
namespace ScaleReader
{
class Program
{
public static void Error(string message)
{
Console.WriteLine(@"{{""success"":false,""error"":""{0}""}}", message);
}
public static void Main(string[] args)
{
int scale = 0;
int retryTime = 100;
int timeoutLength = 3000;
bool debug = false;
for (int i = 0; i < args.Length; i++)
{
string arg = args[i];
if (arg.StartsWith("--"))
{
// Command-line flags take the form `--arg-name=100` or `--arg-name`
string argName;
int argValue = 0;
// We're assuming all argument values will be integers.
if (arg.IndexOf('=') != -1)
{
argName = arg.Substring(2, arg.LastIndexOf('=') - 2);
argValue = Int32.Parse(arg.Substring(arg.LastIndexOf('=') + 1));
} else {
argName = arg.Substring(2, arg.Length - 2);
}
switch (argName)
{
case "retry":
retryTime = argValue;
break;
case "fail":
timeoutLength = argValue;
break;
case "debug":
debug = true;
break;
}
}
// The last argument should always be the scale number.
else if (!(Int32.TryParse(arg, out scale) && i == args.Length - 1))
{
Error(string.Format("Invalid command-line argument. -- {0}", arg));
Environment.Exit(1);
}
}
decimal? weight;
USBScale s = new USBScale(scale, retryTime, timeoutLength);
s.Connect();
if (s.IsConnected)
{
ScaleWeightStatus status = s.GetWeight(out weight);
s.Disconnect();
if (status != ScaleWeightStatus.Stable)
{
Error(USBScale.ErrorStringFor(status));
} else {
Console.WriteLine(@"{{""success"":true,""weight"":{0},""units"":""lbs""}}", weight);
}
if (debug) {
s.DebugScaleData();
}
} else {
Error("No Scale Connected.");
}
}
}
}