Пример #1
0
def encode(params, validate=False):
    '''Create a srbm binary message payload to pack into an AIS Msg srbm.

    Fields in params:
      - MessageID(uint): AIS message number.  Must be 14 (field automatically set to "14")
      - RepeatIndicator(uint): Indicated how many times a message has been repeated
      - UserID(uint): Unique ship identification number (MMSI).  Also known as the Source ID
      - Spare2(uint): Must be 0 (field automatically set to "0")
    @param params: Dictionary of field names/values.  Throws a ValueError exception if required is missing
    @param validate: Set to true to cause checking to occur.  Runs slower.  FIX: not implemented.
    @rtype: BitVector
    @return: encoded binary message (for binary messages, this needs to be wrapped in a msg 8
    @note: The returned bits may not be 6 bit aligned.  It is up to you to pad out the bits.
    '''

    bvList = []
    bvList.append(binary.setBitVectorSize(BitVector(intVal=14), 6))
    if 'RepeatIndicator' in params:
        bvList.append(
            binary.setBitVectorSize(
                BitVector(intVal=params['RepeatIndicator']), 2))
    else:
        bvList.append(binary.setBitVectorSize(BitVector(intVal=0), 2))
    bvList.append(
        binary.setBitVectorSize(BitVector(intVal=params['UserID']), 30))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=0), 1))

    return binary.joinBV(bvList)
Пример #2
0
def waterlevelEncode(*aDict, **params):
    '''Serializer for the waterlevel binary message
	
	Keywords and types:

	  - dac:  uint
	  - unavail_uint:  uint
	  - uint:  uint

	The default message:

	>>> print waterlevelEncode()
	1011011101100

	@param aDict: for passing in a dictionary of keyword and values.
	@param params: keyword dictionary or if a dict is passed, it will use that dict
	@note: only use one of aDict or params
	'''

    if len(aDict) > 1:
        assert (False and 'Illegal call to with more than one param')
    if len(aDict) == 1:
        if not isinstance(dict, aDict):
            assert (False and
                    'a single parameter must be a dictionary of key values')
        if len(params) > 0:
            assert (False
                    and 'Must not specify both a lookup table and keyvalues')
        params = aDict

    bvList = []

    ### FIELD: dac (type=uint)   REQUIRED CONSTANT FIELD
    bvList.append(binary.setBitVectorSize(BitVector(intVal=366)))

    ### FIELD: unavail_uint (type=uint)
    if 'unavail_uint' in params:
        bvList.append(
            binary.setBitVectorSize(BitVector(intVal=param[unavail_uint]), 2))
    else:
        bvList.append(binary.setBitVectorSize(BitVector(intVal=3), 2))

    ### FIELD: uint (type=uint)
    if 'uint' in params:
        bvList.append(binary.setBitVectorSize(BitVector(intVal=param[uint]),
                                              2))
    else:
        bvList.append(BitVector(size=2))
    return binary.joinBV(bvList)
Пример #3
0
def encode(params, validate=False):
    '''Create a alltypesmsg binary message payload to pack into an AIS Msg alltypesmsg.

    Fields in params:
      - dac(uint): Designated Area Code (field automatically set to "366")
      - reqDecimal(decimal): required decimal value... FIX: scale or no? (field automatically set to "122")
      - unavail_uint(uint): Unavailable unsigned integer
      - anUInt(uint): NO unavailable unsigned integer
      - anInt(int): NO unavailable signed integer
      - aBool(bool): Simple bool
      - aStr(aisstr6): An ais string of 5 characters
      - anUDecimal(udecimal): An unsigned decimal.  Allow smaller numbers
      - aDecimal(decimal): A decimal
      - aFloat(float): An IEEE floating point number
    @param params: Dictionary of field names/values.  Throws a ValueError exception if required is missing
    @param validate: Set to true to cause checking to occur.  Runs slower.  FIX: not implemented.
    @rtype: BitVector
    @return: encoded binary message (for binary messages, this needs to be wrapped in a msg 8
    @note: The returned bits may not be 6 bit aligned.  It is up to you to pad out the bits.
    '''

    bvList = []
    bvList.append(binary.setBitVectorSize(BitVector(intVal=366), 16))
    bvList.append(binary.bvFromSignedInt(122, 8))
    if 'unavail_uint' in params:
        bvList.append(
            binary.setBitVectorSize(BitVector(intVal=params['unavail_uint']),
                                    2))
    else:
        bvList.append(binary.setBitVectorSize(BitVector(intVal=3), 2))
    bvList.append(
        binary.setBitVectorSize(BitVector(intVal=params['anUInt']), 2))
    bvList.append(binary.bvFromSignedInt(params['anInt'], 3))
    if params["aBool"]: bvList.append(TrueBV)
    else: bvList.append(FalseBV)
    bvList.append(aisstring.encode(params['aStr'], 30))
    bvList.append(
        binary.setBitVectorSize(
            BitVector(intVal=int((Decimal(params['anUDecimal']) *
                                  Decimal('10')))), 16))
    bvList.append(
        binary.bvFromSignedInt(
            int(Decimal(params['aDecimal']) * Decimal('10')), 16))
    bvList.append(binary.float2bitvec(params['aFloat']))

    return binary.joinBV(bvList)
Пример #4
0
def encode(params, validate=False):
    '''Create a bin_broadcast binary message payload to pack into an AIS Msg bin_broadcast.

    Fields in params:
      - MessageID(uint): AIS message number.  Must be 8 (field automatically set to "8")
      - RepeatIndicator(uint): Indicated how many times a message has been repeated
      - UserID(uint): Unique ship identification number (MMSI)
      - Spare(uint): Reserved for definition by a regional authority. (field automatically set to "0")
      - dac(uint): Appid designated area code (country)
      - fi(uint): Appid functional identifier
      - BinaryData(binary): Bits for a binary broadcast message
    @param params: Dictionary of field names/values.  Throws a ValueError exception if required is missing
    @param validate: Set to true to cause checking to occur.  Runs slower.  FIX: not implemented.
    @rtype: BitVector
    @return: encoded binary message (for binary messages, this needs to be wrapped in a msg 8
    @note: The returned bits may not be 6 bit aligned.  It is up to you to pad out the bits.
    '''

    bvList = []
    bvList.append(binary.setBitVectorSize(BitVector(intVal=8), 6))
    if 'RepeatIndicator' in params:
        bvList.append(
            binary.setBitVectorSize(
                BitVector(intVal=params['RepeatIndicator']), 2))
    else:
        bvList.append(binary.setBitVectorSize(BitVector(intVal=0), 2))
    bvList.append(
        binary.setBitVectorSize(BitVector(intVal=params['UserID']), 30))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=0), 2))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=params['dac']), 10))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=params['fi']), 6))
    bvList.append(params['BinaryData'])

    return binary.joinBV(bvList)
