Skip to content

Commit

Permalink
Switched to requests and made configure mandatory before use
Browse files Browse the repository at this point in the history
  • Loading branch information
Tej Pochiraju committed May 10, 2021
1 parent 0b049c8 commit 453bac8
Showing 1 changed file with 68 additions and 71 deletions.
139 changes: 68 additions & 71 deletions bodh.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,15 @@
import click
import http.client
import requests
import json
import os
from os import path, makedirs
from time import sleep
from config_path import ConfigPath

default_host = "localhost"
default_port = 4000
default_host = "https://bodh.iotready.co"

conf_path = ConfigPath( 'bodh', 'iotready.co', '.json' )
file_path = conf_path.saveFilePath( mkdir=False )

path = conf_path.readFilePath()
if path is not None:
with open(file_path, "r") as f:
config = json.load(f)
else:
config = {}


@click.group()
def cli():
Expand All @@ -26,85 +18,88 @@ def cli():

@cli.command()
@click.option('--host', default=default_host, prompt="Bodh host", help='Bodh host (for self-hosted).')
@click.option('--port', default=default_port, prompt="Bodh host port", help='Bodh host port (for self-hosted).')
@click.option('--secure', default=True, prompt="Use SSL", help='Use SSL to connect.')
@click.option('--apikey', prompt='Admin API key', help='Admin API key to save.')
def save(host, port, secure, apikey):
def configure(host, apikey):
"""Save host and apikey in the user's config directory."""
config = {
"apikey": apikey,
"api_key": apikey,
"host": host,
"port": port,
"secure": secure
}
with open(file_path, "w") as f:
json.dump(config, f)
click.echo('Stored config at: %s' % file_path)


def read_saved_config():
path = conf_path.readFilePath()
assert path, "Could not locate config file. Please run `bodh configure` first."

with open(file_path, "r") as f:
config = json.load(f)
host = config['host']
api_key = config['api_key']

assert host and api_key, "Could not detect host or API key. Please run `bodh configure` again."
return host, api_key

@cli.command()
@click.option('--host', default=config.get('host') or default_host, help='Bodh host (for self-hosted).')
@click.option('--port', default=config.get('port') or default_port, help='Bodh host (for self-hosted).')
@click.option('--secure', default=config.get('secure'), help='Bodh host (for self-hosted).')
@click.option('--apikey', default=config.get('apikey'), prompt='Admin API key', help='Admin API key.')
@click.option('--deviceid', prompt='Device ID',
help='ID of device to register')
def register(host, port, secure, apikey, deviceid):
@click.option('--deviceid', prompt='Device ID', help='ID of device to register')
def register(deviceid):
"""Register a device using the apikey."""
# TODO: migrate to requests
api_endpoint = "/api/devices"
if secure:
conn = http.client.HTTPSConnection(host, port)
else:
conn = http.client.HTTPConnection(host, port)
payload = json.dumps({
"device": {
"id": deviceid

host, api_key = read_saved_config()

url = host + "/api/devices"
payload = {
"device": {
"id": deviceid
}
}
})
headers = {
'Accept': 'application/json',
'x-api-key': apikey,
'Content-Type': 'application/json'
'Accept': 'application/json',
'x-api-key': api_key,
'Content-Type': 'application/json'
}
conn.request("POST", api_endpoint, payload, headers)
res = conn.getresponse()
data = res.read()
data = json.loads(data.decode("utf-8"))

res = requests.post(url, data = json.dumps(payload), headers = headers)

data = res.json()
base_path = "certs/{}".format(deviceid)
mkdir(base_path)
for key, url in data.items():
download_file(url)

click.echo("All done!")
download_file(url, base_path)
click.echo("Use the saved certifcates to connect device with ID {} to AWS IoT!".format(deviceid))

def download_file(url):
def download_file(url, base_path):
r = requests.get(url, allow_redirects=True)
file_name = get_file_name(url)
print("Downloading", file_name)
with open(file_name, 'wb') as f:
file_path = path.join(base_path, file_name)
print("Downloading", file_path)
with open(file_path, 'wb') as f:
f.write(r.content)


def get_file_name(url):
return url.split('?')[0].split('/')[-1]


def mkdir(path):
makedirs(path, exist_ok=True)

@cli.command()
@click.option('--host', default=config.get('host') or default_host, help='Bodh host (for self-hosted).')
@click.option('--port', default=config.get('port') or default_port, help='Bodh host (for self-hosted).')
@click.option('--secure', default=config.get('secure'), help='Bodh host (for self-hosted).')
@click.option('--apikey', default=config.get('apikey'), prompt='Admin API key', help='Admin API key.')
@click.option('--deviceid', prompt='Device ID',
help='ID of device for which to send a test event.')
def sendevent(host, port, secure, apikey, deviceid):
"""Sends a test event using the apikey."""
# TODO: migrate to requests
api_endpoint = "/api/events"
if secure:
conn = http.client.HTTPSConnection(host, port)
else:
conn = http.client.HTTPConnection(host, port)
payload = json.dumps({
@click.option('--deviceid', prompt='Device ID', help='ID of device for which to send a test event.')
@click.option('--interval', prompt='Interval', default=10, type=int, help='Interval between test events (min = 5s).')
def simulate(deviceid, interval):
"""Sends `MAX` test events using the apikey."""
MAX = 10

if interval < 5:
interval = 5
print("Using min interval of 5s")

host, api_key = read_saved_config()

url = host + "/api/events"
payload = {
"event": {
"device_id": deviceid,
"data": {
Expand All @@ -113,16 +108,18 @@ def sendevent(host, port, secure, apikey, deviceid):
"metric3": "dry"
}
}
})
}
headers = {
'Accept': 'application/json',
'x-api-key': apikey,
'Content-Type': 'application/json'
'Accept': 'application/json',
'x-api-key': api_key,
'Content-Type': 'application/json'
}
conn.request("POST", api_endpoint, payload, headers)
res = conn.getresponse()
data = res.read()
click.echo(data.decode("utf-8"))

for i in range(0, MAX):
res = requests.post(url, data=json.dumps(payload), headers=headers)
data = res.json()
click.echo(data)
sleep(interval)

if __name__ == '__main__':
cli()

0 comments on commit 453bac8

Please sign in to comment.