I recall an unfinished discussion a while back where we were thinking that chirp should have proper logging support. One thought was to have a more complete logging subsystem, e.g., thru logger module. This would be more flexible in terms of supporting various levels i.e., CRIT, WARN, INFO, DEBUG, as well as various outputs, e.g., logfile, console, etc.

It does seem to be a rather large task, as you have begun undertaking.
Thanks for taking this on Zach. This looks like a great start.


From: Zach Welch <zach@mandolincreekfarm.com>
To: chirp_devel@intrepid.danplanet.com
Sent: Monday, February 23, 2015 1:09 AM
Subject: [chirp_devel] [PATCH 3/4] Simplify and centralize debugging messages (#2343)

At its core, this patch adds a dprint function that wraps print with
a conditional on CHIRP_DEBUG.  That variable is set by the environment,
but it can also be set by a command line option (--debug) in chirp.py.
I would like to add that option to chirpw too, but that would require a
separate patch that adds proper option parsing.

The remainder of the patch involves chasing down all references to
CHIRP_DEBUG, nearly all of which were wrapping plain print statements.
I also eliminated a few plain DEBUG variables and a couple of other
one-off variants.
---
chirp.py              |  8 ++++++++
chirp/__init__.py      |  9 +++++++++
chirp/anytone.py      | 11 ++++-------
chirp/baofeng_uv3r.py  |  5 -----
chirp/bjuv55.py        |  5 -----
chirp/ft1d.py          | 12 +++++-------
chirp/ft2800.py        | 19 ++++++------------
chirp/ft60.py          |  5 ++---
chirp/ft7800.py        | 27 ++++++++------------------
chirp/ft817.py        | 28 +++++++++++----------------
chirp/ft857.py        |  7 +++----
chirp/ft90.py          | 52 +++++++++++++++++---------------------------------
chirp/ftm350.py        |  6 +++---
chirp/h777.py          | 17 ++++++-----------
chirp/icomciv.py      | 12 ++++--------
chirp/idrp.py          | 11 +++--------
chirp/kenwood_live.py  |  8 ++------
chirp/kguv8d.py        | 43 ++++++++++++++---------------------------
chirp/kyd.py          | 27 ++++++++++----------------
chirp/leixen.py        |  5 -----
chirp/puxing.py        |  5 -----
chirp/th9800.py        | 35 ++++++++++++---------------------
chirp/th_uv3r.py      |  5 -----
chirp/thd72.py        | 10 +++-------
chirp/tk8102.py        |  7 +++----
chirp/tmv71_ll.py      | 10 +++-------
chirp/uv5r.py          | 27 ++++++++------------------
chirp/vx170.py        |  5 -----
chirp/vx2.py          | 29 +++++++++-------------------
chirp/vx3.py          | 29 +++++++++-------------------
chirp/vx8.py          | 10 ++++------
chirp/wouxun.py        | 12 +++++-------
chirp/wouxun_common.py |  8 +++-----
chirp/yaesu_clone.py  | 11 ++++-------
chirpui/reporting.py  | 29 ++++++++++++----------------
35 files changed, 191 insertions(+), 358 deletions(-)

diff --git a/chirp.py b/chirp.py
index 28ed8f9..20c7f55 100755
--- a/chirp.py
+++ b/chirp.py
@@ -21,6 +21,7 @@ import sys
from optparse import OptionParser
import optparse

+import chirp;
from chirp import *
from chirp import chirp_common, errors, idrp, directory, util
from chirp import print_chirp_version
@@ -160,11 +161,18 @@ if __name__ == "__main__":
              action="store_true",
              default=False,
              help="Upload memory map to radio")
+        parser.add_option("-d", "--debug", dest="debug",
+                          action="store_true",
+                          default=False,
+                          help="Print debugging messages")
    if len(sys.argv) <= 1:
        parser.print_help()
        sys.exit(0)
    (options, args) = parser.parse_args()

+    if options.debug:
+            chirp.CHIRP_DEBUG = True
+
        if options.list_radios:
            print "Supported Radios:\n\t", "\n\t".join(sorted(RADIOS.keys()))
            sys.exit(0);
diff --git a/chirp/__init__.py b/chirp/__init__.py
index e5118d1..a706e56 100644
--- a/chirp/__init__.py
+++ b/chirp/__init__.py
@@ -32,3 +32,12 @@ def print_chirp_version():
    print "CHIRP %s on %s (Python %s)" % (CHIRP_VERSION,
              platform.get_platform().os_version_string(),
              sys.version.split()[0])
+
+# For early debug (before option parsing), set CHIRP_DEBUG in environment;
+# otherwise, use --debug option to enable debugging messages.
+CHIRP_DEBUG = os.getenv("CHIRP_DEBUG") and True or False
+
+def dprint(*args):
+    """Print a debug message if CHIRP_DEBUG is True)"""
+    if CHIRP_DEBUG:
+        print "".join(map(str,args))
diff --git a/chirp/anytone.py b/chirp/anytone.py
index 4b9c785..93aea5a 100644
--- a/chirp/anytone.py
+++ b/chirp/anytone.py
@@ -17,6 +17,7 @@ import os
import struct
import time

+from chirp import dprint
from chirp import bitwise
from chirp import chirp_common
from chirp import directory
@@ -164,10 +165,6 @@ def _should_send_addr(memobj, addr):
    else:
        return _is_loc_used(memobj, _addr_to_loc(addr))

-def _debug(string):
-    if "CHIRP_DEBUG" in os.environ or True:
-        print string
-
def _echo_write(radio, data):
    try:
        radio.pipe.write(data)
@@ -201,7 +198,7 @@ def _ident(radio):
        raise errors.RadioError("Unsupported model")
    _echo_write(radio, "\x02")
    response = radio.pipe.read(16)
-    _debug(util.hexprint(response))
+    dprint(util.hexprint(response))
    if response[1:8] not in valid_model:
        print "Response was:\n%s" % util.hexprint(response)
        raise errors.RadioError("Unsupported model")
@@ -227,7 +224,7 @@ def _send(radio, cmd, addr, length, data=None):
        frame += chr(_checksum(frame[1:]))
        frame += "\x06"
    _echo_write(radio, frame)
-    _debug("Sent:\n%s" % util.hexprint(frame))
+    dprint("Sent:\n%s" % util.hexprint(frame))
    if data:
        result = radio.pipe.read(1)
        if result != "\x06":
@@ -236,7 +233,7 @@ def _send(radio, cmd, addr, length, data=None):
                            addr)
        return
    result = _read(radio, length + 6)
-    _debug("Got:\n%s" % util.hexprint(result))
+    dprint("Got:\n%s" % util.hexprint(result))
    header = result[0:4]
    data = result[4:-2]
    ack = result[-1]
diff --git a/chirp/baofeng_uv3r.py b/chirp/baofeng_uv3r.py
index 52d1a78..0827885 100644
--- a/chirp/baofeng_uv3r.py
+++ b/chirp/baofeng_uv3r.py
@@ -24,11 +24,6 @@ from chirp.settings import RadioSetting, RadioSettingGroup, \
                RadioSettingValueInteger, RadioSettingValueString, \
                RadioSettingValueFloat, RadioSettings

-if os.getenv("CHIRP_DEBUG"):
-    DEBUG = True
-else:
-    DEBUG = False
-
def _uv3r_prep(radio):
    radio.pipe.write("\x05PROGRAM")
    ack = radio.pipe.read(1)
diff --git a/chirp/bjuv55.py b/chirp/bjuv55.py
index 7dd61be..9fb7e5a 100644
--- a/chirp/bjuv55.py
+++ b/chirp/bjuv55.py
@@ -28,11 +28,6 @@ from chirp.settings import RadioSetting, RadioSettingGroup, \
from textwrap import dedent
from chirp import uv5r

-if os.getenv("CHIRP_DEBUG"):
-    CHIRP_DEBUG = True
-else:
-    CHIRP_DEBUG = False
-
BJUV55_MODEL  = "\x50\xBB\xDD\x55\x63\x98\x4D"

COLOR_LIST = ["Off", "Blue", "Red", "Pink"]
diff --git a/chirp/ft1d.py b/chirp/ft1d.py
index eb7a0b1..39472df 100644
--- a/chirp/ft1d.py
+++ b/chirp/ft1d.py
@@ -19,7 +19,7 @@ import re
import string

from chirp import chirp_common, yaesu_clone, directory
-from chirp import bitwise
+from chirp import bitwise, dprint
from chirp.settings import RadioSettingGroup, RadioSetting, RadioSettings
from chirp.settings import RadioSettingValueInteger, RadioSettingValueString
from chirp.settings import RadioSettingValueList, RadioSettingValueBoolean
@@ -1549,8 +1549,7 @@ class FT1Radio(yaesu_clone.YaesuCloneModeRadio):
        is_latitude = name.endswith("latitude")
        lat_long = setting.value.get_value().strip()
        sign, l_d, l_m, l_s = cls._str_to_latlong(lat_long, is_latitude)
