Added gain patch and setup.py #1

Closed
wants to merge 3 commits into
from
View
@@ -11,6 +11,9 @@
has_numpy = False
class BaseRtlSdr(object):
+ #Gain values in tenths of a dB
+ GAIN_VALUES = [-10, 15, 40, 65, 90, 115, 140, 165, 190, \
+ 215, 240, 290, 340, 420, 430, 450, 470, 490]
DEFAULT_GAIN = 1
DEFAULT_FC = 80e6
DEFAULT_RS = 1e6
@@ -40,6 +43,7 @@ def __init__(self, device_index=0):
# set default state
self.set_sample_rate(self.DEFAULT_RS)
self.set_center_freq(self.DEFAULT_FC)
+ self.manual_gain_mode = False
self.set_gain(self.DEFAULT_GAIN)
def close(self):
@@ -75,6 +79,21 @@ def get_center_freq(self):
center_freq = round(reported_center_freq, -3)
return center_freq
+
+ def get_gain_mode(self):
+ return self.manual_gain_mode
+
+ def set_gain_mode(self, manual):
+ manual = int(manual)
+
+ result = librtlsdr.rtlsdr_set_tuner_gain_mode(self.dev_p, manual)
+ if result < 0:
+ self.close()
+ raise IOError('Error code %d when setting gain mode rate to %d'\
+ % (result, manual))
+
+ self.manual_gain_mode = manual != 0
+ return
def set_sample_rate(self, rate):
rate = int(rate)
@@ -103,7 +122,10 @@ def get_sample_rate(self):
return real_rate
def set_gain(self, gain):
- gain = int(gain)
+ gain = self.GAIN_VALUES[int(gain)]
+
+ if not self.manual_gain_mode:
+ self.set_gain_mode(True)
result = librtlsdr.rtlsdr_set_tuner_gain(self.dev_p, gain)
if result < 0:
@@ -180,6 +202,7 @@ def packed_bytes_to_iq(self, bytes):
center_freq = fc = property(get_center_freq, set_center_freq)
sample_rate = rs = property(get_sample_rate, set_sample_rate)
+ manual_gain = property(get_gain_mode, set_gain_mode)
gain = property(get_gain, set_gain)
# This adds async read support to base class BaseRtlSdr (don't use that one)
View
218 setup.py
@@ -0,0 +1,218 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+""" distribute- and pip-enabled setup.py """
+
+import logging
+import os
+import re
+
+# ----- overrides -----
+
+# set these to anything but None to override the automatic defaults
+packages = None
+package_name = None
+package_data = None
+scripts = None
+requirements_file = None
+requirements = None
+dependency_links = None
+
+# ---------------------
+
+
+# ----- control flags -----
+
+# fallback to setuptools if distribute isn't found
+setup_tools_fallback = False
+
+# don't include subdir named 'tests' in package_data
+skip_tests = True
+
+# print some extra debugging info
+debug = True
+
+# -------------------------
+
+if debug:
+ logging.basicConfig(level=logging.DEBUG)
+# distribute import and testing
+try:
+ import distribute_setup
+ distribute_setup.use_setuptools()
+ logging.debug("distribute_setup.py imported and used")
+except ImportError:
+ # fallback to setuptools?
+ # distribute_setup.py was not in this directory
+ if not (setup_tools_fallback):
+ import setuptools
+ if not (hasattr(setuptools, '_distribute') and \
+ setuptools._distribute):
+ raise ImportError(\
+ "distribute was not found and fallback " \
+ "to setuptools was not allowed")
+ else:
+ logging.debug("distribute_setup.py not found, \
+ defaulted to system distribute")
+ else:
+ logging.debug("distribute_setup.py not found, " \
+ "defaulting to system setuptools")
+
+import setuptools
+
+
+def find_scripts():
+ return [s for s in setuptools.findall('scripts/') \
+ if os.path.splitext(s)[1] != '.pyc']
+
+
+def package_to_path(package):
+ """
+ Convert a package (as found by setuptools.find_packages)
+ e.g. "foo.bar" to usable path
+ e.g. "foo/bar"
+
+ No idea if this works on windows
+ """
+ return package.replace('.', '/')
+
+
+def find_subdirectories(package):
+ """
+ Get the subdirectories within a package
+ This will include resources (non-submodules) and submodules
+ """
+ try:
+ subdirectories = os.walk(package_to_path(package)).next()[1]
+ except StopIteration:
+ subdirectories = []
+ return subdirectories
+
+
+def subdir_findall(dir, subdir):
+ """
+ Find all files in a subdirectory and return paths relative to dir
+
+ This is similar to (and uses) setuptools.findall
+ However, the paths returned are in the form needed for package_data
+ """
+ strip_n = len(dir.split('/'))
+ path = '/'.join((dir, subdir))
+ return ['/'.join(s.split('/')[strip_n:]) for s in setuptools.findall(path)]
+
+
+def find_package_data(packages):
+ """
+ For a list of packages, find the package_data
+
+ This function scans the subdirectories of a package and considers all
+ non-submodule subdirectories as resources, including them in
+ the package_data
+
+ Returns a dictionary suitable for setup(package_data=<result>)
+ """
+ package_data = {}
+ for package in packages:
+ package_data[package] = []
+ for subdir in find_subdirectories(package):
+ if '.'.join((package, subdir)) in packages: # skip submodules
+ logging.debug("skipping submodule %s/%s" % (package, subdir))
+ continue
+ if skip_tests and (subdir == 'tests'): # skip tests
+ logging.debug("skipping tests %s/%s" % (package, subdir))
+ continue
+ package_data[package] += \
+ subdir_findall(package_to_path(package), subdir)
+ return package_data
+
+
+def parse_requirements(file_name):
+ """
+ from:
+ http://cburgmer.posterous.com/pip-requirementstxt-and-setuppy
+ """
+ requirements = []
+ with open(file_name, 'r') as f:
+ for line in f:
+ if re.match(r'(\s*#)|(\s*$)', line):
+ continue
+ if re.match(r'\s*-e\s+', line):
+ requirements.append(re.sub(r'\s*-e\s+.*#egg=(.*)$',\
+ r'\1', line).strip())
+ elif re.match(r'\s*-f\s+', line):
+ pass
+ else:
+ requirements.append(line.strip())
+ return requirements
+
+
+def parse_dependency_links(file_name):
+ """
+ from:
+ http://cburgmer.posterous.com/pip-requirementstxt-and-setuppy
+ """
+ dependency_links = []
+ with open(file_name) as f:
+ for line in f:
+ if re.match(r'\s*-[ef]\s+', line):
+ dependency_links.append(re.sub(r'\s*-[ef]\s+',\
+ '', line))
+ return dependency_links
+
+# ----------- Override defaults here ----------------
+if packages is None:
+ packages = setuptools.find_packages()
+
+if len(packages) == 0:
+ raise Exception("No valid packages found")
+
+if package_name is None:
+ package_name = packages[0]
+
+if package_data is None:
+ package_data = find_package_data(packages)
+
+if scripts is None:
+ scripts = find_scripts()
+
+if requirements_file is None:
+ requirements_file = 'requirements.txt'
+
+if os.path.exists(requirements_file):
+ if requirements is None:
+ requirements = parse_requirements(requirements_file)
+ if dependency_links is None:
+ dependency_links = parse_dependency_links(requirements_file)
+else:
+ if requirements is None:
+ requirements = []
+ if dependency_links is None:
+ dependency_links = []
+
+if debug:
+ logging.debug("Module name: %s" % package_name)
+ for package in packages:
+ logging.debug("Package: %s" % package)
+ logging.debug("\tData: %s" % str(package_data[package]))
+ logging.debug("Scripts:")
+ for script in scripts:
+ logging.debug("\tScript: %s" % script)
+ logging.debug("Requirements:")
+ for req in requirements:
+ logging.debug("\t%s" % req)
+ logging.debug("Dependency links:")
+ for dl in dependency_links:
+ logging.debug("\t%s" % dl)
+
+setuptools.setup(
+ name=package_name,
+ version='dev',
+ packages=packages,
+ scripts=scripts,
+
+ package_data=package_data,
+ include_package_data=True,
+
+ install_requires=requirements,
+ dependency_links=dependency_links
+)
View
30 test.py
@@ -1,43 +1,45 @@
from __future__ import division
from rtlsdr import *
+
@limit_calls(2)
def test_callback(samples, rtlsdr_obj):
print ' in callback'
- print ' signal mean:', sum(samples)/len(samples)
+ print ' signal mean:', sum(samples) / len(samples)
+
-def main():
+def main():
sdr = RtlSdr()
-
+
print 'Configuring SDR...'
sdr.rs = 2e6
sdr.fc = 70e6
sdr.gain = 5
- print ' sample rate: %0.6f MHz' % (sdr.rs/1e6)
- print ' center frequency %0.6f MHz' % (sdr.fc/1e6)
+ print ' sample rate: %0.6f MHz' % (sdr.rs / 1e6)
+ print ' center frequency %0.6f MHz' % (sdr.fc / 1e6)
print ' gain: %d dB' % sdr.gain
- print 'Reading samples...'
+ print 'Reading samples...'
samples = sdr.read_samples(1024)
- print ' signal mean:', sum(samples)/len(samples)
-
+ print ' signal mean:', sum(samples) / len(samples)
+
print 'Testing callback...'
sdr.read_samples_async(test_callback, 1024)
-
+
try:
import pylab as mpl
-
+
print 'Testing spectrum plotting...'
mpl.figure()
- mpl.psd(samples, Fc=sdr.fc/1e6, Fs=sdr.rs/1e6)
-
+ mpl.psd(samples, Fc=sdr.fc / 1e6, Fs=sdr.rs / 1e6)
+
mpl.show()
except:
# matplotlib not installed/working
pass
-
+
print 'Done\n'
sdr.close()
if __name__ == '__main__':
- main()
+ main()