001/*
002 * Copyright (C) Cross The Road Electronics.  All rights reserved.
003 * License information can be found in CTRE_LICENSE.txt
004 * For support and suggestions contact support@ctr-electronics.com or file
005 * an issue tracker at https://github.com/CrossTheRoadElec/Phoenix-Releases
006 */
007package com.ctre.phoenix6;
008
009import com.ctre.phoenix6.jni.CANBusJNI;
010
011import java.nio.ByteBuffer;
012import java.nio.charset.StandardCharsets;
013
014/**
015 * Class for getting information about an available CAN bus.
016 */
017public class CANBus implements Cloneable, Comparable<CANBus> {
018    /**
019     * Contains status information about a CAN bus.
020     */
021    public static class CANBusStatus {
022        /**
023         * Status code response of getting the data
024         */
025        public StatusCode Status;
026
027        /**
028         * CAN bus utilization, from 0.0 to 1.0
029         */
030        public float BusUtilization;
031        /**
032         * Bus off count
033         */
034        public int BusOffCount;
035        /**
036         * Transmit buffer full count
037         */
038        public int TxFullCount;
039        /**
040         * Receive Error Counter (REC)
041         */
042        public int REC;
043        /**
044         * Transmit Error Counter (TEC)
045         */
046        public int TEC;
047    }
048
049    private final String _name;
050    private ByteBuffer _nameByteBuffer = null;
051    private CANBusStatus _status = null;
052    private CANBusJNI _jni = null;
053
054    /**
055     * Creates a new CAN bus using the default for the system:
056     * <ul>
057     *   <li>"rio" on roboRIO
058     *   <li>"can0" on Linux
059     *   <li>"*" on Windows
060     * </ul>
061     */
062    public CANBus() {
063        this("");
064    }
065
066    /**
067     * Creates a new CAN bus with the given name.
068     * <p>
069     * For the native roboRIO CAN bus, use {@link #roboRIO()} instead.
070     *
071     * @param canbus    Name of the CAN bus. Possible CAN bus strings are:
072     *                  <ul>
073     *                    <li>"rio" for the native roboRIO CAN bus
074     *                    <li>CANivore name or serial number
075     *                    <li>SocketCAN interface (non-FRC Linux only)
076     *                    <li>"*" for any CANivore seen by the program
077     *                    <li>empty string (default) to select the default for the system:
078     *                    <ul>
079     *                      <li>"rio" on roboRIO
080     *                      <li>"can0" on Linux
081     *                      <li>"*" on Windows
082     *                    </ul>
083     *                  </ul>
084     */
085    public CANBus(String canbus) {
086        _name = canbus;
087    }
088
089    /**
090     * Creates a new CAN bus with the given name, and loads an associated
091     * hoot file for replay (equivalent to {@link HootReplay#loadFile}).
092     * <p>
093     * Only one hoot log may be replayed at a time. As a result, only one
094     * CAN bus should be constructed with a hoot file.
095     * <p>
096     * When using relative paths, the file path is typically relative
097     * to the top-level folder of the robot project.
098     * <p>
099     * For the native roboRIO CAN bus, use {@link #roboRIO(String)} instead.
100     *
101     * @param canbus    Name of the CAN bus. Possible CAN bus strings are:
102     *                  <ul>
103     *                    <li>"rio" for the native roboRIO CAN bus
104     *                    <li>CANivore name or serial number
105     *                    <li>SocketCAN interface (non-FRC Linux only)
106     *                    <li>"*" for any CANivore seen by the program
107     *                    <li>empty string (default) to select the default for the system:
108     *                    <ul>
109     *                      <li>"rio" on roboRIO
110     *                      <li>"can0" on Linux
111     *                      <li>"*" on Windows
112     *                    </ul>
113     *                  </ul>
114     * @param hootFilepath Path and name of the hoot file to load
115     */
116    public CANBus(String canbus, String hootFilepath) {
117        this(canbus);
118        HootReplay.loadFile(hootFilepath);
119    }
120
121    /**
122     * Creates a new CAN bus for the native roboRIO bus.
123     *
124     * @return The native roboRIO CAN bus
125     */
126    public static CANBus roboRIO() {
127        return new CANBus("rio");
128    }
129
130    /**
131     * Creates a new CAN bus for the native roboRIO bus, and
132     * loads an associated hoot file for replay (equivalent to
133     * {@link HootReplay#loadFile}).
134     * <p>
135     * Only one hoot log may be replayed at a time. As a result, only one
136     * CAN bus should be constructed with a hoot file.
137     * <p>
138     * When using relative paths, the file path is typically relative
139     * to the top-level folder of the robot project.
140     *
141     * @param hootFilepath Path and name of the hoot file to load
142     * @return The native roboRIO CAN bus
143     */
144    public static CANBus roboRIO(String hootFilepath) {
145        HootReplay.loadFile(hootFilepath);
146        return roboRIO();
147    }
148
149    /**
150     * Get the name used to construct this CAN bus.
151     *
152     * @return Name of the CAN bus
153     */
154    public final String getName() {
155        return _name;
156    }
157
158    /**
159     * Get the name used to construct this CAN bus as raw UTF-8
160     * bytes, including null termination. This is only used for
161     * JNI; robot code should call {@link #getName()} instead.
162     *
163     * @return Name of the CAN bus as a raw UTF-8 byte buffer
164     */
165    public final ByteBuffer getNameUTF8Bytes() {
166        if (_nameByteBuffer == null) {
167            final var nameBytes = _name.getBytes(StandardCharsets.UTF_8);
168            final var nameByteBuffer = ByteBuffer.allocateDirect(nameBytes.length + 1);
169            nameByteBuffer.put(nameBytes);
170            nameByteBuffer.put((byte)0);
171            _nameByteBuffer = nameByteBuffer.asReadOnlyBuffer();
172        }
173        return _nameByteBuffer;
174    }
175
176    /**
177     * Gets whether the network is CAN FD.
178     *
179     * @return True if the network is CAN FD
180     */
181    public final boolean isNetworkFD() {
182        return CANBusJNI.JNI_IsNetworkFD(getNameUTF8Bytes());
183    }
184
185    /**
186     * Gets the status of the CAN bus, including the
187     * bus utilization and the error counters.
188     * <p>
189     * This can block for up to 0.001 seconds (1 ms).
190     * <p>
191     * This function refreshes and returns a cached object.
192     *
193     * @return Status of the CAN bus
194     */
195    public final CANBusStatus getStatus() {
196        if (_status == null) {
197            _status = new CANBusStatus();
198        }
199        if (_jni == null) {
200            _jni = new CANBusJNI();
201        }
202        var err = _jni.JNI_GetStatus(getNameUTF8Bytes());
203
204        _status.BusUtilization = _jni.busUtilization;
205        _status.BusOffCount = _jni.busOffCount;
206        _status.TxFullCount = _jni.txFullCount;
207        _status.REC = _jni.rec;
208        _status.TEC = _jni.tec;
209
210        if (err != 0) {
211            _status.Status = StatusCode.InvalidNetwork;
212        } else {
213            _status.Status = StatusCode.OK;
214        }
215        return _status;
216    }
217
218    @Override
219    public String toString() {
220        return getName();
221    }
222
223    @Override
224    public boolean equals(Object other) {
225        if (other instanceof CANBus canbus) {
226            return getName().equals(canbus.getName());
227        }
228        return false;
229    }
230
231    @Override
232    public int hashCode() {
233        return getName().hashCode();
234    }
235
236    @Override
237    public CANBus clone() {
238        return new CANBus(getName());
239    }
240
241    /**
242     * Compares the two CAN bus names.
243     *
244     * @param other The CANBus to be compared
245     * @return The result of calling {@link String#compareTo(String)}
246     *         on the names of the two CAN buses
247     */
248    @Override
249    public int compareTo(CANBus other) {
250        return getName().compareTo(other.getName());
251    }
252}