nanovna-saver/src/NanoVNASaver/Hardware/NanoVNA.py

156 wiersze
5.5 KiB
Python
Czysty Zwykły widok Historia

# NanoVNASaver
2020-06-25 17:52:30 +00:00
#
# A python program to view and export Touchstone data from a NanoVNA
2020-06-25 17:52:30 +00:00
# Copyright (C) 2019, 2020 Rune B. Broberg
2021-06-30 05:21:14 +00:00
# Copyright (C) 2020,2021 NanoVNA-Saver Authors
2020-05-16 15:10:07 +00:00
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
import logging
import struct
from typing import List
2020-05-16 15:10:07 +00:00
import serial
import numpy as np
from PyQt5 import QtGui
2020-05-16 15:10:07 +00:00
from NanoVNASaver.Hardware.Serial import drain_serial, Interface
2020-07-25 18:10:24 +00:00
from NanoVNASaver.Hardware.VNA import VNA
from NanoVNASaver.Version import Version
2020-05-16 15:10:07 +00:00
logger = logging.getLogger(__name__)
2020-05-16 15:10:07 +00:00
class NanoVNA(VNA):
name = "NanoVNA"
screenwidth = 320
screenheight = 240
def __init__(self, iface: Interface):
super().__init__(iface)
self.sweep_method = "sweep"
2020-07-11 13:58:30 +00:00
self.read_features()
2020-12-23 15:15:08 +00:00
logger.debug("Setting initial start,stop")
self.start, self.stop = self._get_running_frequencies()
self.sweep_max_freq_Hz = 300e6
self._sweepdata = []
2020-05-16 15:10:07 +00:00
2020-12-23 15:15:08 +00:00
def _get_running_frequencies(self):
2021-01-08 19:00:43 +00:00
logger.debug("Reading values: frequencies")
try:
frequencies = super().readValues("frequencies")
return frequencies[0], frequencies[-1]
except Exception as e:
logger.warning("%s reading frequencies", e)
logger.info("falling back to generic")
2020-12-23 15:15:08 +00:00
return VNA._get_running_frequencies(self)
2020-07-04 11:10:29 +00:00
def _capture_data(self) -> bytes:
2020-07-07 14:48:43 +00:00
timeout = self.serial.timeout
with self.serial.lock:
2020-07-04 11:10:29 +00:00
drain_serial(self.serial)
2023-03-08 08:40:39 +00:00
self.serial.write("capture\r".encode("ascii"))
2020-07-04 11:10:29 +00:00
self.serial.readline()
2020-07-07 14:48:43 +00:00
self.serial.timeout = 4
2020-07-04 11:10:29 +00:00
image_data = self.serial.read(
2023-03-08 08:40:39 +00:00
self.screenwidth * self.screenheight * 2
)
2020-07-04 11:10:29 +00:00
self.serial.timeout = timeout
2020-07-07 14:48:43 +00:00
self.serial.timeout = timeout
return image_data
def _convert_data(self, image_data: bytes) -> bytes:
2020-07-04 11:10:29 +00:00
rgb_data = struct.unpack(
2023-03-08 08:40:39 +00:00
f">{self.screenwidth * self.screenheight}H", image_data
)
2020-07-04 11:10:29 +00:00
rgb_array = np.array(rgb_data, dtype=np.uint32)
2023-03-08 08:40:39 +00:00
return (
0xFF000000
+ ((rgb_array & 0xF800) << 8)
+ ((rgb_array & 0x07E0) << 5)
+ ((rgb_array & 0x001F) << 3)
)
2020-05-16 15:10:07 +00:00
def getScreenshot(self) -> QtGui.QPixmap:
logger.debug("Capturing screenshot...")
2020-07-05 11:00:03 +00:00
if not self.connected():
2020-05-16 15:10:07 +00:00
return QtGui.QPixmap()
2020-07-01 17:46:35 +00:00
try:
rgba_array = self._convert_data(self._capture_data())
2020-07-01 17:46:35 +00:00
image = QtGui.QImage(
rgba_array,
self.screenwidth,
self.screenheight,
2023-03-08 08:40:39 +00:00
QtGui.QImage.Format_ARGB32,
)
2020-07-01 17:46:35 +00:00
logger.debug("Captured screenshot")
return QtGui.QPixmap(image)
except serial.SerialException as exc:
2023-03-08 08:40:39 +00:00
logger.exception("Exception while capturing screenshot: %s", exc)
2020-05-16 15:10:07 +00:00
return QtGui.QPixmap()
def resetSweep(self, start: int, stop: int):
2020-07-07 14:48:43 +00:00
list(self.exec_command(f"sweep {start} {stop} {self.datapoints}"))
2020-07-07 14:50:59 +00:00
list(self.exec_command("resume"))
2020-05-16 15:10:07 +00:00
def setSweep(self, start, stop):
self.start = start
self.stop = stop
if self.sweep_method == "sweep":
2020-07-07 14:48:43 +00:00
list(self.exec_command(f"sweep {start} {stop} {self.datapoints}"))
elif self.sweep_method == "scan":
2020-07-07 14:48:43 +00:00
list(self.exec_command(f"scan {start} {stop} {self.datapoints}"))
2020-07-07 10:33:32 +00:00
def read_features(self):
2020-07-08 13:45:33 +00:00
super().read_features()
2020-07-07 10:33:32 +00:00
if self.version >= Version("0.7.1"):
2020-07-11 13:58:30 +00:00
logger.debug("Using scan mask command.")
2020-07-07 10:33:32 +00:00
self.features.add("Scan mask command")
self.sweep_method = "scan_mask"
elif self.version >= Version("0.2.0"):
2020-07-11 13:58:30 +00:00
logger.debug("Using new scan command.")
2020-07-07 10:33:32 +00:00
self.features.add("Scan command")
self.sweep_method = "scan"
def readFrequencies(self) -> List[int]:
2020-07-11 13:58:30 +00:00
logger.debug("readFrequencies: %s", self.sweep_method)
if self.sweep_method != "scan_mask":
return super().readFrequencies()
2023-03-08 08:40:39 +00:00
return [
int(line)
for line in self.exec_command(
f"scan {self.start} {self.stop} {self.datapoints} 0b001"
)
]
def readValues(self, value) -> List[str]:
if self.sweep_method != "scan_mask":
return super().readValues(value)
logger.debug("readValue with scan mask (%s)", value)
# Actually grab the data only when requesting channel 0.
# The hardware will return all channels which we will store.
if value == "data 0":
self._sweepdata = []
2020-07-07 14:48:43 +00:00
for line in self.exec_command(
2023-03-08 08:40:39 +00:00
f"scan {self.start} {self.stop} {self.datapoints} 0b110"
):
2020-07-07 14:48:43 +00:00
data = line.split()
2023-03-08 08:40:39 +00:00
self._sweepdata.append(
(f"{data[0]} {data[1]}", f"{data[2]} {data[3]}")
)
if value == "data 0":
return [x[0] for x in self._sweepdata]
if value == "data 1":
return [x[1] for x in self._sweepdata]