summaryrefslogtreecommitdiffstats
path: root/scripts/sdks
diff options
context:
space:
mode:
Diffstat (limited to 'scripts/sdks')
-rwxr-xr-xscripts/sdks/agl/db-dump265
1 files changed, 129 insertions, 136 deletions
diff --git a/scripts/sdks/agl/db-dump b/scripts/sdks/agl/db-dump
index aa8b30d..77f729e 100755
--- a/scripts/sdks/agl/db-dump
+++ b/scripts/sdks/agl/db-dump
@@ -1,137 +1,130 @@
-#! /usr/bin/env nodejs
-
-/**************************************************************************
- * Copyright 2017-2018 IoT.bzh
- *
- * author: Sebastien Douheret <sebastien@iot.bzh>
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- **************************************************************************/
-
-const fs = require('fs');
-const process = require('process');
-const execSync = require('child_process').execSync;
-const path = require('path');
-
-
-// Only used for debug purpose
-const DEBUG = false || (process.argv.length > 2 && process.argv[2] == '-debug');
-dbgPrint = function () {
- if (DEBUG) console.log.apply(console, arguments);
-}
-// Get env vars
-var envMap = {};
-envData = execSync(path.join(__dirname, '_env-init.sh -print'));
-envData.toString().split('\n').forEach(e => envMap[e.split('=')[0]] = e.split('=')[1]);
-const opts = {
- cwd: __dirname,
- env: envMap
-};
-
-// Get list of available SDKs
-sdksDBFile = path.join(envMap["SDK_ROOT_DIR"], "sdks_latest.json")
-try {
- // Fetch SDK Json database file when not existing
- if (!fs.existsSync(sdksDBFile)) {
- var data = execSync(path.join(__dirname, 'db-update ' + sdksDBFile), opts);
- }
- // Read SDK Json database file
- var data = fs.readFileSync(sdksDBFile);
- var sdks = JSON.parse(data);
-
- // Force some default fields value
- sdks.forEach(sdk => {
- sdk.status = 'Not Installed';
- });
-} catch (err) {
- dbgPrint('ERROR: ', err);
- process.exit(-1)
-}
-
-// Get list of installed SDKs
-try {
- const cmd = 'find "${SDK_ROOT_DIR}" -maxdepth 4 -name "${SDK_ENV_SETUP_FILENAME}"';
- var data = execSync(cmd, opts);
- data.toString().split('\n').forEach(envFile => {
- if (envFile == '') return;
-
- dbgPrint('Processing ', envFile);
- const profile = envFile.split('/')[3];
- const version = envFile.split('/')[4];
- const arch = envFile.split('/')[5];
- const dir = path.dirname(envFile);
- if (profile == '' || version == '' || arch == '' || dir == '') {
- return;
- }
-
- sdkDate = ''
- versionFile = path.join(path.dirname(envFile), 'version-*')
- try {
- cmdVer = "[ -f " + versionFile + " ] && grep Timestamp " + versionFile + " |cut -d' ' -f2"
- var data = execSync(cmdVer);
- } catch (err) {
- dbgPrint('IGNORING SDK ', dir);
- dbgPrint(err.toString());
- if (DEBUG) {
- process.exit(-1);
- } else {
- return;
- }
- }
- d = data.toString()
- if (d != "") {
- sdkDate = d.substring(0, 4) + "-" + d.substring(4, 6) + "-" + d.substring(6, 8)
- sdkDate += " " + d.substring(8, 10) + ":" + d.substring(10, 12)
- }
-
- var found = false;
- sdks.forEach(sdk => {
- // Update sdk with local info when found
- if (profile == sdk.profile && version == sdk.version && arch == sdk.arch) {
- found = true;
- dbgPrint(" OK found, updating...");
- sdk.path = dir;
- sdk.status = 'Installed';
- sdk.data = sdkDate;
- sdk.setupFile = envFile;
- return
+#!/usr/bin/python
+#
+#/**************************************************************************
+# * Copyright 2017-2018 IoT.bzh
+# *
+# * author: Romain Forlot <romain.forlot@iot.bzh>
+# *
+# * Licensed under the Apache License, Version 2.0 (the "License");
+# * you may not use this file except in compliance with the License.
+# * You may obtain a copy of the License at
+# *
+# * http://www.apache.org/licenses/LICENSE-2.0
+# *
+# * Unless required by applicable law or agreed to in writing, software
+# * distributed under the License is distributed on an "AS IS" BASIS,
+# * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# * See the License for the specific language governing permissions and
+# * limitations under the License.
+# **************************************************************************/
+
+import os
+import json
+import logging
+import inspect
+import fnmatch
+import argparse
+import subprocess
+
+PARSER = argparse.ArgumentParser(description='Lists available and installed SDKs')
+PARSER.add_argument('-debug', dest='debug', action='store_true',
+ help='Output debug log messages')
+
+ARGS = PARSER.parse_args()
+
+if ARGS.debug:
+ logging.basicConfig(level=logging.DEBUG, format='%(asctime)s:%(levelname)s: %(message)s')
+else:
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s:%(levelname)s: %(message)s')
+
+SCRIPT_PATH = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
+
+ENV = subprocess.check_output([os.path.join(SCRIPT_PATH, './_env-init.sh'), '-print']).splitlines()
+
+for elt in ENV:
+ k, v = elt.split('=', 1)
+ if k == 'SDK_ROOT_DIR':
+ SDK_ROOT_DIR = v
+ elif k == 'SDK_ENV_SETUP_FILENAME':
+ SDK_ENV_SETUP_FILENAME = v
+
+if SDK_ROOT_DIR is None:
+ logging.error('No SDK_ROOT_DIR environment variable found.')
+ exit(1)
+elif SDK_ENV_SETUP_FILENAME is None:
+ SDK_ENV_SETUP_FILENAME = 'environment-setup*'
+
+# Get list of available SDKs
+SDK_DB_FILEPATH = os.path.join(SDK_ROOT_DIR, "sdks_latest.json")
+
+if not os.path.exists(SDK_DB_FILEPATH):
+ DB_UPDATE_FILEPATH = os.path.join(SCRIPT_PATH, 'db-update')
+ os.system(DB_UPDATE_FILEPATH + " " + SDK_DB_FILEPATH)
+
+SDK_DB_JSON = json.load(open(SDK_DB_FILEPATH, 'r'))
+
+for one_sdk in SDK_DB_JSON:
+ one_sdk['status'] = 'Not Installed'
+
+INSTALLED_SDK = []
+for root, dirs, files in os.walk(SDK_ROOT_DIR):
+ depth = root[len(SDK_ROOT_DIR) + len(os.path.sep):].count(os.path.sep)
+ if depth >= 4:
+ dirs[:] = []
+ EF, VF = '', ''
+ for one_file in files:
+ if fnmatch.fnmatch(one_file, SDK_ENV_SETUP_FILENAME):
+ EF = os.path.join(root, one_file)
+ if fnmatch.fnmatch(one_file, 'version-*'):
+ VF = os.path.join(root, one_file)
+ if EF != '' and VF != '':
+ INSTALLED_SDK.append({'ENV_FILE': EF, 'VERSION_FILE': VF})
+
+for one_sdk in INSTALLED_SDK:
+ logging.debug("Processing %s", one_sdk['ENV_FILE'])
+ PROFILE = one_sdk['ENV_FILE'].split('/')[3]
+ VERSION = one_sdk['ENV_FILE'].split('/')[4]
+ ARCH = one_sdk['ENV_FILE'].split('/')[5]
+ DIR = os.path.dirname(one_sdk['ENV_FILE'])
+ if PROFILE == '' or VERSION == '' or ARCH == '' or DIR == '':
+ logging.debug('Path not compliant, skipping')
+ continue
+
+ SDK_DATE = ''
+ for line in open(one_sdk['VERSION_FILE']).readlines():
+ if line.startswith('Timestamp'):
+ D = line.split(':')[1]
+ if D:
+ D = D.strip()
+ SDK_DATE = '{}-{}-{} {}:{}'.format(D[0:4], D[4:6], D[6:8], D[8:10], D[10:12])
+ logging.debug('Found date: %s', SDK_DATE)
+
+ found = False
+ for sdk in SDK_DB_JSON:
+ if sdk['profile'] == PROFILE and sdk['version'] == VERSION and sdk['arch'] == ARCH:
+ found = True
+ sdk['status'] = 'Installed'
+ sdk['date'] = SDK_DATE
+ sdk['setupFile'] = one_sdk['ENV_FILE']
+ sdk['path'] = DIR
+ break
+
+ if not found:
+ logging.debug('Not found in database, adding it...')
+ NEW_SDK = {
+ 'name': PROFILE + '-' + ARCH + '-' + VERSION,
+ 'description': 'AGL SDK ' + ARCH + ' (version ' + VERSION + ')',
+ 'profile': PROFILE,
+ 'version': VERSION,
+ 'arch': ARCH,
+ 'path': DIR,
+ 'url': "",
+ 'status': "Installed",
+ 'date': SDK_DATE,
+ 'size': "",
+ 'md5sum': "",
+ 'setupFile': one_sdk['ENV_FILE']
}
- });
- if (found == false) {
- dbgPrint(" NOT found in database, adding it...");
- sdks.push({
- name: profile + '-' + arch + '-' + version,
- description: 'AGL SDK ' + arch + ' (version ' + version + ')',
- profile: profile,
- version: version,
- arch: arch,
- path: dir,
- url: "",
- status: "Installed",
- date: sdkDate,
- size: "",
- md5sum: "",
- setupFile: envFile
- });
/*
 * Copyright (C) 2018, 2019 "IoT.bzh"
 * Author "Arthur Guyader" <arthur.guyader@iot.bzh>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *	 http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <cstring>
#include <iomanip>
#include <net/if.h>
#include "../../binding/low-can-hat.hpp"
#include "../../utils/converter.hpp"
#include "j1939-message.hpp"

/**
 * @brief Construct a new j1939 message t::j1939 message t object
 *
 */
j1939_message_t::j1939_message_t():
	message_t(),
	name_{0},
	pgn_{0},
	addr_{0}
{}

/**
 * @brief Construct a new j1939 message t::j1939 message t object
 *
 * @param length The length of the message
 * @param format The format of the message
 * @param data The vector data of the message
 * @param timestamp The timetamp of the message
 * @param name The name of the message
 * @param pgn The PGN of the message
 * @param addr The address of the message
 */
j1939_message_t::j1939_message_t(uint32_t length,
	std::vector<uint8_t>& data,
	uint64_t timestamp,
	name_t name,
	pgn_t pgn,
	uint8_t addr):
	message_t(J1939_MAX_DLEN, length, J1939_PROTOCOL, data, timestamp),
	name_{name},
	pgn_{pgn},
	addr_{addr}
{}

///
/// @brief Retrieve name_ member value.
///
/// @return name_ class member
///
uint64_t j1939_message_t::get_name() const {
	return name_;
}

///
/// @brief Retrieve pgn_ member value.
///
/// @return pgn_ class member
///
uint32_t j1939_message_t::get_pgn() const{
	return pgn_;
}

///
/// @brief Retrieve addr_ member value.
///
/// @return addr_ class member
///
uint8_t j1939_message_t::get_addr() const{
	return addr_;
}


/// @brief Take a sockaddr_can struct and array of data to initialize class members
///
/// This is the preferred way to initialize class members.
///
/// @param[in] addr - sockaddr_can to get pgn, name and addr
/// @param[in] data - array of data get from the j1939 socket
/// @param[in] nbytes - size of the array of data
/// @param[in] timestamp - timestamp of the message
///
/// @return A j1939_message_t object fully initialized with sockaddr_can and data values.
std::shared_ptr<j1939_message_t> j1939_message_t::convert_from_addr(struct sockaddr_can& addr, uint8_t (&data)[128],size_t nbytes, uint64_t timestamp)
{
	int i;
	uint32_t length = 0;
	uint32_t flags;
	std::vector<uint8_t> data_vector;

	if(nbytes > J1939_MAX_DLEN)
	{
		AFB_DEBUG("Unsupported j1939 frame");
		return std::make_shared<j1939_message_t>(j1939_message_t());
	}

	length = (uint32_t) nbytes;
	data_vector.reserve(length);

	data_vector.clear();

	std::string data_string;
	data_string = converter_t::to_hex(data,length);

	for(i=0;i<length;i++)
	{
		data_vector.push_back(data[i]);
	};

	AFB_DEBUG("Found pgn: %X, length: %X, data %s",
							addr.can_addr.j1939.pgn, length, data_string.c_str());

	return std::make_shared<j1939_message_t>(j1939_message_t(length, data_vector, timestamp,addr.can_addr.j1939.name,addr.can_addr.j1939.pgn,addr.can_addr.j1939.addr));
}

/// @brief Test if members pgn_ and length are set.
///
/// @return boolean - true = set - false = not set
bool j1939_message_t::is_set()
{
	return (pgn_ != 0 && length_ != 0);
}

/// @brief Generate a string with informations about the message
///
/// @return Debug message with informations about members
std::string j1939_message_t::get_debug_message()
{
	std::string ret = "";
	ret = ret + "Here is the next j1939 message : pgn " + std::to_string(pgn_)  + " length " + std::to_string(length_) + ", data ";
	for (size_t i = 0; i < data_.size(); i++)
	{
		ret = ret + std::to_string(data_[i]);
	}
	return ret;
}

///
/// @brief Retrieve pgn_ member value.
///
/// @return pgn_ class member
///
uint32_t j1939_message_t::get_id() const
{
	AFB_DEBUG("Prefer method get_pgn() for j1939 messages");
	return get_pgn();
}

/**
 * @brief Return the sockname of the message
 *
 * @return struct sockaddr_can The sockname of the message
 */
struct sockaddr_can j1939_message_t::get_sockname()
{
	return sockname_;
}

/**
 * @brief Allows to set a sockname at a message to send it after
 *
 * @param sockname The sockname of the message
 */
void j1939_message_t::set_sockname(struct sockaddr_can sockname)
{
	sockname_ = sockname;
}

/**
 * @brief Allows to generate a sockname for the message
 *
 * @param pgn The pgn for the sockname
 * @param name The name for the sockname
 * @param addr The address for the sockname
 */
void j1939_message_t::set_sockname(pgn_t pgn, name_t name, uint8_t addr)
{
	memset(&sockname_, 0, sizeof(sockname_));
	sockname_.can_family = AF_CAN;
	sockname_.can_ifindex = 0;

	if(addr <= 0 || addr >= UINT8_MAX )
	{
		sockname_.can_addr.j1939.addr = J1939_NO_ADDR;
	}
	else
	{
		sockname_.can_addr.j1939.addr = addr;
	}

	if(name <= 0 || name >= UINT64_MAX )
	{
		sockname_.can_addr.j1939.name = J1939_NO_NAME;
	}
	else
	{
		sockname_.can_addr.j1939.name = name;
	}

	if(pgn <= 0 || pgn > J1939_PGN_MAX)
	{
		sockname_.can_addr.j1939.pgn = J1939_NO_PGN;
	}
	else
	{
		sockname_.can_addr.j1939.pgn = pgn;
	}
}