[GIS] Connect / Disconnect GPS device via PyQGIS

gpspyqgispythonqgis

In QGIS I would like to establish a connection to my GPS device programmatically (not via button in the GPS control panel)

I found out how to get available ports with QgsGPSDetector i.e.

QgsGPSDetector.availablePorts()
[(u'localhost:2947:', u'Lokaler GPSD'), (u'\\\\.\\COM4', 'COM4:')]

and how to get information via QgsGPSConnection to a connected device (cp. Accessing GPS from QGIS 2.14.1/Python 2.7 /Windows10).

Via

connectionRegistry = QgsGPSConnectionRegistry().instance()
connectionList = connectionRegistry.connectionList()

i can do

connectionList[0].close() rp. .connect()

But if no device is initially connected via the GPS control panel, the .connectionList() return nothing, so I'm not shure how to connect / disconnect to a GPS device.

ADD/EDIT

tried

con = QgsGpsdConnection('localhost',2947,'local gpsd')
# or con = QgsGpsdConnection('localhost',2947,''), rsp.
con.connect()
>>> True
con.status()
>>> 1
cr = QgsGPSConnectionRegistry().instance()
cr.connectionList()
>>> []

I'd like to try this 'COM4', but the port parameter is an integer.

Connecting via GPS Information panel does not work with gpsd, only Autodetect and serial (COM4:):

enter image description here

Do I have to construct a QgsGPSConnection that i can

.connect()

and

.close()

?

Best Answer

As indicated in qgis api documentation (https://qgis.org/api/classQgsNMEAConnection.html) the third parameter of the constructor is the device. It's the string you put in the "Device" field of the GPS pane. In the case you have only one device on your gpsd, you can keep it empty.

So, you should try:

d = QgsGPSDetector("COM4")
def _connected(c):
  global con
  con = c
d.detected.connect(_connected)
d.advance()

(sorry for the ugly signal interception, there is no method exposed to get the connection object)

If you are using GPSD, update the first line to:

d = QgsGPSDetector("localhost:2947:")

But when you call con.status() you should get 3.

Here is the values table:

  • Connected = 1
  • DataReceived = 2
  • GPSDataReceived = 3
  • NotConnected = 0

If the value is 3, you can then query values!

Here is a sample:

>>> d = QgsGPSDetector("COM4")
>>> def _connected(c):
...   global con
...   con = c
>>> d.detected.connect(_connected)
>>> d.advance()
>>> con.status()
3
>>> con.currentGPSInformation().latitude
55.67122833333333
>>> con.currentGPSInformation().longitude
12.521531666666666

Here is the field list: https://qgis.org/api/structQgsGPSInformation.html

Related Question