Arrow / Mbed OS DAPLink Reset
Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers mbedapi.py Source File

mbedapi.py

00001 #
00002 # DAPLink Interface Firmware
00003 # Copyright (c) 2009-2016, ARM Limited, All Rights Reserved
00004 # SPDX-License-Identifier: Apache-2.0
00005 #
00006 # Licensed under the Apache License, Version 2.0 (the "License"); you may
00007 # not use this file except in compliance with the License.
00008 # You may obtain a copy of the License at
00009 #
00010 # http://www.apache.org/licenses/LICENSE-2.0
00011 #
00012 # Unless required by applicable law or agreed to in writing, software
00013 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
00014 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
00015 # See the License for the specific language governing permissions and
00016 # limitations under the License.
00017 #
00018  
00019 """
00020 
00021 Usage example:
00022 
00023 python mbedapi.py  --repo http://developer.mbed.org/users/dan/code/pubtest/
00024 --user dan --api http://developer.mbed.org --platform mbed-LPC1768
00025 --destdir /tmp/ --debug 2
00026 
00027 This will compile http://developer.mbed.org/users/dan/code/pubtest/
00028 for the 1768 and download the result.
00029 
00030 Examples of options:
00031 --extra_symbols "foo=bar,x=y"
00032 
00033 --replace_file "main.cpp:/tmp/replace_main.cpp"
00034 (can be repeated)
00035 
00036 """
00037 import os
00038 import getpass
00039 import json
00040 import time
00041 import requests
00042 import logging
00043 
00044 MBED_API_SERVER = 'https://os.mbed.com/'
00045 
00046 
00047 def build_repo(user, password, repo, platform, destdir,
00048                replace='', symbols='', clean=False, api=MBED_API_SERVER):
00049 
00050     payload = {
00051         'clean': clean,
00052         'platform': platform,
00053         'repo': repo,
00054         'extra_symbols': symbols
00055     }
00056 
00057     if replace:
00058         replace = []
00059         for pair in replace:
00060             dest = pair.split(':')[0]
00061             src = pair.split(':')[1]
00062             print(dest)
00063             cwd = os.getcwd()
00064             srcfile = open(os.path.join(cwd, src), 'r')
00065             replace.append({dest: srcfile.read()})
00066 
00067         payload['replace'] = json.dumps(replace)
00068         logging.debug("Payload is: %s" % payload)
00069 
00070     auth = (user, password,)
00071 
00072     # send task to api
00073     logging.debug(api + "/api/v2/tasks/compiler/start/" + "| data: " +
00074                   str(payload))
00075     r = requests.post(api + "/api/v2/tasks/compiler/start/",
00076                       data=payload, auth=auth)
00077 
00078     logging.debug(r.content)
00079 
00080     if r.status_code != 200:
00081         raise Exception("Error while talking to the mbed API")
00082 
00083     uuid = json.loads(r.content)['result']['data']['task_id']
00084     logging.debug("Task accepted and given ID: %s" % uuid)
00085     success = False
00086 
00087     # poll for output
00088     for check in range(0, 40):
00089         logging.debug("Checking for output: cycle %s of %s" % (check, 10))
00090         time.sleep(2)
00091         r = requests.get(api + "/api/v2/tasks/compiler/output/%s" %
00092                          uuid, auth=auth)
00093         logging.debug(r.content)
00094         response = json.loads(r.content)
00095         messages = response['result']['data']['new_messages']
00096         percent = 0
00097         for message in messages:
00098             if message.get('message'):
00099                 if message.get('type') != 'debug':
00100                     logging.info("[%s] %s" % (message['type'],
00101                                               message['message']))
00102             if message.get('action'):
00103                 if message.get('percent'):
00104                     percent = message['percent']
00105                 logging.info("[%s%% - %s] %s " % (percent, message['action'],
00106                                                   message.get('file', '')))
00107 
00108         if response['result']['data']['task_complete']:
00109             logging.info("Task completed.")
00110             success = response['result']['data']['compilation_success']
00111             logging.info("Compile success: %s" % (success))
00112             break
00113 
00114     # now download
00115     if success:
00116         logging.info("Downloading your binary")
00117         params = {
00118             'repomode': True,
00119             'program': response['result']['data']['program'],
00120             'binary': response['result']['data']['binary'],
00121             'task_id': uuid
00122         }
00123         r = requests.get(api + "/api/v2/tasks/compiler/bin/",
00124                          params=params, auth=auth)
00125         destination = os.path.join(destdir,
00126                                    response['result']['data']['binary'])
00127 
00128         with open(destination, 'wb') as fd:
00129             for chunk in r.iter_content(1024):
00130                 fd.write(chunk)
00131 
00132         logging.info("Finished!")
00133     else:
00134         raise Exception("Failed to build platform %s" % platform)
00135     return destination
00136 
00137 if __name__ == "__main__":
00138     import argparse
00139     parser = argparse.ArgumentParser(description='Build an mbed repository.')
00140     parser.add_argument('--user', type=str, help='Your username on mbed.', required=True)
00141     parser.add_argument('--password', type=str, help='Your password on mbed.', default=None, required=False)
00142     parser.add_argument('--api', type=str, help='URL to API server', required=False, default=MBED_API_SERVER)
00143     parser.add_argument('--repo', type=str, help='URL of repository to build.', required=True)
00144     parser.add_argument('--platform', type=str, help='Platform name', required=True)
00145     parser.add_argument('--destdir', type=str, help='Binary destination directory', required=True)
00146     parser.add_argument('--replace_file', type=str, help='Replace file and build. Can be repeated. Syntax: remotepath:localpath', required=False, action='append')
00147     parser.add_argument('--extra_symbols', type=str, help='Provide extra symbols to build system', required=False, action='append')
00148     parser.add_argument('--clean', action='store_true', help='Force clean build')
00149     parser.add_argument('--debug', help='Show debugging info', required=False)
00150 
00151     args = parser.parse_args()
00152     if args.debug:
00153         logging.basicConfig(level=logging.DEBUG)
00154     else:
00155         logging.basicConfig(level=logging.INFO)
00156     if args.password is None:
00157         args.password = getpass.getpass('mbed password: ')
00158     build_repo(args.user, args.password, args.repo, args.platform,
00159                args.destdir, args.replace_file, args.extra_symbols,
00160                args.clean, args.api)