Skip to content

Commit

Permalink
fix issues #34 (#35)
Browse files Browse the repository at this point in the history
  • Loading branch information
JasonChenGt authored Apr 12, 2021
1 parent 02216cd commit 6143be0
Show file tree
Hide file tree
Showing 12 changed files with 675 additions and 269 deletions.
6 changes: 3 additions & 3 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,13 @@ before_deploy:
- export DISTDIR=/tmp/dist
- git fetch origin gh-pages:gh-pages
- git worktree add ${DISTDIR} gh-pages
- cp ./build-web/dan2-web.js ${DISTDIR}/dan2.js
- cp ./build-web/dan2-web.js ${DISTDIR}/dan2-${TRAVIS_COMMIT}.js
- cp ./build-web/iottalkjs-web.js ${DISTDIR}/iottalkjs.js
- cp ./build-web/iottalkjs-web.js ${DISTDIR}/iottalkjs-${TRAVIS_COMMIT}.js
- echo "TRAVIS_TAG = ${TRAVIS_TAG}"
- echo "TRAVIS_BRANCH = ${TRAVIS_BRANCH}"
- if [ "${TRAVIS_TAG}" ]; then
echo 'Add tags build';
cp ./build-web/dan2-web.js ${DISTDIR}/dan2-${TRAVIS_TAG}.js;
cp ./build-web/iottalkjs-web.js ${DISTDIR}/iottalkjs-${TRAVIS_TAG}.js;
fi

deploy:
Expand Down
20 changes: 20 additions & 0 deletions examples/Dummy_Device/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<!DOCTYPE html>
<html lang="en">

<head>
<title>Dummy_Device</title>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script src="js/sa.js"></script>
<script src="../../build-web/iottalkjs-web.js"></script>

</head>

<body>
<legend>Dummy_Sensor</legend>
<legend class='IDF_value'>_____________</legend>
<legend>Dummy_Control</legend>
<legend class='ODF_value'>_____________</legend>
</body>

</html>
27 changes: 27 additions & 0 deletions examples/Dummy_Device/js/sa.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
$(function () {
function Dummy_Sensor() {
var number = Math.floor((1 + Math.random()) * 0x10000);
$('.IDF_value')[0].innerText = number;
return [number];
}

function Dummy_Control(data) {
$('.ODF_value')[0].innerText = data[0];
}

var option = {
'api_url': 'https://iottalk2.tw/csm',
'device_model': 'Dummy_Device',
'device_addr': 'c96ca71c-9e48-2a23-2868-acb420a2f105',
'device_name': 'Dummy',
'persistent_binding': true,
'idf_list': [[Dummy_Sensor, ['int']]],
'odf_list': [Dummy_Control],
'push_interval': 0,
'interval': {
'Dummy_Sensor': 1.5,
}
};

new iottalkjs.dai(option).run();
});
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@
"name": "iottalk-js",
"version": "2.0.4",
"description": "IoTtalk javascript library SDK",
"main": "dan2.js",
"main": "iottalkjs.js",
"directories": {
"example": "examples"
},
"scripts": {
"start": "npx webpack -w --mode development",
"build": "npm run build:node && npm run build:web",
"build:node": "npx babel src --out-dir build-node && npx ncc build build-node/dan2.js -o build-node/dist && mv build-node/dist/index.js build-node/dist/dan2.js",
"build:node": "npx babel src --out-dir build-node && npx ncc build build-node/index.js -o build-node/dist && mv build-node/dist/index.js build-node/dist/iottalkjs.js",
"build:web": "npx webpack",
"test": "echo \"Error: no test specified\" && exit 1"
},
Expand Down
24 changes: 24 additions & 0 deletions src/context.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import ChannelPool from './channel-pool.js';

export default class {

constructor() {
this.url = null;
this.app_id = null;
this.name = null;
this.mqtt_host = null;
this.mqtt_port = null;
this.mqtt_username = null;
this.mqtt_password = null;
this.mqtt_client = null;
this.i_chans = new ChannelPool();
this.o_chans = new ChannelPool();
this.rev = null;
this.on_signal = null;
this.on_data = null;
this.on_register = null;
this.on_deregister = null;
this.on_connect = null;
this.on_disconnect = null;
}
}
203 changes: 203 additions & 0 deletions src/dai.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,203 @@
import DeviceFeature from './device-feature.js';
import { Client } from './dan.js';
import { RegistrationError, ArgumentError } from './exceptions.js';

