title: Intermittently getting connect error: Function not implemented (38) when connecting with gatttool
body: <p>I'm working on a project where I need to get data from a BLE environmental sensor onto a raspberry pi and send it to a server at regular intervals. The more often I can send, the better. I found <a href="https://github.com/omron-devhub/2jciebl-bu-ble-raspberrypi/blob/master/sample_2jciebl-bu-ble.py" rel="nofollow noreferrer">a script online that works with the particular type of sensor that I'm working</a>, but it only reads the data once and doesn't update unless some device connects and disconnects to the sensor. </p>
  
  <p>So, for example, if I ran the script twice in a row it would contain the same data, but if I run the script once, then connected and disconnected from the sensor with my phone, then ran the script again, it would have new, updated data. Now, I'm trying to make this fully automated and don't want to have to keep connecting and disconnecting with my phone every time to get new data, so I've found that running gatttool and connecting has the same effect as if I were to connect and disconnect with my phone. So I've come up with a somewhat clunky solution of automation that all runs through crontab:</p>
  
  <ol>
  <li>Run a script that connects and immediately disconnects from the sensor using gatttool</li>
  <li>Run the data-collection script and send the data to the server</li>
  <li>Repeat as soon as possible</li>
  </ol>
  
  <p>Step 3 is where the issue lies. I can't run this series as often as I want. The ideal interval is to collect and send data every 30 seconds, but for some reason I intermittently get an error from gatttool: </p>
  
  <pre><code>connect error: Function not implemented (38)
  </code></pre>
  
  <p>I get this error on every iteration of the cron schedule until I set the interval so that the scripts only run every <em>2 minutes</em>, and even then I'm intermittently getting the error. I need the data to be consistent and definitely not as sparse as 2 minutes apart. 1 minute would be the absolute max interval I can afford to have the data sent. </p>
  
  <p>How can I get rid of this error?</p>
  
  <p>My script to connect and disconnect from the device: </p>
  
  <pre><code>import pexpect
  import time
  
  print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
  
  scan = pexpect.spawn("sudo hcitool lescan")
  time.sleep(5)
  print(scan.terminate())
  
  child = pexpect.spawn("sudo gatttool -i hci0 -b E2:D8:9D:FF:72:A2 -I -t random")
  child.sendline("connect")
  
  child.expect("Connection successful", timeout=7)
  print("connected!")
  
  
  child.sendline("disconnect")
  child.sendline("quit")
  
  child.sendline("sudo hciconfig hci0 down")
  child.sendline("sudo hciconfig hci0 up")
  
  print("done!")
  </code></pre>