Пример #5
0
def encode(params, validate=False):
    '''Create a sls_waterlevel binary message payload to pack into an AIS Msg sls_waterlevel.

    Fields in params:
      - time_month(uint): Time tag of measurement  month 1..12
      - time_day(uint): Time tag of measurement  day of the month 1..31
      - time_hour(uint): Time tag of measurement  UTC hours 0..23
      - time_min(uint): Time tag of measurement  minutes
      - stationid(aisstr6): Character identifier of the station.  Usually a number.
      - pos_longitude(decimal): Location of measurement  East West location
      - pos_latitude(decimal): Location of measurement  North South location
      - type(uint): How to interpret the water level
      - waterlevel(int): Water level in centimeters
      - datum(uint): What reference datum applies to the value
      - reserved(uint): Reserved bits for future use (field automatically set to "0")
    @param params: Dictionary of field names/values.  Throws a ValueError exception if required is missing
    @param validate: Set to true to cause checking to occur.  Runs slower.  FIX: not implemented.
    @rtype: BitVector
    @return: encoded binary message (for binary messages, this needs to be wrapped in a msg 8
    @note: The returned bits may not be 6 bit aligned.  It is up to you to pad out the bits.
    '''

    bvList = []
    bvList.append(binary.setBitVectorSize(BitVector(intVal=params['time_month']),4))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=params['time_day']),5))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=params['time_hour']),5))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=params['time_min']),6))
    if 'stationid' in params:
        bvList.append(aisstring.encode(params['stationid'],42))
    else:
        bvList.append(aisstring.encode('@@@@@@@',42))
    if 'pos_longitude' in params:
        bvList.append(binary.bvFromSignedInt(int(Decimal(params['pos_longitude'])*Decimal('60000')),25))
    else:
        bvList.append(binary.bvFromSignedInt(10860000,25))
    if 'pos_latitude' in params:
        bvList.append(binary.bvFromSignedInt(int(Decimal(params['pos_latitude'])*Decimal('60000')),24))
    else:
        bvList.append(binary.bvFromSignedInt(5460000,24))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=params['type']),1))
    if 'waterlevel' in params:
        bvList.append(binary.bvFromSignedInt(params['waterlevel'],16))
    else:
        bvList.append(binary.bvFromSignedInt(-32768,16))
    if 'datum' in params:
        bvList.append(binary.setBitVectorSize(BitVector(intVal=params['datum']),2))
    else:
        bvList.append(binary.setBitVectorSize(BitVector(intVal=31),2))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=0),14))

    return binary.joinBV(bvList)
Пример #6
0
def encode(params, validate=False):
    '''Create a abm binary message payload to pack into an AIS Msg abm.

    Fields in params:
      - MessageID(uint): AIS message number.  Must be 6 (field automatically set to "6")
      - RepeatIndicator(uint): Indicated how many times a message has been repeated
      - UserID(uint): Unique ship identification number (MMSI).  Also known as the Source ID
      - SeqNum(uint): Sequence number as described in 5.3.1.  Assigned to each station
      - DestinationID(uint): Unique ship identification number (MMSI).
      - RetransmitFlag(bool): Should the message be restransmitted?
      - Spare(uint): Must be 0 (field automatically set to "0")
      - dac(uint): Appid designated area code (country)
      - fi(uint): Appid functional identifier
      - BinaryData(binary): Bits for a binary broadcast message
    @param params: Dictionary of field names/values.  Throws a ValueError exception if required is missing
    @param validate: Set to true to cause checking to occur.  Runs slower.  FIX: not implemented.
    @rtype: BitVector
    @return: encoded binary message (for binary messages, this needs to be wrapped in a msg 8
    @note: The returned bits may not be 6 bit aligned.  It is up to you to pad out the bits.
    '''

    bvList = []
    bvList.append(binary.setBitVectorSize(BitVector(intVal=6), 6))
    if 'RepeatIndicator' in params:
        bvList.append(
            binary.setBitVectorSize(
                BitVector(intVal=params['RepeatIndicator']), 2))
    else:
        bvList.append(binary.setBitVectorSize(BitVector(intVal=0), 2))
    bvList.append(
        binary.setBitVectorSize(BitVector(intVal=params['UserID']), 30))
    bvList.append(
        binary.setBitVectorSize(BitVector(intVal=params['SeqNum']), 2))
    bvList.append(
        binary.setBitVectorSize(BitVector(intVal=params['DestinationID']), 30))
    if params["RetransmitFlag"]: bvList.append(TrueBV)
    else: bvList.append(FalseBV)
    bvList.append(binary.setBitVectorSize(BitVector(intVal=0), 1))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=params['dac']), 10))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=params['fi']), 6))
    bvList.append(params['BinaryData'])

    return binary.joinBV(bvList)
Пример #7
0
def encode(params, validate=False):
    '''Create a sls_lockschedule binary message payload to pack into an AIS Msg sls_lockschedule.

    Fields in params:
      - vessel(aisstr6): Vessel Name
      - direction(bool): Up bound/Down bound
      - ETA_month(uint): Estimated time of arrival  month 1..12
      - ETA_day(uint): Estimated time of arrival  day of the month 1..31
      - ETA_hour(uint): Estimated time of arrival  UTC hours 0..23
      - ETA_min(uint): Estimated time of arrival  minutes
      - reserved(uint): Reserved bits for future use (field automatically set to "0")
    @param params: Dictionary of field names/values.  Throws a ValueError exception if required is missing
    @param validate: Set to true to cause checking to occur.  Runs slower.  FIX: not implemented.
    @rtype: BitVector
    @return: encoded binary message (for binary messages, this needs to be wrapped in a msg 8
    @note: The returned bits may not be 6 bit aligned.  It is up to you to pad out the bits.
    '''

    bvList = []
    if 'vessel' in params:
        bvList.append(aisstring.encode(params['vessel'], 90))
    else:
        bvList.append(aisstring.encode('@@@@@@@@@@@@@@@', 90))
    if params["direction"]: bvList.append(TrueBV)
    else: bvList.append(FalseBV)
    bvList.append(
        binary.setBitVectorSize(BitVector(intVal=params['ETA_month']), 4))
    bvList.append(
        binary.setBitVectorSize(BitVector(intVal=params['ETA_day']), 5))
    bvList.append(
        binary.setBitVectorSize(BitVector(intVal=params['ETA_hour']), 5))
    bvList.append(
        binary.setBitVectorSize(BitVector(intVal=params['ETA_min']), 6))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=0), 19))

    return binary.joinBV(bvList)
