Ver Fonte

Updated pyserial command.py

  Found the function to obtain a list of devices which I can then use to
verify the requested device (or auto-find an Arduino) is connected.

  Also added comments to further explain what the code is doing. (In
a general sense)
david há 3 anos atrás
pai
commit
04cf06412b
1 ficheiros alterados com 31 adições e 10 exclusões
  1. 31 10
      command.py

+ 31 - 10
command.py

@@ -1,10 +1,7 @@
 #!/usr/bin/env python3
 
 from serial import Serial
-
-# Use port_listing to print out the avalible ports
-# from serial.tools.list_ports import main as port_listing
-# port_listing()
+from serial.tools.list_ports import comports as port_list
 
 from remotes import tv
 
@@ -14,6 +11,28 @@ ser = Serial(timeout=1)
 ser.baudrate = 9600
 ser.port = '/dev/ttyACM0'
 
+# Find the first Arduino we can find (Or verify the port we got is valid)
+ports_open = port_list(False)
+found = False
+for p in ports_open:
+    #print(p)
+    if ser.port == None:
+        if p.manufacturer == "Arduino (www.arduino.cc)":
+            found = True
+            ser.port = "/dev/{0}".format(p.name)
+            print("Automagically found an Arduino on port '/dev/{0}'!".format(p.name))
+            break # Stop needlessly looping over devices
+    else:
+        if '/dev/{0}'.format(p.name) == ser.port:
+            found = True
+            print("Found your Arduino!")
+            break # Stop needlessly looping over devices
+
+# Verify I have found a Arduino
+if not found:
+    raise TypeError("Device not found!")
+
+# Attempts to send the requested code
 def send_code(ky):
     if ky in tv:
         msg = "0x{0},{1},1\n".format(tv[ky], tv["_config"]["size"])
@@ -22,18 +41,20 @@ def send_code(ky):
     else:
         print("Invalid key")
 
+# Ok we are ready to actually open the Serial port
 ser.open()
 print("Opened!")
-connect_t = 0
-while ser.is_open:
-    line = ser.readline().decode().strip("\n").strip("\r")
-    if line != "":
+connect_t = 0 # Aproximately how many itterations we have done (Aprox. 1 second, due to timeout)
+while ser.is_open: # While the connection is open
+    line = ser.readline().decode().strip("\n").strip("\r") # Attempt to read a line
+    if line != "": # If there is a line Pretty Print it to the screen
         pprint(line)
+    # Based on the itteration thru send some code
     if connect_t == 6:
         send_code('power')
     elif connect_t == 18:
         send_code('power')
-    elif connect_t == 30:
+    elif connect_t == 30: # Ok we are done testing let's quit
         ser.close()
         print("Closed!")
-    connect_t += 1 # About 1 every second
+    connect_t += 1 # About 1 every second (or when ever the timeout occurs