export default class {

constructor(option) {
this.api_url = option['api_url'];
this.device_model = option['device_model'];
this.device_addr = option['device_addr'];
this.device_name = option['device_name'];
this.persistent_binding = option['persistent_binding'] || false;
this.username = option['username'];
this.extra_setup_webpage = option['extra_setup_webpage'] || '';
this.device_webpage = option['device_webpage'] || '';

this.register_callback = option['register_callback'];
this.on_register = option['on_register'];
this.on_deregister = option['on_deregister'];
this.on_connect = option['on_connect'];
this.on_disconnect = option['on_disconnect'];

this.push_interval = option['push_interval'] != undefined ? option['push_interval'] : 1;
this.interval = option['interval'] || {};

this.device_features = {};
this.flags = {};

this.on_signal = this.on_signal.bind(this);
this.on_data = this.on_data.bind(this);

this.parse_df_profile(option, 'idf');
this.parse_df_profile(option, 'odf');
}

push_data(df_name) {
if (this.device_features[df_name].push_data == null)
return;
let _df_interval = this.interval[df_name] != undefined ? this.interval[df_name] : this.push_interval;
console.debug(`${df_name} : ${this.flags[df_name]} [message / ${_df_interval} s]`);
let _push_interval = setInterval(() => {
let _data = this.device_features[df_name].push_data();
if (!this.flags[df_name]) {
clearInterval(_push_interval);
return;
}
if (_data === undefined) {
return;
}
this.dan.push(df_name, _data);

}, _df_interval * 1000);
}

on_signal(signal, df_list) {
console.log(`Receive signal: ${signal}, ${df_list}`);
if ('CONNECT' == signal) {
df_list.forEach(df_name => {
if (this.flags[df_name]) {
return;
}
this.flags[df_name] = true;
this.push_data(df_name);
});
}
else if ('DISCONNECT' == signal) {
df_list.forEach(df_name => {
this.flags[df_name] = false;
});
}
else if ('SUSPEND' == signal) {
// Not use
}
else if ('RESUME' == signal) {
// Not use
}
return true;
}

on_data(df_name, data) {
try {
this.device_features[df_name].on_data(data);
} catch (err) {
console.error(err);
return false;
}
return true;
}

df_func_name(df_name) {
if (df_name.match(/_[A-Z]?(I|O)[0-9]?$/i)) {
return df_name.replace('_', '-');
}
return df_name;
}

_check_parameter() {
if (!this.api_url)
throw new RegistrationError('api_url is required.');

if (!this.device_model)
throw new RegistrationError('device_model not given.');

if (this.persistent_binding && !this.device_addr)
throw new ArgumentError('In case of `persistent_binding` set to `True`, ' +
'the `device_addr` should be set and fixed.');

if (Object.keys(this.device_features).length === 0)
throw new RegistrationError('Neither idf_list nor odf_list is empty.');
}

run() {
this._check_parameter();

this.dan = new Client();

let idf_list = [];
let odf_list = [];

for (const [df_name, df] of Object.entries(this.device_features)) {
if (df.df_type == 'idf')
idf_list.push([df_name, df.df_type]);
else
odf_list.push([df_name, df.df_type]);
}

const msg = {
'url': this.api_url,
'on_signal': this.on_signal,
'on_data': this.on_data,
'accept_protos': ['mqtt'],
'id': this.device_addr,
'idf_list': idf_list,
'odf_list': odf_list,
'name': this.device_name,
'profile': {
'model': this.device_model,
'u_name': this.username,
'extra_setup_webpage': this.extra_setup_webpage,
'device_webpage': this.device_webpage,
},
'register_callback': this.register_callback,
'on_register': this.on_register,
'on_deregister': this.on_deregister,
'on_connect': this.on_connect,
'on_disconnect': () => {
for (const key in this.flags) {
this.flags[key] = false;
}
console.debug(`on_disconnect: _flag = ${this.flags}`);
if (on_disconnect) {
return on_disconnect;
}
}
};

this.dan.register(msg);

// FIXME: window is not defined in node.js
window.onbeforeunload = function () {
try {
if (!this.persistent_binding) {
this.dan.deregister();
}
} catch (error) {
console.error(`dai process cleanup exception: ${error}`);
}
};
}

parse_df_profile(option, typ) {
const df_list = `${typ}_list`;
for (let i = 0; i < option[df_list].length; i++) {
let df_name;
let param_type;
let on_data;
let push_data;
if (!Array.isArray(option[df_list][i])) {
df_name = this.df_func_name(option[df_list][i].name);
param_type = null;
on_data = push_data = option[df_list][i];
}
else if (Array.isArray(option[df_list][i]) && option[df_list][i].length == 2) {
df_name = this.df_func_name(option[df_list][i][0].name);
param_type = option[df_list][i][1];
on_data = push_data = option[df_list][i][0];
}
else {
throw new RegistrationError(`Invalid ${df_list}, usage: [df_func, ...] or [[df_func, type], ...]`);
}

let df = new DeviceFeature({
'df_name': df_name,
'df_type': typ,
'param_type': param_type,
'push_data': push_data,
'on_data': on_data
});

this.device_features[df_name] = df;
}
}
}
Loading

0 comments on commit 6143be0

Please sign in to comment.