Пример #8
0
def testParams():
    '''Return a params file base on the testvalue tags.
    @rtype: dict
    @return: params based on testvalue tags
    '''
    params = {}
    params['time_month'] = 2
    params['time_day'] = 28
    params['time_hour'] = 23
    params['time_min'] = 45
    params['lockid'] = 'A345678'
    params['pos_longitude'] = Decimal('-122.16328')
    params['pos_latitude'] = Decimal('37.42446')
    params['reserved'] = 0
    params['lockschedules'] = BitVector(bitstring='0001010101010000')

    return params
Пример #9
0
def testParams():
    '''Return a params file base on the testvalue tags.
    @rtype: dict
    @return: params based on testvalue tags
    '''
    params = {}
    params['MessageID'] = 8
    params['RepeatIndicator'] = 1
    params['UserID'] = 1193046
    params['Spare'] = 0
    params['dac'] = 366
    params['fi'] = 42
    params['BinaryData'] = BitVector(
        bitstring=
        '110000101100000111100010010101001110111001101010011011111111100000110001011100001011111111101111111110011001000000010001110'
    )

    return params
Пример #10
0
def testParams():
    '''Return a params file base on the testvalue tags.
    @rtype: dict
    @return: params based on testvalue tags
    '''
    params = {}
    params['MessageID'] = 17
    params['RepeatIndicator'] = 1
    params['UserID'] = 1193046
    params['Spare'] = 0
    params['x'] = Decimal('-122.16')
    params['y'] = Decimal('37.42')
    params['Spare2'] = 0
    params['BinaryData'] = BitVector(
        bitstring=
        '110000101100000111100010010101001110111001101010011011111111100000110001011100001011111111101111111110011001000000010001110'
    )

    return params
Пример #11
0
def encode(params, validate=False):
    '''Create a gnss_correction binary message payload to pack into an AIS Msg gnss_correction.

    Fields in params:
      - MessageID(uint): AIS message number.  Must be 17 (field automatically set to "17")
      - RepeatIndicator(uint): Indicated how many times a message has been repeated
      - UserID(uint): Base station identification number (MMSI)
      - Spare(uint): Reserved for definition by a regional authority. (field automatically set to "0")
      - x(decimal): East West location
      - y(decimal): North South location
      - Spare2(uint): Reserved for definition by a regional authority. (field automatically set to "0")
      - BinaryData(binary): GNSS Differential correction data
    @param params: Dictionary of field names/values.  Throws a ValueError exception if required is missing
    @param validate: Set to true to cause checking to occur.  Runs slower.  FIX: not implemented.
    @rtype: BitVector
    @return: encoded binary message (for binary messages, this needs to be wrapped in a msg 8
    @note: The returned bits may not be 6 bit aligned.  It is up to you to pad out the bits.
    '''

    bvList = []
    bvList.append(binary.setBitVectorSize(BitVector(intVal=17), 6))
    if 'RepeatIndicator' in params:
        bvList.append(
            binary.setBitVectorSize(
                BitVector(intVal=params['RepeatIndicator']), 2))
    else:
        bvList.append(binary.setBitVectorSize(BitVector(intVal=0), 2))
    bvList.append(
        binary.setBitVectorSize(BitVector(intVal=params['UserID']), 30))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=0), 2))
    if 'x' in params:
        bvList.append(
            binary.bvFromSignedInt(int(Decimal(params['x']) * Decimal('600')),
                                   18))
    else:
        bvList.append(binary.bvFromSignedInt(108600, 18))
    if 'y' in params:
        bvList.append(
            binary.bvFromSignedInt(int(Decimal(params['y']) * Decimal('600')),
                                   17))
    else:
        bvList.append(binary.bvFromSignedInt(54600, 17))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=0), 5))
    bvList.append(params['BinaryData'])

    return binary.joinBV(bvList)
Пример #12
0
def encode(params, validate=False):
    '''Create a timed_circular_notice binary message payload to pack into an AIS Msg timed_circular_notice.

    Fields in params:
      - MessageID(uint): AIS message number.  Must be 8 (field automatically set to "8")
      - RepeatIndicator(uint): Indicated how many times a message has been repeated
      - UserID(uint): Unique ship identification number (MMSI)
      - Spare(uint): Reserved for definition by a regional authority. (field automatically set to "0")
      - dac(uint): Designated Area Code - 366 for the United States (field automatically set to "366")
      - fid(uint): Functional IDentifier - 63 (field automatically set to "63")
      - month(uint): Start time of most recent notice  UTC month
      - day(uint): Start time of most recent notice  UTC day of the month 1..31
      - hour(uint): Start time of most recent notice  UTC hours 0..23
      - min(uint): Start time of most recent notice  UTC minutes
      - longitude(decimal): Center of the area/zone  East West location
      - latitude(decimal): Center of the area/zone  North South location
      - timetoexpire(uint): Minutes from the start time until the notice expires.  Max is aprox 23 days
      - radius(udecimal): Distance from center of detection zone (lat/lon above).  Distance in increments of 10 meters
      - areatype(uint): What does this circular area represent
    @param params: Dictionary of field names/values.  Throws a ValueError exception if required is missing
    @param validate: Set to true to cause checking to occur.  Runs slower.  FIX: not implemented.
    @rtype: BitVector
    @return: encoded binary message (for binary messages, this needs to be wrapped in a msg 8
    @note: The returned bits may not be 6 bit aligned.  It is up to you to pad out the bits.
    '''

    bvList = []
    bvList.append(binary.setBitVectorSize(BitVector(intVal=8),6))
    if 'RepeatIndicator' in params:
        bvList.append(binary.setBitVectorSize(BitVector(intVal=params['RepeatIndicator']),2))
    else:
        bvList.append(binary.setBitVectorSize(BitVector(intVal=0),2))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=params['UserID']),30))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=0),2))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=366),10))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=63),6))
    if 'month' in params:
        bvList.append(binary.setBitVectorSize(BitVector(intVal=params['month']),4))
    else:
        bvList.append(binary.setBitVectorSize(BitVector(intVal=0),4))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=params['day']),5))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=params['hour']),5))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=params['min']),6))
    if 'longitude' in params:
        bvList.append(binary.bvFromSignedInt(int(Decimal(params['longitude'])*Decimal('600000')),28))
    else:
        bvList.append(binary.bvFromSignedInt(108600000,28))
    if 'latitude' in params:
        bvList.append(binary.bvFromSignedInt(int(Decimal(params['latitude'])*Decimal('600000')),27))
    else:
        bvList.append(binary.bvFromSignedInt(54600000,27))
    if 'timetoexpire' in params:
        bvList.append(binary.setBitVectorSize(BitVector(intVal=params['timetoexpire']),15))
    else:
        bvList.append(binary.setBitVectorSize(BitVector(intVal=32767),15))
    if 'radius' in params:
        bvList.append(binary.setBitVectorSize(BitVector(intVal=int((Decimal(params['radius'])*Decimal('0.1')))),14))
    else:
        bvList.append(binary.setBitVectorSize(BitVector(intVal=int(16383)),14))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=params['areatype']),8))

    return binary.joinBV(bvList)
