-
Notifications
You must be signed in to change notification settings - Fork 0
/
MainPage.xaml.cs
102 lines (81 loc) · 2.33 KB
/
MainPage.xaml.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
namespace SetT41Clock;
using System.IO.Ports;
public partial class MainPage : ContentPage
{
// serial port data
private bool connectionStarted = false;
private string selectedPort = "";
private SerialPort? serialPort = null;
public string[] Ports { get; set; }
public MainPage()
{
InitializeComponent();
Ports = SerialPort.GetPortNames();
serialPortPicker.ItemsSource = Ports;
}
public bool Connect(string port) {
bool result = false;
try {
if (!connectionStarted && port != selectedPort) {
// try to connect to selected port
serialPort = new SerialPort();
serialPort.PortName = port;
// we have a USB serial port communicating at native USB speeds
// these aren't used
serialPort.BaudRate = 19200;
serialPort.Parity = Parity.None;
serialPort.DataBits = 8;
serialPort.DtrEnable = false;
serialPort.RtsEnable = false;
try {
serialPort.Open();
}
//catch (Exception ex) {
catch (Exception) {
connectionStarted = false;
selectedPort = "";
return result;
}
Thread.Sleep(30);
if (serialPort.IsOpen) {
connectionStarted = true;
selectedPort = port;
result = true;
// set T41 time
SetTime();
} else {
connectionStarted = false;
selectedPort = "";
}
}
return result;
}
//catch (Exception ex) {
catch (Exception) {
connectionStarted = false;
selectedPort = "";
return result;
}
}
public void SetTime() { //long time) {
// *** TODO: the T41 time will lag from this by the serial processing time, add a second for now ***
SendCmd("TM" + (DateTimeOffset.Now.ToUnixTimeSeconds() - 7 * 60 * 60 + 1).ToString("D11"));
}
private void SendCmd(string cmd) {
if (serialPort != null && serialPort.IsOpen) {
serialPort.Write(cmd + ";");
}
}
private void serialPortPicker_SelectedIndexChanged(object sender, EventArgs e) {
var picker = (Picker)sender;
int selectedIndex = picker.SelectedIndex;
if(selectedIndex != -1) {
var port = picker.ItemsSource[selectedIndex];
if(port != null) {
if(Connect((string)port)) {
SetTime();
}
}
}
}
}