#!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import with_statement
from __future__ import division

import sys
import os
import time
import glob
import serial
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import struct
import re
import urllib2
import urlparse
import pprint

from smartFormat import smartFormat, simpleFormat

if os.name is 'nt':
    import scanwin32

if os.name is 'posix':
    pass

def wstdout(s):
    sys.stdout.write(s)
    sys.stdout.flush()

def wstderr(s):
    sys.stderr.write(s)
    sys.stderr.flush()

PPstderr = pprint.PrettyPrinter(indent=2, width=80, depth=None, stream=sys.stderr)
PPstdout = pprint.PrettyPrinter(indent=2, width=80, depth=None, stream=sys.stderr)

#===============================================================================
# Module exception definitions
#===============================================================================
class CommProtocolError(Exception):
    pass

class MethodCallError(CommProtocolError):
    pass

class InvalidArgumentError(CommProtocolError):
    pass

class ArgumentConversionError(InvalidArgumentError):
    pass

class ArgumentLengthError(InvalidArgumentError):
    pass

class UnexptectedArgumentError(InvalidArgumentError):
    pass

class InvalidResponseError(CommProtocolError):
    pass

class ResponseConversionError(InvalidResponseError):
    pass

class ResponseLengthError(InvalidResponseError):
    pass

class UnexptectedResponseError(InvalidResponseError):
    pass

class UnsupportedOSError(CommProtocolError):
    pass

class InvalidCommandError(CommProtocolError):
    pass

class ChecksumMismatchError(CommProtocolError):
    pass

class SerialPortError(CommProtocolError):
    pass


class InstrumentComms(object):
    def __init__(self, useSerial=True, useEthernet=False,
                 ipAddress=None, ethPort=80,
                 serialPortName=None,
                 baud=19200, bytesize=8, parity='N', stopbits=1,
                 timeout=2, xonxoff=False, rtscts=False, dsrdtr=False,
                 serCmdPrefix="", serCmdTerm='\r', serIdnCmd='*IDN?',
                 ethCmdPrefix='COMMAND=', ethCmdTerm='\r\ngpibsend=Send\r\n',
                 ethDataRE=re.compile('.*<TEXTAREA.*>(.*)</TEXTAREA>'),
                 ethIdnCmd='*IDN?',
                 argSep=""):
        
        self.config = {}
        self.data = {}

        self.lowerRegex = re.compile("[a-z]")

        self.useSerial = useSerial
        self.useEthernet = useEthernet

        if self.useEthernet == True and ipAddress == None:
            raise CommProtocolError("IP address must be supplied")
        else:
            self.ipAddress = ipAddress
        
        if self.useEthernet == True and ethPort == None:
            raise CommProtocolError("Ethernet port must be supplied")
        else:
            self.ethPort = ethPort

        self.controllerSPName = serialPortName
        if self.useSerial:
            self.serialPort = serial.Serial()
        else:
            self.serialPort = None
        # Common baud rates: 115200, 38400, 19200, 9600, 4800, 2400, 1200
        self.BAUDRATE = baud
        self.BYTESIZE = bytesize