Пример #13
0
def encode(params, validate=False):
    '''Create a sls_weatherreport binary message payload to pack into an AIS Msg sls_weatherreport.

    Fields in params:
      - time_month(uint): Time tag of measurement  month 1..12
      - time_day(uint): Time tag of measurement  day of the month 1..31
      - time_hour(uint): Time tag of measurement  UTC hours 0..23
      - time_min(uint): Time tag of measurement  minutes
      - stationid(aisstr6): Character identifier of the station
      - pos_longitude(decimal): Location of measurement  East West location
      - pos_latitude(decimal): Location of measurement  North South location
      - speed(udecimal): Average wind speed
      - gust(udecimal): Wind gust
      - direction(uint): Wind direction
      - atmpressure(udecimal): Atmospheric pressure
      - airtemp(decimal): Air temperature
      - dewpoint(decimal): Dew Point
      - visibility(udecimal): Visibility
      - watertemp(decimal): Water Temperature
      - reserved(uint): Reserved bits for future use (field automatically set to "0")
    @param params: Dictionary of field names/values.  Throws a ValueError exception if required is missing
    @param validate: Set to true to cause checking to occur.  Runs slower.  FIX: not implemented.
    @rtype: BitVector
    @return: encoded binary message (for binary messages, this needs to be wrapped in a msg 8
    @note: The returned bits may not be 6 bit aligned.  It is up to you to pad out the bits.
    '''

    bvList = []
    bvList.append(
        binary.setBitVectorSize(BitVector(intVal=params['time_month']), 4))
    bvList.append(
        binary.setBitVectorSize(BitVector(intVal=params['time_day']), 5))
    bvList.append(
        binary.setBitVectorSize(BitVector(intVal=params['time_hour']), 5))
    bvList.append(
        binary.setBitVectorSize(BitVector(intVal=params['time_min']), 6))
    if 'stationid' in params:
        bvList.append(aisstring.encode(params['stationid'], 42))
    else:
        bvList.append(aisstring.encode('@@@@@@@', 42))
    if 'pos_longitude' in params:
        bvList.append(
            binary.bvFromSignedInt(
                int(Decimal(params['pos_longitude']) * Decimal('60000')), 25))
    else:
        bvList.append(binary.bvFromSignedInt(10860000, 25))
    if 'pos_latitude' in params:
        bvList.append(
            binary.bvFromSignedInt(
                int(Decimal(params['pos_latitude']) * Decimal('60000')), 24))
    else:
        bvList.append(binary.bvFromSignedInt(5460000, 24))
    if 'speed' in params:
        bvList.append(
            binary.setBitVectorSize(
                BitVector(intVal=int((Decimal(params['speed']) *
                                      Decimal('10')))), 10))
    else:
        bvList.append(binary.setBitVectorSize(BitVector(intVal=int(1023)), 10))
    if 'gust' in params:
        bvList.append(
            binary.setBitVectorSize(
                BitVector(intVal=int((Decimal(params['gust']) *
                                      Decimal('10')))), 10))
    else:
        bvList.append(binary.setBitVectorSize(BitVector(intVal=int(1023)), 10))
    if 'direction' in params:
        bvList.append(
            binary.setBitVectorSize(BitVector(intVal=params['direction']), 9))
    else:
        bvList.append(binary.setBitVectorSize(BitVector(intVal=511), 9))
    if 'atmpressure' in params:
        bvList.append(
            binary.setBitVectorSize(
                BitVector(intVal=int((Decimal(params['atmpressure']) *
                                      Decimal('10')))), 14))
    else:
        bvList.append(
            binary.setBitVectorSize(BitVector(intVal=int(163830)), 14))
    if 'airtemp' in params:
        bvList.append(
            binary.bvFromSignedInt(
                int(Decimal(params['airtemp']) * Decimal('10')), 10))
    else:
        bvList.append(binary.bvFromSignedInt(-512, 10))
    if 'dewpoint' in params:
        bvList.append(
            binary.bvFromSignedInt(
                int(Decimal(params['dewpoint']) * Decimal('10')), 10))
    else:
        bvList.append(binary.bvFromSignedInt(-512, 10))
    if 'visibility' in params:
        bvList.append(
            binary.setBitVectorSize(
                BitVector(intVal=int((Decimal(params['visibility']) *
                                      Decimal('10')))), 8))
    else:
        bvList.append(binary.setBitVectorSize(BitVector(intVal=int(255)), 8))
    if 'watertemp' in params:
        bvList.append(
            binary.bvFromSignedInt(
                int(Decimal(params['watertemp']) * Decimal('10')), 10))
    else:
        bvList.append(binary.bvFromSignedInt(-512, 10))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=0), 4))

    return binary.joinBV(bvList)