-        if os.getenv("CHIRP_DEBUG"):
-            print "%s: %d %d %d %d" % (name, sign, l_d, l_m, l_s)
+        dprint("%s: %d %d %d %d" % (name, sign, l_d, l_m, l_s))
        setattr(obj, "%s_sign" % name, sign)
        setattr(obj, "%s_degree" % name, l_d)
        setattr(obj, "%s_minute" % name, l_m)
@@ -1587,9 +1586,8 @@ class FT1Radio(yaesu_clone.YaesuCloneModeRadio):

                try:
                    old_val = getattr(obj, setting)
-                    if os.getenv("CHIRP_DEBUG"):
-                        print "Setting %s(%r) <= %s" % (
-                            element.get_name(), old_val, element.value)
+                    dprint("Setting %s(%r) <= %s" % (
+                            element.get_name(), old_val, element.value))
                    setattr(obj, setting, element.value)
                except AttributeError as e:
                    print "Setting %s is not in the memory map: %s" % (
@@ -1623,4 +1621,4 @@ class FT1Radio(yaesu_clone.YaesuCloneModeRadio):
        val = [FT1_DTMF_CHARS.index(x) for x in rawval]
        for x in range(len(val), 16):
            val.append(0xFF)
-        cls._memobj.dtmf[i].memory = val
\ No newline at end of file
+        cls._memobj.dtmf[i].memory = val
diff --git a/chirp/ft2800.py b/chirp/ft2800.py
index fb9d10c..645a240 100644
--- a/chirp/ft2800.py
+++ b/chirp/ft2800.py
@@ -16,11 +16,9 @@
import time
import os

-from chirp import util, memmap, chirp_common, bitwise, directory, errors
+from chirp import util, memmap, chirp_common, bitwise, directory, errors, dprint
from chirp.yaesu_clone import YaesuCloneModeRadio

-DEBUG = os.getenv("CHIRP_DEBUG") and True or False
-
CHUNK_SIZE = 16
def _send(s, data):
    for i in range(0, len(data), CHUNK_SIZE):
@@ -41,8 +39,7 @@ def _download(radio):
        if data == IDBLOCK:
            break

-    if DEBUG:
-        print "Header:\n%s" % util.hexprint(data)
+    dprint("Header:\n%s" % util.hexprint(data))

    if len(data) != 8:
        raise Exception("Failed to read header")
@@ -54,8 +51,7 @@ def _download(radio):
    while len(data) < radio._block_sizes[1]:
        time.sleep(0.1)
        chunk = radio.pipe.read(38)
-        if DEBUG:
-            print "Got: %i:\n%s" % (len(chunk), util.hexprint(chunk))
+        dprint("Got: %i:\n%s" % (len(chunk), util.hexprint(chunk)))
        if len(chunk) == 8:
            print "END?"
        elif len(chunk) != 38:
@@ -79,8 +75,7 @@ def _download(radio):
            status.msg = "Cloning from radio"
            radio.status_fn(status)

-    if DEBUG:
-        print "Total: %i" % len(data)
+    dprint("Total: %i" % len(data))

    return memmap.MemoryMap(data)

@@ -94,8 +89,7 @@ def _upload(radio):
    _send(radio.pipe, IDBLOCK)
    time.sleep(1)
    ack = radio.pipe.read(300)
-    if DEBUG:
-        print "Ack was (%i):\n%s" % (len(ack), util.hexprint(ack))
+    dprint("Ack was (%i):\n%s" % (len(ack), util.hexprint(ack)))
    if ack != ACK:
        raise Exception("Radio did not ack ID")

@@ -108,8 +102,7 @@ def _upload(radio):
            cs += ord(byte)
        data += chr(cs & 0xFF)

-        if DEBUG:
-            print "Writing block %i:\n%s" % (block, util.hexprint(data))
+        dprint("Writing block %i:\n%s" % (block, util.hexprint(data)))

        _send(radio.pipe, data)
        time.sleep(0.1)
diff --git a/chirp/ft60.py b/chirp/ft60.py
index 45c92d0..d8cc428 100644
--- a/chirp/ft60.py
+++ b/chirp/ft60.py
@@ -15,7 +15,7 @@

import time, os
from chirp import chirp_common, yaesu_clone, memmap, bitwise, directory
-from chirp import errors
+from chirp import errors, dprint
from chirp.settings import RadioSetting, RadioSettingGroup, \
    RadioSettingValueInteger, RadioSettingValueList, \
    RadioSettingValueBoolean, RadioSettingValueString, \
@@ -617,8 +617,7 @@ class FT60Radio(yaesu_clone.YaesuCloneModeRadio):
                    obj = getattr(_settings, name)
                    setattr(_settings, name, value)

-                if os.getenv("CHIRP_DEBUG"):
-                    print "Setting %s: %s" % (name, value)
+                dprint("Setting %s: %s" % (name, value))
            except Exception, e:
                print element.get_name()
                raise
diff --git a/chirp/ft7800.py b/chirp/ft7800.py
index 451fb08..7a48066 100644
--- a/chirp/ft7800.py
+++ b/chirp/ft7800.py
@@ -15,7 +15,7 @@

import time
from chirp import chirp_common, yaesu_clone, memmap, directory
-from chirp import bitwise, errors
+from chirp import bitwise, errors, dprint
from textwrap import dedent
from chirp.settings import RadioSetting, RadioSettingGroup, \
    RadioSettingValueInteger, RadioSettingValueList, \
@@ -25,11 +25,6 @@ import os, re

from collections import defaultdict

-if os.getenv("CHIRP_DEBUG"):
-    CHIRP_DEBUG = True
-else:
-    CHIRP_DEBUG = False
-
ACK = chr(0x06)

MEM_FORMAT = """
@@ -540,9 +535,8 @@ class FT7800Radio(FTx800Radio):
        FTx800Radio.set_memory(self, memory)

    def _decode_chars(self, inarr):
-        if CHIRP_DEBUG:
-            print "@_decode_chars, type: %s" % type(inarr)
-            print inarr
+        dprint("@_decode_chars, type: %s" % type(inarr))
+        dprint(inarr)
        outstr = ""
        for i in inarr:
            if i == 0xFF:
@@ -551,9 +545,8 @@ class FT7800Radio(FTx800Radio):
        return outstr.rstrip()
           
    def _encode_chars(self, instr, length = 16):
-        if CHIRP_DEBUG:
-            print "@_encode_chars, type: %s" % type(instr)
-            print instr
+        dprint("@_encode_chars, type: %s" % type(instr))
+        dprint(instr)
        outarr = []
        instr = str(instr)
        for i in range(length):
@@ -647,8 +640,7 @@ class FT7800Radio(FTx800Radio):
                    break
                if c < len(DTMFCHARSET):
                    dtmfstr += DTMFCHARSET[c]
-            if CHIRP_DEBUG:
-                print dtmfstr
+            dprint(dtmfstr)
            dtmfentry = RadioSettingValueString(0, 16, dtmfstr)
            dtmfentry.set_charset(DTMFCHARSET + list(" "))
            rs = RadioSetting(name, name.upper(), dtmfentry)
@@ -721,8 +713,7 @@ class FT7800Radio(FTx800Radio):
                            newval.append(DTMFCHARSET.index(dtmfstr[i]))
                        else:
                            newval.append(0xFF)
-                    if CHIRP_DEBUG:
-                        print newval
+                    dprint(newval)
                    idx = int(setting[-2:])
                    _settings = self._memobj.dtmf[idx]
                    _settings.memory = newval
@@ -735,9 +726,7 @@ class FT7800Radio(FTx800Radio):
                # normal settings
                newval = element.value
                oldval = getattr(_settings, setting)
-                if CHIRP_DEBUG:
-                    print "Setting %s(%s) <= %s" % (setting,
-                                    oldval, newval)
+                dprint("Setting %s(%s) <= %s" % (setting, oldval, newval))
                setattr(_settings, setting, newval)
            except Exception, e:
                print element.get_name()
diff --git a/chirp/ft817.py b/chirp/ft817.py
index 8950f73..de98c31 100644
--- a/chirp/ft817.py
+++ b/chirp/ft817.py
@@ -17,7 +17,7 @@
"""FT817 - FT817ND - FT817ND/US management module"""

from chirp import chirp_common, yaesu_clone, util, memmap, errors, directory
-from chirp import bitwise
+from chirp import bitwise, dprint
from chirp.settings import RadioSetting, RadioSettingGroup, \
    RadioSettingValueInteger, RadioSettingValueList, \
    RadioSettingValueBoolean, RadioSettingValueString, \
@@ -319,8 +319,7 @@ class FT817Radio(yaesu_clone.YaesuCloneModeRadio):
                raise Exception("Unable to read block %02X expected %i got %i" %
                                (blocknum, block + 2, len(data)))

-        if os.getenv("CHIRP_DEBUG"):
-            print "Read %i" % len(data)
+        dprint("Read %i" % len(data))
        return data

    def _clone_in(self):
@@ -382,15 +381,12 @@ class FT817Radio(yaesu_clone.YaesuCloneModeRadio):
            for _i in range(0, repeat):
                time.sleep(0.01)
                checksum = yaesu_clone.YaesuChecksum(pos, pos + block - 1)
-                if os.getenv("CHIRP_DEBUG"):
-                    print "Block %i - will send from %i to %i byte " % \
-                        (blocks,
-                        pos,
-                        pos + block)
-                    print util.hexprint(chr(blocks))
-                    print util.hexprint(self.get_mmap()[pos:pos + block])
-                    print util.hexprint(chr(checksum.get_calculated(
-                                self.get_mmap())))
+                dprint("Block %i - will send from %i to %i byte " % \
+                        (blocks, pos, pos + block))
+                dprint(util.hexprint(chr(blocks)))
+                dprint(util.hexprint(self.get_mmap()[pos:pos + block]))
+                dprint(util.hexprint(chr(checksum.get_calculated(
+                            self.get_mmap()))))
                self.pipe.write(chr(blocks))
                self.pipe.write(self.get_mmap()[pos:pos + block])
                self.pipe.write(chr(checksum.get_calculated(self.get_mmap())))
@@ -399,8 +395,7 @@ class FT817Radio(yaesu_clone.YaesuCloneModeRadio):
                    time.sleep(delay)
                    buf = self.pipe.read(1)
                if not buf or buf[0] != chr(CMD_ACK):
-                    if os.getenv("CHIRP_DEBUG"):
-                        print util.hexprint(buf)
+                    dprint(util.hexprint(buf))
                    raise Exception(_("Radio did not ack block %i") % blocks)
                pos += block
                blocks += 1
@@ -1030,9 +1025,8 @@ class FT817Radio(yaesu_clone.YaesuCloneModeRadio):
                else:
                    obj = _settings
                    setting = element.get_name()
-                if os.getenv("CHIRP_DEBUG"):
-                    print "Setting %s(%s) <= %s" % (setting,
-                            getattr(obj, setting), element.value)
+                dprint("Setting %s(%s) <= %s" % (setting,
+                        getattr(obj, setting), element.value))
                if setting == "contrast":
                    setattr(obj, setting, int(element.value) + 1)
                elif setting == "callsign":
diff --git a/chirp/ft857.py b/chirp/ft857.py
index a479623..cccaa44 100644
--- a/chirp/ft857.py
+++ b/chirp/ft857.py
@@ -16,7 +16,7 @@

"""FT857 - FT857/US management module"""

-from chirp import ft817, chirp_common, errors, directory
+from chirp import ft817, chirp_common, errors, directory, dprint
from chirp.settings import RadioSetting, RadioSettingGroup, \
    RadioSettingValueInteger, RadioSettingValueList, \
    RadioSettingValueBoolean, RadioSettingValueString, \
@@ -956,9 +956,8 @@ class FT857Radio(ft817.FT817Radio):
                else:
                    obj = _settings
                    setting = element.get_name()
-                if os.getenv("CHIRP_DEBUG"):
-                    print "Setting %s(%s) <= %s" % (setting,
-                                    getattr(obj, setting), element.value)
+                dprint("Setting %s(%s) <= %s" % (setting,
+                        getattr(obj, setting), element.value))
                if setting == "arts_idw":
                    self._memobj.arts_idw = \
                        [self._CALLSIGN_CHARSET_REV[x] for x in
diff --git a/chirp/ft90.py b/chirp/ft90.py
index bfbddda..4060756 100644
--- a/chirp/ft90.py
+++ b/chirp/ft90.py
@@ -15,6 +15,7 @@
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from chirp import chirp_common, bitwise, memmap, directory, errors, util, yaesu_clone
+from chirp import dprint
from chirp.settings import RadioSetting, RadioSettingGroup, \
    RadioSettingValueInteger, RadioSettingValueList, \
    RadioSettingValueBoolean, RadioSettingValueString, \
@@ -22,11 +23,6 @@ from chirp.settings import RadioSetting, RadioSettingGroup, \
import time, os, traceback, string, re
from textwrap import dedent

-if os.getenv("CHIRP_DEBUG"):
-    CHIRP_DEBUG = True
-else:
-    CHIRP_DEBUG=False
-
CMD_ACK = chr(0x06)

FT90_STEPS = [5.0, 10.0, 12.5, 15.0, 20.0, 25.0, 50.0]
@@ -289,27 +285,24 @@ class FT90Radio(yaesu_clone.YaesuCloneModeRadio):
            blocknumbyte = chr(blocknum)
            payloadbytes = self.get_mmap()[pos:pos+blocksize]
            checksumbyte = chr(checksum.get_calculated(self.get_mmap()))
-            if CHIRP_DEBUG:
-                print "Block %i - will send from %i to %i byte " % \
-                    (blocknum, pos, pos + blocksize)
-                print util.hexprint(blocknumbyte)
-                print util.hexprint(payloadbytes)
-                print util.hexprint(checksumbyte)
+            dprint("Block %i - will send from %i to %i byte " % \
+                (blocknum, pos, pos + blocksize))
+            dprint(util.hexprint(blocknumbyte))
+            dprint(util.hexprint(payloadbytes))
+            dprint(util.hexprint(checksumbyte))
            # send wrapped bytes
            time.sleep(looppredelay)
            self.pipe.write(blocknumbyte)
            self.pipe.write(payloadbytes)
            self.pipe.write(checksumbyte)
            tmp = self.pipe.read(blocksize+2)  #chew echo
-            if CHIRP_DEBUG:
-                print "bytes echoed: "
-                print util.hexprint(tmp)
+            dprint("bytes echoed: ")
+            dprint(util.hexprint(tmp))
            # radio is slow to write/ack:
            time.sleep(looppostdelay)
            buf = self.pipe.read(1)
-            if CHIRP_DEBUG:
-                print "ack recd:"
-                print util.hexprint(buf)
+            dprint("ack recd:")
+            dprint(util.hexprint(buf))
            if buf != CMD_ACK:
                raise Exception("Radio did not ack block %i" % blocknum)
            pos += blocksize
@@ -463,12 +456,10 @@ class FT90Radio(yaesu_clone.YaesuCloneModeRadio):

    def _decode_cwid(self, cwidarr):
        cwid = ""
-        if CHIRP_DEBUG:
-            print "@ +_decode_cwid:"
+        dprint("@ +_decode_cwid:")
        for byte in cwidarr.get_value():
            char = int(byte)
-            if CHIRP_DEBUG:
-                print char
+            dprint(char)
            # bitwise wraps in quotes! get rid of those
            if char < len(FT90_CWID_CHARS):
                cwid += FT90_CWID_CHARS[char]
@@ -476,21 +467,17 @@ class FT90Radio(yaesu_clone.YaesuCloneModeRadio):

    def _encode_cwid(self, cwidarr):
        cwid = ""
-        if CHIRP_DEBUG:
-            print "@ _encode_cwid:"
+        dprint("@ _encode_cwid:")
        for char in cwidarr.get_value():
            cwid += chr(FT90_CWID_CHARS.index(char))
-        if CHIRP_DEBUG:
-            print cwid
+        dprint(cwid)
        return cwid
   
    def _bbcd2dtmf(self, bcdarr, strlen = 16):
        # doing bbcd, but with support for ABCD*#
-        if CHIRP_DEBUG:
-            print bcdarr.get_value()
+        dprint(bcdarr.get_value())
        string = ''.join("%02X" % b for b in bcdarr)
-        if CHIRP_DEBUG:
-            print "@_bbcd2dtmf, received: %s" % string
+        dprint("@_bbcd2dtmf, received: %s" % string)
        string = string.replace('E','*').replace('F','#')
        if strlen <= 16:
            string = string[:strlen]
@@ -501,8 +488,7 @@ class FT90Radio(yaesu_clone.YaesuCloneModeRadio):
        dtmfstr = dtmfstr.replace('*', 'E').replace('#', 'F')
        dtmfstr = str.ljust(dtmfstr.strip(), 16, "0" )
        bcdarr = list(bytearray.fromhex(dtmfstr))
-        if CHIRP_DEBUG:
-            print "@_dtmf2bbcd, sending: %s" % bcdarr
+        dprint("@_dtmf2bbcd, sending: %s" % bcdarr)
        return bcdarr
   
    def get_settings(self):
@@ -644,9 +630,7 @@ class FT90Radio(yaesu_clone.YaesuCloneModeRadio):
                    dtmfstrlen = len(str(newval).strip())
                    setattr(_settings, setting + "_len", dtmfstrlen)
                    newval = self._dtmf2bbcd(newval)
-                if CHIRP_DEBUG:
-                    print "Setting %s(%s) <= %s" % (setting,
-                                    oldval, newval)
+                dprint("Setting %s(%s) <= %s" % (setting, oldval, newval))
                setattr(_settings, setting, newval)
            except Exception, e:
                print element.get_name()
diff --git a/chirp/ftm350.py b/chirp/ftm350.py
index 442cde1..4b823bc 100644
--- a/chirp/ftm350.py
+++ b/chirp/ftm350.py
@@ -18,7 +18,7 @@ import struct
import os

from chirp import chirp_common, yaesu_clone, directory, errors, util
-from chirp import bitwise, memmap
+from chirp import bitwise, memmap, dprint
from chirp.settings import RadioSettingGroup, RadioSetting, RadioSettings
from chirp.settings import RadioSettingValueInteger, RadioSettingValueString

@@ -141,8 +141,8 @@ def _clone_in(radio):
            radio.pipe.write("\x06")
            time.sleep(0.05)

-            if os.getenv("CHIRP_DEBUG") and (last_addr + 128) != addr:
-                print "Gap, expecting %04x, got %04x" % (last_addr+128, addr)
+            if (last_addr + 128) != addr:
+                dprint("Gap, expecting %04x, got %04x" % (last_addr+128, addr))
            last_addr = addr
            data[addr] = block
            length += len(block)
diff --git a/chirp/h777.py b/chirp/h777.py
index bce4b98..f37d193 100644
--- a/chirp/h777.py
+++ b/chirp/h777.py
@@ -20,13 +20,11 @@ import struct
import unittest

from chirp import chirp_common, directory, memmap
-from chirp import bitwise, errors, util
+from chirp import bitwise, errors, util, dprint
from chirp.settings import RadioSetting, RadioSettingGroup, \
    RadioSettingValueInteger, RadioSettingValueList, \
    RadioSettingValueBoolean, RadioSettings

-DEBUG = os.getenv("CHIRP_DEBUG") and True or False
-
MEM_FORMAT = """
#seekto 0x0010;
struct {
@@ -139,8 +137,7 @@ def _h777_read_block(radio, block_addr, block_size):

    cmd = struct.pack(">cHb", 'R', block_addr, BLOCK_SIZE)
    expectedresponse = "W" + cmd[1:]
-    if DEBUG:
-        print("Reading block %04x..." % (block_addr))
+    dprint("Reading block %04x..." % (block_addr))

    try:
        serial.write(cmd)
@@ -166,9 +163,8 @@ def _h777_write_block(radio, block_addr, block_size):
    cmd = struct.pack(">cHb", 'W', block_addr, BLOCK_SIZE)
    data = radio.get_mmap()[block_addr:block_addr + 8]

-    if DEBUG:
-        print("Writing Data:")
-        print util.hexprint(cmd + data)
+    dprint("Writing Data:")
+    dprint(util.hexprint(cmd + data))

    try:
        serial.write(cmd + data)
@@ -197,9 +193,8 @@ def do_download(radio):
        block = _h777_read_block(radio, addr, BLOCK_SIZE)
        data += block

-        if DEBUG:
-            print "Address: %04x" % addr
-            print util.hexprint(block)
+        dprint("Address: %04x" % addr)
+        dprint(util.hexprint(block))

    _h777_exit_programming_mode(radio)

diff --git a/chirp/icomciv.py b/chirp/icomciv.py
index 71af300..54f2b57 100644
--- a/chirp/icomciv.py
+++ b/chirp/icomciv.py
@@ -1,10 +1,8 @@

import struct
-from chirp import chirp_common, icf, util, errors, bitwise, directory
+from chirp import chirp_common, icf, util, errors, bitwise, directory, dprint
from chirp.memmap import MemoryMap

-DEBUG = True
-
MEM_FORMAT = """
bbcd number[2];
u8  unknown1;
@@ -80,9 +78,8 @@ class Frame:
        raw = struct.pack("BBBBBB", 0xFE, 0xFE, src, dst, self._cmd, self._sub)
        raw += str(self._data) + chr(0xFD)

-        if DEBUG:
-            print "%02x -> %02x (%i):\n%s" % (src, dst,
-                                              len(raw), util.hexprint(raw))
+        dprint("%02x -> %02x (%i):\n%s" % (src, dst,
+                                          len(raw), util.hexprint(raw)))

        serial.write(raw)
        if willecho:
@@ -106,8 +103,7 @@ class Frame:
            raise errors.RadioError("Radio reported error")

        src, dst = struct.unpack("BB", data[2:4])
-        if DEBUG:
-            print "%02x <- %02x:\n%s" % (src, dst, util.hexprint(data))
+        dprint("%02x <- %02x:\n%s" % (src, dst, util.hexprint(data)))

        self._cmd = ord(data[4])
        self._sub = ord(data[5])
diff --git a/chirp/idrp.py b/chirp/idrp.py
index e20ba07..8a08e00 100644
--- a/chirp/idrp.py
+++ b/chirp/idrp.py
@@ -15,10 +15,7 @@

import serial

-from chirp import chirp_common, errors
-from chirp import util
-
-DEBUG_IDRP = False
+from chirp import chirp_common, errors, util, dprint

def parse_frames(buf):
    """Parse frames from the radio"""
@@ -49,8 +46,7 @@ def send(pipe, buf):
            break

        data += buf
-        if DEBUG_IDRP:
-            print "Got: \n%s" % util.hexprint(buf)
+        dprint("Got: \n%s" % util.hexprint(buf))

    return parse_frames(data)

@@ -97,8 +93,7 @@ def get_freq(pipe):
                                                  ord(els[2]),
                                                  ord(els[1]),
                                                  ord(els[0])))
-            if DEBUG_IDRP:
-                print "Freq: %f" % freq
+            dprint("Freq: %f" % freq)
            return freq

    raise errors.InvalidDataError("No frequency frame received")
diff --git a/chirp/kenwood_live.py b/chirp/kenwood_live.py
index 971c08e..f63dda5 100644
--- a/chirp/kenwood_live.py
+++ b/chirp/kenwood_live.py
@@ -29,8 +29,6 @@ from chirp.settings import RadioSetting, RadioSettingGroup, \
    RadioSettingValueInteger, RadioSettingValueBoolean, \
    RadioSettingValueString, RadioSettingValueList, RadioSettings

-DEBUG = True
-
DUPLEX = { 0 : "", 1 : "+", 2 : "-" }
MODES = { 0 : "FM", 1 : "AM" }
STEPS = list(chirp_common.TUNING_STEPS)
@@ -49,8 +47,7 @@ def command(ser, cmd, *args):
    LOCK.acquire()
    if args:
        cmd += " " + " ".join(args)
-    if DEBUG:
-        print "PC->RADIO: %s" % cmd
+    dprint("PC->RADIO: %s" % cmd)
    ser.write(cmd + "\r")

    result = ""
@@ -60,8 +57,7 @@ def command(ser, cmd, *args):
            print "Timeout waiting for data"
            break

-    if DEBUG:
-        print "D7->PC: %s" % result.strip()
+    dprint("D7->PC: %s" % result.strip())

    LOCK.release()

diff --git a/chirp/kguv8d.py b/chirp/kguv8d.py
index 772b04f..3344b5c 100644
--- a/chirp/kguv8d.py
+++ b/chirp/kguv8d.py
@@ -17,17 +17,12 @@

import time
import os
-from chirp import util, chirp_common, bitwise, memmap, errors, directory
+from chirp import util, chirp_common, bitwise, memmap, errors, directory, dprint
from chirp.settings import RadioSetting, RadioSettingGroup, \
                RadioSettingValueBoolean, RadioSettingValueList, \
                RadioSettingValueInteger, RadioSettingValueString, \
                RadioSettings

-if os.getenv("CHIRP_DEBUG"):
-    CHIRP_DEBUG = True
-else:
-    CHIRP_DEBUG = False
-
CMD_ID = 128
CMD_END = 129
CMD_RD = 130
@@ -304,8 +299,7 @@ class KGUV8DRadio(chirp_common.CloneModeRadio,
            _packet += payload
        # calculate and add the checksum to the packet
        _packet += chr(self._checksum(_packet[1:]))
-        if CHIRP_DEBUG:
-            print "Sent:\n%s" % util.hexprint(_packet)
+        dprint("Sent:\n%s" % util.hexprint(_packet))
        self.pipe.write(_packet)

    def _read_record(self):
@@ -317,9 +311,8 @@ class KGUV8DRadio(chirp_common.CloneModeRadio,
        _cs += self._checksum(_packet)
        _cs %= 256
        _rcs = ord(self.pipe.read(1))
-        if CHIRP_DEBUG:
-            print "_cs =", _cs
-            print "_rcs=", _rcs
+        dprint("_cs =", _cs)
+        dprint("_rcs=", _rcs)
        return (_rcs != _cs, _packet)

# Identify the radio
@@ -350,14 +343,12 @@ class KGUV8DRadio(chirp_common.CloneModeRadio,
        for _i in range(0, 10):
            self._write_record(CMD_ID)
            _chksum_err, _resp = self._read_record()
-            if CHIRP_DEBUG:
-                print "Got:\n%s" % util.hexprint(_resp)
+            dprint("Got:\n%s" % util.hexprint(_resp))
            if _chksum_err:
                print "Checksum error: retrying ident..."
                time.sleep(0.100)
                continue
-            if CHIRP_DEBUG:
-                print "Model %s" % util.hexprint(_resp[0:7])
+            dprint("Model %s" % util.hexprint(_resp[0:7]))
            if _resp[0:7] == self._model:
                return
            if len(_resp) == 0:
@@ -407,8 +398,7 @@ class KGUV8DRadio(chirp_common.CloneModeRadio,
                # TODO: probably should retry a few times here
                print util.hexprint(resp)
                raise Exception("Checksum error on read")
-            if CHIRP_DEBUG:
-                print "Got:\n%s" % util.hexprint(resp)
+            dprint("Got:\n%s" % util.hexprint(resp))
            image += resp[2:]
            if self.status_fn:
                status = chirp_common.Status()
@@ -436,11 +426,9 @@ class KGUV8DRadio(chirp_common.CloneModeRadio,
            req = chr(i / 256) + chr(i % 256)
            chunk = self.get_mmap()[ptr:ptr + blocksize]
            self._write_record(CMD_WR, req + chunk)
-            if CHIRP_DEBUG:
-                print util.hexprint(req + chunk)
+            dprint(util.hexprint(req + chunk))
            cserr, ack = self._read_record()
-            if CHIRP_DEBUG:
-                print util.hexprint(ack)
+            dprint(util.hexprint(ack))
            j = ord(ack[0]) * 256 + ord(ack[1])
            if cserr or j != ptr:
                raise Exception("Radio did not ack block %i" % ptr)
@@ -537,9 +525,8 @@ class KGUV8DRadio(chirp_common.CloneModeRadio,
        # always set it even if no dtcs is used
        mem.dtcs_polarity = "%s%s" % (tpol or "N", rpol or "N")

-        if os.getenv("CHIRP_DEBUG"):
-            print "Got TX %s (%i) RX %s (%i)" % (txmode, _mem.txtone,
-                                                rxmode, _mem.rxtone)
+        dprint("Got TX %s (%i) RX %s (%i)" % (txmode, _mem.txtone,
+                                              rxmode, _mem.rxtone))

    def get_memory(self, number):
        _mem = self._memobj.memory[number]
@@ -549,8 +536,7 @@ class KGUV8DRadio(chirp_common.CloneModeRadio,
        mem.number = number
        _valid = self._memobj.valid[mem.number]

-        if CHIRP_DEBUG:
-            print number, _valid == MEM_VALID
+        dprint(number, _valid == MEM_VALID)
        if _valid != MEM_VALID:
            mem.empty = True
            return mem
@@ -618,9 +604,8 @@ class KGUV8DRadio(chirp_common.CloneModeRadio,
        else:
            _mem.rxtone = 0

-        if CHIRP_DEBUG:
-            print "Set TX %s (%i) RX %s (%i)" % (tx_mode, _mem.txtone,
-                                                rx_mode, _mem.rxtone)
+        dprint("Set TX %s (%i) RX %s (%i)" % (tx_mode, _mem.txtone,
+                                              rx_mode, _mem.rxtone))

    def set_memory(self, mem):
        number = mem.number
diff --git a/chirp/kyd.py b/chirp/kyd.py
index 2d4223d..ac2c3b1 100644
--- a/chirp/kyd.py
+++ b/chirp/kyd.py
@@ -19,13 +19,11 @@ import os
import struct

from chirp import chirp_common, directory, memmap
-from chirp import bitwise, errors, util
+from chirp import bitwise, errors, util, dprint
from chirp.settings import RadioSetting, RadioSettingGroup, \
    RadioSettingValueInteger, RadioSettingValueList, \
    RadioSettingValueBoolean, RadioSettings

-DEBUG = os.getenv("CHIRP_DEBUG") and True or False
-
MEM_FORMAT = """
#seekto 0x0010;
struct {
@@ -132,8 +130,7 @@ def _nc630a_read_block(radio, block_addr, block_size):

    cmd = struct.pack(">cHb", 'R', block_addr, BLOCK_SIZE)
    expectedresponse = "W" + cmd[1:]
-    if DEBUG:
-        print("Reading block %04x..." % (block_addr))
+    dprint("Reading block %04x..." % (block_addr))

    try:
        serial.write(cmd)
@@ -159,9 +156,8 @@ def _nc630a_write_block(radio, block_addr, block_size):
    cmd = struct.pack(">cHb", 'W', block_addr, BLOCK_SIZE)
    data = radio.get_mmap()[block_addr:block_addr + 8]

-    if DEBUG:
-        print("Writing Data:")
-        print util.hexprint(cmd + data)
+    dprint("Writing Data:")
+    dprint(util.hexprint(cmd + data))

    try:
        serial.write(cmd + data)
@@ -190,9 +186,8 @@ def do_download(radio):
        block = _nc630a_read_block(radio, addr, BLOCK_SIZE)
        data += block

-        if DEBUG:
-            print "Address: %04x" % addr
-            print util.hexprint(block)
+        dprint("Address: %04x" % addr)
+        dprint(util.hexprint(block))

    _nc630a_exit_programming_mode(radio)

@@ -301,9 +296,8 @@ class NC630aRadio(chirp_common.CloneModeRadio):
        if mem.tmode == "DTCS":
            mem.dtcs_polarity = "%s%s" % (tpol, rpol)

-        if os.getenv("CHIRP_DEBUG"):
-            print "Got TX %s (%i) RX %s (%i)" % (txmode, _mem.tx_tone,
-                                                rxmode, _mem.rx_tone)
+        dprint("Got TX %s (%i) RX %s (%i)" % (txmode, _mem.tx_tone,
+                                              rxmode, _mem.rx_tone))

    def get_memory(self, number):
        bitpos = (1 << ((number - 1) % 8))
@@ -387,9 +381,8 @@ class NC630aRadio(chirp_common.CloneModeRadio):
        else:
            _mem.rx_tone = 0xFFFF

-        if os.getenv("CHIRP_DEBUG"):
-            print "Set TX %s (%i) RX %s (%i)" % (tx_mode, _mem.tx_tone,
-                                                rx_mode, _mem.rx_tone)
+        dprint("Set TX %s (%i) RX %s (%i)" % (tx_mode, _mem.tx_tone,
+                                              rx_mode, _mem.rx_tone))

    def set_memory(self, mem):
        bitpos = (1 << ((mem.number - 1) % 8))
diff --git a/chirp/leixen.py b/chirp/leixen.py
index 1977f0c..285fe84 100644
--- a/chirp/leixen.py
+++ b/chirp/leixen.py
@@ -24,11 +24,6 @@ from chirp.settings import RadioSetting, RadioSettingGroup, \
    RadioSettingValueFloat, InvalidValueError, RadioSettings
from textwrap import dedent

-if os.getenv("CHIRP_DEBUG"):
-    CHIRP_DEBUG = True
-else:
-    CHIRP_DEBUG = False
-
MEM_FORMAT = """
#seekto 0x0184;
struct {
diff --git a/chirp/puxing.py b/chirp/puxing.py
index 88cbe79..f38b41e 100644
--- a/chirp/puxing.py
+++ b/chirp/puxing.py
@@ -20,11 +20,6 @@ import os
from chirp import util, chirp_common, bitwise, errors, directory
from chirp.wouxun_common import wipe_memory, do_download, do_upload

-if os.getenv("CHIRP_DEBUG"):
-    DEBUG = True
-else:
-    DEBUG = False
-
def _puxing_prep(radio):
    radio.pipe.write("\x02PROGRA")
    ack = radio.pipe.read(1)
diff --git a/chirp/th9800.py b/chirp/th9800.py
index 3edc310..50dbd53 100644
--- a/chirp/th9800.py
+++ b/chirp/th9800.py
@@ -15,7 +15,7 @@
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

-from chirp import bitwise, chirp_common, directory, errors, util, memmap
+from chirp import bitwise, chirp_common, directory, errors, util, memmap, dprint
import struct
from chirp.settings import RadioSetting, RadioSettingGroup, \
    RadioSettingValueInteger, RadioSettingValueList, \
@@ -26,11 +26,6 @@ import os
import time
from datetime import date

-if os.getenv("CHIRP_DEBUG"):
-    CHIRP_DEBUG = True
-else:
-    CHIRP_DEBUG = False
-
TH9800_MEM_FORMAT = """
struct mem {
  lbcd rx_freq[4];
@@ -323,8 +318,7 @@ class TYTTH9800Base(chirp_common.Radio):
    _prev_active = self.get_active("chan_active", mem.number)
    self.set_active("chan_active", mem.number, not mem.empty)
    if mem.empty or not _prev_active:
-      if CHIRP_DEBUG:
-        print "initializing memory channel %d" % mem.number
+      dprint("initializing memory channel %d" % mem.number)
      _mem.set_raw(BLANK_MEMORY)

    if mem.empty:
@@ -390,8 +384,7 @@ class TYTTH9800Base(chirp_common.Radio):
    _mem.step = STEPS.index(mem.tuning_step)

    for setting in mem.extra:
-      if CHIRP_DEBUG:
-          print "@set_mem:", setting.get_name(), setting.value
+      dprint("@set_mem:", setting.get_name(), setting.value)
      setattr(_mem, setting.get_name(), setting.value)

  def get_settings(self):
@@ -559,9 +552,7 @@ class TYTTH9800Base(chirp_common.Radio):
              oldval = getattr(_settings, setting)
              newval = element.value

-              if CHIRP_DEBUG:
-                  print "Setting %s(%s) <= %s" % (setting,
-                                                  oldval, newval)
+              dprint("Setting %s(%s) <= %s" % (setting, oldval, newval))
              setattr(_settings, setting, newval)
          except Exception, e:
              print element.get_name()
@@ -666,12 +657,12 @@ def _upload(radio, memsize = 0xF400, blocksize = 0x80):
    m = today.month
    d = today.day
    _info = radio._memobj.info
-    if CHIRP_DEBUG:
-        ly = _info.prog_yr
-        lm = _info.prog_mon
-        ld = _info.prog_day
-        print "Updating last program date:%d/%d/%d" % (lm,ld,ly)
-        print "                  to today:%d/%d/%d" % (m,d,y)
+
+    ly = _info.prog_yr
+    lm = _info.prog_mon
+    ld = _info.prog_day
+    dprint("Updating last program date:%d/%d/%d" % (lm,ld,ly))
+    dprint("                  to today:%d/%d/%d" % (m,d,y))

    _info.prog_yr = y
    _info.prog_mon = m
@@ -680,8 +671,7 @@ def _upload(radio, memsize = 0xF400, blocksize = 0x80):
    offset = 0x0100
    for addr in range(offset, memsize, blocksize):
        mapaddr = addr + radio._mmap_offset - offset
-        if CHIRP_DEBUG:
-          print "addr: 0x%04X, mmapaddr: 0x%04X" % (addr, mapaddr)
+        dprint("addr: 0x%04X, mmapaddr: 0x%04X" % (addr, mapaddr))
        msg = struct.pack(">cHB", "W", addr, blocksize)       
        msg += radio._mmap[mapaddr:(mapaddr + blocksize)]
        print util.hexprint(msg)
@@ -703,8 +693,7 @@ def _upload(radio, memsize = 0xF400, blocksize = 0x80):

    # Checksum?
    final_data = radio.pipe.read(3)
-    if CHIRP_DEBUG:
-      print "final:", util.hexprint(final_data)
+    dprint("final:", util.hexprint(final_data))

@directory.register
class TYTTH9800Radio(TYTTH9800Base, chirp_common.CloneModeRadio,
diff --git a/chirp/th_uv3r.py b/chirp/th_uv3r.py
index 5e3e2c0..3b670fe 100644
--- a/chirp/th_uv3r.py
+++ b/chirp/th_uv3r.py
@@ -19,11 +19,6 @@ import os
from chirp import chirp_common, bitwise, errors, directory
from chirp.wouxun_common import do_download, do_upload

-if os.getenv("CHIRP_DEBUG"):
-    DEBUG = True
-else:
-    DEBUG = False
-
def tyt_uv3r_prep(radio):
    try:
        radio.pipe.write("PROGRAMa")
diff --git a/chirp/thd72.py b/chirp/thd72.py
index 0d80adc..926a927 100644
--- a/chirp/thd72.py
+++ b/chirp/thd72.py
@@ -14,11 +14,9 @@
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from chirp import chirp_common, errors, util, directory
-from chirp import bitwise, memmap
+from chirp import bitwise, memmap, dprint
import time, struct, sys

-DEBUG = True
-
# TH-D72 memory map
# 0x0000..0x0200: startup password and other stuff
# 0x0200..0x0400: current channel and other settings
@@ -452,13 +450,11 @@ class THD72Radio(chirp_common.CloneModeRadio):
        start = time.time()

        data = ""
-        if DEBUG:
-            print "PC->D72: %s" % cmd
+        dprint("PC->D72: %s" % cmd)
        self.pipe.write(cmd + "\r")
        while not data.endswith("\r") and (time.time() - start) < timeout:
            data += self.pipe.read(1)
-        if DEBUG:
-            print "D72->PC: %s" % data.strip()
+        dprint("D72->PC: %s" % data.strip())
        return data.strip()

    def get_id(self):
diff --git a/chirp/tk8102.py b/chirp/tk8102.py
index 32e8621..9cc661f 100644
--- a/chirp/tk8102.py
+++ b/chirp/tk8102.py
@@ -17,7 +17,7 @@ import struct
import os

from chirp import chirp_common, directory, memmap, errors, util
-from chirp import bitwise
+from chirp import bitwise, dprint
from chirp.settings import RadioSettingGroup, RadioSetting
from chirp.settings import RadioSettingValueBoolean, RadioSettingValueList
from chirp.settings import RadioSettingValueString, RadioSettings
@@ -317,9 +317,8 @@ class KenwoodTKx102Radio(chirp_common.CloneModeRadio):
        else:
            _mem.rx_tone = 0xFFFF

-        if os.getenv("CHIRP_DEBUG"):
-            print "Set TX %s (%i) RX %s (%i)" % (tx_mode, _mem.tx_tone,
-                                                rx_mode, _mem.rx_tone)
+        dprint("Set TX %s (%i) RX %s (%i)" % (tx_mode, _mem.tx_tone,
+                                              rx_mode, _mem.rx_tone))
    def set_memory(self, mem):
        _mem = self._memobj.memory[mem.number - 1]

diff --git a/chirp/tmv71_ll.py b/chirp/tmv71_ll.py
index dac7f36..affe360 100644
--- a/chirp/tmv71_ll.py
+++ b/chirp/tmv71_ll.py
@@ -15,9 +15,7 @@

import struct, time

-from chirp import memmap, chirp_common, errors
-
-DEBUG = True
+from chirp import memmap, chirp_common, errors, dprint

POS_MODE  = 5
POS_DUP    = 6
@@ -50,13 +48,11 @@ def command(s, cmd, timeout=0.5):
    start = time.time()

    data = ""
-    if DEBUG:
-        print "PC->V71: %s" % cmd
+    dprint("PC->V71: %s" % cmd)
    s.write(cmd + "\r")
    while not data.endswith("\r") and (time.time() - start) < timeout:
        data += s.read(1)
-    if DEBUG:
-        print "V71->PC: %s" % data.strip()
+    dprint("V71->PC: %s" % data.strip())
    return data.strip()

def get_id(s):
diff --git a/chirp/uv5r.py b/chirp/uv5r.py
index 6fcbae1..55e0516 100644
--- a/chirp/uv5r.py
+++ b/chirp/uv5r.py
@@ -18,18 +18,13 @@ import time
import os

from chirp import chirp_common, errors, util, directory, memmap
-from chirp import bitwise
+from chirp import bitwise, dprint
from chirp.settings import RadioSetting, RadioSettingGroup, \
    RadioSettingValueInteger, RadioSettingValueList, \
    RadioSettingValueBoolean, RadioSettingValueString, \
    RadioSettingValueFloat, InvalidValueError, RadioSettings
from textwrap import dedent

-if os.getenv("CHIRP_DEBUG"):
-    CHIRP_DEBUG = True
-else:
-    CHIRP_DEBUG = False
-
MEM_FORMAT = """
#seekto 0x0008;
struct {
@@ -394,8 +389,7 @@ def _firmware_version_from_image(radio):
    version = _firmware_version_from_data(radio.get_mmap(),
                                          radio._fw_ver_file_start,
                                          radio._fw_ver_file_stop)
-    if CHIRP_DEBUG:
-        print "_firmware_version_from_image: " + util.hexprint(version)
+    dprint("_firmware_version_from_image: " + util.hexprint(version))
    return version

def _special_block_from_data(data, special_block_start, special_block_stop):
@@ -404,8 +398,7 @@ def _special_block_from_data(data, special_block_start, special_block_stop):

def _special_block_from_image(radio):
    special_block = _special_block_from_data(radio.get_mmap(), 0x0CFA, 0x0D01)
-    if CHIRP_DEBUG:
-        print "_special_block_from_image: " + util.hexprint(special_block)
+    dprint("_special_block_from_image: " + util.hexprint(special_block))
    return special_block

def _do_ident(radio, magic):
@@ -504,19 +497,16 @@ def _do_download(radio):
        raise errors.RadioError("Incorrect 'Model' selected.")

    # Main block
-    if CHIRP_DEBUG:
-        print "downloading main block..."
+    dprint("downloading main block...")
    for i in range(0, 0x1800, 0x40):
        data += _read_block(radio, i, 0x40)
        _do_status(radio, i)
-    if CHIRP_DEBUG:
-        print "done."
-        print "downloading aux block..."
+    dprint("done.")
+    dprint("downloading aux block...")
    # Auxiliary block starts at 0x1ECO (?)
    for i in range(0x1EC0, 0x2000, 0x40):
        data += _read_block(radio, i, 0x40)
-    if CHIRP_DEBUG:
-        print "done."
+    dprint("done.")
    return memmap.MemoryMap(data)

def _send_block(radio, addr, data):
@@ -916,8 +906,7 @@ class BaofengUV5R(chirp_common.CloneModeRadio,

    def _is_orig(self):
        version_tag = _firmware_version_from_image(self)
-        if CHIRP_DEBUG:
-            print "@_is_orig, version_tag:", util.hexprint(version_tag)
+        dprint("@_is_orig, version_tag:", util.hexprint(version_tag))
        try:
            if 'BFB' in version_tag:
                idx = version_tag.index("BFB") + 3
diff --git a/chirp/vx170.py b/chirp/vx170.py
index 20aac04..eaa7dbc 100644
--- a/chirp/vx170.py
+++ b/chirp/vx170.py
@@ -19,11 +19,6 @@ from textwrap import dedent
import time, os
from chirp import ft7800

-if os.getenv("CHIRP_DEBUG"):
-    CHIRP_DEBUG = True
-else:
-    CHIRP_DEBUG = False
-
MEM_FORMAT = """
#seekto 0x018A;
struct {
diff --git a/chirp/vx2.py b/chirp/vx2.py
index 3156806..dadf336 100644
--- a/chirp/vx2.py
+++ b/chirp/vx2.py
@@ -14,18 +14,13 @@
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

-from chirp import chirp_common, yaesu_clone, directory, bitwise
+from chirp import chirp_common, yaesu_clone, directory, bitwise, dprint
from chirp.settings import RadioSetting, RadioSettingGroup, \
    RadioSettingValueInteger, RadioSettingValueList, \
    RadioSettingValueBoolean, RadioSettingValueString, \
    RadioSettings
import os, traceback, re

-if os.getenv("CHIRP_DEBUG"):
-    CHIRP_DEBUG = True
-else:
-    CHIRP_DEBUG = False
-
MEM_FORMAT = """
#seekto 0x7F52;
u8 checksum;
@@ -410,9 +405,8 @@ class VX2Radio(yaesu_clone.YaesuCloneModeRadio):
        return VX2BankModel(self)

    def _decode_chars(self, inarr):
-        if CHIRP_DEBUG:
-            print "@_decode_chars, type: %s" % type(inarr)
-            print inarr
+        dprint("@_decode_chars, type: %s" % type(inarr))
+        dprint(inarr)
        outstr = ""
        for i in inarr:
            if i == 0xFF:
@@ -421,9 +415,8 @@ class VX2Radio(yaesu_clone.YaesuCloneModeRadio):
        return outstr.rstrip()
           
    def _encode_chars(self, instr, length = 16):
-        if CHIRP_DEBUG:
-            print "@_encode_chars, type: %s" % type(instr)
-            print instr
+        dprint("@_encode_chars, type: %s" % type(instr))
+        dprint(instr)
        outarr = []
        instr = str(instr)
        for i in range(0, length):
@@ -648,8 +641,7 @@ class VX2Radio(yaesu_clone.YaesuCloneModeRadio):
            for c in dtmfsetting.digits:
                if c < len(DTMFCHARSET):
                    dtmfstr += DTMFCHARSET[c]
-            if CHIRP_DEBUG:
-                print dtmfstr
+            dprint(dtmfstr)
            dtmfentry = RadioSettingValueString(0, 16, dtmfstr)
            dtmfentry.set_charset(DTMFCHARSET + list(" "))
            rs = RadioSetting(name, name.upper(), dtmfentry)
@@ -676,8 +668,7 @@ class VX2Radio(yaesu_clone.YaesuCloneModeRadio):
                            newval.append(DTMFCHARSET.index(dtmfstr[i]))
                        else:
                            newval.append(0xFF)
-                    if CHIRP_DEBUG:
-                        print newval
+                    dprint(newval)
                    idx = int(setting[-1:]) - 1
                    _settings = self._memobj.dtmf[idx]
                    _settings.digits = newval
@@ -698,12 +689,10 @@ class VX2Radio(yaesu_clone.YaesuCloneModeRadio):
                    newval = self._encode_chars(newval)
                if setting == "openmsg":
                    newval = self._encode_chars(newval, 6)
-                if CHIRP_DEBUG:
-                    print "Setting %s(%s) <= %s" % (setting,
-                                    oldval, newval)
+                dprint("Setting %s(%s) <= %s" % (setting, oldval, newval))
                setattr(_settings, setting, newval)
            except Exception, e:
                print element.get_name()
                raise
       
-       
\ No newline at end of file
+       
diff --git a/chirp/vx3.py b/chirp/vx3.py
index 99d0951..dfa6ffe 100644
--- a/chirp/vx3.py
+++ b/chirp/vx3.py
@@ -15,7 +15,7 @@
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from chirp import chirp_common, yaesu_clone, directory
-from chirp import bitwise
+from chirp import bitwise, dprint
from chirp.settings import RadioSetting, RadioSettingGroup, \
    RadioSettingValueInteger, RadioSettingValueList, \
    RadioSettingValueBoolean, RadioSettingValueString, \
@@ -29,11 +29,6 @@ import os, re
#0x0409 checksum2?
#0x04C9 checksum2a?

-if os.getenv("CHIRP_DEBUG"):
-    CHIRP_DEBUG = True
-else:
-    CHIRP_DEBUG = False
-
MEM_FORMAT = """
#seekto 0x7F4A;
u8 checksum;
@@ -499,9 +494,8 @@ class VX3Radio(yaesu_clone.YaesuCloneModeRadio):
        return VX3BankModel(self)

    def _decode_chars(self, inarr):
-        if CHIRP_DEBUG:
-            print "@_decode_chars, type: %s" % type(inarr)
-            print inarr
+        dprint("@_decode_chars, type: %s" % type(inarr))
+        dprint(inarr)
        outstr = ""
        for i in inarr:
            if i == 0xFF:
@@ -510,9 +504,8 @@ class VX3Radio(yaesu_clone.YaesuCloneModeRadio):
        return outstr.rstrip()
           
    def _encode_chars(self, instr, length = 16):
-        if CHIRP_DEBUG:
-            print "@_encode_chars, type: %s" % type(instr)
-            print instr
+        dprint("@_encode_chars, type: %s" % type(instr))
+        dprint(instr)
        outarr = []
        instr = str(instr)
        for i in range(length):
@@ -785,8 +778,7 @@ class VX3Radio(yaesu_clone.YaesuCloneModeRadio):
            for c in dtmfsetting.memory:
                if c < len(DTMFCHARSET):
                    dtmfstr += DTMFCHARSET[c]
-            if CHIRP_DEBUG:
-                print dtmfstr
+            dprint(dtmfstr)
            dtmfentry = RadioSettingValueString(0, 16, dtmfstr)
            dtmfentry.set_charset(DTMFCHARSET + list(" "))
            rs = RadioSetting(name, name.upper(), dtmfentry)
@@ -861,8 +853,7 @@ class VX3Radio(yaesu_clone.YaesuCloneModeRadio):
                            newval.append(DTMFCHARSET.index(dtmfstr[i]))
                        else:
                            newval.append(0xFF)
-                    if CHIRP_DEBUG:
-                        print newval
+                    dprint(newval)
                    idx = int(setting[-1:])
                    _settings = self._memobj.dtmf[idx]
                    _settings.memory = newval
@@ -885,11 +876,9 @@ class VX3Radio(yaesu_clone.YaesuCloneModeRadio):
                    newval = self._encode_chars(newval)
                if setting == "openmsg":
                    newval = self._encode_chars(newval, 6)
-                if CHIRP_DEBUG:
-                    print "Setting %s(%s) <= %s" % (setting,
-                                    oldval, newval)
+                dprint("Setting %s(%s) <= %s" % (setting, oldval, newval))
                setattr(_settings, setting, newval)
            except Exception, e:
                print element.get_name()
                raise
-       
\ No newline at end of file
+       
diff --git a/chirp/vx8.py b/chirp/vx8.py
index 02490a1..945abbd 100644
--- a/chirp/vx8.py
+++ b/chirp/vx8.py
@@ -17,7 +17,7 @@ import os
import re

from chirp import chirp_common, yaesu_clone, directory
-from chirp import bitwise
+from chirp import bitwise, dprint
from chirp.settings import RadioSettingGroup, RadioSetting, RadioSettings
from chirp.settings import RadioSettingValueInteger, RadioSettingValueString
from chirp.settings import RadioSettingValueList, RadioSettingValueBoolean
@@ -1461,8 +1461,7 @@ class VX8DRadio(VX8Radio):
        is_latitude = name.endswith("latitude")
        lat_long = setting.value.get_value().strip()
        sign, l_d, l_m, l_s = cls._str_to_latlong(lat_long, is_latitude)
-        if os.getenv("CHIRP_DEBUG"):
-            print "%s: %d %d %d %d" % (name, sign, l_d, l_m, l_s)
+        dprint("%s: %d %d %d %d" % (name, sign, l_d, l_m, l_s))
        setattr(obj, "%s_sign" % name, sign)
        setattr(obj, "%s_degree" % name, l_d)
        setattr(obj, "%s_minute" % name, l_m)
@@ -1499,9 +1498,8 @@ class VX8DRadio(VX8Radio):

                try:
                    old_val = getattr(obj, setting)
-                    if os.getenv("CHIRP_DEBUG"):
-                        print "Setting %s(%r) <= %s" % (
-                            element.get_name(), old_val, element.value)
+                    dprint("Setting %s(%r) <= %s" % (
+                            element.get_name(), old_val, element.value))
                    setattr(obj, setting, element.value)
                except AttributeError as e:
                    print "Setting %s is not in the memory map: %s" % (
diff --git a/chirp/wouxun.py b/chirp/wouxun.py
index 6feec42..e63f6ed 100644
--- a/chirp/wouxun.py
+++ b/chirp/wouxun.py
@@ -17,7 +17,7 @@

import time
import os
-from chirp import util, chirp_common, bitwise, memmap, errors, directory
+from chirp import util, chirp_common, bitwise, memmap, errors, directory, dprint
from chirp.settings import RadioSetting, RadioSettingGroup, \
                RadioSettingValueBoolean, RadioSettingValueList, \
                RadioSettingValueInteger, RadioSettingValueString, \
@@ -717,9 +717,8 @@ class KGUVD1PRadio(chirp_common.CloneModeRadio,
        # always set it even if no dtcs is used
        mem.dtcs_polarity = "%s%s" % (tpol or "N", rpol or "N")

-        if os.getenv("CHIRP_DEBUG"):
-            print "Got TX %s (%i) RX %s (%i)" % (txmode, _mem.tx_tone,
-                                                rxmode, _mem.rx_tone)
+        dprint("Got TX %s (%i) RX %s (%i)" % (txmode, _mem.tx_tone,
+                                              rxmode, _mem.rx_tone))

    def _is_txinh(self, _mem):
        raw_tx = ""
@@ -817,9 +816,8 @@ class KGUVD1PRadio(chirp_common.CloneModeRadio,
        else:
            _mem.rx_tone = 0xFFFF

-        if os.getenv("CHIRP_DEBUG"):
-            print "Set TX %s (%i) RX %s (%i)" % (tx_mode, _mem.tx_tone,
-                                                rx_mode, _mem.rx_tone)
+        dprint("Set TX %s (%i) RX %s (%i)" % (tx_mode, _mem.tx_tone,
+                                              rx_mode, _mem.rx_tone))

    def set_memory(self, mem):
        _mem = self._memobj.memory[mem.number - 1]
diff --git a/chirp/wouxun_common.py b/chirp/wouxun_common.py
index 3c78b3a..d384007 100644
--- a/chirp/wouxun_common.py
+++ b/chirp/wouxun_common.py
@@ -18,7 +18,7 @@

import struct
import os
-from chirp import util, chirp_common, memmap
+from chirp import util, chirp_common, memmap, dprint

def wipe_memory(_mem, byte):
    """Cleanup a memory"""
@@ -29,8 +29,7 @@ def do_download(radio, start, end, blocksize):
    image = ""
    for i in range(start, end, blocksize):
        cmd = struct.pack(">cHb", "R", i, blocksize)
-        if os.getenv("CHIRP_DEBUG"):
-            print util.hexprint(cmd)
+        dprint(util.hexprint(cmd))
        radio.pipe.write(cmd)
        length = len(cmd) + blocksize
        resp = radio.pipe.read(length)
@@ -61,8 +60,7 @@ def do_upload(radio, start, end, blocksize):
        chunk = radio.get_mmap()[ptr:ptr+blocksize]
        ptr += blocksize
        radio.pipe.write(cmd + chunk)
-        if os.getenv("CHIRP_DEBUG"):
-            print util.hexprint(cmd + chunk)
+        dprint(util.hexprint(cmd + chunk))

        ack = radio.pipe.read(1)
        if not ack == "\x06":
diff --git a/chirp/yaesu_clone.py b/chirp/yaesu_clone.py
index 57958c3..f27c375 100644
--- a/chirp/yaesu_clone.py
+++ b/chirp/yaesu_clone.py
@@ -15,7 +15,7 @@

CMD_ACK = 0x06

-from chirp import chirp_common, util, memmap, errors
+from chirp import chirp_common, util, memmap, errors, dprint
import time, os
from textwrap import dedent

@@ -49,8 +49,7 @@ def _chunk_read(pipe, count, status_fn):
        status.max = count
        status.cur = len(data)
        status_fn(status)
-        if os.getenv("CHIRP_DEBUG"):
-            print "Read %i/%i" % (len(data), count)
+        dprint("Read %i/%i" % (len(data), count))
    return data       

def __clone_in(radio):
@@ -91,8 +90,7 @@ def _chunk_write(pipe, data, status_fn, block):
        chunk = data[i:i+block]
        pipe.write(chunk)
        count += len(chunk)
-        if os.getenv("CHIRP_DEBUG"):
-            print "@_chunk_write, count: %i, blocksize: %i" % (count,block)
+        dprint("@_chunk_write, count: %i, blocksize: %i" % (count,block))
        time.sleep(delay)

        status = chirp_common.Status()
@@ -120,8 +118,7 @@ def __clone_out(radio):
    for block in radio._block_lengths:
        blocks += 1
        if blocks != len(radio._block_lengths):
-            if os.getenv("CHIRP_DEBUG"):
-                print "Sending %i-%i" % (pos, pos+block)
+            dprint("Sending %i-%i" % (pos, pos+block))
            pipe.write(radio.get_mmap()[pos:pos+block])
            buf = pipe.read(1)
            if buf and buf[0] != chr(CMD_ACK):
diff --git a/chirpui/reporting.py b/chirpui/reporting.py
index c48c6bb..23baa88 100644
--- a/chirpui/reporting.py
+++ b/chirpui/reporting.py
@@ -33,7 +33,6 @@ from chirp import CHIRP_VERSION, platform

REPORT_URL = "http://chirp.danplanet.com/report/report.php?do_report"
ENABLED = True
-DEBUG = os.getenv("CHIRP_DEBUG") == "y"
THREAD_SEM = threading.Semaphore(10) # Maximum number of outstanding threads
LAST = 0
LAST_TYPE = None
@@ -45,18 +44,14 @@ try:
except:
    ENABLED = False

-def debug(string):
-    if DEBUG:
-        print string
-
def should_report():
    if not ENABLED:
-        debug("Not reporting due to recent failure")
+        dprint("Not reporting due to recent failure")
        return False

    conf = config.get()
    if conf.get_bool("no_report"):
-        debug("Reporting disabled")
+        dprint("Reporting disabled")
        return False

    return True
@@ -70,7 +65,7 @@ def _report_model_usage(model, direction, success):
    model = "%s_%s" % (model.VENDOR, model.MODEL)
    data = "%s,%s,%s" % (model, direction, success)

-    debug("Reporting model usage: %s" % data)
+    dprint("Reporting model usage: %s" % data)

    proxy = xmlrpclib.ServerProxy(REPORT_URL)
    id = proxy.report_stats(CHIRP_VERSION,
@@ -84,7 +79,7 @@ def _report_model_usage(model, direction, success):
def _report_exception(stack):
    global ENABLED

-    debug("Reporting exception")
+    dprint("Reporting exception")

    proxy = xmlrpclib.ServerProxy(REPORT_URL)
    id = proxy.report_exception(CHIRP_VERSION,
@@ -98,7 +93,7 @@ def _report_exception(stack):
def _report_misc_error(module, data):
    global ENABLED

-    debug("Reporting misc error with %s" % module)
+    dprint("Reporting misc error with %s" % module)

    proxy = xmlrpclib.ServerProxy(REPORT_URL)
    id = proxy.report_misc_error(CHIRP_VERSION,
@@ -109,12 +104,12 @@ def _report_misc_error(module, data):
    return id != 0

def _check_for_updates(callback):
-    debug("Checking for updates")
+    dprint("Checking for updates")
    proxy = xmlrpclib.ServerProxy(REPORT_URL)
    ver = proxy.check_for_updates(CHIRP_VERSION,
                                  platform.get_platform().os_version_string())

-    debug("Server reports version %s is latest" % ver)
+    dprint("Server reports version %s is latest" % ver)
    callback(ver)
    return True

@@ -128,7 +123,7 @@ class ReportThread(threading.Thread):
        try:
            return self.__func(*self.__args)
        except Exception, e:
-            debug("Failed to report: %s" % e)
+            dprint("Failed to report: %s" % e)
            return False
       
    def run(self):
@@ -139,7 +134,7 @@ class ReportThread(threading.Thread):
            ENABLED = False
        elif (time.time() - start) > 15:
            # Reporting took too long
-            debug("Time to report was %.2f sec -- Disabling" % \
+            dprint("Time to report was %.2f sec -- Disabling" % \
                      (time.time()-start))
            ENABLED = False

@@ -151,13 +146,13 @@ def dispatch_thread(func, *args):

    # If reporting is disabled or failing, bail
    if not should_report():
-        debug("Reporting is disabled")
+        dprint("Reporting is disabled")
        return

    # If the time between now and the last report is less than 5 seconds, bail
    delta = time.time() - LAST
    if delta < 5 and func == LAST_TYPE:
-        debug("Throttling...")
+        dprint("Throttling...")
        return

    LAST = time.time()
@@ -165,7 +160,7 @@ def dispatch_thread(func, *args):

    # If there are already too many threads running, bail
    if not THREAD_SEM.acquire(False):
-        debug("Too many threads already running")
+        dprint("Too many threads already running")
        return

    t = ReportThread(func, *args)
--
1.9.1

_______________________________________________
chirp_devel mailing list
chirp_devel@intrepid.danplanet.com
http://intrepid.danplanet.com/mailman/listinfo/chirp_devel
Developer docs: http://chirp.danplanet.com/projects/chirp/wiki/Developers