Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Initial stab at chirpstack support #149

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
207 changes: 148 additions & 59 deletions lambda/ttn_helium/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

TOPIC = config_handler.get("HAM_SNS","TOPIC")

HELIUM_GW_VERSION = "2023.10.14"
HELIUM_GW_VERSION = "2024.11.10"

# Mappings between input (Helium) field names, and field names fed into SondeHub-Amateur
FIELD_MAPPINGS = [
Expand Down Expand Up @@ -76,81 +76,170 @@ def upload_helium(event, context):
# Iterate over list:
for payload in payloads:

try:
telem = {
'software_name': 'SondeHub-Amateur Helium Gateway',
'software_version': HELIUM_GW_VERSION
}
# Use the presence of the 'reported_at' field to determine if this data is from either
# Chirpstack, or the legacy Helium IoT.
if "reported_at" in payload:
chirpstack = False
else:
chirpstack = True

#
# Extract mandatory fields.
#
# Name -> Payload Callsign
telem['payload_callsign'] = payload['name']
if chirpstack:
try:
telem = {
'software_name': 'SondeHub-Amateur Helium Gateway',
'software_version': HELIUM_GW_VERSION
}

#
# Extract mandatory fields.
#
# Device Name -> Payload Callsign
telem['payload_callsign'] = payload["deviceInfo"]["deviceName"]

# Time
telem['datetime'] = payload["time"].split("+")[0] + "Z"

# Positional and other data
telem_data = payload["object"]["decoded"]

# Work through all accepted field names and map them
# into the output structure.
for _field in FIELD_MAPPINGS:
_input = _field[0]
_output = _field[1]

if _input in telem_data:
telem[_output] = telem_data[_input]

# Position field, required by OpenSearch
# If lat/lon are not in the telemetry, then this will error
telem["position"] = f'{telem["lat"]},{telem["lon"]}'

# We also need altitude as a minimum
if 'alt' not in telem:
raise IOError("No altitude field")

# Extract raw payload data, base64
telem["raw"] = payload["data"]

# Time
telem['datetime'] = datetime.datetime.utcfromtimestamp(payload["reported_at"]/1000.0).isoformat() + "Z"
except Exception as e:
errors.append({
"error_message": f"Error parsing telemetry data - {str(e)}",
"payload": payload
})
continue

# Positional and other data
telem_data = payload["decoded"]["payload"]
# Now iterate through the receiving stations
_frequency = payload['txInfo']['frequency']/1e6
_bw = int(payload['txInfo']['modulation']['lora']['bandwidth']/1000)
_sf = payload['txInfo']['modulation']['lora']['spreadingFactor']
_cr = payload['txInfo']['modulation']['lora']['codeRate'][3:].replace('_','')
_modulation = f"Helium (SF{_sf}BW{_bw}CR{_cr})"
for hotspot in payload['rxInfo']:
try:
hotspot_telem = telem.copy()

# Work through all accepted field names and map them
# into the output structure.
for _field in FIELD_MAPPINGS:
_input = _field[0]
_output = _field[1]
hotspot_telem['uploader_callsign'] = hotspot["metadata"]["gateway_name"]
hotspot_telem['modulation'] = _modulation
hotspot_telem['snr'] = hotspot['snr']
hotspot_telem['rssi'] = hotspot['rssi']
hotspot_telem['frequency'] = _frequency
hotspot_telem['time_received'] = hotspot["gwTime"].split("+")[0] + "Z"

if _input in telem_data:
telem[_output] = telem_data[_input]
try:
hotspot_telem['uploader_position'] = f'{hotspot["metadata"]["gateway_lat"]},{hotspot["metadata"]["gateway_long"]}'
hotspot_telem['uploader_alt'] = 0
except:
pass

# Position field, required by OpenSearch
# If lat/lon are not in the telemetry, then this will error
telem["position"] = f'{telem["lat"]},{telem["lon"]}'

to_sns.append(hotspot_telem)

# We also need altitude as a minimum
if 'alt' not in telem:
raise IOError("No altitude field")

# Extract raw payload data, base64
telem["raw"] = payload["payload"]
except Exception as e:
errors.append({
"error_message": f"Error parsing hotspot data - {str(e)}",
"payload": payload
})
continue

except Exception as e:
errors.append({
"error_message": f"Error parsing telemetry data - {str(e)}",
"payload": payload
})
continue

# Now iterate through the receiving stations
for hotspot in payload['hotspots']:
else:
try:
hotspot_telem = telem.copy()

hotspot_telem['uploader_callsign'] = hotspot['name']
hotspot_telem['modulation'] = f"Helium ({hotspot['spreading']})"
hotspot_telem['snr'] = hotspot['snr']
hotspot_telem['rssi'] = hotspot['rssi']
hotspot_telem['frequency'] = hotspot['frequency']
hotspot_telem['time_received'] = datetime.datetime.utcfromtimestamp(hotspot["reported_at"]/1000.0).isoformat() + "Z"

try:
hotspot_telem['uploader_position'] = f'{hotspot["lat"]},{hotspot["long"]}'
hotspot_telem['uploader_alt'] = 0
except:
pass

telem = {
'software_name': 'SondeHub-Amateur Helium Gateway',
'software_version': HELIUM_GW_VERSION
}

#
# Extract mandatory fields.
#
# Name -> Payload Callsign
telem['payload_callsign'] = payload['name']

# Time
telem['datetime'] = datetime.datetime.utcfromtimestamp(payload["reported_at"]/1000.0).isoformat() + "Z"

# Positional and other data
telem_data = payload["decoded"]["payload"]

# Work through all accepted field names and map them
# into the output structure.
for _field in FIELD_MAPPINGS:
_input = _field[0]
_output = _field[1]

if _input in telem_data:
telem[_output] = telem_data[_input]

# Position field, required by OpenSearch
# If lat/lon are not in the telemetry, then this will error
telem["position"] = f'{telem["lat"]},{telem["lon"]}'

# We also need altitude as a minimum
if 'alt' not in telem:
raise IOError("No altitude field")

to_sns.append(hotspot_telem)
# Extract raw payload data, base64
telem["raw"] = payload["payload"]

except Exception as e:
errors.append({
"error_message": f"Error parsing hotspot data - {str(e)}",
"payload": payload
"error_message": f"Error parsing telemetry data - {str(e)}",
"payload": payload
})
continue

# Now iterate through the receiving stations
for hotspot in payload['hotspots']:
try:
hotspot_telem = telem.copy()

hotspot_telem['uploader_callsign'] = hotspot['name']
hotspot_telem['modulation'] = f"Helium ({hotspot['spreading']})"
hotspot_telem['snr'] = hotspot['snr']
hotspot_telem['rssi'] = hotspot['rssi']
hotspot_telem['frequency'] = hotspot['frequency']
hotspot_telem['time_received'] = datetime.datetime.utcfromtimestamp(hotspot["reported_at"]/1000.0).isoformat() + "Z"

try:
hotspot_telem['uploader_position'] = f'{hotspot["lat"]},{hotspot["long"]}'
hotspot_telem['uploader_alt'] = 0
except:
pass


to_sns.append(hotspot_telem)

except Exception as e:
errors.append({
"error_message": f"Error parsing hotspot data - {str(e)}",
"payload": payload
})
continue

#print(to_sns)
post(to_sns)
#import pprint
#pprint.pprint(to_sns)
#post(to_sns)
return errors, warnings


Expand Down
61 changes: 60 additions & 1 deletion lambda/ttn_helium/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@

import sys

filename = "./ttn_helium/helium_test_data.json"

filename = "./ttn_helium/chirpstack_test_data.json"

_f = open(filename, 'r')
_json = json.loads(_f.read())
Expand All @@ -20,7 +21,62 @@
compressed.seek(0)
bbody = base64.b64encode(compressed.read()).decode("utf-8")

payload = {
"version": "2.0",
"routeKey": "POST /helium",
"rawPath": "/helium",
"rawQueryString": "",
"headers": {
"accept": "*/*",
"accept-encoding": "gzip, deflate",
"content-encoding": "gzip",
"content-length": "2135",
"content-type": "application/json",
"host": "api.v2.sondehub.org",
"user-agent": "autorx-1.4.1-beta4",
"x-amzn-trace-id": "Root=1-6015f571-6aef2e73165042d53fcc317a",
"x-forwarded-for": "103.107.130.22",
"x-forwarded-port": "443",
"x-forwarded-proto": "https",
"date": "Sun, 31 Jan 2021 00:21:45 GMT",
},
"requestContext": {
"accountId": "143841941773",
"apiId": "r03szwwq41",
"domainName": "api.v2.sondehub.org",
"domainPrefix": "api",
"http": {
"method": "POST",
"path": "/helium",
"protocol": "HTTP/1.1",
"sourceIp": "103.107.130.22",
"userAgent": "everybody-needs-to-get-a-blimp",
},
"requestId": "Z_NJvh0RoAMEJaw=",
"routeKey": "PUT /sondes/telemetry",
"stage": "$default",
"time": "31/Jan/2021:00:10:25 +0000",
"timeEpoch": 1612051825409,
},
"body": bbody,
"isBase64Encoded": True,
}

print(lambda_handler_helium(payload, {}))


filename = "./ttn_helium/helium_test_data.json"

_f = open(filename, 'r')
_json = json.loads(_f.read())

body = _json

compressed = BytesIO()
with gzip.GzipFile(fileobj=compressed, mode='w') as f:
f.write(json.dumps(body).encode('utf-8'))
compressed.seek(0)
bbody = base64.b64encode(compressed.read()).decode("utf-8")

payload = {
"version": "2.0",
Expand Down Expand Up @@ -66,6 +122,9 @@
print(lambda_handler_helium(payload, {}))





filename = "./ttn_helium/ttn_test_data.json"

_f = open(filename, 'r')
Expand Down
Loading
Loading