Пример #14
0
def encode(params, validate=False):
    '''Create a interrogation binary message payload to pack into an AIS Msg interrogation.

    Fields in params:
      - MessageID(uint): AIS message number.  Must be 15 (field automatically set to "15")
      - RepeatIndicator(uint): Indicated how many times a message has been repeated
      - UserID(uint): MMSI number of interrogating station
      - DestID(uint): MMSI number of interrogated station
      - MessageID1(uint): requested message type from interrogated station
      - SlotOffset(uint): requested message type from interrogated station
      - Spare(uint): Not used.  Should be set to zero. Researved for future use. (field automatically set to "0")
      - MessageID12(uint): requested message type from interrogated station
      - SlotOffset12(uint): requested message type from interrogated station
      - Spare2(uint): Not used.  Should be set to zero. Researved for future use. (field automatically set to "0")
      - DestID2(uint): MMSI number of interrogated station
      - MessageID2(uint): requested message type from interrogated station
      - SlotOffset2(uint): requested message type from interrogated station
      - Spare3(uint): Not used.  Should be set to zero. Researved for future use. (field automatically set to "0")
    @param params: Dictionary of field names/values.  Throws a ValueError exception if required is missing
    @param validate: Set to true to cause checking to occur.  Runs slower.  FIX: not implemented.
    @rtype: BitVector
    @return: encoded binary message (for binary messages, this needs to be wrapped in a msg 8
    @note: The returned bits may not be 6 bit aligned.  It is up to you to pad out the bits.
    '''

    bvList = []
    bvList.append(binary.setBitVectorSize(BitVector(intVal=15), 6))
    if 'RepeatIndicator' in params:
        bvList.append(
            binary.setBitVectorSize(
                BitVector(intVal=params['RepeatIndicator']), 2))
    else:
        bvList.append(binary.setBitVectorSize(BitVector(intVal=0), 2))
    bvList.append(
        binary.setBitVectorSize(BitVector(intVal=params['UserID']), 30))
    bvList.append(
        binary.setBitVectorSize(BitVector(intVal=params['DestID']), 30))
    bvList.append(
        binary.setBitVectorSize(BitVector(intVal=params['MessageID1']), 6))
    bvList.append(
        binary.setBitVectorSize(BitVector(intVal=params['SlotOffset']), 6))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=0), 2))
    bvList.append(
        binary.setBitVectorSize(BitVector(intVal=params['MessageID12']), 6))
    bvList.append(
        binary.setBitVectorSize(BitVector(intVal=params['SlotOffset12']), 6))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=0), 2))
    bvList.append(
        binary.setBitVectorSize(BitVector(intVal=params['DestID2']), 30))
    bvList.append(
        binary.setBitVectorSize(BitVector(intVal=params['MessageID2']), 6))
    bvList.append(
        binary.setBitVectorSize(BitVector(intVal=params['SlotOffset2']), 6))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=0), 2))

    return binary.joinBV(bvList)
Пример #15
0
def unsigned_decimal_enc(val, bitSize):
    '''@rtype: BitVector'''
    # FIX: make sure there is no remainder
    bv = BitVector(intVal=int(val))
    return binary.setBitVectorSize(bv, bitSize)
Пример #16
0
def bool_enc(val, bitSize):
    '''@rtype: BitVector'''
    assert (bitSize == 1)
    if val: return BitVector(bitString="0")
    return BitVector(bitString="1")
Пример #17
0
def unsigned_int_enc(val, bitSize):
    '''@rtype: BitVector'''
    bv = BitVector(intVal=val)
    return binary.setBitVectorSize(bv, bitSize)
Пример #18
0
                else:
                    print 'FAILED'
                    success=False

        if not success: sys.exit('Something Failed')
        del success # Hide success from epydoc

        if options.unittest:
                sys.argv = [sys.argv[0]]
                if options.verbose: sys.argv.append('-v')
                unittest.main()


        outfile = sys.stdout
        if None!=options.outputFileName:
                outfile = file(options.outputFileName,'w')

        bv=None
        for msg in args:
            if   'binary'      == options.inputType:  bv = BitVector(bitstring=msg)
            elif 'nmeapayload' == options.inputType:  bv = binary.ais6tobitvec(msg)
            elif 'nmea'        == options.inputType:  bv = binary.ais6tobitvec(msg.split(',')[5])
            else: sys.exit('ERROR: unknown inputType.  Help!')

            #import ais.ais_msg_8 as m8
            #m8dict = m8.decode(bv)
            import ais.waterlevel as wl

            #wl.printFields(wl.decode(m8dict['BinaryData']),out=outfile,format=options.outputType)
            wl.printFields(wl.decode(bv),out=outfile,format=options.outputType)
