code
stringlengths
1
1.05M
repo_name
stringlengths
6
83
path
stringlengths
3
242
language
stringclasses
222 values
license
stringclasses
20 values
size
int64
1
1.05M
import * as SPI from 'SPI' function byteArrayToArrayBuffer(byteArray) { return new Uint8Array(byteArray).buffer } class HW_SPI { constructor(options) { if (!options || !options.id) { throw new Error("options is invalid"); } this.options = { id: options.id }; this.success = options.success || function(){}; this.fail = options.fail || function(){}; this._open(); } _open() { this.spiInstance = SPI.open(this.options.id); if (Object.prototype.toString.call(this.spiInstance) !== '[object Object]') { this.fail(); } else { this.success(); } } write(data) { if (!this.spiInstance || !data) { throw new Error("spi not init or params is invalid"); } return this.spiInstance.write(byteArrayToArrayBuffer(data)); } read(bytes) { if (!this.spiInstance || !bytes) { throw new Error("spi not init or params is invalid"); } return Array.prototype.slice.call(new Uint8Array(this.spiInstance.read(bytes))); }; readWrite(sendData, bytes) { if (!this.spiInstance || !sendData ||!bytes) { throw new Error("spi not init or params is invalid"); } return Array.prototype.slice.call(new Uint8Array(this.spiInstance.sendRecv(byteArrayToArrayBuffer(sendData),bytes))); }; close() { if (!this.spiInstance) { throw new Error("spi not init"); } this.spiInstance.close(this.spiInstance); }; } export function open(options) { return new HW_SPI(options); }
YifuLiu/AliOS-Things
components/amp/jslib/src/spi.js
JavaScript
apache-2.0
1,674
'use strict'; import * as event from 'events' import * as TCP from 'TCP' class TCPClient extends event.EventEmitter{ constructor(options) { super(); if (!options || !options.host || !options.port) { throw new Error("invalid params"); } this.options = { host: options.host, port: options.port } this.success = options.success || function(){}; this.fail = options.fail || function(){}; this._connect(); } _connect() { this.connected = false; var cb = function(ret) { if (ret < 0) { this.fail(); this.emit('error', 'tcp connect error'); return; } this.tcpClientInstance = ret; this.connected = true; this.success(); this.emit('connect'); this._onListening(); } if(TCP.createSocket(this.options, cb.bind(this)) < 0){ this.fail(); this.emit('error', 'tcp connect error'); } } send(options) { if (!options.message) { throw new Error("tcp send message is empty"); } if(this.connected === false) { throw new Error("tcp not connected"); } TCP.send(this.tcpClientInstance, options.message, function(ret) { if (ret < 0) { this.emit('error', 'tcp send error'); if(options.fail) options.fail(); return; } this.emit('send', 'tcp send success'); if(options.success) options.success(); }.bind(this)); }; _onListening() { if (!this.tcpClientInstance) { throw new Error("tcpserver not init"); } TCP.recv(this.tcpClientInstance, function(datalen, data) { if (datalen === -2) { this.connected = false; this.emit('error', 'tcp receive message error'); return; } if (datalen === -1) { this.connected = false; this.emit('disconnect'); return; } if (datalen > 0) { this.emit('message', data); } }.bind(this)); }; close() { if (!this.tcpClientInstance) { throw new Error("tcpserver not init"); } var ret = TCP.close(this.tcpClientInstance); if (ret != 0) { this.emit('error', 'tcp socket close error'); return; } this.emit('close', 'tcp socket close success'); }; reconnect() { if (this.tcpClientInstance) { TCP.close(this.tcpClientInstance); } this._connect(); }; } export function createClient(options) { return new TCPClient(options); }
YifuLiu/AliOS-Things
components/amp/jslib/src/tcp.js
JavaScript
apache-2.0
2,890
import * as UART from 'UART' import * as event from 'events' function byteArrayToArrayBuffer(byteArray) { return new Uint8Array(byteArray).buffer } class HW_UART extends event.EventEmitter{ constructor(options) { super(); if (!options || !options.id) { throw new Error("options is invalid"); } this.options = { id: options.id, mode: options.mode }; this.success = options.success || function(){}; this.fail = options.fail || function(){}; this._open(); if (this.options.mode !== 'poll') { this._onData(); } } _open() { this.uartInstance = UART.open(this.options.id); if (this.uartInstance === null) { this.fail(); return; } this.success(); } write(data) { if (this.uartInstance === null || !data) { throw new Error("uart not init"); } if (Object.prototype.toString.call(data) !== '[object String]') { this.uartInstance.write(byteArrayToArrayBuffer(data)); } else { this.uartInstance.write(data); } } read() { if (this.uartInstance === null) { throw new Error("uart not init"); } return this.uartInstance.read(); }; off() { if (this.uartInstance === null) { throw new Error("uart not init"); } this.removeAllListeners('data'); } _onData() { if (this.uartInstance === null) { throw new Error("uart not init"); } this.uartInstance.on(function(data, len){ this.emit('data', data, len); }.bind(this)); }; close() { if (this.uartInstance === null) { throw new Error("uart not init"); } this.uartInstance.close(); }; on_mode() { if (this.uartInstance === null) { throw new Error("uart not init"); } this._onData(); }; } export function open(options) { return new HW_UART(options); }
YifuLiu/AliOS-Things
components/amp/jslib/src/uart.js
JavaScript
apache-2.0
2,119
'use strict'; import * as UDP from 'UDP' import * as event from 'events' class UDPClient extends event.EventEmitter { constructor() { super(); this.udpClientInstance = UDP.createSocket(); if(this.udpClientInstance < 0) { throw new Error("create socket error!"); } this.localPort = 0; } bind(port) { this.localPort = port || 0; if(UDP.bind(this.udpClientInstance, this.localPort) < 0) { throw new Error("bind error"); } this._onListening(); }; send(options) { if (!(options.message instanceof Array)) { throw new Error("udp send message is empty"); } options.message = new Uint8Array(options.message).buffer; UDP.sendto(this.udpClientInstance, options, function(ret) { console.log("sendto callback " + ret); if (ret < 0) { this.emit('error', 'udp send error'); if(options.fail) options.fail(); return; } this.emit('send', 'udp send success'); if(options.success) options.success(); }.bind(this)); }; close() { var ret = UDP.close(this.udpClientInstance); if (ret < 0) { console.log('close udp socket faild'); return; } this.emit('close', 'udp client close'); }; _onListening() { UDP.recvfrom(this.udpClientInstance, function(data, rinfo, err) { console.log("recvfrom callback " + err); if (err === -4) { this.emit('error', 'udp client receive data error'); return; } if (err > 0) { this.emit('message', data, rinfo); } }.bind(this)); }; } export function createSocket(options) { return new UDPClient(options); }
YifuLiu/AliOS-Things
components/amp/jslib/src/udp.js
JavaScript
apache-2.0
1,901
import * as WDG from 'WDG' export function start(timeout) { if (!timeout) { throw new Error('params is invalid'); } WDG.start(timeout); } export function feed() { WDG.feed(); } export function stop() { WDG.stop(); }
YifuLiu/AliOS-Things
components/amp/jslib/src/wdg.js
JavaScript
apache-2.0
246
// The driver for DS18B20 chip, it is a temperature sensor. // Require libjs/lib/onewire.js module. import * as onewire from 'onewire' var DS18B20Dev; var start_flag = 0; /* * prebuild: * ./qjsc -c -m ../jsmodules/ds18b20.js -N jslib_ds18b20 -M onewire -o bytecode/jslib_ds18b20.c * config DS18B20 * GPIO's options are configured in app.json. Specify the ID, e.g. GPIO below to init DS18B20. { "version": "1.0.0", "io": { "DS18B20": { "type": "GPIO", "port": 4, "dir": "output", "pull": "pullup" } }, "debugLevel": "DEBUG" } */ export function init(gpioid) { DS18B20Dev = onewire.open({id: gpioid}); } // Get temperature export function getTemperature() { var TL, TH; var tem; /* { DS18B20Dev.setspeed(1); start_flag = 1; } DS18B20Dev.reset(); DS18B20Dev.writeByte(0x55);*/ if(1) { if(!start_flag) { DS18B20Dev.setspeed(1); DS18B20Dev.reset(); DS18B20Dev.writeByte(0xcc); DS18B20Dev.writeByte(0x44); start_flag = 1; } DS18B20Dev.reset(); DS18B20Dev.writeByte(0xcc); DS18B20Dev.writeByte(0xbe); TL = DS18B20Dev.readByte(); /* LSB first */ TH = DS18B20Dev.readByte(); if (TH > 7) { TH =~ TH; TL =~ TL; tem = TH; tem <<= 8; tem += TL; tem = (tem * 0.0625 * 10 + 0.5); return -tem; } else { tem = TH; tem <<= 8; tem += TL; tem = (tem * 0.0625 * 10 + 0.5); return tem; } } } // De-init Si7006 export function deinit() { DS18B20Dev.close(); }
YifuLiu/AliOS-Things
components/amp/jsmodules/ds18b20.js
JavaScript
apache-2.0
1,868
const watch = require('node-watch'); const minify = require('@node-minify/core'); const babelMinify = require('@node-minify/babel-minify'); const fse = require('fs-extra'); let watchFile = false; process.argv.forEach((val, index) => { if(val === '--watch'){ watchFile = true; } }); fse.ensureDirSync('../build/bin/node_modules'); minify({ compressor: babelMinify, input: 'lib/*.js', output: '../build/bin/node_modules/$1.js', options: { babelrc: '.babelrc' }, callback: function(err, min) { console.log('minify updated'); } }); if(watchFile) { console.log('watching...'); watch('./lib', { recursive: true }, function(evt, name) { console.log('%s changed.', name); minify({ compressor: babelMinify, input: 'lib/*.js', output: '../build/bin/node_modules/$1.js', options: { babelrc: '.babelrc' }, callback: function(err, min) { console.log('minify updated'); } }); }); }
YifuLiu/AliOS-Things
components/amp/libjs/build.js
JavaScript
apache-2.0
1,077
const fs = require("fs"); const path = require("path"); // const watch = require("node-watch"); const minify = require("@node-minify/core"); const babelMinify = require("@node-minify/babel-minify"); const uglifyJS = require('@node-minify/uglify-js'); let watchFile = false; process.argv.forEach((val, index) => { if (val === "--watch") { watchFile = true; } }); let macro4libjs = { /* periperal */ adc: 'JSE_HW_ADDON_ADC', can: 'JSE_HW_ADDON_CAN', dac: 'JSE_HW_ADDON_DAC', gpio: 'JSE_HW_ADDON_GPIO', i2c: 'JSE_HW_ADDON_I2C', spi: 'JSE_HW_ADDON_SPI', timer: 'JSE_HW_ADDON_TIMER', pwm: 'JSE_HW_ADDON_PWM', rtc: 'JSE_HW_ADDON_RTC', uart: 'JSE_HW_ADDON_UART', wdg: 'JSE_HW_ADDON_WDG', rtc: 'JSE_HW_ADDON_RTC', /* network */ udp: 'JSE_NET_ADDON_UDP', tcp: 'JSE_NET_ADDON_TCP', mqtt: 'JSE_NET_ADDON_MQTT', http: 'JSE_NET_ADDON_HTTP', network: ['JSE_NET_ADDON_CELLULAR', 'JSE_NET_ADDON_WIFI'], /* system */ init: 'JSE_CORE_ADDON_INITJS', fs: 'JSE_CORE_ADDON_FS', kv: 'JSE_CORE_ADDON_KV', pm: 'JSE_CORE_ADDON_PM', battery: 'JSE_CORE_ADDON_BATTERY', charger: 'JSE_CORE_ADDON_CHARGER', /* adavanced */ iot: ['JSE_ADVANCED_ADDON_AIOT_DEVICE', 'JSE_ADVANCED_ADDON_AIOT_GATEWAY'], audioplayer: 'JSE_ADVANCED_ADDON_AUDIOPLAYER', tts: 'JSE_ADVANCED_ADDON_TTS', location: 'JSE_ADVANCED_ADDON_LOCATION', ui: 'JSE_ADVANCED_ADDON_UI', vm: 'JSE_ADVANCED_ADDON_UI', keypad: 'JSE_ADVANCED_ADDON_KEYPAD', und: 'JSE_ADVANCED_ADDON_UND', appota: 'JSE_ADVANCED_ADDON_OTA', at: 'JSE_CORE_ADDON_AT', paybox: 'JSE_ADVANCED_ADDON_PAYBOX', smartcard: 'JSE_ADVANCED_ADDON_SMARTCARD', blecfgnet: 'JSE_ADVANCED_ADDON_BLECFGNET', /* wireless */ bt_host: 'JSE_WIRELESS_ADDON_BT_HOST' /* others will not include in macro */ } let template = ` /* * Copyright (C) 2015-2020 Alibaba Group Holding Limited * This file autogenerated for jsapi */ #include <stdio.h> #include <string.h> #include "amp_config.h" #include "addons/libjs.h" #ifdef JSE_HIGHLEVEL_JSAPI `; // Async/Await async function doMinifyLibs(content) { const data = await minify({ compressor: babelMinify, content, options: { babelrc: ".babelrc", }, }); return data; } // 读取lib文件 async function doBuildLibs() { let files = fs.readdirSync("./lib"); template += `libjs_entry_t LIBJS_ENTRIES[] = {\n`; for (let i = 0; i < files.length; i++) { let file = files[i]; console.log(file); const filePath = `./lib/${file}`; const fileInfo = fs.statSync(filePath); if (fileInfo.isDirectory()) { return; } // 转译 + 压缩 const fileContent = fs.readFileSync(filePath); console.log(fileContent); try { // 转译 + 压缩后的数据,生成C代码 let minifyContent = await doMinifyLibs(fileContent); minifyContent = minifyContent.replace(/\\/g, "\\\\").replace(/"/g, "\\\""); console.log(minifyContent); let fileName = path.basename(filePath, ".js"); if(macro4libjs.hasOwnProperty(fileName)) { console.log(macro4libjs[fileName]); if(typeof macro4libjs[fileName] !== 'string') { template += '#if '; macro4libjs[fileName].forEach((macro, index) => { template += `defined(${macro})`; if(index < macro4libjs[fileName].length - 1){ template += ' || '; } }); template += `\n {"${fileName}", "${minifyContent}"},\n#endif\n\n`; } else { template += `#ifdef ${macro4libjs[fileName]}\n {"${fileName}", "${minifyContent}"},\n#endif\n\n`; } } else { template += ` {"${fileName}", "${minifyContent}"},\n\n`; } } catch (e) { console.log(e); process.exit(-1); } } const initContent = await doBuildInit(); console.log(initContent); template += `#ifdef ${macro4libjs['init']}\n {"init", "${initContent}"},\n#endif\n\n`; template += "};\n\n"; template += "int libjs_num = (sizeof(LIBJS_ENTRIES)/ sizeof(LIBJS_ENTRIES[0]));\n\n#endif /* JSE_HIGHLEVEL_JSAPI */\n" console.log(template); // 写入到文件 fs.writeFileSync('../engine/duktape_engine/addons/libjs.c', template); } async function doBuildInit() { try { // 转译 + 压缩后的生成init.js await minify({ compressor: uglifyJS, input: 'init/*.js', output: 'init.js', }); // 打包到c代码,转义部分字符(引号和反斜杠) let initContent = fs.readFileSync('./init.js').toString().replace(/"/g, "\\\""); return initContent; } catch (e) { console.log(e); process.exit(-1); } } doBuildLibs(); doBuildInit();
YifuLiu/AliOS-Things
components/amp/libjs/generator.js
JavaScript
apache-2.0
4,684
(function () { globalThis = new Function('return this;')(); globalThis.process = system; })();
YifuLiu/AliOS-Things
components/amp/libjs/init/process.js
JavaScript
apache-2.0
102
(function (global) { // // Check for native Promise and it has correct interface // var NativePromise = global['Promise']; var nativePromiseSupported = NativePromise && // Some of these methods are missing from // Firefox/Chrome experimental implementations 'resolve' in NativePromise && 'reject' in NativePromise && 'all' in NativePromise && 'race' in NativePromise && // Older version of the spec had a resolver object // as the arg rather than a function (function () { var resolve; new NativePromise(function (r) { resolve = r; }); return typeof resolve === 'function'; })(); // // export if necessary // if (typeof exports !== 'undefined' && exports) { // node.js exports.Promise = nativePromiseSupported ? NativePromise : Promise; exports.Polyfill = Promise; } else { // AMD if (typeof define == 'function' && define.amd) { define(function () { return nativePromiseSupported ? NativePromise : Promise; }); } else { // in browser add to global if (!nativePromiseSupported) global['Promise'] = Promise; } } // // Polyfill // var PENDING = 'pending'; var SEALED = 'sealed'; var FULFILLED = 'fulfilled'; var REJECTED = 'rejected'; var NOOP = function () { }; function isArray(value) { return Object.prototype.toString.call(value) === '[object Array]'; } // async calls var asyncSetTimer = typeof setImmediate !== 'undefined' ? setImmediate : setTimeout; var asyncQueue = []; var asyncTimer; function asyncFlush() { // run promise callbacks for (var i = 0; i < asyncQueue.length; i++) asyncQueue[i][0](asyncQueue[i][1]); // reset async asyncQueue asyncQueue = []; asyncTimer = false; // print("asyncFlush"); } function asyncCall(callback, arg) { asyncQueue.push([callback, arg]); if (!asyncTimer) { asyncTimer = true; asyncSetTimer(asyncFlush, 1); } } function invokeResolver(resolver, promise) { function resolvePromise(value) { resolve(promise, value); } function rejectPromise(reason) { reject(promise, reason); } try { resolver(resolvePromise, rejectPromise); } catch (e) { rejectPromise(e); } } function invokeCallback(subscriber) { var owner = subscriber.owner; var settled = owner.state_; var value = owner.data_; var callback = subscriber[settled]; var promise = subscriber.then; if (typeof callback === 'function') { settled = FULFILLED; try { value = callback(value); } catch (e) { reject(promise, e); } } if (!handleThenable(promise, value)) { if (settled === FULFILLED) resolve(promise, value); if (settled === REJECTED) reject(promise, value); } } function handleThenable(promise, value) { var resolved; try { if (promise === value) throw new TypeError('A promises callback cannot return that same promise.'); if (value && (typeof value === 'function' || typeof value === 'object')) { var then = value.then; // then should be retrived only once if (typeof then === 'function') { then.call(value, function (val) { if (!resolved) { resolved = true; if (value !== val) resolve(promise, val); else fulfill(promise, val); } }, function (reason) { if (!resolved) { resolved = true; reject(promise, reason); } }); return true; } } } catch (e) { if (!resolved) reject(promise, e); return true; } return false; } function resolve(promise, value) { if (promise === value || !handleThenable(promise, value)) fulfill(promise, value); } function fulfill(promise, value) { if (promise.state_ === PENDING) { promise.state_ = SEALED; promise.data_ = value; asyncCall(publishFulfillment, promise); } } function reject(promise, reason) { if (promise.state_ === PENDING) { promise.state_ = SEALED; promise.data_ = reason; asyncCall(publishRejection, promise); } } function publish(promise) { var callbacks = promise.then_; promise.then_ = undefined; for (var i = 0; i < callbacks.length; i++) { invokeCallback(callbacks[i]); } } function publishFulfillment(promise) { promise.state_ = FULFILLED; publish(promise); } function publishRejection(promise) { promise.state_ = REJECTED; publish(promise); } /** * @class */ function Promise(resolver) { if (typeof resolver !== 'function') throw new TypeError('Promise constructor takes a function argument'); if (this instanceof Promise === false) throw new TypeError('Failed to construct \'Promise\': Please use the \'new\' operator, this object constructor cannot be called as a function.'); this.then_ = []; invokeResolver(resolver, this); } Promise.prototype = { constructor: Promise, state_: PENDING, then_: null, data_: undefined, then: function (onFulfillment, onRejection) { var subscriber = { owner: this, then: new this.constructor(NOOP), fulfilled: onFulfillment, rejected: onRejection }; if (this.state_ === FULFILLED || this.state_ === REJECTED) { // already resolved, call callback async asyncCall(invokeCallback, subscriber); } else { // subscribe this.then_.push(subscriber); } return subscriber.then; }, 'catch': function (onRejection) { return this.then(null, onRejection); } }; Promise.all = function (promises) { var Class = this; if (!isArray(promises)) throw new TypeError('You must pass an array to Promise.all().'); return new Class(function (resolve, reject) { var results = []; var remaining = 0; function resolver(index) { remaining++; return function (value) { results[index] = value; if (!--remaining) resolve(results); }; } for (var i = 0, promise; i < promises.length; i++) { promise = promises[i]; if (promise && typeof promise.then === 'function') promise.then(resolver(i), reject); else results[i] = promise; } if (!remaining) resolve(results); }); }; Promise.race = function (promises) { var Class = this; if (!isArray(promises)) throw new TypeError('You must pass an array to Promise.race().'); return new Class(function (resolve, reject) { for (var i = 0, promise; i < promises.length; i++) { promise = promises[i]; if (promise && typeof promise.then === 'function') promise.then(resolve, reject); else resolve(promise); } }); }; Promise.resolve = function (value) { var Class = this; if (value && typeof value === 'object' && value.constructor === Class) return value; return new Class(function (resolve) { resolve(value); }); }; Promise.reject = function (reason) { var Class = this; return new Class(function (resolve, reject) { reject(reason); }); }; })(typeof window != 'undefined' ? window : typeof global != 'undefined' ? global : typeof self != 'undefined' ? self : this);
YifuLiu/AliOS-Things
components/amp/libjs/init/promise.js
JavaScript
apache-2.0
8,966
'use strict'; class HW_ADC { constructor(options) { if (!options || !options.id) { throw new Error('options is invalid'); } this.options = { id: options.id }; this.success = options.success || function(){}; this.fail = options.fail || function(){}; this._open(); } _open() { this.adcInstance = __native.ADC.open(this.options.id); if (!this.adcInstance) { this.fail(); return; } this.success(); } readValue() { if (!this.adcInstance) { throw new Error('adc not init'); } return __native.ADC.read(this.adcInstance); }; close() { if (!this.adcInstance) { throw new Error('adc not init'); } __native.ADC.close(this.adcInstance); }; } function open(options) { return new HW_ADC(options); } module.exports = { open, }
YifuLiu/AliOS-Things
components/amp/libjs/lib/adc.js
JavaScript
apache-2.0
969
'use strict'; const EventEmitter = require('events'); class UTILS_APPOTA extends EventEmitter { constructor(options){ super(); if (!options) { throw new Error('options invalid'); } this._init(options); } _init(options) { __native.APPOTA.otaInit(options, function(res) { this.emit('new', res); }.bind(this)); } download(options, cb) { __native.APPOTA.otaDownload(options, cb); } verify(options, cb) { __native.APPOTA.otaVerify(options, cb); } report(options) { var res = __native.APPOTA.otaReport(options); if (res < 0) { this.emit('error'); } } upgrade(options, cb) { __native.APPOTA.otaUpgrade(options, cb); } } function open(options) { return new UTILS_APPOTA(options); } module.exports = { open }
YifuLiu/AliOS-Things
components/amp/libjs/lib/appota.js
JavaScript
apache-2.0
898
'use strict'; module.exports = __native.AT;
YifuLiu/AliOS-Things
components/amp/libjs/lib/at.js
JavaScript
apache-2.0
44
'use strict'; const EventEmitter = require('events'); module.exports = new class AudioPlayer extends EventEmitter { constructor(){ super(); this._onState(); } play(source, callback) { if (!source || !callback) { throw new Error('invalid params'); } return __native.audioplayer.play(source, callback); }; pause() { return __native.audioplayer.pause(); }; resume() { return __native.audioplayer.resume(); }; stop() { return __native.audioplayer.stop(); }; seekto(seconds) { if (seconds < 0) { throw new Error('invalid params'); } return __native.audioplayer.seekto(seconds); }; getPosition() { return __native.audioplayer.getPosition(); }; getDuration() { return __native.audioplayer.getDuration(); }; getState() { return __native.audioplayer.getState(); }; _onState() { __native.audioplayer.onState(function(state) { this.emit('stateChange', state); }.bind(this)); }; listPlay(sourcelist, callback) { if (!sourcelist || !callback) { throw new Error('invalid params'); } return __native.audioplayer.listPlay(sourcelist, callback); }; listPlayStop() { return __native.audioplayer.listPlayStop(); }; setVolume(volume) { if (volume < 0) { throw new Error('invalid params'); } return __native.audioplayer.setVolume(volume); }; getVolume() { return __native.audioplayer.getVolume(); }; }
YifuLiu/AliOS-Things
components/amp/libjs/lib/audioplayer.js
JavaScript
apache-2.0
1,659
'use strict'; const EventEmitter = require('events'); module.exports = new class UTILS_Battery extends EventEmitter { constructor(){ super(); } getConnectState() { return __native.Battery.getConnectState(); } getVoltage() { return __native.Battery.getVoltage(); } getLevel() { return __native.Battery.getLevel(); } getTemperature() { return __native.Battery.getTemperature(); } }
YifuLiu/AliOS-Things
components/amp/libjs/lib/battery.js
JavaScript
apache-2.0
465
'use strict'; function start() { __native.BLECFGNET.start(); } function recoveryWifi() { __native.BLECFGNET.recoveryWifi(); } function recoveryDevInfo() { __native.BLECFGNET.recoveryDevInfo(); } module.exports = { start, recoveryWifi, recoveryDevInfo }
YifuLiu/AliOS-Things
components/amp/libjs/lib/blecfgnet.js
JavaScript
apache-2.0
280
'use strict'; const EventEmitter = require('events'); class bt_host extends EventEmitter{ constructor(options) { super(); if (!options) { throw new Error('options is invalid'); } if (this.inited == true) { throw new Error('bt_host already inited'); } this.options = { deviceName: options.deviceName, conn_num_max: options.conn_num_max, }; this.success = options.success|| function(){}; this.failed = options.failed|| function(){}; this._init(); } _init() { console.log('bt_host native init') let result = __native.BT_HOST.init(this.options); if (result == 0) { this.inited = true; console.log('bt host inited'); this.success(); } else { console.log('bt host init failed'); this.failed(); } } start_adv(params) { console.log('bt host start adv') if (this.inited == false) { throw new Error('bt host not initialed'); } if (this.adv_flag == true) { stop_adv() } let result = __native.BT_HOST.start_adv(params, function(conn_handle, connect){ console.log('connect callback'+conn_handle+connect); if (connect) { this.emit('connect', conn_handle); } else { this.emit('disconnect', conn_handle); } }.bind(this)); if (result == 0) { this.adv_flag = true; if (params.success) { params.success(); } } else { if (params.failed) { params.failed(); } } } stop_adv(params) { if (this.inited == false) { throw new Error('bt host not initialed'); } if (this.adv_flag == false) { return; } let result = __native.BT_HOST.stop_adv(); if (result == 0) { if (params.success) { params.success(); } this.adv_flag = false; } else { if (params.failed) { params.failed(); } } } start_scan(params) { console.log('bt host start scan') if (this.inited == false) { throw new Error('bt host not initialed'); } if (this.scan_flag == true) { stop_scan() } let result = __native.BT_HOST.start_scan(params, function(addr, addr_type, adv_type, adv_data, rssi){ console.log('scan result callback'+' addr:'+addr+' data:'+adv_data); }.bind(this)); if (result == 0) { this.scan_flag = true; if (params.success) { params.success(); } } else { if (params.failed) { params.failed(); } } } stop_scan(params) { if (this.inited == false) { throw new Error('bt host not initialed'); } if (this.scan_flag == false) { return; } let result = __native.BT_HOST.stop_scan(); if (result == 0) { this.scan_flag = false; if (params.success) { params.success(); } } else { if (params.failed) { params.failed(); } } } add_service(params) { if (this.inited == false) { throw new Error('bt host not initialed'); } console.log('srvc_cfg: ' + params.service); let result = __native.BT_HOST.add_service(params.service, function(data){ console.log('len: ' + data.len + ', data: ' + data); this.emit('onCharWrite', data); }.bind(this)); console.log('add_service result: ' + result); if (result == 0) { if (params.success) { params.success(); } } else { if (params.failed) { params.failed(); } } } update_char(params) { if (this.inited == false) { throw new Error('bt host not initialed'); } let result = __native.BT_HOST.update_chars(params.arg); if (result == 0) { if (params.success) { params.success(); } } else { if (params.failed) { params.failed(); } } } } function open(options) { return new bt_host(options); } module.exports = { open, }
YifuLiu/AliOS-Things
components/amp/libjs/lib/bt_host.js
JavaScript
apache-2.0
3,652
'use strict'; const EventEmitter = require('events'); class HW_CAN extends EventEmitter{ constructor(options) { super(); if (!options || !options.id) { throw new Error('options is invalid'); } this.options = { id: options.id }; this.success = options.success || function(){}; this.fail = options.fail || function(){}; this._open(); this._onData(); } _open() { this.canInstance = __native.CAN.open(this.options.id); if (!this.canInstance) { this.fail(); return; } this.success(); } receive() { if (!this.canInstance) { throw new Error('can not init'); } return __native.CAN.receive(this.canInstance); }; _onData() { if (!this.canInstance) { throw new Error("can not init"); } __native.CAN.receive(this.canInstance, function(type, id, data){ this.emit('data', type, id, data); }.bind(this)); }; send(txheader, data) { if (!this.canInstance || !data) { throw new Error('can not init or params is invalid'); } __native.CAN.send(this.canInstance, txheader, data); }; close() { if (!this.canInstance) { throw new Error('can not init'); } __native.CAN.close(this.canInstance); }; } function open(options) { return new HW_CAN(options); } module.exports = { open, }
YifuLiu/AliOS-Things
components/amp/libjs/lib/can.js
JavaScript
apache-2.0
1,539
'use strict'; const EventEmitter = require('events'); module.exports = new class UTILS_Charger extends EventEmitter { constructor(){ super(); this._onConnect(); } _onConnect() { __native.Charger.onConnect(function(state) { this.emit('connect', state); }.bind(this)); }; getState() { return __native.Charger.getState(); } getConnectState() { return __native.Charger.getConnectState(); } getCurrent() { return __native.Charger.getCurrent(); } switch(onoff) { return __native.Charger.switch(onoff); } }
YifuLiu/AliOS-Things
components/amp/libjs/lib/charger.js
JavaScript
apache-2.0
630
'use strict'; class HW_DAC { constructor(options) { if (!options || !options.id) { throw new Error('options is invalid'); } this.options = { id: options.id }; this.success = options.success || function(){}; this.fail = options.fail || function(){}; this._open(); } _open() { this.dacInstance = __native.DAC.open(this.options.id); if (!this.dacInstance) { this.fail(); return; } this.success(); } readValue() { if (!this.dacInstance) { throw new Error('dac not init'); } return __native.DAC.getVol(this.dacInstance); }; writeValue(value) { if (!this.dacInstance || !value) { throw new Error('dac not init or params is invalid'); } __native.DAC.setVol(this.dacInstance, value); }; close() { if (!this.dacInstance) { throw new Error('dac not init'); } __native.DAC.close(this.dacInstance); }; } function open(options) { return new HW_DAC(options); } module.exports = { open, }
YifuLiu/AliOS-Things
components/amp/libjs/lib/dac.js
JavaScript
apache-2.0
1,173
'use strict'; var kv = require('kv'); function setDeviceInfo(pk, ps) { if (!pk || !ps) { throw new Error('params is invalid'); } var productkey_key = '_amp_internal_productkey'; var productsecret_key = '_amp_internal_productsecret'; kv.setStorageSync(productkey_key, pk); kv.setStorageSync(productsecret_key, ps); } function setToken(token) { if(!token) { throw new Error("invalid params"); } var token_key = '_amp_device_token'; kv.setStorageSync(token_key, token); } function getToken() { return kv.getStorageSync('_amp_device_token'); } module.exports = { setDeviceInfo, setToken, getToken }
YifuLiu/AliOS-Things
components/amp/libjs/lib/device.js
JavaScript
apache-2.0
677
'use strict'; var spliceOne; function EventEmitter() { EventEmitter.init.call(this); } EventEmitter.EventEmitter = EventEmitter; EventEmitter.usingDomains = false; EventEmitter.prototype._events = undefined; EventEmitter.prototype._eventsCount = 0; EventEmitter.prototype._maxListeners = undefined; var defaultMaxListeners = 10; Object.defineProperty(EventEmitter, 'defaultMaxListeners', { enumerable: true, get: function () { return defaultMaxListeners; }, set: function (arg) { if (typeof arg !== 'number' || arg < 0 || Number.isNaN(arg)) { throw new Error('defaultMaxListeners:a non-negative number'); } defaultMaxListeners = arg; } }); EventEmitter.init = function () { if (this._events === undefined || this._events === Object.getPrototypeOf(this)._events) { this._events = Object.create(null); this._eventsCount = 0; } this._maxListeners = this._maxListeners || undefined; }; EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { if (typeof n !== 'number' || n < 0 || Number.isNaN(n)) { throw new Error('a non-negative number'); } this._maxListeners = n; var that = this; return that; }; function _getMaxListeners(that) { if (that._maxListeners === undefined) return EventEmitter.defaultMaxListeners; return that._maxListeners; } EventEmitter.prototype.getMaxListeners = function getMaxListeners() { return _getMaxListeners(this); }; function longestSeqContainedIn(a, b) { for (var len = a.length; len >= 3; --len) { for (var i = 0; i < a.length - len; ++i) { for (var j = 0; j < b.length - len; ++j) { var matches = true; for (var k = 0; k < len; ++k) { if (a[i + k] !== b[j + k]) { matches = false; break; } } if (matches) return [len, i, j]; } } } return [0, 0, 0]; } function enhanceStackTrace(err, own) { var sep = '\nEmitted \'error\' event at:\n'; var errStack = err.stack.split('\n').slice(1); var ownStack = own.stack.split('\n').slice(1); var seq = longestSeqContainedIn(ownStack, errStack); if (seq.len > 0) { ownStack.splice(seq.off + 1, seq.len - 1, ' [... lines matching original stack trace ...]'); } err.stack = err.stack + sep + ownStack.join('\n'); } EventEmitter.prototype.emit = function emit(type) { var doError = (type === 'error'); var events = this._events; if (events !== undefined) doError = (doError && events.error === undefined); else if (!doError) return false; var args = []; for (var i = 1, len = arguments.length; i < len; i++) { args.push(arguments[i]); } if (doError) { var er; if (args.length > 0) er = args[0]; if (er instanceof Error) { throw er; } throw new Error('unhandled error'); } var handler = events[type]; if (handler === undefined) return false; if (typeof handler === 'function') { Function.prototype.apply.call(handler, this, args); } else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) Function.prototype.apply.call(listeners[i], this, args); } return true; }; function _addListener(target, type, listener, prepend) { var m; var events; var existing; if (typeof listener !== 'function') { throw new Error('addListener invalid arg type: Function'); } events = target._events; if (events === undefined) { events = target._events = Object.create(null); target._eventsCount = 0; } else { if (events.newListener !== undefined) { target.emit('newListener', type, listener.listener ? listener.listener : listener); events = target._events; } existing = events[type]; } if (existing === undefined) { existing = events[type] = listener; ++target._eventsCount; } else { if (typeof existing === 'function') { existing = events[type] = prepend ? [listener, existing] : [existing, listener]; } else if (prepend) { existing.unshift(listener); } else { existing.push(listener); } } return target; } EventEmitter.prototype.addListener = function addListener(type, listener) { return _addListener(this, type, listener, false); }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.prependListener = function prependListener(type, listener) { return _addListener(this, type, listener, true); }; function onceWrapper() { if (!this.fired) { this.target.removeListener(this.type, this.wrapFn); this.fired = true; Function.prototype.apply.call(this.listener, this.target, arguments); } } function _onceWrap(target, type, listener) { var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener }; var wrapped = onceWrapper.bind(state); wrapped.listener = listener; state.wrapFn = wrapped; return wrapped; } EventEmitter.prototype.once = function once(type, listener) { if (typeof listener !== 'function') { throw new Error('listener invalid arg type'); } this.on(type, _onceWrap(this, type, listener)); var that = this; return that; }; EventEmitter.prototype.prependOnceListener = function prependOnceListener(type, listener) { if (typeof listener !== 'function') { throw new Error('prependOnceListener invalid arg type'); } this.prependListener(type, _onceWrap(this, type, listener)); var that = this; return that; }; EventEmitter.prototype.removeListener = function removeListener(type, listener) { var list, events, position, i, originalListener; var that = this; if (typeof listener !== 'function') { throw new Error('removeListener invalid arg type'); } events = this._events; if (events === undefined) return that; list = events[type]; if (list === undefined) return that; if (list === listener || list.listener === listener) { if (--this._eventsCount === 0) this._events = Object.create(null); else { delete events[type]; if (events.removeListener) this.emit('removeListener', type, list.listener || listener); } } else if (typeof list !== 'function') { position = -1; for (i = list.length - 1; i >= 0; i--) { if (list[i] === listener || list[i].listener === listener) { originalListener = list[i].listener; position = i; break; } } if (position < 0) return that; if (position === 0) list.shift(); else { if (spliceOne === undefined) spliceOne = require('internal/util').spliceOne; spliceOne(list, position); } if (list.length === 1) events[type] = list[0]; if (events.removeListener !== undefined) this.emit('removeListener', type, originalListener || listener); } return that; }; EventEmitter.prototype.off = EventEmitter.prototype.removeListener; EventEmitter.prototype.removeAllListeners = function removeAllListeners(type) { var listeners, events, i; var that = this; events = this._events; if (events === undefined) return that; if (events.removeListener === undefined) { if (arguments.length === 0) { this._events = Object.create(null); this._eventsCount = 0; } else if (events[type] !== undefined) { if (--this._eventsCount === 0) this._events = Object.create(null); else delete events[type]; } return that; } if (arguments.length === 0) { var keys = Object.keys(events); var key; for (i = 0; i < keys.length; ++i) { key = keys[i]; if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = Object.create(null); this._eventsCount = 0; return that; } listeners = events[type]; if (typeof listeners === 'function') { this.removeListener(type, listeners); } else if (listeners !== undefined) { for (i = listeners.length - 1; i >= 0; i--) { this.removeListener(type, listeners[i]); } } return that; }; function _listeners(target, type, unwrap) { var events = target._events; if (events === undefined) return []; var evlistener = events[type]; if (evlistener === undefined) return []; if (typeof evlistener === 'function') return unwrap ? [evlistener.listener || evlistener] : [evlistener]; return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); } EventEmitter.prototype.listeners = function listeners(type) { return _listeners(this, type, true); }; EventEmitter.prototype.rawListeners = function rawListeners(type) { return _listeners(this, type, false); }; EventEmitter.listenerCount = function (emitter, type) { if (typeof emitter.listenerCount === 'function') { return emitter.listenerCount(type); } else { return listenerCount.call(emitter, type); } }; EventEmitter.prototype.listenerCount = listenerCount; function listenerCount(type) { var events = this._events; if (events !== undefined) { var evlistener = events[type]; if (typeof evlistener === 'function') { return 1; } else if (evlistener !== undefined) { return evlistener.length; } } return 0; } EventEmitter.prototype.eventNames = function eventNames() { return this._eventsCount > 0 ? Function.prototype.apply.call(this._events) : []; }; function arrayClone(arr, n) { var copy = new Array(n); for (var i = 0; i < n; ++i) copy[i] = arr[i]; return copy; } function unwrapListeners(arr) { var ret = new Array(arr.length); for (var i = 0; i < ret.length; ++i) { ret[i] = arr[i].listener || arr[i]; } return ret; } module.exports = EventEmitter;
YifuLiu/AliOS-Things
components/amp/libjs/lib/events.js
JavaScript
apache-2.0
11,144
'use strict'; function writeSync(path, data, options) { if (!path || !data) { throw new Error('params is invalid'); } options = options || {flag: 'w'}; __native.FS.write(path, data, options); } function readSync(path) { if(!path) { throw new Error("invalid params"); } var content = __native.FS.read(path); if (!content) { throw 'file open error'; } return content; } function unlinkSync(path) { if(!path) { throw new Error("invalid params"); } __native.FS.delete(path); } function totalSize() { return __native.FS.totalsize(); } function usedSize() { return __native.FS.usedsize(); } function freeSize() { return __native.FS.freesize(); } module.exports = { writeSync, readSync, unlinkSync, totalSize, usedSize, freeSize }
YifuLiu/AliOS-Things
components/amp/libjs/lib/fs.js
JavaScript
apache-2.0
855
'use strict'; class HW_GPIO { constructor(options) { if (!options || !options.id) { throw new Error("options is invalid"); } this.options = { id: options.id }; this.success = options.success || function(){}; this.fail = options.fail || function(){}; this._open(); } _open() { this.gpioInstance = __native.GPIO.open(this.options.id); if (!this.gpioInstance) { this.fail(); return; } this.success(); } writeValue(level) { if (!this.gpioInstance) { throw new Error("gpio not init"); } __native.GPIO.write(this.gpioInstance, level); } toggle() { if (!this.gpioInstance) { throw new Error("gpio not init"); } __native.GPIO.toggle(this.gpioInstance); } onIRQ(options) { if (!this.gpioInstance || !options || !options.cb) { throw new Error("gpio not init or params is invalid"); } __native.GPIO.on(this.gpioInstance, options.cb); } readValue() { if (!this.gpioInstance) { throw new Error("gpio not init"); } return __native.GPIO.read(this.gpioInstance); }; close() { if (!this.gpioInstance) { throw new Error("gpio not init"); } __native.GPIO.close(this.gpioInstance); }; } function open(options) { return new HW_GPIO(options); } module.exports = { open, }
YifuLiu/AliOS-Things
components/amp/libjs/lib/gpio.js
JavaScript
apache-2.0
1,555
'use strict'; module.exports = __native.HTTP;
YifuLiu/AliOS-Things
components/amp/libjs/lib/http.js
JavaScript
apache-2.0
46
'use strict'; class HW_I2C { constructor(options) { if (!options || !options.id) { throw new Error("options is invalid"); } this.options = { id: options.id }; this.success = options.success || function(){}; this.fail = options.fail || function(){}; this._open(); } _open() { this.i2cInstance = __native.I2C.open(this.options.id); if (!this.i2cInstance) { this.fail(); return; } this.success(); } write(data) { if (!this.i2cInstance || !data) { throw new Error("i2c not init or params is invalid"); } __native.I2C.write(this.i2cInstance, data); } read(bytes) { if (!this.i2cInstance || !bytes) { throw new Error("i2c not init or params is invalid"); } return __native.I2C.read(this.i2cInstance, bytes); }; writeMem(memaddr, data) { if (!this.i2cInstance) { throw new Error("i2c not init or params is invalid"); } __native.I2C.writeReg(this.i2cInstance, memaddr, data); } readMem(memaddr, bytes) { if (!this.i2cInstance) { throw new Error("i2c not init or params is invalid"); } return __native.I2C.readReg(this.i2cInstance, memaddr, bytes); }; close() { if (!this.i2cInstance) { throw new Error("i2c not init"); } __native.I2C.close(this.i2cInstance); }; } function open(options) { return new HW_I2C(options); } module.exports = { open, }
YifuLiu/AliOS-Things
components/amp/libjs/lib/i2c.js
JavaScript
apache-2.0
1,644
'use strict'; const EventEmitter = require('events'); class IotDeviceClient extends EventEmitter { constructor(options){ super(); if(!options || !options.productKey || !options.deviceName || !options.deviceSecret){ throw new Error('device info error'); } this.options = { productKey: options.productKey, deviceName: options.deviceName, deviceSecret: options.deviceSecret, region: options.region || 'cn-shanghai', keepaliveSec: options.keepaliveSec || 60 } this._connect(); } _connect() { __native.AIOT_DEVICE.device(this.options, function(res) { if (!res.handle) { return; } this.IoTDeviceInstance = res.handle; switch (res.code) { case 0: this.emit('connect'); break; case 1: this.emit('reconnect'); break; case 2: this.emit('disconnect'); break; case 3: this.emit('message', res); break; default : break ; } }.bind(this)); } getDeviceHandle() { return this.IoTDeviceInstance; } subscribe(options, cb) { var ret = __native.AIOT_DEVICE.subscribe(this.IoTDeviceInstance, options, cb || function() {}); if (ret < 0) { throw new Error('subscribe topic error', options.topic); } return ret; } unsubscribe(topic, cb) { var ret = __native.AIOT_DEVICE.unsubscribe(this.IoTDeviceInstance, topic, cb || function() {}); if (ret < 0) { throw new Error('unsubscribe topic error', topic); } return ret; } publish(options, cb) { var ret = __native.AIOT_DEVICE.publish(this.IoTDeviceInstance, options, cb || function() {}); if (ret < 0) { throw new Error('publish topic info error', options.topic); } return ret; } postProps(params, cb) { var ret = __native.AIOT_DEVICE.postProps(this.IoTDeviceInstance, params, cb || function() {}); if (ret < 0) { throw new Error('post props error'); } return ret; } onProps(cb) { var ret = __native.AIOT_DEVICE.onProps(this.IoTDeviceInstance, cb); if (ret < 0) { throw new Error('on props error'); } return ret; } postEvent(options, cb) { var ret = __native.AIOT_DEVICE.postEvent(this.IoTDeviceInstance, options, cb || function() {}); if (ret < 0) { throw new Error('post event error'); } return ret; } onService(cb) { var ret = __native.AIOT_DEVICE.onService(this.IoTDeviceInstance, cb); if (ret < 0) { throw new Error('on service error'); } return ret; } end(cb) { var ret = __native.AIOT_DEVICE.close(this.IoTDeviceInstance, cb || function() {}); if (ret < 0) { throw new Error('end iot client error'); } return ret; } } class IotGatewayClient extends EventEmitter{ constructor(options){ super(); if(!options || !options.productKey || !options.deviceName || !options.deviceSecret){ throw new Error('device info error'); } this.options = { productKey: options.productKey, deviceName: options.deviceName, deviceSecret: options.deviceSecret, keepaliveSec: options.keepaliveSec || 60, region: options.region || 'cn-shanghai' } this._on(); this._connect(); } _connect() { __native.AIOT_GATEWAY.gateway(this.options, function(res) { if (!res.handle || res.code != 0) { return; } this.IoTGatewayInstance = res.handle; this.emit('connect'); }.bind(this)); } _on() { __native.AIOT_GATEWAY.onMqttMessage(function(res) { switch (res.code) { case 1: this.emit('reconnect'); break; case 2: this.emit('disconnect'); break; case 3: this.emit('message', res); break; default : break ; } }.bind(this)); } addTopo(options, cb) { var ret = __native.AIOT_GATEWAY.addTopo(this.IoTGatewayInstance, options, cb || function(ret, message) {}); if (ret < 0) { throw new Error('add topo error'); } return ret; } getTopo(cb) { var ret = __native.AIOT_GATEWAY.getTopo(this.IoTGatewayInstance, cb || function(ret, message) {}); if (ret < 0) { throw new Error('get topo error'); } return ret; } removeTopo(options, cb) { var ret = __native.AIOT_GATEWAY.removeTopo(this.IoTGatewayInstance, options, cb || function() {}); if (ret < 0) { throw new Error('remove topo error'); } return ret; } login(options, cb) { var ret = __native.AIOT_GATEWAY.login(this.IoTGatewayInstance, options, cb || function() {}); if (ret < 0) { throw new Error('aiot subdev login error'); } return ret; } logout(options, cb) { var ret = __native.AIOT_GATEWAY.logout(this.IoTGatewayInstance, options, cb || function() {}); if (ret < 0) { throw new Error('aiot subdev logout error'); } return ret; } registerSubDevice(options, cb) { var ret = __native.AIOT_GATEWAY.registerSubDevice(this.IoTGatewayInstance, options, cb || function(ret, message) {}); if (ret < 0) { throw new Error('aiot register subdev error'); } return ret; } subscribe(params, cb) { var ret = __native.AIOT_GATEWAY.subscribe(this.IoTGatewayInstance, params, cb || function() {}); if (ret < 0) { throw new Error('subscribe topic error', options.topic); } return ret; } unsubscribe(topic, cb) { var ret = __native.AIOT_GATEWAY.unsubscribe(this.IoTGatewayInstance, topic, cb || function() {}); if (ret < 0) { throw new Error('unsubscribe topic error', topic); } return ret; } publish(options, cb) { var ret = __native.AIOT_GATEWAY.publish(this.IoTGatewayInstance, options, cb || function() {}); if (ret < 0) { throw new Error('publish topic info error', options.topic); } return ret; } } function dynreg(options, cb) { var ret = __native.AIOT_DEVICE.register(options, cb); if (ret < 0) { throw new Error('dynmic register error'); } return ret; } function device(options) { return new IotDeviceClient(options); } function gateway(options){ return new IotGatewayClient(options); } module.exports = { device, gateway, dynreg }
YifuLiu/AliOS-Things
components/amp/libjs/lib/iot.js
JavaScript
apache-2.0
7,145
'use strict'; const EventEmitter = require('events'); module.exports = new class Keypad extends EventEmitter { constructor(){ super(); this._on(); } open() { return __native.Keypad.open(); }; close() { this.removeAllListeners('keypadEvent'); return __native.Keypad.close(); }; _on() { __native.Keypad.on(function(code, value) { this.emit('keypadEvent', code, value); }.bind(this)); }; }
YifuLiu/AliOS-Things
components/amp/libjs/lib/keypad.js
JavaScript
apache-2.0
492
'use strict'; module.exports = __native.KV;
YifuLiu/AliOS-Things
components/amp/libjs/lib/kv.js
JavaScript
apache-2.0
44
'use strict'; class ADVANCED_LOCATION { constructor() {} getAccessApInfo() { var ap_info; ap_info = __native.LOCATION.accessedWifi(); return ap_info; } getScannedApInfo() { var ap_info; ap_info = __native.LOCATION.scannedWifi(); return ap_info; } getAccessedLbsInfo() { var lbs_info; lbs_info = __native.LOCATION.accessedLbs(); return lbs_info; } getNearLbsInfo() { var near_lbs_info; near_lbs_info = __native.LOCATION.nearbts(); return near_lbs_info; } } function open() { return new ADVANCED_LOCATION(); } module.exports = { open, }
YifuLiu/AliOS-Things
components/amp/libjs/lib/location.js
JavaScript
apache-2.0
683
'use strict'; const EventEmitter = require('events'); class MQTTClient extends EventEmitter{ constructor(options) { super(); if (!options || !options.host) { throw new Error('options is invalid'); } this.options = { host: options.host, port: options.port || 1883, client_id: options.clientId || this._getRandomClientId(), username: options.username || '', password: options.password || '', keepalive_interval: options.keepalive_interval || 60 }; this._fail = options.fail || function(){}; this._success = options.success || function(){}; this.connected = false; this._connect(); } _getRandomClientId() { return 'amp-' + parseInt(Math.random() * 1000000); } _connect() { var cb = function(err){ if(err === -2) { // connect failed this._fail(); this.emit('error', 'connect failed'); } if(err === -1) { // status: disconnect this.connected = false; this.emit('disconnect'); } if(err === 0) { // status: connect this.connected = true; this._success(); this.emit('connect'); } }; this.mqttInstance = __native.MQTT.start(this.options, cb.bind(this)); if (!this.mqttInstance){ // connect failed this._fail(); this.emit('error', 'connect failed'); return } } subscribe(options) { if (!this.mqttInstance || !options || !options.topic) { throw new Error('mqtt not init or options invalid'); } if(this.connected === false) { this.emit('error', 'subscirbe fail: not connected'); return; } var ret = __native.MQTT.subscribe(this.mqttInstance, options.topic, options.qos || 0, function(topic, payload){ this.emit('message', topic, payload); }.bind(this)); if (ret < 0) { if(typeof options.fail === 'function') { options.fail(); } this.emit('error', 'subscribe error'); } else { if(typeof options.success === 'function') { options.success(); } } } unsubscribe(options) { if (!this.mqttInstance || !options || !options.topic) { throw new Error('mqtt not init or mqtt topic is invalid'); } if(this.connected === false) { this.emit('error', 'unsubscribe fail: not connected'); return; } var ret = __native.MQTT.unsubscribe(this.mqttInstance, options.topic, function() { }.bind(this)); if (ret < 0) { if(typeof options.fail === 'function') { options.fail(); } this.emit('error', 'unsubscribe error'); return } if(typeof options.success === 'function') { options.success(); } } publish(options) { if (!this.mqttInstance || !options || !options.topic || !options.message) { throw new Error('mqtt not init or options invalid'); } if(this.connected === false) { this.emit('error', 'publish fail: not connected'); return; } __native.MQTT.publish(this.mqttInstance, options.topic, options.message, options.qos || 0, function(ret) { if (ret < 0) { if(typeof options.fail === 'function') { options.fail(); } this.emit('error', options.topic); return; } if(typeof options.success === 'function') { options.success(); } }.bind(this)); } close() { if (!this.mqttInstance) { throw new Error('mqtt not init'); } __native.MQTT.close(this.mqttInstance, function(ret){ if (ret != 0) { this.emit('error', 'mqtt client close error'); return; } this.emit('close'); }.bind(this)); } } function createClient(options) { return new MQTTClient(options); } module.exports = { createClient, }
YifuLiu/AliOS-Things
components/amp/libjs/lib/mqtt.js
JavaScript
apache-2.0
4,445
'use strict'; const EventEmitter = require('events'); class netMgr extends EventEmitter{ constructor(options) { super(); if(!options || !options.name){ throw new Error('device info error'); } this.options = { name: options.name }; this.name = options.name this._init(); this.dev_handler = this._getDev(); } _init() { if(__native.NETMGR.serviceInit() !== 0){ this.emit('error', 'netmgr init error'); } } _getDev() { console.log('netMgr._getDev: ' + this.name) var dev_handler = __native.NETMGR.getDev(this.name); if (!dev_handler){ this.emit('error', 'netmgr get dev error ' + this.name); return; } return dev_handler; } setMsgCb(cb) { __native.NETMGR.setMsgCb(this.dev_handler, cb); } delMsgCb(cb) { __native.NETMGR.delMsgCb(this.dev_handler, cb); } setAutoReconnect(flag) { var ret = __native.NETMGR.setAutoReconnect(this.dev_handler, flag); if (ret !== 0) { this.emit('error', 'netmgr set auto reconnect error'); } } connect(options) { options = { ssid: options.ssid, password: options.password, bssid: options.bssid || '', timeout_ms: options.timeout_ms || 18000 } __native.NETMGR.connect(this.dev_handler, options, function(status) { if (status == 'DISCONNECT'){ this.emit('disconnect', options.ssid); return; } this.emit('connect', options.ssid); }.bind(this)); } disconnect() { var ret = __native.NETMGR.disconnect(this.dev_handler); if (ret !== 0) { this.emit('error', 'netmgr disconnect error'); return; } this.emit('disconnect', ssid); } getState() { var ret = __native.NETMGR.getState(this.dev_handler); switch (ret) { case 0: return 'disconnecting'; case 1: return 'disconnected'; case 2: return 'connecting'; case 3: return 'connected'; case 4: return 'obtaining ip'; case 5: return 'network connected'; case 6: return 'failed'; } } saveConfig() { var ret = __native.NETMGR.saveConfig(this.dev_handler); if (ret !== 0) { this.emit('error', 'netmgr save config error'); } } setIfConfig(options) { options = { dhcp_en: options.dhcp_en || true, ip_addr: options.ip_addr || '', mask: options.mask || '', gw: options.gw || '', dns_server: options.dns_server || '', mac: options.mac || '' } var ret = __native.NETMGR.setIfConfig(this.dev_handler, options); if (ret !== 0) { this.emit('error', 'netmgr save config error'); } } getIfConfig() { var config = __native.NETMGR.getIfConfig(this.dev_handler); if (!config) { this.emit('error', 'get if config error'); } } } function openNetMgrClient(options) { return new netMgr(options); } module.exports = { openNetMgrClient, }
YifuLiu/AliOS-Things
components/amp/libjs/lib/netmgr.js
JavaScript
apache-2.0
3,456
'use strict'; const EventEmitter = require('events'); class netWork extends EventEmitter{ constructor(options) { super(); if(!options || !options.type){ throw new Error('net type is error'); } this.options = { type: options.type || 'cellular', devName: options.devName || '' }; this._init(); this._cellularStatus(); this.dev_handler = this._getDev(this.devName); } _init() { if (__native.NETMGR.serviceInit() !== 0) { this.emit('error', 'netmgr init error'); } } _getDev(devName) { var dev_handler = __native.NETMGR.getDev(devName); if (!dev_handler){ this.emit('error', 'netmgr get dev error ' + devName); return; } return dev_handler; } _cellularStatus() { var cb = function(status) { if (status === 1) { this.emit('connect'); } else { this.emit('disconnect'); } } var type = this.type; if (type != 'cellular') { return; } if(__native.CELLULAR.onConnect(cb.bind(this)) !== 0){ this.emit('error', 'network status error'); } } setMsgCb(cb) { __native.NETMGR.setMsgCb(this.dev_handler, cb); } delMsgCb(cb) { __native.NETMGR.delMsgCb(this.dev_handler, cb); } setAutoReconnect(flag) { var ret = __native.NETMGR.setAutoReconnect(this.dev_handler, flag); if (ret !== 0) { this.emit('error', 'netmgr set auto reconnect error'); } } connect(options) { options = { ssid: options.ssid, password: options.password, bssid: options.bssid || '', timeout_ms: options.timeout_ms || 18000 } __native.NETMGR.connect(this.dev_handler, options, function(status) { if (status == 'DISCONNECT'){ this.emit('disconnect', options.ssid); return; } this.emit('connect', options.ssid); }.bind(this)); } disconnect() { var ret = __native.NETMGR.disconnect(this.dev_handler); if (ret !== 0) { this.emit('error', 'netmgr disconnect error'); return; } this.emit('disconnect', ssid); } getStatus() { if (this.type == 'wifi') { var ret = __native.NETMGR.getState(this.dev_handler); switch (ret) { case 0: return 'disconnecting'; case 1: return 'disconnected'; case 2: return 'connecting'; case 3: return 'connected'; case 4: return 'obtaining ip'; case 5: return 'network connected'; case 6: return 'failed'; } } if (this.type == 'cellular') { if (__native.CELLULAR.getStatus() != 1) { return 'disconnect'; } return 'connect'; } } getInfo() { var info = { simInfo: null, locatorInfo: null, wifiInfo: null }; if (this.type == 'wifi') { info.wifiInfo = __native.WIFI.getIfConfig(); return info; } if (this.type == 'cellular') { info.simInfo = __native.CELLULAR.getSimInfo(); info.locatorInfo = __native.CELLULAR.getLocatorInfo(); return info; } return; } saveConfig() { var ret = __native.NETMGR.saveConfig(this.dev_handler); if (ret !== 0) { this.emit('error', 'netmgr save config error'); } } setIfConfig(options) { options = { dhcp_en: options.dhcp_en || true, ip_addr: options.ip_addr || '', mask: options.mask || '', gw: options.gw || '', dns_server: options.dns_server || '', mac: options.mac || '' } var ret = __native.NETMGR.setIfConfig(this.dev_handler, options); if (ret !== 0) { this.emit('error', 'netmgr save config error'); } } getIfConfig() { var config = __native.NETMGR.getIfConfig(this.dev_handler); if (!config) { this.emit('error', 'get if config error'); } } } function openNetWorkClient(options) { return new netWork(options); } module.exports = { openNetWorkClient, }
YifuLiu/AliOS-Things
components/amp/libjs/lib/network.js
JavaScript
apache-2.0
4,651
'use strict'; class HW_ONEWIRE { constructor(options) { if (!options || !options.id) { throw new Error("options is invalid"); } this.options = { id: options.id }; this.success = options.success || function(){}; this.fail = options.fail || function(){}; this._open(); } _open() { this.onewireinstance = __native.ONEWIRE.open(this.options.id); if (!this.onewireinstance) { this.fail(); return; } this.success(); } setspeed(standard) { if (!this.onewireinstance) { throw new Error("onewire not init"); } __native.ONEWIRE.setspeed(this.onewireinstance, standard); } reset() { if (!this.onewireinstance) { throw new Error("onewire not init"); } __native.ONEWIRE.reset(this.onewireinstance); } readByte() { if (!this.onewireinstance) { throw new Error("onewire not init"); } return __native.ONEWIRE.readByte(this.onewireinstance); }; writeByte(data) { if (!this.onewireinstance) { throw new Error("onewire not init"); } return __native.ONEWIRE.writeByte(this.onewireinstance, data); }; close() { if (!this.onewireinstance) { throw new Error("onewire not init"); } __native.ONEWIRE.close(this.onewireinstance); } } function open(options) { return new HW_ONEWIRE(options); } module.exports = { open, }
YifuLiu/AliOS-Things
components/amp/libjs/lib/onewire.js
JavaScript
apache-2.0
1,582
'use strict'; const EventEmitter = require('events'); class PayboxClient extends EventEmitter{ constructor(options){ super(); if(!options || !options.xpPrductKey || !options.xpDeviceSecret){ throw new Error('device info error'); } this.options = { mqttPrductKey: options.mqttPrductKey ? options.mqttPrductKey : 'null', supplierId: options.supplierId ? options.supplierId : 'null', itemId: options.itemId ? options.itemId : 'null', boxModel: options.boxModel ? options.boxModel : 'null', boxVersion: options.boxVersion ? options.boxVersion : 'null', xpPrductKey: options.xpPrductKey, xpPrductSecret: options.xpPrductSecret ? options.xpPrductSecret : 'null', xpDeviceSecret: options.xpDeviceSecret } this.fail = options.fail || function(){}; this.success = options.success || function(){}; this.opened = false; this.onFlag = false; this._open(); this._on(); } _open() { this.payboxInstance = __native.PAYBOX.open(this.options); if (this.payboxInstance < 0) { this.fail(); return; } this.opened = true; this.success(); } _on() { if (this.payboxInstance < 0) { throw new Error("PAYBOX not init"); } __native.PAYBOX.on(this.payboxInstance, function(event, data){ this.emit(event, data); }.bind(this)); }; close() { if(this.payboxInstance < 0){ throw new Error('device not init...'); } var ret = __native.PAYBOX.close(this.payboxInstance); if (ret != 0) { this.emit('error', 'paybox client close falied') return } this.opened = false; this.emit('close'); } } function open(options){ return new PayboxClient(options); } module.exports = { open, }
YifuLiu/AliOS-Things
components/amp/libjs/lib/paybox.js
JavaScript
apache-2.0
1,999
'use strict'; const EventEmitter = require('events'); module.exports = new class UTILS_PM extends EventEmitter { constructor(){ super(); this._onPwrkey(); } _onPwrkey() { __native.PM.onPwrkey(function(state) { this.emit('powerKey', state); }.bind(this)); }; setAutosleepMode(mode) { var ret = __native.PM.setAutosleepMode(mode); if (ret < 0) { this.emit('error', ret); return; } } getAutosleepMode() { var ret = __native.PM.getAutosleepMode(); if (ret < 0) { this.emit('error', ret); return; } } sleep() { var ret = __native.PM.sleep(); if (ret < 0) { this.emit('error', ret); return; } } powerReset() { var ret = __native.PM.powerReset(); if (ret < 0) { this.emit('error', ret); return; } } powerDown() { var ret = __native.PM.powerDown(); if (ret < 0) { this.emit('error', ret); return; } } wakelockLock() { var ret = __native.PM.wakelockLock(); if (ret < 0) { this.emit('error', ret); return; } } wakelockUnlock() { var ret = __native.PM.wakelockUnlock(); if (ret < 0) { this.emit('error', ret); return; } } wakelockTimedlock(timeMs) { var ret = __native.PM.wakelockTimedlock(timeMs); if (ret < 0) { this.emit('error', ret); return; } } }
YifuLiu/AliOS-Things
components/amp/libjs/lib/pm.js
JavaScript
apache-2.0
1,660
'use strict'; class HW_PWM { constructor(options) { if (!options || !options.id) { throw new Error("options is invalid"); } this.options = { id: options.id }; this.success = options.success || function(){}; this.fail = options.fail || function(){}; this._open(); } _open() { this.pwmInstance = __native.PWM.open(this.options.id); if (!this.pwmInstance) { this.fail(); return; } this.success(); } set(options) { if (!this.pwmInstance || !options) { throw new Error("pwm not init or params is invalid"); } __native.PWM.setConfig(this.pwmInstance, options); }; get() { if (!this.pwmInstance) { throw new Error("pwm not init"); } return __native.PWM.getConfig(this.pwmInstance); }; close() { if (!this.pwmInstance) { throw new Error("pwm not init"); } __native.PWM.close(this.pwmInstance); }; } function open(options) { return new HW_PWM(options); } module.exports = { open, }
YifuLiu/AliOS-Things
components/amp/libjs/lib/pwm.js
JavaScript
apache-2.0
1,172
'use strict'; function start() { __native.RTC.open(); } function setTime(time) { if (!time) { throw new Error('params is invalid'); } if (!(time instanceof Date)) { throw new Error('params is invalid'); } var date = { year: time.getYear(), month: time.getMonth(), day: time.getDate(), hour: time.getHours(), minute: time.getMinutes(), second: time.getSeconds() } __native.RTC.setTime(date); } function getTime() { var time = __native.RTC.getTime(); console.log(time); return new Date(parseInt(time.year) + 1900, parseInt(time.month), parseInt(time.day), parseInt(time.hour), parseInt(time.minute), parseInt(time.second)); } function close() { __native.RTC.close(); } module.exports = { start, setTime, getTime, close }
YifuLiu/AliOS-Things
components/amp/libjs/lib/rtc.js
JavaScript
apache-2.0
853
'use strict'; const EventEmitter = require('events'); module.exports = new class Smartcard extends EventEmitter { constructor(){ super(); } init() { return __native.smartcard.init(); }; deinit() { return __native.smartcard.deinit(); }; select(operator) { return __native.smartcard.select(operator); }; }
YifuLiu/AliOS-Things
components/amp/libjs/lib/smartcard.js
JavaScript
apache-2.0
372
'use strict'; class HW_SPI { constructor(options) { if (!options || !options.id) { throw new Error("options is invalid"); } this.options = { id: options.id }; this.success = options.success || function(){}; this.fail = options.fail || function(){}; this._open(); } _open() { this.spiInstance = __native.SPI.open(this.options.id); if (!this.spiInstance) { this.fail(); return; } this.success(); } write(data) { if (!this.spiInstance || !data) { throw new Error("spi not init or params is invalid"); } __native.SPI.write(this.spiInstance, data); } read(bytes) { if (!this.spiInstance || !bytes) { throw new Error("spi not init or params is invalid"); } return __native.SPI.read(this.spiInstance, bytes); }; readWrite(sendData, bytes) { if (!this.spiInstance || !sendData ||!bytes) { throw new Error("spi not init or params is invalid"); } return __native.SPI.sendRecv(this.spiInstance, sendData, bytes); }; close() { if (!this.spiInstance) { throw new Error("spi not init"); } __native.SPI.close(this.spiInstance); }; } function open(options) { return new HW_SPI(options); } module.exports = { open, }
YifuLiu/AliOS-Things
components/amp/libjs/lib/spi.js
JavaScript
apache-2.0
1,444
'use strict'; const EventEmitter = require('events'); function stringToBytesArray(str) { var ch, st, re = []; for (var i = 0; i < str.length; i++ ) { ch = str.charCodeAt(i); st = []; do { st.push(ch & 0xFF); ch = ch >> 8; } while ( ch ); re = re.concat(st.reverse()); } return re; } class TCPClient extends EventEmitter{ constructor(options) { super(); if (!options || !options.host || !options.port) { throw new Error("invalid params"); } this.options = { host: options.host, port: options.port } this.success = options.success || function(){}; this.fail = options.fail || function(){}; this._connect(); } _connect() { this.connected = false; var cb = function(ret) { if (ret < 0) { this.fail(); this.emit('error', 'tcp connect error'); return; } this.tcpClientInstance = ret; this.connected = true; this.success(); this.emit('connect'); this._onListening(); } if(__native.TCP.createSocket(this.options, cb.bind(this)) < 0){ this.fail(); this.emit('error', 'tcp connect error'); } } send(options) { if (!(options.message instanceof Array)) { options.message = stringToBytesArray(options.message); } if(this.connected === false) { throw new Error("tcp not connected"); } __native.TCP.send(this.tcpClientInstance, options.message, function(ret) { if (ret < 0) { this.emit('error', 'tcp send error'); if(options.fail) options.fail(); return; } this.emit('send', 'tcp send success'); if(options.success) options.success(); }.bind(this)); }; _onListening() { if (!this.tcpClientInstance) { throw new Error("tcpserver not init"); } __native.TCP.recv(this.tcpClientInstance, function(datalen, data) { if (datalen === -2) { this.connected = false; this.emit('error', 'tcp receive message error'); return; } if (datalen === -1) { this.connected = false; this.emit('disconnect'); return; } if (datalen > 0) { this.emit('message', data); } }.bind(this)); }; close() { if (!this.tcpClientInstance) { throw new Error("tcpserver not init"); } var ret = __native.TCP.close(this.tcpClientInstance); if (ret != 0) { this.emit('error', 'tcp socket close error'); return; } this.emit('close', 'tcp socket close success'); }; reconnect() { if (this.tcpClientInstance) { __native.TCP.close(this.tcpClientInstance); } this._connect(); }; } function createClient(options) { return new TCPClient(options); } module.exports = { createClient, }
YifuLiu/AliOS-Things
components/amp/libjs/lib/tcp.js
JavaScript
apache-2.0
3,286
'use strict'; class HW_TIMER { constructor(options) { if (!options || !options.id) { throw new Error('options is invalid'); } this.options = { id: options.id }; this.success = options.success || function(){}; this.fail = options.fail || function(){}; this._open(); } _open() { this.timerInstance = __native.TIMER.open(this.options.id); if (!this.timerInstance) { this.fail(); return; } this.success(); } setTimeout(cb, timeout) { if (!this.timerInstance) { throw new Error("timer not init"); } var ret = __native.TIMER.setTimeout(this.timerInstance, cb, timeout); if (ret != 0) { throw new Error("set time out failed"); } } clearTimeout() { if (!this.timerInstance) { throw new Error("timer not init"); } var ret = __native.TIMER.clearTimeout(this.timerInstance); if (ret != 0) { throw new Error("clear time out failed"); } } setInterval(cb, timeout) { if (!this.timerInstance) { throw new Error("timer not init"); } var ret = __native.TIMER.setInterval(this.timerInstance, cb, timeout); if (ret != 0) { throw new Error("set interval failed"); } } clearInterval() { if (!this.timerInstance) { throw new Error("timer not init"); } var ret = __native.TIMER.clearInterval(this.timerInstance); if (ret != 0) { throw new Error("clear interval failed"); } }; close() { if (!this.timerInstance) { throw new Error("timer not init"); } __native.TIMER.close(this.timerInstance); }; } function open(options) { return new HW_TIMER(options); } module.exports = { open, }
YifuLiu/AliOS-Things
components/amp/libjs/lib/timer.js
JavaScript
apache-2.0
1,961
'use strict'; const EventEmitter = require('events'); module.exports = new class TTSSystem extends EventEmitter { constructor(){ super(); this._onState(); } play(content, encode) { if (!content) { throw new Error('invalid params'); } return __native.TTS.play(content, encode); }; stop() { return __native.TTS.stop(); }; getState() { return __native.TTS.getState(); }; _onState() { __native.TTS.onState(function(state) { this.emit('state', state); }.bind(this)); }; setPitch(type) { if (!type) { throw new Error('invalid params'); } return __native.TTS.setPitch(type); }; setSpeed(speed) { if (!speed) { throw new Error('invalid params'); } return __native.TTS.setSpeed(speed); }; getSpeed() { return __native.TTS.getSpeed(); }; setVolume(volume) { if (!volume) { throw new Error('invalid params'); } return __native.TTS.setVolume(volume); }; getVolume() { return __native.TTS.getVolume(); }; }
YifuLiu/AliOS-Things
components/amp/libjs/lib/tts.js
JavaScript
apache-2.0
1,205
'use strict'; const EventEmitter = require('events'); class HW_UART extends EventEmitter{ constructor(options) { super(); if (!options || !options.id) { throw new Error("options is invalid"); } this.options = { id: options.id, mode: options.mode }; this.success = options.success || function(){}; this.fail = options.fail || function(){}; this._open(); if (this.options.mode !== 'poll') { this._onData(); } } _open() { this.uartInstance = __native.UART.open(this.options.id); if (this.uartInstance === null) { this.fail(); return; } this.success(); } write(data) { if (this.uartInstance === null || !data) { throw new Error("uart not init"); } __native.UART.write(this.uartInstance, data); } read() { if (this.uartInstance === null) { throw new Error("uart not init"); } return __native.UART.read(this.uartInstance); }; off() { if (this.uartInstance === null) { throw new Error("uart not init"); } this.removeAllListeners('data'); } _onData() { if (this.uartInstance === null) { throw new Error("uart not init"); } __native.UART.on(this.uartInstance, function(len, data){ this.emit('data', len, data); }.bind(this)); }; close() { if (this.uartInstance === null) { throw new Error("uart not init"); } __native.UART.close(this.uartInstance); }; on_mode() { if (this.uartInstance === null) { throw new Error("uart not init"); } this._onData(); }; } function open(options) { return new HW_UART(options); } module.exports = { open, }
YifuLiu/AliOS-Things
components/amp/libjs/lib/uart.js
JavaScript
apache-2.0
1,939
'use strict'; const EventEmitter = require('events'); function stringToBytesArray(str) { var ch, st, re = []; for (var i = 0; i < str.length; i++ ) { ch = str.charCodeAt(i); st = []; do { st.push(ch & 0xFF); ch = ch >> 8; } while ( ch ); re = re.concat(st.reverse()); } return re; } class UDPClient extends EventEmitter { constructor() { super(); this.udpClientInstance = __native.UDP.createSocket(); this.localPort = 0; } bind(port) { this.localPort = port || 0; if(__native.UDP.bind(this.udpClientInstance, this.localPort) < 0) { throw new Error("bind error"); } this._onListening(); }; send(options) { if (!(options.message instanceof Array)) { options.message = stringToBytesArray(options.message); } __native.UDP.sendto(this.udpClientInstance, options, function(ret) { if (ret < 0) { this.emit('error', 'udp send error'); if(options.fail) options.fail(); return; } this.emit('send', 'udp send success'); if(options.success) options.success(); }.bind(this)); }; close() { var ret = __native.UDP.close(this.udpClientInstance); if (ret < 0) { console.log('close udp socket faild'); return; } this.emit('close', 'udp client close'); }; _onListening() { __native.UDP.recvfrom(this.udpClientInstance, function(data, rinfo, err) { if (err === -4) { this.emit('error', 'udp client receive data error'); return; } if (err > 0) { this.emit('message', data, rinfo); } }.bind(this)); }; } function createSocket(options) { return new UDPClient(options); } module.exports = { createSocket, }
YifuLiu/AliOS-Things
components/amp/libjs/lib/udp.js
JavaScript
apache-2.0
2,003
'use strict'; module.exports = __native.UI;
YifuLiu/AliOS-Things
components/amp/libjs/lib/ui.js
JavaScript
apache-2.0
47
'use strict'; module.exports = __native.UND;
YifuLiu/AliOS-Things
components/amp/libjs/lib/und.js
JavaScript
apache-2.0
45
'use strict'; module.exports = __native.VM;
YifuLiu/AliOS-Things
components/amp/libjs/lib/vm.js
JavaScript
apache-2.0
44
'use strict'; function start(timeout) { if (!timeout) { throw new Error('params is invalid'); } __native.WDG.start(timeout); } function feed() { __native.WDG.feed(); } function stop() { __native.WDG.stop(); } module.exports = { start, feed, stop }
YifuLiu/AliOS-Things
components/amp/libjs/lib/wdg.js
JavaScript
apache-2.0
291
'use strict'; const event = require('events'); function setIfConfig(options) { if (!options) { throw new Error('params is invalid'); } __native.WIFI.set_ifconfig(options); } function getIfConfig() { var config = __native.WIFI.get_ifconfig(); if (!config) { throw 'get ifconfig failed'; } return config; } function connect(options) { if(!options) { throw new Error("invalid params"); } __native.WIFI.connect(options, function(state) { if (state == 1) { console.log('wifi connected success') event.emit('connect'); } }); } function disconnect() { return __native.WIFI.disconnect(); } function getState() { var state; state = __native.WIFI.getState(); return state; } module.exports = { setIfConfig, getIfConfig, connect, disconnect, getState }
YifuLiu/AliOS-Things
components/amp/libjs/lib/wifi.js
JavaScript
apache-2.0
893
TARGET = libmain.a MODULE = main MOD_SOURCES += \ amp_main.c \ amp_engine.c \ amp_task.c MOD_INCLUDES := \ ../adapter/include \ ../adapter/include/peripheral \ ../adapter/platform/linux \ ../utils/mbedtls/include \ ../utils/mbedtls/platform/include \ ../utils/mbedtls/platform/amp/include \ ../utils/cJSON \ ../utils/list \ ../components/linkkit \ ../components/linkkit/infra \ ../components/ulog \ ../services/board_mgr \ ../services/recovery \ ../services/app_mgr ifeq ($(ADDON), ui) MOD_INCLUDES += \ ../ui/render/include \ ../ui/aui/ \ ../ui/aui/aui_core \ ../ui/aui/aui_draw \ ../ui/aui/aui_fonts \ ../ui/aui/aui_hal \ ../ui/aui/aui_misc \ ../ui/aui/aui_objx \ ../ui/aui/aui_themes \ ../ui/aui/libs \ ../ui/aui/libs/lvgl \ ../ui/aui/libs/lvgl/src\ ../ui/aui/libs/lvgl/src/lv_misc \ ../ui/aui/libs/lvgl/src/lv_font \ ../ui/aui/libs/lvgl/src/lv_core \ ../ui/aui/libs/lvgl/src/lv_draw \ ../ui/aui/libs/lvgl/src/lv_hal \ ../ui/aui/libs/lvgl/src/lv_objx \ ../ui/aui/libs/lvgl/src/lv_themes \ ../utils/ezxml \ ../utils/lexbor \ ../utils/lexbor/css \ ../adapter/include \ ../components/linkkit \ ../components/linkkit/infra \ ../main \ ../utils/mbedtls/include \ ../components/ulog \ ../engine/duktape_engine \ ../adapter/platform/linux endif include $(TOOLS_DIR)/rules.mk
YifuLiu/AliOS-Things
components/amp/main/Makefile
Makefile
apache-2.0
1,372
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #ifndef AMP_DEFINES_H #define AMP_DEFINES_H #include "amp_config.h" #include "amp_memory.h" #include "mbedtls/md5.h" #include "mbedtls/sha1.h" #include "mbedtls/aes.h" #include "mbedtls/des.h" #include "mbedtls/base64.h" #include "ulog/ulog.h" #include "aos_fs.h" #define AMP_APP_MAIN_JS AMP_FS_ROOT_DIR"/app.js" #define AMP_APP_MAIN_JSB AMP_FS_ROOT_DIR"/app.jsb" #define AMP_APP_MAIN_JSON AMP_FS_ROOT_DIR"/app.json" #define AMP_APP_PACKAGE_JSON AMP_FS_ROOT_DIR"/package.json" #define AMP_APP_INDEX_JS AMP_FS_ROOT_DIR"/index.js" typedef enum { HAL_SEEK_SET, HAL_SEEK_CUR, HAL_SEEK_END } hal_fs_seek_type_t; /* sdk version */ #define AMP_VERSION_LENGTH 128 #define AMP_VERSION_NUMBER "3.0.1" #define AMP_GIT_COMMIT "g9c40fab" #define AMP_MODULE_HARDWARE aos_get_module_hardware_version() #define AMP_MODULE_SOFTWARE aos_get_module_software_version() /* interval device infomation */ #define AMP_DEVICE_TOKEN "_amp_device_token" #define AMP_DEVICE_TOKEN_VERIFY_FLAG "_amp_device_token_verify_flag" #define AMP_DEVICE_TOKEN_LENGTH 64 #define AMP_INTERNAL_PRODUCTKEY "_amp_internal_productkey" #define AMP_INTERNAL_PRODUCTSECRET "_amp_internal_productsecret" #define AMP_INTERNAL_DEVICENAME "_amp_internal_devicename" #define AMP_INTERNAL_DEVICESECRET "_amp_internal_devicesecret" /* customer device infomation */ #define AMP_CUSTOMER_PRODUCTKEY "_amp_customer_productkey" #define AMP_CUSTOMER_PRODUCTSECRET "_amp_customer_productsecret" #define AMP_CUSTOMER_DEVICENAME "_amp_customer_devicename" #define AMP_CUSTOMER_DEVICESECRET "_amp_customer_devicesecret" #define osWaitForever 0xFFFFFFFF /* wait forever timeout value */ #define PLATFORM_WAIT_INFINITE (~0) #define IOTX_PRODUCT_KEY_LEN (20) #define IOTX_DEVICE_NAME_LEN (32) #define IOTX_DEVICE_SECRET_LEN (64) #define IOTX_PRODUCT_SECRET_LEN (64) /* task stack size */ #define JSENGINE_TASK_STACK_SIZE 1024 * 15 /* task priority */ #define JSE_TSK_PRIORITY AOS_DEFAULT_APP_PRI + 5 #define CLI_TSK_PRIORITY AOS_DEFAULT_APP_PRI + 7 #define MQTT_TSK_PRIORITY AOS_DEFAULT_APP_PRI + 6 #define MQTTHTTP_TSK_PRIORITY AOS_DEFAULT_APP_PRI + 4 #define SSDP_TSK_PRIORITY AOS_DEFAULT_APP_PRI + 3 #define WEBSOCKET_TSK_PRIORITY AOS_DEFAULT_APP_PRI + 4 #define WIFI_TSK_PRIORITY AOS_DEFAULT_APP_PRI + 4 #define UPDATE_TSK_PRIORITY AOS_DEFAULT_APP_PRI + 6 #define ADDON_TSK_PRIORRITY AOS_DEFAULT_APP_PRI + 3 /* log system operation wrapper */ #define amp_debug(mod, fmt, ...) LOGD(mod, fmt, ##__VA_ARGS__) #define amp_info(mod, fmt, ...) LOGI(mod, fmt, ##__VA_ARGS__) #define amp_warn(mod, fmt, ...) LOGW(mod, fmt, ##__VA_ARGS__) #define amp_error(mod, fmt, ...) LOGE(mod, fmt, ##__VA_ARGS__) #define amp_fatal(mod, fmt, ...) LOGF(mod, fmt, ##__VA_ARGS__) /* JS console stdout */ #if defined(AMP_REPL_ENABLE) && defined(AMP_REPL_STDIO_EXTERNAL) #define amp_console(fmt, ...) do { \ repl_printf(fmt, ##__VA_ARGS__); \ repl_printf("\r\n"); \ }while(0) #else #define amp_console(fmt, ...) do { \ aos_printf(fmt, ##__VA_ARGS__); \ aos_printf("\r\n"); \ }while(0) #endif /* md5 */ #define amp_md5_context mbedtls_md5_context #define amp_md5 mbedtls_md5 #define amp_md5_init mbedtls_md5_init #define amp_md5_starts mbedtls_md5_starts #define amp_md5_update mbedtls_md5_update #define amp_md5_finish mbedtls_md5_finish #define amp_md5_free mbedtls_md5_free /* sha1 */ #define amp_sha1_context mbedtls_sha1_context #define amp_sha1_init mbedtls_sha1_init #define amp_sha1_starts mbedtls_sha1_starts #define amp_sha1_update mbedtls_sha1_update #define amp_sha1_finish mbedtls_sha1_finish #define amp_sha1_free mbedtls_sha1_free /* aes */ #define AMP_AES_ENCRYPT MBEDTLS_AES_ENCRYPT #define AMP_AES_DECRYPT MBEDTLS_AES_DECRYPT #define amp_aes_context mbedtls_aes_context #define amp_aes_init mbedtls_aes_init #define amp_aes_setkey_enc mbedtls_aes_setkey_enc #define amp_aes_setkey_dec mbedtls_aes_setkey_dec #define amp_aes_crypt_cbc mbedtls_aes_crypt_cbc #define amp_aes_free mbedtls_aes_free /* des */ #define amp_des_context mbedtls_des_context #define amp_des_init mbedtls_des_init #define amp_des_setkey_enc mbedtls_des_setkey_enc #define amp_des_crypt_ecb mbedtls_des_crypt_ecb #define amp_des_free mbedtls_des_free /* base64 */ #define amp_base64_encode mbedtls_base64_encode #define amp_base64_decode mbedtls_base64_decode #endif /* AMP_DEFINES_H */
YifuLiu/AliOS-Things
components/amp/main/amp_defines.h
C
apache-2.0
4,762
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include "aos/kernel.h" #include "aos/vfs.h" #include "aos_system.h" #include "aos_fs.h" #include "amp_platform.h" #include "amp_config.h" #include "amp_task.h" #include "amp_defines.h" #include "board_mgr.h" #include "cJSON.h" #define MOD_STR "AMP_ENGINE" #define APP_PACKAGE_FILE_NAME JSE_FS_ROOT_DIR "/package.json" #define MAX_FILE_NAME_LEN 127 static char js_app_file_name[128]; static int32_t g_console_log_enable = 1; aos_sem_t jse_task_exit_sem; extern void jsengine_init(void); extern void jsengine_eval_file(const char *filename); int32_t bone_console_get_log_flag(void) { return g_console_log_enable; } void bone_console_log_enable(void) { g_console_log_enable = 1; } void bone_console_log_disable(void) { g_console_log_enable = 0; } /** * 1. search js entry: /spiffs/index.js in spiffs * 2. get [test] or [main] in /spiffs/package.json */ char *search_js_app_main_entry(void) { cJSON *root = NULL; cJSON *item = NULL; void *json_data = NULL; int js_app_fd = -1; int file_len = 0; int json_fd = -1; snprintf(js_app_file_name, 128, AMP_APP_MAIN_JS); /* use the currrent dir default index.js file to the main js entry programe */ if ((js_app_fd = aos_open(js_app_file_name, O_RDONLY)) >= 0) { aos_close(js_app_fd); amp_debug(MOD_STR, "find the default file :%s", js_app_file_name); return js_app_file_name; } snprintf(js_app_file_name, 128, AMP_APP_MAIN_JSB); /* use the currrent dir default index.js file to the main js entry programe */ if ((js_app_fd = aos_open(js_app_file_name, O_RDONLY)) >= 0) { aos_close(js_app_fd); amp_debug(MOD_STR, "find the default file :%s", js_app_file_name); return js_app_file_name; } snprintf(js_app_file_name, 128, AMP_APP_PACKAGE_JSON); /* cannot find the index.js int current dir */ if ((json_fd = aos_open(js_app_file_name, O_RDONLY)) < 0) { amp_error(MOD_STR, "cannot find the file :%s", js_app_file_name); return NULL; } /* read package config file to json_data buffer */ file_len = aos_lseek(json_fd, 0, SEEK_END); json_data = amp_calloc(1, sizeof(char) * (file_len + 1)); if (NULL == json_data) { aos_close(json_fd); json_fd = -1; return NULL; } aos_lseek(json_fd, 0, SEEK_SET); aos_read(json_fd, json_data, file_len); aos_close(json_fd); /* parser the package json data */ root = cJSON_Parse(json_data); if (NULL == root) { amp_free(json_data); amp_error(MOD_STR, "cJSON_Parse failed"); return NULL; } /* find the test/xxx.js */ item = cJSON_GetObjectItem(root, "test"); if (NULL != item && cJSON_String == item->type && strstr(item->valuestring, ".js")) { snprintf(js_app_file_name, sizeof(js_app_file_name), "/%s", item->valuestring); if ((js_app_fd = aos_open(js_app_file_name, O_RDONLY)) < 0) { aos_close(js_app_fd); amp_free(json_data); cJSON_Delete(root); amp_debug(MOD_STR, "find test index %s", js_app_file_name); return js_app_file_name; } } /* find the main/xxx.js */ item = cJSON_GetObjectItem(root, "main"); if (NULL != item && cJSON_String == item->type && strstr(item->valuestring, ".js")) { strncpy(js_app_file_name, item->valuestring, MAX_FILE_NAME_LEN); amp_free(json_data); cJSON_Delete(root); amp_debug(MOD_STR, "find main index %s", js_app_file_name); return js_app_file_name; } amp_free(json_data); cJSON_Delete(root); return NULL; } void be_jse_task_main_entrance(void *arg) { amp_debug(MOD_STR, "jse main task start..."); amp_task_main(); aos_task_exit(0); return; } void amp_task_main() { uint8_t ssdp_started = 0; int app_running = 1; char user_dir[128] = {0}; snprintf(user_dir, sizeof(user_dir), AMP_APP_MAIN_JSON); if (0 != board_mgr_init(user_dir)) { amp_error(MOD_STR, "read %s error", user_dir); app_running = 0; } /* JSE task init */ amp_task_init(); /* JSE init */ jsengine_init(); amp_debug(MOD_STR, "jsengine_init ok"); #ifndef HAASUI_AMP_BUILD /* run the js application */ char *filename = search_js_app_main_entry(); amp_debug(MOD_STR, "search_js_app_main_entry: %s", filename ? filename : "null"); if (filename && app_running) { jsengine_eval_file(filename); } else { amp_error(MOD_STR, "Won't run app.js"); } while (1) { /* loop for asynchronous operation */ jsengine_loop_once(); if(amp_task_yield(200) == 1) { amp_debug(MOD_STR, "jsengine task yield exit!"); break; } } amp_task_deinit(); aos_sem_signal(&jse_task_exit_sem); amp_memmgt_mem_show_rec(); #endif } void jsengine_main(void) { int ret = 0; aos_task_t jsengine_task; amp_debug(MOD_STR, "jsengine start..."); if (aos_sem_new(&jse_task_exit_sem, 0) != 0) { amp_error(MOD_STR, "create jse exit sem failed"); return; } #ifndef HAASUI_AMP_BUILD amp_debug(MOD_STR, "jse_task created"); aos_task_new_ext(&jsengine_task, "amp_jsengine_task", be_jse_task_main_entrance, NULL, JSENGINE_TASK_STACK_SIZE, AOS_DEFAULT_APP_PRI); #else amp_task_main(); #endif }
YifuLiu/AliOS-Things
components/amp/main/amp_engine.c
C
apache-2.0
5,489
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #ifndef AMP_ERRNO_H #define AMP_ERRNO_H #ifdef __cplusplus extern "C" { #endif #if defined(__GNUC__)&&!defined(__CC_ARM)||defined(_WIN32) #include <errno.h> #else #define EPERM 1 /* Operation not permitted */ #define ENOENT 2 /* No such file or directory */ #define ESRCH 3 /* No such process */ #define EINTR 4 /* Interrupted system call */ #define EIO 5 /* I/O error */ #define ENXIO 6 /* No such device or address */ #define E2BIG 7 /* Arg list too long */ #define ENOEXEC 8 /* Exec format error */ #define EBADF 9 /* Bad file number */ #define ECHILD 10 /* No child processes */ #define EAGAIN 11 /* Try again */ #ifdef ENOMEM #undef ENOMEM #endif #define ENOMEM 12 /* Out of memory */ #define EACCES 13 /* Permission denied */ #define EFAULT 14 /* Bad address */ #define ENOTBLK 15 /* Block device required */ #define EBUSY 16 /* Device or resource busy */ #define EEXIST 17 /* File exists */ #define EXDEV 18 /* Cross-device link */ #define ENODEV 19 /* No such device */ #define ENOTDIR 20 /* Not a directory */ #define EISDIR 21 /* Is a directory */ #ifdef EINVAL #undef EINVAL #endif #define EINVAL 22 /* Invalid argument */ #define ENFILE 23 /* File table overflow */ #define EMFILE 24 /* Too many open files */ #define ENOTTY 25 /* Not a typewriter */ #define ETXTBSY 26 /* Text file busy */ #define EFBIG 27 /* File too large */ #define ENOSPC 28 /* No space left on device */ #define ESPIPE 29 /* Illegal seek */ #define EROFS 30 /* Read-only file system */ #define EMLINK 31 /* Too many links */ #define EPIPE 32 /* Broken pipe */ #ifdef EDOM #undef EDOM #define EDOM 33 /* Math argument out of domain of func */ #endif #ifdef ERANGE #undef ERANGE #define ERANGE 34 /* Math result not representable */ #endif #define EDEADLK 35 /* Resource deadlock would occur */ #define ENAMETOOLONG 36 /* File name too long */ #define ENOLCK 37 /* No record locks available */ #define ENOSYS 38 /* Function not implemented */ #define ENOTEMPTY 39 /* Directory not empty */ #define ELOOP 40 /* Too many symbolic links encountered */ #define EWOULDBLOCK EAGAIN /* Operation would block */ #define ENOMSG 42 /* No message of desired type */ #define EIDRM 43 /* Identifier removed */ #define ECHRNG 44 /* Channel number out of range */ #define EL2NSYNC 45 /* Level 2 not synchronized */ #define EL3HLT 46 /* Level 3 halted */ #define EL3RST 47 /* Level 3 reset */ #define ELNRNG 48 /* Link number out of range */ #define EUNATCH 49 /* Protocol driver not attached */ #define ENOCSI 50 /* No CSI structure available */ #define EL2HLT 51 /* Level 2 halted */ #define EBADE 52 /* Invalid exchange */ #define EBADR 53 /* Invalid request descriptor */ #define EXFULL 54 /* Exchange full */ #define ENOANO 55 /* No anode */ #define EBADRQC 56 /* Invalid request code */ #define EBADSLT 57 /* Invalid slot */ #define EDEADLOCK EDEADLK #define EBFONT 59 /* Bad font file format */ #define ENOSTR 60 /* Device not a stream */ #define ENODATA 61 /* No data available */ #define ETIME 62 /* Timer expired */ #define ENOSR 63 /* Out of streams resources */ #define ENONET 64 /* Machine is not on the network */ #define ENOPKG 65 /* Package not installed */ #define EREMOTE 66 /* Object is remote */ #define ENOLINK 67 /* Link has been severed */ #define EADV 68 /* Advertise error */ #define ESRMNT 69 /* Srmount error */ #define ECOMM 70 /* Communication error on send */ #define EPROTO 71 /* Protocol error */ #define EMULTIHOP 72 /* Multihop attempted */ #define EDOTDOT 73 /* RFS specific error */ #define EBADMSG 74 /* Not a data message */ #define EOVERFLOW 75 /* Value too large for defined data type */ #define ENOTUNIQ 76 /* Name not unique on network */ #define EBADFD 77 /* File descriptor in bad state */ #define EREMCHG 78 /* Remote address changed */ #define ELIBACC 79 /* Can not access a needed shared library */ #define ELIBBAD 80 /* Accessing a corrupted shared library */ #define ELIBSCN 81 /* .lib section in a.out corrupted */ #define ELIBMAX 82 /* Attempting to link in too many shared libraries */ #define ELIBEXEC 83 /* Cannot exec a shared library directly */ #ifdef EILSEQ #undef EILSEQ #endif #define EILSEQ 84 /* Illegal byte sequence */ #define ERESTART 85 /* Interrupted system call should be restarted */ #define ESTRPIPE 86 /* Streams pipe error */ #define EUSERS 87 /* Too many users */ #define ENOTSOCK 88 /* Socket operation on non-socket */ #define EDESTADDRREQ 89 /* Destination address required */ #define EMSGSIZE 90 /* Message too long */ #define EPROTOTYPE 91 /* Protocol wrong type for socket */ #define ENOPROTOOPT 92 /* Protocol not available */ #define EPROTONOSUPPORT 93 /* Protocol not supported */ #define ESOCKTNOSUPPORT 94 /* Socket type not supported */ #define EOPNOTSUPP 95 /* Operation not supported on transport endpoint */ #define EPFNOSUPPORT 96 /* Protocol family not supported */ #define EAFNOSUPPORT 97 /* Address family not supported by protocol */ #define EADDRINUSE 98 /* Address already in use */ #define EADDRNOTAVAIL 99 /* Cannot assign requested address */ #define ENETDOWN 100 /* Network is down */ #define ENETUNREACH 101 /* Network is unreachable */ #define ENETRESET 102 /* Network dropped connection because of reset */ #define ECONNABORTED 103 /* Software caused connection abort */ #define ECONNRESET 104 /* Connection reset by peer */ #define ENOBUFS 105 /* No buffer space available */ #define EISCONN 106 /* Transport endpoint is already connected */ #define ENOTCONN 107 /* Transport endpoint is not connected */ #define ESHUTDOWN 108 /* Cannot send after transport endpoint shutdown */ #define ETOOMANYREFS 109 /* Too many references: cannot splice */ #define ETIMEDOUT 110 /* Connection timed out */ #define ECONNREFUSED 111 /* Connection refused */ #define EHOSTDOWN 112 /* Host is down */ #define EHOSTUNREACH 113 /* No route to host */ #define EALREADY 114 /* Operation already in progress */ #define EINPROGRESS 115 /* Operation now in progress */ #define ESTALE 116 /* Stale NFS file handle */ #define EUCLEAN 117 /* Structure needs cleaning */ #define ENOTNAM 118 /* Not a XENIX named type file */ #define ENAVAIL 119 /* No XENIX semaphores available */ #define EISNAM 120 /* Is a named type file */ #define EREMOTEIO 121 /* Remote I/O error */ #define EDQUOT 122 /* Quota exceeded */ #define ENOMEDIUM 123 /* No medium found */ #define EMEDIUMTYPE 124 /* Wrong medium type */ #define ENSROK 0 /* DNS server returned answer with no data */ #define ENSRNODATA 160 /* DNS server returned answer with no data */ #define ENSRFORMERR 161 /* DNS server claims query was misformatted */ #define ENSRSERVFAIL 162 /* DNS server returned general failure */ #define ENSRNOTFOUND 163 /* Domain name not found */ #define ENSRNOTIMP 164 /* DNS server does not implement requested operation */ #define ENSRREFUSED 165 /* DNS server refused query */ #define ENSRBADQUERY 166 /* Misformatted DNS query */ #define ENSRBADNAME 167 /* Misformatted domain name */ #define ENSRBADFAMILY 168 /* Unsupported address family */ #define ENSRBADRESP 169 /* Misformatted DNS reply */ #define ENSRCONNREFUSED 170 /* Could not contact DNS servers */ #define ENSRTIMEOUT 171 /* Timeout while contacting DNS servers */ #define ENSROF 172 /* End of file */ #define ENSRFILE 173 /* Error reading file */ #define ENSRNOMEM 174 /* Out of memory */ #define ENSRDESTRUCTION 175 /* Application terminated lookup */ #define ENSRQUERYDOMAINTOOLONG 176 /* Domain name is too long */ #define ENSRCNAMELOOP 177 /* Domain name is too long */ #endif /* defined(__GNUC__)&&!defined(__CC_ARM)||defined(_WIN32) */ /** * Redefine the errno, Only use in framework/app */ #ifdef BUILD_BIN #undef set_errno #define set_errno(err) do { if (err) { errno = (err); } } while(0) #else /* BUILD_BIN */ #ifdef BUILD_APP extern int get_errno(void); extern void set_errno(int err); #undef errno #define errno get_errno() #endif /* BUILD_APP */ #endif /* BUILD_BIN */ #ifdef __cplusplus } #endif #endif /* AMP_ERRNO_H */
YifuLiu/AliOS-Things
components/amp/main/amp_errno.h
C
apache-2.0
9,176
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include "amp_platform.h" #include "amp_defines.h" #include "amp_config.h" #include "aos_system.h" #include "aos_network.h" #ifdef AMP_KV_ENABLE #include "aos/kv.h" #endif #include "aos_fs.h" #include "amp_boot_recovery.h" #include "amp_boot.h" #ifdef JSE_ADVANCED_ADDON_UI #include "render_public.h" #include "../../../../littlevgl/lv_conf.h" #include "view_model.h" extern volatile int app_run_flag; volatile int g_ui_run_flag = 1; #endif #define MOD_STR "AMP_MAIN" extern void jsengine_main(void); extern int aos_network_status_registercb(void (*cb)(int status, void *), void *arg); #ifdef AMP_NETWORK_ENABLE void network_func(void *argv) { aos_network_status_registercb(NULL, NULL); while(!aos_get_network_status()) { aos_msleep(1000); } app_management_center_init(); aos_task_exit(0); return; } #endif void jsengine_func(void *argv) { jsengine_main(); aos_task_exit(0); return; } int amp_main(void) { int ret = -1; /* add memory init */ amp_memory_init(); /* system init */ aos_system_init(); /* printf amp system info */ aos_printf("=================amp info=================\r\n"); aos_printf("amp version: amp-v%s-%s\r\n", AMP_VERSION_NUMBER, AMP_GIT_COMMIT); aos_printf("amp build time: %s, %s\r\n", __DATE__, __TIME__); aos_printf("amp device name: %s\r\n", aos_get_device_name()); aos_printf("==========================================\r\n"); /* system init */ aos_system_init(); /* file system init */ aos_fs_init(); /* ulog module init */ ulog_init(); /* set ulog level, make all the level of log is not lower than this value could be logged */ aos_set_log_level(AOS_LL_ERROR); #ifndef HAASUI_AMP_BUILD /* amp recovery service init */ amp_boot_main(); aos_task_t jsengine_task; #ifdef AMP_NETWORK_ENABLE aos_task_t network_task; #endif #ifdef AMP_KV_ENABLE ret = kv_init(); if (ret != 0) { amp_warn(MOD_STR, "kv init failed!"); } #endif /* amp main start */ ret = aos_task_new_ext(&jsengine_task, "amp_jsengine", jsengine_func, NULL, 1024 * 8, AOS_DEFAULT_APP_PRI); if (ret != 0) { amp_debug(MOD_STR, "jsengine task creat failed!"); return ret; } #ifdef AMP_NETWORK_ENABLE /* network start */ ret = aos_task_new_ext(&network_task, "amp_network", network_func, NULL, 1024 * 4, AOS_DEFAULT_APP_PRI); if (ret != 0) { amp_debug(MOD_STR, "network task creat failed!"); return ret; } #endif #ifdef JSE_ADVANCED_ADDON_UI while(!app_run_flag){ aos_msleep(50); } if (g_ui_run_flag) { amp_view_model_init(); render_init(); } #endif while(1) { aos_msleep(5000); } #else /* HAASUI_AMP_BUILD defined */ ret = kv_init(); if (ret != 0) { amp_warn(MOD_STR, "kv init failed!"); } jsengine_main(); #endif return 0; } int amp_sysdep_init(void) { return amp_main(); }
YifuLiu/AliOS-Things
components/amp/main/amp_main.c
C
apache-2.0
3,063
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include "amp_platform.h" #include "amp_defines.h" #include "amp_config.h" #include "aos_system.h" #include "amp_task.h" #include "amp_list.h" #define MOD_STR "AMP_TASK" #define AMP_MSGQ_WAITIME (2000) #define AMP_MSGQ_MAX_NUM 128 typedef struct { dlist_t node; void (*callback)(void); } amp_source_node_t; static dlist_t g_sources_list = AMP_DLIST_HEAD_INIT(g_sources_list); static aos_queue_t amp_task_mq = NULL; /* JSEngine message queue */ static aos_mutex_t amp_task_mutex = NULL; /* JSEngine mutex */ static void (*g_task_msg_notify)(int (*msg_handler)(void)); void amp_module_free(void) { amp_source_node_t *source_node; dlist_t *temp; dlist_for_each_entry_safe(&g_sources_list, temp, source_node, amp_source_node_t, node) { source_node->callback(); dlist_del(&source_node->node); amp_free(source_node); } } int32_t amp_module_free_register(void (*callback)(void)) { amp_source_node_t *source_node; if (!callback) { return -1; } source_node = amp_malloc(sizeof(amp_source_node_t)); if (!source_node) { return -1; } source_node->callback = callback; dlist_add_tail(&source_node->node, &g_sources_list); return 0; } int32_t amp_task_yield(uint32_t timeout) { int32_t ret = 0; size_t revsize; amp_task_msg_t amp_msg; memset(&amp_msg, 0, sizeof(amp_msg)); amp_msg.type = AMP_TASK_MSG_TYPE_MAX; if ((ret = aos_queue_recv(&amp_task_mq, timeout, &amp_msg, &revsize)) != 0) { return -1; } if (amp_msg.type == AMP_TASK_MSG_CALLBACK) { amp_msg.callback(amp_msg.param); } else if (amp_msg.type == AMP_TASK_MSG_EXIT) { return 1; } return 0; } static int amp_task_yield_nowait(void) { return amp_task_yield(0); } static void amp_task_timer_cb_handler(void *timer, void *arg) { amp_task_msg_t *p_amp_msg = (amp_task_msg_t *)arg; if (amp_task_mq == NULL) { return; } aos_queue_send(&amp_task_mq, p_amp_msg, sizeof(amp_task_msg_t)); } aos_timer_t *amp_task_timer_action(uint32_t ms, amp_engine_call_t action, void *arg, amp_timer_type_t type, void **timer_msg) { int ret = -1; aos_timer_t *timer_id = (aos_timer_t *)amp_malloc(sizeof(aos_timer_t)); if (timer_id == NULL) { return NULL; } amp_task_msg_t *p_param = (amp_task_msg_t *)amp_calloc(1, sizeof(amp_task_msg_t)); if (!p_param) return NULL; *timer_msg = p_param; if (amp_task_mq == NULL) { goto fail; } p_param->callback = action; p_param->param = arg; p_param->type = AMP_TASK_MSG_CALLBACK; if (type == AMP_TIMER_REPEAT) { ret = aos_timer_create(timer_id, amp_task_timer_cb_handler, p_param, ms, AOS_TIMER_REPEAT); } else if (type == AMP_TIMER_ONCE) { ret = aos_timer_create(timer_id, amp_task_timer_cb_handler, p_param, ms, 0); } else { goto fail; } if (ret != 0) goto fail; ret = aos_timer_start(timer_id); if (ret) { aos_timer_free(timer_id); goto fail; } return timer_id; fail: amp_free(p_param); amp_free(timer_id); return NULL; } int32_t amp_task_schedule_call(amp_engine_call_t call, void *arg) { int ret = 0; amp_task_msg_t msg_buf; amp_task_msg_t *p_param = &msg_buf; if (amp_task_mq == NULL) { return -1; } p_param->callback = call; p_param->param = arg; p_param->type = AMP_TASK_MSG_CALLBACK; if (amp_task_mq == NULL) { amp_warn(MOD_STR, "amp_task_mq has not been initlized"); return -1; } ret = aos_queue_send(&amp_task_mq, p_param, sizeof(amp_task_msg_t)); #ifdef HAASUI_AMP_BUILD if (g_task_msg_notify) g_task_msg_notify(amp_task_yield_nowait); #endif return ret; } void amp_task_msg_register(void (*msg_notify)(int (*msg_handler)(void))) { g_task_msg_notify = msg_notify; } int32_t amp_task_exit_call(amp_engine_call_t call, void *arg) { amp_task_msg_t msg_buf; amp_task_msg_t *p_param = &msg_buf; memset(p_param, 0, sizeof(amp_task_msg_t)); p_param->callback = call; p_param->param = arg; p_param->type = AMP_TASK_MSG_EXIT; if (amp_task_mq == NULL) { amp_warn(MOD_STR, "amp_task_mq has not been initlized"); return -1; } aos_mutex_lock(&amp_task_mutex, AOS_WAIT_FOREVER); aos_queue_send(&amp_task_mq, p_param, sizeof(amp_task_msg_t)); aos_mutex_unlock(&amp_task_mutex); return 0; } int32_t amp_task_init() { if (amp_task_mq != NULL) { return 0; } if (aos_queue_new(&amp_task_mq, NULL, AMP_MSGQ_MAX_NUM * sizeof(amp_task_msg_t), sizeof(amp_task_msg_t)) != 0) { amp_error(MOD_STR, "create messageQ error"); return -1; } if (aos_mutex_new(&amp_task_mutex) != 0) { amp_error(MOD_STR, "create mutex error"); return -1; } amp_debug(MOD_STR, "jsengine task init"); return 0; } int32_t amp_task_deinit() { if (amp_task_mq != NULL) { aos_queue_free(&amp_task_mq); amp_task_mq = NULL; } if (amp_task_mutex != NULL) { aos_mutex_free(&amp_task_mutex); amp_task_mutex = NULL; } /* free all jsengine heap */ jsengine_exit(); amp_debug(MOD_STR, "jsengine task free"); return 0; }
YifuLiu/AliOS-Things
components/amp/main/amp_task.c
C
apache-2.0
5,464
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #ifndef AMP_TASK_H #define AMP_TASK_H #include <aos/kernel.h> #include <stdint.h> typedef void (*amp_engine_call_t)(void *data); typedef enum { AMP_TASK_MSG_CALLBACK = 0, /* default JSE callback */ AMP_TASK_MSG_EXIT = 1, AMP_TASK_MSG_TYPE_MAX } amp_task_msg_type_t; typedef enum { AMP_TIMER_ONCE = 0, /* one shot timer */ AMP_TIMER_REPEAT /* repeat timer */ } amp_timer_type_t; typedef struct { amp_task_msg_type_t type; amp_engine_call_t callback; void *param; } amp_task_msg_t; int32_t amp_task_schedule_call(amp_engine_call_t call, void *arg); /** * * JSEngine task initialization * */ int32_t amp_task_init(void); /** * JSEngine yield task, for asynchronous event process * */ int32_t amp_task_yield(uint32_t timeout); aos_timer_t *amp_task_timer_action(uint32_t ms, amp_engine_call_t action, void *arg, amp_timer_type_t type, void **timer_msg); int32_t amp_task_exit_call(amp_engine_call_t call, void *arg); void amp_module_free(void); int32_t amp_module_free_register(void (*callback)(void)); void amp_task_main(); int32_t amp_task_deinit(); #endif /* AMP_TASK_H */
YifuLiu/AliOS-Things
components/amp/main/amp_task.h
C
apache-2.0
1,225
// The driver for DS18B20 chip, it is a temperature sensor. // Require libjs/lib/onewire.js module. var onewire = require('onewire'); var DS18B20Dev; var start_flag = 0; /* Init DS18B20 * * GPIO's options are configured in app.json. Specify the ID, e.g. GPIO below to init DS18B20. { "version": "1.0.0", "io": { "DS18B20": { "type": "GPIO", "port": 4, "dir": "output", "pull": "pullup" } }, "debugLevel": "DEBUG" } */ function init(gpioid) { DS18B20Dev = onewire.open({id: gpioid}); } // Get temperature function getTemperature() { var TL, TH; var tem; /* { DS18B20Dev.setspeed(1); start_flag = 1; } DS18B20Dev.reset(); DS18B20Dev.writeByte(0x55);*/ if(1) { if(!start_flag) { DS18B20Dev.setspeed(1); DS18B20Dev.reset(); DS18B20Dev.writeByte(0xcc); DS18B20Dev.writeByte(0x44); start_flag = 1; } DS18B20Dev.reset(); DS18B20Dev.writeByte(0xcc); DS18B20Dev.writeByte(0xbe); TL = DS18B20Dev.readByte(); /* LSB first */ TH = DS18B20Dev.readByte(); if (TH > 7) { TH =~ TH; TL =~ TL; tem = TH; tem <<= 8; tem += TL; tem = (tem * 0.0625 * 10 + 0.5); return -tem; } else { tem = TH; tem <<= 8; tem += TL; tem = (tem * 0.0625 * 10 + 0.5); return tem; } } } // De-init Si7006 function deinit() { DS18B20Dev.close(); } module.exports = { init, getTemperature, deinit }
YifuLiu/AliOS-Things
components/amp/modules/DS18B20.js
JavaScript
apache-2.0
1,792
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ /* The driver for AP3216C chip, The AP3216C is an integrated ALS & PS module that includes a digital ambient light sensor [ALS], a proximity sensor [PS], and an IR LED in a single package. */ /* 添加如下配置到app.json中: "ap3216c": { "type": "I2C", "port": 1, "addrWidth": 7, "freq": 100000, "mode": "master", "devAddr": 30 } */ // Require libjs/lib/i2c.js module. const AP3216C_I2C_PORT = 1 const AP3216C_ADDR = 0x1e // System Register const AP3216C_SYS_CONFIGURATION_REG = 0x00 const AP3216C_SYS_INT_STATUS_REG = 0x01 const AP3216C_SYS_INT_CLEAR_MANNER_REG = 0x02 const AP3216C_IR_DATA_L_REG = 0x0A const AP3216C_IR_DATA_H_REG = 0x0B const AP3216C_ALS_DATA_L_REG = 0x0C const AP3216C_ALS_DATA_H_REG = 0x0D const AP3216C_PS_DATA_L_REG = 0x0E const AP3216C_PS_DATA_H_REG = 0x0F // ALS Register const AP3216C_ALS_CONFIGURATION_REG = 0x10 const AP3216C_ALS_CALIBRATION_REG = 0x19 const AP3216C_ALS_THRESHOLD_LOW_L_REG = 0x1A const AP3216C_ALS_THRESHOLD_LOW_H_REG = 0x1B const AP3216C_ALS_THRESHOLD_HIGH_L_REG = 0x1C const AP3216C_ALS_THRESHOLD_HIGH_H_REG = 0x1D // PS Register const AP3216C_PS_CONFIGURATION_REG = 0x20 const AP3216C_PS_LED_DRIVER_REG = 0x21 const AP3216C_PS_INT_FORM_REG = 0x22 const AP3216C_PS_MEAN_TIME_REG = 0x23 const AP3216C_PS_LED_WAITING_TIME_REG = 0x24 const AP3216C_PS_CALIBRATION_L_REG = 0x28 const AP3216C_PS_CALIBRATION_H_REG = 0x29 const AP3216C_PS_THRESHOLD_LOW_L_REG = 0x2A const AP3216C_PS_THRESHOLD_LOW_H_REG = 0x2B const AP3216C_PS_THRESHOLD_HIGH_L_REG = 0x2C const AP3216C_PS_THRESHOLD_HIGH_H_REG = 0x2D //mode value const AP3216C_MODE_POWER_DOWN = 0x0 const AP3216C_MODE_ALS = 0x1 const AP3216C_MODE_PS = 0x2 const AP3216C_MODE_ALS_AND_PS = 0x3 const AP3216C_MODE_SW_RESET = 0x4 const AP3216C_MODE_ALS_ONCE = 0x5 const AP3216C_MODE_PS_ONCE = 0x6 const AP3216C_MODE_ALS_AND_PS_ONCE = 0x7 //ap3216c_int_clear_manner const AP3216C_INT_CLEAR_MANNER_BY_READING = 0x0 const AP3216C_ALS_CLEAR_MANNER_BY_SOFTWARE = 0x1 //als_range const AP3216C_ALS_RANGE_20661 = 0x0 const AP3216C_ALS_RANGE_5162 = 0x1 const AP3216C_ALS_RANGE_1291 = 0x2 const AP3216C_ALS_RANGE_323 = 0x3 //als_range const AP3216C_PS_GAIN1 = 0x0 const AP3216C_PS_GAIN2 = 0x1 const AP3216C_PS_GAIN4 = 0x2 const AP3216C_PS_GAIN8 = 0x3 const AP3216C_SYSTEM_MODE = 0x0 const AP3216C_INT_PARAM = 0x1 const AP3216C_ALS_RANGE = 0x2 const AP3216C_ALS_PERSIST = 0x3 const AP3216C_ALS_CALIBRATION = 0x4 const AP3216C_ALS_LOW_THRESHOLD_L = 0x5 const AP3216C_ALS_LOW_THRESHOLD_H = 0x6 const AP3216C_ALS_HIGH_THRESHOLD_L = 0x7 const AP3216C_ALS_HIGH_THRESHOLD_H = 0x8 const AP3216C_PS_INTEGRATED_TIME = 0x9 const AP3216C_PS_GAIN = 0xa const AP3216C_PS_PERSIST = 0xb const AP3216C_PS_LED_CONTROL = 0xc const AP3216C_PS_LED_DRIVER_RATIO = 0xd const AP3216C_PS_INT_MODE = 0xe const AP3216C_PS_MEAN_TIME = 0xf const AP3216C_PS_WAITING_TIME = 0x10 const AP3216C_PS_CALIBRATION_L = 0x11 const AP3216C_PS_CALIBRATION_H = 0x12 const AP3216C_PS_LOW_THRESHOLD_L = 0x13 const AP3216C_PS_LOW_THRESHOLD_H = 0x14 const AP3216C_PS_HIGH_THRESHOLD_L = 0x15 const AP3216C_PS_HIGH_THRESHOLD_H = 0x16 var i2c = require('i2c'); var ap3216cDev; function fakeSleep(ms) { var date = new Date(); var curDate; do { curDate = new Date(); } while((curDate - date) < ms); } /* 写寄存器的值 */ function write_reg(addr, data) { var msgbuf = [data]; ap3216cDev.writeMem(addr, msgbuf); console.log("--> write addr " + addr + ", value = " + msgbuf); } /* 读寄存器的值 */ function read_regs(addr, len) { buf = ap3216cDev.readMem(addr, len); console.log("--> read addr " + addr + ", value = " + buf); return buf; } /* 软件复位传感器 */ function reset_sensor() { write_reg(AP3216C_SYS_CONFIGURATION_REG, AP3216C_MODE_SW_RESET); // reset } /** * This function is convenient to getting data except including high and low * data for this sensor. note:after reading lower register first,reading higher * add one. */ function read_low_and_high(reg, len) { var data; var buf0; var buf1; buf0 = read_regs(reg, len); // 读低字节 buf1 = read_regs(reg + 1, len); // 读高字节 data = buf0 | (buf1 << len * 8); // 合并数据 data = data >>> 0 return data; } /** * This function reads status register by ap3216c sensor measurement * * @param no * * @return status register value. */ function ap3216c_get_IntStatus() { var IntStatus; /* 读中断状态寄存器 */ IntStatus = read_regs(AP3216C_SYS_INT_STATUS_REG, 1); // IntStatus 第 0 位表示 ALS 中断,第 1 位表示 PS 中断。 return IntStatus; // 返回状态 } function ap3216c_int_init() { ; } /** * @brief 配置 中断输入引脚 * @param 无 * @retval 无 */ function ap3216c_int_Config() { ; } /** * This function initializes ap3216c registered device driver * * @param no * * @return the ap3216c device. */ function init(i2cid) { ap3216cDev = i2c.open({id: i2cid}); fakeSleep(30); /* reset ap3216c */ reset_sensor(); fakeSleep(100); ap3216c_set_param(AP3216C_SYSTEM_MODE, AP3216C_MODE_ALS_AND_PS); fakeSleep(150); // delay at least 112.5ms ap3216c_int_Config(); ap3216c_int_init(); } function ap3216c_deinit() { ap3216cDev.close(); } /** * This function reads light by ap3216c sensor measurement * * @param no * * @return the ambient light converted to float data. */ function ap3216c_read_ambient_light() { var brightness; // default error data var read_data; var range; read_data = read_low_and_high(AP3216C_ALS_DATA_L_REG, 1); range = ap3216c_get_param(AP3216C_ALS_RANGE); //console.log("ap3216c_read_ambient_light read_data is " , read_data, range); if (range == AP3216C_ALS_RANGE_20661) { brightness = 0.35 * read_data; // sensor ambient light converse to reality } else if (range == AP3216C_ALS_RANGE_5162) { brightness = 0.0788 * read_data; // sensor ambient light converse to reality } else if (range == AP3216C_ALS_RANGE_1291) { brightness = 0.0197 * read_data; // sensor ambient light converse to reality } else if (range == AP3216C_ALS_RANGE_323) { brightness = 0.0049 * read_data; // sensor ambient light converse to reality } return brightness; } /** * This function reads proximity by ap3216c sensor measurement * * @param no * * @return the proximity data. */ function ap3216c_read_ps_data() { var proximity = 0; var read_data; read_data = read_low_and_high(AP3216C_PS_DATA_L_REG, 1); // read two data //console.log("ap3216c_read_ps_data read_data is " , read_data); if (1 == ((read_data >> 6) & 0x01 || (read_data >> 14) & 0x01)) { return proximity = 55555; // 红外过高(IR),PS无效 返回一个 55555 的无效数据 } proximity = (read_data & 0x000f) + (((read_data >> 8) & 0x3f) << 4); // sensor proximity converse to reality proximity = proximity >>> 0 proximity |= read_data & 0x8000; // 取最高位,0 表示物体远离,1 表示物体靠近 return proximity; // proximity 后十位是数据位,最高位为状态位 } /** * This function reads ir by ap3216c sensor measurement * * @param no * * @return the ir data. */ function ap3216c_read_ir_data() { var proximity = 0; var read_data; read_data = read_low_and_high(AP3216C_IR_DATA_L_REG, 1); // read two data //console.log("ap3216c_read_ir_data read_data is" , read_data); proximity = (read_data & 0x0003) + ((read_data >> 8) & 0xFF); // sensor proximity converse to reality proximity = proximity >>> 0 return proximity; } /** * This function sets parameter of ap3216c sensor * * @param cmd the parameter cmd of device * @param value for setting value in cmd register * * @return the setting parameter status,RT_EOK reprensents setting successfully. */ function ap3216c_set_param(cmd, value) { switch (cmd) { case AP3216C_SYSTEM_MODE: { /* default 000,power down */ write_reg(AP3216C_SYS_CONFIGURATION_REG, value); break; } case AP3216C_INT_PARAM: { write_reg(AP3216C_SYS_INT_CLEAR_MANNER_REG, value); break; } case AP3216C_ALS_RANGE: { var args = read_regs(AP3216C_ALS_CONFIGURATION_REG, 1); args &= 0xcf; args |= value << 4; write_reg(AP3216C_ALS_CONFIGURATION_REG, args); break; } case AP3216C_ALS_PERSIST: { var args = read_regs(AP3216C_ALS_CONFIGURATION_REG, 1); args &= 0xf0; args |= value; write_reg(AP3216C_ALS_CONFIGURATION_REG, args); break; } case AP3216C_ALS_LOW_THRESHOLD_L: { write_reg(AP3216C_ALS_THRESHOLD_LOW_L_REG, value); break; } case AP3216C_ALS_LOW_THRESHOLD_H: { write_reg(AP3216C_ALS_THRESHOLD_LOW_H_REG, value); break; } case AP3216C_ALS_HIGH_THRESHOLD_L: { write_reg(AP3216C_ALS_THRESHOLD_HIGH_L_REG, value); break; } case AP3216C_ALS_HIGH_THRESHOLD_H: { write_reg(AP3216C_ALS_THRESHOLD_HIGH_H_REG, value); break; } case AP3216C_PS_GAIN: { var args = read_regs(AP3216C_PS_CONFIGURATION_REG, 1); args &= 0xf3; args |= value; write_reg(AP3216C_PS_CONFIGURATION_REG, args); break; } case AP3216C_PS_PERSIST: { var args = read_regs(AP3216C_PS_CONFIGURATION_REG, 1); args &= 0xfc; args |= value; write_reg(AP3216C_PS_CONFIGURATION_REG, args); break; } case AP3216C_PS_LOW_THRESHOLD_L: { write_reg(AP3216C_PS_THRESHOLD_LOW_L_REG, value); break; } case AP3216C_PS_LOW_THRESHOLD_H: { write_reg(AP3216C_PS_THRESHOLD_LOW_H_REG, value); break; } case AP3216C_PS_HIGH_THRESHOLD_L: { write_reg(AP3216C_PS_THRESHOLD_HIGH_L_REG, value); break; } case AP3216C_PS_HIGH_THRESHOLD_H: { write_reg(AP3216C_PS_THRESHOLD_HIGH_H_REG, value); break; } default: { } } } /** * This function gets parameter of ap3216c sensor * * @param cmd the parameter cmd of device * @param value to get value in cmd register * * @return the getting parameter status,RT_EOK reprensents getting successfully. */ function ap3216c_get_param(cmd) { switch (cmd) { case AP3216C_SYSTEM_MODE: { value = read_regs(AP3216C_SYS_CONFIGURATION_REG, 1); break; } case AP3216C_INT_PARAM: { value = read_regs(AP3216C_SYS_INT_CLEAR_MANNER_REG, 1); break; } case AP3216C_ALS_RANGE: { var value = read_regs(AP3216C_ALS_CONFIGURATION_REG, 1); temp = (value & 0xff) >> 4; value = temp; break; } case AP3216C_ALS_PERSIST: { var temp = read_regs(AP3216C_ALS_CONFIGURATION_REG, 1); temp = value & 0x0f; value = temp; break; } case AP3216C_ALS_LOW_THRESHOLD_L: { value = read_regs(AP3216C_ALS_THRESHOLD_LOW_L_REG, 1); break; } case AP3216C_ALS_LOW_THRESHOLD_H: { value = read_regs(AP3216C_ALS_THRESHOLD_LOW_H_REG, 1); break; } case AP3216C_ALS_HIGH_THRESHOLD_L: { value = read_regs(AP3216C_ALS_THRESHOLD_HIGH_L_REG, 1); break; } case AP3216C_ALS_HIGH_THRESHOLD_H: { value = read_regs(AP3216C_ALS_THRESHOLD_HIGH_H_REG, 1); break; } case AP3216C_PS_GAIN: { var temp = read_regs(AP3216C_PS_CONFIGURATION_REG, 1); value = (temp & 0xc) >> 2; break; } case AP3216C_PS_PERSIST: { var temp = read_regs(AP3216C_PS_CONFIGURATION_REG, 1); value = temp & 0x3; break; } case AP3216C_PS_LOW_THRESHOLD_L: { value = read_regs(AP3216C_PS_THRESHOLD_LOW_L_REG, 1); break; } case AP3216C_PS_LOW_THRESHOLD_H: { value = read_regs(AP3216C_PS_THRESHOLD_LOW_H_REG, 1); break; } case AP3216C_PS_HIGH_THRESHOLD_L: { value = read_regs(AP3216C_PS_THRESHOLD_HIGH_L_REG, 1); break; } case AP3216C_PS_HIGH_THRESHOLD_H: { value = read_regs(AP3216C_PS_THRESHOLD_HIGH_H_REG, 1); break; } default: { } } return value; } // 初始化MPU6050 // 返回值:0,成功 // 其他,错误代码 function init(i2cid) { ap3216cDev = i2c.open({id: i2cid}); fakeSleep(100); /* reset ap3216c */ reset_sensor(); fakeSleep(100); ap3216c_set_param(AP3216C_SYSTEM_MODE, AP3216C_MODE_ALS_AND_PS); fakeSleep(150); // delay at least 112.5ms ap3216c_int_Config(); ap3216c_int_init(); } // De-init qlc5883 function deinit() { ap3216cDev.close(); } module.exports = { init, deinit, ap3216c_read_ambient_light, ap3216c_read_ps_data, ap3216c_read_ir_data, deinit, }
YifuLiu/AliOS-Things
components/amp/modules/ap3216c.js
JavaScript
apache-2.0
14,703
// The driver for mpu6050 chip, it is a temperature and humidity sensor. /* 添加如下配置到app.json中: "mpu6050": { "type": "I2C", "port": 1, "addrWidth": 7, "freq": 100000, "mode": "master", "devAddr": 105 } */ // Require libjs/lib/i2c.js module. const MPU_SELF_TESTX_REG = 0X0D // 自检寄存器X const MPU_SELF_TESTY_REG = 0X0E // 自检寄存器Y const MPU_SELF_TESTZ_REG = 0X0F // 自检寄存器Z const MPU_SELF_TESTA_REG = 0X10 // 自检寄存器A const MPU_SAMPLE_RATE_REG = 0X19 // 采样频率分频器 const MPU_CFG_REG = 0X1A // 配置寄存器 const MPU_GYRO_CFG_REG = 0X1B // 陀螺仪配置寄存器 const MPU_ACCEL_CFG_REG = 0X1C // 加速度计配置寄存器 const MPU_MOTION_DET_REG = 0X1F // 运动检测阀值设置寄存器 const MPU_FIFO_EN_REG = 0X23 // FIFO使能寄存器 const MPU_I2CMST_CTRL_REG = 0X24 // IIC主机控制寄存器 const MPU_I2CSLV0_ADDR_REG = 0X25 // IIC从机0器件地址寄存器 const MPU_I2CSLV0_REG = 0X26 // IIC从机0数据地址寄存器 const MPU_I2CSLV0_CTRL_REG = 0X27 // IIC从机0控制寄存器 const MPU_I2CSLV1_ADDR_REG = 0X28 // IIC从机1器件地址寄存器 const MPU_I2CSLV1_REG = 0X29 // IIC从机1数据地址寄存器 const MPU_I2CSLV1_CTRL_REG = 0X2A // IIC从机1控制寄存器 const MPU_I2CSLV2_ADDR_REG = 0X2B // IIC从机2器件地址寄存器 const MPU_I2CSLV2_REG = 0X2C // IIC从机2数据地址寄存器 const MPU_I2CSLV2_CTRL_REG = 0X2D // IIC从机2控制寄存器 const MPU_I2CSLV3_ADDR_REG = 0X2E // IIC从机3器件地址寄存器 const MPU_I2CSLV3_REG = 0X2F // IIC从机3数据地址寄存器 const MPU_I2CSLV3_CTRL_REG = 0X30 // IIC从机3控制寄存器 const MPU_I2CSLV4_ADDR_REG = 0X31 // IIC从机4器件地址寄存器 const MPU_I2CSLV4_REG = 0X32 // IIC从机4数据地址寄存器 const MPU_I2CSLV4_DO_REG = 0X33 // IIC从机4写数据寄存器 const MPU_I2CSLV4_CTRL_REG = 0X34 // IIC从机4控制寄存器 const MPU_I2CSLV4_DI_REG = 0X35 // IIC从机4读数据寄存器 const MPU_I2CMST_STA_REG = 0X36 // IIC主机状态寄存器 const MPU_INTBP_CFG_REG = 0X37 // 中断/旁路设置寄存器 const MPU_INT_EN_REG = 0X38 // 中断使能寄存器 const MPU_INT_STA_REG = 0X3A // 中断状态寄存器 const MPU_ACCEL_XOUTH_REG = 0X3B // 加速度值,X轴高8位寄存器 const MPU_ACCEL_XOUTL_REG = 0X3C // 加速度值,X轴低8位寄存器 const MPU_ACCEL_YOUTH_REG = 0X3D // 加速度值,Y轴高8位寄存器 const MPU_ACCEL_YOUTL_REG = 0X3E // 加速度值,Y轴低8位寄存器 const MPU_ACCEL_ZOUTH_REG = 0X3F // 加速度值,Z轴高8位寄存器 const MPU_ACCEL_ZOUTL_REG = 0X40 // 加速度值,Z轴低8位寄存器 const MPU_TEMP_OUTH_REG = 0X41 // 温度值高八位寄存器 const MPU_TEMP_OUTL_REG = 0X42 // 温度值低8位寄存器 const MPU_GYRO_XOUTH_REG = 0X43 // 陀螺仪值,X轴高8位寄存器 const MPU_GYRO_XOUTL_REG = 0X44 // 陀螺仪值,X轴低8位寄存器 const MPU_GYRO_YOUTH_REG = 0X45 // 陀螺仪值,Y轴高8位寄存器 const MPU_GYRO_YOUTL_REG = 0X46 // 陀螺仪值,Y轴低8位寄存器 const MPU_GYRO_ZOUTH_REG = 0X47 // 陀螺仪值,Z轴高8位寄存器 const MPU_GYRO_ZOUTL_REG = 0X48 // 陀螺仪值,Z轴低8位寄存器 const MPU_I2CSLV0_DO_REG = 0X63 // IIC从机0数据寄存器 const MPU_I2CSLV1_DO_REG = 0X64 // IIC从机1数据寄存器 const MPU_I2CSLV2_DO_REG = 0X65 // IIC从机2数据寄存器 const MPU_I2CSLV3_DO_REG = 0X66 // IIC从机3数据寄存器 const MPU_I2CMST_DELAY_REG = 0X67 // IIC主机延时管理寄存器 const MPU_SIGPATH_RST_REG = 0X68 // 信号通道复位寄存器 const MPU_MDETECT_CTRL_REG = 0X69 // 运动检测控制寄存器 const MPU_USER_CTRL_REG = 0X6A // 用户控制寄存器 const MPU_PWR_MGMT1_REG = 0X6B // 电源管理寄存器1 const MPU_PWR_MGMT2_REG = 0X6C // 电源管理寄存器2 const MPU_FIFO_CNTH_REG = 0X72 // FIFO计数寄存器高八位 const MPU_FIFO_CNTL_REG = 0X73 // FIFO计数寄存器低八位 const MPU_FIFO_RW_REG = 0X74 // FIFO读写寄存器 const MPU_DEVICE_ID_REG = 0X75 // 器件ID寄存器 // 如果AD0脚(9脚)接地,IIC地址为0X68(不包含最低位). // 如果接V3.3,则IIC地址为0X69(不包含最低位). const MPU_I2C_PORT = 0x1 const MPU_ADDR = 0X69 const MPU_DEV_ID = 0x68 var i2c = require('i2c'); var mpu6050Dev; /* duktape engine doesn't support async/await to sleep. function sleep(ms) { return new Promise(function (resolve, reject) { setTimeout(function () { resolve(); }, ms); }); } */ function fakeSleep(ms) { var date = new Date(); var curDate; do { curDate = new Date(); } while((curDate - date) < ms); } function i2c_eeprom_write_byte(addr, value) { var Reg = [addr, value]; mpu6050Dev.write(Reg); console.log("--> write addr " + addr + ", value = " + Reg); } function i2c_eeprom_read_byte(addr) { var Reg = []; Reg[0] = addr; mpu6050Dev.write(Reg); value = mpu6050Dev.read(1); console.log("<-- read addr " + addr + ", value = " + value); return value; } function i2c_eeprom_write_len(addr, len, data) { var data = []; var reg = [addr]; mpu6050Dev.write(reg); for (i = 0; i < len; i++) { mpu6050Dev.write(data[i]); } console.log("--> write addr " + addr + ", " + len + " bytes value = " + data); } function i2c_eeprom_read_len(addr, len) { var data = []; var reg = [addr]; mpu6050Dev.write(reg); for (i = 0; i < len; i++) { data[i] = mpu6050Dev.read(1); } console.log("--> read addr " + addr + ", " + len + " bytes value = " + data); return data; } // 设置MPU6050陀螺仪传感器满量程范围 // fsr:0,±250dps;1,±500dps;2,±1000dps;3,±2000dps // 返回值:0,设置成功 // 其他,设置失败 function MPU_Set_Gyro_Fsr(fsr) { return i2c_eeprom_write_byte(MPU_GYRO_CFG_REG, fsr << 3); // 设置陀螺仪满量程范围 } // 设置MPU6050加速度传感器满量程范围 // fsr:0,±2g;1,±4g;2,±8g;3,±16g // 返回值:0,设置成功 // 其他,设置失败 function MPU_Set_Accel_Fsr(fsr) { return i2c_eeprom_write_byte(MPU_ACCEL_CFG_REG, fsr << 3); // 设置加速度传感器满量程范围 } // 设置MPU6050的数字低通滤波器 // lpf:数字低通滤波频率(Hz) // 返回值:0,设置成功 // 其他,设置失败 function MPU_Set_LPF(lpf) { var data = 0; if (lpf >= 188) data = 1; else if (lpf >= 98) data = 2; else if (lpf >= 42) data = 3; else if (lpf >= 20) data = 4; else if (lpf >= 10) data = 5; else data = 6; return i2c_eeprom_write_byte(MPU_CFG_REG, data); // 设置数字低通滤波器 } // 设置MPU6050的采样率(假定Fs=1KHz) // rate:4~1000(Hz) // 返回值:0,设置成功 // 其他,设置失败 function MPU_Set_Rate(rate) { var data; if (rate > 1000) rate = 1000; if (rate < 4) rate = 4; data = 1000 / rate - 1; i2c_eeprom_write_byte(MPU_SAMPLE_RATE_REG, data); // 设置数字低通滤波器 return MPU_Set_LPF(rate / 2); // 自动设置LPF为采样率的一半 } // 得到温度值 // 返回值:温度值(扩大了100倍) function get_Temperature() { var buf = []; var raw; var temp; buf = i2c_eeprom_read_len(MPU_TEMP_OUTH_REG, 2); raw = (buf[0] << 8) | buf[1]; if (raw > (1 << 15)) { raw = raw - (1<<16) } temp = 36.53 + (raw) / 340; return temp * 100; } // 得到陀螺仪值(原始值) // gx,gy,gz:陀螺仪x,y,z轴的原始读数(带符号) // 返回值:0,成功 // 其他,错误代码 function get_Gyroscope(gx, gy, gz) { var buf = []; var arr = []; buf = i2c_eeprom_read_len(MPU_GYRO_XOUTH_REG, 6); gx = (buf[0] << 8) | buf[1]; gy = (buf[2] << 8) | buf[3]; gz = (buf[4] << 8) | buf[5]; if (gx > (1 << 15)) { gx = gx - (1<<16) } if (gy > (1 << 15)) { gy = gy - (1<<16) } if (gz > (1 << 15)) { gz = gz - (1<<16) } arr[0] = gx; arr[1] = gy; arr[2] = gz; return arr; } // 得到加速度值(原始值) // gx,gy,gz:陀螺仪x,y,z轴的原始读数(带符号) // 返回值:0,成功 // 其他,错误代码 function get_Accelerometer(ax, ay, az) { var buf = []; var arr = []; buf = i2c_eeprom_read_len(MPU_ACCEL_XOUTH_REG, 6); ax = (buf[0] << 8) | buf[1]; ay = (buf[2] << 8) | buf[3]; az = (buf[4] << 8) | buf[5]; if (ax > (1 << 15)) { ax = ax - (1<<16) } if (ay > (1 << 15)) { ay = ay - (1<<16) } if (az > (1 << 15)) { az = az - (1<<16) } arr[0] = ax; arr[1] = ay; arr[2] = az; return arr; } // 初始化MPU6050 // 返回值:0,成功 // 其他,错误代码 function init(i2cid) { var device_id = 0; mpu6050Dev = i2c.open({id: i2cid}); fakeSleep(30); i2c_eeprom_write_byte(MPU_PWR_MGMT1_REG, 0X80); // 复位MPU6050 fakeSleep(200); i2c_eeprom_write_byte(MPU_PWR_MGMT1_REG, 0X00); // 唤醒MPU6050 MPU_Set_Gyro_Fsr(3); // 陀螺仪传感器,±2000dps MPU_Set_Accel_Fsr(0); // 加速度传感器,±2g MPU_Set_Rate(50); // 设置采样率50Hz i2c_eeprom_write_byte(MPU_INT_EN_REG, 0X00); // 关闭所有中断 i2c_eeprom_write_byte(MPU_USER_CTRL_REG, 0X00); // I2C主模式关闭 i2c_eeprom_write_byte(MPU_FIFO_EN_REG, 0X00); // 关闭FIFO i2c_eeprom_write_byte(MPU_INTBP_CFG_REG, 0X80); // INT引脚低电平有效 device_id = i2c_eeprom_read_byte(MPU_DEVICE_ID_REG); if (device_id == MPU_DEV_ID) { // 器件ID正确 i2c_eeprom_write_byte(MPU_PWR_MGMT1_REG, 0X01); // 设置CLKSEL,PLL X轴为参考 i2c_eeprom_write_byte(MPU_PWR_MGMT2_REG, 0X00); // 加速度与陀螺仪都工作 MPU_Set_Rate(50); // 设置采样率为50Hz } else { return 1; } return 0; } // De-init qlc5883 function deinit() { mpu6050Dev.close(); } module.exports = { init, deinit, get_Temperature, get_Gyroscope, get_Accelerometer, deinit, }
YifuLiu/AliOS-Things
components/amp/modules/mpu6050.js
JavaScript
apache-2.0
10,243
// The driver for qlc5883 chip, it is a temperature and humidity sensor. var x_max, x_min, z_min, y_max, y_min, z_max; var addr; var mode; var rate; var range; var oversampling; var INT16_MIN = (-32767-1) var INT16_MAX = 32767 /* Register numbers */ var QMC5883L_X_LSB = 0 var QMC5883L_X_MSB = 1 var QMC5883L_Y_LSB = 2 var QMC5883L_Y_MSB = 3 var QMC5883L_Z_LSB = 4 var QMC5883L_Z_MSB = 5 var QMC5883L_STATUS = 6 var QMC5883L_TEMP_LSB = 7 var QMC5883L_TEMP_MSB = 8 var QMC5883L_CONFIG = 9 var QMC5883L_CONFIG2 = 10 var QMC5883L_RESET = 11 var QMC5883L_RESERVED = 12 var QMC5883L_CHIP_ID = 13 /* Bit values for the STATUS register */ var QMC5883L_STATUS_DRDY = 1 var QMC5883L_STATUS_OVL = 2 var QMC5883L_STATUS_DOR = 4 /* Oversampling values for the CONFIG register */ var QMC5883L_CONFIG_OS512 = 0b00000000 var QMC5883L_CONFIG_OS256 = 0b01000000 var QMC5883L_CONFIG_OS128 = 0b10000000 var QMC5883L_CONFIG_OS64 = 0b11000000 /* Range values for the CONFIG register */ var QMC5883L_CONFIG_2GAUSS = 0b00000000 var QMC5883L_CONFIG_8GAUSS = 0b00010000 /* Rate values for the CONFIG register */ var QMC5883L_CONFIG_10HZ = 0b00000000 var QMC5883L_CONFIG_50HZ = 0b00000100 var QMC5883L_CONFIG_100HZ = 0b00001000 var QMC5883L_CONFIG_200HZ = 0b00001100 /* Mode values for the CONFIG register */ var QMC5883L_CONFIG_STANDBY = 0b00000000 var QMC5883L_CONFIG_CONT = 0b00000001 /* Apparently M_PI isn't available in all environments. */ var M_PI = 3.14159265358979323846264338327950288 /* 添加如下配置到app.json中: "qlc5883": { "type": "I2C", "port": 1, "addrWidth": 7, "freq": 400000, "mode": "master", "devAddr": 13 } */ // Require libjs/lib/i2c.js module. var i2c = require('i2c'); var qlc5883Dev; /* duktape engine doesn't support async/await to sleep. function sleep(ms) { return new Promise(function (resolve, reject) { setTimeout(function () { resolve(); }, ms); }); } */ function fakeSleep(ms) { var date = new Date(); var curDate; do { curDate = new Date(); } while((curDate - date) < ms); } /* Init qlc5883 * * I2C's options are configured in app.json. Specify the ID, e.g. I2C0 below to init qlc5883. * "I2C0": { * "type": "I2C", * "port": 1, * "addrWidth": 7, * "freq": 400000, * "mode": "master", * "devAddr": 13 * } */ var QMC5883L_ADDR = 0x0D; function i2c_eeprom_read_var(chipAddress, addr){ return devRegReadWrite1Byte(0, addr, 0); } function devRegRead1Byte(addr) { var Reg = []; Reg[0] = addr qlc5883Dev.write(Reg); value = qlc5883Dev.read(1); console.log("<-- read addr " + addr + ", value = " + value); return value; } function devRegWrite1Byte(data) { var Reg = []; Reg[0] = data; qlc5883Dev.write(Reg); console.log("--> write addr " + addr + ", value = " + Reg); } function devRegReadNByte(addr, len) { var data = []; var reg = [addr] qlc5883Dev.write(reg); for (i = 0; i < len; i++) { data[i] = qlc5883Dev.read(1); } console.log("--> read addr " + addr + ", " + len + " bytes value = " + data); return data; } function init(i2cid) { qlc5883Dev = i2c.open({id: i2cid}); fakeSleep(30); _qmc5883l_init(); } // De-init qlc5883 function deinit() { qlc5883Dev.close(); } function qmc5883l_write_register(addr, reg, data) { devRegWrite1Byte(reg); fakeSleep(200); devRegWrite1Byte(data); } function qmc5883l_read_register(addr, reg) { return devRegRead1Byte(reg); } function qmc5883l_read_len(addr, reg, buf, len) { return devRegReadNByte(reg, len); } function qmc5883l_reconfig() { qmc5883l_write_register(addr, QMC5883L_CONFIG, oversampling | range | rate | mode); qmc5883l_write_register(addr, QMC5883L_CONFIG2, 0x1); } function qmc5883l_reset() { qmc5883l_write_register(addr, QMC5883L_RESET, 0x01); fakeSleep(500); qmc5883l_reconfig(); qmc5883l_resetCalibration(); } function qmc5883l_setOversampling(x) { switch (x) { case 512: oversampling = QMC5883L_CONFIG_OS512; break; case 256: oversampling = QMC5883L_CONFIG_OS256; break; case 128: oversampling = QMC5883L_CONFIG_OS128; break; case 64: oversampling = QMC5883L_CONFIG_OS64; break; } qmc5883l_reconfig(); } function qmc5883l_setRange(x) { switch (x) { case 2: range = QMC5883L_CONFIG_2GAUSS; break; case 8: range = QMC5883L_CONFIG_8GAUSS; break; } qmc5883l_reconfig(); } function qmc5883l_setSamplingRate(x) { switch (x) { case 10: rate = QMC5883L_CONFIG_10HZ; break; case 50: rate = QMC5883L_CONFIG_50HZ; break; case 100: rate = QMC5883L_CONFIG_100HZ; break; case 200: rate = QMC5883L_CONFIG_200HZ; break; } qmc5883l_reconfig(); } function _qmc5883l_init() { /* This assumes the wire library has been initialized. */ addr = QMC5883L_ADDR; oversampling = QMC5883L_CONFIG_OS512; range = QMC5883L_CONFIG_8GAUSS; rate = QMC5883L_CONFIG_200HZ; mode = QMC5883L_CONFIG_CONT; qmc5883l_reset(); } function qmc5883l_ready() { fakeSleep(200); return qmc5883l_read_register(addr, QMC5883L_STATUS) & QMC5883L_STATUS_DRDY; } function qmc5883l_readRaw(x, y, z) { var data; var timeout = 10000; var arr = []; while (!qmc5883l_ready() && (timeout--)) ; data = qmc5883l_read_len(addr, QMC5883L_X_LSB, data, 6); x = data[0] | (data[1] << 8); y = data[2] | (data[3] << 8); z = data[4] | (data[5] << 8); if (x > (1 << 15)) { x = x - (1<<16) } if (y > (1 << 15)) { y = y - (1<<16) } if (z > (1 << 15)) { z = z - (1<<16) } arr[0] = x; arr[1] = y; arr[2] = z; return arr; } function qmc5883l_resetCalibration() { x_max = y_max = z_max = INT16_MIN; x_min = y_min = z_min = INT16_MAX; } function qmc5883l_readHeading() { var x_org, y_org, z_org; var xyz_org = []; var x_offset, y_offset, z_offset; var x_fit, y_fit, z_fit; qmc5883l_read_register(addr, QMC5883L_STATUS) & QMC5883L_STATUS_DRDY; xyz_org = qmc5883l_readRaw(x_org, y_org, z_org); x_org = xyz_org[0]; y_org = xyz_org[1]; z_org = xyz_org[2]; console.log("org[%d,%d,%d],\n"+ " x:" + x_org+ " y:" + y_org+ " z:" + z_org); /* Update the observed boundaries of the measurements */ x_min = x_org < x_min ? x_org : x_min; x_max = x_org > x_max ? x_org : x_max; y_min = y_org < y_min ? y_org : y_min; y_max = y_org > y_max ? y_org : y_max; z_min = z_org < z_min ? z_org : z_min; z_max = z_org > z_max ? z_org : z_max; /* Bail out if not enough data is available. */ if (x_min == x_max || y_min == y_max || z_max == z_min) return 0; /* Recenter the measurement by subtracting the average */ x_offset = (x_max + x_min) / 2.0; y_offset = (y_max + y_min) / 2.0; z_offset = (z_max + z_min) / 2.0; x_fit = (x_org - x_offset) * 1000.0 / (x_max - x_min); y_fit = (y_org - y_offset) * 1000.0 / (y_max - y_min); z_fit = (z_org - z_offset) * 1000.0 / (z_max - z_min); console.log("fix[%f,%f,%f],\n", "x " + x_fit + ",y " + y_fit + ",z " + z_fit); var heading = 180.0 * Math.atan2(x_fit, y_fit) / M_PI; heading = (heading <= 0) ? (heading + 360) : heading; return heading; } module.exports = { init, qmc5883l_readHeading, deinit }
YifuLiu/AliOS-Things
components/amp/modules/qlc5883.js
JavaScript
apache-2.0
7,845
const SET_SCAN_DIR = 0xc0 const LOW_COLUMN_ADDRESS = 0x00 const HIGH_COLUMN_ADDRESS = 0x10 const SET_PAGE_ADDRESS = 0xB0 const SET_CONTRAST = 0x81 const SET_ENTIRE_ON = 0xa4 const SET_NORM_INV = 0xa6 const SET_DISP = 0xae const SET_MEM_ADDR = 0x20 const SET_DISP_START_LINE = 0x40 const SET_SEG_REMAP = 0xa0 const SET_MUX_RATIO = 0xa8 const SET_COM_OUT_DIR = 0xc0 const SET_DISP_OFFSET = 0xd3 const SET_COM_PIN_CFG = 0xda const SET_DISP_CLK_DIV = 0xd5 const SET_PRECHARGE = 0xd9 const SET_VCOM_DESEL = 0xdb const SET_CHARGE_PUMP = 0x8d export default class SH1106 { constructor(width, height, spi, dc, res, cs) { this.width = width; this.height = height; this.spi = spi; this.dc = dc; this.res = res; this.cs = cs; this.dc_var = 0; this.cs_var = 1; this.pages = Math.floor(this.height / 8) this.framebuf = new Array(this.pages * this.width).fill(0) return this; } reset() { if (this.res != undefined) { this.res.writeValue(1) sleepMs(1) this.res.writeValue(0) sleepMs(20) this.res.writeValue(1) sleepMs(20) } } show() { for (let page = 0; page < this.pages; page++) { this.write_cmd(SET_PAGE_ADDRESS | page) this.write_cmd(LOW_COLUMN_ADDRESS) this.write_cmd(HIGH_COLUMN_ADDRESS) this.write_data(this.framebuf.slice(this.width * page, this.width * (page + 1))) } } write_cmd(cmd) { if (this.dc_var == 1) { this.dc.writeValue(0) this.dc_var = 0 } if (this.cs != undefined && this.cs_var == 1) { this.cs.writeValue(0) this.cs_var = 0 } this.spi.write([cmd]) } write_data(buf) { if (this.dc_var == 0) { this.dc.writeValue(1) this.dc_var = 1 } if (this.cs != undefined && this.cs_var == 1) { this.cs.writeValue(0) this.cs_var = 0 } this.spi.write(buf) } pixel(x, y, color) { if ((x > (this.width)) || (y > this.height) || x < 0 || y < 0) return; let page = Math.floor(y / 8) let bit_offset = y % 8; let mask = 0x01 << bit_offset; if (color == 0) this.framebuf[page * this.width + x] &= ~mask; if (color == 1) this.framebuf[page * this.width + x] |= mask; if (color == 2) this.framebuf[page * this.width + x] ^= mask; if (color == undefined) return (this.framebuf[page * this.width + x] & mask) } fill(color) { this.framebuf.fill(color == 0 ? 0 : 255) } line(x1, y1, x2, y2, color) { let xerr = 1, yerr = 1, delta_x, delta_y, distance; let incx, incy, uRow, uCol; delta_x = x2 - x1; delta_y = y2 - y1; uRow = x1; uCol = y1; if (delta_x > 0) { incx = 1; } else if (delta_x == 0) { incx = 0; } else { incx = -1; delta_x = -delta_x; } if (delta_y > 0) { incy = 1; } else if (delta_y == 0) { incy = 0; } else { incy = -1; delta_y = -delta_y; } if (delta_x > delta_y) distance = delta_x; else distance = delta_y; for (let t = 0; t <= distance; t++) { this.pixel(uRow, uCol, color); xerr += delta_x; yerr += delta_y; if (xerr > distance / 2) { xerr -= distance; uRow += incx; } if (yerr > distance) { yerr -= distance; uCol += incy; } } } rect(x, y, w, h, color) { this.line(x, y, x + w, y, color) this.line(x, y, x, y + h, color) this.line(x + w, y + h, x, y + h, color) this.line(x + w, y + h, x + w, y, color) } fill_rect(x, y, w, h, color) { for (let i = 0; i < h; i++) { this.line(x, y, x + w, y + i, color) } } draw_XBM(x, y, w, h, bitmap) { let p_x, p_y; let x_byte = Math.floor(w / 8) + (w % 8 != 0) for (let nbyte = 0; nbyte < bitmap.length; nbyte++) { for (let bit = 0; bit < 8; bit++) { if (bitmap[nbyte] & (0b10000000 >> bit)) { p_x = (nbyte % x_byte) * 8 + bit p_y = Math.floor(nbyte / x_byte) this.pixel(x + p_x, y + p_y, 1) } } } } open() { this.reset() this.dc.writeValue(0) this.dc_var = 0; if (this.cs != undefined) { this.cs.writeValue(1) this.cs_var = 1; } this.write_cmd(SET_DISP | 0x00) // 关闭显示 this.write_cmd(SET_DISP_CLK_DIV) this.write_cmd(0x80) // 设置时钟分频因子 this.write_cmd(SET_MUX_RATIO) this.write_cmd(this.height - 1) // 设置驱动路数 路数默认0x3F(1/64) this.write_cmd(SET_DISP_OFFSET) this.write_cmd(0x00) // 设置显示偏移 偏移默认为0 this.write_cmd(SET_DISP_START_LINE | 0x00) // 设置显示开始行[5:0] this.write_cmd(SET_CHARGE_PUMP) this.write_cmd(0x14) // 电荷泵设置 bit2,开启/关闭 this.write_cmd(SET_MEM_ADDR) this.write_cmd(0x02) // 设置内存地址模式 [1:0],00,列地址模式;01,行地址模式;10,页地址模式;默认10; this.write_cmd(SET_SEG_REMAP | 0x01) // 段重定义设置,bit0:0,0->0;1,0->127; this.write_cmd(SET_COM_OUT_DIR | 0x08) // 设置COM扫描方向;bit3:0,普通模式;1,重定义模式 COM[N-1]->COM0;N:驱动路数 this.write_cmd(SET_COM_PIN_CFG) this.write_cmd(0x12) // 设置COM硬件引脚配置 [5:4]配置 this.write_cmd(SET_PRECHARGE) this.write_cmd(0xf1) // 设置预充电周期 [3:0],PHASE 1;[7:4],PHASE 2; this.write_cmd(SET_VCOM_DESEL) this.write_cmd(0x30) // 设置VCOMH 电压倍率 [6:4] 000,0.65*vcc;001,0.77*vcc;011,0.83*vcc; this.write_cmd(SET_CONTRAST) this.write_cmd(0xff) // 对比度设置 默认0x7F(范围1~255,越大越亮) this.write_cmd(SET_ENTIRE_ON) // 全局显示开启;bit0:1,开启;0,关闭;(白屏/黑屏) this.write_cmd(SET_NORM_INV) // 设置显示方式;bit0:1,反相显示;0,正常显示 this.write_cmd(SET_DISP | 0x01) this.fill(1) this.show() } poweroff() { this.write_cmd(SET_DISP | 0x00) } poweron() { this.write_cmd(SET_DISP | 0x01) } rotate(flag, update) { if (update === undefined) { update = true } if (flag) { this.write_cmd(SET_SEG_REMAP | 0x01) // mirror display vertically this.write_cmd(SET_SCAN_DIR | 0x08) // mirror display hor. } else { this.write_cmd(SET_SEG_REMAP | 0x00) this.write_cmd(SET_SCAN_DIR | 0x00) } if (update) { this.show() } } contrast(contrast) { this.write_cmd(SET_CONTRAST) this.write_cmd(contrast) } invert(invert) { this.write_cmd(SET_NORM_INV | (invert & 1)) } }
YifuLiu/AliOS-Things
components/amp/modules/sh1106.js
JavaScript
apache-2.0
7,456
// The driver for Si7006 chip, it is a temperature and humidity sensor. // The register address in Si7006 controller. var Si7006_MEAS_REL_HUMIDITY_MASTER_MODE = 0xE5; var Si7006_MEAS_REL_HUMIDITY_NO_MASTER_MODE = 0xF5; var Si7006_MEAS_TEMP_MASTER_MODE = 0xE3; var Si7006_MEAS_TEMP_NO_MASTER_MODE = 0xF3; var Si7006_READ_OLD_TEMP = 0xE0; var Si7006_RESET = 0xFE; var Si7006_READ_ID_LOW_0 = 0xFA; var Si7006_READ_ID_LOW_1 = 0x0F; var Si7006_READ_ID_HIGH_0 = 0xFC; var Si7006_READ_ID_HIGH_1 = 0xC9; var Si7006_READ_Firmware_Revision_0 = 0x84; var Si7006_READ_Firmware_Revision_1 = 0xB8; // Require libjs/lib/i2c.js module. var i2c = require('i2c'); var si7006Dev; /* Init Si7006 * * I2C's options are configured in app.json. Specify the ID, e.g. I2C0 below to init Si7006. * "I2C0": { * "type": "I2C", * "port": 1, * "addrWidth": 7, * "freq": 400000, * "mode": "master", * "devAddr": 72 * } */ function init(i2cid) { si7006Dev = i2c.open({id: i2cid}); } /* duktape engine doesn't support async/await to sleep. function sleep(ms) { return new Promise(function (resolve, reject) { setTimeout(function () { resolve(); }, ms); }); } */ function fakeSleep(ms) { var date = new Date(); var curDate; do { curDate = new Date(); } while((curDate - date) < ms); } // Get the firmware version of the chip. function getVer() { var reg = [Si7006_READ_Firmware_Revision_0, Si7006_READ_Firmware_Revision_1]; var version = 0; si7006Dev.write(reg); version = si7006Dev.read(1); //console.log("si7006 firmware version is " + version); return version; } // Get the chip ID. function getID() { var chipID, lowID, highID; var lowIDReg = [Si7006_READ_ID_LOW_0, Si7006_READ_ID_LOW_1]; var highIDReg = [Si7006_READ_ID_HIGH_0, Si7006_READ_ID_HIGH_1]; si7006Dev.write(lowIDReg); lowID = si7006Dev.read(4); si7006Dev.write(highIDReg); highID = si7006Dev.read(4); chipID = lowID.concat(highID); return chipID; } // Get temperature function getTemperature() { var reg = [Si7006_MEAS_TEMP_NO_MASTER_MODE]; var readData; var value; var temperature; si7006Dev.write(reg); fakeSleep(30); readData = si7006Dev.read(2); value = (readData[0] << 8) | readData[1]; // A temperature measurement will always return XXXXXX00 in the LSB field. if (value & 0xFFFC) { temperature = ((175.72 * value) / 65536.0) - 46.85; return temperature; } else { throw new Error("Error on getTemperature"); } } // Get humidity function getHumidity() { var reg = [Si7006_MEAS_REL_HUMIDITY_NO_MASTER_MODE]; var readData; var value; var humidity; si7006Dev.write(reg); fakeSleep(30); readData = si7006Dev.read(2); value = (readData[0] << 8) | readData[1]; if (value & 0xFFFE) { humidity = ((125.0 * value) / 65535.0) - 6.0; return humidity; } else { throw new Error ("Error on getHumidity"); } } // Get temperature and humidity function getTempHumidity() { var tempHumidity = [0, 0]; tempHumidity[0] = getTemperature(); tempHumidity[1] = getHumidity(); return tempHumidity; } // De-init Si7006 function deinit() { si7006Dev.close(); } module.exports = { init, getVer, getID, getTemperature, getHumidity, getTempHumidity, deinit }
YifuLiu/AliOS-Things
components/amp/modules/si7006.js
JavaScript
apache-2.0
3,600
// The driver for spl06 chip, it is a temperature and humidity sensor. /* 添加如下配置到app.json中: "spl06": { "type": "I2C", "port": 1, "addrWidth": 7, "freq": 400000, "mode": "master", "devAddr": 119 } */ // Require libjs/lib/i2c.js module. var i2c = require('i2c'); var spl06Dev; /* duktape engine doesn't support async/await to sleep. function sleep(ms) { return new Promise(function (resolve, reject) { setTimeout(function () { resolve(); }, ms); }); } */ function fakeSleep(ms) { var date = new Date(); var curDate; do { curDate = new Date(); } while((curDate - date) < ms); } /* Init spl06 * * I2C's options are configured in app.json. Specify the ID, e.g. I2C0 below to init spl06. * "I2C0": { * "type": "I2C", * "port": 1, * "addrWidth": 7, * "freq": 400000, * "mode": "master", * "devAddr": 119 * } */ var EEPROM_CHIP_ADDRESS = 0x77; function i2c_eeprom_read_var(chipAddress, addr){ return devRegReadWrite1Byte(0, addr, 0); } function devRegRead1Byte(addr) { return devRegReadWrite1Byte(0, addr, 0); } function devRegReadWrite1Byte(mode, addr, value) { //0 read mode //1 write mode if (mode == 0) { var Reg = []; Reg[0] = addr spl06Dev.write(Reg); value = spl06Dev.read(1); // console.log("<-- read addr " + addr + ", value = " + value); return value; } else { var Reg = [addr, value]; spl06Dev.write(Reg); // console.log("--> write addr " + addr + ", value = " + value); return 0; } } function init(i2cid) { spl06Dev = i2c.open({id: i2cid}); fakeSleep(30); var tmp = 0; var rRegID = [0x0D, 0x0]; var wRegPressure8xOversampling = [0x06, 0x03]; var wRegTemperature8xOversampling = [0x07, 0x83]; var wRegContinuousTempAndPressureMeasurement = [0x08, 0B0111]; var wRegFIFOPressureMeasurement = [0x09, 0x00]; tmp = rRegID; devRegReadWrite1Byte(0, tmp[0], tmp[1]); tmp = wRegPressure8xOversampling; devRegReadWrite1Byte(1, tmp[0], tmp[1]); tmp = wRegTemperature8xOversampling; devRegReadWrite1Byte(1, tmp[0], tmp[1]); tmp = wRegContinuousTempAndPressureMeasurement; devRegReadWrite1Byte(1, tmp[0], tmp[1]); tmp = wRegFIFOPressureMeasurement; devRegReadWrite1Byte(1, tmp[0], tmp[1]); } // Get the firmware version of the chip. function getID() { var reg = [0x0D]; var version = 0; spl06Dev.write(reg); version = spl06Dev.read(1); console.log("spl06 ID is " + version); return version; } function get_altitude(pressure, seaLevelhPa) { if (seaLevelhPa == 0) { return -1; } var altitude; pressure /= 100; altitude = 44330 * (1.0 - Math.pow(pressure / seaLevelhPa, 0.1903)); return altitude; } function get_temperature_scale_factor() { var k; var tmp_Byte; tmp_Byte = i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0X07); // MSB tmp_Byte = tmp_Byte & 0B00000111; console.log("tmp_Byte: %d\n", tmp_Byte); switch (tmp_Byte) { case 0B000: k = 524288.0; break; case 0B001: k = 1572864.0; break; case 0B010: k = 3670016.0; break; case 0B011: k = 7864320.0; break; case 0B100: k = 253952.0; break; case 0B101: k = 516096.0; break; case 0B110: k = 1040384.0; break; case 0B111: k = 2088960.0; break; } console.log("k=%d\n", k); return k; } function get_pressure_scale_factor() { var k; var tmp_Byte; tmp_Byte = i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0X06); // MSB // tmp_Byte = tmp_Byte >> 4; //Focus on bits 6-4 - measurement rate tmp_Byte = tmp_Byte & 0B00000111; // Focus on 2-0 oversampling rate // tmp_Byte = 0B011; // oversampling rate switch (tmp_Byte) { case 0B000: k = 524288.0; break; case 0B001: k = 1572864.0; break; case 0B010: k = 3670016.0; break; case 0B011: k = 7864320.0; break; case 0B100: k = 253952.0; break; case 0B101: k = 516096.0; break; case 0B110: k = 1040384.0; break; case 0B111: k = 2088960.0; break; } console.log("k=%d\n", k); return k; } function get_traw() { var tmp; var tmp_MSB, tmp_LSB, tmp_XLSB; tmp_MSB = i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0X03); // MSB tmp_LSB = i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0X04); // LSB tmp_XLSB = i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0X05); // XLSB tmp = (tmp_MSB << 8) | tmp_LSB; tmp = (tmp << 8) | tmp_XLSB; if (tmp & (1 << 23)) tmp = tmp | 0XFF000000; // Set left bits to one for 2's complement // conversion of negitive number console.log("get_traw: tmp_MSB=%d, tmp_LSB=%d, tmp_XLSB=%d\n", tmp_MSB, tmp_LSB, tmp_XLSB); return tmp; } function get_praw(){ var tmp; var tmp_MSB, tmp_LSB, tmp_XLSB; tmp_MSB = i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0X00); // MSB tmp_LSB = i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0X01); // LSB tmp_XLSB = i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0X02); // XLSB tmp = (tmp_MSB << 8) | tmp_LSB; tmp = (tmp << 8) | tmp_XLSB; if (tmp & (1 << 23)) tmp = tmp | 0XFF000000; // Set left bits to one for 2's complement // conversion of negitive number return tmp; } function get_c0() { var tmp; var tmp_MSB, tmp_LSB; tmp_MSB = i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0X10); tmp_LSB = i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0X11); tmp_LSB = tmp_LSB >> 4; tmp = (tmp_MSB << 4) | tmp_LSB; if (tmp & (1 << 11)) // Check for 2's complement negative number tmp = tmp | 0XF000; // Set left bits to one for 2's complement // conversion of negitive number if (tmp > (1 << 15)) { tmp = tmp - (1<<16) } console.log("get_c0: tmp_MSB=%d, tmp_LSB=%d, tmp=%d\n", tmp_MSB, tmp_LSB, tmp); return tmp; } function get_c1() { var tmp; var tmp_MSB, tmp_LSB; tmp_MSB = i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0X11); tmp_LSB = i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0X12); tmp_MSB = tmp_MSB & 0XF; tmp = (tmp_MSB << 8) | tmp_LSB; if (tmp & (1 << 11)) // Check for 2's complement negative number tmp = tmp | 0XF000; // Set left bits to one for 2's complement // conversion of negitive number if (tmp > (1 << 15)) { tmp = tmp - (1<<16) } console.log("get_c1: tmp_MSB=%d, tmp_LSB=%d, tmp=%d\n", tmp_MSB, tmp_LSB, tmp); return tmp; } function get_c00() { var tmp; var tmp_MSB, tmp_LSB, tmp_XLSB; tmp_MSB = i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0X13); tmp_LSB = i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0X14); tmp_XLSB = i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0X15); tmp_XLSB = tmp_XLSB >> 4; tmp = (tmp_MSB << 8) | tmp_LSB; tmp = (tmp << 4) | tmp_XLSB; tmp = tmp_MSB << 12 | tmp_LSB << 4 | tmp_XLSB >> 4; if (tmp & (1 << 19)) tmp = tmp | 0XFFF00000; // Set left bits to one for 2's complement // conversion of negitive number return tmp; } function get_c10() { var tmp; var tmp_MSB, tmp_LSB, tmp_XLSB; tmp_MSB = i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0X15); // 4 bits tmp_LSB = i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0X16); // 8 bits tmp_XLSB = i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0X17); // 8 bits tmp_MSB = tmp_MSB & 0b00001111; tmp = (tmp_MSB << 4) | tmp_LSB; tmp = (tmp << 8) | tmp_XLSB; tmp = tmp_MSB << 16 | tmp_LSB << 8 | tmp_XLSB; if (tmp & (1 << 19)) tmp = tmp | 0XFFF00000; // Set left bits to one for 2's complement // conversion of negitive number return tmp; } function get_c01() { var tmp; var tmp_MSB, tmp_LSB; tmp_MSB = i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0X18); tmp_LSB = i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0X19); tmp = (tmp_MSB << 8) | tmp_LSB; if (tmp > (1 << 15)) { tmp = tmp - (1<<16) } return tmp; } function get_c11() { var tmp; var tmp_MSB, tmp_LSB; tmp_MSB = i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0X1A); tmp_LSB = i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0X1B); tmp = (tmp_MSB << 8) | tmp_LSB; if (tmp > (1 << 15)) { tmp = tmp - (1<<16) } return tmp; } function get_c20() { var tmp; var tmp_MSB, tmp_LSB; tmp_MSB = i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0X1C); tmp_LSB = i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0X1D); tmp = (tmp_MSB << 8) | tmp_LSB; if (tmp > (1 << 15)) { tmp = tmp - (1<<16) } return tmp; } function get_c21() { var tmp; var tmp_MSB, tmp_LSB; tmp_MSB = i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0X1E); tmp_LSB = i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0X1F); tmp = (tmp_MSB << 8) | tmp_LSB; if (tmp > (1 << 15)) { tmp = tmp - (1<<16) } return tmp; } function get_c30() { var tmp; var tmp_MSB, tmp_LSB; tmp_MSB = i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0X20); tmp_LSB = i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0X21); tmp = (tmp_MSB << 8) | tmp_LSB; if (tmp > (1 << 15)) { tmp = tmp - (1<<16) } return tmp; // console.log("tmp: %d\n", tmp); } function spl06_getdata() { var tmp; var c00, c10; var c0, c1, c01, c11, c20, c21, c30; // Serial.println("\nDevice Reset\n"); // i2c_eeprom_write_var(EEPROM_CHIP_ADDRESS, 0x0C, 0b1001); // delay(1000); tmp = i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0x0D); tmp = i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0x06); tmp = i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0x07); tmp = i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0x08); tmp = i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0x09); tmp = i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0x0A); tmp = i2c_eeprom_read_var(EEPROM_CHIP_ADDRESS, 0x0B); c0 = get_c0(); c1 = get_c1(); c00 = get_c00(); c10 = get_c10(); c01 = get_c01(); c11 = get_c11(); c20 = get_c20(); c21 = get_c21(); c30 = get_c30(); var traw = get_traw(); var traw_sc = traw / get_temperature_scale_factor(); traw_sc = traw_sc.toFixed(2) console.log("traw_sc: %0.2f\n", traw_sc); var Ctemp = c0 * 0.5 + c1 * traw_sc; Ctemp = Ctemp.toFixed(2) console.log("Ctemp:" + Ctemp + ". " + "c0:" + c0 + " c1" + c1 + " traw_sc:" + traw_sc); var Ftemp = (Ctemp * 9 / 5) + 32; Ftemp = Ftemp.toFixed(2) console.log("Ftemp:" + Ftemp) var praw = get_praw(); var praw_sc = (praw) / get_pressure_scale_factor(); console.log("praw:" + praw) console.log("praw_sc:" + praw_sc) console.log("c00:" + c00) console.log("c10:" + c10) console.log("c20:" + c20) console.log("c30:" + c30) console.log("c01:" + c01) console.log("c11:" + c11) console.log("c21:" + c21) var pcomp = (c00) + praw_sc * ((c10) + praw_sc * ((c20) + praw_sc * (c30))) + traw_sc * (c01) + traw_sc * praw_sc * ((c11) + praw_sc * (c21)); var pressure = pcomp / 100; // convert to mb console.log("pressure:" + pressure) // var local_pressure = 1010.5; // Look up local sea level pressure on // google var local_pressure = 1011.1; // Look up local sea level pressure on google // Local pressure // from airport website 8/22 console.log("Local Airport Sea Level Pressure: %0.2f mb\n", local_pressure); var altitude = get_altitude(pcomp, local_pressure); console.log("altitude:" + altitude) } // De-init spl06 function deinit() { spl06Dev.close(); } module.exports = { init, getID, spl06_getdata, deinit }
YifuLiu/AliOS-Things
components/amp/modules/spl06.js
JavaScript
apache-2.0
12,554
TARGET = libservices.a MODULE = services MOD_SOURCES += \ app_mgr/app_message.c \ app_mgr/app_mgr.c \ app_mgr/app_management_center.c \ app_mgr/app_upgrade.c MOD_SOURCES += \ board_mgr/board_info.c \ board_mgr/board_mgr.c MOD_SOURCES += \ recovery/recovery.c \ recovery/ymodem.c MOD_SOURCES += \ amp_utils/amp_utils.c \ MOD_INCLUDES := \ ../main \ ../adapter/include \ ../adapter/include/peripheral \ ../adapter/platform/linux \ ../utils/mbedtls/include \ ../utils/mbedtls/platform/include \ ../utils/mbedtls/platform/amp/include \ ../utils/cJSON \ ../components/linksdk/components/bootstrap \ ../components/linksdk/components/das \ ../components/linksdk/components/data-model \ ../components/linksdk/components/devinfo \ ../components/linksdk/components/diag \ ../components/linksdk/components/dynreg \ ../components/linksdk/components/ntp \ ../components/linksdk/components/subdev \ ../components/linksdk/core \ ../components/linksdk/core/sysdep \ ../components/linksdk/core/utils \ ../components/ulog \ ../components/das/include \ ../components/ota/include \ amp_utils \ app_mgr \ board_mgr \ recovery ifeq ($(ADDON), ui) MOD_INCLUDES += \ ../ui/render/include \ ../ui/aui/ \ ../ui/aui/aui_core \ ../ui/aui/aui_draw \ ../ui/aui/aui_fonts \ ../ui/aui/aui_hal \ ../ui/aui/aui_misc \ ../ui/aui/aui_objx \ ../ui/aui/aui_themes \ ../ui/aui/libs \ ../ui/aui/libs/lvgl \ ../ui/aui/libs/lvgl/src\ ../ui/aui/libs/lvgl/src/lv_misc \ ../ui/aui/libs/lvgl/src/lv_font \ ../ui/aui/libs/lvgl/src/lv_core \ ../ui/aui/libs/lvgl/src/lv_draw \ ../ui/aui/libs/lvgl/src/lv_hal \ ../ui/aui/libs/lvgl/src/lv_objx \ ../ui/aui/libs/lvgl/src/lv_themes \ ../utils/ezxml \ ../utils/lexbor \ ../utils/lexbor/css \ ../adapter/include \ ../components/linkkit \ ../components/linkkit/infra \ ../main \ ../utils/mbedtls/include \ ../components/ulog \ ../engine/duktape_engine \ ../adapter/platform/linux endif include $(TOOLS_DIR)/rules.mk
YifuLiu/AliOS-Things
components/amp/services/Makefile
Makefile
apache-2.0
2,048
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include "aos/kernel.h" #include "aos/kv.h" #include "amp_boot.h" #define MOD_STR "amp_boot" #define AMP_BOOT_WAIT_TIME 1000 #define AMP_BOOT_MAX_KV_LEN 256 #define AMP_BOOT_KV_VALUE_END_STR "[amp_value_end]\n" static char g_amp_boot_sync[] = "amp_boot"; void amp_boot_init() { #if ((!defined(BOARD_HAAS100)) && (!defined(BOARD_HAASEDUK1))) amp_boot_uart_init(); #endif } void amp_boot_deinit() { #if ((!defined(BOARD_HAAS100)) && (!defined(BOARD_HAASEDUK1))) amp_boot_uart_deinit(); #endif } void print_usage() { } void aos_boot_delay(uint32_t ms) { uint64_t begin_ms = aos_now_ms(); while (1) { uint64_t now_ms = aos_now_ms(); if (now_ms - begin_ms >= ms) { break; } } } void amp_boot_loop(int line) { while (1) { aos_boot_delay(500); } } void amp_boot_flash_js() { amp_recovery_appbin(); } void amp_boot_flash_kv() { char key[64] = {0}; char kv_value_end_str[] = AMP_BOOT_KV_VALUE_END_STR; uint8_t *data = NULL; int num = 0; int ret = 0; aos_boot_delay(5); num = amp_boot_uart_recv_line(key, 64, 50000); if ((num == 0) || (num >= 64)) { amp_error(MOD_STR, "recv key error %d\n", num); return; } aos_boot_delay(5); key[num] = '\0'; amp_debug(MOD_STR, "[key]=%s\n", key); for (int i = 0; i < 1; i++) { amp_boot_uart_send_str("[value]="); } aos_boot_delay(5); amp_debug(MOD_STR, "[value]="); data = (uint8_t *)amp_malloc(AMP_BOOT_MAX_KV_LEN); if (data == NULL) { return; } memset(data, 0, AMP_BOOT_MAX_KV_LEN); num = 0; while (num < AMP_BOOT_MAX_KV_LEN) { unsigned char c = 0; if (1 == amp_boot_uart_recv_byte(&c)) { data[num] = (uint8_t)c; num ++; if ((c == '\n') && (num > strlen(kv_value_end_str))) { if (strncmp(kv_value_end_str, (char *)&data[num - strlen(kv_value_end_str)], strlen(kv_value_end_str)) == 0) { break; } } } aos_boot_delay(5); } amp_debug(MOD_STR, "\n"); num -= strlen(kv_value_end_str); data[num] = 0; amp_debug(MOD_STR, "begin write kv %s, size %d value 0x%x, 0x%x 0x%x\n", key, num, (uint32_t)(*(uint16_t *)(data)), (uint32_t)data[0], (uint32_t)data[1]); ret = aos_kv_set(key, data, num, 1); if (ret == 0) { amp_boot_uart_send_str("[kvok]"); amp_debug(MOD_STR, "write kv [%s] success\n", key); } amp_free(data); } void amp_boot_cli_menu() { print_usage(); amp_debug(MOD_STR, "\r\namp boot# "); while (1) { int boot_cmd = 0; boot_cmd = amp_boot_get_cmd(3000); switch (boot_cmd) { case AMP_BOOT_CMD_NULL: amp_debug(MOD_STR, "no command 3 seconds \r\n"); return; break; case AMP_BOOT_CMD_ERROR: amp_debug(MOD_STR, "command not supported \r\n"); break; case AMP_BOOT_CMD_EXIT: amp_debug(MOD_STR, "aos boot finished \r\n"); return; case AMP_BOOT_CMD_FLASH_JS: amp_boot_cmd_begin(AMP_BOOT_CMD_FLASH_JS); amp_boot_flash_js(); amp_boot_cmd_end(AMP_BOOT_CMD_FLASH_JS); break; case AMP_BOOT_CMD_FLASH_KV: amp_boot_cmd_begin(AMP_BOOT_CMD_FLASH_KV); amp_boot_flash_kv(); amp_boot_cmd_end(AMP_BOOT_CMD_FLASH_KV); break; default: print_usage(); return; } amp_debug(MOD_STR, "\r\namp boot# "); } } bool amp_boot_cli_in() { int begin_num = 0; int i = 0; unsigned char c = 0; uint64_t begin_time = aos_now_ms(); amp_boot_uart_send_str("amp shakehand begin...\n"); while (1) { c = 0; if ((amp_boot_uart_recv_byte(&c) != 1) || (c == 0)) { aos_boot_delay(5); if ((aos_now_ms() - begin_time) > AMP_BOOT_WAIT_TIME) { return false; } continue; } if (c == 0xA5) { begin_num ++; amp_boot_uart_send_byte(0x5A); } else { begin_num = 0; } if (begin_num == 4) { break; } } while (1) { c = 0; aos_boot_delay(5); if (amp_boot_uart_recv_byte(&c) == 1) { if (c != g_amp_boot_sync[i]) { i = 0; } else { i ++; } if (i >= strlen(g_amp_boot_sync)) { break; } } if ((aos_now_ms() - begin_time) > AMP_BOOT_WAIT_TIME) { return false; } } amp_debug(MOD_STR, "amp shakehand success\n"); return true; } void amp_boot_main(void) { int ret = 0; unsigned char c = 0; unsigned int i = 0; #ifdef SUPPORT_SET_DRIVER_TRACE_FLAG aos_set_driver_trace_flag(0); #endif amp_boot_init(); if (amp_boot_cli_in() == false) { #ifdef SUPPORT_SET_DRIVER_TRACE_FLAG aos_set_driver_trace_flag(1); #endif amp_boot_deinit(); return; } amp_boot_cli_menu(); #ifdef SUPPORT_SET_DRIVER_TRACE_FLAG aos_set_driver_trace_flag(1); #endif amp_boot_deinit(); return; }
YifuLiu/AliOS-Things
components/amp/services/amp_boot/amp_boot.c
C
apache-2.0
5,395
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #ifndef AMP_BOOT_H #define AMP_BOOT_H #include <stdio.h> #include <string.h> #include "stdint.h" #include "stdbool.h" #include "amp_platform.h" #include "amp_defines.h" #include "amp_config.h" #include "aos_system.h" #include "aos_network.h" #include "aos_fs.h" #include "aos_hal_uart.h" #include "amp_boot_recovery.h" #include "amp_boot_uart.h" #include "amp_boot_cmd.h" void aos_boot_delay(uint32_t ms); void amp_boot_main(void); #endif
YifuLiu/AliOS-Things
components/amp/services/amp_boot/amp_boot.h
C
apache-2.0
506
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include "amp_boot.h" static amp_boot_cmd_t g_amp_boot_cmd[] = { [AMP_BOOT_CMD_EXIT] = { "cmd_exit" }, [AMP_BOOT_CMD_QUERY_IMEI] = { "cmd_query_imei" }, [AMP_BOOT_CMD_QUERY_SEC] = { "cmd_query_sec" }, [AMP_BOOT_CMD_FLASH_SEC] = { "cmd_flash_sec" }, [AMP_BOOT_CMD_FLASH_JS] = { "cmd_flash_js" }, [AMP_BOOT_CMD_FLASH_KV] = { "cmd_flash_kv" } }; int amp_boot_get_cmd(int timeout_ms) { int32_t cmd_id = 0; int32_t recv_len = 0; char cmd_buff[32] = {0}; recv_len = amp_boot_uart_recv_line(cmd_buff, 32, timeout_ms); if (recv_len <= 0) { return AMP_BOOT_CMD_NULL; } for (cmd_id = 0; cmd_id < AMP_BOOT_CMD_MAX; cmd_id++) { if(recv_len != strlen(g_amp_boot_cmd[cmd_id].cmd_str)) { continue; } if (strncmp(cmd_buff, g_amp_boot_cmd[cmd_id].cmd_str, recv_len) == 0) { return cmd_id; } } return AMP_BOOT_CMD_ERROR; } void amp_boot_cmd_begin(int cmd) { amp_boot_uart_send_str(">>>>"); amp_boot_uart_send_str(g_amp_boot_cmd[cmd].cmd_str); } void amp_boot_cmd_end(int cmd) { amp_boot_uart_send_str("<<<<"); amp_boot_uart_send_str(g_amp_boot_cmd[cmd].cmd_str); }
YifuLiu/AliOS-Things
components/amp/services/amp_boot/amp_boot_cmd.c
C
apache-2.0
1,332
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #ifndef AMP_BOOT_CMD_H #define AMP_BOOT_CMD_H enum { AMP_BOOT_CMD_NULL, AMP_BOOT_CMD_EXIT, AMP_BOOT_CMD_QUERY_IMEI, AMP_BOOT_CMD_QUERY_SEC, AMP_BOOT_CMD_FLASH_SEC, AMP_BOOT_CMD_FLASH_JS, AMP_BOOT_CMD_FLASH_KV, AMP_BOOT_CMD_MAX, AMP_BOOT_CMD_ERROR = 127, }; typedef struct { char cmd_str[32]; } amp_boot_cmd_t; int amp_boot_get_cmd(int timeout_ms); void amp_boot_cmd_begin(int cmd); void amp_boot_cmd_end(int cmd); #endif
YifuLiu/AliOS-Things
components/amp/services/amp_boot/amp_boot_cmd.h
C
apache-2.0
529
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdarg.h> #include "amp_config.h" #include "amp_utils.h" #include "aos_system.h" #include "amp_defines.h" #include "aos_hal_uart.h" #include "aos_hal_gpio.h" #include "aos/kernel.h" #include "amp_board_config.h" #include "amp_boot_recovery.h" #include "app_mgr.h" #define MOD_STR "AMP_BOOT_RECOVERY" static gpio_dev_t amp_status_led; static gpio_dev_t amp_rec_switch; /* status led mode */ static AMP_STATUS amp_status = AMP_STATUS_NORMAL; extern int download_apppack(uint8_t *buf, int32_t buf_len); extern int ymodem_upgrade(void (*func)(unsigned char *, int)); extern int write_app_pack(const char *filename, int32_t file_size, int32_t type, int32_t offset, uint8_t *buf, int32_t buf_len, int32_t complete); static void ymodem_appbin_init(void) { apppack_init(write_app_pack); } static void amp_status_set(AMP_STATUS mode) { if (mode >= AMP_STATUS_END) { return; } amp_status = mode; } static void ymodem_appbin_finish(void) { apppack_final(); amp_status_set(AMP_STATUS_NORMAL); amp_debug(MOD_STR, "ymodem_appbin_finish"); } static void ymodem_appbin_write(unsigned char *buf, int size) { //hexdump("ymodem data", buf, size); amp_status_set(AMP_STATUS_UPDATING); download_apppack(buf, size); } static void _amp_status_led_on(void) { AMP_STATUS_IO_ON ? aos_hal_gpio_output_high(&amp_status_led) : aos_hal_gpio_output_low(&amp_status_led); } static void _amp_status_led_off(void) { AMP_STATUS_IO_ON ? aos_hal_gpio_output_low(&amp_status_led) : aos_hal_gpio_output_high(&amp_status_led); } static void _amp_status_led_task(void *param) { while (1) { // amp_debug(MOD_STR, "status_led_mode set"); switch (amp_status) { case AMP_STATUS_NORMAL: /* normal running */ _amp_status_led_on(); aos_msleep(500); _amp_status_led_off(); aos_msleep(2500); break; case AMP_STATUS_SERVICE_AVAILABLE: /* service available */ _amp_status_led_on(); aos_msleep(2500); _amp_status_led_off(); aos_msleep(500); break; case AMP_STATUS_RECOVERY: /* recovery mode */ _amp_status_led_on(); aos_msleep(100); _amp_status_led_off(); aos_msleep(100); _amp_status_led_on(); aos_msleep(100); _amp_status_led_off(); aos_msleep(850); break; case AMP_STATUS_UPDATING: /* upgrading */ _amp_status_led_on(); aos_msleep(50); _amp_status_led_off(); aos_msleep(50); _amp_status_led_on(); aos_msleep(50); _amp_status_led_off(); aos_msleep(50); break; case AMP_STATUS_JSERROR: /* JS Error */ _amp_status_led_on(); aos_msleep(1000); break; case AMP_STATUS_COREDUMP: /* JS Error */ _amp_status_led_on(); aos_msleep(1000); break; default: amp_debug(MOD_STR, "wrong status mode"); break; } } return; } int amp_recovery_init(void) { int delay = 0, ret = -1, status_off = 1; uint32_t value = 0; aos_task_t amp_stat_task; amp_debug(MOD_STR, "recovery entry"); amp_rec_switch.port = AMP_REC_IO; amp_rec_switch.config = INPUT_PULL_UP; amp_status_led.port = AMP_STATUS_IO; amp_status_led.config = OUTPUT_OPEN_DRAIN_PULL_UP; amp_error(MOD_STR, "recovery switch io is %d led port is %d", AMP_REC_IO, AMP_STATUS_IO); /* configure GPIO with the given settings */ ret = aos_hal_gpio_init(&amp_rec_switch); if (ret != 0) { amp_error(MOD_STR, "recovery switch gpio init error!"); return 0; } // for debounce while (delay++ <= 10) { aos_hal_gpio_input_get(&amp_rec_switch, &value); // recovery switch if (value == !AMP_REC_IO_ON) { status_off = 0; } amp_debug(MOD_STR, "gpio status: %d", value); aos_msleep(10); delay += 1; } if (status_off) { /* enter to recovery mode */ amp_debug(MOD_STR, "enter to recovery, not to start JS code"); ret = aos_hal_gpio_init(&amp_status_led); if (ret != 0) { amp_error(MOD_STR, "recovery status gpio init error!"); return 0; } aos_task_new_ext(&amp_stat_task, "amp status task", _amp_status_led_task, NULL, 1024, ADDON_TSK_PRIORRITY); amp_status_set(AMP_STATUS_RECOVERY); aos_hal_gpio_finalize(&amp_rec_switch); return -1; } aos_hal_gpio_finalize(&amp_rec_switch); return 0; } int amp_recovery_entry(void) { ymodem_appbin_init(); ymodem_upgrade(ymodem_appbin_write); ymodem_appbin_finish(); amp_debug(MOD_STR, "ymodem_upgrade done"); while (1) { aos_msleep(1000); } return 0; } int amp_recovery_appbin(void) { ymodem_appbin_init(); ymodem_upgrade(ymodem_appbin_write); ymodem_appbin_finish(); return 0; }
YifuLiu/AliOS-Things
components/amp/services/amp_boot/amp_boot_recovery.c
C
apache-2.0
5,554
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #ifndef AMP_RECOVERY_H #define AMP_RECOVERY_H #include <stddef.h> #include <stdint.h> #include "amp_config.h" /* recovery switch & status led. default for esp32 */ #ifndef AMP_REC_UART #define AMP_REC_UART 2 #endif #ifndef AMP_STATUS_IO #define AMP_STATUS_IO 33 #endif #ifndef AMP_STATUS_IO_ON #define AMP_STATUS_IO_ON 1 #endif /* recovery switch */ #ifndef AMP_REC_IO #define AMP_REC_IO 11 #endif #ifndef AMP_REC_IO_ON #define AMP_REC_IO_ON 1 #endif typedef enum{ AMP_STATUS_NORMAL = 0, AMP_STATUS_SERVICE_AVAILABLE, // 1 AMP_STATUS_RECOVERY, // 2 AMP_STATUS_UPDATING, // 3 AMP_STATUS_JSERROR, // 4 AMP_STATUS_COREDUMP, // 5 AMP_STATUS_END }AMP_STATUS; int amp_recovery_init(void); int amp_recovery_entry(void); int amp_recovery_appbin(void); void uart_send_byte(unsigned char c); unsigned char uart_recv_byte(unsigned char *c); #endif /* AMP_RECOVERY_H */
YifuLiu/AliOS-Things
components/amp/services/amp_boot/amp_boot_recovery.h
C
apache-2.0
964
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include "amp_boot.h" #include "amp_board_config.h" #ifdef AMP_VUART_PORT static vuart_dev_t g_boot_vuart = {0}; #else static uart_dev_t g_boot_uart = {0}; #endif void amp_boot_uart_send_byte(unsigned char c) { #ifdef AMP_VUART_PORT if ((aos_hal_vuart_send(&g_boot_vuart, &c, 1, osWaitForever)) != 0) { #else if ((aos_hal_uart_send(&g_boot_uart, &c, 1, osWaitForever)) != 0) { #endif //aos_printf("amp_boot_uart_send_byte error\n"); } } void amp_boot_uart_send_str(char *str) { #ifdef AMP_VUART_PORT if ((aos_hal_vuart_send(&g_boot_vuart, str, strlen(str), osWaitForever)) != 0) { #else if ((aos_hal_uart_send(&g_boot_uart, str, strlen(str), osWaitForever)) != 0) { #endif //aos_printf("amp_boot_uart_send_str %s error\n", str); } } unsigned char amp_boot_uart_recv_byte(unsigned char *c) { uint32_t read_byte = 0; #ifdef AMP_VUART_PORT if (aos_hal_vuart_recv_poll(&g_boot_vuart, c, 1, &read_byte) != 0) { // amp_error("AMP_BOOT_UART", "read len=%d, char=%c",read_byte, c); #else if (aos_hal_uart_recv_poll(&g_boot_uart, c, 1, &read_byte) != 0) { #endif return 0; } // amp_error("AMP_BOOT_UART", "read len=%d, char=%c",read_byte,c); return read_byte; } int amp_boot_uart_recv_line(char *str_line, int lens, int timeout_ms) { uint64_t begin_time = (uint64_t)aos_now_ms(); uint32_t read_byte = 0; int32_t str_num = 0; char c = 0; while (1) { c = 0; #ifdef AMP_VUART_PORT aos_hal_vuart_recv_poll(&g_boot_vuart, &c, 1, &read_byte); #else aos_hal_uart_recv_poll(&g_boot_uart, &c, 1, &read_byte); #endif if (read_byte == 1) { str_line[str_num] = c; if (c == '\n') { if ((str_num > 0) && (str_line[str_num - 1] == '\r')) { str_num --; } return str_num; } if (str_num >= lens) { return 0; } str_num ++; } if ((timeout_ms != osWaitForever) && (begin_time + timeout_ms < aos_now_ms())) { return 0; } } return 0; } void amp_boot_uart_init(void) { #ifdef AMP_VUART_PORT g_boot_vuart.port = AMP_RECOVERY_PORT; int ret = aos_hal_vuart_init(&g_boot_vuart); if (ret != 0) { amp_error("AMP_BOOT_UART", "open vuart failed!"); return; } #else g_boot_uart.port = AMP_RECOVERY_PORT; g_boot_uart.config.baud_rate = AMP_RECOVERY_PORT_BAUDRATE; g_boot_uart.config.data_width = DATA_WIDTH_8BIT; g_boot_uart.config.flow_control = FLOW_CONTROL_DISABLED; g_boot_uart.config.mode = MODE_TX_RX; g_boot_uart.config.parity = NO_PARITY; g_boot_uart.config.stop_bits = STOP_BITS_1; int ret = aos_hal_uart_init(&g_boot_uart); #endif if (ret) { return; } } void amp_boot_uart_deinit(void) { #ifdef AMP_VUART_PORT int ret = aos_hal_vuart_finalize(&g_boot_vuart); #else int ret = aos_hal_uart_finalize(&g_boot_uart); #endif if (ret) { return; } }
YifuLiu/AliOS-Things
components/amp/services/amp_boot/amp_boot_uart.c
C
apache-2.0
3,126
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #ifndef AMP_BOOT_UART_H #define AMP_BOOT_UART_H void amp_boot_uart_send_byte(unsigned char c); void amp_boot_uart_send_str(char *str); unsigned char amp_boot_uart_recv_byte(unsigned char *c); int amp_boot_uart_recv_line(char *str_line, int lens, int timeout_ms); void amp_boot_uart_init(void); void amp_boot_uart_deinit(void); #endif
YifuLiu/AliOS-Things
components/amp/services/amp_boot/amp_boot_uart.h
C
apache-2.0
399
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #include "amp_boot.h" #define MOD_STR "AMP_YMODEM" #define YMODEM_OK 0 #define YMODEM_ERR (-1) #define YMODEM_FILE_TOOBIG (-2) #define YMODEM_SOH 0x01 #define YMODEM_STX 0x02 #define YMODEM_EOT 0x04 #define YMODEM_ACK 0x06 #define YMODEM_NAK 0x15 #define YMODEM_CAN 0x18 #define YMODEM_CCHAR 'C' #define SOH_DATA_LEN 128 #define STX_DATA_LEN 1024 #define UART_RECV_TIMEOUT 4000000 #define YMODEM_STATE_INIT 0 #define YMODEM_STATE_WAIT_HEAD 1 #define YMODEM_STATE_WAIT_DATA 2 #define YMODEM_STATE_WAIT_END 3 #define YMODEM_STATE_WAIT_NEXT 4 #define YMODEM_MAX_CHAR_NUM 64 #define YMODEM_ERR_NAK_NUM 5 static unsigned int ymodem_flash_addr = 0; static unsigned int ymodem_flash_size = 0; static unsigned int ymodem_max_write_size = 40 * 1024 * 1024; #define uart_send_byte amp_boot_uart_send_byte #define uart_recv_byte amp_boot_uart_recv_byte typedef void (*ymodem_write_t)(unsigned char *, int); static ymodem_write_t ymodem_write = NULL; extern void aos_boot_delay(uint32_t ms); typedef struct { uint16_t crc; } CRC16_Context; static uint16_t UpdateCRC16(uint16_t crcIn, uint8_t byte) { uint32_t crc = crcIn; uint32_t in = byte | 0x100; do { crc <<= 1; in <<= 1; if (in & 0x100) { ++crc; } if (crc & 0x10000) { crc ^= 0x1021; } } while (!(in & 0x10000)); return crc & 0xffffu; } static void CRC16_Init( CRC16_Context *inContext ) { inContext->crc = 0; } static void CRC16_Update( CRC16_Context *inContext, const void *inSrc, size_t inLen ) { const uint8_t *src = (const uint8_t *) inSrc; const uint8_t *srcEnd = src + inLen; while ( src < srcEnd ) { inContext->crc = UpdateCRC16(inContext->crc, *src++); } } static void CRC16_Final( CRC16_Context *inContext, uint16_t *outResult ) { inContext->crc = UpdateCRC16(inContext->crc, 0); inContext->crc = UpdateCRC16(inContext->crc, 0); *outResult = inContext->crc & 0xffffu; } static unsigned short crc16_computer(void *addr, size_t len) { unsigned short crc = 0; CRC16_Context crc_context; CRC16_Init(&crc_context); CRC16_Update(&crc_context, addr, len); CRC16_Final(&crc_context, &crc); return crc; } unsigned int ymodem_str2int(char *buf, unsigned int buf_len) { int type = 10; int value = 0; int i = 0; if((buf[0] == '0') && (buf[1] == 'x' || buf[1] == 'X')) { type = 16; buf += 2; } for (i = 0; i < buf_len; buf++, i++) { if(*buf == 0) { return value; } if (*buf >= '0' && *buf <= '9') { value = value * type + *buf - '0'; } else { if(10 == type) { return value; } if (*buf >= 'A' && *buf <= 'F') { value = value * 16 + *buf - 'A' + 10; } else if (*buf >= 'a' && *buf <= 'f') { value = value * 16 + *buf - 'a' + 10; } else { return value; } } } return value; } unsigned int ymodem_recv_bytes(unsigned char *buffer, unsigned int nbytes, unsigned int timeout) { int ret = 0; unsigned char c = 0; unsigned int i = 0; unsigned int t = 0; while ((i < nbytes) && (t < timeout)) { ret = uart_recv_byte(&c); if (1 == ret) { buffer[i] = c; i++; } t++; } return i; } int ymodem_data_head_parse(unsigned char data_type) { int i = 0; int ret = YMODEM_ERR; int lp = 0; unsigned int buf_len = 0; unsigned char *buffer = NULL; unsigned short crc = 0; unsigned int value = 0; amp_debug(MOD_STR, "ymodem_data_head_parse\n"); buf_len = ((YMODEM_SOH == data_type) ? SOH_DATA_LEN : STX_DATA_LEN) + 4; buffer = amp_malloc(buf_len); memset(buffer, 0, buf_len); /* SOH HEAD */ value = ymodem_recv_bytes(buffer, buf_len, UART_RECV_TIMEOUT); if( (buf_len != value) || (0 != buffer[0]) || (0xFF != buffer[1]) ) { amp_debug(MOD_STR, "header error: %d %02x %02x\n", buf_len, buffer[0], buffer[1]); goto err_exit; } amp_debug(MOD_STR, "ymodem_recv_bytes head done, buf_len:%d\n", buf_len); /* check CRC */ crc = crc16_computer(&buffer[2], buf_len-4); if (((crc >> 8) != buffer[buf_len - 2]) || ((crc & 0xFF) != buffer[buf_len - 1])) { amp_debug(MOD_STR, "header crc error\n"); goto err_exit; } /* parse file name && file length */ for(i = 2; i < buf_len - 2; i++) { if((0 == buffer[i]) && (0 == lp)) { lp = i + 1; continue; } if((0 == buffer[i]) && (0 != lp)) { /* from buffer[lp] to buffer[i] is file length ascii */ value = ymodem_str2int((char *)&buffer[lp], i - lp); if (0 == value) { goto err_exit; } ymodem_flash_size = value; if(value > ymodem_max_write_size) { ret = YMODEM_FILE_TOOBIG; goto err_exit; } break; } } for (i = 2; i < buf_len - 4; i ++) { if (buffer[i] != 0) { ret = YMODEM_OK; } } amp_debug(MOD_STR, "get file size:%d\n", ymodem_flash_size); err_exit: amp_free(buffer); return ret; } int ymodem_data_parse(unsigned char data_type) { int ret = YMODEM_ERR; unsigned int buf_len = 0; unsigned short crc = 0; unsigned int value = 0; unsigned char *buffer = NULL; buf_len = ((YMODEM_SOH == data_type) ? SOH_DATA_LEN : STX_DATA_LEN) + 4; buffer = amp_malloc(buf_len); memset(buffer, 0, buf_len); amp_debug(MOD_STR, "ymodem_data_parse\n"); /* SOH HEAD */ value = ymodem_recv_bytes(buffer, buf_len, UART_RECV_TIMEOUT); if ((buf_len != value) || (0xFF != buffer[0] + buffer[1])) { amp_error(MOD_STR, "ymodem_data_parse crc error:%02x %02x\n", buffer[buf_len - 2], buffer[buf_len - 1] ); goto err_exit; } /* check CRC */ crc = crc16_computer(&buffer[2], buf_len - 4); if (((crc >> 8) != buffer[buf_len - 2]) || ((crc & 0xFF) != buffer[buf_len - 1])) { goto err_exit; } /* write data fo flash */ amp_debug(MOD_STR, "write data, buf_len:%d\n", buf_len - 4); if (ymodem_write != NULL) { ymodem_write(&buffer[2], buf_len - 4); } // ymodem_write_data_to_flash(&buffer[2], *addr, buf_len - 4); // *addr += buf_len - 4; ret = YMODEM_OK; err_exit : amp_free(buffer); return ret; } int ymodem_recv_file(void) { int i = 0; int ret = YMODEM_OK; int state = 0; int end_flag = 0; unsigned char c = 0; unsigned int bytes = 0; /* send C */ while (1) { aos_boot_delay(1); if(state != YMODEM_STATE_INIT) { bytes = ymodem_recv_bytes(&c, 1, 50000); } //aos_printf("ymodem_recv_file bytes = %d, i = %d, state = %d\n", bytes, i, state); //amp_debug_send_str("ymodem_recv_file \n"); switch (state) { case YMODEM_STATE_INIT: /* send 'C' */ if(i % 20 == 0) { uart_send_byte(YMODEM_CCHAR); } state = YMODEM_STATE_WAIT_HEAD; break; case YMODEM_STATE_WAIT_HEAD: /* wait SOH */ if(1 != bytes) { i ++; state = YMODEM_STATE_INIT; break; } if(( YMODEM_SOH == c ) || ( YMODEM_STX == c )) { ret = ymodem_data_head_parse(c); if (ret == YMODEM_OK) { uart_send_byte(YMODEM_ACK); aos_boot_delay(100); uart_send_byte(YMODEM_CCHAR); state = YMODEM_STATE_WAIT_DATA; break; } else { /* end */ uart_send_byte(YMODEM_ACK); aos_boot_delay(200); if(end_flag == 1) { ret = YMODEM_OK; } else { for(i = 0; i < YMODEM_ERR_NAK_NUM; i++) { uart_send_byte(YMODEM_NAK); } } return ret; } } else if (3 == c) { /* ctrl+c abort ymodem */ amp_debug(MOD_STR, "Abort\n"); return YMODEM_ERR; } break; case YMODEM_STATE_WAIT_DATA: /* receive data */ if(1 == bytes) { if( (YMODEM_SOH == c) || (YMODEM_STX == c) ) { ret = ymodem_data_parse(c); if (ret == YMODEM_OK) { uart_send_byte(YMODEM_ACK); } } else if( YMODEM_EOT == c ) { uart_send_byte(YMODEM_NAK); state = YMODEM_STATE_WAIT_END; } } break; case YMODEM_STATE_WAIT_END: /* receive end eot */ if ((1 == bytes) && (YMODEM_EOT == c)) { uart_send_byte(YMODEM_ACK); i = 0; state = YMODEM_STATE_INIT; end_flag = 1; } break; default: state = YMODEM_STATE_INIT; break; } } return YMODEM_OK; } int ymodem_upgrade(void (*func)(unsigned char *, int)) { int i = 0; int ret = 0; unsigned char c = 0; ymodem_write = func; amp_debug(MOD_STR, "Please start ymodem ... (press ctrl+c to cancel)\n"); ret = ymodem_recv_file(); if (ret != YMODEM_OK) { for(i = 0; i < 5000; i++ ) { if(uart_recv_byte(&c)) { break; } } } if(ret == YMODEM_OK) { amp_debug(MOD_STR, "Recv App Bin OK\n"); } else if(ret == YMODEM_FILE_TOOBIG) { amp_debug(MOD_STR, "file too big len:0x%08x !!!\n", ymodem_flash_size); } else { amp_debug(MOD_STR, "Ymodem recv file Err:%d !!!\n", ret); } return ret; }
YifuLiu/AliOS-Things
components/amp/services/amp_boot/amp_boot_ymodem.c
C
apache-2.0
10,249
#include "stdlib.h" #include "stdint.h" #include "string.h" #include "aos_system.h" #include "amp_memmgt.h" typedef struct amp_memmgt_rec_stru_tag { void *ptr; unsigned int size; unsigned int lr; unsigned int seq; struct amp_memmgt_rec_stru_tag *next; struct amp_memmgt_rec_stru_tag *prev; } amp_memmgt_rec_stru; static amp_memmgt_rec_stru *g_mem_rec_head = NULL; static amp_memmgt_rec_stru *g_mem_rec_tail = NULL; static amp_memmgt_config_t g_mem_config; static unsigned int g_mem_rec_num = 0; static unsigned int g_mem_max[MEMMGT_TOTAL_PT_NUM] = {0}; static unsigned int g_mem_total[MEMMGT_TOTAL_PT_NUM] = {0}; static aos_mutex_t g_mem_rec_lock = NULL; #ifdef MEMMGT_MEM_DBG_STATIC static void add_node(void *ptr, unsigned int size, unsigned int lr, int ptno) { amp_memmgt_rec_stru * node = NULL; node = g_mem_config.malloc_fn(sizeof(amp_memmgt_rec_stru)); if(NULL == node) { return; } memset(node, 0, sizeof(amp_memmgt_rec_stru)); aos_mutex_lock(&g_mem_rec_lock, AOS_WAIT_FOREVER); g_mem_rec_tail->next = node; node->prev = g_mem_rec_tail; g_mem_rec_tail = node; node->ptr = ptr; node->size = size; node->seq = g_mem_rec_num; node->lr = lr; *(unsigned int *)ptr = (unsigned int)node; g_mem_rec_num ++; aos_mutex_unlock(&g_mem_rec_lock); } static void delete_node(amp_memmgt_rec_stru *node) { if(node == NULL) { return; } aos_mutex_lock(&g_mem_rec_lock, AOS_WAIT_FOREVER); if(node == g_mem_rec_tail) { g_mem_rec_tail = node->prev; } if(NULL != node->prev) { node->prev->next = node->next; } if(NULL != node->next) { node->next->prev = node->prev; } if (g_mem_config.free_fn) { g_mem_config.free_fn(node); } aos_mutex_unlock(&g_mem_rec_lock); } #endif int amp_memmgt_init(amp_memmgt_config_t *config) { if ((config->malloc_fn == NULL) || (config->free_fn == NULL)) { return -1; } memcpy(&g_mem_config, config, sizeof(amp_memmgt_config_t)); #ifdef MEMMGT_MEM_DBG_STATIC if(NULL == g_mem_rec_head) { g_mem_rec_head = config->malloc_fn(sizeof(amp_memmgt_rec_stru)); memset(g_mem_rec_head, 0, sizeof(amp_memmgt_rec_stru)); aos_mutex_new(&g_mem_rec_lock); g_mem_rec_tail = g_mem_rec_head; } #endif return 0; } void amp_memmgt_mem_show_rec() { #ifdef MEMMGT_MEM_DBG_STATIC aos_mutex_lock(&g_mem_rec_lock, AOS_WAIT_FOREVER); amp_memmgt_rec_stru *rec_node = g_mem_rec_head; if(rec_node != NULL) { aos_printf("seq addr size LR\r\n"); while(rec_node) { if(rec_node->ptr) { aos_printf("%4u ", rec_node->seq); aos_printf("0x%x ", rec_node->ptr); aos_printf("0x%x ", rec_node->size); aos_printf("0x%x \n", rec_node->lr); } rec_node = rec_node->next; } } aos_mutex_unlock(&g_mem_rec_lock); #endif for (int i = 0; i < g_mem_config.pt_num; i++) { aos_printf("\r\nPT[%d]: max mem %u, now mem %u \n", i, g_mem_max[i], g_mem_total[i]); } } void *amp_memmgt_malloc(unsigned int size, unsigned int lr, int ptno) { void *ptr = NULL; unsigned int alloc_size = size + MEMMGT_OFFSET; unsigned int once_size = alloc_size; if(NULL == g_mem_config.malloc_fn) { return NULL; } #ifdef MEMMGT_MEM_SIZE_CHECK #ifdef MEMMGT_MEM_DBG_STATIC once_size += sizeof(amp_memmgt_rec_stru); #endif if((g_mem_config.mem_limit[ptno] != 0) && (g_mem_total[ptno] + once_size > g_mem_config.mem_limit[ptno])) { aos_printf("[amp_memory] memory leak, pt %d, size %d, lr 0x%x, total size 0x%x, limit 0x%x\n", ptno, size, lr, g_mem_total[ptno], g_mem_config.mem_limit[ptno]); return NULL; } #endif ptr = g_mem_config.malloc_fn(alloc_size); if(NULL == ptr) { aos_printf("[amp_memory%s] lr 0x%x memory alloc failed, system will stop !!!\n", __TIME__, lr); amp_memmgt_mem_show_rec(); while(1) { aos_msleep(1000); } return NULL; } g_mem_total[ptno] += alloc_size; #ifdef MEMMGT_MEM_DBG_STATIC add_node(ptr, alloc_size, lr, ptno); g_mem_total[ptno] += sizeof(amp_memmgt_rec_stru); #else *(unsigned int *)ptr = alloc_size; #endif if(g_mem_total[ptno] > g_mem_max[ptno]) { g_mem_max[ptno] = g_mem_total[ptno]; } #ifdef MEMMGT_MEM_TRACE if(((1<<ptno) & g_mem_config.trace_pt) != 0) { aos_printf("[amp_memory:%s] lr 0x%x alloc %p, size %d\n", __TIME__, lr, (void *)((unsigned int)ptr + MEMMGT_OFFSET), size); aos_printf(" now total malloc %u, max malloc %u\n", g_mem_total[ptno], g_mem_max[ptno]); } #endif return (void *)((unsigned int)ptr + MEMMGT_OFFSET); } void *amp_memmgt_realloc(void *ptr, unsigned int size, unsigned int lr, int ptno) { void *ptr_new = NULL; void *origin_ptr = NULL; unsigned int alloc_size = size + MEMMGT_OFFSET; unsigned int old_size = size; unsigned int once_size = alloc_size; if (size == 0) { amp_memmgt_free(ptr, lr, ptno); return NULL; } if(NULL == g_mem_config.realloc_fn) { return NULL; } #ifdef MEMMGT_MEM_TRACE if(((1<<ptno) & g_mem_config.trace_pt) != 0) { aos_printf("[amp_memory:%s] lr 0x%x realloc %p, size %d\n", __TIME__, lr, ptr, size); } #endif #ifdef MEMMGT_MEM_DBG_STATIC amp_memmgt_rec_stru *node = *(unsigned int *)((uint32_t)ptr - MEMMGT_OFFSET); amp_memmgt_rec_stru tmp_node; memcpy(&tmp_node, node, sizeof(amp_memmgt_rec_stru)); old_size = node->size; #else old_size = *(unsigned int *)((unsigned int)ptr - 4); #endif origin_ptr = (void *)((unsigned int)ptr - 4); #ifdef MEMMGT_MEM_SIZE_CHECK #ifdef MEMMGT_MEM_DBG_STATIC once_size += sizeof(amp_memmgt_rec_stru); #endif once_size -= old_size; if((g_mem_config.mem_limit[ptno] != 0) && (g_mem_total[ptno] + once_size > g_mem_config.mem_limit[ptno])) { aos_printf("[amp_memory:%s] memory leak, pt %d, size %d, lr 0x%x, total size 0x%x, limit 0x%x\n", __TIME__, ptno, size, lr, g_mem_total[ptno], g_mem_config.mem_limit[ptno]); return NULL; } #endif ptr_new = g_mem_config.realloc_fn(origin_ptr, alloc_size); if(NULL == ptr_new) { aos_printf("[amp_memory:%s] lr 0x%x memory realloc failed, system will stop !!!\n", __TIME__, lr); amp_memmgt_mem_show_rec(); while(1) { aos_msleep(1000); } return NULL; } g_mem_total[ptno] += alloc_size - old_size; if(g_mem_total[ptno] > g_mem_max[ptno]) { g_mem_max[ptno] = g_mem_total[ptno]; } #ifdef MEMMGT_MEM_DBG_STATIC if(origin_ptr != ptr_new) { delete_node(node); add_node(ptr_new, alloc_size, lr, ptno); } else { node->size = size; } #else *(unsigned int *)ptr_new = alloc_size; #endif #ifdef MEMMGT_MEM_TRACE if(((1<<ptno) & g_mem_config.trace_pt) != 0) { aos_printf("[amp_memory:%s] lr 0x%x realloc result %p\n", __TIME__, lr, (void *)((unsigned int)ptr_new + MEMMGT_OFFSET)); aos_printf(" now total malloc %u, max malloc %u\n", g_mem_total[ptno], g_mem_max[ptno]); } #endif return (void *)((unsigned int)ptr_new + MEMMGT_OFFSET); } void amp_memmgt_free(void *ptr, unsigned int lr, int ptno) { void *origin_ptr = (void *)((uint32_t)ptr - MEMMGT_OFFSET); unsigned int free_size = 0; if (ptr == NULL) { return; } #ifdef MEMMGT_MEM_DBG_STATIC amp_memmgt_rec_stru *node = NULL; node = (amp_memmgt_rec_stru *)(*(unsigned int *)origin_ptr); free_size = node->size; #else free_size = *(unsigned int *)((unsigned int)origin_ptr); #endif g_mem_total[ptno] -= free_size; #ifdef MEMMGT_MEM_DBG_STATIC delete_node(node); #endif g_mem_config.free_fn(origin_ptr); #ifdef MEMMGT_MEM_TRACE if(((1<<ptno) & g_mem_config.trace_pt) != 0) { aos_printf("[amp_memory:%s] lr 0x%x free %p\n", __TIME__, lr, ptr); aos_printf(" now total malloc %u, max malloc %u\n", g_mem_total[ptno], g_mem_max[ptno]); } #endif } unsigned int amp_malloc_usable_size(void *ptr) { void *origin_ptr = (void *)((uint32_t)ptr - MEMMGT_OFFSET); uint32_t size = 0; if (ptr == NULL) { return 0; } #ifdef MEMMGT_MEM_DBG_STATIC amp_memmgt_rec_stru *node = NULL; node = (amp_memmgt_rec_stru *)(*(unsigned int *)origin_ptr); if (node != NULL) { size = node->size; } #else size = *(unsigned int *)((unsigned int)origin_ptr); #endif return size - MEMMGT_OFFSET; }
YifuLiu/AliOS-Things
components/amp/services/amp_memmgt/amp_memmgt.c
C
apache-2.0
8,777
/*! * @file amp_memmgt.h * * Copyright (C) 2015-2021 Alibaba Group Holding Limited */ #ifndef _AMP_MEMMGT_H_ #define _AMP_MEMMGT_H_ #include "stdio.h" #include "stdlib.h" #include "stdint.h" //#define MEMMGT_MEM_SIZE_CHECK //#define MEMMGT_MEM_DBG_STATIC //#define MEMMGT_MEM_TRACE #define MEMMGT_TOTAL_PT_NUM 2 #define MEMMGT_OFFSET 4 typedef void * (*amp_memmgt_malloc_fn)(unsigned int size); typedef void * (*amp_memmgt_realloc_fn)(void *ptr, unsigned int size); typedef void (*amp_memmgt_free_fn)(void *ptr); typedef struct { amp_memmgt_malloc_fn malloc_fn; amp_memmgt_realloc_fn realloc_fn; amp_memmgt_free_fn free_fn; int pt_num; int trace_pt; unsigned int mem_limit[MEMMGT_TOTAL_PT_NUM]; } amp_memmgt_config_t; extern int amp_memmgt_init(amp_memmgt_config_t *config); ////////////////////////////////////////////////////////////////////////////// #ifdef __i386__ #define GET_LR(tmp_lr) tmp_lr = 0 #else #ifdef __GNUC__ #define GET_LR(tmp_lr) __asm__ __volatile__("mov %0, lr \n":"=r"(tmp_lr):) #else #define GET_LR(tmp_lr) __asm("MOV tmp_lr, lr\n") #endif #endif extern void *amp_memmgt_malloc(unsigned int size, unsigned int lr, int ptno); #define AMP_MEMMGT_MALLOC(ptr, size, ptno) \ do { \ unsigned int tmp_lr = 0; \ GET_LR(tmp_lr); \ ptr = amp_memmgt_malloc(size, tmp_lr, ptno); \ } while(0) ///////////////////////////////////////////////////////////////////////////////////////// extern void *amp_memmgt_realloc(void *ptr, unsigned int size, unsigned int lr, int ptno); #define AMP_MEMMGT_REALLOC(ptr_new, ptr, size, ptno) \ do { \ unsigned int tmp_lr = 0; \ GET_LR(tmp_lr); \ ptr_new = amp_memmgt_realloc(ptr, size, tmp_lr, ptno); \ } while(0) ///////////////////////////////////////////////////////////////////////////// extern void amp_memmgt_free(void *ptr, unsigned int lr, int ptno); #define AMP_MEMMGT_FREE(ptr, ptno) \ do { \ unsigned int tmp_lr = 0; \ GET_LR(tmp_lr); \ amp_memmgt_free(ptr, tmp_lr, ptno); \ } while(0) #endif
YifuLiu/AliOS-Things
components/amp/services/amp_memmgt/amp_memmgt.h
C
apache-2.0
2,398
#include "amp_memmgt.h" #include "aos_system.h" void amp_memory_init() { static int memory_initialized = 0; if(0 == memory_initialized) { amp_memmgt_config_t config; memset(&config, 0, sizeof(config)); config.malloc_fn = aos_malloc; config.realloc_fn = aos_realloc; config.free_fn = aos_free; config.pt_num = 2; config.trace_pt = 1; //b0001 config.mem_limit[1] = 512000; amp_memmgt_init(&config); memory_initialized = 1; } } void *amp_malloc(unsigned int size) { void *ptr = NULL; AMP_MEMMGT_MALLOC(ptr, size, 0); return ptr; } void amp_free(void *ptr) { AMP_MEMMGT_FREE(ptr, 0); } void *amp_calloc(unsigned int nitems, unsigned int size) { void *ptr = NULL; AMP_MEMMGT_MALLOC(ptr, nitems * size, 0); if (ptr) memset(ptr, 0, nitems * size); return ptr; } void *amp_realloc(void *ptr, unsigned int size) { void *ptr_new = NULL; if (ptr != NULL) { AMP_MEMMGT_REALLOC(ptr_new, ptr, size, 0); } else { AMP_MEMMGT_MALLOC(ptr_new, size, 0); } return ptr_new; }
YifuLiu/AliOS-Things
components/amp/services/amp_memmgt/amp_memory.c
C
apache-2.0
1,138
/*! * @file amp_memory.h * * Copyright (C) 2015-2021 Alibaba Group Holding Limited */ #ifndef _AMP_MEMORY_H_ #define _AMP_MEMORY_H_ void amp_memory_init(); void *amp_malloc(unsigned int size); void amp_free(void *ptr); void *amp_calloc(unsigned int nitems, unsigned int size); void *amp_realloc(void *ptr, unsigned int size); unsigned int amp_malloc_usable_size(void *ptr); void amp_memmgt_mem_show_rec(); #endif
YifuLiu/AliOS-Things
components/amp/services/amp_memmgt/amp_memory.h
C
apache-2.0
421
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include <stdio.h> #include <string.h> #include "amp_utils.h" #include "amp_defines.h" #include "aos_system.h" #define MOD_STR "AMP_UTILS" static AOS_SYSTEM_VERSION aos_version = {0}; unsigned char hex2num(unsigned char ch) { if (ch >= 'a') { return ch - 'a' + 10; } else if (ch >= 'A') { return ch - 'A' + 10; } return ch - '0'; } char itoch(int val) { if (val < 10) { return (char)('0' + val); } return (char)('a' + val - 10); } void num2hex(unsigned char ch, unsigned char *hex) { hex[0] = itoch(ch / 16); hex[1] = itoch(ch % 16); } /***************************************************************************** *Function: end_with *Description: check if str1 end with str2 *Input: str1 and str2 *Output: if str1 end with str2,return 1 else return 0 *****************************************************************************/ int end_with(char *str1, char *str2) { if (!str1 || !str2) { return 0; } int len1 = strlen(str1); int len2 = strlen(str2); if (len1 >= len2) { if (strcmp(str1 + len1 - len2, str2) == 0) { return 1; } } return 0; } /***************************************************************************** *Function: hexdump *Description: print buff with hex style *Input: title: a string, buff: the dest buff for dump,len:the buffer len *Output: none *****************************************************************************/ void amp_dump(const char *title, const void *buff, const int len) { int i, j, written; unsigned char ascii[16 + 1] = {0}; // char header[64] = {0}; unsigned char *buf = (unsigned char *)buff; written = 0; amp_debug(MOD_STR, "%s : ", title); for (i = 0; i < len; ++i) { if (i % 16 == 0) { amp_debug(MOD_STR, "| %08X: ", (unsigned int)(i + (long)buff)); written += 8; } amp_debug(MOD_STR, "%02X", buf[i]); written += 2; if (i % 2 == 1) { amp_debug(MOD_STR, " "); written += 1; } sprintf((char *)ascii + i % 16, "%c", ((buf[i] >= ' ' && buf[i] <= '~') ? buf[i] : '.')); if (((i + 1) % 16 == 0) || (i == len - 1)) { for (j = 0; j < 48 - written; ++j) { amp_debug(MOD_STR, " "); } amp_debug(MOD_STR, " %s", ascii); amp_debug(MOD_STR, ""); written = 0; memset(ascii, 0, sizeof(ascii)); } } amp_debug(MOD_STR, "%s", "+" "-----------------------" "-----------------------" "-----------------------"); return; } /** * 设置用户JS脚本版本号 * */ void aos_userjs_version_set(char *version) { if (!version) return; snprintf(aos_version.userjs, sizeof(aos_version.userjs), "%s", version); // amp_debug(MOD_STR, "version %s", aos_version.userjs); } /** * 获取用户的JS脚本版本号 * */ const char *aos_userjs_version_get(void) { // amp_debug(MOD_STR, "version %s", aos_version.userjs); return aos_version.userjs; } /** * 获取用户的JS脚本版本号 * */ const char *aos_app_version_get(void) { const char *amp_version_fmt = "amp-v%s"; aos_snprintf(aos_version.app, 64, amp_version_fmt, AMP_VERSION_NUMBER); // amp_debug(MOD_STR, "version %s", aos_version.app); return aos_version.app; } /** * 获取系统kernel软件版本号,在模组设备上即模组软件版本号 * */ const char *aos_kernel_version_get(void) { memset(aos_version.kernel, 0, AOS_VERSION_LENGTH); memcpy(aos_version.kernel, AMP_MODULE_SOFTWARE, strlen(AMP_MODULE_SOFTWARE)); // amp_debug(MOD_STR, "version %s", aos_version.kernel); return aos_version.kernel; } /** * 获取系统软件版本号,包括JS轻应用软件版本和模组软件版本 * 用于模组软件不能单独升级、只能和应用软件一起打包升级的场景 * */ const char *aos_system_version_get(void) { const char *amp_version_fmt = "amp-v%s-%s"; memset(aos_version.system, 0, AOS_VERSION_LENGTH * 2); aos_snprintf(aos_version.system, AMP_VERSION_LENGTH, amp_version_fmt, \ AMP_VERSION_NUMBER, AMP_MODULE_SOFTWARE); // amp_debug(MOD_STR, "version %s", aos_version.system); return aos_version.system; } /** * 系统软件编译时间 * */ const char *aos_system_build_time(void) { const char *amp_version_fmt = "%s, %s"; memset(aos_version.build_time, 0, 128); aos_snprintf(aos_version.build_time, AMP_VERSION_LENGTH, amp_version_fmt, \ __DATE__, __TIME__); // amp_debug(MOD_STR, "version %s", aos_version.build_time); return aos_version.build_time; } /** * 模组硬件版本 * */ const char *aos_hardware_version_get(void) { memset(aos_version.module_hardware, 0, AOS_VERSION_LENGTH); memcpy(aos_version.module_hardware, AMP_MODULE_HARDWARE, strlen(AMP_MODULE_HARDWARE)); // amp_debug(MOD_STR, "version %s", aos_version.module_hardware); return aos_version.module_hardware; }
YifuLiu/AliOS-Things
components/amp/services/amp_utils/amp_utils.c
C
apache-2.0
5,254
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #ifndef AMP_UTILS_H #define AMP_UTILS_H #if defined(__cplusplus) extern "C" { #endif #define AOS_VERSION_LENGTH 32 typedef struct { char userjs[AOS_VERSION_LENGTH]; char app[AOS_VERSION_LENGTH]; char kernel[AOS_VERSION_LENGTH]; char system[AOS_VERSION_LENGTH * 2]; char module_hardware[AOS_VERSION_LENGTH]; char product_hardware[AOS_VERSION_LENGTH]; char build_time[AOS_VERSION_LENGTH]; } AOS_SYSTEM_VERSION; unsigned char hex2num(unsigned char ch); char itoch(int val); void num2hex(unsigned char ch, unsigned char *hex); int end_with(char *str1, char *str2); void amp_dump(const char *title, const void *buff, const int len); void aos_userjs_version_set(char *version); const char *aos_userjs_version_get(void); const char *aos_app_version_get(void); const char *aos_system_version_get(void); const char *aos_system_info_get(void); const char *aos_kernel_version_get(void); const char *aos_system_build_time(void); const char *aos_hardware_version_get(void); #ifdef SUPPORT_NODE_MODELES char *getFilePath(char *name); char *getClearPath(char *path); char *getNodeModulePath(char *path); #endif #if defined(__cplusplus) } #endif #endif /* JSE_UTILS_H */
YifuLiu/AliOS-Things
components/amp/services/amp_utils/amp_utils.h
C
apache-2.0
1,254
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #include "aos/kernel.h" #include "aos/vfs.h" #include "amp_platform.h" #include "amp_config.h" #include "amp_memory.h" #include "aos_system.h" #include "aos_fs.h" #include "aos_tcp.h" #include "amp_task.h" #include "amp_errno.h" #include "amp_defines.h" #include "app_mgr.h" #include "ota_agent.h" #include "mbedtls/md5.h" #ifdef LINUXOSX #define OTA_BUFFER_MAX_SIZE 8192 #else #define OTA_BUFFER_MAX_SIZE 1536 #endif #define HTTP_HEADER \ "GET /%s HTTP/1.1\r\nAccept:*/*\r\n" \ "User-Agent: Mozilla/5.0\r\n" \ "Cache-Control: no-cache\r\n" \ "Connection: close\r\n" \ "Host:%s:%d\r\n\r\n" typedef struct { uint16_t file_count; uint16_t pack_version; uint32_t pack_size; } JSEPACK_HEADER; typedef struct { uint32_t header_size; uint32_t file_size; uint8_t md5[16]; /* uint8_t name[...]; uint8 data[]; */ } JSEPACK_FILE; static write_js_cb_t jspackcb = NULL; static JSEPACK_HEADER header; static JSEPACK_FILE fileheader; static int jspacksize = 0; static int32_t jspackfile_offset; static int32_t jspackfile_header_offset; static int32_t jspackfile_count; static int32_t jspack_done = 0; static int32_t jspack_found_error = 0; #define MOD_STR "APP_MGR" #define JSEPACK_BLOCK_SIZE (2 * 1024) extern void jsengine_exit(void); extern int aos_rmdir_r(const char *path); void apppack_init(write_js_cb_t cb) { jspackcb = cb; jspacksize = 0; jspackfile_offset = 0; jspackfile_header_offset = 0; jspack_done = 0; jspackfile_count = 0; jspack_found_error = 0; /* remove all js file */ aos_rmdir_r(AMP_FS_ROOT_DIR); aos_mkdir(AMP_FS_ROOT_DIR); } void apppack_final(void) { jspackcb = NULL; jspack_done = 1; } static amp_md5_context g_ctx; static uint8_t digest[16] = {0}; static int32_t app_file_offset = 0; static void jspackoutput(const char *filename, const uint8_t *md5, int32_t file_size, int32_t type, int32_t offset, uint8_t *buf, int32_t buf_len) { int outsize; if (offset == 0) { amp_md5_init(&g_ctx); amp_md5_starts(&g_ctx); app_file_offset = 0; } amp_md5_update(&g_ctx, buf, buf_len); if (buf_len > 0) { outsize = buf_len; if (jspackcb) { jspackcb(filename, file_size, type, app_file_offset, buf, outsize, 0); } app_file_offset += outsize; buf_len -= outsize; buf += outsize; } int32_t complete = 0; /* end of file, check MD5 */ if (file_size == app_file_offset) { amp_md5_finish(&g_ctx, digest); amp_md5_free(&g_ctx); amp_warn(MOD_STR, "0x%x 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x " "0x%x 0x%x 0x%x 0x%x", digest[0], digest[1], digest[2], digest[3], digest[4], digest[5], digest[6], digest[7], digest[8], digest[9], digest[10], digest[11], digest[12], digest[13], digest[14], digest[15]); amp_warn(MOD_STR, "0x%x 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x " "0x%x 0x%x 0x%x 0x%x", md5[0], md5[1], md5[2], md5[3], md5[4], md5[5], md5[6], md5[7], md5[8], md5[9], md5[10], md5[11], md5[12], md5[13], md5[14], md5[15]); jspackfile_count--; if (jspackfile_count == 0) { jspack_done = 1; } if (memcmp(digest, md5, 16) == 0) { complete = 1; /* check success */ } else { complete = -1; jspack_found_error = 1; jspack_done = 1; } if (jspackcb) { jspackcb(filename, app_file_offset, type, app_file_offset, NULL, 0, complete); } } } #define JSEPACK_HEADER_SIZE 8 /* sizeof(JSEPACK_HEADER) */ #define JSEPACK_FILE_HEADER 24 /* sizeof(JSEPACK_FILE) exclude filename */ static uint32_t g_file_header_size = 24 + 1; static char *g_file_name = NULL; /* report process state */ void apppack_post_process_state(void) { char msg[128]; if (jspacksize >= JSEPACK_HEADER_SIZE) { sprintf(msg, "%d/%lu", jspacksize, header.pack_size); } } /* analysis recursive */ int apppack_update(uint8_t *ptr, int size) { int len = 0; uint8_t *pdst; if (jspack_found_error) { return -1; } if ((size < 1) || (jspack_done)) { amp_debug(MOD_STR, "size: %d, jspack_done: %d", size, jspack_done); return 0; } amp_debug(MOD_STR, "jspacksize = %d size=%d ", jspacksize, size); amp_debug(MOD_STR, "jspackfile_header_offset = %d ", jspackfile_header_offset); amp_debug(MOD_STR, "g_file_header_size = %d ", g_file_header_size); /* parse file header */ if (jspacksize == 0) { if (size > JSEPACK_HEADER_SIZE) { jspacksize = JSEPACK_HEADER_SIZE; } else { jspacksize = size; } memcpy(&header, ptr, jspacksize); if (jspacksize < JSEPACK_HEADER_SIZE) { return 0; } return apppack_update(ptr + jspacksize, size - jspacksize); } else if (jspacksize < JSEPACK_HEADER_SIZE) { len = JSEPACK_HEADER_SIZE - jspacksize; if (len > size) { len = size; } pdst = (uint8_t *)&header; memcpy(pdst + jspacksize, ptr, len); jspacksize += len; return apppack_update(ptr + len, size - len); } else if (jspacksize == JSEPACK_HEADER_SIZE) { /* start parse file header */ jspackfile_count = header.file_count; amp_warn(MOD_STR, "file_count = %d ", header.file_count); amp_warn(MOD_STR, "pack_version = %d ", header.pack_version); amp_warn(MOD_STR, "pack_size = %d ", header.pack_size); /* reset jspackfile_header_offset */ len = JSEPACK_FILE_HEADER; /* sizeof(JSEPACK_FILE) */ if (len > size) { len = size; } memcpy(&fileheader, ptr, len); jspackfile_header_offset = len; jspacksize += len; jspackfile_offset = 0; return apppack_update(ptr + len, size - len); } else if (jspackfile_header_offset < JSEPACK_FILE_HEADER) { amp_warn(MOD_STR, "jspackfile_header_offset = %d size=%d ", jspackfile_header_offset, size); len = JSEPACK_FILE_HEADER - jspackfile_header_offset; /* sizeof(JSEPACK_FILE) */ if (len > size) { len = size; } pdst = (uint8_t *)&fileheader; memcpy(pdst + jspackfile_header_offset, ptr, len); jspackfile_header_offset += len; jspacksize += len; jspackfile_offset = 0; return apppack_update(ptr + len, size - len); } else if (jspackfile_header_offset == JSEPACK_FILE_HEADER) { /* read g_file_header_size */ amp_warn(MOD_STR, "file_size = %d", fileheader.file_size); amp_warn(MOD_STR, "header_size = %d", fileheader.header_size); g_file_header_size = fileheader.header_size; amp_warn(MOD_STR, "update g_file_header_size = %d", g_file_header_size); amp_warn(MOD_STR, "filename len = %d", g_file_header_size - JSEPACK_FILE_HEADER); if (g_file_name) { amp_free(g_file_name); } g_file_name = amp_calloc(1, g_file_header_size - JSEPACK_FILE_HEADER + 1); /* get file name */ len = g_file_header_size - JSEPACK_FILE_HEADER; if (len > size) { /* part of file name */ len = size; } memcpy(g_file_name, ptr, len); jspackfile_header_offset += len; jspacksize += len; return apppack_update(ptr + len, size - len); } else if (jspackfile_header_offset < g_file_header_size) { /* read rest length of file name */ len = g_file_header_size - jspackfile_header_offset; if (len > size) { /* part of file name */ len = size; } int offset = jspackfile_header_offset - JSEPACK_FILE_HEADER; amp_warn(MOD_STR, "get filename, offset = %d len = %d", offset, len); memcpy(g_file_name + offset, ptr, len); jspackfile_header_offset += len; jspacksize += len; return apppack_update(ptr + len, size - len); } else if (jspackfile_header_offset == g_file_header_size) { if (jspackfile_offset == 0) { amp_warn(MOD_STR, "name = %s", g_file_name); amp_warn(MOD_STR, "file_size = %d", fileheader.file_size); len = fileheader.file_size; } else { len = fileheader.file_size - jspackfile_offset; } if (len > size) { len = size; } /* max length */ if (len > JSEPACK_BLOCK_SIZE) { len = JSEPACK_BLOCK_SIZE; } /* parse file */ jspackoutput(g_file_name, fileheader.md5, fileheader.file_size, 3, jspackfile_offset, ptr, len); jspacksize += len; jspackfile_offset += len; amp_warn(MOD_STR, "jspackfile_offset = %d file_size = %d", jspackfile_offset, fileheader.file_size); if (jspackfile_offset == fileheader.file_size) { /* next file */ jspackfile_header_offset = 0; jspackfile_offset = 0; /* reset g_file_header_size to default */ g_file_header_size = 24 + 1; if (jspackfile_count > 0) amp_warn(MOD_STR, "parse next file"); else amp_warn(MOD_STR, "app pack parse complete"); } amp_warn(MOD_STR, "jspacksize = %d len = %d", jspacksize, len); return apppack_update(ptr + len, size - len); } amp_warn(MOD_STR, "jspackfile_header_offset = %d", jspackfile_header_offset); amp_warn(MOD_STR, "g_file_header_size = %d", g_file_header_size); amp_warn(MOD_STR, "apppack check file content fail"); return -1; } /** * @brief http_gethost_info * * @Param: src url * @Param: web WEB * @Param: file download filename * @Param: port default 80 */ static void http_gethost_info(char *src, char **web, char **file, int *port) { char *pa; char *pb; int isHttps = 0; if (!src || strlen(src) == 0) { amp_warn(MOD_STR, "http_gethost_info parms error!"); return; } amp_warn(MOD_STR, "src = %s %d", src, strlen(src)); *port = 0; if (!(*src)) { return; } pa = src; if (!strncmp(pa, "https://", strlen("https://"))) { pa = src + strlen("https://"); isHttps = 1; } if (!isHttps) { if (!strncmp(pa, "http://", strlen("http://"))) { pa = src + strlen("http://"); } } *web = pa; pb = strchr(pa, '/'); if (pb) { *pb = 0; pb += 1; if (*pb) { *file = pb; *((*file) + strlen(pb)) = 0; } } else { (*web)[strlen(pa)] = 0; } pa = strchr(*web, ':'); if (pa) { *pa = 0; *port = atoi(pa + 1); } else { /* TODO: support https:443 if (isHttps) { *port = 80; } else { *port = 80; } */ *port = 80; } } int apppack_download(char *url, download_js_cb_t func) { int ret = 0; int sockfd = 0; int port = 0; int nbytes = 0; int send = 0; int totalsend = 0; int size = 0; int header_found = 0; char *pos = 0; int file_size = 0; char *host_file = NULL; char *host_addr = NULL; char script_dir[128] = {0}; amp_warn(MOD_STR, "url = %s", url); if (!url || strlen(url) == 0 || func == NULL) { amp_warn(MOD_STR, "ota_download parms error!"); return OTA_DOWNLOAD_INIT_FAIL; } char *http_buffer = amp_malloc(OTA_BUFFER_MAX_SIZE); amp_warn(MOD_STR, "http_buffer = %p", http_buffer); http_gethost_info(url, &host_addr, &host_file, &port); if (host_file == NULL || host_addr == NULL) { ret = OTA_DOWNLOAD_INIT_FAIL; amp_free(http_buffer); return ret; } amp_warn(MOD_STR, "upgrade_socket_connect %s %d", host_addr, port); sockfd = aos_tcp_establish(host_addr, port); if (sockfd < 0) { amp_warn(MOD_STR, "upgrade_socket_connect error"); ret = OTA_DOWNLOAD_CON_FAIL; amp_free(http_buffer); return ret; } sprintf(http_buffer, HTTP_HEADER, host_file, host_addr, port); send = 0; totalsend = 0; nbytes = strlen(http_buffer); amp_warn(MOD_STR, "send %s", http_buffer); while (totalsend < nbytes) { send = aos_tcp_write(sockfd, http_buffer + totalsend, nbytes - totalsend, 3000); if (send == -1) { amp_warn(MOD_STR, "send error!%s", strerror(errno)); ret = OTA_DOWNLOAD_REQ_FAIL; goto DOWNLOAD_END; } totalsend += send; amp_warn(MOD_STR, "%d bytes send OK!", totalsend); } #ifdef LINUXOSX /* clean the root direcoty when user update app */ be_osal_rmdir(JSE_FS_ROOT_DIR); #else snprintf(script_dir, 128, AMP_APP_INDEX_JS); aos_remove(script_dir); #endif memset(http_buffer, 0, OTA_BUFFER_MAX_SIZE); while (1) { nbytes = aos_tcp_read(sockfd, http_buffer, OTA_BUFFER_MAX_SIZE - 1, 3000); if (nbytes == 0) { break; } if (nbytes < 0) { amp_warn(MOD_STR, "upgrade_socket_recv nbytes < 0"); if (errno != EINTR) { break; } if (sockfd < 0) { amp_warn(MOD_STR, "download system error %s", strerror(errno)); break; } else { continue; } } if (!header_found) { if (!file_size) { char *ptr = strstr(http_buffer, "Content-Length:"); if (ptr) { sscanf(ptr, "%*[^ ]%d", &file_size); } } pos = strstr(http_buffer, "\r\n\r\n"); if (!pos) { /* header pos */ /* memcpy(headbuf, http_buffer, OTA_BUFFER_MAX_SIZE); */ } else { pos += 4; int len = pos - http_buffer; header_found = 1; size = nbytes - len; if (size <= 0) { break; } func((uint8_t *)pos, size); if (size == file_size) { nbytes = 0; break; } memset(http_buffer, 0, OTA_BUFFER_MAX_SIZE); } continue; } size += nbytes; amp_debug(MOD_STR, "receive data len: %d, total recvSize: %d, get fileSize: %d", nbytes, size, file_size); func((uint8_t *)http_buffer, nbytes); if (size == file_size) { nbytes = 0; break; } memset(http_buffer, 0, OTA_BUFFER_MAX_SIZE); } amp_debug(MOD_STR, "file recv done: %d", nbytes); if (nbytes < 0) { amp_warn(MOD_STR, "download read error %s", strerror(errno)); ret = OTA_DOWNLOAD_RECV_FAIL; } else if (nbytes == 0) { ret = OTA_SUCCESS; } else { /* can never reach here */ /* ret = OTA_INIT_FAIL; */ } DOWNLOAD_END: amp_debug(MOD_STR, "DOWNLOAD_END, sockfd: %d ", sockfd); aos_tcp_destroy(sockfd); amp_debug(MOD_STR, "upgrade_socket_close, sockfd: %d ", sockfd); amp_debug(MOD_STR, "http_buffer free :%p", http_buffer); amp_free(http_buffer); amp_debug(MOD_STR, "http_buffer free done"); return ret; } static int32_t update_done = 1; static int app_fp = -1; int write_app_pack(const char *filename, int32_t file_size, int32_t type, int32_t offset, uint8_t *buf, int32_t buf_len, int32_t complete) { /* char path[64]; */ int ret; amp_debug(MOD_STR, "file_size=%d, offset = %d buf_len = %d complete = %d", file_size, offset, buf_len, complete); if (offset == 0) { app_fp = app_mgr_open_file(filename); amp_debug(MOD_STR, "app_mgr_open_file %s", filename); } if (app_fp >= 0) { if (buf_len > 0) { ret = aos_write(app_fp, buf, buf_len); } if ((offset + buf_len) == file_size) { ret = aos_sync(app_fp); ret = aos_close(app_fp); app_fp = -1; amp_warn(MOD_STR, "jse_close return %d", ret); } } if (complete != 0) { /* check failed */ if (app_fp >= 0) { ret = aos_sync(app_fp); ret = aos_close(app_fp); app_fp = -1; } amp_warn(MOD_STR, "file verify %s", (complete == 1 ? "success" : "failed")); return -1; } return 0; } int download_apppack(uint8_t *buf, int32_t buf_len) { amp_warn(MOD_STR, "download buf len = %d", buf_len); apppack_update(buf, buf_len); // amp_warn(MOD_STR, "apppack_post_process_state"); // apppack_post_process_state(); return 0; } void be_jse_task_restart_entrance(void *data) { amp_debug(MOD_STR, "[APPENGINE.D] appengine will restart ..."); amp_task_main(); aos_task_exit(0); return; } extern void *task_mutex; extern aos_sem_t jse_task_exit_sem; extern int upgrading; static void download_work(void *arg) { int ret; aos_task_t restart_task; // amp_warn(MOD_STR, "download_work task name=%s", jse_osal_get_taskname()); amp_warn(MOD_STR, "url=%s", (char *)arg); ret = apppack_download((char *)arg, download_apppack); amp_debug(MOD_STR, "apppack_download done:%d", ret); apppack_final(); update_done = 1; /* clear jsengine timer */ amp_module_free(); // aos_free(arg); if (ret == 0) { amp_warn(MOD_STR, "Upgrade app success"); aos_msleep(200); } amp_warn(MOD_STR, "reboot ..."); upgrading = 0; amp_task_exit_call(NULL, NULL); // jse_system_reboot(); amp_warn(MOD_STR, "waiting jse taks exit completely\n"); aos_sem_wait(&jse_task_exit_sem, AOS_WAIT_FOREVER); aos_msleep(50); amp_debug(MOD_STR, "amp restart task will create"); if (aos_task_new_ext(&restart_task, "amp_restart", be_jse_task_restart_entrance, NULL, JSENGINE_TASK_STACK_SIZE, AOS_DEFAULT_APP_PRI) != 0) { amp_warn(MOD_STR, "jse osal task failed!"); return; } aos_task_exit(0); return; } int32_t app_js_restart() { int32_t ret = -1; aos_task_t restart_task; amp_debug(MOD_STR, "amp restart task will create"); ret = aos_task_new_ext(&restart_task, "amp_restart", be_jse_task_restart_entrance, NULL, JSENGINE_TASK_STACK_SIZE, AOS_DEFAULT_APP_PRI); if (ret != 0) { amp_warn(MOD_STR, "jse osal task failed!"); return ret; } return ret; } void app_js_stop() { amp_task_exit_call(NULL, NULL); amp_warn(MOD_STR, "waiting jse task exit completely\n"); aos_sem_wait(&jse_task_exit_sem, AOS_WAIT_FOREVER); aos_msleep(50); amp_debug(MOD_STR, "amp task exit completely\n"); } int apppack_upgrade(char *url) { upgrading = 1; aos_task_t upgrade_task; amp_warn(MOD_STR, "apppack_upgrade url=%s ", (char *)url); if (update_done) { update_done = 0; apppack_init(write_app_pack); amp_warn(MOD_STR, "create upgrade task ..."); if (aos_task_new_ext(&upgrade_task, "amp_upgrade", download_work, (void *)url, 1024 * 6, AOS_DEFAULT_APP_PRI) != 0) { update_done = 1; apppack_final(); amp_warn(MOD_STR, "jse_osal_task_new fail"); return -1; } } else { amp_free(url); amp_warn(MOD_STR, "apppack upgrading..."); } return 0; } #ifdef LINUXOSX static int upgrading_mutex = 0; static int upgrade_file_size = 0; int upgrade_simulator_reply(uint8_t *buf, int32_t buf_len) { char msg[64] = {0}; static int last_buf_len = 0; static int total_recv = 0; total_recv += buf_len; sprintf(msg, "%d/%d", total_recv, upgrade_file_size); if (((total_recv - last_buf_len) > OTA_BUFFER_MAX_SIZE * 2) || total_recv >= upgrade_file_size) { amp_debug(MOD_STR, "upgrade_simulator_reply lastbuf=%d %s", last_buf_len, msg); if (total_recv == upgrade_file_size) { last_buf_len = 0; total_recv = 0; } else { last_buf_len = total_recv; } } } static void upgrade_simulator_work(upgrade_image_param_t *arg) { int ret; amp_warn(MOD_STR, "url=%s ,size=%d", (char *)arg->url, arg->file_size); ret = apppack_download((char *)arg->url, upgrade_simulator_reply); upgrading_mutex = 0; amp_free(arg); amp_free(arg->url); if (ret == OTA_DOWNLOAD_FINISH) { amp_warn(MOD_STR, "Upgrade app success"); jse_osal_delay(200); } amp_warn(MOD_STR, "reboot ..."); jse_system_reboot(); jse_osal_exit_task(0); } int simulator_upgrade(upgrade_image_param_t *p_info) { amp_warn(MOD_STR, "simulator_upgrade url=%s %d", p_info->url, p_info->file_size); if (upgrading_mutex == 0) { upgrading_mutex = 1; upgrade_file_size = p_info->file_size; amp_warn(MOD_STR, "simulator_upgrade ..."); if (jse_osal_new_task("simulator_upgrade", upgrade_simulator_work, p_info, 1024 * 4, NULL) != 0) { amp_warn(MOD_STR, "jse_osal_task_new fail"); upgrading_mutex = 0; return -1; } } else { amp_free(p_info); amp_warn(MOD_STR, "simulator_upgrading..."); } return 0; } #endif /* max length 192 */ int app_mgr_open_file(const char *targetname) { int fp; char path[256] = {0}; if (targetname == NULL) { return -1; } strncat(path, AMP_FS_ROOT_DIR"/", sizeof(path) - 1); strncat(path, targetname, sizeof(path) - 1); int i = 1; int len = strlen(path); for (; i < len; i++) { if (path[i] == '/') { path[i] = 0; aos_mkdir(path); path[i] = '/'; } } fp = aos_open(path, O_WRONLY | O_CREAT | O_TRUNC); return fp; }
YifuLiu/AliOS-Things
components/amp/services/app_mgr/app_mgr.c
C
apache-2.0
22,760
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #ifndef APP_MGR_H #define APP_MGR_H #include <stdio.h> #include <string.h> // #include <unistd.h> /* complete = 0 success, 1 check success(EOF), -1 check failed */ typedef int (*write_js_cb_t)(const char *filename, int32_t file_size, int32_t type, int32_t offset, uint8_t *buf, int32_t buf_len, int32_t complete); /* write js file into filesystem, callback function */ int write_app_pack(const char *filename, int32_t file_size, int32_t type, int32_t offset, uint8_t *buf, int32_t buf_len, int32_t complete); /* js pack parser */ void apppack_init(write_js_cb_t cb); int apppack_update(uint8_t *ptr, int size); void apppack_final(void); /* report process state to webIDE */ void apppack_post_process_state(void); /* get apppack from URL */ typedef int (*download_js_cb_t)(uint8_t *buf, int32_t buf_len); int apppack_download(char *url, download_js_cb_t func); /* get apppack and upgrade from URL */ int apppack_upgrade(char *url); #ifdef LINUXOSX typedef struct { char *url; int file_size; char md5[32 + 1]; int type; } upgrade_image_param_t; int simulator_upgrade(upgrade_image_param_t *p_info); #endif int app_mgr_open_file(const char *targetname); void app_js_stop(void); int32_t app_js_restart(void); #endif /* APP_MGR_H */
YifuLiu/AliOS-Things
components/amp/services/app_mgr/app_mgr.h
C
apache-2.0
1,420
/* * Copyright (C) 2015-2021 Alibaba Group Holding Limited */ #include "aos/kernel.h" #include "amp_platform.h" #include "aos_system.h" #include "amp_defines.h" #include "amp_utils.h" #include "app_mgr.h" #include "app_upgrade.h" #include "ota_agent.h" #include "aiot_state_api.h" #define MOD_STR "APP_UPGRADE" static ota_store_module_info_t module_info[3]; static ota_service_t internal_ctx = {0}; static char module_version[128] = {0}; extern int32_t app_js_restart(); extern void app_js_stop(); int ota_get_js_install_path(char *store_file_full_path, char *path_buf, int path_buf_len); int ota_file_plus_name(char *file_path1, char *file_path2, char *new_path, int new_path_len); int ota_service_maindev_fs_start(ota_service_t *ctx); void internal_module_upgrade_start(void *ctx); char *ota_get_module_ver(void* pctx, char *module_name) { int ret = 0; ota_store_module_info_t module_info; ota_service_t *ctx = (ota_service_t *)pctx; if ((pctx != NULL) && (module_name != NULL)) { if (strncmp(module_name, AMP_OTA_MODULE_NAME, strlen(module_name)) == 0) { char app_js_full_path[128] = {0}; char js_install_path[64] = {0}; memset(module_version, 0x00, sizeof(module_version)); ret = ota_get_module_information(ctx, module_name, &module_info); if (ret < 0) { amp_error(MOD_STR, "get store module info failed\n"); goto INTERNAL_M_VER_OVER; } ret = ota_get_js_install_path(module_info.store_path, js_install_path, sizeof(js_install_path)); if (ret < 0) { amp_error(MOD_STR, "get js install path failed!"); goto INTERNAL_M_VER_OVER; } ret = ota_file_plus_name(js_install_path, "app.json", app_js_full_path, sizeof(app_js_full_path)); if ((ret < 0)) { amp_error(MOD_STR, "module get js version failed!"); goto INTERNAL_M_VER_OVER; } ret = ota_jsapp_version_get(module_version, app_js_full_path); if ((ret < 0)) { amp_error(MOD_STR, "app.json path get failed!"); } } else if (strncmp(module_name, "default", strlen(module_name)) == 0) { strncpy(module_version, aos_app_version_get(), sizeof(aos_app_version_get())); } } else { amp_error(MOD_STR, "get store file path failed, path buf too short\n"); } INTERNAL_M_VER_OVER: if (ret < 0) { amp_error(MOD_STR, "app.json ver get failed! set default ver"); strncpy(module_version, "0.0.0", 5); } return module_version; } int ota_get_js_install_path(char *store_file_full_path, char *path_buf, int path_buf_len) { int ret = -1; int store_file_path_len = 0; int want_copy_len = 0; if ((store_file_full_path != NULL) && (path_buf != NULL)) { store_file_path_len = strlen(store_file_full_path); for (want_copy_len = store_file_path_len - 1; want_copy_len > 0; want_copy_len--) { if (store_file_full_path[want_copy_len] == '/') { break; } } if (want_copy_len > 0) { want_copy_len++; if (want_copy_len < path_buf_len) { ret = 0; memset(path_buf, 0x00, path_buf_len); strncpy(path_buf, store_file_full_path, want_copy_len); amp_debug(MOD_STR, "get store file path:%s\n", path_buf); } else { amp_error(MOD_STR, "get store file path failed, path buf too short\n"); } } } return ret; } int ota_file_plus_name(char *file_path1, char *file_path2, char *new_path, int new_path_len) { int ret = -1; int file_path1_len = 0; int file_path2_len = 0; if ((file_path1 == NULL) || (file_path2 == NULL) || (new_path == NULL)) { return ret; } file_path1_len = strlen(file_path1); file_path2_len = strlen(file_path2); memset(new_path, 0x00, new_path_len); if (file_path1_len + file_path2_len < new_path_len) { strncpy(new_path, file_path1, file_path1_len); if (new_path[file_path1_len - 1] != '/') { new_path[file_path1_len++] = '/'; } strncpy(&new_path[file_path1_len], file_path2, file_path2_len); ret = 0; } return ret; } int ota_load_jsapp(void *ota_ctx) { int ret = -1; ota_service_t *ctx = ota_ctx; ret = app_js_restart(); if (ret < 0) { amp_error(MOD_STR, "module load failed\n"); if ((ctx != NULL) && (ctx->report_func.report_status_cb != NULL)) { ctx->report_func.report_status_cb(ctx->report_func.param, ret); } } if ((ctx != NULL) && (ctx->feedback_func.on_user_event_cb != NULL)) { ctx->feedback_func.on_user_event_cb(OTA_EVENT_LOAD, ret, ctx->feedback_func.param); } return ret; } int ota_service_maindev_fs_start(ota_service_t *ctx) { int ret = 0; ota_boot_param_t ota_param = {0}; ota_store_module_info_t module_info = {0}; if (ctx == NULL) { return OTA_DOWNLOAD_INIT_FAIL; } ret = ota_read_parameter(&ota_param); if (ret < 0) { goto MAINDEV_FS_EXIT; } amp_debug(MOD_STR, "download start upg_flag:0x%x\n", ota_param.upg_flag); ret = ota_get_module_information(ctx, ctx->module_name, &module_info); if (ret < 0) { amp_error(MOD_STR, "get store module info failed\n"); goto MAINDEV_FS_EXIT; } amp_debug(MOD_STR, "file_path = %s\rn", module_info.store_path); ret = ota_download_to_fs_service(ctx, module_info.store_path); if (ret < 0) { amp_error(MOD_STR, "module download failed!"); goto MAINDEV_FS_EXIT; } MAINDEV_FS_EXIT: amp_debug(MOD_STR, "Download complete, rebooting ret:%d.\n", ret); if (ret < 0) { if (ctx->report_func.report_status_cb != NULL) { ctx->report_func.report_status_cb(ctx->report_func.param, ret); } ret = ota_clear(); if (ret < 0) { amp_error(MOD_STR, "clear ota failed\n"); } /* give same time to sync err msg to cloud*/ ota_msleep(3000); } else { ret = aos_fota_image_local_copy(module_info.store_path, ota_param.len); if (ret < 0) { amp_error(MOD_STR, "ota local copy failed\n"); if (ctx->report_func.report_status_cb != NULL) { ctx->report_func.report_status_cb(ctx->report_func.param, ret); } ota_msleep(1500); } } ota_reboot(); aos_task_exit(0); return ret; } /* system image upgrade */ static int32_t internal_upgrade_cb(void *pctx, char *ver, char *module_name) { int32_t ret = OTA_TRANSPORT_PAR_FAIL; aos_task_t internal_ota_task; char *current_ver = NULL; if ((pctx == NULL) || (ver == NULL) || (module_name == NULL)) { amp_error(MOD_STR, "amp:ota triggered param err!"); return ret; } if (strncmp(module_name, "default", strlen(module_name)) == 0) { ret = STATE_SUCCESS; current_ver = ota_get_module_ver(pctx, module_name); if (strncmp(ver, current_ver, strlen(ver)) <= 0) { ret = OTA_TRANSPORT_VER_FAIL; amp_error(MOD_STR, "amp ota version too old!"); } else { amp_debug(MOD_STR, "ota version:%s is coming, if OTA upgrade or not ?\n", ver); /* clear jsengine timer, distory js app*/ amp_module_free(); app_js_stop(); if (aos_task_new_ext(&internal_ota_task, "amp_internal_ota", internal_sys_upgrade_start, (void *)pctx, 1024 * 8, AOS_DEFAULT_APP_PRI) != 0) { amp_debug(MOD_STR, "internal ota task create failed!"); ret = OTA_TRANSPORT_PAR_FAIL; } amp_debug(MOD_STR, "app management center start"); } } else { current_ver = ota_get_module_ver(pctx, module_name); if (current_ver != NULL) { ret = STATE_SUCCESS; if (strncmp(ver, current_ver, strlen(ver)) <= 0) { ret = OTA_TRANSPORT_VER_FAIL; amp_error(MOD_STR, "submodule jsapp ota version too old!"); } else { amp_debug(MOD_STR, "ota module version:%s is coming, if OTA module upgrade or not ?\n", ver); /* clear jsengine timer, distory js app*/ amp_module_free(); app_js_stop(); if (aos_task_new_ext(&internal_ota_task, "amp_moudle_ota", internal_module_upgrade_start, (void *)pctx, 1024 * 8, AOS_DEFAULT_APP_PRI) != 0) { amp_debug(MOD_STR, "internal ota task create failed!"); ret = OTA_TRANSPORT_PAR_FAIL; } amp_debug(MOD_STR, "app management center start"); } } } return ret; } /* app upgrade service */ int32_t amp_app_upgrade_service(void *mqtt_handle) { int res = STATE_SUCCESS; int productkey_len = IOTX_PRODUCT_KEY_LEN; int productsecret_len = IOTX_PRODUCT_SECRET_LEN; int devicename_len = IOTX_DEVICE_NAME_LEN; int devicesecret_len = IOTX_DEVICE_SECRET_LEN; char *current_ver = NULL; ota_service_param_reset(&internal_ctx); memset(module_info, 0x00, sizeof(module_info)); ota_register_module_store(&internal_ctx, module_info, 3); /* get device info */ aos_kv_get(AMP_INTERNAL_PRODUCTKEY, internal_ctx.pk, &productkey_len); aos_kv_get(AMP_INTERNAL_PRODUCTSECRET, internal_ctx.ps, &productsecret_len); aos_kv_get(AMP_INTERNAL_DEVICENAME, internal_ctx.dn, &devicename_len); aos_kv_get(AMP_INTERNAL_DEVICESECRET, internal_ctx.ds, &devicesecret_len); ota_register_trigger_msg_cb(&internal_ctx, (void *)internal_upgrade_cb, NULL); internal_ctx.mqtt_client = (void *)mqtt_handle; ota_set_module_information(&internal_ctx, AMP_OTA_MODULE_NAME, SUBDEV_FILE_PATH, OTA_UPGRADE_CUST); ota_set_module_information(&internal_ctx, "default", OS_APP_PATH, OTA_UPGRADE_ALL); /* init ota service */ res = ota_service_init(&internal_ctx); if (res < STATE_SUCCESS) { amp_error(MOD_STR, "internal ota init failed!"); } amp_warn(MOD_STR, "internal ota init success!"); /*custom report version*/ current_ver = ota_get_module_ver(&internal_ctx, "default"); res = ota_report_module_version(&internal_ctx, "default", current_ver); if (res < STATE_SUCCESS) { amp_error(MOD_STR, "amp ota report ver failed!"); } current_ver = ota_get_module_ver(&internal_ctx, AMP_OTA_MODULE_NAME); res = ota_report_module_version(&internal_ctx, AMP_OTA_MODULE_NAME, current_ver); if (res < STATE_SUCCESS) { amp_error(MOD_STR, "amp jsota report ver failed!"); return -1; } return STATE_SUCCESS; }
YifuLiu/AliOS-Things
components/amp/services/app_mgr/app_upgrade.c
C
apache-2.0
10,875
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #ifndef APP_UPGRADE_H #define APP_UPGRADE_H #include <stdint.h> #define AMP_OTA_MODULE_NAME "jsapp" #define SUBDEV_FILE_PATH AMP_FS_ROOT_DIR"/pack.bin" #define JS_JSON_PATH AMP_FS_ROOT_DIR"/js.json" #define OS_APP_PATH AMP_FS_ROOT_DIR"/os_app.bin" #define OS_KERNEL_PATH AMP_FS_ROOT_DIR"/os_kernel.bin" int ota_load_jsapp(void *ota_ctx); int32_t amp_app_upgrade_service(void *mqtt_handle); void internal_sys_upgrade_start(void *ctx); #endif /* APP_UPGRADE_H */
YifuLiu/AliOS-Things
components/amp/services/app_mgr/app_upgrade.h
C
apache-2.0
550
/* * Copyright (C) 2015-2021 Alibaba Group Holding Limited */ #include "amp_platform.h" #include "aos_system.h" #include "aos_ota.h" #include "amp_defines.h" #include "amp_task.h" #include "app_mgr.h" #include "app_upgrade.h" #include "ota_agent.h" #include "ota_import.h" // #include "ota_hal_os.h" #include "aiot_state_api.h" #include "upack_data_file.h" #define MOD_STR "APP_UPGRADE" #if defined(__ICCARM__) #define AMP_WEAK __weak #else #define AMP_WEAK __attribute__((weak)) #endif int ota_get_js_install_path(char *store_file_full_path, char *path_buf, int path_buf_len); int ota_file_plus_name(char *file_path1, char *file_path2, char *new_path, int new_path_len); int ota_service_maindev_fs_start(ota_service_t *ctx); OTA_WEAK int ota_jsapp_version_get(char *version, char *file_path) { int ret = -1; int i = 0; int fd = -1; char read_buf[65]; int read_len = 0; char *pos = 0; if ((version != NULL) && (file_path != NULL)) { ret = 0; fd = ota_fopen(file_path, O_RDONLY); if (fd < 0) { OTA_LOG_I("can't find app.json file\r\n"); strcpy(version, "0.0.0"); } else { memset(read_buf, 0x00, sizeof(read_buf)); read_len = ota_fread(fd, read_buf, sizeof(read_buf) - 1); if (read_len > 13) { pos = strstr(read_buf, "\"version\":"); if (pos != NULL) { pos += 10; while (pos[0] != '"') { pos++; } pos++; while (pos[0] != '"') { version[i++] = pos[0]; pos++; } version[i] = 0; } } } if (fd >= 0) { ota_fclose(fd); } } return ret; } int ota_install_jsapp(void *ota_ctx, char *store_file, int store_file_len, char *install_path) { int ret = -1; ota_service_t *ctx = ota_ctx; if ((store_file != NULL) && (install_path != NULL)) { ret = data_file_unpack(store_file, store_file_len, install_path); } if (ret < 0) { if ((ctx != NULL) && (ctx->report_func.report_status_cb != NULL)) { ctx->report_func.report_status_cb(ctx->report_func.param, ret); } } if ((ctx != NULL) && (ctx->feedback_func.on_user_event_cb != NULL)) { ctx->feedback_func.on_user_event_cb(OTA_EVENT_INSTALL, ret, ctx->feedback_func.param); } return ret; } AMP_WEAK int aos_fota_image_local_copy(char *image_name, int image_size) { amp_error(MOD_STR, "local copy code is invalid, weak function failed!"); return -1; } AMP_WEAK void internal_sys_upgrade_start(void *ctx) { amp_debug(MOD_STR, "internal sys upgrade start weak function\n"); ota_service_maindev_fs_start((ota_service_t *)ctx); return; } AMP_WEAK void internal_module_upgrade_start(void *ctx) { int ret = -1; ota_service_t *tmp_ctx = (ota_service_t *)ctx; char version[64] = {0}; char js_install_path[64] = {0}; char app_js_full_path[128] = {0}; ota_store_module_info_t module_info; ota_boot_param_t ota_param = {0}; if (tmp_ctx == NULL) { amp_error(MOD_STR, "internal module ota input ctx is null\n"); return; } ret = ota_read_parameter(&ota_param); if (ret < 0) { amp_error(MOD_STR, "get store ota param info failed\n"); goto INTERNAL_M_OTA_OVER; } ret = ota_get_module_information(tmp_ctx, tmp_ctx->module_name, &module_info); if (ret < 0) { amp_error(MOD_STR, "get store module info failed\n"); goto INTERNAL_M_OTA_OVER; } amp_debug(MOD_STR, "file_path = %s\rn", module_info.store_path); ret = ota_download_to_fs_service(ctx, module_info.store_path); if (ret < 0) { amp_error(MOD_STR, "module download failed!"); goto INTERNAL_M_OTA_OVER; } ret = ota_get_js_install_path(module_info.store_path, js_install_path, sizeof(js_install_path)); if (ret < 0) { amp_error(MOD_STR, "get js install path failed!"); goto INTERNAL_M_OTA_OVER; } ret = ota_install_jsapp(ctx, module_info.store_path, ota_param.len, js_install_path); if (ret < 0) { amp_error(MOD_STR, "module install failed!"); goto INTERNAL_M_OTA_OVER; } ret = ota_load_jsapp(ctx); if (ret < 0) { amp_error(MOD_STR, "module load failed!"); goto INTERNAL_M_OTA_OVER; } ret = ota_file_plus_name(js_install_path, "app.json", app_js_full_path, sizeof(app_js_full_path)); if ((ret < 0)) { amp_error(MOD_STR, "module get js version failed!"); goto INTERNAL_M_OTA_OVER; } ret = ota_jsapp_version_get(version, app_js_full_path); if ((ret < 0)) { amp_error(MOD_STR, "app.json path get failed!"); goto INTERNAL_M_OTA_OVER; } ret = ota_report_module_version(ctx, tmp_ctx->module_name, version); if (ret < 0) { amp_error(MOD_STR, "module report ver failed!"); goto INTERNAL_M_OTA_OVER; } INTERNAL_M_OTA_OVER: if (ret < 0) { amp_error(MOD_STR, "ota module upgrade failed\n"); if ((tmp_ctx->report_func.report_status_cb != NULL)) { tmp_ctx->report_func.report_status_cb(tmp_ctx->report_func.param, ret); } aos_msleep(3000); } else { amp_debug(MOD_STR, "module download success!"); } ret = ota_clear(); if (ret < 0) { amp_error(MOD_STR, "clear ota failed\n"); } aos_task_exit(0); return; }
YifuLiu/AliOS-Things
components/amp/services/app_mgr/app_upgrade_adapt.c
C
apache-2.0
5,642
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #define CONFIG_LOGMACRO_DETAILS #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "board_info.h" #include "board_mgr.h" #ifdef AMP_KV_ENABLE #include "aos/kv.h" #endif int8_t board_setDeviceInfo(char *deviceKey, char *deviceName, char *deviceSecret) { #ifdef AMP_KV_ENABLE if (NULL != deviceKey) { aos_kv_set(DEVICE_KEY_TAG, (void *)deviceKey, strlen(deviceKey), 1); } if (NULL != deviceName) { aos_kv_set(DEVICE_NAME_TAG, (void *)deviceName, strlen(deviceName), 1); } if (NULL != deviceSecret) { aos_kv_set(DEVICE_SECRET_TAG, (void *)deviceSecret, strlen(deviceSecret), 1); } #endif return (0); } int8_t board_getDeviceInfo(char **productKey, char **deviceName, char **deviceSecret) { #ifdef AMP_KV_ENABLE char tmp[64] = {0x00}; uint32_t len = 0; int8_t ret = -1; if (NULL != productKey) { len = 64; ret = aos_kv_get(DEVICE_KEY_TAG, tmp, &len); if (0 == ret) { tmp[len] = 0x00; *productKey = strdup(tmp); } else { *productKey = NULL; } } if (NULL != deviceName) { len = 64; ret = aos_kv_get(DEVICE_NAME_TAG, tmp, &len); if (0 == ret) { tmp[len] = 0x00; *deviceName = strdup(tmp); } else { *deviceName = NULL; } } if (NULL != deviceSecret) { len = 64; ret = aos_kv_get(DEVICE_SECRET_TAG, tmp, &len); if (0 == ret) { tmp[len] = 0x00; *deviceSecret = strdup(tmp); } else { *deviceSecret = NULL; } } #endif return (0); }
YifuLiu/AliOS-Things
components/amp/services/board_mgr/board_info.c
C
apache-2.0
1,906
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #ifndef BE_BOARD_INFO_H #define BE_BOARD_INFO_H #ifdef __cplusplus extern "C" { #endif #include <stdint.h> #define DEVICE_KEY_TAG "DEVICE_KEY" #define DEVICE_NAME_TAG "DEVICE_NAME" #define DEVICE_SECRET_TAG "DEVICE_SECRET" /** * set config info of the board * * @param[in] deviceKey the key of a product * @param[in] deviceName the name of a product *@param[in] deviceSecret the secret of a product * @return 0 is ok, others fail */ int8_t board_setDeviceInfo(char *deviceKey, char *deviceName, char *deviceSecret); /** * get config info of the board * * @param[out] deviceKey the key of a product * @param[out] deviceName the name of a product *@param[out] deviceSecret the secret of a product * @return 0 is ok, others fail */ int8_t board_getDeviceInfo(char **productKey, char **deviceName, char **deviceSecret); #ifdef __cplusplus } #endif #endif /* BE_BOARD_INFO_H */
YifuLiu/AliOS-Things
components/amp/services/board_mgr/board_info.h
C
apache-2.0
1,029
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #ifndef BE_BOARD_MARKER_H #define BE_BOARD_MARKER_H #ifdef __cplusplus extern "C" { #endif /* app.json configuration */ #define APP_CONFIG_PAGES "pages" #define APP_CONFIG_IO "io" #define APP_CONFIG_AUDIO "audio" #define APP_CONFIG_NET "net" #define APP_CONFIG_DEBUG "debugLevel" #define APP_CONFIG_REPL "repl" #define APP_CONFIG_VERSION "version" #define MARKER_ID "type" #define MARKER_PORT "port" /* GPIO */ #define MARKER_GPIO "GPIO" #define GPIO_DIR "dir" #define GPIO_PULL "pull" #define GPIO_INTMODE "intMode" #define GPIO_DIR_OUTPUT "output" #define GPIO_DIR_INPUT "input" #define GPIO_DIR_IRQ "irq" #define GPIO_DIR_ANALOG "analog" #define GPIO_PULL_DOWN "pulldown" #define GPIO_PULL_UP "pullup" #define GPIO_PULL_OPEN "opendrain" #define GPIO_INT_RISING "rising" #define GPIO_INT_FALLING "falling" #define GPIO_INT_BOTH "both" #define GPIO_INT_HIGH_LEVEL "high" #define GPIO_INT_LOW_LEVEL "low" /* UART */ #define MARKER_UART "UART" #define UART_DATA_WIDTH "dataWidth" #define UART_BAUD_RATE "baudRate" #define UART_STOP_BITS "stopBits" #define UART_FLOW_CONTROL "flowControl" #define UART_PARITY_CONFIG "parity" #define UART_MODE "mode" #define UART_FC_DISABLE "disable" #define UART_FC_CTS "cts" #define UART_FC_RTS "rts" #define UART_FC_RTSCTS "rtscts" #define UART_PARITY_NONE "none" #define UART_PARITY_ODD "odd" #define UART_PARITY_EVEN "even" /* I2C */ #define MARKER_I2C "I2C" #define I2C_ADDR_WIDTH "addrWidth" #define I2C_FREQ "freq" #define I2C_MODE "mode" #define I2C_ADDR_DEV "devAddr" #define I2C_MASTER "master" #define I2C_SLAVE "slave" /* SPI */ #define MARKER_SPI "SPI" #define SPI_MODE "mode" #define SPI_FREQ "freq" #define SPI_MODE_0 "mode0" #define SPI_MODE_1 "mode1" #define SPI_MODE_2 "mode2" #define SPI_MODE_3 "mode3" /* ADC */ #define MARKER_ADC "ADC" #define ADC_SAMPLING "sampling" /* DAC */ #define MARKER_DAC "DAC" /* CAN */ #define MARKER_CAN "CAN" #define CAN_BAUD_RATE "baudRate" #define CAN_IDE "ide" #define CAN_AUTO_BUS_OFF "auto_bus_off" #define CAN_RETRY_TRANSMIT "retry_transmit" #define IDE_NORMAL_CAN "normal" #define IDE_EXTEND_CAN "extend" #define CAN_DISABLE "disable" #define CAN_ENABLE "enable" /* PWM */ #define MARKER_PWM "PWM" /* TIMER */ #define MARKER_TIMER "TIMER" /* AUDIO */ #define MARKER_AUDIO "AUDIO" #define OUT_DEVICE "out_device" #define EXTERNAL_PA "external_pa" #define EXTERNAL_PA_PIN "external_pa_pin" #define EXTERNAL_PA_DELAY "external_pa_delay_ms" #define EXTERNAL_PA_ACTIVE "external_pa_active_level" #ifdef __cplusplus } #endif #endif /* BE_BOARD_MARKER_H */
YifuLiu/AliOS-Things
components/amp/services/board_mgr/board_marker.h
C
apache-2.0
3,088
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #define CONFIG_LOGMACRO_DETAILS #include "amp_platform.h" #include "amp_config.h" #include "aos_system.h" #include "aos_fs.h" #include "amp_defines.h" #include "board_mgr.h" #include "board_marker.h" //#include "core_list.h" #include "cJSON.h" #ifdef JSE_ADVANCED_ADDON_UI #include "render.h" void page_config_parse(); volatile int app_run_flag = 0; #endif #define MOD_STR "BOARD_MGR" #define DRIVER_DIR JSE_FS_ROOT_DIR "/drivers/" #define DRIVER_NAME "driver.json" extern int g_repl_config; typedef struct parse_json { char *marker_name; addon_module_m module; int8_t (*fn)(cJSON *, char *); } parse_json_t; typedef struct board_item { addon_module_m module; item_handle_t handle; char *name_id; void *node; uint8_t status; } board_item_t; typedef struct board_mgr { uint32_t item_size; board_item_t **item; } board_mgr_t; #if 0 typedef struct page_entry { char *page; struct core_list_head node; }page_entry_t; #endif extern void aos_userjs_version_set(char *version); static board_mgr_t g_board_mgr = {0, NULL}; //static struct core_list_head g_pages_list; static int8_t board_add_new_item(addon_module_m module, char *name_id, void *node); static board_mgr_t *board_get_handle(void) { return &g_board_mgr; } #ifdef JSE_HW_ADDON_GPIO #include "aos_hal_gpio.h" static void board_set_gpio_default(gpio_dev_t *gpio_device) { gpio_params_t *priv = (gpio_params_t *)gpio_device->priv; if (NULL == gpio_device || NULL == priv) { return; } gpio_device->port = -1; gpio_device->config = OUTPUT_PUSH_PULL; gpio_device->gpioc = NULL; gpio_device->gpioc_index = 0; gpio_device->pin_index = 0; priv->irq_mode = 0; priv->js_cb_ref = 0; priv->reserved = NULL; } static int8_t board_parse_gpio(cJSON *gpio, char *id) { int index = 0; int8_t ret = -1; cJSON *port = NULL; cJSON *item = NULL; cJSON *dir = NULL; cJSON *pull = NULL; cJSON *intMode = NULL; gpio_dev_t device; gpio_params_t *priv = NULL; gpio_config_t *config = (gpio_config_t *)&device.config; int8_t size = 1; if (size <= 0) { return (-1); } while (index < size) { priv = (gpio_params_t *)amp_calloc(1, sizeof(gpio_params_t)); if (priv == NULL) { amp_error(MOD_STR, "malloc failed"); return (-1); } item = gpio; index += 1; if (NULL == item || NULL == id) { continue; } port = cJSON_GetObjectItem(item, MARKER_PORT); if (NULL == port || cJSON_Number != port->type) { continue; } device.priv = priv; board_set_gpio_default(&device); dir = cJSON_GetObjectItem(item, GPIO_DIR); pull = cJSON_GetObjectItem(item, GPIO_PULL); intMode = cJSON_GetObjectItem(item, GPIO_INTMODE); if (NULL != dir && cJSON_String == dir->type && NULL != pull && cJSON_String == pull->type) { if (strcmp(dir->valuestring, GPIO_DIR_INPUT) == 0) { if (strcmp(GPIO_PULL_DOWN, pull->valuestring) == 0) *config = INPUT_PULL_DOWN; else if (strcmp(GPIO_PULL_UP, pull->valuestring) == 0) *config = INPUT_PULL_UP; else if (strcmp(GPIO_PULL_OPEN, pull->valuestring) == 0) *config = INPUT_HIGH_IMPEDANCE; } else if (strcmp(dir->valuestring, GPIO_DIR_OUTPUT) == 0) { if (strcmp(GPIO_PULL_DOWN, pull->valuestring) == 0) *config = OUTPUT_PUSH_PULL; else if (strcmp(GPIO_PULL_UP, pull->valuestring) == 0) *config = OUTPUT_OPEN_DRAIN_PULL_UP; else if (strcmp(GPIO_PULL_OPEN, pull->valuestring) == 0) *config = OUTPUT_OPEN_DRAIN_NO_PULL; } else if (strcmp(dir->valuestring, GPIO_DIR_IRQ) == 0) { *config = IRQ_MODE; if (strcmp(GPIO_PULL_DOWN, pull->valuestring) == 0) *config = INPUT_PULL_DOWN; else if (strcmp(GPIO_PULL_UP, pull->valuestring) == 0) *config = INPUT_PULL_UP; else if (strcmp(GPIO_PULL_OPEN, pull->valuestring) == 0) *config = INPUT_HIGH_IMPEDANCE; if (strcmp(GPIO_INT_RISING, intMode->valuestring) == 0) priv->irq_mode = IRQ_TRIGGER_RISING_EDGE; else if (strcmp(GPIO_INT_FALLING, intMode->valuestring) == 0) priv->irq_mode = IRQ_TRIGGER_FALLING_EDGE; else if (strcmp(GPIO_INT_BOTH, intMode->valuestring) == 0) priv->irq_mode = IRQ_TRIGGER_BOTH_EDGES; else if (strcmp(GPIO_INT_HIGH_LEVEL, intMode->valuestring) == 0) priv->irq_mode = IRQ_TRIGGER_LEVEL_HIGH; else if (strcmp(GPIO_INT_LOW_LEVEL, intMode->valuestring) == 0) priv->irq_mode = IRQ_TRIGGER_LEVEL_LOW; } else if (strcmp(dir->valuestring, GPIO_DIR_ANALOG) == 0) { *config = ANALOG_MODE; } } gpio_dev_t *new_gpio = amp_calloc(1, sizeof(*new_gpio)); if (NULL == new_gpio) { continue; } device.port = port->valueint; char *gpio_id = strdup(id); memcpy(new_gpio, &device, sizeof(gpio_dev_t)); ret = board_add_new_item(MODULE_GPIO, gpio_id, new_gpio); if (0 == ret) { continue; } if (NULL != gpio_id) { amp_free(gpio_id); gpio_id = NULL; } if (NULL != new_gpio) { amp_free(new_gpio); new_gpio = NULL; amp_free(priv); priv = NULL; } } return (0); } #endif #ifdef JSE_HW_ADDON_UART #include "aos_hal_uart.h" static void board_set_uart_default(uart_dev_t *uart_device) { if (NULL == uart_device) { return; } uart_device->port = 0; uart_device->priv = NULL; uart_device->config.baud_rate = 115200; uart_device->config.data_width = DATA_WIDTH_8BIT; uart_device->config.flow_control = FLOW_CONTROL_DISABLED; uart_device->config.parity = NO_PARITY; uart_device->config.stop_bits = STOP_BITS_1; uart_device->config.mode = MODE_TX_RX; } static int8_t board_parse_uart(cJSON *uart, char *id) { int index = 0; int8_t ret = -1; cJSON *port = NULL; cJSON *item = NULL; cJSON *temp = NULL; uart_dev_t device; uart_config_t *config = (uart_config_t *)&device.config; int8_t size = 1; if (size <= 0) { return (-1); } while (index < size) { item = uart; index += 1; if (NULL == item) { continue; } port = cJSON_GetObjectItem(item, MARKER_PORT); if (NULL == port || cJSON_Number != port->type) { continue; } board_set_uart_default(&device); temp = cJSON_GetObjectItem(item, UART_DATA_WIDTH); if (NULL != temp && cJSON_Number == temp->type) { int32_t width = temp->valueint; switch (width) { case 5: config->data_width = DATA_WIDTH_5BIT; break; case 6: config->data_width = DATA_WIDTH_6BIT; break; case 7: config->data_width = DATA_WIDTH_7BIT; break; case 8: config->data_width = DATA_WIDTH_8BIT; break; default: break; } } temp = cJSON_GetObjectItem(item, UART_BAUD_RATE); if (NULL != temp && cJSON_Number == temp->type) { config->baud_rate = temp->valueint; } temp = cJSON_GetObjectItem(item, UART_STOP_BITS); if (NULL != temp && cJSON_Number == temp->type) { int32_t stopbits = temp->valueint; switch (stopbits) { case 1: config->stop_bits = STOP_BITS_1; break; case 2: config->stop_bits = STOP_BITS_2; default: break; } } temp = cJSON_GetObjectItem(item, UART_FLOW_CONTROL); if (NULL != temp && cJSON_String == temp->type) { if (strcmp(temp->valuestring, UART_FC_DISABLE) == 0) { config->flow_control = FLOW_CONTROL_DISABLED; } else if (strcmp(temp->valuestring, UART_FC_CTS) == 0) { config->flow_control = FLOW_CONTROL_CTS; } else if (strcmp(temp->valuestring, UART_FC_RTS) == 0) { config->flow_control = FLOW_CONTROL_RTS; } else if (strcmp(temp->valuestring, UART_FC_RTSCTS) == 0) { config->flow_control = FLOW_CONTROL_CTS_RTS; } } temp = cJSON_GetObjectItem(item, UART_PARITY_CONFIG); if (NULL != temp && cJSON_String == temp->type) { if (strcmp(temp->valuestring, UART_PARITY_NONE) == 0) { config->parity = NO_PARITY; } else if (strcmp(temp->valuestring, UART_PARITY_ODD) == 0) { config->parity = ODD_PARITY; } else if (strcmp(temp->valuestring, UART_PARITY_EVEN) == 0) { config->parity = EVEN_PARITY; } } uart_dev_t *new_uart = amp_calloc(1, sizeof(*new_uart)); if (NULL == new_uart) { continue; } device.port = port->valueint; char *uart_id = strdup(id); *new_uart = device; ret = board_add_new_item(MODULE_UART, uart_id, new_uart); amp_debug(MOD_STR, "*** add item: %s", uart_id); if (0 == ret) { continue; } if (NULL != uart_id) { amp_free(uart_id); uart_id = NULL; } if (NULL != new_uart) { amp_free(new_uart); new_uart = NULL; } } return (0); } #endif #ifdef JSE_HW_ADDON_I2C #include "aos_hal_i2c.h" static void board_set_i2c_default(i2c_dev_t *i2c_device) { if (NULL == i2c_device) { return; } i2c_device->port = 0; i2c_device->priv = NULL; i2c_device->config.address_width = 7; i2c_device->config.freq = 100000; i2c_device->config.mode = I2C_MODE_MASTER; i2c_device->config.dev_addr = 0xFF; } static int8_t board_parse_i2c(cJSON *i2c, char *id) { int index = 0; int8_t ret = -1; cJSON *port = NULL; cJSON *item = NULL; cJSON *temp = NULL; i2c_dev_t device; i2c_config_t *config = (i2c_config_t *)&device.config; int8_t size = 1; if (size <= 0) { return (-1); } while (index < size) { item = i2c; index += 1; if (NULL == item) { continue; } port = cJSON_GetObjectItem(item, MARKER_PORT); if (NULL == port || cJSON_Number != port->type) { continue; } board_set_i2c_default(&device); temp = cJSON_GetObjectItem(item, I2C_ADDR_WIDTH); if (NULL != temp && cJSON_Number == temp->type) { switch (temp->valueint) { case 7: config->address_width = I2C_HAL_ADDRESS_WIDTH_7BIT; break; case 10: config->address_width = I2C_HAL_ADDRESS_WIDTH_10BIT; break; default: break; } } temp = cJSON_GetObjectItem(item, I2C_FREQ); if (NULL != temp && cJSON_Number == temp->type) { config->freq = temp->valueint; } temp = cJSON_GetObjectItem(item, I2C_MODE); if (NULL != temp && cJSON_String == temp->type) { if (strcmp(temp->valuestring, I2C_MASTER) == 0) { config->mode = I2C_MODE_MASTER; } else if (strcmp(temp->valuestring, I2C_SLAVE) == 0) { config->mode = I2C_MODE_SLAVE; } } temp = cJSON_GetObjectItem(item, I2C_ADDR_DEV); if (NULL != temp && cJSON_Number == temp->type) { config->dev_addr = temp->valueint; } i2c_dev_t *new_i2c = amp_calloc(1, sizeof(*new_i2c)); if (NULL == new_i2c) { continue; } device.port = port->valueint; char *i2c_id = strdup(id); *new_i2c = device; ret = board_add_new_item(MODULE_I2C, i2c_id, new_i2c); if (0 == ret) { continue; } if (NULL != i2c_id) { amp_free(i2c_id); i2c_id = NULL; } if (NULL != new_i2c) { amp_free(new_i2c); new_i2c = NULL; } } return (0); } #endif #ifdef JSE_HW_ADDON_SPI #include "aos_hal_spi.h" static void board_set_spi_default(spi_dev_t *spi_device) { if (NULL == spi_device) { return; } spi_device->port = 0; spi_device->priv = NULL; spi_device->config.data_size = 8; spi_device->config.mode = 3; spi_device->config.cs = 0; spi_device->config.role = 1; spi_device->config.serial_len = 0; spi_device->config.firstbit = 0; spi_device->config.t_mode = 1; spi_device->config.freq = 2000000; } static int8_t board_parse_spi(cJSON *spi, char *id) { int index = 0; int8_t ret = -1; cJSON *port = NULL; cJSON *item = NULL; cJSON *temp = NULL; spi_dev_t device; spi_config_t *config = (spi_config_t *)&device.config; int8_t size = 1; if (size <= 0) { return (-1); } while (index < size) { item = spi; index += 1; if (NULL == item) { continue; } port = cJSON_GetObjectItem(item, MARKER_PORT); if (NULL == port || cJSON_Number != port->type) { continue; } board_set_spi_default(&device); temp = cJSON_GetObjectItem(item, SPI_MODE); if (NULL != temp && cJSON_String == temp->type) { if (strcmp(temp->valuestring, SPI_MODE_0) == 0) { config->mode = SPI_WORK_MODE_0; } else if (strcmp(temp->valuestring, SPI_MODE_1) == 0) { config->mode = SPI_WORK_MODE_1; } else if (strcmp(temp->valuestring, SPI_MODE_2) == 0) { config->mode = SPI_WORK_MODE_2; } else if (strcmp(temp->valuestring, SPI_MODE_3) == 0) { config->mode = SPI_WORK_MODE_3; } } temp = cJSON_GetObjectItem(item, SPI_FREQ); if (NULL != temp && cJSON_Number == temp->type) { config->freq = temp->valueint; } spi_dev_t *new_spi = amp_calloc(1, sizeof(*new_spi)); if (NULL == new_spi) { continue; } device.port = port->valueint; char *spi_id = strdup(id); *new_spi = device; ret = board_add_new_item(MODULE_SPI, spi_id, new_spi); if (0 == ret) { continue; } if (NULL != spi_id) { amp_free(spi_id); spi_id = NULL; } if (NULL != new_spi) { amp_free(new_spi); new_spi = NULL; } } return (0); } #endif #ifdef JSE_HW_ADDON_CAN #include "aos_hal_can.h" static void board_set_can_default(can_dev_t *can_device) { if (NULL == can_device) { return; } can_device->port = 0; can_device->priv = NULL; can_device->config.baud_rate = CAN_BAUD_500K; can_device->config.ide = CAN_IDE_NORMAL; can_device->config.auto_bus_off = CAN_AUTO_BUS_OFF_ENABLE; can_device->config.auto_retry_transmit = CAN_AUTO_RETRY_TRANSMIT_ENABLE; } static int8_t board_parse_can(cJSON *can, char *id) { int index = 0; int8_t ret = -1; cJSON *port = NULL; cJSON *item = NULL; cJSON *temp = NULL; can_dev_t device; can_config_t *config = (can_config_t *)&device.config; int8_t size = 1; if (size <= 0) { return (-1); } while (index < size) { item = can; index += 1; if (NULL == item) { continue; } port = cJSON_GetObjectItem(item, MARKER_PORT); if (NULL == port || cJSON_Number != port->type) { continue; } board_set_can_default(&device); temp = cJSON_GetObjectItem(item, CAN_BAUD_RATE); if (NULL != temp && cJSON_Number == temp->type) { switch (temp->valueint) { case 1000000: config->baud_rate = CAN_BAUD_1M; break; case 500000: config->baud_rate = CAN_BAUD_500K; break; case 250000: config->baud_rate = CAN_BAUD_250K; break; case 125000: config->baud_rate = CAN_BAUD_125K; break; default: break; } } temp = cJSON_GetObjectItem(item, CAN_IDE); if (NULL != temp && cJSON_String == temp->type) { if (strcmp(temp->valuestring, IDE_NORMAL_CAN) == 0) { config->ide = CAN_IDE_NORMAL; } else if (strcmp(temp->valuestring, IDE_EXTEND_CAN) == 0) { config->ide = CAN_IDE_EXTEND; } } temp = cJSON_GetObjectItem(item, CAN_AUTO_BUS_OFF); if (NULL != temp && cJSON_String == temp->type) { if (strcmp(temp->valuestring, CAN_DISABLE) == 0) { config->auto_bus_off = CAN_AUTO_BUS_OFF_DISABLE; } else if (strcmp(temp->valuestring, CAN_ENABLE) == 0) { config->auto_bus_off = CAN_AUTO_BUS_OFF_ENABLE; } } temp = cJSON_GetObjectItem(item, CAN_RETRY_TRANSMIT); if (NULL != temp && cJSON_String == temp->type) { if (strcmp(temp->valuestring, CAN_DISABLE) == 0) { config->auto_retry_transmit = CAN_AUTO_RETRY_TRANSMIT_DISABLE; } else if (strcmp(temp->valuestring, CAN_ENABLE) == 0) { config->auto_retry_transmit = CAN_AUTO_RETRY_TRANSMIT_ENABLE; } } can_dev_t *new_can = amp_calloc(1, sizeof(*new_can)); if (NULL == new_can) { continue; } device.port = port->valueint; char *can_id = strdup(id); *new_can = device; ret = board_add_new_item(MODULE_CAN, can_id, new_can); if (0 == ret) { continue; } if (NULL != can_id) { amp_free(can_id); can_id = NULL; } if (NULL != new_can) { amp_free(new_can); new_can = NULL; } } return (0); } #endif #ifdef JSE_HW_ADDON_PWM #include "aos_hal_pwm.h" static void board_set_pwm_default(pwm_dev_t *pwm_device) { if (NULL == pwm_device) { return; } pwm_device->port = 0; pwm_device->priv = NULL; pwm_device->config.freq = 0; pwm_device->config.duty_cycle = 100; } static int8_t board_parse_pwm(cJSON *pwm, char *id) { int index = 0; int8_t ret = -1; cJSON *port = NULL; cJSON *item = NULL; cJSON *temp = NULL; pwm_dev_t device; pwm_config_t *config = (pwm_config_t *)&device.config; int8_t size = 1; if (size <= 0) { return (-1); } while (index < size) { item = pwm; index += 1; if (NULL == item) { continue; } port = cJSON_GetObjectItem(item, MARKER_PORT); if (NULL == port || cJSON_Number != port->type) { continue; } board_set_pwm_default(&device); pwm_dev_t *new_pwm = amp_calloc(1, sizeof(*new_pwm)); if (NULL == new_pwm) { continue; } device.port = port->valueint; char *pwm_id = strdup(id); *new_pwm = device; ret = board_add_new_item(MODULE_PWM, pwm_id, new_pwm); if (0 == ret) { continue; } if (NULL != pwm_id) { amp_free(pwm_id); pwm_id = NULL; } if (NULL != new_pwm) { amp_free(new_pwm); new_pwm = NULL; } } return (0); } #endif #ifdef JSE_HW_ADDON_ADC #include "aos_hal_adc.h" static void board_set_adc_default(adc_dev_t *adc_device) { if (NULL == adc_device) { return; } adc_device->port = 0; adc_device->priv = NULL; adc_device->config.sampling_cycle = 12000000; } static int8_t board_parse_adc(cJSON *adc, char *id) { int index = 0; int8_t ret = -1; cJSON *port = NULL; cJSON *item = NULL; cJSON *temp = NULL; adc_dev_t device; adc_config_t *config = (adc_config_t *)&device.config; int8_t size = 1; if (size <= 0) { return (-1); } while (index < size) { item = adc; index += 1; if (NULL == item) { continue; } port = cJSON_GetObjectItem(item, MARKER_PORT); if (NULL == port || cJSON_Number != port->type) { continue; } board_set_adc_default(&device); temp = cJSON_GetObjectItem(item, ADC_SAMPLING); if (NULL != temp && cJSON_Number == temp->type) { config->sampling_cycle = temp->valueint; } adc_dev_t *new_adc = amp_calloc(1, sizeof(*new_adc)); if (NULL == new_adc) { continue; } device.port = port->valueint; char *adc_id = strdup(id); *new_adc = device; ret = board_add_new_item(MODULE_ADC, adc_id, new_adc); if (0 == ret) { continue; } if (NULL != adc_id) { amp_free(adc_id); adc_id = NULL; } if (NULL != new_adc) { amp_free(new_adc); new_adc = NULL; } } return (0); } #endif #ifdef JSE_HW_ADDON_DAC #include "aos_hal_dac.h" static void board_set_dac_default(dac_dev_t *dac_device) { if (NULL == dac_device) { return; } dac_device->port = 0; dac_device->priv = NULL; } static int8_t board_parse_dac(cJSON *dac, char *id) { int index = 0; int8_t ret = -1; cJSON *port = NULL; cJSON *item = NULL; cJSON *temp = NULL; dac_dev_t device; int8_t size = 1; if (size <= 0) { return (-1); } while (index < size) { item = dac; index += 1; if (NULL == item) { continue; } port = cJSON_GetObjectItem(item, MARKER_PORT); if (NULL == port || cJSON_Number != port->type) { continue; } board_set_dac_default(&device); dac_dev_t *new_dac = aos_calloc(1, sizeof(*new_dac)); if (NULL == new_dac) { continue; } device.port = port->valueint; char *dac_id = strdup(id); *new_dac = device; ret = board_add_new_item(MODULE_DAC, dac_id, new_dac); if (0 == ret) { continue; } if (NULL != dac_id) { aos_free(dac_id); dac_id = NULL; } if (NULL != new_dac) { aos_free(new_dac); new_dac = NULL; } } return (0); } #endif #ifdef JSE_HW_ADDON_TIMER #include "aos_hal_timer.h" static void board_set_timer_default(timer_dev_t *timer_device) { if (NULL == timer_device) { return; } timer_device->port = 0; timer_device->priv = NULL; timer_device->config.reload_mode = TIMER_RELOAD_MANU; timer_device->config.period = 1000; } static int8_t board_parse_timer(cJSON *timer, char *id) { int index = 0; int8_t ret = -1; cJSON *port = NULL; cJSON *item = NULL; cJSON *temp = NULL; timer_dev_t device; timer_config_t *config = (timer_config_t *)&device.config; int8_t size = 1; if (size <= 0) { return (-1); } while (index < size) { item = timer; index += 1; if (NULL == item) { continue; } port = cJSON_GetObjectItem(item, MARKER_PORT); if (NULL == port || cJSON_Number != port->type) { continue; } board_set_timer_default(&device); timer_dev_t *new_timer = amp_calloc(1, sizeof(*new_timer)); if (NULL == new_timer) { continue; } device.port = port->valueint; char *timer_id = strdup(id); *new_timer = device; ret = board_add_new_item(MODULE_TIMER, timer_id, new_timer); if (0 == ret) { continue; } if (NULL != timer_id) { amp_free(timer_id); timer_id = NULL; } if (NULL != new_timer) { amp_free(new_timer); new_timer = NULL; } } return (0); } #endif #ifdef JSE_ADVANCED_ADDON_AUDIOPLAYER #include "aos_pcm.h" static int8_t board_parse_audio(cJSON *audio, char *id) { int index = 0; int8_t ret = -1; cJSON *out_device = NULL; cJSON *external_pa = NULL; cJSON *external_pa_pin = NULL; cJSON *external_pa_delay = NULL; cJSON *external_pa_active_level = NULL; cJSON *item = NULL; cJSON *temp = NULL; int8_t size = 1; if (size <= 0) { return (-1); } while (index < size) { item = audio; index += 1; if (NULL == item) { continue; } out_device = cJSON_GetObjectItem(item, OUT_DEVICE); if (NULL == out_device || cJSON_String != out_device->type) { continue; } aos_audio_dev_t *new_audio = amp_calloc(1, sizeof(aos_audio_dev_t)); if (NULL == new_audio) { continue; } if (!strcmp(out_device->valuestring, "speaker")) { new_audio->out_device = AOS_SND_DEVICE_OUT_SPEAKER; } else if (!strcmp(out_device->valuestring, "receiver")) { new_audio->out_device = AOS_SND_DEVICE_OUT_RECEIVER; } else if (!strcmp(out_device->valuestring, "headphone")) { new_audio->out_device = AOS_SND_DEVICE_OUT_HEADPHONE; } else if (!strcmp(out_device->valuestring, "headset")) { new_audio->out_device = AOS_SND_DEVICE_OUT_HEADSET; } else if (!strcmp(out_device->valuestring, "speaker_and_headphone")) { new_audio->out_device = AOS_SND_DEVICE_OUT_SPEAKER_AND_HEADPHONE; } else if (!strcmp(out_device->valuestring, "speaker_and_headset")) { new_audio->out_device = AOS_SND_DEVICE_OUT_SPEAKER_AND_HEADSET; } else { new_audio->out_device = AOS_SND_DEVICE_OUT_SPEAKER; } external_pa = cJSON_GetObjectItem(item, EXTERNAL_PA); if (NULL == external_pa) { new_audio->external_pa = 0; } else { if (cJSON_String != external_pa->type) { new_audio->external_pa = 0; } else { if (!strcmp(external_pa->valuestring, "enable")) { new_audio->external_pa = 1; } else { new_audio->external_pa = 0; } } } external_pa_pin = cJSON_GetObjectItem(item, EXTERNAL_PA_PIN); if (NULL == external_pa_pin) { new_audio->external_pa_pin = -1; } else { if (cJSON_Number != external_pa_pin->type) { new_audio->external_pa_pin = -1; } else { new_audio->external_pa_pin = external_pa_pin->valueint; } } external_pa_delay = cJSON_GetObjectItem(item, EXTERNAL_PA_DELAY); if (NULL == external_pa_delay) { new_audio->external_pa_delay_ms = 0; } else { if (cJSON_Number != external_pa_delay->type) { new_audio->external_pa_delay_ms = 0; } else { new_audio->external_pa_delay_ms = external_pa_delay->valueint; } } external_pa_active_level = cJSON_GetObjectItem(item, EXTERNAL_PA_ACTIVE); if (NULL == external_pa_active_level) { new_audio->external_pa_active_high = 1; } else { if (cJSON_Number != external_pa_active_level->type) { new_audio->external_pa_active_high = 1; } else { new_audio->external_pa_active_high = external_pa_active_level->valueint; } } char *audio_id = strdup(id); ret = board_add_new_item(MODULE_AUDIO, audio_id, new_audio); if (0 == ret) { continue; } if (NULL != audio_id) { amp_free(audio_id); audio_id = NULL; } if (NULL != new_audio) { amp_free(new_audio); new_audio = NULL; } } return (0); } #endif static char *board_get_json_buff(const char *json_path) { void *json_data = NULL; uint32_t len = 0; int json_fd = -1; if (NULL == json_path) { return (NULL); } json_fd = aos_open(json_path, O_RDONLY); if (json_fd < 0) { amp_debug(MOD_STR, "aos open fail"); return (NULL); } // amp_debug(MOD_STR, "jse_lseek"); len = aos_lseek(json_fd, 0, HAL_SEEK_END); amp_warn(MOD_STR, "%s len %u", json_path, len); json_data = amp_calloc(1, sizeof(char) * (len + 1)); if (NULL == json_data) { aos_close(json_fd); amp_debug(MOD_STR, "jse_close"); return (NULL); } aos_lseek(json_fd, 0, HAL_SEEK_SET); // amp_debug(MOD_STR, "jse_read"); aos_read(json_fd, json_data, len); // amp_debug(MOD_STR, "jse_read, data: %s", json_data); aos_close(json_fd); return json_data; } static parse_json_t g_parse_json[] = { #ifdef JSE_HW_ADDON_UART {MARKER_UART, MODULE_UART, board_parse_uart}, #endif #ifdef JSE_HW_ADDON_GPIO {MARKER_GPIO, MODULE_GPIO, board_parse_gpio}, #endif #ifdef JSE_HW_ADDON_PWM {MARKER_PWM, MODULE_PWM, board_parse_pwm}, #endif #ifdef JSE_HW_ADDON_I2C {MARKER_I2C, MODULE_I2C, board_parse_i2c}, #endif #ifdef JSE_HW_ADDON_SPI {MARKER_SPI, MODULE_SPI, board_parse_spi}, #endif #ifdef JSE_HW_ADDON_CAN {MARKER_CAN, MODULE_CAN, board_parse_can}, #endif #ifdef JSE_HW_ADDON_ADC {MARKER_ADC, MODULE_ADC, board_parse_adc}, #endif #ifdef JSE_HW_ADDON_DAC {MARKER_DAC, MODULE_DAC, board_parse_dac}, #endif #ifdef JSE_HW_ADDON_TIMER {MARKER_TIMER, MODULE_TIMER, board_parse_timer}, #endif #ifdef JSE_ADVANCED_ADDON_AUDIOPLAYER {MARKER_AUDIO, MODULE_AUDIO, board_parse_audio}, #endif {NULL, MODULE_NUMS, NULL}, }; static int32_t board_parse_json_buff(const char *json_buff) { cJSON *root = NULL; cJSON *page = NULL, *pages = NULL; cJSON *io = NULL; cJSON *audio = NULL; cJSON *debug = NULL; cJSON *repl = NULL; cJSON *version = NULL; cJSON *item = NULL; cJSON *child = NULL; parse_json_t *parser_handle = NULL; if (NULL == json_buff) { return -1; } root = cJSON_Parse(json_buff); if (NULL == root) { return -1; } /* debugLevel configuration */ if((debug = cJSON_GetObjectItem(root, APP_CONFIG_DEBUG)) != NULL) { /* parsing debugLevel configuration */ if (!cJSON_IsString(debug)) { amp_error(MOD_STR, "debugLevel not string"); goto parse_end; } amp_debug(MOD_STR, "get debugLevel:%s", debug->valuestring); if(strcmp(debug->valuestring, "DEBUG") == 0) { aos_set_log_level(LOG_DEBUG); } else if(strcmp(debug->valuestring, "INFO") == 0) { aos_set_log_level(LOG_INFO); } else if(strcmp(debug->valuestring, "WARN") == 0) { aos_set_log_level(LOG_WARNING); } else if(strcmp(debug->valuestring, "ERROR") == 0) { aos_set_log_level(LOG_ERR); } else if(strcmp(debug->valuestring, "FATAL") == 0) { aos_set_log_level(LOG_CRIT); } else { amp_debug(MOD_STR, "debugLevel error, set to default: 'ERROR'"); aos_set_log_level(LOG_ERR); } } else { amp_debug(MOD_STR, "No debugLevel configuration in app.json, set to default: 'ERROR'"); } /* page configuration */ if((pages = cJSON_GetObjectItem(root, APP_CONFIG_PAGES)) != NULL) { #if 0 /* parsing io configuration */ if(!cJSON_IsArray(pages)) { amp_error(MOD_STR, "Pages entries need array"); goto parse_end; } dlist_init(&g_pages_list); cJSON_ArrayForEach(page, pages) { if (!cJSON_IsString(page)) { amp_error(MOD_STR, "page not string"); goto parse_end; } amp_debug(MOD_STR, "get page:%s", page->valuestring); /* add page to dlink */ page_entry_t *page_entry = amp_malloc(sizeof(page_entry_t)); page_entry->page = strdup(page->valuestring); /* don't forget to free */ dlist_add_tail(&page_entry->node, &g_pages_list); } #else #ifdef JSE_ADVANCED_ADDON_UI app_run_flag = 1; page_config_parse(); #endif #endif } else { amp_debug(MOD_STR, "No pages configuration in app.json"); } /* repl configuration */ if((repl = cJSON_GetObjectItem(root, APP_CONFIG_REPL)) != NULL) { /* parsing debugLevel configuration */ if (!cJSON_IsString(repl)) { amp_error(MOD_STR, "repl not string"); goto parse_end; } amp_debug(MOD_STR, "get app repl config is:%s", repl->valuestring); if (strcmp(repl->valuestring, "disable") == 0) { g_repl_config = 0; } else if (strcmp(repl->valuestring, "enable") == 0) { g_repl_config = 1; } else { amp_debug(MOD_STR, "repl configuration is wrong, set to default: 'enable'"); g_repl_config = 1; } } else { amp_debug(MOD_STR, "No repl configuration in app.json, set to default: 'enable'"); } /* net configuration */ /* TODO */ /* io configuration */ if((io = cJSON_GetObjectItem(root, APP_CONFIG_IO)) != NULL) { /* parsing io configuration */ child = io->child; while (NULL != child) { item = cJSON_GetObjectItem(child, MARKER_ID); if (NULL == item || cJSON_String != item->type) { child = child->next; continue; } parser_handle = &g_parse_json[0]; while (NULL != parser_handle->marker_name) { if (0 == strcmp(item->valuestring, parser_handle->marker_name)) { parser_handle->fn(child, child->string); } parser_handle += 1; } child = child->next; } } else { amp_warn(MOD_STR, "No io configuration in app.json"); } /* audio configuration */ if((audio = cJSON_GetObjectItem(root, APP_CONFIG_AUDIO)) != NULL) { /* parsing audio configuration */ item = cJSON_GetObjectItem(audio, MARKER_ID); if (NULL == item || cJSON_String != item->type) { amp_warn(MOD_STR, "audio marker invalid"); } else { parser_handle = &g_parse_json[0]; while (NULL != parser_handle->marker_name) { if (0 == strcmp(item->valuestring, parser_handle->marker_name)) { parser_handle->fn(audio, audio->string); break; } parser_handle += 1; } } } else { amp_debug(MOD_STR, "No audio configuration in app.json"); } /* version configuration */ if((version = cJSON_GetObjectItem(root, APP_CONFIG_VERSION)) != NULL) { if (!cJSON_IsString(version)) { amp_error(MOD_STR, "version not string"); goto parse_end; } amp_debug(MOD_STR, "get app version is: %s", version->valuestring); #ifndef HAASUI_AMP_BUILD aos_userjs_version_set(version->valuestring); #endif } else { amp_debug(MOD_STR, "No version info in app.json"); } cJSON_Delete(root); return 0; parse_end: cJSON_Delete(root); return -1; } static void *board_get_items(addon_module_m module, item_handle_t *handle, const char *name_id) { board_mgr_t *mgr_handle = board_get_handle(); board_item_t *item = NULL; if (NULL == handle && NULL == name_id) { return (NULL); } uint32_t i = 0; for (i = 0; i < mgr_handle->item_size; ++i) { item = mgr_handle->item[i]; if (module != item->module) { continue; } if (NULL != handle && item->handle.handle != handle->handle) { continue; } if (NULL != name_id && 0 != strcmp(item->name_id, name_id)) { continue; } return (item); } return (NULL); } static int8_t board_add_new_item(addon_module_m module, char *name_id, void *node) { board_item_t *item = NULL; board_mgr_t *mgr_handle = board_get_handle(); if (NULL == name_id || NULL == node) return (-1); if (NULL != board_get_items(module, NULL, name_id)) { return (-1); } board_item_t *new_item = amp_calloc(1, sizeof(*new_item)); if (NULL == new_item) { return (-1); } void *addr = amp_realloc( mgr_handle->item, sizeof(board_item_t *) * (mgr_handle->item_size + 1)); if (NULL == addr) { goto out; } new_item->module = module; new_item->name_id = name_id; new_item->handle.handle = (void*)new_item; new_item->node = node; new_item->status = 0; mgr_handle->item = addr; mgr_handle->item[mgr_handle->item_size] = new_item; mgr_handle->item_size += 1; return (0); out: if (NULL != new_item) { amp_free(new_item); new_item = NULL; } return (-1); } int8_t board_attach_item(addon_module_m module, const char *name_id, item_handle_t *out) { board_item_t *item = NULL; if (NULL == name_id) { return (-1); } item = board_get_items(module, NULL, name_id); if (NULL == item || 1 == item->status) { return (-1); } item->status = 1; *out = item->handle; return (0); } int8_t board_disattach_item(addon_module_m module, item_handle_t *handle) { board_item_t *item = NULL; if (NULL == handle) { return (-1); } item = board_get_items(module, handle, NULL); if (NULL == item) { return (-1); } item->status = 0; return (0); } int8_t board_check_attach_status(addon_module_m module, item_handle_t *handle) { board_item_t *item = NULL; if (NULL == handle) { return (0); } item = board_get_items(module, handle, NULL); if (NULL == item) { return (0); } return (item->status); } void *board_get_node_by_name(addon_module_m module, const char *name_id) { board_item_t *item = NULL; if (NULL == name_id) { return (NULL); } item = board_get_items(module, NULL, name_id); if (NULL == item || 0 == item->status) { return (NULL); } return (item->node); } void *board_get_node_by_handle(addon_module_m module, item_handle_t *handle) { board_item_t *item = NULL; if (NULL == handle) return (NULL); item = board_get_items(module, handle, NULL); if (NULL == item || 0 == item->status) { return (NULL); } return (item->node); } int32_t board_mgr_init(const char *json_path) { int32_t ret = -1; char *json = NULL; memset(&g_board_mgr, 0x00, sizeof(g_board_mgr)); json = board_get_json_buff(json_path); if (NULL == json) { amp_debug(MOD_STR, "default board config is null"); return ret; } // return 0; ret = board_parse_json_buff(json); amp_free(json); json = NULL; return ret; } int8_t board_load_drivers(const char *driver) { char *p = (char *)driver; char *index = NULL; char *json = NULL; char *new_driver = NULL; int32_t len = -1; int8_t ret = -1; if (NULL == driver) { return (-1); } len = strlen(driver); if (len < 8) { return (-1); } if (0 != strncmp(driver + len - 3, ".js", 3)) { return (-1); } p = p + strlen("/spiffs/"); index = (char *)driver + len - 1; while (index > p) { if (*index == '/') { break; } index -= 1; } if (index <= p) { return (-1); } new_driver = amp_calloc(1, sizeof(char) * (index - driver + 16)); if (NULL == new_driver) { return (-1); } memmove(new_driver, driver, index - driver + 1); memmove(new_driver + (index - driver + 1), DRIVER_NAME, strlen(DRIVER_NAME)); amp_debug(MOD_STR, "%s%d, new_driver = %s ", __FUNCTION__, __LINE__, new_driver); json = board_get_json_buff(new_driver); if (NULL == json) { goto out; } ret = board_parse_json_buff(json); out: if (NULL != new_driver) { amp_free(new_driver); new_driver = NULL; } if (NULL != json) { amp_free(json); json = NULL; } return (ret); }
YifuLiu/AliOS-Things
components/amp/services/board_mgr/board_mgr.c
C
apache-2.0
42,966
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #ifndef BE_BOARD_MGR_H #define BE_BOARD_MGR_H #ifdef __cplusplus extern "C" { #endif #include <stdint.h> typedef enum addon_module { MODULE_GPIO = 0x1324, MODULE_UART, MODULE_I2C, MODULE_PWM, MODULE_ADC, MODULE_DAC, MODULE_SPI, MODULE_TIMER, MODULE_RTC, MODULE_BT, MODULE_IR, MODULE_I2S, MODULE_CAN, MODULE_SDIO, MODULE_USB, MODULE_AUDIO, MODULE_I2C_GPIO, MODULE_NUMS, } addon_module_m; typedef struct item_handle { void *handle; } item_handle_t; typedef struct { int irq_mode; int js_cb_ref; void *reserved; } gpio_params_t; /** * initialize mgr system * * @param[in] json_path the path of boar-mgr file * @return the operation status, 0 is OK, others is error */ int32_t board_mgr_init(const char* json_path); /** * load driver config * * @param[in] driver the path of boar-driver file * @return the operation status, 0 is OK, others is error */ int8_t board_load_drivers(const char* driver); /** * attach a driver resource * * @param[in] module the module type of a driver * @param[in] name_id the name of a driver * @param[out] name_id the resource of a driver * @return the operation status, 0 is OK, others is error */ int8_t board_attach_item(addon_module_m module, const char* name_id, item_handle_t* out); /** * release a driver resource * * @param[in] module the module type of a driver * @param[in] handle the resource of a driver * @return the operation status, 0 is OK, others is error */ int8_t board_disattach_item(addon_module_m module, item_handle_t* handle); /** * the attach status of the driver and resource * * @param[in] module the module type of a driver * @param[in] handle the resource of a driver * @return the attach status, 1 is attach, others is dis-attach */ int8_t board_check_attach_status(addon_module_m module, item_handle_t* handle); /** * get the resource of a driver by name * * @param[in] module the module type of a driver * @param[in] name_id the name of a driver * @return driver resource, null if not exist,otherwise it's right */ void* board_get_node_by_name(addon_module_m module, const char* name_id); /** * get the resource of a driver by the handle of a driver resource * * @param[in] module the module type of a driver * @param[in] handle the resource of a driver * @return driver resource, null if not exist,otherwise it's right */ void* board_get_node_by_handle(addon_module_m module, item_handle_t* handle); #ifdef __cplusplus } #endif #endif /* BE_BOARD_MGR_H */
YifuLiu/AliOS-Things
components/amp/services/board_mgr/board_mgr.h
C
apache-2.0
2,689
var net = require('net'); var HOST = '100.81.240.32'; var PORT = 50000; var server = net.createServer(); server.listen(PORT, HOST); // console.log(server); console.log('Server listening on ' + HOST + ':' + PORT); server.on('connection', function(sock) { console.log('CONNECTED: ' + sock.remoteAddress +':'+ sock.remotePort); // 为这个socket实例添加一个"data"事件处理函数 sock.on('data', function(data) { console.log('DATA ' + sock.remoteAddress + ': ' + data); // 回发该数据,客户端将收到来自服务端的数据 sock.write('AMP tcp server reply'); }); // 为这个socket实例添加一个"close"事件处理函数 sock.on('close', function(data) { console.log('CLOSED: ' + sock.remoteAddress + ' ' + sock.remotePort); }); });
YifuLiu/AliOS-Things
components/amp/test/host/tcpServer.js
JavaScript
apache-2.0
796
const dgram = require('dgram'); const server = dgram.createSocket('udp4'); //创建udp服务器 //以下server.on 都是在监听不同信号 server.on('close',()=>{ console.log('socket已关闭'); }); server.on('error',(err)=>{ console.log(err); }); server.on('listening',()=>{ console.log('socket正在监听中...'); }); server.on('message',(msg,rinfo)=>{ console.log(`receive message: ${msg} from ${rinfo.address}:${rinfo.port}`); var message = 'AMP udp server reply'; server.send(message,rinfo.port,rinfo.address); }); server.bind(50000); //绑定端口,不绑定的话也可以send数据但是无法接受
YifuLiu/AliOS-Things
components/amp/test/host/udpServer.js
JavaScript
apache-2.0
645
/* Please add this section into app.json when run this script as app.js. This configuration is designed for haas100 edu k1. { "version": "1.0.0", "io": { "DS18B20": { "type": "GPIO", "port": 4, "dir": "output", "pull": "pullup" } }, "debugLevel": "DEBUG" } */ console.log('testing DS18B20...'); var DS18B20 = require('./DS18B20.js'); DS18B20.init("DS18B20"); var temperature; var count = 10; while(1) { temperature = DS18B20.getTemperature(); { console.log("Temperature is: " , temperature); } } DS18B20.deinit(); console.log("test DS18B20 success!");
YifuLiu/AliOS-Things
components/amp/test/test_DS18B20.js
JavaScript
apache-2.0
663
/* Please add this section into app.json when run this script as app.js. This configuration is designed for HaaS EDU K1. "ap3216c": { "type": "I2C", "port": 1, "addrWidth": 7, "freq": 100000, "mode": "master", "devAddr": 30 } */ console.log('testing ap3216c...'); var ap3216c = require('./ap3216c.js'); ap3216c.init("ap3216c"); while (1) { var brightness = ap3216c.ap3216c_read_ambient_light(); console.log("ap3216c brightness is: " , brightness); var ir_data = ap3216c.ap3216c_read_ir_data(); console.log("ap3216c ir_data is: " , ir_data); var ps_data = ap3216c.ap3216c_read_ps_data(); console.log("ap3216c ps_data is: " , ps_data); if ((ps_data >> 15) & 1) console.log("near !"); else console.log("far !"); sleepMs(500) } ap3216c.deinit(); console.log("test ap3216c success!");
YifuLiu/AliOS-Things
components/amp/test/test_ap3216c.js
JavaScript
apache-2.0
857
/* 本测试case,测试fs的接口,接口返回值等 */ console.log('testing fs...'); // 测试 fs 模块 var fs = require('fs'); if(!(fs && fs.writeSync && fs.readSync && fs.unlinkSync)){ throw new Error("[failed] require(\'fs\')"); } console.log('[success] require(\'fs\')'); // 测试 fs 写入 if(fs.writeSync('./aiot.txt', 'amp')){ throw new Error("[failed] fs.writeSync()"); } console.log("[success] fs.writeSync()"); // 测试 fs 读取 fs.readSync('./aiot.txt'); var value = fs.readSync('./aiot.txt'); if(!value || value !== 'amp'){ throw new Error("[failed] fs.readSync()"); } function testWrongFile() { try{ fs.readSync('./aiot1.txt') } catch (e) { return true; } throw new Error("[failed] fs.readSync()"); } if (testWrongFile()) { console.log("[success] fs.readSync()"); } // 测试 fs 清除 if(fs.unlinkSync('./aiot.txt') || fs.unlinkSync('./aiot.txt') !== undefined){ throw new Error("[failed] fs.unlinkSync()"); } console.log("[success] fs.unlinkSync()");
YifuLiu/AliOS-Things
components/amp/test/test_fs.js
JavaScript
apache-2.0
1,033
console.log('http: testing http...'); var http = require('http'); if (!(http && http.request)) { throw new Error("http: [failed] require(\'http\')"); } console.log('http: [success] require(\'http\')'); var request_url = 'http://appengine.oss-cn-hangzhou.aliyuncs.com/httpTest.txt'; var defaultMessage = 'this is AMP HTTP test file'; http.request({ url: request_url, method: 'GET', headers: { 'content-type':'application/json' }, success: function (data) { console.log('http: [debug] receive data is ' + data); if(data === defaultMessage) { console.log('http: [success] http.request'); } } });
YifuLiu/AliOS-Things
components/amp/test/test_http.js
JavaScript
apache-2.0
659
console.log('iot: testing iot...'); var iot = require('iot'); if (!(iot && iot.device)) { throw new Error("iot: [failed] require(\'iot\')"); } console.log('iot: [success] require(\'iot\')'); var productKey = 'a10h6IdruJf'; var deviceName = 'nodemcu_02'; var deviceSecret = 'StFYN4UigwDiRbhRwVFkFIKsEqpuaHKu'; var device = iot.device({ productKey: productKey, deviceName: deviceName, deviceSecret: deviceSecret, region: 'cn-shanghai', success: function () { console.log('iot: [success] connect'); onConnect(); }, fail: function () { console.log('iot: [failed] connect'); } }); var postCnt = 10; var lightSwitch = 0; function onConnect() { var intervalHandle = setInterval(function () { postCnt--; if(postCnt <= 0) { clearInterval(intervalHandle); } /** post properties */ lightSwitch = 1 - lightSwitch; device.postProps({ payload: { LightSwitch: lightSwitch }, success: function () { console.log('iot: [success] iot.postProps cnt: ' + postCnt); }, fail: function () { console.log('iot: [failed] iot.postProps cnt: ' + postCnt); } }); /** post events */ device.postEvent({ id: 'Error', params: { ErrorCode: 0 }, success: function () { console.log('iot: [success] iot.postEvent cnt: ' + postCnt); }, fail: function () { console.log('iot: [failed] iot.postEvent cnt: ' + postCnt); } }); }, 1000); } device.on('connect', function () { console.log('iot: [success] iot.on(\'connect\')'); }); /* 网络断开事件 */ device.on('disconnect', function () { console.log('iot: [success] iot.on(\'disconnect\')'); }); /* 关闭连接事件 */ device.on('close', function () { console.log('iot: [success] iot.on(\'close\')'); }); /* 发生错误事件 */ device.on('error', function (err) { throw new Error('iot: [failed] iot.on(\'error\') ' + err); }); /* 云端设置属性事件 */ device.on('props', function (payload) { console.log('iot: [success] iot.on(\'props\'), payload: ' + JSON.stringify(payload)); }); /* 云端下发服务事件 */ device.on('service', function (id, payload) { console.log('iot: [success] iot.on(\'service\'), id: ' + id + ', payload: ' + JSON.stringify(payload)); });
YifuLiu/AliOS-Things
components/amp/test/test_iot.js
JavaScript
apache-2.0
2,535
/* 本测试case,测试kv的接口,接口返回值等 */ console.log('testing kv...'); // 测试 kv 模块 var kv = require('kv'); if(!(kv && kv.setStorageSync && kv.getStorageSync && kv.removeStorageSync)){ throw new Error("[failed] require(\'kv\')"); } console.log('[success] require(\'kv\')'); // 测试 kv 写入 if(kv.setStorageSync('aiot', 'amp')){ throw new Error("[failed] kv.setStorageSync()"); } console.log("[success] kv.setStorageSync()"); // 测试 kv 读取 kv.getStorageSync('aiot'); var value = kv.getStorageSync('aiot'); if(!value || value !== 'amp'){ throw new Error("[failed] kv.getStorageSync()"); } if(kv.getStorageSync('aiot1') == 0){ throw new Error("[failed] kv.getStorageSync()"); } console.log("[success] kv.getStorageSync()"); // 测试 kv 修改 if(kv.setStorageSync('aiot', 'alios-things')){ throw new Error("[failed] kv modify"); } var value2 = kv.getStorageSync('aiot'); if(!value2 || value2 !== 'alios-things'){ throw new Error("[failed] kv modify"); } console.log("[success] kv modify"); // 测试 kv 清除 if(kv.removeStorageSync('aiot') || kv.getStorageSync('aiot') !== undefined){ throw new Error("[failed] kv.removeStorageSync()"); } console.log("[success] kv.removeStorageSync()");
YifuLiu/AliOS-Things
components/amp/test/test_kv.js
JavaScript
apache-2.0
1,257
/* Please add this section into app.json when run this script as app.js. This configuration is designed for haas100 edu k1. "spl06": { "type": "I2C", "port": 1, "addrWidth": 7, "freq": 400000, "mode": "master", "devAddr": 105 } */ console.log('testing mpu6050...'); var mpu6050 = require('./mpu6050.js'); mpu6050.init("mpu6050"); var temp = mpu6050.get_Temperature(); console.log("mpu6050 temp is: " , temp); var gy = mpu6050.get_Gyroscope(); console.log("mpu6050 gyro is: " , gy[0], gy[1], gy[2]); var ac = mpu6050.get_Accelerometer(); console.log("mpu6050 acc is: " , ac[0], ac[1], ac[2]); mpu6050.deinit(); console.log("test mpu6050 success!");
YifuLiu/AliOS-Things
components/amp/test/test_mpu6050.js
JavaScript
apache-2.0
678
function ArrayToString(fileData) { var dataString = ""; for (var i = 0; i < fileData.length; i++) { dataString += String.fromCharCode(fileData[i]); } return dataString; } console.log('mqtt: testing mqtt...'); var mqtt = require('mqtt'); if (!(mqtt && mqtt.createClient)) { throw new Error("mqtt: [failed] require(\'mqtt\')"); } console.log('mqtt: [success] require(\'mqtt\')'); function testUnsubscribe() { return new Promise(function (resolve, reject) { mqttClient.subscribe({ topic: '/amp-test', success: function () { console.log('mqtt: [success] mqtt subscribe'); mqttClient.unsubscribe({ topic: '/amp-test', success: function () { console.log('mqtt: [success] mqtt unsubscribe'); resolve(); }, fail: function () { console.log('mqtt: [failed] mqtt unsubscribe'); reject(); } }); }, fail: function () { console.log('mqtt: [failed] mqtt subscribe'); reject(); } }); }); } function testOnMessage() { return new Promise(function (resolve, reject) { var testTopic = '/amp-hello'; var recvCnt = 0, sendCnt = 0; var defaultMessage = 'AMP mqtt reply'; mqttClient.subscribe({ topic: testTopic }); mqttClient.on('message', function (topic, payload) { recvCnt++; console.log('mqtt: [debug] mqtt on message, topic[' + topic + ']: ' + ArrayToString(payload) + ', cnt: ' + recvCnt); if (!topic || typeof topic !== 'string' || !payload || typeof payload !== 'object') { console.log("mqtt: [failed] mqtt on(\'message\')"); reject(); } if (topic !== testTopic || ArrayToString(payload) !== defaultMessage) { console.log("mqtt: [failed] mqtt on(\'message\')"); reject(); } if (recvCnt >= 10) { mqttClient.close(); console.log('mqtt: [success] mqtt.on(\'message\')'); console.log('mqtt: testing mqtt success'); resolve(); } }); setTimeout(function () { if (recvCnt != 10) { console.log('mqtt: [failed] mqtt on message'); reject(); } }, 12000); var intervalHandle = setInterval(function () { mqttClient.publish({ topic: testTopic, message: defaultMessage, success: function () { sendCnt++; console.log("mqtt: [debug] publish success, cnt: ", sendCnt); if (sendCnt >= 10) { clearInterval(intervalHandle); console.log('mqtt: [success] mqtt.publish()'); resolve(); } }, fail: function () { console.log("mqtt: [failed] mqtt.publish()"); reject(); } }); }, 1000); }); } function onConnect() { testUnsubscribe().then(function () { return testOnMessage().then(function () { console.log('mqtt: testing mqtt success'); }); }).catch(function () { console.log('mqtt: testing mqtt failed'); }); } var mqttClient = mqtt.createClient({ host: 'mqtt.eclipse.org', port: 1883, username: 'aiot', password: '123', success: function () { console.log('mqtt: [debug] mqtt connected'); }, fail: function () { console.log('mqtt: [debug] mqtt connect failed'); } }); mqttClient.on('connect', function () { console.log('mqtt: [success] mqtt.on(\'connect\')'); onConnect(); }); mqttClient.on('disconnect', function () { console.log('mqtt: [success] mqtt.on(\'disconnect\')'); }); mqttClient.on('close', function () { console.log('mqtt: [success] mqtt.on(\'close\')'); });
YifuLiu/AliOS-Things
components/amp/test/test_mqtt.js
JavaScript
apache-2.0
4,243