peterschwarz / clj-serial

Simple Serial Access for Clojure
Eclipse Public License 1.0
41 stars 11 forks source link

Arduino port detection utility method (mac only) #1

Closed blakejakopovic closed 10 years ago

blakejakopovic commented 10 years ago

I wrote a method to automatically detect an Arduino port based on it's name for the dashboard server I'm working on. It likely only works for Mac, since Linux and Windows don't seem to give ports meaningful names, but it can always be expanded if that changed.

I was going to just submit a PR, but I wasn't sure where, or if you wanted to include arduino specific methods in the library.

(ns serial.util)

...

(defn- substring? [sub st]
  (not= (.indexOf st sub) -1))

(defn- arduino-port?
  "Compares port name with known arduino port formats"
  [port-name]
  (or
    (substring? "tty.usbmodem" port-name)      ;; Uno or Mega 2560
    (substring? "tty.usbserial" port-name)))   ;; Older boards

(defn detect-arduino-port
  "Returns the first arduino serial port based on port name, or nil"
  []
  (first (filter arduino-port?
                 (map #(.getName %) (port-ids)))))

# Example Usage

(defn read-board-events
  "Reads arduino serial data containing TestDrive messages"
  [port-name]
  (let [port (or port-name (detect-arduino-port) "tty.usbmodemfa1331")] 
    ...))

Also list-ports can likely be refactored (unless there is a reason to use loop) to

(defn list-ports
  "Print out the available ports. The names are printed exactly as they should be passed to open."
  []
  (doall (map #(println (.getName %)) (port-ids))))

Let me know if you'd like me to submit a PR.

peterschwarz commented 10 years ago

This is a great idea, but I think I'd rather it be in clj-firmata. clj-serial is for generic serial I/O.

It would make a handy firmata.util method.

The refactor of list-ports would be good.

blakejakopovic commented 10 years ago

Sure. I'll wait until the adapters have been factored out, and then we can add them. However, would try and group it with the serial adapter implementation, rather than firmata.util, as it is only useful with serial connections.