Пример #19
0
def main():
    from optparse import OptionParser
    parser = OptionParser(usage="%prog [options]")

    parser.add_option('--unit-test',
                      dest='unittest',
                      default=False,
                      action='store_true',
                      help='run the unit tests')
    parser.add_option('-v',
                      '--verbose',
                      dest='verbose',
                      default=False,
                      action='store_true',
                      help='Make the test output verbose')

    # FIX: remove nmea from binary messages.  No way to build the whole packet?
    # FIX: or build the surrounding msg 8 for a broadcast?
    typeChoices = ('binary', 'nmeapayload', 'nmea'
                   )  # FIX: what about a USCG type message?
    parser.add_option('-t',
                      '--type',
                      choices=typeChoices,
                      type='choice',
                      dest='ioType',
                      default='nmeapayload',
                      help='What kind of string to write for encoding (' +
                      ', '.join(typeChoices) + ') [default: %default]')

    outputChoices = ('std', 'html', 'csv', 'sql')
    parser.add_option('-T',
                      '--output-type',
                      choices=outputChoices,
                      type='choice',
                      dest='outputType',
                      default='std',
                      help='What kind of string to output (' +
                      ', '.join(outputChoices) + ') '
                      '[default: %default]')

    parser.add_option(
        '-o',
        '--output',
        dest='outputFileName',
        default=None,
        help='Name of the python file to write [default: stdout]')

    parser.add_option(
        '-f',
        '--fields',
        dest='fieldList',
        default=None,
        action='append',
        choices=fieldList,
        help='Which fields to include in the output.  Currently only for csv '
        'output [default: all]')

    parser.add_option('-p',
                      '--print-csv-field-list',
                      dest='printCsvfieldList',
                      default=False,
                      action='store_true',
                      help='Print the field name for csv')

    parser.add_option('-c',
                      '--sql-create',
                      dest='sqlCreate',
                      default=False,
                      action='store_true',
                      help='Print out an sql create command for the table.')

    parser.add_option('--latex-table',
                      dest='latexDefinitionTable',
                      default=False,
                      action='store_true',
                      help='Print a LaTeX table of the type')

    parser.add_option(
        '--text-table',
        dest='textDefinitionTable',
        default=False,
        action='store_true',
        help='Print delimited table of the type (for Word table importing)')

    parser.add_option('--delimt-text-table',
                      dest='delimTextDefinitionTable',
                      default='    ',
                      help='Delimiter for text table [default: \'%default\'] '
                      '(for Word table importing)')

    dbChoices = ('sqlite', 'postgres')
    parser.add_option('-D',
                      '--db-type',
                      dest='dbType',
                      default='postgres',
                      choices=dbChoices,
                      type='choice',
                      help='What kind of database (' + ', '.join(dbChoices) +
                      ') '
                      '[default: %default]')

    addMsgOptions(parser)

    options, args = parser.parse_args()

    if options.unittest:
        sys.argv = [sys.argv[0]]
        if options.verbose: sys.argv.append('-v')
        unittest.main()

    outfile = sys.stdout
    if None != options.outputFileName:
        outfile = file(options.outputFileName, 'w')

    if options.doEncode:
        # Make sure all non required options are specified.
        if None == options.RepeatIndicatorField:
            parser.error("missing value for RepeatIndicatorField")
        if None == options.UserIDField:
            parser.error("missing value for UserIDField")
        if None == options.reasonField:
            parser.error("missing value for reasonField")
        if None == options.fromField:
            parser.error("missing value for fromField")
        if None == options.toField: parser.error("missing value for toField")
        if None == options.radiusField:
            parser.error("missing value for radiusField")
        if None == options.unitField:
            parser.error("missing value for unitField")
        if None == options.closingdayField:
            parser.error("missing value for closingdayField")
        if None == options.closingmonthField:
            parser.error("missing value for closingmonthField")
        if None == options.fromhourField:
            parser.error("missing value for fromhourField")
        if None == options.fromminField:
            parser.error("missing value for fromminField")
        if None == options.todayField:
            parser.error("missing value for todayField")
        if None == options.tomonthField:
            parser.error("missing value for tomonthField")
        if None == options.tohourField:
            parser.error("missing value for tohourField")
        if None == options.tominField:
            parser.error("missing value for tominField")
    msgDict = {
        'MessageID': '8',
        'RepeatIndicator': options.RepeatIndicatorField,
        'UserID': options.UserIDField,
        'Spare': '0',
        'dac': '1',
        'fid': '11',
        'reason': options.reasonField,
        'from': options.fromField,
        'to': options.toField,
        'radius': options.radiusField,
        'unit': options.unitField,
        'closingday': options.closingdayField,
        'closingmonth': options.closingmonthField,
        'fromhour': options.fromhourField,
        'frommin': options.fromminField,
        'today': options.todayField,
        'tomonth': options.tomonthField,
        'tohour': options.tohourField,
        'tomin': options.tominField,
        'spare2': '0',
    }

    bits = encode(msgDict)
    if 'binary' == options.ioType:
        print str(bits)
    elif 'nmeapayload' == options.ioType:
        # FIX: figure out if this might be necessary at compile time
        bitLen = len(bits)
        if bitLen % 6 != 0:
            bits = bits + BitVector(
                size=(6 - (bitLen % 6)))  # Pad out to multiple of 6
        print binary.bitvectoais6(bits)[0]

    # FIX: Do not emit this option for the binary message payloads.  Does not make sense.
    elif 'nmea' == options.ioType:
        nmea = uscg.create_nmea(bits)
        print nmea
    else:
        sys.exit('ERROR: unknown ioType.  Help!')

        if options.sqlCreate:
            sqlCreateStr(outfile, options.fieldList, dbType=options.dbType)

        if options.latexDefinitionTable:
            latexDefinitionTable(outfile)

        # For conversion to word tables
        if options.textDefinitionTable:
            textDefinitionTable(outfile, options.delimTextDefinitionTable)

        if options.printCsvfieldList:
            # Make a csv separated list of fields that will be displayed for csv
            if None == options.fieldList: options.fieldList = fieldList
            import StringIO
            buf = StringIO.StringIO()
            for field in options.fieldList:
                buf.write(field + ',')
            result = buf.getvalue()
            if result[-1] == ',': print result[:-1]
            else: print result

        if options.doDecode:
            if len(args) == 0: args = sys.stdin
            for msg in args:
                bv = None

                if msg[0] in ('$', '!') and msg[3:6] in ('VDM', 'VDO'):
                    # Found nmea
                    # FIX: do checksum
                    bv = binary.ais6tobitvec(msg.split(',')[5])
                else:  # either binary or nmeapayload... expect mostly nmeapayloads
                    # assumes that an all 0 and 1 string can not be a nmeapayload
                    binaryMsg = True
                    for c in msg:
                        if c not in ('0', '1'):
                            binaryMsg = False
                            break
                    if binaryMsg:
                        bv = BitVector(bitstring=msg)
                    else:  # nmeapayload
                        bv = binary.ais6tobitvec(msg)

                printFields(decode(bv),
                            out=outfile,
                            format=options.outputType,
                            fieldList=options.fieldList,
                            dbType=options.dbType)
Пример #20
0
def encode(params, validate=False):
    '''Create a ChanMngmt binary message payload to pack into an AIS Msg ChanMngmt.

    Fields in params:
      - MessageID(uint): AIS message number.  Must be 22 (field automatically set to "22")
      - RepeatIndicator(uint): Indicated how many times a message has been repeated
      - UserID(uint): Unique ship identification number (MMSI)
      - Spare(uint): Not used.  Should be set to zero. (field automatically set to "0")
      - ChanA(uint): Channel number from ITU-R M.1084 Annex 4
      - ChanB(uint): Channel number from ITU-R M.1084 Annex 4
      - TxRxMode(uint): FIX: find the description
      - power(uint): FIX: put in a description
      - corner1_lon(decimal): north-east corner of area for assignment  longitude of corner
      - corner1_lat(decimal): north-east corner of area for assignment  latitude of corner
      - corner2_lon(decimal): south-west corner of area for assignment  longitude of corner
      - corner2_lat(decimal): south-west corner of area for assignment  latitude of corner
      - IndicatorType(uint): FIX: put in a description
      - ChanABandwidth(uint): FIX: put in a description
      - ChanBBandwidth(uint): FIX: put in a description
      - TransZoneSize(uint): FIX: put in a description
      - Spare2(uint): Not used.  Should be set to zero. (field automatically set to "0")
    @param params: Dictionary of field names/values.  Throws a ValueError exception if required is missing
    @param validate: Set to true to cause checking to occur.  Runs slower.  FIX: not implemented.
    @rtype: BitVector
    @return: encoded binary message (for binary messages, this needs to be wrapped in a msg 8
    @note: The returned bits may not be 6 bit aligned.  It is up to you to pad out the bits.
    '''

    bvList = []
    bvList.append(binary.setBitVectorSize(BitVector(intVal=22),6))
    if 'RepeatIndicator' in params:
        bvList.append(binary.setBitVectorSize(BitVector(intVal=params['RepeatIndicator']),2))
    else:
        bvList.append(binary.setBitVectorSize(BitVector(intVal=0),2))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=params['UserID']),30))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=0),2))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=params['ChanA']),12))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=params['ChanB']),12))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=params['TxRxMode']),4))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=params['power']),1))
    if 'corner1_lon' in params:
        bvList.append(binary.bvFromSignedInt(int(Decimal(params['corner1_lon'])*Decimal('600')),18))
    else:
        bvList.append(binary.bvFromSignedInt(108600,18))
    if 'corner1_lat' in params:
        bvList.append(binary.bvFromSignedInt(int(Decimal(params['corner1_lat'])*Decimal('600')),17))
    else:
        bvList.append(binary.bvFromSignedInt(108600,17))
    if 'corner2_lon' in params:
        bvList.append(binary.bvFromSignedInt(int(Decimal(params['corner2_lon'])*Decimal('600')),18))
    else:
        bvList.append(binary.bvFromSignedInt(108600,18))
    if 'corner2_lat' in params:
        bvList.append(binary.bvFromSignedInt(int(Decimal(params['corner2_lat'])*Decimal('600')),17))
    else:
        bvList.append(binary.bvFromSignedInt(108600,17))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=params['IndicatorType']),1))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=params['ChanABandwidth']),1))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=params['ChanBBandwidth']),1))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=params['TransZoneSize']),3))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=0),23))

    return binary.joinBV(bvList)
