INSTRUCTION
stringlengths 1
46.3k
| RESPONSE
stringlengths 75
80.2k
|
---|---|
Check if the status bit and field bits are consistency. This Function
is used for checking BDS code versions.
|
def wrongstatus(data, sb, msb, lsb):
"""Check if the status bit and field bits are consistency. This Function
is used for checking BDS code versions.
"""
# status bit, most significant bit, least significant bit
status = int(data[sb-1])
value = bin2int(data[msb-1:lsb])
if not status:
if value != 0:
return True
return False
|
Check if a message is likely to be BDS code 2,0
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
bool: True or False
|
def is30(msg):
"""Check if a message is likely to be BDS code 2,0
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
bool: True or False
"""
if allzeros(msg):
return False
d = hex2bin(data(msg))
if d[0:8] != '00110000':
return False
# threat type 3 not assigned
if d[28:30] == '11':
return False
# reserved for ACAS III, in far future
if bin2int(d[15:22]) >= 48:
return False
return True
|
Decode position from a pair of even and odd position message
(works with both airborne and surface position messages)
Args:
msg0 (string): even message (28 bytes hexadecimal string)
msg1 (string): odd message (28 bytes hexadecimal string)
t0 (int): timestamps for the even message
t1 (int): timestamps for the odd message
Returns:
(float, float): (latitude, longitude) of the aircraft
|
def position(msg0, msg1, t0, t1, lat_ref=None, lon_ref=None):
"""Decode position from a pair of even and odd position message
(works with both airborne and surface position messages)
Args:
msg0 (string): even message (28 bytes hexadecimal string)
msg1 (string): odd message (28 bytes hexadecimal string)
t0 (int): timestamps for the even message
t1 (int): timestamps for the odd message
Returns:
(float, float): (latitude, longitude) of the aircraft
"""
tc0 = typecode(msg0)
tc1 = typecode(msg1)
if (5<=tc0<=8 and 5<=tc1<=8):
if (not lat_ref) or (not lon_ref):
raise RuntimeError("Surface position encountered, a reference \
position lat/lon required. Location of \
receiver can be used.")
else:
return surface_position(msg0, msg1, t0, t1, lat_ref, lon_ref)
elif (9<=tc0<=18 and 9<=tc1<=18):
# Airborne position with barometric height
return airborne_position(msg0, msg1, t0, t1)
elif (20<=tc0<=22 and 20<=tc1<=22):
# Airborne position with GNSS height
return airborne_position(msg0, msg1, t0, t1)
else:
raise RuntimeError("incorrect or inconsistant message types")
|
Decode position with only one message,
knowing reference nearby location, such as previously
calculated location, ground station, or airport location, etc.
Works with both airborne and surface position messages.
The reference position shall be with in 180NM (airborne) or 45NM (surface)
of the true position.
Args:
msg (string): even message (28 bytes hexadecimal string)
lat_ref: previous known latitude
lon_ref: previous known longitude
Returns:
(float, float): (latitude, longitude) of the aircraft
|
def position_with_ref(msg, lat_ref, lon_ref):
"""Decode position with only one message,
knowing reference nearby location, such as previously
calculated location, ground station, or airport location, etc.
Works with both airborne and surface position messages.
The reference position shall be with in 180NM (airborne) or 45NM (surface)
of the true position.
Args:
msg (string): even message (28 bytes hexadecimal string)
lat_ref: previous known latitude
lon_ref: previous known longitude
Returns:
(float, float): (latitude, longitude) of the aircraft
"""
tc = typecode(msg)
if 5<=tc<=8:
return surface_position_with_ref(msg, lat_ref, lon_ref)
elif 9<=tc<=18 or 20<=tc<=22:
return airborne_position_with_ref(msg, lat_ref, lon_ref)
else:
raise RuntimeError("incorrect or inconsistant message types")
|
Decode aircraft altitude
Args:
msg (string): 28 bytes hexadecimal message string
Returns:
int: altitude in feet
|
def altitude(msg):
"""Decode aircraft altitude
Args:
msg (string): 28 bytes hexadecimal message string
Returns:
int: altitude in feet
"""
tc = typecode(msg)
if tc<5 or tc==19 or tc>22:
raise RuntimeError("%s: Not a position message" % msg)
if tc>=5 and tc<=8:
# surface position, altitude 0
return 0
msgbin = common.hex2bin(msg)
q = msgbin[47]
if q:
n = common.bin2int(msgbin[40:47]+msgbin[48:52])
alt = n * 25 - 1000
return alt
else:
return None
|
Calculate the speed, heading, and vertical rate
(handles both airborne or surface message)
Args:
msg (string): 28 bytes hexadecimal message string
Returns:
(int, float, int, string): speed (kt), ground track or heading (degree),
rate of climb/descend (ft/min), and speed type
('GS' for ground speed, 'AS' for airspeed)
|
def velocity(msg):
"""Calculate the speed, heading, and vertical rate
(handles both airborne or surface message)
Args:
msg (string): 28 bytes hexadecimal message string
Returns:
(int, float, int, string): speed (kt), ground track or heading (degree),
rate of climb/descend (ft/min), and speed type
('GS' for ground speed, 'AS' for airspeed)
"""
if 5 <= typecode(msg) <= 8:
return surface_velocity(msg)
elif typecode(msg) == 19:
return airborne_velocity(msg)
else:
raise RuntimeError("incorrect or inconsistant message types, expecting 4<TC<9 or TC=19")
|
Get speed and ground track (or heading) from the velocity message
(handles both airborne or surface message)
Args:
msg (string): 28 bytes hexadecimal message string
Returns:
(int, float): speed (kt), ground track or heading (degree)
|
def speed_heading(msg):
"""Get speed and ground track (or heading) from the velocity message
(handles both airborne or surface message)
Args:
msg (string): 28 bytes hexadecimal message string
Returns:
(int, float): speed (kt), ground track or heading (degree)
"""
spd, trk_or_hdg, rocd, tag = velocity(msg)
return spd, trk_or_hdg
|
ADS-B Version
Args:
msg (string): 28 bytes hexadecimal message string, TC = 31
Returns:
int: version number
|
def version(msg):
"""ADS-B Version
Args:
msg (string): 28 bytes hexadecimal message string, TC = 31
Returns:
int: version number
"""
tc = typecode(msg)
if tc != 31:
raise RuntimeError("%s: Not a status operation message, expecting TC = 31" % msg)
msgbin = common.hex2bin(msg)
version = common.bin2int(msgbin[72:75])
return version
|
Calculate NUCp, Navigation Uncertainty Category - Position (ADS-B version 1)
Args:
msg (string): 28 bytes hexadecimal message string,
Returns:
int: Horizontal Protection Limit
int: 95% Containment Radius - Horizontal (meters)
int: 95% Containment Radius - Vertical (meters)
|
def nuc_p(msg):
"""Calculate NUCp, Navigation Uncertainty Category - Position (ADS-B version 1)
Args:
msg (string): 28 bytes hexadecimal message string,
Returns:
int: Horizontal Protection Limit
int: 95% Containment Radius - Horizontal (meters)
int: 95% Containment Radius - Vertical (meters)
"""
tc = typecode(msg)
if typecode(msg) < 5 or typecode(msg) > 22:
raise RuntimeError(
"%s: Not a surface position message (5<TC<8), \
airborne position message (8<TC<19), \
or airborne position with GNSS height (20<TC<22)" % msg
)
try:
NUCp = uncertainty.TC_NUCp_lookup[tc]
HPL = uncertainty.NUCp[NUCp]['HPL']
RCu = uncertainty.NUCp[NUCp]['RCu']
RCv = uncertainty.NUCp[NUCp]['RCv']
except KeyError:
HPL, RCu, RCv = uncertainty.NA, uncertainty.NA, uncertainty.NA
if tc in [20, 21]:
RCv = uncertainty.NA
return HPL, RCu, RCv
|
Calculate NUCv, Navigation Uncertainty Category - Velocity (ADS-B version 1)
Args:
msg (string): 28 bytes hexadecimal message string,
Returns:
int or string: 95% Horizontal Velocity Error
int or string: 95% Vertical Velocity Error
|
def nuc_v(msg):
"""Calculate NUCv, Navigation Uncertainty Category - Velocity (ADS-B version 1)
Args:
msg (string): 28 bytes hexadecimal message string,
Returns:
int or string: 95% Horizontal Velocity Error
int or string: 95% Vertical Velocity Error
"""
tc = typecode(msg)
if tc != 19:
raise RuntimeError("%s: Not an airborne velocity message, expecting TC = 19" % msg)
msgbin = common.hex2bin(msg)
NUCv = common.bin2int(msgbin[42:45])
try:
HVE = uncertainty.NUCv[NUCv]['HVE']
VVE = uncertainty.NUCv[NUCv]['VVE']
except KeyError:
HVE, VVE = uncertainty.NA, uncertainty.NA
return HVE, VVE
|
Calculate NIC, navigation integrity category, for ADS-B version 1
Args:
msg (string): 28 bytes hexadecimal message string
NICs (int or string): NIC supplement
Returns:
int or string: Horizontal Radius of Containment
int or string: Vertical Protection Limit
|
def nic_v1(msg, NICs):
"""Calculate NIC, navigation integrity category, for ADS-B version 1
Args:
msg (string): 28 bytes hexadecimal message string
NICs (int or string): NIC supplement
Returns:
int or string: Horizontal Radius of Containment
int or string: Vertical Protection Limit
"""
if typecode(msg) < 5 or typecode(msg) > 22:
raise RuntimeError(
"%s: Not a surface position message (5<TC<8), \
airborne position message (8<TC<19), \
or airborne position with GNSS height (20<TC<22)" % msg
)
tc = typecode(msg)
NIC = uncertainty.TC_NICv1_lookup[tc]
if isinstance(NIC, dict):
NIC = NIC[NICs]
try:
Rc = uncertainty.NICv1[NIC][NICs]['Rc']
VPL = uncertainty.NICv1[NIC][NICs]['VPL']
except KeyError:
Rc, VPL = uncertainty.NA, uncertainty.NA
return Rc, VPL
|
Calculate NIC, navigation integrity category, for ADS-B version 2
Args:
msg (string): 28 bytes hexadecimal message string
NICa (int or string): NIC supplement - A
NICbc (int or srting): NIC supplement - B or C
Returns:
int or string: Horizontal Radius of Containment
|
def nic_v2(msg, NICa, NICbc):
"""Calculate NIC, navigation integrity category, for ADS-B version 2
Args:
msg (string): 28 bytes hexadecimal message string
NICa (int or string): NIC supplement - A
NICbc (int or srting): NIC supplement - B or C
Returns:
int or string: Horizontal Radius of Containment
"""
if typecode(msg) < 5 or typecode(msg) > 22:
raise RuntimeError(
"%s: Not a surface position message (5<TC<8), \
airborne position message (8<TC<19), \
or airborne position with GNSS height (20<TC<22)" % msg
)
tc = typecode(msg)
NIC = uncertainty.TC_NICv2_lookup[tc]
if 20<=tc<=22:
NICs = 0
else:
NICs = NICa*2 + NICbc
try:
if isinstance(NIC, dict):
NIC = NIC[NICs]
Rc = uncertainty.NICv2[NIC][NICs]['Rc']
except KeyError:
Rc = uncertainty.NA
return Rc
|
Obtain NIC supplement bit, TC=31 message
Args:
msg (string): 28 bytes hexadecimal message string
Returns:
int: NICs number (0 or 1)
|
def nic_s(msg):
"""Obtain NIC supplement bit, TC=31 message
Args:
msg (string): 28 bytes hexadecimal message string
Returns:
int: NICs number (0 or 1)
"""
tc = typecode(msg)
if tc != 31:
raise RuntimeError("%s: Not a status operation message, expecting TC = 31" % msg)
msgbin = common.hex2bin(msg)
nic_s = int(msgbin[75])
return nic_s
|
Obtain NICa/c, navigation integrity category supplements a and c
Args:
msg (string): 28 bytes hexadecimal message string
Returns:
(int, int): NICa and NICc number (0 or 1)
|
def nic_a_c(msg):
"""Obtain NICa/c, navigation integrity category supplements a and c
Args:
msg (string): 28 bytes hexadecimal message string
Returns:
(int, int): NICa and NICc number (0 or 1)
"""
tc = typecode(msg)
if tc != 31:
raise RuntimeError("%s: Not a status operation message, expecting TC = 31" % msg)
msgbin = common.hex2bin(msg)
nic_a = int(msgbin[75])
nic_c = int(msgbin[51])
return nic_a, nic_c
|
Obtain NICb, navigation integrity category supplement-b
Args:
msg (string): 28 bytes hexadecimal message string
Returns:
int: NICb number (0 or 1)
|
def nic_b(msg):
"""Obtain NICb, navigation integrity category supplement-b
Args:
msg (string): 28 bytes hexadecimal message string
Returns:
int: NICb number (0 or 1)
"""
tc = typecode(msg)
if tc < 9 or tc > 18:
raise RuntimeError("%s: Not a airborne position message, expecting 8<TC<19" % msg)
msgbin = common.hex2bin(msg)
nic_b = int(msgbin[39])
return nic_b
|
Calculate NACp, Navigation Accuracy Category - Position
Args:
msg (string): 28 bytes hexadecimal message string, TC = 29 or 31
Returns:
int or string: 95% horizontal accuracy bounds, Estimated Position Uncertainty
int or string: 95% vertical accuracy bounds, Vertical Estimated Position Uncertainty
|
def nac_p(msg):
"""Calculate NACp, Navigation Accuracy Category - Position
Args:
msg (string): 28 bytes hexadecimal message string, TC = 29 or 31
Returns:
int or string: 95% horizontal accuracy bounds, Estimated Position Uncertainty
int or string: 95% vertical accuracy bounds, Vertical Estimated Position Uncertainty
"""
tc = typecode(msg)
if tc not in [29, 31]:
raise RuntimeError("%s: Not a target state and status message, \
or operation status message, expecting TC = 29 or 31" % msg)
msgbin = common.hex2bin(msg)
if tc == 29:
NACp = common.bin2int(msgbin[71:75])
elif tc == 31:
NACp = common.bin2int(msgbin[76:80])
try:
EPU = uncertainty.NACp[NACp]['EPU']
VEPU = uncertainty.NACp[NACp]['VEPU']
except KeyError:
EPU, VEPU = uncertainty.NA, uncertainty.NA
return EPU, VEPU
|
Calculate NACv, Navigation Accuracy Category - Velocity
Args:
msg (string): 28 bytes hexadecimal message string, TC = 19
Returns:
int or string: 95% horizontal accuracy bounds for velocity, Horizontal Figure of Merit
int or string: 95% vertical accuracy bounds for velocity, Vertical Figure of Merit
|
def nac_v(msg):
"""Calculate NACv, Navigation Accuracy Category - Velocity
Args:
msg (string): 28 bytes hexadecimal message string, TC = 19
Returns:
int or string: 95% horizontal accuracy bounds for velocity, Horizontal Figure of Merit
int or string: 95% vertical accuracy bounds for velocity, Vertical Figure of Merit
"""
tc = typecode(msg)
if tc != 19:
raise RuntimeError("%s: Not an airborne velocity message, expecting TC = 19" % msg)
msgbin = common.hex2bin(msg)
NACv = common.bin2int(msgbin[42:45])
try:
HFOMr = uncertainty.NACv[NACv]['HFOMr']
VFOMr = uncertainty.NACv[NACv]['VFOMr']
except KeyError:
HFOMr, VFOMr = uncertainty.NA, uncertainty.NA
return HFOMr, VFOMr
|
Calculate SIL, Surveillance Integrity Level
Args:
msg (string): 28 bytes hexadecimal message string with TC = 29, 31
Returns:
int or string: Probability of exceeding Horizontal Radius of Containment RCu
int or string: Probability of exceeding Vertical Integrity Containment Region VPL
string: SIL supplement based on per "hour" or "sample", or 'unknown'
|
def sil(msg, version):
"""Calculate SIL, Surveillance Integrity Level
Args:
msg (string): 28 bytes hexadecimal message string with TC = 29, 31
Returns:
int or string: Probability of exceeding Horizontal Radius of Containment RCu
int or string: Probability of exceeding Vertical Integrity Containment Region VPL
string: SIL supplement based on per "hour" or "sample", or 'unknown'
"""
tc = typecode(msg)
if tc not in [29, 31]:
raise RuntimeError("%s: Not a target state and status messag, \
or operation status message, expecting TC = 29 or 31" % msg)
msgbin = common.hex2bin(msg)
if tc == 29:
SIL = common.bin2int(msgbin[76:78])
elif tc == 31:
SIL = common.bin2int(msgbin[82:84])
try:
PE_RCu = uncertainty.SIL[SIL]['PE_RCu']
PE_VPL = uncertainty.SIL[SIL]['PE_VPL']
except KeyError:
PE_RCu, PE_VPL = uncertainty.NA, uncertainty.NA
base = 'unknown'
if version == 2:
if tc == 29:
SIL_SUP = common.bin2int(msgbin[39])
elif tc == 31:
SIL_SUP = common.bin2int(msgbin[86])
if SIL_SUP == 0:
base = "hour"
elif SIL_SUP == 1:
base = "sample"
return PE_RCu, PE_VPL, base
|
Check if a message is likely to be BDS code 5,0
(Track and turn report)
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
bool: True or False
|
def is50(msg):
"""Check if a message is likely to be BDS code 5,0
(Track and turn report)
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
bool: True or False
"""
if allzeros(msg):
return False
d = hex2bin(data(msg))
# status bit 1, 12, 24, 35, 46
if wrongstatus(d, 1, 3, 11):
return False
if wrongstatus(d, 12, 13, 23):
return False
if wrongstatus(d, 24, 25, 34):
return False
if wrongstatus(d, 35, 36, 45):
return False
if wrongstatus(d, 46, 47, 56):
return False
roll = roll50(msg)
if (roll is not None) and abs(roll) > 60:
return False
gs = gs50(msg)
if gs is not None and gs > 600:
return False
tas = tas50(msg)
if tas is not None and tas > 500:
return False
if (gs is not None) and (tas is not None) and (abs(tas - gs) > 200):
return False
return True
|
Roll angle, BDS 5,0 message
Args:
msg (String): 28 bytes hexadecimal message (BDS50) string
Returns:
float: angle in degrees,
negative->left wing down, positive->right wing down
|
def roll50(msg):
"""Roll angle, BDS 5,0 message
Args:
msg (String): 28 bytes hexadecimal message (BDS50) string
Returns:
float: angle in degrees,
negative->left wing down, positive->right wing down
"""
d = hex2bin(data(msg))
if d[0] == '0':
return None
sign = int(d[1]) # 1 -> left wing down
value = bin2int(d[2:11])
if sign:
value = value - 512
angle = value * 45.0 / 256.0 # degree
return round(angle, 1)
|
True track angle, BDS 5,0 message
Args:
msg (String): 28 bytes hexadecimal message (BDS50) string
Returns:
float: angle in degrees to true north (from 0 to 360)
|
def trk50(msg):
"""True track angle, BDS 5,0 message
Args:
msg (String): 28 bytes hexadecimal message (BDS50) string
Returns:
float: angle in degrees to true north (from 0 to 360)
"""
d = hex2bin(data(msg))
if d[11] == '0':
return None
sign = int(d[12]) # 1 -> west
value = bin2int(d[13:23])
if sign:
value = value - 1024
trk = value * 90.0 / 512.0
# convert from [-180, 180] to [0, 360]
if trk < 0:
trk = 360 + trk
return round(trk, 3)
|
Ground speed, BDS 5,0 message
Args:
msg (String): 28 bytes hexadecimal message (BDS50) string
Returns:
int: ground speed in knots
|
def gs50(msg):
"""Ground speed, BDS 5,0 message
Args:
msg (String): 28 bytes hexadecimal message (BDS50) string
Returns:
int: ground speed in knots
"""
d = hex2bin(data(msg))
if d[23] == '0':
return None
spd = bin2int(d[24:34]) * 2 # kts
return spd
|
Aircraft true airspeed, BDS 5,0 message
Args:
msg (String): 28 bytes hexadecimal message (BDS50) string
Returns:
int: true airspeed in knots
|
def tas50(msg):
"""Aircraft true airspeed, BDS 5,0 message
Args:
msg (String): 28 bytes hexadecimal message (BDS50) string
Returns:
int: true airspeed in knots
"""
d = hex2bin(data(msg))
if d[45] == '0':
return None
tas = bin2int(d[46:56]) * 2 # kts
return tas
|
Check if a message is likely to be BDS code 5,3
(Air-referenced state vector)
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
bool: True or False
|
def is53(msg):
"""Check if a message is likely to be BDS code 5,3
(Air-referenced state vector)
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
bool: True or False
"""
if allzeros(msg):
return False
d = hex2bin(data(msg))
# status bit 1, 13, 24, 34, 47
if wrongstatus(d, 1, 3, 12):
return False
if wrongstatus(d, 13, 14, 23):
return False
if wrongstatus(d, 24, 25, 33):
return False
if wrongstatus(d, 34, 35, 46):
return False
if wrongstatus(d, 47, 49, 56):
return False
ias = ias53(msg)
if ias is not None and ias > 500:
return False
mach = mach53(msg)
if mach is not None and mach > 1:
return False
tas = tas53(msg)
if tas is not None and tas > 500:
return False
vr = vr53(msg)
if vr is not None and abs(vr) > 8000:
return False
return True
|
Indicated airspeed, DBS 5,3 message
Args:
msg (String): 28 bytes hexadecimal message
Returns:
int: indicated arispeed in knots
|
def ias53(msg):
"""Indicated airspeed, DBS 5,3 message
Args:
msg (String): 28 bytes hexadecimal message
Returns:
int: indicated arispeed in knots
"""
d = hex2bin(data(msg))
if d[12] == '0':
return None
ias = bin2int(d[13:23]) # knots
return ias
|
MACH number, DBS 5,3 message
Args:
msg (String): 28 bytes hexadecimal message
Returns:
float: MACH number
|
def mach53(msg):
"""MACH number, DBS 5,3 message
Args:
msg (String): 28 bytes hexadecimal message
Returns:
float: MACH number
"""
d = hex2bin(data(msg))
if d[23] == '0':
return None
mach = bin2int(d[24:33]) * 0.008
return round(mach, 3)
|
Aircraft true airspeed, BDS 5,3 message
Args:
msg (String): 28 bytes hexadecimal message
Returns:
float: true airspeed in knots
|
def tas53(msg):
"""Aircraft true airspeed, BDS 5,3 message
Args:
msg (String): 28 bytes hexadecimal message
Returns:
float: true airspeed in knots
"""
d = hex2bin(data(msg))
if d[33] == '0':
return None
tas = bin2int(d[34:46]) * 0.5 # kts
return round(tas, 1)
|
<esc> "1" : 6 byte MLAT timestamp, 1 byte signal level,
2 byte Mode-AC
<esc> "2" : 6 byte MLAT timestamp, 1 byte signal level,
7 byte Mode-S short frame
<esc> "3" : 6 byte MLAT timestamp, 1 byte signal level,
14 byte Mode-S long frame
<esc> "4" : 6 byte MLAT timestamp, status data, DIP switch
configuration settings (not on Mode-S Beast classic)
<esc><esc>: true 0x1a
<esc> is 0x1a, and "1", "2" and "3" are 0x31, 0x32 and 0x33
timestamp:
wiki.modesbeast.com/Radarcape:Firmware_Versions#The_GPS_timestamp
|
def read_beast_buffer(self):
'''
<esc> "1" : 6 byte MLAT timestamp, 1 byte signal level,
2 byte Mode-AC
<esc> "2" : 6 byte MLAT timestamp, 1 byte signal level,
7 byte Mode-S short frame
<esc> "3" : 6 byte MLAT timestamp, 1 byte signal level,
14 byte Mode-S long frame
<esc> "4" : 6 byte MLAT timestamp, status data, DIP switch
configuration settings (not on Mode-S Beast classic)
<esc><esc>: true 0x1a
<esc> is 0x1a, and "1", "2" and "3" are 0x31, 0x32 and 0x33
timestamp:
wiki.modesbeast.com/Radarcape:Firmware_Versions#The_GPS_timestamp
'''
messages_mlat = []
msg = []
i = 0
# process the buffer until the last divider <esc> 0x1a
# then, reset the self.buffer with the remainder
while i < len(self.buffer):
if (self.buffer[i:i+2] == [0x1a, 0x1a]):
msg.append(0x1a)
i += 1
elif (i == len(self.buffer) - 1) and (self.buffer[i] == 0x1a):
# special case where the last bit is 0x1a
msg.append(0x1a)
elif self.buffer[i] == 0x1a:
if i == len(self.buffer) - 1:
# special case where the last bit is 0x1a
msg.append(0x1a)
elif len(msg) > 0:
messages_mlat.append(msg)
msg = []
else:
msg.append(self.buffer[i])
i += 1
# save the reminder for next reading cycle, if not empty
if len(msg) > 0:
reminder = []
for i, m in enumerate(msg):
if (m == 0x1a) and (i < len(msg)-1):
# rewind 0x1a, except when it is at the last bit
reminder.extend([m, m])
else:
reminder.append(m)
self.buffer = [0x1a] + msg
else:
self.buffer = []
# extract messages
messages = []
for mm in messages_mlat:
ts = time.time()
msgtype = mm[0]
# print(''.join('%02X' % i for i in mm))
if msgtype == 0x32:
# Mode-S Short Message, 7 byte, 14-len hexstr
msg = ''.join('%02X' % i for i in mm[8:15])
elif msgtype == 0x33:
# Mode-S Long Message, 14 byte, 28-len hexstr
msg = ''.join('%02X' % i for i in mm[8:22])
else:
# Other message tupe
continue
if len(msg) not in [14, 28]:
# incomplete message
continue
messages.append([msg, ts])
return messages
|
Skysense stream format.
::
----------------------------------------------------------------------------------
Field SS MS MS MS MS MS MS MS MS MS MS MS MS MS MS TS TS TS TS TS TS RS RS RS
----------------------------------------------------------------------------------
Position: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
----------------------------------------------------------------------------------
SS field - Start character
Position 0:
1 byte = 8 bits
Start character '$'
MS field - Payload
Postion 1 through 14:
14 bytes = 112 bits
Mode-S payload
In case of DF types that only carry 7 bytes of information
position 8 through 14 are set to 0x00.
TS field - Time stamp
Position 15 through 20:
6 bytes = 48 bits
Time stamp with fields as:
Lock Status - Status of internal time keeping mechanism
Equal to 1 if operating normally
Bit 47 - 1 bit
Time of day in UTC seconds, between 0 and 86399
Bits 46 through 30 - 17 bits
Nanoseconds into current second, between 0 and 999999999
Bits 29 through 0 - 30 bits
RS field - Signal Level
Position 21 through 23:
3 bytes = 24 bits
RSSI (received signal strength indication) and relative
noise level with fields
RNL, Q12.4 unsigned fixed point binary with 4 fractional
bits and 8 integer bits.
This is and indication of the noise level of the message.
Roughly 40 counts per 10dBm.
Bits 23 through 12 - 12 bits
RSSI, Q12.4 unsigned fixed point binary with 4 fractional
bits and 8 integer bits.
This is an indication of the signal level of the received
message in ADC counts. Roughly 40 counts per 10dBm.
Bits 11 through 0 - 12 bits
|
def read_skysense_buffer(self):
"""Skysense stream format.
::
----------------------------------------------------------------------------------
Field SS MS MS MS MS MS MS MS MS MS MS MS MS MS MS TS TS TS TS TS TS RS RS RS
----------------------------------------------------------------------------------
Position: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
----------------------------------------------------------------------------------
SS field - Start character
Position 0:
1 byte = 8 bits
Start character '$'
MS field - Payload
Postion 1 through 14:
14 bytes = 112 bits
Mode-S payload
In case of DF types that only carry 7 bytes of information
position 8 through 14 are set to 0x00.
TS field - Time stamp
Position 15 through 20:
6 bytes = 48 bits
Time stamp with fields as:
Lock Status - Status of internal time keeping mechanism
Equal to 1 if operating normally
Bit 47 - 1 bit
Time of day in UTC seconds, between 0 and 86399
Bits 46 through 30 - 17 bits
Nanoseconds into current second, between 0 and 999999999
Bits 29 through 0 - 30 bits
RS field - Signal Level
Position 21 through 23:
3 bytes = 24 bits
RSSI (received signal strength indication) and relative
noise level with fields
RNL, Q12.4 unsigned fixed point binary with 4 fractional
bits and 8 integer bits.
This is and indication of the noise level of the message.
Roughly 40 counts per 10dBm.
Bits 23 through 12 - 12 bits
RSSI, Q12.4 unsigned fixed point binary with 4 fractional
bits and 8 integer bits.
This is an indication of the signal level of the received
message in ADC counts. Roughly 40 counts per 10dBm.
Bits 11 through 0 - 12 bits
"""
SS_MSGLENGTH = 24
SS_STARTCHAR = 0x24
if len(self.buffer) <= SS_MSGLENGTH:
return None
messages = []
while len(self.buffer) > SS_MSGLENGTH:
i = 0
if self.buffer[i] == SS_STARTCHAR and self.buffer[i+SS_MSGLENGTH] == SS_STARTCHAR:
i += 1
if (self.buffer[i]>>7):
#Long message
payload = self.buffer[i:i+14]
else:
#Short message
payload = self.buffer[i:i+7]
msg = ''.join('%02X' % j for j in payload)
i += 14 #Both message types use 14 bytes
tsbin = self.buffer[i:i+6]
sec = ( (tsbin[0] & 0x7f) << 10) | (tsbin[1] << 2 ) | (tsbin[2] >> 6)
nano = ( (tsbin[2] & 0x3f) << 24) | (tsbin[3] << 16) | (tsbin[4] << 8) | tsbin[5]
ts = sec + nano*1.0e-9
i += 6
#Signal and noise level - Don't care for now
i += 3
self.buffer = self.buffer[SS_MSGLENGTH:]
messages.append( [msg,ts] )
else:
self.buffer = self.buffer[1:]
return messages
|
Check if a message is likely to be BDS code 1,0
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
bool: True or False
|
def is10(msg):
"""Check if a message is likely to be BDS code 1,0
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
bool: True or False
"""
if allzeros(msg):
return False
d = hex2bin(data(msg))
# first 8 bits must be 0x10
if d[0:8] != '00010000':
return False
# bit 10 to 14 are reserved
if bin2int(d[9:14]) != 0:
return False
# overlay capabilty conflict
if d[14] == '1' and bin2int(d[16:23]) < 5:
return False
if d[14] == '0' and bin2int(d[16:23]) > 4:
return False
return True
|
Check if a message is likely to be BDS code 1,7
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
bool: True or False
|
def is17(msg):
"""Check if a message is likely to be BDS code 1,7
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
bool: True or False
"""
if allzeros(msg):
return False
d = hex2bin(data(msg))
if bin2int(d[28:56]) != 0:
return False
caps = cap17(msg)
# basic BDS codes for ADS-B shall be supported
# assuming ADS-B out is installed (2017EU/2020US mandate)
# if not set(['BDS05', 'BDS06', 'BDS08', 'BDS09', 'BDS20']).issubset(caps):
# return False
# at least you can respond who you are
if 'BDS20' not in caps:
return False
return True
|
Extract capacities from BDS 1,7 message
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
list: list of suport BDS codes
|
def cap17(msg):
"""Extract capacities from BDS 1,7 message
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
list: list of suport BDS codes
"""
allbds = ['05', '06', '07', '08', '09', '0A', '20', '21', '40', '41',
'42', '43', '44', '45', '48', '50', '51', '52', '53', '54',
'55', '56', '5F', '60', 'NA', 'NA', 'E1', 'E2']
d = hex2bin(data(msg))
idx = [i for i, v in enumerate(d[:28]) if v=='1']
capacity = ['BDS'+allbds[i] for i in idx if allbds[i] is not 'NA']
return capacity
|
process a chunk of adsb and commb messages recieved in the same
time period.
|
def process_raw(self, adsb_ts, adsb_msgs, commb_ts, commb_msgs, tnow=None):
"""process a chunk of adsb and commb messages recieved in the same
time period.
"""
if tnow is None:
tnow = time.time()
self.t = tnow
local_updated_acs_buffer = []
output_buffer = []
# process adsb message
for t, msg in zip(adsb_ts, adsb_msgs):
icao = pms.icao(msg)
tc = pms.adsb.typecode(msg)
if icao not in self.acs:
self.acs[icao] = {
'live': None,
'call': None,
'lat': None,
'lon': None,
'alt': None,
'gs': None,
'trk': None,
'roc': None,
'tas': None,
'roll': None,
'rtrk': None,
'ias': None,
'mach': None,
'hdg': None,
'ver' : None,
'HPL' : None,
'RCu' : None,
'RCv' : None,
'HVE' : None,
'VVE' : None,
'Rc' : None,
'VPL' : None,
'EPU' : None,
'VEPU' : None,
'HFOMr' : None,
'VFOMr' : None,
'PE_RCu' : None,
'PE_VPL' : None,
}
self.acs[icao]['t'] = t
self.acs[icao]['live'] = int(t)
if 1 <= tc <= 4:
cs = pms.adsb.callsign(msg)
self.acs[icao]['call'] = cs
output_buffer.append([t, icao, 'cs', cs])
if (5 <= tc <= 8) or (tc == 19):
vdata = pms.adsb.velocity(msg)
if vdata is None:
continue
spd, trk, roc, tag = vdata
if tag != 'GS':
continue
if (spd is None) or (trk is None):
continue
self.acs[icao]['gs'] = spd
self.acs[icao]['trk'] = trk
self.acs[icao]['roc'] = roc
self.acs[icao]['tv'] = t
output_buffer.append([t, icao, 'gs', spd])
output_buffer.append([t, icao, 'trk', trk])
output_buffer.append([t, icao, 'roc', roc])
if (5 <= tc <= 18):
oe = pms.adsb.oe_flag(msg)
self.acs[icao][oe] = msg
self.acs[icao]['t'+str(oe)] = t
if ('tpos' in self.acs[icao]) and (t - self.acs[icao]['tpos'] < 180):
# use single message decoding
rlat = self.acs[icao]['lat']
rlon = self.acs[icao]['lon']
latlon = pms.adsb.position_with_ref(msg, rlat, rlon)
elif ('t0' in self.acs[icao]) and ('t1' in self.acs[icao]) and \
(abs(self.acs[icao]['t0'] - self.acs[icao]['t1']) < 10):
# use multi message decoding
try:
latlon = pms.adsb.position(
self.acs[icao][0],
self.acs[icao][1],
self.acs[icao]['t0'],
self.acs[icao]['t1'],
self.lat0, self.lon0
)
except:
# mix of surface and airborne position message
continue
else:
latlon = None
if latlon is not None:
self.acs[icao]['tpos'] = t
self.acs[icao]['lat'] = latlon[0]
self.acs[icao]['lon'] = latlon[1]
alt = pms.adsb.altitude(msg)
self.acs[icao]['alt'] = alt
output_buffer.append([t, icao, 'lat', latlon[0]])
output_buffer.append([t, icao, 'lon', latlon[1]])
output_buffer.append([t, icao, 'alt', alt])
local_updated_acs_buffer.append(icao)
# Uncertainty & accuracy
ac = self.acs[icao]
if 9 <= tc <= 18:
ac['nic_bc'] = pms.adsb.nic_b(msg)
if (5 <= tc <= 8) or (9 <= tc <= 18) or (20 <= tc <= 22):
ac['HPL'], ac['RCu'], ac['RCv'] = pms.adsb.nuc_p(msg)
if (ac['ver'] == 1) and ('nic_s' in ac.keys()):
ac['Rc'], ac['VPL'] = pms.adsb.nic_v1(msg, ac['nic_s'])
elif (ac['ver'] == 2) and ('nic_a' in ac.keys()) and ('nic_bc' in ac.keys()):
ac['Rc'] = pms.adsb.nic_v2(msg, ac['nic_a'], ac['nic_bc'])
if tc == 19:
ac['HVE'], ac['VVE'] = pms.adsb.nuc_v(msg)
if ac['ver'] in [1, 2]:
ac['HFOMr'], ac['VFOMr'] = pms.adsb.nac_v(msg)
if tc == 29:
ac['PE_RCu'], ac['PE_VPL'], ac['base'] = pms.adsb.sil(msg, ac['ver'])
ac['EPU'], ac['VEPU'] = pms.adsb.nac_p(msg)
if tc == 31:
ac['ver'] = pms.adsb.version(msg)
ac['EPU'], ac['VEPU'] = pms.adsb.nac_p(msg)
ac['PE_RCu'], ac['PE_VPL'], ac['sil_base'] = pms.adsb.sil(msg, ac['ver'])
if ac['ver'] == 1:
ac['nic_s'] = pms.adsb.nic_s(msg)
elif ac['ver'] == 2:
ac['nic_a'], ac['nic_bc'] = pms.adsb.nic_a_c(msg)
# process commb message
for t, msg in zip(commb_ts, commb_msgs):
icao = pms.icao(msg)
if icao not in self.acs:
continue
bds = pms.bds.infer(msg)
if bds == 'BDS50':
roll50 = pms.commb.roll50(msg)
trk50 = pms.commb.trk50(msg)
rtrk50 = pms.commb.rtrk50(msg)
gs50 = pms.commb.gs50(msg)
tas50 = pms.commb.tas50(msg)
self.acs[icao]['t50'] = t
if tas50:
self.acs[icao]['tas'] = tas50
output_buffer.append([t, icao, 'tas50', tas50])
if roll50:
self.acs[icao]['roll'] = roll50
output_buffer.append([t, icao, 'roll50', roll50])
if rtrk50:
self.acs[icao]['rtrk'] = rtrk50
output_buffer.append([t, icao, 'rtrk50', rtrk50])
if trk50:
output_buffer.append([t, icao, 'trk50', trk50])
if gs50:
output_buffer.append([t, icao, 'gs50', gs50])
elif bds == 'BDS60':
ias60 = pms.commb.ias60(msg)
hdg60 = pms.commb.hdg60(msg)
mach60 = pms.commb.mach60(msg)
roc60baro = pms.commb.vr60baro(msg)
roc60ins = pms.commb.vr60ins(msg)
if ias60 or hdg60 or mach60:
self.acs[icao]['t60'] = t
if ias60:
self.acs[icao]['ias'] = ias60
if hdg60:
self.acs[icao]['hdg'] = hdg60
if mach60:
self.acs[icao]['mach'] = mach60
if roc60baro:
output_buffer.append([t, icao, 'roc60baro', roc60baro])
if roc60ins:
output_buffer.append([t, icao, 'roc60ins', roc60ins])
# clear up old data
for icao in list(self.acs.keys()):
if self.t - self.acs[icao]['live'] > self.cache_timeout:
del self.acs[icao]
continue
if self.dumpto is not None:
dh = str(datetime.datetime.now().strftime("%Y%m%d_%H"))
fn = self.dumpto + '/pymodes_dump_%s.csv' % dh
output_buffer.sort(key=lambda x: x[0])
with open(fn, "a") as f:
writer = csv.writer(f)
writer.writerows(output_buffer)
return
|
all aircraft that are stored in memeory
|
def get_aircraft(self):
"""all aircraft that are stored in memeory"""
acs = self.acs
icaos = list(acs.keys())
for icao in icaos:
if acs[icao]['lat'] is None:
acs.pop(icao)
return acs
|
Calculate the speed, track (or heading), and vertical rate
Args:
msg (string): 28 bytes hexadecimal message string
Returns:
(int, float, int, string): speed (kt), ground track or heading (degree),
rate of climb/descend (ft/min), and speed type
('GS' for ground speed, 'AS' for airspeed)
|
def airborne_velocity(msg):
"""Calculate the speed, track (or heading), and vertical rate
Args:
msg (string): 28 bytes hexadecimal message string
Returns:
(int, float, int, string): speed (kt), ground track or heading (degree),
rate of climb/descend (ft/min), and speed type
('GS' for ground speed, 'AS' for airspeed)
"""
if common.typecode(msg) != 19:
raise RuntimeError("%s: Not a airborne velocity message, expecting TC=19" % msg)
mb = common.hex2bin(msg)[32:]
subtype = common.bin2int(mb[5:8])
if common.bin2int(mb[14:24]) == 0 or common.bin2int(mb[25:35]) == 0:
return None
if subtype in (1, 2):
v_ew_sign = -1 if mb[13]=='1' else 1
v_ew = common.bin2int(mb[14:24]) - 1 # east-west velocity
v_ns_sign = -1 if mb[24]=='1' else 1
v_ns = common.bin2int(mb[25:35]) - 1 # north-south velocity
v_we = v_ew_sign * v_ew
v_sn = v_ns_sign * v_ns
spd = math.sqrt(v_sn*v_sn + v_we*v_we) # unit in kts
spd = int(spd)
trk = math.atan2(v_we, v_sn)
trk = math.degrees(trk) # convert to degrees
trk = trk if trk >= 0 else trk + 360 # no negative val
tag = 'GS'
trk_or_hdg = round(trk, 2)
else:
if mb[13] == '0':
hdg = None
else:
hdg = common.bin2int(mb[14:24]) / 1024.0 * 360.0
hdg = round(hdg, 2)
trk_or_hdg = hdg
spd = common.bin2int(mb[25:35])
spd = None if spd==0 else spd-1
if mb[24]=='0':
tag = 'IAS'
else:
tag = 'TAS'
vr_sign = -1 if mb[36]=='1' else 1
vr = common.bin2int(mb[37:46])
rocd = None if vr==0 else int(vr_sign*(vr-1)*64)
return spd, trk_or_hdg, rocd, tag
|
Decode the differece between GNSS and barometric altitude
Args:
msg (string): 28 bytes hexadecimal message string, TC=19
Returns:
int: Altitude difference in ft. Negative value indicates GNSS altitude
below barometric altitude.
|
def altitude_diff(msg):
"""Decode the differece between GNSS and barometric altitude
Args:
msg (string): 28 bytes hexadecimal message string, TC=19
Returns:
int: Altitude difference in ft. Negative value indicates GNSS altitude
below barometric altitude.
"""
tc = common.typecode(msg)
if tc != 19:
raise RuntimeError("%s: Not a airborne velocity message, expecting TC=19" % msg)
msgbin = common.hex2bin(msg)
sign = -1 if int(msgbin[80]) else 1
value = common.bin2int(msgbin[81:88])
if value == 0 or value == 127:
return None
else:
return sign * (value - 1) * 25
|
Use reference ground speed and trk to determine BDS50 and DBS60.
Args:
msg (String): 28 bytes hexadecimal message string
spd_ref (float): reference speed (ADS-B ground speed), kts
trk_ref (float): reference track (ADS-B track angle), deg
alt_ref (float): reference altitude (ADS-B altitude), ft
Returns:
String or None: BDS version, or possible versions, or None if nothing matches.
|
def is50or60(msg, spd_ref, trk_ref, alt_ref):
"""Use reference ground speed and trk to determine BDS50 and DBS60.
Args:
msg (String): 28 bytes hexadecimal message string
spd_ref (float): reference speed (ADS-B ground speed), kts
trk_ref (float): reference track (ADS-B track angle), deg
alt_ref (float): reference altitude (ADS-B altitude), ft
Returns:
String or None: BDS version, or possible versions, or None if nothing matches.
"""
def vxy(v, angle):
vx = v * np.sin(np.radians(angle))
vy = v * np.cos(np.radians(angle))
return vx, vy
if not (bds50.is50(msg) and bds60.is60(msg)):
return None
h50 = bds50.trk50(msg)
v50 = bds50.gs50(msg)
if h50 is None or v50 is None:
return 'BDS50,BDS60'
h60 = bds60.hdg60(msg)
m60 = bds60.mach60(msg)
i60 = bds60.ias60(msg)
if h60 is None or (m60 is None and i60 is None):
return 'BDS50,BDS60'
m60 = np.nan if m60 is None else m60
i60 = np.nan if i60 is None else i60
XY5 = vxy(v50*aero.kts, h50)
XY6m = vxy(aero.mach2tas(m60, alt_ref*aero.ft), h60)
XY6i = vxy(aero.cas2tas(i60*aero.kts, alt_ref*aero.ft), h60)
allbds = ['BDS50', 'BDS60', 'BDS60']
X = np.array([XY5, XY6m, XY6i])
Mu = np.array(vxy(spd_ref*aero.kts, trk_ref))
# compute Mahalanobis distance matrix
# Cov = [[20**2, 0], [0, 20**2]]
# mmatrix = np.sqrt(np.dot(np.dot(X-Mu, np.linalg.inv(Cov)), (X-Mu).T))
# dist = np.diag(mmatrix)
# since the covariance matrix is identity matrix,
# M-dist is same as eculidian distance
try:
dist = np.linalg.norm(X-Mu, axis=1)
BDS = allbds[np.nanargmin(dist)]
except ValueError:
return 'BDS50,BDS60'
return BDS
|
Estimate the most likely BDS code of an message.
Args:
msg (String): 28 bytes hexadecimal message string
mrar (bool): Also infer MRAR (BDS 44) and MHR (BDS 45). Defaults to False.
Returns:
String or None: BDS version, or possible versions, or None if nothing matches.
|
def infer(msg, mrar=False):
"""Estimate the most likely BDS code of an message.
Args:
msg (String): 28 bytes hexadecimal message string
mrar (bool): Also infer MRAR (BDS 44) and MHR (BDS 45). Defaults to False.
Returns:
String or None: BDS version, or possible versions, or None if nothing matches.
"""
df = common.df(msg)
if common.allzeros(msg):
return 'EMPTY'
# For ADS-B / Mode-S extended squitter
if df == 17:
tc = common.typecode(msg)
if 1 <= tc <= 4:
return 'BDS08' # indentification and category
if 5 <= tc <= 8:
return 'BDS06' # surface movement
if 9 <= tc <= 18:
return 'BDS05' # airborne position, baro-alt
if tc == 19:
return 'BDS09' # airborne velocity
if 20 <= tc <= 22:
return 'BDS05' # airborne position, gnss-alt
if tc == 28:
return 'BDS61' # aircraft status
if tc == 29:
return 'BDS62' # target state and status
if tc == 31:
return 'BDS65' # operational status
# For Comm-B replies
IS10 = bds10.is10(msg)
IS17 = bds17.is17(msg)
IS20 = bds20.is20(msg)
IS30 = bds30.is30(msg)
IS40 = bds40.is40(msg)
IS50 = bds50.is50(msg)
IS60 = bds60.is60(msg)
IS44 = bds44.is44(msg)
IS45 = bds45.is45(msg)
if mrar:
allbds = np.array(["BDS10", "BDS17", "BDS20", "BDS30", "BDS40",
"BDS44", "BDS45", "BDS50", "BDS60"])
mask = [IS10, IS17, IS20, IS30, IS40, IS44, IS45, IS50, IS60]
else:
allbds = np.array(["BDS10", "BDS17", "BDS20", "BDS30", "BDS40",
"BDS50", "BDS60"])
mask = [IS10, IS17, IS20, IS30, IS40, IS50, IS60]
bds = ','.join(sorted(allbds[mask]))
if len(bds) == 0:
return None
else:
return bds
|
Check if a message is likely to be BDS code 4,0
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
bool: True or False
|
def is40(msg):
"""Check if a message is likely to be BDS code 4,0
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
bool: True or False
"""
if allzeros(msg):
return False
d = hex2bin(data(msg))
# status bit 1, 14, and 27
if wrongstatus(d, 1, 2, 13):
return False
if wrongstatus(d, 14, 15, 26):
return False
if wrongstatus(d, 27, 28, 39):
return False
if wrongstatus(d, 48, 49, 51):
return False
if wrongstatus(d, 54, 55, 56):
return False
# bits 40-47 and 52-53 shall all be zero
if bin2int(d[39:47]) != 0:
return False
if bin2int(d[51:53]) != 0:
return False
return True
|
Selected altitude, MCP/FCU
Args:
msg (String): 28 bytes hexadecimal message (BDS40) string
Returns:
int: altitude in feet
|
def alt40mcp(msg):
"""Selected altitude, MCP/FCU
Args:
msg (String): 28 bytes hexadecimal message (BDS40) string
Returns:
int: altitude in feet
"""
d = hex2bin(data(msg))
if d[0] == '0':
return None
alt = bin2int(d[1:13]) * 16 # ft
return alt
|
Selected altitude, FMS
Args:
msg (String): 28 bytes hexadecimal message (BDS40) string
Returns:
int: altitude in feet
|
def alt40fms(msg):
"""Selected altitude, FMS
Args:
msg (String): 28 bytes hexadecimal message (BDS40) string
Returns:
int: altitude in feet
"""
d = hex2bin(data(msg))
if d[13] == '0':
return None
alt = bin2int(d[14:26]) * 16 # ft
return alt
|
Barometric pressure setting
Args:
msg (String): 28 bytes hexadecimal message (BDS40) string
Returns:
float: pressure in millibar
|
def p40baro(msg):
"""Barometric pressure setting
Args:
msg (String): 28 bytes hexadecimal message (BDS40) string
Returns:
float: pressure in millibar
"""
d = hex2bin(data(msg))
if d[26] == '0':
return None
p = bin2int(d[27:39]) * 0.1 + 800 # millibar
return p
|
Check if a message is likely to be BDS code 4,4.
Meteorological routine air report
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
bool: True or False
|
def is44(msg):
"""Check if a message is likely to be BDS code 4,4.
Meteorological routine air report
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
bool: True or False
"""
if allzeros(msg):
return False
d = hex2bin(data(msg))
# status bit 5, 35, 47, 50
if wrongstatus(d, 5, 6, 23):
return False
if wrongstatus(d, 35, 36, 46):
return False
if wrongstatus(d, 47, 48, 49):
return False
if wrongstatus(d, 50, 51, 56):
return False
# Bits 1-4 indicate source, values > 4 reserved and should not occur
if bin2int(d[0:4]) > 4:
return False
vw = wind44(msg)
if vw is not None and vw[0] > 250:
return False
temp, temp2 = temp44(msg)
if min(temp, temp2) > 60 or max(temp, temp2) < -80:
return False
return True
|
Wind speed and direction.
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
(int, float): speed (kt), direction (degree)
|
def wind44(msg):
"""Wind speed and direction.
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
(int, float): speed (kt), direction (degree)
"""
d = hex2bin(data(msg))
status = int(d[4])
if not status:
return None
speed = bin2int(d[5:14]) # knots
direction = bin2int(d[14:23]) * 180.0 / 256.0 # degree
return round(speed, 0), round(direction, 1)
|
Static air temperature.
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
float, float: temperature and alternative temperature in Celsius degree.
Note: Two values returns due to what seems to be an inconsistancy
error in ICAO 9871 (2008) Appendix A-67.
|
def temp44(msg):
"""Static air temperature.
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
float, float: temperature and alternative temperature in Celsius degree.
Note: Two values returns due to what seems to be an inconsistancy
error in ICAO 9871 (2008) Appendix A-67.
"""
d = hex2bin(data(msg))
sign = int(d[23])
value = bin2int(d[24:34])
if sign:
value = value - 1024
temp = value * 0.25 # celsius
temp = round(temp, 2)
temp_alternative = value * 0.125 # celsius
temp_alternative = round(temp, 3)
return temp, temp_alternative
|
Static pressure.
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
int: static pressure in hPa
|
def p44(msg):
"""Static pressure.
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
int: static pressure in hPa
"""
d = hex2bin(data(msg))
if d[34] == '0':
return None
p = bin2int(d[35:46]) # hPa
return p
|
humidity
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
float: percentage of humidity, [0 - 100] %
|
def hum44(msg):
"""humidity
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
float: percentage of humidity, [0 - 100] %
"""
d = hex2bin(data(msg))
if d[49] == '0':
return None
hm = bin2int(d[50:56]) * 100.0 / 64 # %
return round(hm, 1)
|
Turblence.
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
int: turbulence level. 0=NIL, 1=Light, 2=Moderate, 3=Severe
|
def turb44(msg):
"""Turblence.
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
int: turbulence level. 0=NIL, 1=Light, 2=Moderate, 3=Severe
"""
d = hex2bin(data(msg))
if d[46] == '0':
return None
turb = bin2int(d[47:49])
return turb
|
Decode surface position from a pair of even and odd position message,
the lat/lon of receiver must be provided to yield the correct solution.
Args:
msg0 (string): even message (28 bytes hexadecimal string)
msg1 (string): odd message (28 bytes hexadecimal string)
t0 (int): timestamps for the even message
t1 (int): timestamps for the odd message
lat_ref (float): latitude of the receiver
lon_ref (float): longitude of the receiver
Returns:
(float, float): (latitude, longitude) of the aircraft
|
def surface_position(msg0, msg1, t0, t1, lat_ref, lon_ref):
"""Decode surface position from a pair of even and odd position message,
the lat/lon of receiver must be provided to yield the correct solution.
Args:
msg0 (string): even message (28 bytes hexadecimal string)
msg1 (string): odd message (28 bytes hexadecimal string)
t0 (int): timestamps for the even message
t1 (int): timestamps for the odd message
lat_ref (float): latitude of the receiver
lon_ref (float): longitude of the receiver
Returns:
(float, float): (latitude, longitude) of the aircraft
"""
msgbin0 = common.hex2bin(msg0)
msgbin1 = common.hex2bin(msg1)
# 131072 is 2^17, since CPR lat and lon are 17 bits each.
cprlat_even = common.bin2int(msgbin0[54:71]) / 131072.0
cprlon_even = common.bin2int(msgbin0[71:88]) / 131072.0
cprlat_odd = common.bin2int(msgbin1[54:71]) / 131072.0
cprlon_odd = common.bin2int(msgbin1[71:88]) / 131072.0
air_d_lat_even = 90.0 / 60
air_d_lat_odd = 90.0 / 59
# compute latitude index 'j'
j = common.floor(59 * cprlat_even - 60 * cprlat_odd + 0.5)
# solution for north hemisphere
lat_even_n = float(air_d_lat_even * (j % 60 + cprlat_even))
lat_odd_n = float(air_d_lat_odd * (j % 59 + cprlat_odd))
# solution for north hemisphere
lat_even_s = lat_even_n - 90.0
lat_odd_s = lat_odd_n - 90.0
# chose which solution corrispondes to receiver location
lat_even = lat_even_n if lat_ref > 0 else lat_even_s
lat_odd = lat_odd_n if lat_ref > 0 else lat_odd_s
# check if both are in the same latidude zone, rare but possible
if common.cprNL(lat_even) != common.cprNL(lat_odd):
return None
# compute ni, longitude index m, and longitude
if (t0 > t1):
lat = lat_even
nl = common.cprNL(lat_even)
ni = max(common.cprNL(lat_even) - 0, 1)
m = common.floor(cprlon_even * (nl-1) - cprlon_odd * nl + 0.5)
lon = (90.0 / ni) * (m % ni + cprlon_even)
else:
lat = lat_odd
nl = common.cprNL(lat_odd)
ni = max(common.cprNL(lat_odd) - 1, 1)
m = common.floor(cprlon_even * (nl-1) - cprlon_odd * nl + 0.5)
lon = (90.0 / ni) * (m % ni + cprlon_odd)
# four possible longitude solutions
lons = [lon, lon + 90.0, lon + 180.0, lon + 270.0]
# the closest solution to receiver is the correct one
dls = [abs(lon_ref - l) for l in lons]
imin = min(range(4), key=dls.__getitem__)
lon = lons[imin]
return round(lat, 5), round(lon, 5)
|
Decode surface velocity from from a surface position message
Args:
msg (string): 28 bytes hexadecimal message string
Returns:
(int, float, int, string): speed (kt), ground track (degree),
rate of climb/descend (ft/min), and speed type
('GS' for ground speed, 'AS' for airspeed)
|
def surface_velocity(msg):
"""Decode surface velocity from from a surface position message
Args:
msg (string): 28 bytes hexadecimal message string
Returns:
(int, float, int, string): speed (kt), ground track (degree),
rate of climb/descend (ft/min), and speed type
('GS' for ground speed, 'AS' for airspeed)
"""
if common.typecode(msg) < 5 or common.typecode(msg) > 8:
raise RuntimeError("%s: Not a surface message, expecting 5<TC<8" % msg)
mb = common.hex2bin(msg)[32:]
# ground track
trk_status = int(mb[12])
if trk_status == 1:
trk = common.bin2int(mb[13:20]) * 360.0 / 128.0
trk = round(trk, 1)
else:
trk = None
# ground movment / speed
mov = common.bin2int(mb[5:12])
if mov == 0 or mov > 124:
spd = None
elif mov == 1:
spd = 0
elif mov == 124:
spd = 175
else:
movs = [2, 9, 13, 39, 94, 109, 124]
kts = [0.125, 1, 2, 15, 70, 100, 175]
i = next(m[0] for m in enumerate(movs) if m[1] > mov)
step = (kts[i] - kts[i-1]) * 1.0 / (movs[i]-movs[i-1])
spd = kts[i-1] + (mov-movs[i-1]) * step
spd = round(spd, 2)
return spd, trk, 0, 'GS'
|
Check if a message is likely to be BDS code 2,0
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
bool: True or False
|
def is20(msg):
"""Check if a message is likely to be BDS code 2,0
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
bool: True or False
"""
if allzeros(msg):
return False
d = hex2bin(data(msg))
if d[0:8] != '00100000':
return False
cs = cs20(msg)
if '#' in cs:
return False
return True
|
Aircraft callsign
Args:
msg (String): 28 bytes hexadecimal message (BDS40) string
Returns:
string: callsign, max. 8 chars
|
def cs20(msg):
"""Aircraft callsign
Args:
msg (String): 28 bytes hexadecimal message (BDS40) string
Returns:
string: callsign, max. 8 chars
"""
chars = '#ABCDEFGHIJKLMNOPQRSTUVWXYZ#####_###############0123456789######'
d = hex2bin(data(msg))
cs = ''
cs += chars[bin2int(d[8:14])]
cs += chars[bin2int(d[14:20])]
cs += chars[bin2int(d[20:26])]
cs += chars[bin2int(d[26:32])]
cs += chars[bin2int(d[32:38])]
cs += chars[bin2int(d[38:44])]
cs += chars[bin2int(d[44:50])]
cs += chars[bin2int(d[50:56])]
return cs
|
Check if a message is likely to be BDS code 6,0
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
bool: True or False
|
def is60(msg):
"""Check if a message is likely to be BDS code 6,0
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
bool: True or False
"""
if allzeros(msg):
return False
d = hex2bin(data(msg))
# status bit 1, 13, 24, 35, 46
if wrongstatus(d, 1, 2, 12):
return False
if wrongstatus(d, 13, 14, 23):
return False
if wrongstatus(d, 24, 25, 34):
return False
if wrongstatus(d, 35, 36, 45):
return False
if wrongstatus(d, 46, 47, 56):
return False
ias = ias60(msg)
if ias is not None and ias > 500:
return False
mach = mach60(msg)
if mach is not None and mach > 1:
return False
vr_baro = vr60baro(msg)
if vr_baro is not None and abs(vr_baro) > 6000:
return False
vr_ins = vr60ins(msg)
if vr_ins is not None and abs(vr_ins) > 6000:
return False
return True
|
Megnetic heading of aircraft
Args:
msg (String): 28 bytes hexadecimal message (BDS60) string
Returns:
float: heading in degrees to megnetic north (from 0 to 360)
|
def hdg60(msg):
"""Megnetic heading of aircraft
Args:
msg (String): 28 bytes hexadecimal message (BDS60) string
Returns:
float: heading in degrees to megnetic north (from 0 to 360)
"""
d = hex2bin(data(msg))
if d[0] == '0':
return None
sign = int(d[1]) # 1 -> west
value = bin2int(d[2:12])
if sign:
value = value - 1024
hdg = value * 90 / 512.0 # degree
# convert from [-180, 180] to [0, 360]
if hdg < 0:
hdg = 360 + hdg
return round(hdg, 3)
|
Indicated airspeed
Args:
msg (String): 28 bytes hexadecimal message (BDS60) string
Returns:
int: indicated airspeed in knots
|
def ias60(msg):
"""Indicated airspeed
Args:
msg (String): 28 bytes hexadecimal message (BDS60) string
Returns:
int: indicated airspeed in knots
"""
d = hex2bin(data(msg))
if d[12] == '0':
return None
ias = bin2int(d[13:23]) # kts
return ias
|
Aircraft MACH number
Args:
msg (String): 28 bytes hexadecimal message (BDS60) string
Returns:
float: MACH number
|
def mach60(msg):
"""Aircraft MACH number
Args:
msg (String): 28 bytes hexadecimal message (BDS60) string
Returns:
float: MACH number
"""
d = hex2bin(data(msg))
if d[23] == '0':
return None
mach = bin2int(d[24:34]) * 2.048 / 512.0
return round(mach, 3)
|
Vertical rate from barometric measurement, this value may be very noisy.
Args:
msg (String): 28 bytes hexadecimal message (BDS60) string
Returns:
int: vertical rate in feet/minutes
|
def vr60baro(msg):
"""Vertical rate from barometric measurement, this value may be very noisy.
Args:
msg (String): 28 bytes hexadecimal message (BDS60) string
Returns:
int: vertical rate in feet/minutes
"""
d = hex2bin(data(msg))
if d[34] == '0':
return None
sign = int(d[35]) # 1 -> negative value, two's complement
value = bin2int(d[36:45])
if value == 0 or value == 511: # all zeros or all ones
return 0
value = value - 512 if sign else value
roc = value * 32 # feet/min
return roc
|
Check if a message is likely to be BDS code 4,5.
Meteorological hazard report
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
bool: True or False
|
def is45(msg):
"""Check if a message is likely to be BDS code 4,5.
Meteorological hazard report
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
bool: True or False
"""
if allzeros(msg):
return False
d = hex2bin(data(msg))
# status bit 1, 4, 7, 10, 13, 16, 27, 39
if wrongstatus(d, 1, 2, 3):
return False
if wrongstatus(d, 4, 5, 6):
return False
if wrongstatus(d, 7, 8, 9):
return False
if wrongstatus(d, 10, 11, 12):
return False
if wrongstatus(d, 13, 14, 15):
return False
if wrongstatus(d, 16, 17, 26):
return False
if wrongstatus(d, 27, 28, 38):
return False
if wrongstatus(d, 39, 40, 51):
return False
# reserved
if bin2int(d[51:56]) != 0:
return False
temp = temp45(msg)
if temp:
if temp > 60 or temp < -80:
return False
return True
|
Turbulence.
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
int: Turbulence level. 0=NIL, 1=Light, 2=Moderate, 3=Severe
|
def turb45(msg):
"""Turbulence.
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
int: Turbulence level. 0=NIL, 1=Light, 2=Moderate, 3=Severe
"""
d = hex2bin(data(msg))
if d[0] == '0':
return None
turb = bin2int(d[1:3])
return turb
|
Wind shear.
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
int: Wind shear level. 0=NIL, 1=Light, 2=Moderate, 3=Severe
|
def ws45(msg):
"""Wind shear.
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
int: Wind shear level. 0=NIL, 1=Light, 2=Moderate, 3=Severe
"""
d = hex2bin(data(msg))
if d[3] == '0':
return None
ws = bin2int(d[4:6])
return ws
|
Microburst.
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
int: Microburst level. 0=NIL, 1=Light, 2=Moderate, 3=Severe
|
def mb45(msg):
"""Microburst.
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
int: Microburst level. 0=NIL, 1=Light, 2=Moderate, 3=Severe
"""
d = hex2bin(data(msg))
if d[6] == '0':
return None
mb = bin2int(d[7:9])
return mb
|
Icing.
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
int: Icing level. 0=NIL, 1=Light, 2=Moderate, 3=Severe
|
def ic45(msg):
"""Icing.
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
int: Icing level. 0=NIL, 1=Light, 2=Moderate, 3=Severe
"""
d = hex2bin(data(msg))
if d[9] == '0':
return None
ic = bin2int(d[10:12])
return ic
|
Wake vortex.
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
int: Wake vortex level. 0=NIL, 1=Light, 2=Moderate, 3=Severe
|
def wv45(msg):
"""Wake vortex.
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
int: Wake vortex level. 0=NIL, 1=Light, 2=Moderate, 3=Severe
"""
d = hex2bin(data(msg))
if d[12] == '0':
return None
ws = bin2int(d[13:15])
return ws
|
Static air temperature.
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
float: tmeperature in Celsius degree
|
def temp45(msg):
"""Static air temperature.
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
float: tmeperature in Celsius degree
"""
d = hex2bin(data(msg))
sign = int(d[16])
value = bin2int(d[17:26])
if sign:
value = value - 512
temp = value * 0.25 # celsius
temp = round(temp, 1)
return temp
|
Average static pressure.
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
int: static pressure in hPa
|
def p45(msg):
"""Average static pressure.
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
int: static pressure in hPa
"""
d = hex2bin(data(msg))
if d[26] == '0':
return None
p = bin2int(d[27:38]) # hPa
return p
|
Radio height.
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
int: radio height in ft
|
def rh45(msg):
"""Radio height.
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
int: radio height in ft
"""
d = hex2bin(data(msg))
if d[38] == '0':
return None
rh = bin2int(d[39:51]) * 16
return rh
|
Speed of sound
|
def vsound(H):
"""Speed of sound"""
T = temperature(H)
a = np.sqrt(gamma * R * T)
return a
|
Compute spherical distance from spherical coordinates.
For two locations in spherical coordinates
(1, theta, phi) and (1, theta', phi')
cosine( arc length ) =
sin phi sin phi' cos(theta-theta') + cos phi cos phi'
distance = rho * arc length
|
def distance(lat1, lon1, lat2, lon2, H=0):
"""
Compute spherical distance from spherical coordinates.
For two locations in spherical coordinates
(1, theta, phi) and (1, theta', phi')
cosine( arc length ) =
sin phi sin phi' cos(theta-theta') + cos phi cos phi'
distance = rho * arc length
"""
# phi = 90 - latitude
phi1 = np.radians(90.0 - lat1)
phi2 = np.radians(90.0 - lat2)
# theta = longitude
theta1 = np.radians(lon1)
theta2 = np.radians(lon2)
cos = np.sin(phi1) * np.sin(phi2) * np.cos(theta1 - theta2) + np.cos(phi1) * np.cos(phi2)
cos = np.where(cos>1, 1, cos)
arc = np.arccos(cos)
dist = arc * (r_earth + H) # meters, radius of earth
return dist
|
True Airspeed to Mach number
|
def tas2mach(Vtas, H):
"""True Airspeed to Mach number"""
a = vsound(H)
Mach = Vtas/a
return Mach
|
Mach number to True Airspeed
|
def mach2tas(Mach, H):
"""Mach number to True Airspeed"""
a = vsound(H)
Vtas = Mach*a
return Vtas
|
True Airspeed to Equivalent Airspeed
|
def tas2eas(Vtas, H):
"""True Airspeed to Equivalent Airspeed"""
rho = density(H)
Veas = Vtas * np.sqrt(rho/rho0)
return Veas
|
Calibrated Airspeed to True Airspeed
|
def cas2tas(Vcas, H):
"""Calibrated Airspeed to True Airspeed"""
p, rho, T = atmos(H)
qdyn = p0*((1.+rho0*Vcas*Vcas/(7.*p0))**3.5-1.)
Vtas = np.sqrt(7.*p/rho*((1.+qdyn/p)**(2./7.)-1.))
return Vtas
|
Mach number to Calibrated Airspeed
|
def mach2cas(Mach, H):
"""Mach number to Calibrated Airspeed"""
Vtas = mach2tas(Mach, H)
Vcas = tas2cas(Vtas, H)
return Vcas
|
Calibrated Airspeed to Mach number
|
def cas2mach(Vcas, H):
"""Calibrated Airspeed to Mach number"""
Vtas = cas2tas(Vcas, H)
Mach = tas2mach(Vtas, H)
return Mach
|
Makdown image upload for uploading to imgur.com
and represent as json to markdown editor.
|
def markdown_imgur_uploader(request):
"""
Makdown image upload for uploading to imgur.com
and represent as json to markdown editor.
"""
if request.method == 'POST' and request.is_ajax():
if 'markdown-image-upload' in request.FILES:
image = request.FILES['markdown-image-upload']
data = imgur_uploader(image)
return HttpResponse(data, content_type='application/json')
return HttpResponse(_('Invalid request!'))
return HttpResponse(_('Invalid request!'))
|
Json usernames of the users registered & actived.
url(method=get):
/martor/search-user/?username={username}
Response:
error:
- `status` is status code (204)
- `error` is error message.
success:
- `status` is status code (204)
- `data` is list dict of usernames.
{ 'status': 200,
'data': [
{'usernane': 'john'},
{'usernane': 'albert'}]
}
|
def markdown_search_user(request):
"""
Json usernames of the users registered & actived.
url(method=get):
/martor/search-user/?username={username}
Response:
error:
- `status` is status code (204)
- `error` is error message.
success:
- `status` is status code (204)
- `data` is list dict of usernames.
{ 'status': 200,
'data': [
{'usernane': 'john'},
{'usernane': 'albert'}]
}
"""
data = {}
username = request.GET.get('username')
if username is not None \
and username != '' \
and ' ' not in username:
users = User.objects.filter(
Q(username__icontains=username)
).filter(is_active=True)
if users.exists():
data.update({
'status': 200,
'data': [{'username': u.username} for u in users]
})
return HttpResponse(
json.dumps(data, cls=LazyEncoder),
content_type='application/json')
data.update({
'status': 204,
'error': _('No users registered as `%(username)s` '
'or user is unactived.') % {'username': username}
})
else:
data.update({
'status': 204,
'error': _('Validation Failed for field `username`')
})
return HttpResponse(
json.dumps(data, cls=LazyEncoder),
content_type='application/json')
|
Makesure `username` is registered and actived.
|
def handleMatch(self, m):
username = self.unescape(m.group(2))
"""Makesure `username` is registered and actived."""
if MARTOR_ENABLE_CONFIGS['mention'] == 'true':
if username in [u.username for u in User.objects.exclude(is_active=False)]:
url = '{0}{1}/'.format(MARTOR_MARKDOWN_BASE_MENTION_URL, username)
el = markdown.util.etree.Element('a')
el.set('href', url)
el.set('class', 'direct-mention-link')
el.text = markdown.util.AtomicString('@' + username)
return el
|
Basic imgur uploader return as json data.
:param `image` is from `request.FILES['markdown-image-upload']`
Return:
success: {'status': 200, 'link': <link_image>, 'name': <image_name>}
error : {'status': <error_code>, 'erorr': <erorr_message>}
|
def imgur_uploader(image):
"""
Basic imgur uploader return as json data.
:param `image` is from `request.FILES['markdown-image-upload']`
Return:
success: {'status': 200, 'link': <link_image>, 'name': <image_name>}
error : {'status': <error_code>, 'erorr': <erorr_message>}
"""
url_api = 'https://api.imgur.com/3/upload.json'
headers = {'Authorization': 'Client-ID ' + MARTOR_IMGUR_CLIENT_ID}
response = requests.post(
url_api,
headers=headers,
data={
'key': MARTOR_IMGUR_API_KEY,
'image': base64.b64encode(image.read()),
'type': 'base64',
'name': image.name
}
)
"""
Some function we got from `response`:
['connection', 'content', 'cookies', 'elapsed', 'encoding', 'headers','history',
'is_permanent_redirect', 'is_redirect', 'iter_content', 'iter_lines', 'json',
'links', 'ok', 'raise_for_status', 'raw', 'reason', 'request', 'status_code', 'text', 'url']
"""
if response.status_code == 200:
respdata = json.loads(response.content.decode('utf-8'))
return json.dumps({
'status': respdata['status'],
'link': respdata['data']['link'],
'name': respdata['data']['name']
})
elif response.status_code == 415:
# Unsupport File type
return json.dumps({
'status': response.status_code,
'error': response.reason
})
return json.dumps({
'status': response.status_code,
'error': response.content.decode('utf-8')
})
|
Render the markdown content to HTML.
Basic:
>>> from martor.utils import markdownify
>>> content = ""
>>> markdownify(content)
'<p><img alt="awesome" src="http://i.imgur.com/hvguiSn.jpg" /></p>'
>>>
|
def markdownify(markdown_content):
"""
Render the markdown content to HTML.
Basic:
>>> from martor.utils import markdownify
>>> content = ""
>>> markdownify(content)
'<p><img alt="awesome" src="http://i.imgur.com/hvguiSn.jpg" /></p>'
>>>
"""
try:
return markdown.markdown(
markdown_content,
safe_mode=MARTOR_MARKDOWN_SAFE_MODE,
extensions=MARTOR_MARKDOWN_EXTENSIONS,
extension_configs=MARTOR_MARKDOWN_EXTENSION_CONFIGS
)
except Exception:
raise VersionNotCompatible("The markdown isn't compatible, please reinstall "
"your python markdown into Markdown>=3.0")
|
:rtype: list of SliceViewContext
|
def _ctxs(self):
"""
:rtype: list of SliceViewContext
"""
return [self._tab_widget.widget(index).context for index in range(0, self._tab_widget.count())]
|
:param widget: The SegyViewWidget that will be added to the SegyTabWidget
:type widget: SegyViewWidget
|
def add_segy_view_widget(self, ind, widget, name=None):
"""
:param widget: The SegyViewWidget that will be added to the SegyTabWidget
:type widget: SegyViewWidget
"""
if self._context is None:
self._segywidgets.append(widget)
self.initialize()
return 0 # return 0 for first widget index
self._tab_widget.updatesEnabled = False
widget.show_toolbar(toolbar=True, layout_combo=False, colormap=True, save=True, settings=True)
self._modify_qtree(widget.settings_window.qtree, [0, 1, 2, 4])
if name is None:
name = os.path.basename(widget.slice_data_source.source_filename)
id = self._tab_widget.insertTab(ind, widget, name)
widget.context.data_changed.connect(self._local_data_changed)
self._tab_widget.updatesEnabled = True
return id
|
:type indexes: list[int]
|
def indexes(self, indexes):
""" :type indexes: list[int] """
self._indexes = indexes
self._index = len(indexes) / 2
|
:type indexes: list[int]
|
def x_indexes(self, indexes):
""" :type indexes: list[int] """
self._assert_shape(self._data, indexes, self._y_indexes)
self._x_indexes = indexes
self.x_index = len(indexes) / 2
|
:type indexes: list[int]
|
def y_indexes(self, indexes):
""" :type indexes: list[int] """
self._assert_shape(self._data, self._x_indexes, indexes)
self._y_indexes = indexes
self.y_index = len(indexes) / 2
|
:type: numppy.ndarray
|
def data(self, data):
""" :type: numppy.ndarray """
self._assert_shape(data, self._x_indexes, self._y_indexes)
data[data == -np.inf] = 0.0
data[data == np.inf] = 0.0
self._data = data
self._min_value = np.nanmin(self.data)
self._max_value = np.nanmax(self.data)
self._data_x_indexes = list(range(data.shape[0]))
self._data_y_indexes = list(range(data.shape[1]))
self._dirty = False
|
:type index: int
|
def index(self, index):
""" :type index: int """
if self._index != index:
self._dirty = True
self._index = index
|
:type context: dict
|
def create_slice(self, context):
""" :type context: dict """
model = self._model
axes = self._image.axes
""" :type: matplotlib.axes.Axes """
axes.set_title(model.title, fontsize=12)
axes.tick_params(axis='both')
axes.set_ylabel(model.y_axis_name, fontsize=9)
axes.set_xlabel(model.x_axis_name, fontsize=9)
axes.get_xaxis().set_major_formatter(FuncFormatter(model.x_axis_formatter))
axes.get_xaxis().set_major_locator(AutoLocator())
axes.get_yaxis().set_major_formatter(FuncFormatter(model.y_axis_formatter))
axes.get_yaxis().set_major_locator(AutoLocator())
for label in (axes.get_xticklabels() + axes.get_yticklabels()):
label.set_fontsize(9)
self._reset_zoom()
axes.add_patch(self._vertical_indicator)
axes.add_patch(self._horizontal_indicator)
self._update_indicators(context)
self._image.set_cmap(cmap=context['colormap'])
self._view_limits = context["view_limits"][self._model.index_direction['name']]
if model.data is not None:
self._image.set_data(model.data)
|
:type context: dict
|
def data_changed(self, context):
""" :type context: dict """
model = self._model
self._image.set_data(model.data)
self._image.set_extent((0, model.width, model.height, 0))
|
:type context: dict
|
def context_changed(self, context):
""" :type context: dict """
self._image.set_cmap(context['colormap'])
self._image.set_clim(context['min'], context['max'])
self._image.set_interpolation(context['interpolation'])
self._update_indicators(context)
self._set_view_limits()
if self._model.index_direction is not SliceDirection.depth:
self._image.axes.set_ylabel(context['samples_unit'])
|
:type context: dict
|
def _update_indicators(self, context):
""" :type context: dict """
model = self._model
self._vertical_indicator.set_height(model.height + 1)
self._vertical_indicator.set_width(1)
self._horizontal_indicator.set_width(model.width + 1)
self._horizontal_indicator.set_height(1)
show_indicators = context['show_indicators']
self._vertical_indicator.set_visible(model.x_index is not None and show_indicators)
self._horizontal_indicator.set_visible(model.y_index is not None and show_indicators)
if model.x_index is not None and show_indicators:
self._vertical_indicator.set_x(model.x_index)
if model.y_index is not None and show_indicators:
self._horizontal_indicator.set_y(model.y_index)
|
:type index_direction: SliceDirection
:type index: int
|
def update_index_for_direction(self, index_direction, index):
"""
:type index_direction: SliceDirection
:type index: int
"""
indexes = self._slice_data_source.indexes_for_direction(index_direction)
if index < 0:
index = 0
elif index >= len(indexes):
index = len(indexes) - 1
for m in self._available_slice_models:
if m.index_direction == index_direction:
m.index = index
if m.x_index_direction == index_direction:
m.x_index = index
if m.y_index_direction == index_direction:
m.y_index = index
self.load_data()
|
:type: QVariant
|
def _get_spec(self, index):
user_data = self.itemData(index)
""" :type: QVariant"""
spec = user_data.toPyObject()
return {str(key): value for key, value in spec.items()}
|
:type color_map_name: str
:type image: QImage
:type values: np.ndarray
|
def _create_icon(self, color_map_name, image, values):
""""
:type color_map_name: str
:type image: QImage
:type values: np.ndarray
"""
color_map = ScalarMappable(cmap=color_map_name)
rgba = color_map.to_rgba(values, bytes=True)
color_table = [qRgb(c[0], c[1], c[2]) for c in rgba]
image.setColorTable(color_table)
return QPixmap.fromImage(image).scaledToWidth(128)
|
:param axes: The Axes instance to find the index of.
:type axes: Axes
:rtype: int
|
def index(self, axes):
"""
:param axes: The Axes instance to find the index of.
:type axes: Axes
:rtype: int
"""
return None if axes is self._colormap_axes else self._axes.index(axes)
|
Return package version as listed in `__version__` in `init.py`.
|
def get_version(package):
"""
Return package version as listed in `__version__` in `init.py`.
"""
init_py = codecs.open(os.path.join(package, '__init__.py'), encoding='utf-8').read()
return re.search("^__version__ = ['\"]([^'\"]+)['\"]", init_py, re.MULTILINE).group(1)
|
Get the entry url given and entry page a blog page instances.
It will use an url or another depending if blog_page is the root page.
|
def get_entry_url(entry, blog_page, root_page):
"""
Get the entry url given and entry page a blog page instances.
It will use an url or another depending if blog_page is the root page.
"""
if root_page == blog_page:
return reverse('entry_page_serve', kwargs={
'year': entry.date.strftime('%Y'),
'month': entry.date.strftime('%m'),
'day': entry.date.strftime('%d'),
'slug': entry.slug
})
else:
# The method get_url_parts provides a tuple with a custom URL routing
# scheme. In the last position it finds the subdomain of the blog, which
# it is used to construct the entry url.
# Using the stripped subdomain it allows Puput to generate the urls for
# every sitemap level
blog_path = strip_prefix_and_ending_slash(blog_page.specific.last_url_part)
return reverse('entry_page_serve_slug', kwargs={
'blog_path': blog_path,
'year': entry.date.strftime('%Y'),
'month': entry.date.strftime('%m'),
'day': entry.date.strftime('%d'),
'slug': entry.slug
})
|
Get the feeds urls a blog page instance.
It will use an url or another depending if blog_page is the root page.
|
def get_feeds_url(blog_page, root_page):
"""
Get the feeds urls a blog page instance.
It will use an url or another depending if blog_page is the root page.
"""
if root_page == blog_page:
return reverse('blog_page_feed')
else:
blog_path = strip_prefix_and_ending_slash(blog_page.specific.last_url_part)
return reverse('blog_page_feed_slug', kwargs={'blog_path': blog_path})
|
Registering the `blockquote` feature, which uses the `blockquote` Draft.js block type,
and is stored as HTML with a `<blockquote>` tag.
|
def register_blockquote_feature(features):
"""
Registering the `blockquote` feature, which uses the `blockquote` Draft.js block type,
and is stored as HTML with a `<blockquote>` tag.
"""
feature_name = 'blockquote'
type_ = 'blockquote'
tag = 'blockquote'
control = {
'type': type_,
'label': '❝',
'description': 'Quote',
'element': 'blockquote',
}
features.register_editor_plugin(
'draftail',
feature_name,
draftail_features.BlockFeature(control)
)
features.register_converter_rule(
'contentstate',
feature_name,
{
'from_database_format': {tag: BlockElementHandler(type_)},
'to_database_format': {'block_map': {type_: tag}},
}
)
features.default_features.append(feature_name)
|
Install all packages in dependency list via pip.
|
def install_dependencies(dependencies, verbose=False):
"""Install all packages in dependency list via pip."""
if not dependencies:
return
stdout = stderr = None if verbose else subprocess.DEVNULL
with tempfile.TemporaryDirectory() as req_dir:
req_file = Path(req_dir) / "requirements.txt"
with open(req_file, "w") as f:
for dependency in dependencies:
f.write(f"{dependency}\n")
pip = ["python3", "-m", "pip", "install", "-r", req_file]
# Unless we are in a virtualenv, we need --user
if sys.base_prefix == sys.prefix and not hasattr(sys, "real_prefix"):
pip.append("--user")
try:
subprocess.check_call(pip, stdout=stdout, stderr=stderr)
except subprocess.CalledProcessError:
raise Error(_("failed to install dependencies"))
# Reload sys.path, to find recently installed packages
importlib.reload(site)
|
Add check translations according to ``config`` as a fallback to existing translations
|
def install_translations(config):
"""Add check translations according to ``config`` as a fallback to existing translations"""
if not config:
return
from . import _translation
checks_translation = gettext.translation(domain=config["domain"],
localedir=internal.check_dir / config["localedir"],
fallback=True)
_translation.add_fallback(checks_translation)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.