{"id":353,"date":"2020-12-13T11:06:49","date_gmt":"2020-12-13T15:06:49","guid":{"rendered":"http:\/\/blog.labhackers.com\/?p=353"},"modified":"2020-12-21T12:20:09","modified_gmt":"2020-12-21T16:20:09","slug":"detecting-labhackers-serial-port-addresses-using-python-2","status":"publish","type":"post","link":"https:\/\/blog.labhackers.com\/?p=353","title":{"rendered":"Detecting LabHackers\u2019 Serial Port Addresses using Python"},"content":{"rendered":"\n<p><sub><sup>First posted February 26, 2019<\/sup><\/sub><\/p>\n\n\n\n<p>LabHackers\u2019 MilliKey and USB2TTL8 devices have a USB Serial interface that is assigned a unique address by the operating system the first time the device is connected to a computer. The LabHackers\u2019 Device Manager application can be used to view the serial port address assigned to a device.<\/p>\n\n\n\n<p>However, the same LabHackers\u2019 device will likely be assigned a different serial port address when it is connected to a different computer, so it is also useful to be able to identify LabHackers\u2019 device serial port addresses from within your Python script.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Finding all Serial Ports<\/h2>\n\n\n\n<p>If we want to connect to a LabHackers\u2019 device USB Serial interface, but do not know the device\u2019s serial port address, the first thing we need to do is find it.<\/p>\n\n\n\n<p>Lets start by finding the serial port address for all serial devices connected to the computer.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"python\" class=\"language-python\">import serial\nimport os\n\ndef get_serial_ports():\n    \"\"\"\n    Return list of serial port addresses that have be openned.\n    \"\"\"\n    if os.name == 'nt':  # Windows\n        available = []\n        for i in range(1, 512):\n            try:\n                sport = 'COM%d'%(i)\n                s = serial.Serial(sport, baudrate=128000)\n                available.append(sport)\n                s.close()\n            except (serial.SerialException, ValueError):\n                pass\n        return available\n    else:  # macOS and Linux\n        from serial.tools import list_ports\n        return [port[0] for port in list_ports.comports()]<\/code><\/pre>\n\n\n\n<p>get_serial_ports() returns a list of&nbsp;<strong>all&nbsp;<\/strong>serial port addresses on the computer that have a device connected to them. For example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"python\" class=\"language-python\">serial_ports = get_serial_ports()\nprint(serial_ports)<\/code><\/pre>\n\n\n\n<p>run on a Windows computer with two connected serial ports, will return something like:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code class=\"\"> ['COM2', 'COM9']<\/code><\/pre>\n\n\n\n<p><strong>Note:&nbsp;<\/strong>get_serial_ports() returns&nbsp;<em>all&nbsp;<\/em>the serial devices connected to the computer.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Detecting LabHackers\u2019 device Serial ports<\/h2>\n\n\n\n<p>Next we need to find which, if any, of the serial addresses are connected to a LabHackers\u2019 MilliKey or USB2TTL8 device. Building on get_serial_ports() , we can get a list of the LabHackers\u2019 ports by checking the responds of each serial port when \u201cPING\\n\u201d is sent.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"python\" class=\"language-python\">def get_labhackers_ports():\n    \"\"\"\n    Return list of connected LabHackers' device serial port addresses.\n    \"\"\"\n    devices = []\n    for p in get_serial_ports():\n        s = serial.Serial(p, baudrate=128000, timeout=0.1)\n        s.write(b\"PING\\n\")\n        rx = s.readline()\n        if rx:\n            rx = str(rx)\n            if rx.find('MilliKey')>=0 or rx.find('USB2TTL8')>=0:\n                devices.append(p)\n        s.close()\n    return devices<\/code><\/pre>\n\n\n\n<p>For example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"python\" class=\"language-python\">labhacker_ports = get_labhackers_ports()\nprint(labhacker_ports)<\/code><\/pre>\n\n\n\n<p>run on a Windows computer with one LabHackers\u2019 device connected will return one serial port address:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code class=\"\">['COM9']<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Putting it together<\/h2>\n\n\n\n<p>Here is a complete version of the code.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"python\" class=\"language-python\">#!\/usr\/bin\/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import print_function\n\nimport serial\nimport os\n\ndef get_serial_ports():\n    \"\"\"\n    Return list of serial port addresses that have be openned.\n    \"\"\"\n    if os.name == 'nt':  # Windows\n        available = []\n        for i in range(1, 512):\n            try:\n                sport = 'COM%d'%(i)\n                s = serial.Serial(sport, baudrate=128000)\n                available.append(sport)\n                s.close()\n            except (serial.SerialException, ValueError):\n                pass\n        return available\n    else:  # macOS and Linux\n        from serial.tools import list_ports\n        return [port[0] for port in list_ports.comports()]\n\ndef get_labhackers_ports():\n    \"\"\"\n    Return list of connected LabHackers' device serial port addresses.\n    \"\"\"\n    devices = []\n    for p in get_serial_ports():\n        s = serial.Serial(p, baudrate=128000, timeout=0.1)\n        s.write(b\"PING\\n\")\n        rx = s.readline()\n        if rx:\n            rx = str(rx)\n            if rx.find('MilliKey')&gt;=0 or rx.find('USB2TTL8')&gt;=0:\n                devices.append(p)\n        s.close()\n    return devices\n\nif __name__ == '__main__':\n    print(get_labhackers_ports())<\/code><\/pre>\n\n\n\n<p>Happy Hacking!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>First posted February 26, 2019 LabHackers\u2019 MilliKey and USB2TTL8 devices have a USB Serial interface that is assigned a unique address by the operating system the first time the device is connected to a computer. The LabHackers\u2019 Device Manager application can be used to view the serial port address assigned to a device. However, the&hellip; <a class=\"more-link\" href=\"https:\/\/blog.labhackers.com\/?p=353\">Continue reading <span class=\"screen-reader-text\">Detecting LabHackers\u2019 Serial Port Addresses using Python<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"spay_email":"","footnotes":""},"categories":[5,4,6],"tags":[8,10,11,9],"class_list":["post-353","post","type-post","status-publish","format-standard","hentry","category-how-to","category-millikey-response-box","category-usb2ttl8-adaptor","tag-millikey","tag-python","tag-usb-serial","tag-usb2ttl8","entry"],"jetpack_featured_media_url":"","_links":{"self":[{"href":"https:\/\/blog.labhackers.com\/index.php?rest_route=\/wp\/v2\/posts\/353","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/blog.labhackers.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blog.labhackers.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blog.labhackers.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/blog.labhackers.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=353"}],"version-history":[{"count":6,"href":"https:\/\/blog.labhackers.com\/index.php?rest_route=\/wp\/v2\/posts\/353\/revisions"}],"predecessor-version":[{"id":441,"href":"https:\/\/blog.labhackers.com\/index.php?rest_route=\/wp\/v2\/posts\/353\/revisions\/441"}],"wp:attachment":[{"href":"https:\/\/blog.labhackers.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=353"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blog.labhackers.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=353"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blog.labhackers.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=353"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}