Пример #21
0
def encode(params, validate=False):
    '''Create a whalenotice binary message payload to pack into an AIS Msg whalenotice.

    Fields in params:
      - MessageID(uint): AIS message number.  Must be 8 (field automatically set to "8")
      - RepeatIndicator(uint): Indicated how many times a message has been repeated
      - UserID(uint): Unique ship identification number (MMSI)
      - Spare(uint): Reserved for definition by a regional authority. (field automatically set to "0")
      - dac(uint): Designated Area Code - 366 for the United States (field automatically set to "366")
      - fid(uint): Functional IDentifier - 63 for the Whale Notice (field automatically set to "63")
      - efid(uint): Extended Functional IDentifier.  1 for the Whale Notice (dac+fid+efid defines the exact message type) (field automatically set to "1")
      - month(uint): Time of most recent whale detection.  UTC month 1..12
      - day(uint): Time of most recent whale detection.  UTC day of the month 1..31
      - hour(uint): Time of most recent whale detection.  UTC hours 0..23
      - min(uint): Time of most recent whale detection.  UTC minutes
      - sec(uint): Time of most recent whale detection.  UTC seconds
      - stationid(aisstr6): Identifier of the station that detected the whale.  (e.g. which buoy)
      - longitude(decimal): Center of the detection zone.  East West location
      - latitude(decimal): Center of the detection zone.  North South location
      - timetoexpire(uint): Seconds from the detection time until the notice expires
      - radius(uint): Distance from center of detection zone (lat/lon above)
    @param params: Dictionary of field names/values.  Throws a ValueError exception if required is missing
    @param validate: Set to true to cause checking to occur.  Runs slower.  FIX: not implemented.
    @rtype: BitVector
    @return: encoded binary message (for binary messages, this needs to be wrapped in a msg 8
    @note: The returned bits may not be 6 bit aligned.  It is up to you to pad out the bits.
    '''

    bvList = []
    bvList.append(binary.setBitVectorSize(BitVector(intVal=8), 6))
    if 'RepeatIndicator' in params:
        bvList.append(
            binary.setBitVectorSize(
                BitVector(intVal=params['RepeatIndicator']), 2))
    else:
        bvList.append(binary.setBitVectorSize(BitVector(intVal=0), 2))
    bvList.append(
        binary.setBitVectorSize(BitVector(intVal=params['UserID']), 30))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=0), 2))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=366), 10))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=63), 6))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=1), 12))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=params['month']),
                                          4))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=params['day']), 5))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=params['hour']), 5))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=params['min']), 6))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=params['sec']), 6))
    if 'stationid' in params:
        bvList.append(aisstring.encode(params['stationid'], 42))
    else:
        bvList.append(aisstring.encode('@@@@@@@', 42))
    if 'longitude' in params:
        bvList.append(
            binary.bvFromSignedInt(
                int(Decimal(params['longitude']) * Decimal('600000')), 28))
    else:
        bvList.append(binary.bvFromSignedInt(108600000, 28))
    if 'latitude' in params:
        bvList.append(
            binary.bvFromSignedInt(
                int(Decimal(params['latitude']) * Decimal('600000')), 27))
    else:
        bvList.append(binary.bvFromSignedInt(54600000, 27))
    if 'timetoexpire' in params:
        bvList.append(
            binary.setBitVectorSize(BitVector(intVal=params['timetoexpire']),
                                    16))
    else:
        bvList.append(binary.setBitVectorSize(BitVector(intVal=0), 16))
    if 'radius' in params:
        bvList.append(
            binary.setBitVectorSize(BitVector(intVal=params['radius']), 16))
    else:
        bvList.append(binary.setBitVectorSize(BitVector(intVal=65534), 16))

    return binary.joinBV(bvList)
Пример #22
0
 TODO(schwehr):FIX: put in a description of the message here with fields and types.
