-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSerialController.cs
More file actions
87 lines (76 loc) · 2.29 KB
/
Copy pathSerialController.cs
File metadata and controls
87 lines (76 loc) · 2.29 KB
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
using Godot;
using System;
using System.IO.Ports;
// New USB device found, idVendor=1a86, idProduct=7523, bcdDevice= 2.60
public class SerialController : Node
{
[Signal] delegate void StatusChanged(string message);
[Export] string PortName = "/dev/ttyUSB0";
[Export] int BaudRate = 9600;
private SerialPort _serialPort;
public override void _Ready()
{
GD.Print("[SerialManager] Serial controller loaded");
GD.Print("Port is: " + PortName);
GD.Print("Bound rate is: " + BaudRate);
}
public void WriteData(string data)
{
GD.Print($"[SerialManager] Trying to send character {data} to serial");
if (_serialPort != null && _serialPort.IsOpen)
{
try
{
_serialPort.Write(data);
EmitSignal(nameof(StatusChanged), "Data written");
}
catch (Exception ex)
{
GD.PrintErr($"[SerialManager] Error sending character: {ex.Message}");
}
}
else
{
GD.PrintErr("[SerialManager] Serial port is not open.");
}
}
public string[] GetAllPorts()
{
return SerialPort.GetPortNames();
}
public void OpenPort()
{
GD.Print($"[SerialManager] Trying to open serial port at {PortName}, with {BaudRate} bound rate");
try
{
_serialPort = new SerialPort(PortName, BaudRate);
_serialPort.Open();
GD.Print($"[SerialManager] Port {PortName} open.");
EmitSignal(nameof(StatusChanged), "Port opened");
}
catch (Exception ex)
{
GD.PrintErr($"[SerialManager] Error opening port: {ex.Message}");
EmitSignal(nameof(StatusChanged), ex.Message);
}
}
public void ClosePort()
{
GD.Print("[SerialManager] Closing serial port");
if (_serialPort != null && _serialPort.IsOpen)
{
_serialPort.Close();
_serialPort.Dispose();
GD.Print("[SerialManager] Port closed.");
EmitSignal(nameof(StatusChanged), "Port closed");
}
else
{
GD.Print("[SerialManager] Port already closed.");
}
}
public override void _ExitTree()
{
ClosePort();
}
}