"""
import sys
from decimal import Decimal
import unittest

from aisutils.BitVector import BitVector

from aisutils import aisstring
from aisutils import binary
from aisutils import sqlhelp
from aisutils import uscg

# FIX: check to see if these will be needed
TrueBV = BitVector(bitstring="1")
"Why always rebuild the True bit?  This should speed things up a bunch"
FalseBV = BitVector(bitstring="0")
"Why always rebuild the False bit?  This should speed things up a bunch"

fieldList = (
    'MessageID',
    'RepeatIndicator',
    'UserID',
    'Spare',
    'dac',
    'fid',
    'reason',
    'from',
    'to',
    'radius',
Пример #23
0
        msgDict = ais_msg_8.bin_broadcastDecode(bv)
        ais_msg_8.bin_broadcastPrintFields(msgDict)

        bv = bv[39:]

        print 'dac: ', bv[:10], int(bv[:10])
        bv = bv[10:]
        print 'fid: ', bv[:6], int(bv[:6])
        bv = bv[6:]
        print 'bits:', bv[:16], int(bv[:10])
        bv = bv[10:]
        print 'len: ', len(bv)

    # Position message
    if False:
        nmeaStr = '!AIVDM,1,1,,B,15Mt9B001;rgAFhGKLaRK1v2040@,0*2A'
        msgPayload = nmeaStr.split(',')[5]
        print 'nmea string:    ', nmeaStr
        print 'message payload:', msgPayload
        bv = binary.ais6tobitvec(msgPayload)
        msgDict = ais_msg_1.positionDecode(bv)
        ais_msg_1.positionPrint(msgDict)

    # SLS try for waterlevel
    if True:
        bvStr = '010111101000001000100101000001010100110101001100011000001000000000110001100101110101000000001001010011101101000000000000001000000100000000000000'
        bv = BitVector(bitstring=bvStr)
        print type(bv)
        msgDict = sls.waterlevel.decode(bv)
        sls.waterlevel.printFields(msgDict)
Пример #24
0
def encode(params, validate=False):
    '''Create a imo_fairway_closed binary message payload to pack into an AIS Msg imo_fairway_closed.

    Fields in params:
      - MessageID(uint): AIS message number.  Must be 8 (field automatically set to "8")
      - RepeatIndicator(uint): Indicated how many times a message has been repeated
      - UserID(uint): MMSI number of transmitter broadcasting the message
      - Spare(uint): Reserved for definition by a regional authority. (field automatically set to "0")
      - dac(uint): Designated Area Code - part 1 of the IAI (field automatically set to "1")
      - fid(uint): Functional Identifier - part 2 of the IAI (field automatically set to "11")
      - reason(aisstr6): Reason for closing
      - from(aisstr6): Location of closing from
      - to(aisstr6): Location of closing To
      - radius(uint): Extention of closed area
      - unit(uint): Unit of extension value for range field
      - closingday(uint): Closing from day
      - closingmonth(uint): Closing from month
      - fromhour(uint): From LT hour (appr)
      - frommin(uint): From LT minute (appr)
      - today(uint): To day
      - tomonth(uint): To month
      - tohour(uint): To LT hour (appr)
      - tomin(uint): To LT minute (appr)
      - spare2(uint): Padding out the slot (field automatically set to "0")
    @param params: Dictionary of field names/values.  Throws a ValueError exception if required is missing
    @param validate: Set to true to cause checking to occur.  Runs slower.  FIX: not implemented.
    @rtype: BitVector
    @return: encoded binary message (for binary messages, this needs to be wrapped in a msg 8
    @note: The returned bits may not be 6 bit aligned.  It is up to you to pad out the bits.
    '''

    bvList = []
    bvList.append(binary.setBitVectorSize(BitVector(intVal=8), 6))
    if 'RepeatIndicator' in params:
        bvList.append(
            binary.setBitVectorSize(
                BitVector(intVal=params['RepeatIndicator']), 2))
    else:
        bvList.append(binary.setBitVectorSize(BitVector(intVal=0), 2))
    bvList.append(
        binary.setBitVectorSize(BitVector(intVal=params['UserID']), 30))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=0), 2))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=1), 10))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=11), 6))
    if 'reason' in params:
        bvList.append(aisstring.encode(params['reason'], 120))
    else:
        bvList.append(aisstring.encode('@@@@@@@@@@@@@@@@@@@@', 120))
    if 'from' in params:
        bvList.append(aisstring.encode(params['from'], 120))
    else:
        bvList.append(aisstring.encode('@@@@@@@@@@@@@@@@@@@@', 120))
    if 'to' in params:
        bvList.append(aisstring.encode(params['to'], 120))
    else:
        bvList.append(aisstring.encode('@@@@@@@@@@@@@@@@@@@@', 120))
    if 'radius' in params:
        bvList.append(
            binary.setBitVectorSize(BitVector(intVal=params['radius']), 10))
    else:
        bvList.append(binary.setBitVectorSize(BitVector(intVal=1001), 10))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=params['unit']), 2))
    bvList.append(
        binary.setBitVectorSize(BitVector(intVal=params['closingday']), 5))
    bvList.append(
        binary.setBitVectorSize(BitVector(intVal=params['closingmonth']), 4))
    bvList.append(
        binary.setBitVectorSize(BitVector(intVal=params['fromhour']), 5))
    bvList.append(
        binary.setBitVectorSize(BitVector(intVal=params['frommin']), 6))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=params['today']),
                                          5))
    bvList.append(
        binary.setBitVectorSize(BitVector(intVal=params['tomonth']), 4))
    bvList.append(
        binary.setBitVectorSize(BitVector(intVal=params['tohour']), 5))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=params['tomin']),
                                          6))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=0), 4))

    return binary.joinBV(bvList)
Пример #25
0
def encode(params, validate=False):
    '''Create a waterlevel binary message payload to pack into an AIS Msg waterlevel.

    Fields in params:
      - MessageID(uint): AIS message number.  Must be 8 (field automatically set to "8")
      - RepeatIndicator(uint): Indicated how many times a message has been repeated
      - UserID(uint): Unique ship identification number (MMSI)
      - Spare(uint): Reserved for definition by a regional authority. (field automatically set to "0")
      - dac(uint): Designated Area Code (field automatically set to "366")
      - fid(uint): Functional Identifier (field automatically set to "63")
      - month(uint): Time the measurement represents  month 1..12
      - day(uint): Time the measurement represents  day of the month 1..31
      - hour(uint): Time the measurement represents  UTC hours 0..23
      - min(uint): Time the measurement represents  minutes
      - stationid(aisstr6): Character identifier of the station.  Usually a number.
      - waterlevel(int): Water level in centimeters
      - datum(uint): What reference datum applies to the value
      - sigma(uint): Standard deviation of 1 second samples used to compute the water level height.  FIX: is this the correct description of sigma?
      - source(uint): How the water level was derived
    @param params: Dictionary of field names/values.  Throws a ValueError exception if required is missing
    @param validate: Set to true to cause checking to occur.  Runs slower.  FIX: not implemented.
    @rtype: BitVector
    @return: encoded binary message (for binary messages, this needs to be wrapped in a msg 8
    @note: The returned bits may not be 6 bit aligned.  It is up to you to pad out the bits.
    '''

    bvList = []
    bvList.append(binary.setBitVectorSize(BitVector(intVal=8), 6))
    if 'RepeatIndicator' in params:
        bvList.append(
            binary.setBitVectorSize(
                BitVector(intVal=params['RepeatIndicator']), 2))
    else:
        bvList.append(binary.setBitVectorSize(BitVector(intVal=0), 2))
    bvList.append(
        binary.setBitVectorSize(BitVector(intVal=params['UserID']), 30))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=0), 2))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=366), 10))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=63), 6))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=params['month']),
                                          4))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=params['day']), 5))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=params['hour']), 5))
    bvList.append(binary.setBitVectorSize(BitVector(intVal=params['min']), 6))
    if 'stationid' in params:
        bvList.append(aisstring.encode(params['stationid'], 42))
    else:
        bvList.append(aisstring.encode('@@@@@@@', 42))
    if 'waterlevel' in params:
        bvList.append(binary.bvFromSignedInt(params['waterlevel'], 16))
    else:
        bvList.append(binary.bvFromSignedInt(-32768, 16))
    if 'datum' in params:
        bvList.append(
            binary.setBitVectorSize(BitVector(intVal=params['datum']), 5))
    else:
        bvList.append(binary.setBitVectorSize(BitVector(intVal=31), 5))
    if 'sigma' in params:
        bvList.append(
            binary.setBitVectorSize(BitVector(intVal=params['sigma']), 7))
    else:
        bvList.append(binary.setBitVectorSize(BitVector(intVal=127), 7))
    if 'source' in params:
        bvList.append(
            binary.setBitVectorSize(BitVector(intVal=params['source']), 3))
    else:
        bvList.append(binary.setBitVectorSize(BitVector(intVal=0), 3))

    return binary.joinBV(bvList)