Initial setup of mycontroller

This commit is contained in:
2019-11-28 09:16:11 -06:00
parent 62d71e30c1
commit 665eb783be
504 changed files with 212034 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
tmp

26
bin/start.bat Normal file
View File

@@ -0,0 +1,26 @@
@REM
@REM Copyright 2015-2018 Jeeva Kandasamy (jkandasa@gmail.com)
@REM and other contributors as indicated by the @author tags.
@REM
@REM Licensed under the Apache License, Version 2.0 (the "License");
@REM you may not use this file except in compliance with the License.
@REM You may obtain a copy of the License at
@REM
@REM http://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing, software
@REM distributed under the License is distributed on an "AS IS" BASIS,
@REM WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@REM See the License for the specific language governing permissions and
@REM limitations under the License.
@REM
@ECHO OFF
SET HEAP_MIN=-Xms32m
SET HEAP_MAX=-Xmx256m
SET CONF_PROPERTIES_FILE=../conf/mycontroller.properties
SET CONF_LOG_FILE=../conf/logback.xml
@ECHO ON
java %HEAP_MIN% %HEAP_MAX% -Dlogback.configurationFile=%CONF_LOG_FILE% -Dmc.conf.file=%CONF_PROPERTIES_FILE% -cp "../lib/*" org.mycontroller.standalone.StartApp > ../logs/mycontroller_console.log 2>&1

63
bin/start.sh Normal file
View File

@@ -0,0 +1,63 @@
#!/bin/bash
#
# Copyright 2015-2018 Jeeva Kandasamy (jkandasa@gmail.com)
# and other contributors as indicated by the @author tags.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Get user current location
USER_LOCATION=$PWD
ACTUAL_LOCATION=`dirname $0`
# Change the location to where exactly script is located
cd ${ACTUAL_LOCATION}
#Java Heap settings
HEAP_MIN=-Xms32m
HEAP_MAX=-Xmx256m
JAVA_VERSION="1.7"
#configuration file location
CONF_PROPERTIES_FILE=../conf/mycontroller.properties
CONF_LOG_FILE=../conf/logback.xml
if [[ -n "$JAVA_HOME" ]] && [[ -x "$JAVA_HOME/bin/java" ]]; then
_java="$JAVA_HOME/bin/java"
elif type -p java; then
_java=java
else
echo "java is not installed in our machine"
fi
if [[ "$_java" ]]; then
version=$("$_java" -version 2>&1 | awk -F '"' '/version/ {print $2}')
echo "java version: $version"
if [[ "$version" > "$JAVA_VERSION" ]]; then
MC_PID=`ps -ef | grep "org.mycontroller.standalone.StartApp" | grep -v grep | awk '{ print $2 }'`
if [ ! -z "$MC_PID" ]
then
echo "Mycontroller.org server is already running on pid[${MC_PID}]"
else
$_java ${HEAP_MIN} ${HEAP_MAX} -Dlogback.configurationFile=${CONF_LOG_FILE} -Dmc.conf.file=${CONF_PROPERTIES_FILE} -cp "../lib/*" org.mycontroller.standalone.StartApp >> ../logs/mycontroller.log 2>&1 &
echo 'Start issued for Mycontroller'
fi
else
echo "Mycontroller.org server required java version $JAVA_VERSION or later"
fi
fi
# back to user location
cd ${USER_LOCATION}

26
bin/stop.sh Normal file
View File

@@ -0,0 +1,26 @@
#!/bin/bash
#
# Copyright 2015-2018 Jeeva Kandasamy (jkandasa@gmail.com)
# and other contributors as indicated by the @author tags.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
MC_PID=`ps -ef | grep "org.mycontroller.standalone.StartApp" | grep -v grep | awk '{ print $2 }'`
if [ ! -z "$MC_PID" ]
then
kill -15 ${MC_PID}
echo 'Termination issued for Mycontroller.org server!'
else
echo 'Mycontroller.org server is not running!'
fi

BIN
conf/keystore.jks Normal file

Binary file not shown.

125
conf/logback.xml Normal file
View File

@@ -0,0 +1,125 @@
<!--
Copyright 2015-2018 Jeeva Kandasamy (jkandasa@gmail.com)
and other contributors as indicated by the @author tags.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<configuration scan="true" scanPeriod="2 minutes">
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>../logs/mycontroller.log</file>
<encoder>
<!-- <pattern>%date %level [%thread] [%logger:%line] %msg%n</pattern> -->
<!-- Replace CR(\r) with string \r and LF(\n) with string \n-->
<pattern>%date %level [%thread] [%logger:%line] %replace(%msg){'\r', '\\r'}%n</pattern>
</encoder>
<rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
<FileNamePattern>../logs/mycontroller_%i.log.zip</FileNamePattern>
<MinIndex>1</MinIndex>
<MaxIndex>5</MaxIndex>
</rollingPolicy>
<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<MaxFileSize>5MB</MaxFileSize>
</triggeringPolicy>
</appender>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%date %level [%thread] [%logger:%line] %msg%n</pattern>
</encoder>
</appender>
<appender name="GATEWAY_RAW_MESSAGE_APPENDER" class="ch.qos.logback.classic.sift.SiftingAppender">
<discriminator>
<key>gateway_reference</key>
<defaultValue>0_default</defaultValue>
</discriminator>
<sift>
<appender name="fileAppender" class="ch.qos.logback.core.FileAppender">
<file>../logs/raw_message_gw_${gateway_reference}.log</file>
<encoder>
<pattern>%date %replace(%replace(%msg){'\r', '\\r'}){'\n', '\\n'}%n</pattern>
</encoder>
<rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
<FileNamePattern>../logs/raw_message_gw_${gateway_reference}%i.log.zip</FileNamePattern>
<MinIndex>1</MinIndex>
<MaxIndex>5</MaxIndex>
</rollingPolicy>
<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<MaxFileSize>5MB</MaxFileSize>
</triggeringPolicy>
</appender>
</sift>
</appender>
<logger level="INFO" name="com.j256.ormlite" />
<logger level="INFO" name="org.apache.http" />
<logger level="INFO" name="org.jboss.resteasy.core" />
<logger level="WARN" name="com.j256.ormlite.table.TableUtils" />
<logger level="WARN" name="com.xeiam.sundial" />
<logger level="WARN" name="org.quartz" />
<logger level="WARN" name="io.moquette"/>
<logger level="ERROR" name="io.moquette.persistence.mapdb.MapDBSessionsStore"/>
<logger level="ERROR" name="io.moquette.spi.impl.PersistentQueueMessageSender"/>
<logger level="INFO" name="org.mycontroller.standalone" />
<logger level="INFO" name="org.mycontroller.standalone.api" />
<logger level="INFO" name="org.mycontroller.standalone.api.jaxrs" />
<logger level="INFO" name="org.mycontroller.standalone.auth" />
<logger level="INFO" name="org.mycontroller.standalone.backup" />
<logger level="INFO" name="org.mycontroller.standalone.db" />
<logger level="INFO" name="org.mycontroller.standalone.db.dao" />
<logger level="INFO" name="org.mycontroller.standalone.db.migration" />
<logger level="INFO" name="org.mycontroller.standalone.email" />
<logger level="INFO" name="org.mycontroller.standalone.fwpayload" />
<logger level="INFO" name="org.mycontroller.standalone.gateway" />
<logger level="INFO" name="org.mycontroller.standalone.gateway.ethernet" />
<logger level="INFO" name="org.mycontroller.standalone.gateway.mqtt" />
<logger level="INFO" name="org.mycontroller.standalone.gateway.phantio" />
<logger level="INFO" name="org.mycontroller.standalone.gateway.philipshue" />
<logger level="INFO" name="org.mycontroller.standalone.gateway.rest" />
<logger level="INFO" name="org.mycontroller.standalone.gateway.serial" />
<logger level="INFO" name="org.mycontroller.standalone.gateway.wunderground" />
<logger level="INFO" name="org.mycontroller.standalone.group" />
<logger level="INFO" name="org.mycontroller.standalone.jobs" />
<logger level="INFO" name="org.mycontroller.standalone.loggers.LoggerMySql" />
<logger level="INFO" name="org.mycontroller.standalone.message" />
<logger level="INFO" name="org.mycontroller.standalone.metric" />
<logger level="INFO" name="org.mycontroller.standalone.metric.jobs" />
<logger level="INFO" name="org.mycontroller.standalone.mqttbroker" />
<logger level="INFO" name="org.mycontroller.standalone.provider" />
<logger level="INFO" name="org.mycontroller.standalone.provider.mycontroller" />
<logger level="INFO" name="org.mycontroller.standalone.provider.mysensors" />
<logger level="INFO" name="org.mycontroller.standalone.provider.phantio" />
<logger level="INFO" name="org.mycontroller.standalone.provider.philipshue" />
<logger level="INFO" name="org.mycontroller.standalone.provider.rflink" />
<logger level="INFO" name="org.mycontroller.standalone.provider.wunderground" />
<logger level="INFO" name="org.mycontroller.standalone.restclient" />
<logger level="INFO" name="org.mycontroller.standalone.rule" />
<logger level="INFO" name="org.mycontroller.standalone.scheduler" />
<logger level="INFO" name="org.mycontroller.standalone.scripts" />
<logger level="INFO" name="org.mycontroller.standalone.settings" />
<logger level="INFO" name="org.mycontroller.standalone.timer" />
<logger level="INFO" name="org.mycontroller.standalone.uidtag" />
<root level="WARN">
<appender-ref ref="FILE" />
</root>
<logger name="RAW_MESSAGE_LOGGER" level="INFO" additivity="false">
<appender-ref ref="GATEWAY_RAW_MESSAGE_APPENDER" />
</logger>
</configuration>

BIN
conf/mycontroller.mv.db Normal file

Binary file not shown.

View File

@@ -0,0 +1,134 @@
#
# Copyright 2015-2018 Jeeva Kandasamy (jkandasa@gmail.com)
# and other contributors as indicated by the @author tags.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#========================================================================
# Mycontroller.org properties
# If you change any settings in this file,
# Mycontroller.org server restart is required, to apply new configuration
#========================================================================
#=========================================================================================================
# Data Processing Agreement
# -------------------------
# By using this software you agree that the following non-PII (non personally identifiable information)
# data will be collected, processed and used by MyController.org for the purpose of improving quality of
# MyController software.
# If you do not like to share setup anonymous data, disable it here, by setting false
# restart the server and logout and login in the UI
#=========================================================================================================
mcc.collect.anonymous.data=true
#========================================================================
# Application temporary location
#========================================================================
mcc.tmp.location=tmp/
#========================================================================
# Resources location
#========================================================================
mcc.resources.location=../conf/resources/
#========================================================================
# Database settings
# It is highly recommended to take a backup of this db on upgrade.
# MyController only supports database backup for H2DB(only on same host)
# For other databases users has to manage backup and restore of database
# mcc.db.backup.include: Include database backup along with
# MyController backup. Supports only for H2DB on same host.
# If MyController is running on embedded database mode, this parameter
# will be ignored and backup includes database also.
# mcc.db.type: Select database types
# Supported types: H2DB_EMBEDDED, H2DB, MYSQL, POSTGRESQL, MARIADB
#========================================================================
mcc.db.backup.include=true
#H2DB Embedded settings
mcc.db.type=H2DB_EMBEDDED
mcc.db.url=jdbc:h2:file:../conf/mycontroller;MVCC=TRUE
mcc.db.username=mycontroller
mcc.db.password=mycontroller
# H2DB on TCP settings - Sample
#mcc.db.type=H2DB
#mcc.db.url=jdbc:h2:tcp://localhost//tmp/mycontroller;MVCC=TRUE
#mcc.db.username=mycontroller
#mcc.db.password=mycontroller
# MariaDB settings - Sample
#mcc.db.type=MARIADB
#mcc.db.url=jdbc:mariadb://127.0.0.1:3306/mycontroller
#mcc.db.username=mycontroller
#mcc.db.password=mycontroller
# PostgreSQL settings - Sample
#mcc.db.type=POSTGRESQL
#mcc.db.url=jdbc:postgresql://localhost:5432/mycontroller
#mcc.db.username=mycontroller
#mcc.db.password=mycontroller
# MySQL settings - Sample
#mcc.db.type=MYSQL
#mcc.db.url=jdbc:mysql://localhost:3306/mycontroller
#mcc.db.username=mycontroller
#mcc.db.password=mycontroller
#========================================================================
# Web Application server configuration
# bind.address - interface to bind. 0.0.0.0 - all available interfaces
# You can use either http or https, enable.https - https is enabled
# if https is enabled specify keystore file details
# It is highly recommended to use https also change default keystore file
# Web files, will be located under ../www by default
# For web used angularjs
#========================================================================
mcc.web.bind.address=0.0.0.0
mcc.web.enable.https=true
mcc.web.http.port=8443
mcc.web.file.location=../www/
mcc.web.ssl.keystore.file=../conf/keystore.jks
mcc.web.ssl.keystore.password=mycontroller
mcc.web.ssl.keystore.type=JKS
#========================================================================
# ** MQTT broker configuration **
# broker.enabled - Enable/Disable MQTT broker from back-end
# ** Other settings are available on the GUI **
# ** If MQTT broker disabled here. Cannot enable it from GUI. **
#========================================================================
mcc.mqtt.broker.enabled=true
#========================================================================
# MyController persistent stores location.
# This store used to keep off-heap data.
# It keeps data like messages queue, MQTT broker data, etc.
# If you want to keep execute old data that not processed on shutdown
# set false on mcc.clear.message.queue.on.start
# If you want to keep smart sleep messages on MyController reboot,
# set false on mcc.clear.smart.sleep.msg.queue.on.start
#========================================================================
mcc.persistent.stores.location=../conf/persistent_stores/
mcc.clear.message.queue.on.start=true
mcc.clear.smart.sleep.msg.queue.on.start=true
#========================================================================
# MyController mDNS service settings
# Enable or disable mDNS service
#========================================================================
mcc.mdns.service.enable=false
#logger configuration - logback.xml

2068
conf/mycontroller.trace.db Normal file

File diff suppressed because it is too large Load Diff

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1 @@
"[{\"columns\":[{\"styleClass\":\"col-md-4\",\"widgets\":[{\"type\":\"mycTime\",\"config\":{\"datePattern\":\"MMM dd, yyyy\",\"refreshTime\":\"120\"},\"title\":\"MyController time\",\"titleTemplateUrl\":\"../src/templates/widget-title.html\",\"wid\":\"1454676806001-1\"},{\"type\":\"mycSunriseTime\",\"config\":{\"refreshTime\":\"300\"},\"title\":\"Sunrise and sunset time\",\"titleTemplateUrl\":\"../src/templates/widget-title.html\",\"wid\":\"1454685464871-1\"}],\"cid\":\"1574885484919-2\"},{\"styleClass\":\"col-md-4\",\"widgets\":[{\"type\":\"mycSenVars\",\"config\":{\"variableIds\":[\"3\",\"4\"],\"showIcon\":true,\"confirmationEnabled\":false,\"itemsPerRow\":\"2\",\"refreshTime\":30},\"title\":\"Garage Doors\",\"titleTemplateUrl\":\"../src/templates/widget-title.html\",\"wid\":\"1574885450524-1\"}],\"cid\":\"1574885484920-3\"},{\"styleClass\":\"col-md-4\",\"widgets\":[],\"cid\":\"1574885484921-4\"}]},{\"columns\":[{\"styleClass\":\"col-md-12\",\"widgets\":[],\"cid\":\"1574885484922-5\"}]}]"

View File

@@ -0,0 +1,4 @@
northDoorOpen = mcApi.uidTag().getByUid("north-garage-door-tripped").getResource();
southDoorOpen = mcApi.uidTag().getByUid("south-garage-door-tripped").getResource();
!northDoorOpen || !southDoorOpen

View File

@@ -0,0 +1,19 @@
<!DOCTYPE html>
<html>
<style>body {font-size: 12px;}</style>
<body>
<b>Dear User,</b>
<br>
<br>There is a rule triggered for you!
<br>
<br>
<table border='0'>
<tr><td>Rule definition name</td><td>: ${notification.ruleName}</td> <tr>
<tr><td>Condition</td><td>: ${notification.ruleCondition}</td><tr>
<tr><td>Actual value</td><td>: ${notification.actualValue}</td><tr>
<tr><td>Triggered at</td><td>: ${notification.triggeredAt}</td><tr>
</table>
<br>
<br>-- Powered by <a href='http://www.MyController.org'>www.MyController.org</a>
</body>
</html>

1
logs/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
*.log

View File

View File

@@ -0,0 +1,25 @@
$.when(
//this list is automatically generated by
//Utilites > HTML additional headers > Script files
$.Deferred(function(deferred) { $(deferred.resolve);})
).done(function() {
//this list is automatically generated by
//Utilities > HTML additional headers > Additional AngularJS modules to load
let aModules = [
];
//test each module name to prevent AngularJS from failing to load
let aWorkingModules = [];
for(let i = 0; i < aModules.length; i++)
{
try {
angular.module(aModules[i]); //test if module loads
aWorkingModules.push(aModules[i]); //put working module on list
}
//throw an error, if module can not be loaded
catch(ex) { console.log('unable to load module ' + aModules[i]); }
}
//resume bootstrap process which was halted with /defer_angular_bootstrap.js
//and load working modules
angular.resumeBootstrap(aWorkingModules);
});

View File

@@ -0,0 +1,21 @@
{
"timezone" : "-0600",
"timezoneMilliseconds" : -21600000,
"timezoneString" : "CST",
"appVersion" : "1.4.0.Final",
"systemDate" : 1574884623419,
"appName" : "MyController.org",
"languageId" : "en_us",
"language" : "English (US)",
"dateFormat" : "MMM dd, yyyy hh:mm:ss a",
"dateFormatWithoutSeconds" : "MMM dd, yyyy hh:mm a",
"timeFormat" : "hh:mm:ss a",
"timeFormatWithoutSeconds" : "hh:mm a",
"timeFormatSet" : "12 hours",
"loginMessage" : "Default username: <b>admin</b>, password: <b>admin<b>",
"globalPageRefreshTime" : 30000,
"dashboardLimit" : 5,
"tableRowsLimit" : 10,
"googleAnalyticsEnabled" : true,
"googleAnalyticsTid" : "UA-127071169-1"
}

20
www/angular_defer_bootstrap.js vendored Normal file
View File

@@ -0,0 +1,20 @@
/*
* Copyright 2015-2018 Jeeva Kandasamy (jkandasa@gmail.com)
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//set the window.name to signal AangularJS to delay bootstrapping until resumeBootstrap() is called
//see: https://docs.angularjs.org/guide/bootstrap
window.name = 'NG_DEFER_BOOTSTRAP! ' + window.name;

882
www/app.css Normal file
View File

@@ -0,0 +1,882 @@
/*
* Copyright 2015-2019 Jeeva Kandasamy (jkandasa@gmail.com)
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* app css stylesheet */
body {
background-color: #f5f5f5;
line-height: 1.4;
padding-bottom: 20px;
}
.top-buffer-nm { margin-top:20px; }
.top-buffer-m { margin-top:100px; }
.fa-check-circle-o {
color: #3f9c35;
}
.mc-top-space{
margin-top: 20px;
}
.mc-top-space-header{
margin-top: 25px;
}
.mc-top-space-1x{
margin-top: 35px;
}
.mc-top-space-2x{
margin-top: 60px;
}
.mc-bottom-space{
margin-bottom: 40px;
}
.mc-text-red{
color: red;
}
/*
.fa-arrow-down {
color: #c00;
}
*/
.mc-single-row{
white-space: nowrap;
}
.mc-cards-offset {
margin-top: 30px;
}
.mc-align-center {
text-align: center; /* center checkbox horizontally */
vertical-align: middle; /* center checkbox vertically */
}
.mc-table {
background-color: #ffffff;
}
.mc-table > thead > tr > th {
background-color: #313131;
color: #d0d0d0;
font-weight: bold;
padding-left: 10px;
padding-right: 10px;
padding-top: 5px;
padding-bottom: 5px;
vertical-align: middle;
}
.mc-table > tbody > tr > td {
padding-left: 5px;
padding-right: 5px;
padding-top: 5px;
padding-bottom: 5px;
vertical-align: middle;
}
.mc-table > tbody > tr:hover > td {
cursor: pointer;
background-color:#a3c1db;
}
.mc-table > tbody > tr.mc-selected > td{
background-color: #4077a5;
color: white;
}
.mc-table > tbody > tr.mc-selected > td .pficon,
.mc-table > tbody > tr.mc-selected > td .fa{
color: #ffffff;
}
.mc-form-actions-separator {
border-top: 1px solid #e5e5e5;
padding-top: 15px;
text-align: right;
}
/* Till now not used anywhere */
.mc-graph .mc-spinner-container {
margin-bottom: 50px;
margin-top: 60px;
}
.mc-urls-list {
padding: 0 40px 0 10px;
}
/* END */
.mc-side-space{
margin-right: 10px;
margin-left: 10px;
}
.mc-spinner-container-alone {
margin-top: 220px;
}
.navbar-pf {
margin-bottom: 10px;
}
@media (min-width: 768px) {
.navbar-header {
padding: 0px 0;
}
.navbar-pf .navbar-utility > li > a {
padding: 12px 10px;
}
.navbar-pf .navbar-utility li.dropdown > .dropdown-toggle .pficon-user {
top: 12px;
}
}
@media (max-width: 767px) {
.navbar-pf {
padding-top: 1px;
}
}
.dropdown-menu li:not(.active) > a:hover:active {
background-color: #0099d3;
}
.mc-form-fixer-left {
padding-left:20px;
padding-right:5px;
}
.mc-form-fixer {
padding-left:5px;
padding-right:5px;
}
/* color-1 */
.mc-color-teal {
color: #fff;
background-color: #008080;
border-color: #007070;
}
.mc-color-teal:focus,
.mc-color-teal.focus {
color: #fff;
background-color: #006565;
border-color: #005050;
}
.mc-color-teal:hover {
color: #fff;
background-color: #006565;
border-color: #005050;
}
.mc-color-teal::-webkit-input-placeholder {
color: #ccc;
font-weight: normal;
}
input.mc-color-teal{
font-weight: 600;
}
/* color-2 */
.mc-color-slate-gray {
color: #fff;
background-color: #708090;
border-color: #607080;
}
.mc-color-slate-gray:focus,
.mc-color-slate-gray.focus {
color: #fff;
background-color: #607080;
border-color: #506070;
}
.mc-color-slate-gray:hover {
color: #fff;
background-color: #607080;
border-color: #506070;
}
.mc-color-slate-gray::-webkit-input-placeholder {
color: #ccc;
font-weight: normal;
}
input.mc-color-slate-gray{
font-weight: 600;
}
/* color-3 */
.mc-color-indian-red {
color: #fff;
background-color: #cd5c5c;
border-color: #bc4b4b;
}
.mc-color-indian-red:focus,
.mc-color-indian-red.focus {
color: #fff;
background-color: #bc4b4b;
border-color: #ab3a3a;
}
.mc-color-indian-red:hover {
color: #fff;
background-color: #bc4b4b;
border-color: #ab3a3a;
}
.mc-color-indian-red::-webkit-input-placeholder {
color: #ccc;
font-weight: normal;
}
input.mc-color-indian-red{
font-weight: 600;
}
/* color-4*/
.mc-color-rosy-brown {
color: #fff;
background-color: #9a6d6d;
border-color: #895c5c;
}
.mc-color-rosy-brown:focus,
.mc-color-rosy-brown.focus {
color: #fff;
background-color: #895c5c;
border-color: #784b4b;
}
.mc-color-rosy-brown:hover {
color: #fff;
background-color: #895c5c;
border-color: #784b4b;
}
.mc-color-rosy-brown::-webkit-input-placeholder {
color: #eee;
font-weight: normal;
}
input.mc-color-rosy-brown{
font-weight: 600;
}
/* color-5 */
.mc-color-tan {
color: #fff;
background-color: #af8159;
border-color: #9e7058;
}
.mc-color-tan:focus,
.mc-color-tan.focus {
color: #fff;
background-color: #9e7058;
border-color: #8d6f47;
}
.mc-color-tan:hover {
color: #fff;
background-color: #9e7058;
border-color: #8d6f47;
}
.mc-color-tan::-webkit-input-placeholder {
color: #ddd;
font-weight: normal;
}
input.mc-color-tan{
font-weight: 600;
}
/* color-6 */
.mc-color-steel-blue {
color: #fff;
background-color: #2b4f6e;
border-color: #24425c;
}
.mc-color-steel-blue:focus,
.mc-color-steel-blue.focus {
color: #fff;
background-color: #24425c;
border-color: #1d3549;
}
.mc-color-steel-blue:hover {
color: #fff;
background-color: #24425c;
border-color: #1d3549;
}
.mc-color-steel-blue::-webkit-input-placeholder {
color: #eee;
font-weight: normal;
}
input.mc-color-steel-blue{
font-weight: 600;
}
.mc-model-text-margin {
margin-top:5px;
margin-bottom:5px;
}
/* on angular-patternfly upgrade from 2.x to 3.x introduced issue on sensors-action page.
* To overcome this issue copied style from old version.
* following style used only on sensors-action page.
* */
.data-list-pf {
background: #fff;
overflow-x: hidden;
overflow-y: auto;
padding-bottom: 1px;
}
.data-list-pf .list-row {
margin-right: 0px;
position: relative;
padding-right: 0px;
width: 100%;
}
.data-list-pf .list-content {
left: 15px;
position: relative;
}
.data-list-pf .list-content.with-check-box {
border-left: solid 2px #d2d2d2;
left: 30px;
margin-left: 10px;
}
.data-list-pf .list-content.with-menu {
margin-right: 30px;
right: 15px;
}
.data-list-pf .list-check-box {
bottom: 0px;
left: 20px;
position: absolute;
top: 0px;
width: 20px;
}
.data-list-pf .data-list-loading {
background: rgba(0, 0, 0, 0.05);
}
.data-list-pf .list-group-item:first-of-type {
margin-top: 0;
}
.data-list-pf .list-group-item .list-column {
float: left;
padding: 5px 0px;
}
.data-list-pf .list-group-item .pficon {
-webkit-align-items: center;
align-items: center;
color: #1186C1;
font-size: 26px;
width: 26px;
}
.data-list-pf .list-group-item.active,
.data-list-pf .list-group-item.active:hover,
.data-list-pf .list-group-item.active:focus {
background-color: #def3ff;
border-color: #def3ff;
color: #000000;
}
.data-list-pf .list-group-item:hover,
.data-list-pf .list-group-item:focus {
background-color: #ededed;
border-color: #ededed;
}
.data-list-pf .list-group-item.active .pficon,
.data-list-pf .list-group-item.active:hover .pficon,
.data-list-pf .list-group-item.active:focus .pficon {
color: #ffffff;
}
.data-list-pf .row-column {
padding-right: 5px;
}
/* used in sensors action board list items */
.mc-list-align {
display: flex;
border-bottom: 2px solid #f5f5f5;
border-top: 2px solid #f5f5f5;
line-height: 33px;
}
.mc-list-align {
display: flex;
border-bottom: 2px solid #f5f5f5;
border-top: 2px solid #f5f5f5;
line-height: 33px;
}
.mc-list-align:nth-child(odd) {
background-color: #ffffff;
}
.mc-list-align:nth-child(even) {
background-color: #fbfbfb;
}
/* Dropdown size in sensors action board(sab) */
.mc-sab-dropdown {
width:117px !important;
}
.mc-top-space-5px{
margin-top: 5px;
}
.mc-icon{
font-size:15px;
vertical-align: middle;
margin-right: 5px;
}
.mc-icon{
font-size:100%;
vertical-align: middle;
margin-right: 5px;
}
.mc-icon-md-1{
font-size:110%;
vertical-align: middle;
margin-right: 5px;
}
.mc-icon-md-3{
font-size:130%;
vertical-align: middle;
margin-right: 5px;
}
.mc-icon-lg{
font-size:150%;
vertical-align: middle;
margin-right: 5px;
}
.mc-icon-2x{
font-size:200%;
vertical-align: middle;
margin-right: 5px;
}
.mc-inline-editer-ab{
color: #000000;
cursor: pointer;
font-style:initial;
border-bottom: initial;
}
.mc-inline-editer-ab:hover{
color: #428bca;
font-style:initial;
}
.mc-style-ab{
font-weight: 500;
font-size: 130%;
color:initial;
}
.mc-show-disabled{
background-color: #ffffff !important;
color: #333 !important;
}
.mc-margin-right{
margin-right: 8px;
}
.mc-margin-left{
margin-right: 8px;
}
.mc-margin-icon{
margin-right: 3px;
}
.mc-v-margin > div {
padding:0 20px;
}
.mc-padding {
padding-left:5px;
padding-right:5px;
}
.mc-margin {
margin-left:3px;
margin-right:3px;
}
.dl-horizontal dt {
white-space: normal;
}
.mc-sensor-variable-detail{
height:80px;
}
.mc-sensor-action-tiles{
height:333px;
}
.mc-sa-tiles-variable{
padding-bottom: 3px;
padding-top: 3px;
}
.mc-pointer{
cursor: pointer;
}
/* ADF css */
.adf-myct {
text-align: center;
}
.adf-myct-time {
font-size: 300%;
}
.adf-myct-date {
font-size: 200%;
}
.adf-myct-timezone {
font-size: 80%;
}
/* sunrise sun set*/
.adf-mycsr {
text-align: center;
}
.adf-mycsr-time {
font-size: 200%;
}
.adf-mycsr-time > i{
margin-left: 10px;
margin-right: 10px;
margin-bottom:10px;
font-size: 150%;
vertical-align: middle;
}
.adf-mycsr-location {
font-size: 150%;
}
.adf-mycsr-location > i{
margin-left: 10px;
margin-right: 10px;
font-size: 120%;
vertical-align: middle;
}
.adf-myc-sen-var{
height:75px;
}
.adf-myc-sen-var > .card-pf-title > .fa{
font-size: 12px;
margin-left:2px;
margin-right:2px;
}
.adf-myc-sbg{
height:70px;
}
.adf-myc-sbg-margin{
margin-top:5px;
margin-bottom:7px;
}
.adf-myc-dsi-image{
display: block;
margin-left: auto;
margin-right: auto;
max-height:100%;
max-width:100%;
}
.adf-myc-shm-margin > .heatmap-pf-container > h3{
margin:0px;
}
/* custom buttons */
#custom-buttons-wrapper .btn {
margin: 3px 0px 3px 3px;
font-weight: bold;
font-size: 21px;
}
.adf-myc-cb-margin{
margin-top:5px;
margin-bottom:5px;
}
/* ADF Table widget */
.adf-table > tbody > tr > td{
padding-left: 2px;
padding-right: 5px;
padding-top: 2px;
padding-bottom: 5px;
vertical-align: middle;
}
/* on-off button*/
.bootstrap-switch-on{
font-weight: 600;
}
.bootstrap-switch-off {
font-weight: 500;
}
/* sensors list under rooms page */
.mc-sensors-room {
display: flex;
justify-content: center;
}
.mc-sensors-hr {
margin-top: 3px;
margin-bottom: 0px;
}
kubernetes-topology-graph {
border: 2px solid lightgray;
background-color: #FCFCFC;
}
.container_topology .legend {
padding-top: 5px;
/*font-family: sans-serif;*/
font-size: 15px;
display: inline-block;
vertical-align: middle;
}
.container_topology .legend label {
font-weight: 400;
cursor: pointer;
vertical-align: 10px;
}
.container_topology #selected {
float: right;
display: block;
margin-top: 15px;
}
kubernetes-topology-icon {
padding: 4px 11px 4px 2px !important;
opacity: 0.4;
}
kubernetes-topology-icon.active {
opacity: 1;
}
kubernetes-topology-icon svg {
width: 39px !important;
height: 39px !important;
display: inline-block;
}
.kube-topology g text.attached-label {
display: none;
}
.kube-topology g text.attached-label.visible {
font-size: 12px;
fill: black;
display: block;
}
.kube-topology g.selected {
stroke-width: 4px;
}
.kube-topology g circle {
stroke-width: 2px;
}
.kube-topology g circle.success {
stroke: #3F9C35;
}
.kube-topology g circle.error {
stroke: #CC0000;
}
.kube-topology g circle.warning {
stroke: #EC7A08;
}
.kube-topology g circle.unknown {
stroke: #bbb;
}
.container_topology .canvas {
position: absolute;
}
.container_topology .popup {
position: absolute;
left: 0;
top: 0;
background-color: #fff;
width: 180px;
border: 1px #ccc solid;
border-radius: 6px;
box-shadow: #333 2px 2px 4px;
padding: 6px;
font-size: 14px;
}
.container_topology .popup h5 {
font-weight: bold;
}
.container_topology .popup p {
margin: 0 0 4px;
}
.container_topology .popup p:hover {
color : #0099cc;
cursor: pointer;
}
.container_topology label.checkbox-inline {
font-size:14px;
}
/* Specify styling for uib-tooltip contents */
.tooltip.customClass450px .tooltip-inner {
min-width: 450px;
text-align: left;
}
/* Specify styling for uib-tooltip contents */
.tooltip.customClass350px .tooltip-inner {
min-width: 350px;
text-align: left;
}
.battery-modal-window .modal-dialog {
width: 95%;
}
.tick line {
/* When you do not want to display grid line on your charts enable, 'display:none;' */
/* display: none; */
}
.modal-body {
position: relative;
padding-top: 20px;
padding-right: 10px;
padding-bottom: 2px;
padding-left: 10px;
}
.modal-body-text-only {
position: relative;
padding: 5px 20px;
}
.modal-header {
background-color: rgba(0, 0, 0, 0.07);
}
.modal-footer {
padding: 12px;
}
.mc-dialog {
/*border-style: solid;
border-width: 1px;
border-color: #D3D3D3;*/
}
.panel-body-action-board {
padding-top: 3px;
}
.multiSelect > button {
font-size: 12px;
min-height: 35px !important;
border-radius: 0px;
}
/* Specify styling for angular-bootstrap-colorpicker contents */
.close-colorpicker {
color:gray;
}
.close-colorpicker:hover {
color:black;
}
.text-color-red {
color:red;
}
.text-color-green {
color:green;
}
.text-color-gray {
color:gray;
}

869
www/app.js Normal file
View File

@@ -0,0 +1,869 @@
/*
* Copyright 2015-2018 Jeeva Kandasamy (jkandasa@gmail.com)
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
// Declare app level module which depends on views, and components
var myControllerModule = angular.module('myController',[
'ui.router',
'ui.bootstrap',
'ngResource',
'ngCookies',
'ui.bootstrap.datetimepicker',
'base64',
'colorpicker.module',
'ngFileSaver',
'pascalprecht.translate',
'ngSanitize',
'nvd3',
'patternfly',
'patternfly.charts',
'patternfly.select',
'patternfly.views',
'patternfly.filters',
'patternfly.card',
'patternfly.toolbars',
'frapontillo.bootstrap-switch',
'xeditable',
'angularUtils.directives.dirPagination',
'frapontillo.bootstrap-duallistbox',
'angularMoment',
'adf',
'adf.structures.base',
'adf.widget.myc-a-sensor-graph',
'adf.widget.myc-custom-widget',
'adf.widget.myc-dsi',
'adf.widget.myc-sensors-grouped-graph',
'adf.widget.myc-groups',
'adf.widget.myc-heat-map',
'adf.widget.myc-sensors-mixed-graph',
'adf.widget.myc-time',
'adf.widget.news',
'adf.widget.myc-os-commands',
'adf.widget.myc-custom-buttons',
'adf.widget.myc-sen-vars',
'adf.widget.myc-sensors-bullet-graph',
'adf.widget.myc-sunrisetime',
'ngMap',
'kubernetesUI',
]);
myControllerModule.constant("mchelper", {
internal:{},
cfg:{},
languages:{},
user:{},
userSettings:{},
});
myControllerModule.config(function($stateProvider, $urlRouterProvider) {
//For any unmatched url, redirect to /dashboard
$urlRouterProvider.otherwise('/dashboard');
$stateProvider
/* Dashboard */
.state('dashboardMain', {
url:"/dashboard",
templateUrl: "partials/dashboard/dashboard.html?mcv=29",
controller: "DashboardListController",
data: {
requireLogin: true
}
}).state('dashboardRoomsSensorsList', {
url:"/dashboard/rooms/list/:id",
templateUrl: "partials/rooms/rooms-sensors-list.html?mcv=29",
controller: "RoomsSensorsControllerList",
data: {
requireLogin: true
}
}).state('dashboardTopology', {
url:"/dashboard/topology/:resourceType/:resourceId",
templateUrl: "partials/topology/topology.html?mcv=29",
controller: "TopologyController",
data: {
requireLogin: true
}
})
/* Resources */
.state('gatewaysList', {
url:"/resources/gateways/list",
templateUrl: "partials/gateways/gateways-list.html?mcv=29",
controller: "GatewaysController",
data: {
requireLogin: true
}
}).state('gatewaysAddEdit', {
url:"/resources/gateways/addedit/:id",
templateUrl: "partials/gateways/gateway-add-edit.html?mcv=29",
controller: "GatewaysControllerAddEdit",
data: {
requireLogin: true
}
}).state('gatewaysDetail', {
url:"/resources/gateways/detail/:id",
templateUrl: "partials/gateways/gateways-detail.html?mcv=29",
controller: "GatewaysControllerDetail",
data: {
requireLogin: true
}
}).state('nodesList', {
url:"/resources/nodes/list/:gatewayId",
templateUrl: "partials/nodes/nodes-list.html?mcv=29",
controller: "NodesController",
data: {
requireLogin: true
}
}).state('nodesAddEdit', {
url:"/resources/nodes/addedit/:id",
templateUrl: "partials/nodes/node-add-edit.html?mcv=29",
controller: "NodesControllerAddEdit",
data: {
requireLogin: true
}
}).state('nodesDetail', {
url:"/resources/nodes/detail/:id",
templateUrl: "partials/nodes/node-detail.html?mcv=29",
controller: "NodesControllerDetail",
data: {
requireLogin: true
}
}).state('sensorsList', {
url:"/resources/sensors/list/:nodeId",
templateUrl: "partials/sensors/sensors-list.html?mcv=29",
controller: "SensorsController",
data: {
requireLogin: true
}
}).state('sensorsAddEdit', {
url:"/resources/sensors/addedit/:id",
templateUrl: "partials/sensors/sensor-add-edit.html?mcv=29",
controller: "SensorsControllerAddEdit",
data: {
requireLogin: true
}
}).state('sensorVariablePurge', {
url:"/resources/sensorvariable/purge/:id",
templateUrl: "partials/sensors/sensor-variable-purge.html?mcv=29",
controller: "SensorVariableControllerPurge",
data: {
requireLogin: true
}
}).state('sensorVariableEdit', {
url:"/resources/sensorvariable/edit/:id",
templateUrl: "partials/sensors/sensor-variable-edit.html?mcv=29",
controller: "SensorVariableControllerEdit",
data: {
requireLogin: true
}
}).state('sensorsDetail', {
url:"/resources/sensors/detail/:id",
templateUrl: "partials/sensors/sensors-detail.html?mcv=29",
controller: "SensorsControllerDetail",
data: {
requireLogin: true
}
}).state('rulesList', {
url:"/resources/rules/list/:resourceType/:resourceId",
templateUrl: "partials/rule-engine/rules-list.html?mcv=29",
controller: "RuleEngineController",
data: {
requireLogin: true
}
}).state('rulesAddEdit', {
url:"/resources/rules/addedit/:id/:action",
templateUrl: "partials/rule-engine/rules-add-edit.html?mcv=29",
controller: "RuleEngineControllerAddEdit",
data: {
requireLogin: true
}
}).state('operationsList', {
url:"/resources/operations/list",
templateUrl: "partials/operations/operations-list.html?mcv=29",
controller: "OperationsController",
data: {
requireLogin: true
}
}).state('operationsAddEdit', {
url:"/resources/operations/addedit/:id/:action",
templateUrl: "partials/operations/operations-add-edit.html?mcv=29",
controller: "OperationsControllerAddEdit",
data: {
requireLogin: true
}
}).state('forwardPayloadList', {
url:"/resources/forwardpayload/list/:sensorId",
templateUrl: "partials/forward-payload/forward-payload-list.html?mcv=29",
controller: "ForwardPayloadController",
data: {
requireLogin: true
}
}).state('forwardPayloadAddEdit', {
url:"/resources/forwardpayload/addedit/:id",
templateUrl: "partials/forward-payload/forward-payload-add-edit.html?mcv=29",
controller: "ForwardPayloadControllerAddEdit",
data: {
requireLogin: true
}
}).state('resourcesGroupList', {
url:"/resources/groups/list/:resourceType/:resourceId",
templateUrl: "partials/resources-group/resources-group-list.html?mcv=29",
controller: "ResourcesGroupController",
data: {
requireLogin: true
}
}).state('resourcesGroupAddEdit', {
url:"/resources/groups/addedit/:id",
templateUrl: "partials/resources-group/resources-group-add-edit.html?mcv=29",
controller: "ResourcesGroupControllerAddEdit",
data: {
requireLogin: true
}
}).state('timersList', {
url:"/resources/timers/list/:resourceType/:resourceId",
templateUrl: "partials/timers/timers-list.html?mcv=29",
controller: "TimersController",
data: {
requireLogin: true
}
}).state('timersAddEdit', {
url:"/resources/timers/addedit/:id/:action",
templateUrl: "partials/timers/timer-add-edit.html?mcv=29",
controller: "TimersControllerAddEdit",
data: {
requireLogin: true
}
}).state('resourcesGroupMapList', {
url:"/resources/groups/map/list/:id",
templateUrl: "partials/resources-group/resources-group-map-list.html?mcv=29",
controller: "ResourcesGroupMapController",
data: {
requireLogin: true
}
}).state('resourcesGroupMapAddEdit', {
url:"/resources/groups/map/addedit/:groupId/:id",
templateUrl: "partials/resources-group/resources-group-map-add-edit.html?mcv=29",
controller: "ResourcesGroupMapControllerAddEdit",
data: {
requireLogin: true
}
}).state('roomsList', {
url:"/resources/rooms/list",
templateUrl: "partials/rooms/rooms-list.html?mcv=29",
controller: "RoomsControllerList",
data: {
requireLogin: true
}
}).state('roomsAddEdit', {
url:"/resources/rooms/addedit/:id",
templateUrl: "partials/rooms/rooms-add-edit.html?mcv=29",
controller: "RoomsControllerAddEdit",
data: {
requireLogin: true
}
})
/* Action board */
.state('actionBoardSensorsList', {
url:"/actionboard/sensorsaction/list",
templateUrl: "partials/action-board/sensors-action-list.html?mcv=29",
controller: "SensorsActionControllerList",
data: {
requireLogin: true
}
}).state('sendRawMessage', {
url:"/actionboard/sendrawmessage",
templateUrl: "partials/send-raw-message/send-raw-message.html?mcv=29",
controller: "SendRawMessageController",
data: {
requireLogin: true
}
})
/* Status */
.state('aboutMyController', {
url:"/status/about",
templateUrl: "partials/status/about.html?mcv=29",
controller: "McAboutController",
data: {
requireLogin: true
}
}).state('statusSystem', {
url:"/status/system",
templateUrl: "partials/status/system-status.html?mcv=29",
controller: "StatusSystemController",
data: {
requireLogin: true
}
}).state('resourcesLogsList', {
url:"/status/resourceslogs/:resourceType/:resourceId",
templateUrl: "partials/resources-logs/resources-logs-list.html?mcv=29",
controller: "ResourcesLogsController",
data: {
requireLogin: true
}
}).state('resourcesLogsPurge', {
url:"/status/resourceslogs/purge",
templateUrl: "partials/resources-logs/resources-logs-purge.html?mcv=29",
controller: "ResourcesLogsPurgeController",
data: {
requireLogin: true
}
}).state('mycontrollerLogList', {
url:"/status/log/mycontroller",
templateUrl: "partials/status/mc-log-list.html?mcv=29",
controller: "StatusMcLogController",
data: {
requireLogin: true
}
})
/* Utilities */
.state('scriptsList', {
url:"/utilities/scripts/list",
templateUrl: "partials/scripts/scripts-list.html?mcv=29",
controller: "ScriptsController",
data: {
requireLogin: true
}
}).state('scriptsAddEdit', {
url:"/utilities/scripts/addedit/:name",
templateUrl: "partials/scripts/scripts-add-edit.html?mcv=29",
controller: "ScriptsControllerAddEdit",
data: {
requireLogin: true
}
}).state('templatesList', {
url:"/utilities/templates/list",
templateUrl: "partials/templates/templates-list.html?mcv=29",
controller: "TemplatesController",
data: {
requireLogin: true
}
}).state('templatesAddEdit', {
url:"/utilities/templates/addedit/:name",
templateUrl: "partials/templates/templates-add-edit.html?mcv=29",
controller: "TemplatesControllerAddEdit",
data: {
requireLogin: true
}
}).state('additionalHeadersUpdate', {
url:"/utilities/additionalheaders/update",
templateUrl: "partials/additional-headers/additional-headers-update.html?mcv=29",
controller: "AdditionalHeadersUpdateController",
data: {
requireLogin: true
}
}).state('variablesRepositoryList', {
url:"/utilities/variables/list",
templateUrl: "partials/variables-repository/variables-list.html?mcv=29",
controller: "VariablesRepositoryController",
data: {
requireLogin: true
}
}).state('variablesRepositoryAddEdit', {
url:"/utilities/variables/addedit/:id",
templateUrl: "partials/variables-repository/variables-add-edit.html?mcv=29",
controller: "VariablesRepositoryControllerAddEdit",
data: {
requireLogin: true
}
}).state('firmwaresList', {
url:"/utilities/firmwares/list",
templateUrl: "partials/firmwares/firmwares-list.html?mcv=29",
controller: "FirmwaresController",
data: {
requireLogin: true
}
}).state('firmwaresAddEdit', {
url:"/utilities/firmwares/addedit/:id",
templateUrl: "partials/firmwares/firmwares-add-edit.html?mcv=29",
controller: "FirmwaresControllerAddEdit",
data: {
requireLogin: true
}
}).state('firmwaresTypeList', {
url:"/utilities/firmwares/type/list",
templateUrl: "partials/firmwares/firmwares-type-list.html?mcv=29",
controller: "FirmwaresTypeController",
data: {
requireLogin: true
}
}).state('firmwaresTypeAddEdit', {
url:"/utilities/firmwares/type/addedit/:id",
templateUrl: "partials/firmwares/firmwares-type-add-edit.html?mcv=29",
controller: "FirmwaresTypeControllerAddEdit",
data: {
requireLogin: true
}
}).state('firmwaresVersionList', {
url:"/utilities/firmwares/version/list",
templateUrl: "partials/firmwares/firmwares-version-list.html?mcv=29",
controller: "FirmwaresVersionController",
data: {
requireLogin: true
}
}).state('firmwaresVersionAddEdit', {
url:"/utilities/firmwares/version/addedit/:id",
templateUrl: "partials/firmwares/firmwares-version-add-edit.html?mcv=29",
controller: "FirmwaresVersionControllerAddEdit",
data: {
requireLogin: true
}
}).state('uidTagsList', {
url:"/utilities/uidtags/list",
templateUrl: "partials/uid-tags/uid-tags-list.html?mcv=29",
controller: "UidTagsController",
data: {
requireLogin: true
}
}).state('uidTagsAddEdit', {
url:"/utilities/uidtags/addedit/:id",
templateUrl: "partials/uid-tags/uid-tags-add-edit.html?mcv=29",
controller: "UidTagsControllerAddEdit",
data: {
requireLogin: true
}
}).state('resourcesDataList', {
url:"/utilities/resourcesdata/list",
templateUrl: "partials/resources-data/resources-data-list.html?mcv=29",
controller: "ResourcesDataController",
data: {
requireLogin: true
}
}).state('resourcesDataAddEdit', {
url:"/utilities/resourcesdata/addedit/:id",
templateUrl: "partials/resources-data/resources-data-add-edit.html?mcv=29",
controller: "ResourcesDataControllerAddEdit",
data: {
requireLogin: true
}
}).state('externalServersList', {
url:"/utilities/externalserver/list",
templateUrl: "partials/external-servers/external-servers-list.html?mcv=29",
controller: "ExternalServerController",
data: {
requireLogin: true
}
}).state('externalServersAddEdit', {
url:"/utilities/externalserver/addedit/:id",
templateUrl: "partials/external-servers/external-server-add-edit.html?mcv=29",
controller: "ExternalServersControllerAddEdit",
data: {
requireLogin: true
}
})
/* Settings */
.state('settingsProfileUpdate', {
url:"/settings/profile/update",
templateUrl: "partials/users-roles/profile-update.html?mcv=29",
controller: "ProfileControllerUpdate",
data: {
requireLogin: true
}
}).state('settingsSystem', {
url:"/settings/system",
templateUrl: "partials/settings/settings-system.html?mcv=29",
controller: "SettingsSystemController",
data: {
requireLogin: true
}
}).state('settingsNotifications', {
url:"/settings/notifications",
templateUrl: "partials/settings/settings-notifications.html?mcv=29",
controller: "SettingsNotificationsController",
data: {
requireLogin: true
}
}).state('settingsMqttBroker', {
url:"/settings/mqttbroker",
templateUrl: "partials/settings/settings-mqtt-broker.html?mcv=29",
controller: "SettingsMqttBrokerController",
data: {
requireLogin: true
}
}).state('settingsMetrics', {
url:"/settings/metrics",
templateUrl: "partials/settings/settings-metrics.html?mcv=29",
controller: "SettingsMetricsController",
data: {
requireLogin: true
}
}).state('settingsMySensors', {
url:"/settings/mysensors",
templateUrl: "partials/settings/settings-mysensors.html?mcv=29",
controller: "SettingsSystemMySensors",
data: {
requireLogin: true
}
}).state('settingsVariablesMapperList', {
url:"/settings/variablesmapper/list",
templateUrl: "partials/variables-mapper/variables-mapper-list.html?mcv=29",
controller: "VariablesMapperListController",
data: {
requireLogin: true
}
}).state('settingsVariablesMapperEdit', {
url:"/settings/variablesmapper/edit/:sensorType",
templateUrl: "partials/variables-mapper/variables-mapper-edit.html?mcv=29",
controller: "VariablesMapperEditController",
data: {
requireLogin: true
}
}).state('settingsUsersList', {
url:"/settings/users/list",
templateUrl: "partials/users-roles/users-list.html?mcv=29",
controller: "UsersControllerList",
data: {
requireLogin: true
}
}).state('settingsUsersAddEdit', {
url:"/settings/users/addedit/:id",
templateUrl: "partials/users-roles/users-add-edit.html?mcv=29",
controller: "UsersControllerAddEdit",
data: {
requireLogin: true
}
}).state('settingsRolesList', {
url:"/settings/roles/list",
templateUrl: "partials/users-roles/roles-list.html?mcv=29",
controller: "RolesControllerList",
data: {
requireLogin: true
}
}).state('settingsRolesAddEdit', {
url:"/settings/roles/addedit/:id",
templateUrl: "partials/users-roles/roles-add-edit.html?mcv=29",
controller: "RolesControllerAddEdit",
data: {
requireLogin: true
}
}).state('settingsBackupList', {
url:"/settings/backup/list",
templateUrl: "partials/backup/backup-list.html?mcv=29",
controller: "BackupControllerList",
data: {
requireLogin: true
}
}).state('settingsBackupAuto', {
url:"/settings/backup/settings",
templateUrl: "partials/backup/automatic-backup-settings.html?mcv=29",
controller: "BackupControllerAutoSettings",
data: {
requireLogin: true
}
})
/* Login */
.state('login', {
url:"/login",
templateUrl: "partials/authentication/login.html?mcv=29",
controller: "LoginController",
data: {
requireLogin: false
},
params: {
'toState': 'dashboardMain', // default state to proceed to after login
'toParams': {}
},
});
});
//McNavCtrl
myControllerModule.controller('McNavBarCtrl', function($scope, $location, $translate, $state, mchelper, SettingsFactory, CommonServices) {
$scope.isCollapsed = true;
$scope.mchelper = mchelper;
$scope.$state = $state;
$scope.isAuthenticated = function () {
return mchelper.internal.currentUser;
};
$scope.changeLanguage = function (lang) {
$translate.use(lang.id);
$scope.languageId = lang.id;
mchelper.cfg.languageId = lang.id;
mchelper.cfg.language = lang.displayName;
//Update selected language
if(mchelper.user.permission === 'Super admin'){
SettingsFactory.updateLanguage(lang.displayName);
}
//Update mchelper
CommonServices.saveMchelper(mchelper);
};
//Show hide main menu
$scope.showHideMainMenu = function () {
if(mchelper.userSettings.hideMenu){
mchelper.userSettings.hideMenu = false;
}else{
mchelper.userSettings.hideMenu = true;
}
//Update mchelper
CommonServices.saveMchelper(mchelper);
};
});
myControllerModule.run(function ($rootScope, $state, $location, $http, mchelper, $translate, editableOptions, CommonServices, $window) {
//Load mchelper from cookies
CommonServices.loadMchelper();
// keep user logged in after page refresh
if(!mchelper){
CommonServices.saveMchelper(CommonServices.loadMchelper());
};
if(mchelper.cfg){
$translate.use(mchelper.cfg.languageId);
}
if (mchelper.internal.currentUser) {
$http.defaults.headers.common['Authorization'] = 'Basic ' + mchelper.internal.currentUser.authdata; // jshint ignore:line
}
// initialise google analytics and send browser details, if enabled
if(mchelper.cfg.googleAnalyticsEnabled){
$window.ga('create', mchelper.cfg.googleAnalyticsTid, 'auto');
$window.ga('send', 'pageview', "/");
}
$rootScope.$on('$stateChangeStart', function (event, toState, toParams) {
//alert(angular.toJson(toState));
if(toState.name.indexOf('login') === 0){
angular.element( document.querySelector( '#rootId' ) ).addClass( "login-pf" );
angular.element( document.querySelector( '#rootView' ) ).removeClass( "container-fluid top-buffer-m top-buffer-nm" );
}else{
angular.element( document.querySelector( '#rootId' ) ).removeClass( "login-pf" );
if(!mchelper.userSettings.hideMenu){
angular.element( document.querySelector( '#rootView' ) ).addClass( "container-fluid top-buffer-m");
}else{
angular.element( document.querySelector( '#rootView' ) ).addClass( "container-fluid top-buffer-nm");
}
}
var requireLogin = toState.data.requireLogin;
// redirect to login page if not logged in
if (requireLogin && !mchelper.internal.currentUser) {
event.preventDefault();
//return $state.go('login');
return $state.go('login', {'toState': toState.name, 'toParams': toParams});
}
});
//update xeditable theme
editableOptions.theme = 'bs3'; // bootstrap3 theme. Can be also 'bs2', 'default'
});
myControllerModule.controller('LoginController',
function ($state, $scope, $rootScope, AuthenticationService, ReadFileFactory, alertService, StatusFactory, TypesFactory, SettingsFactory, displayRestError, CommonServices, mchelper, $translate, $filter) {
// load login page settings
$scope.loginSettings = {};
// reset login status
AuthenticationService.ClearCredentials();
// remove mchelper cookies
//CommonServices.clearCookies();
//Update login page details
ReadFileFactory.getConfigFile(function(configFile){
$scope.loginSettings = configFile;
//Update language
$translate.use($scope.loginSettings.languageId);
});
$scope.login = function () {
$scope.dataLoading = true;
AuthenticationService.Login($scope.username, $scope.password, function(authResponse) {
if(authResponse.success) {
AuthenticationService.SetCredentials($scope.username, $scope.password);
mchelper.user = authResponse.user;//Update user details
StatusFactory.getConfig(function(response) {
mchelper.cfg = response;//Update config
//Update language
$translate.use(mchelper.cfg.languageId);
TypesFactory.getLanguages(function(langResponse){
mchelper.languages = langResponse;
SettingsFactory.getUserSettings(function(userNativeSettings){
mchelper.userSettings = userNativeSettings;
mchelper.userSettings.hideMenu = false;
//Store all the configurations locally
CommonServices.saveMchelper(mchelper);
});
});
},function(error){
displayRestError.display(error);
});
//$state.go('dashboard');
$state.go($state.params.toState, $state.params.toParams);
} else {
if(authResponse.message){
alertService.danger(authResponse.message);
}else{
alertService.danger($filter('translate')('INVALID_USERNAME_OR_PASSWORD'));
}
$scope.dataLoading = false;
}
});
};
});
myControllerModule.filter('millSecondsToTimeString', function() {
return function(millseconds) {
var seconds = Math.floor(millseconds / 1000);
var tmpSeconds = seconds % 60;
var days = Math.floor(seconds / 86400);
var hours = Math.floor((seconds % 86400) / 3600);
var minutes = Math.floor(((seconds % 86400) % 3600) / 60);
var timeString = '';
if(days > 0){
timeString += (days > 1) ? (days + " days ") : (days + " day ");
}
if(hours >0){
timeString += (hours > 1) ? (hours + " hours ") : (hours + " hour ");
}
if(minutes > 0){
timeString += (minutes >1) ? (minutes + " minutes ") : (minutes + " minute ");
}
if(tmpSeconds >= 0){
timeString += (tmpSeconds >1) ? (tmpSeconds + " seconds ") : (tmpSeconds + " second ");
}
return timeString;
}
});
myControllerModule.filter('byteToMBsizeConvertor', function() {
return function(sizeInByte) {
if(sizeInByte < 0){
return "n/a";
}
return Math.floor(sizeInByte /(1024 * 1024)) + " MB";
}
});
myControllerModule.filter('byteToFriendlyConvertor', function() {
return function(sizeInByte) {
if(sizeInByte < 0){
return "n/a";
}else if((sizeInByte /(1024 * 1024)) > 1024){
return (sizeInByte /(1024 * 1024 * 1024)).toFixed(2) + " GB";
}else if((sizeInByte /(1024)) > 1024){
return (sizeInByte /(1024 * 1024)).toFixed(2) + " MB";
}else if(sizeInByte > 1024){
return (sizeInByte /1024).toFixed(2) + " KB";
}
return sizeInByte + " Bytes";
}
});
myControllerModule.filter('mcResourceRepresentation', function() {
return function(text){
if(text === undefined){
return undefined;
}
return text.replace(/>>>/g, '<i class="fa fa-forward"></i>')
.replace(/>>/g, '<i class="fa fa-chevron-right"></i>')
.replace(/\[RG\]:/g, '<i class="pficon pficon-replicator fa-lg mc-margin-icon"></i> ')
.replace(/\[G\]:/g, '<i class="fa fa-plug"></i> ')
.replace(/\[N\]:/g, '<i class="fa fa-sitemap"></i> ')
.replace(/\[S\]:/g, '<i class="fa fa-eye"></i> ')
.replace(/\[SV\]:/g, '')
.replace(/\[T\]:/g, '<i class="fa fa-clock-o"></i> ')
.replace(/\[RD\]:/g, '<i class="fa fa-cogs"></i> ');
}
});
myControllerModule.filter('mcHtml', function($sce) {
return function(htmlText) {
return $sce.trustAsHtml(htmlText);
//return htmlText
};
});
myControllerModule.filter('slice', function() {
return function(arr, start, end) {
return (arr || []).slice(start, end);
};
});
/**
* i18n Language support
* */
myControllerModule.config(function($translateProvider) {
// Enable escaping of HTML
//$translateProvider.useSanitizeValueStrategy('sanitize');
$translateProvider.useSanitizeValueStrategy(null);
$translateProvider.useStaticFilesLoader({
prefix: 'languages/mc_locale_gui-',
suffix: '.json'
});
$translateProvider.preferredLanguage('en_us');
});
//Dashboard custom layouts
myControllerModule.config(function(dashboardProvider){
dashboardProvider
.structure('4-4-4/12', {
rows: [{
columns: [{
styleClass: 'col-md-4'
}, {
styleClass: 'col-md-4'
}, {
styleClass: 'col-md-4'
}]
}, {
columns: [{
styleClass: 'col-md-12'
}]
}]
}).structure('6-6/12', {
rows: [{
columns: [{
styleClass: 'col-md-6'
}, {
styleClass: 'col-md-6'
}]
}, {
columns: [{
styleClass: 'col-md-12'
}]
}]
});
});
//Items Delete Modal
myControllerModule.controller('ControllerDeleteModal', function ($scope, $uibModalInstance, $sce, $filter) {
$scope.header = $filter('translate')('DELETE_ITEMS');
$scope.deleteMsg = $filter('translate')('DELETE_MESSAGE');
$scope.remove = function() {
$uibModalInstance.close();
};
$scope.cancel = function () { $uibModalInstance.dismiss('cancel'); }
});
/*
//Global exception handler
myControllerModule.factory('$exceptionHandler', function () {
return function errorCatcherHandler(exception, cause) {
console.log('Exception cause:'+cause+', Exception:'+angular.toJson(exception));
//throw exception;
};
});
*/

View File

@@ -0,0 +1,50 @@
/*
* Copyright 2015-2018 Jeeva Kandasamy (jkandasa@gmail.com)
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//Additional headers update controller
myControllerModule.controller('AdditionalHeadersUpdateController', function ($scope, $stateParams, $state,
SettingsFactory, mchelper, alertService, displayRestError, $filter, CommonServices, $base64) {
$scope.mchelper = mchelper;
$scope.additionalHeaders = {};
//Get data
$scope.loadData = function(){
SettingsFactory.getHtmlAdditionalHeaders(function(response){
$scope.additionalHeaders = response;
$scope.cssFiles = response.links.join('\n');
$scope.scriptFiles = response.scripts.join('\n');
},function(error){
displayRestError.display(error);
});
};
//GUI page settings
$scope.headerStringAdd = $filter('translate')('HTML_ADDITIONAL_HEADERS');
$scope.cancelButtonState = "additionalHeadersUpdate"; //Cancel button url
$scope.saveProgress = false;
$scope.loadData();
$scope.save = function(){
$scope.saveProgress = true;
SettingsFactory.updateHtmlAdditionalHeaders($scope.additionalHeaders, function(response) {
alertService.success($filter('translate')('ITEM_UPDATED_SUCCESSFULLY'));
$scope.saveProgress = false;
},function(error){
displayRestError.display(error);
$scope.saveProgress = false;
});
}
});

View File

@@ -0,0 +1,159 @@
/*
* Copyright 2015-2018 Jeeva Kandasamy (jkandasa@gmail.com)
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// don't forget to declare this service module as a dependency in your main app constructor!
//http://js2.coffee/#coffee2js
//https://coderwall.com/p/r_bvhg/angular-ui-bootstrap-alert-service-for-angular-js
'use strict';
angular.module('adf.widget.myc-a-sensor-graph', [])
.config(function(dashboardProvider){
dashboardProvider
.widget('mycSingleSensorGraph', {
title: 'A sensor graphical view',
description: 'Displays a sensor graphical view',
templateUrl: 'controllers/adf-widgets/adf-myc-asg/view.html?mcv=29',
controller: 'mycSingleSensorGraphController',
controllerAs: 'mycSingleSensorGraph',
config: {
variableId:null,
withMinMax:false,
chartFromTimestamp:'3600000',
refreshTime:30,
marginTop:5,
marginRight:20,
marginBottom:60,
marginLeft:65,
},
edit: {
templateUrl: 'controllers/adf-widgets/adf-myc-asg/edit.html?mcv=29',
controller: 'mycSingleSensorGraphEditController',
controllerAs: 'mycSingleSensorGraphEdit',
}
});
})
.controller('mycSingleSensorGraphController', function($scope, $interval, config, mchelper, $filter, MetricsFactory, TypesFactory, CommonServices){
var mycSingleSensorGraph = this;
mycSingleSensorGraph.showLoading = true;
mycSingleSensorGraph.showError = false;
mycSingleSensorGraph.isSyncing = false;
mycSingleSensorGraph.variables = {};
$scope.tooltipEnabled = false;
$scope.hideVariableName=true;
$scope.cs = CommonServices;
CommonServices.updateGraphMarginDefault(config);
mycSingleSensorGraph.chartOptions = {
chart: {
type: 'lineChart',
noErrorCheck: true,
height: 225,
margin : {
top: config.marginTop,
right: config.marginRight,
bottom: config.marginBottom,
left: config.marginLeft,
},
color: ["#2ca02c","#1f77b4", "#ff7f0e"],
noData:"No data available.",
x: function(d){return d[0];},
y: function(d){return d[1];},
useVoronoi: false,
clipEdge: false,
useInteractiveGuideline: true,
xAxis: {
showMaxMin: false,
tickFormat: function(d) {
return d3.time.format('hh:mm a')(new Date(d))
},
//axisLabel: 'Timestamp',
rotateLabels: -20
},
yAxis: {
tickFormat: function(d){
return d3.format(',.2f')(d);
},
axisLabelDistance: -10,
//axisLabel: ''
},
},
title: {
enable: false,
text: 'Title'
}
};
mycSingleSensorGraph.chartTimeFormat = mchelper.cfg.dateFormat;
mycSingleSensorGraph.chartOptions.chart.xAxis.tickFormat = function(d) {return $filter('date')(d, mycSingleSensorGraph.chartTimeFormat, mchelper.cfg.timezone)};
function updateChart(){
mycSingleSensorGraph.isSyncing = true;
MetricsFactory.getMetricsData({"variableId":config.variableId, "withMinMax":config.withMinMax, "start": new Date().getTime() - config.chartFromTimestamp}, function(resource){
if(resource.length > 0){
mycSingleSensorGraph.chartData = resource[0].chartData;
//Update display time format
mycSingleSensorGraph.chartTimeFormat = resource[0].timeFormat;
mycSingleSensorGraph.chartOptions.chart.type = resource[0].chartType;
mycSingleSensorGraph.chartOptions.chart.interpolate = resource[0].chartInterpolate;
if(resource[0].dataType === 'Double'){
mycSingleSensorGraph.chartOptions.chart.yAxis.tickFormat = function(d){return d3.format('.02f')(d) + ' ' + resource[0].unit};
}else if(resource[0].dataType === 'Binary' || resource[0].dataType === 'Counter'){
mycSingleSensorGraph.chartOptions.chart.yAxis.tickFormat = function(d){return d3.format('.0f')(d)};
}
mycSingleSensorGraph.chartOptions.title.text = resource[0].variableType;
mycSingleSensorGraph.resourceName = resource[0].resourceName;
mycSingleSensorGraph.internalId = resource[0].internalId;
}else{
if(config.variableId !== null){
mycSingleSensorGraph.showError = true;
}
}
mycSingleSensorGraph.isSyncing = false;
if(mycSingleSensorGraph.showLoading){
mycSingleSensorGraph.showLoading = false;
}
});
}
function updateVariables(){
if(mycSingleSensorGraph.isSyncing){
return;
}else if(config.variableId !== null){
updateChart();
}else{
mycSingleSensorGraph.showLoading = false;
}
}
//load graph initially
updateVariables();
// refresh every second
var promise = $interval(updateVariables, config.refreshTime*1000);
// cancel interval on scope destroy
$scope.$on('$destroy', function(){
$interval.cancel(promise);
});
}).controller('mycSingleSensorGraphEditController', function($scope, $interval, config, mchelper, $filter, TypesFactory, CommonServices){
var mycSingleSensorGraphEdit = this;
mycSingleSensorGraphEdit.variables = TypesFactory.getSensorVariables({"metricType":["Double","Binary","Counter"]});
mycSingleSensorGraphEdit.cs = CommonServices;
});

View File

@@ -0,0 +1,88 @@
<!--
Copyright (C) 2015-2016 Jeeva Kandasamy (jkandasa@gmail.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<form role="form">
<div class="form-group">
<label>{{ 'REFRESH_TIME_SECONDS' | translate }}</label>
<input type="text" class="form-control" id="refreshTime" placeholder="{{'REFRESH_TIME_SECONDS' | translate}}" ng-model="config.refreshTime" pf-validation="mycSingleSensorGraphEdit.cs.isNumber(input)" required>
<span class="help-block">{{ 'VALIDATION_ERROR_NUMBER' | translate }}</span>
</div>
<div class="form-group">
<input ng-model="config.withMinMax" type="checkbox"/>
<label class="control-label">{{ 'ENABLE_MIN_MAX' | translate }}</label>
</div>
<div class="form-group">
<label>{{ 'MARGIN' | translate }}</label>
<table class="adf-table">
<tr>
<td>
<label>{{ 'LEFT' | translate }}</label>
</td>
<td>
<input class="form-control" type="number" id="left" placeholder="{{'LEFT' | translate}}" ng-model="config.marginLeft" pf-validation="mycSingleSensorGraphEdit.cs.isNumber(input)" required>
</td>
<td>
<label class="mc-margin-right">{{ 'RIGHT' | translate }}</label>
</td>
<td>
<input class="form-control" type="number" id="right" placeholder="{{'RIGHT' | translate}}" ng-model="config.marginRight" pf-validation="mycSingleSensorGraphEdit.cs.isNumber(input)" required>
</td>
</tr>
<tr>
<td>
<label>{{ 'TOP' | translate }}</label>
</td>
<td>
<input class="form-control" type="number" id="top" placeholder="{{'TOP' | translate}}" ng-model="config.marginTop" pf-validation="mycSingleSensorGraphEdit.cs.isNumber(input)" required>
</td>
<td>
<label>{{ 'BOTTOM' | translate }}</label>
</td>
<td>
<input class="form-control" type="number" id="bottom" placeholder="{{'BOTTOM' | translate}}" ng-model="config.marginBottom" pf-validation="mycSingleSensorGraphEdit.cs.isNumber(input)" required>
</td>
</tr>
</table>
</div>
<div class="form-group">
<label>{{ 'TIME_RANGE' | translate }}</label>
<select id="panelSize" class="form-control" pf-select ng-model="config.chartFromTimestamp">
<option value="" ng-hide="true"></option>
<option value="300000">{{ 'LAST_5_MINUTES' | translate }}</option>
<option value="3600000">{{ 'LAST_HOUR' | translate }}</option>
<option value="21600000">{{ 'LAST_6_HOURS' | translate }}</option>
<option value="43200000">{{ 'LAST_12_HOURS' | translate }}</option>
<option value="86400000">{{ 'LAST_DAY' | translate }}</option>
<option value="604800000">{{ 'LAST_WEEK' | translate }}</option>
<option value="2419200000">{{ 'LAST_MONTH' | translate }}</option>
<option value="31536000000">{{ 'LAST_YEAR' | translate }}</option>
</select>
</div>
<div class="form-group">
<label>{{ 'SENSOR_VARIABLE' | translate }}</label>
<select id="senVars" class="form-control" pf-select data-live-search="true" ng-model="config.variableId">
<option value="" ng-hide="true"></option>
<option ng-repeat="res in mycSingleSensorGraphEdit.variables" ng-bind-html="res.displayName | mcResourceRepresentation" value="{{res.id}}" ng-selected="config.variableId == res.id"></option>
</select>
</div>
</form>

View File

@@ -0,0 +1,32 @@
<!--
Copyright (C) 2015-2016 Jeeva Kandasamy (jkandasa@gmail.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- Loading icon disaplay -->
<div ng-if="mycSingleSensorGraph.showLoading">
<div ng-include src="'partials/common-html/loading-sm.html'"></div>
</div>
<div ng-if="mycSingleSensorGraph.showError">
<div ng-include src="'partials/common-html/error-sm.html'"></div>
</div>
<div ng-if="!(mycSingleSensorGraph.showLoading || mycSingleSensorGraph.showError)">
<span class="mc-pointer" ng-bind-html="mycSingleSensorGraph.resourceName | mcResourceRepresentation" ui-sref="sensorsDetail({id:mycSingleSensorGraph.internalId})"></span>
<nvd3 id="asg-{{config.variableId}}" options='mycSingleSensorGraph.chartOptions' data="mycSingleSensorGraph.chartData"></nvd3>
<div ng-if="config.variableId === null" ng-include src="'partials/common-html/no-items-filter-sm.html'"></div>
</div>

View File

@@ -0,0 +1,106 @@
/*
* Copyright 2015-2018 Jeeva Kandasamy (jkandasa@gmail.com)
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// don't forget to declare this service module as a dependency in your main app constructor!
//http://js2.coffee/#coffee2js
//https://coderwall.com/p/r_bvhg/angular-ui-bootstrap-alert-service-for-angular-js
'use strict';
angular.module('adf.widget.myc-custom-buttons', [])
.config(function(dashboardProvider){
dashboardProvider
.widget('mycCustomBtns', {
title: 'Sensor custom buttons',
description: 'Create custom buttons',
templateUrl: 'controllers/adf-widgets/adf-myc-cb/view.html?mcv=29',
controller: 'mycCusBtnsController',
controllerAs: 'mycCBtns',
config: {
variableId:null,
refreshTime:30,
minBtnHeight:30,
minBtnWidth:90,
buttonsJson:"[\n]",
},
edit: {
templateUrl: 'controllers/adf-widgets/adf-myc-cb/edit.html?mcv=29',
controller: 'mycSenVarsEditController',
controllerAs: 'mycCBtnsEdit',
}
});
})
.controller('mycCusBtnsController', function($scope, $interval, config, mchelper, $filter, SensorsFactory, TypesFactory, CommonServices){
var mycCBtns = this;
mycCBtns.showLoading = true;
mycCBtns.isSyncing = true;
mycCBtns.variable = {};
$scope.tooltipEnabled = false;
$scope.hideVariableName=true;
$scope.cs = CommonServices;
mycCBtns.buttons = angular.fromJson(config.buttonsJson);
function loadVariable(){
mycCBtns.isSyncing = true;
SensorsFactory.getVariables({'ids':config.variableId}, function(response){
if(response.length > 0){
mycCBtns.variable = response[0];
}
mycCBtns.isSyncing = false;
if(mycCBtns.showLoading){
mycCBtns.showLoading = false;
}
});
};
function updateVariable(){
if(mycCBtns.isSyncing){
return;
}else if(config.variableId){
loadVariable();
}
}
//load variables initially
loadVariable();
//updateVariables();
//Update Variable / Send Payload
$scope.updateSVariable = function(button){
var variable = angular.copy(mycCBtns.variable);
variable.value = button.payload;
SensorsFactory.updateVariable(variable, function(){
//update Success
loadVariable();
},function(error){
displayRestError.display(error);
});
};
// refresh every second
var promise = $interval(updateVariable, config.refreshTime*1000);
// cancel interval on scope destroy
$scope.$on('$destroy', function(){
$interval.cancel(promise);
});
}).controller('mycCusBtnsEditController', function($scope, $interval, config, mchelper, $filter, TypesFactory, CommonServices){
var mycCBtnsEdit = this;
mycCBtnsEdit.cs = CommonServices;
mycCBtnsEdit.variables = TypesFactory.getSensorVariables();
});

View File

@@ -0,0 +1,49 @@
<!--
Copyright (C) 2015-2016 Jeeva Kandasamy (jkandasa@gmail.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<form role="form">
<div class="form-group">
<label>{{ 'REFRESH_TIME_SECONDS' | translate }}</label>
<input type="text" class="form-control" id="refreshTime" placeholder="{{'REFRESH_TIME_SECONDS' | translate}}" ng-model="config.refreshTime" pf-validation="mycCBtnsEdit.cs.isNumber(input)" required>
<span class="help-block">{{ 'VALIDATION_ERROR_NUMBER' | translate }}</span>
</div>
<div class="form-group">
<label>{{ 'SENSOR_VARIABLE' | translate }}</label>
<select id="mycCBtns" class="form-control" pf-select data-live-search="true" ng-model="config.variableId" required>
<option value="" ng-hide="true"></option>
<option ng-repeat="res in mycCBtnsEdit.variables" ng-bind-html="res.displayName | mcResourceRepresentation" value="{{res.id}}" ng-selected="res.id.toString().indexOf(config.variableId) != -1"></option>
</select>
</div>
<legend><small>{{ 'BUTTON_SETTINGS' | translate }}</small></legend>
<div class="form-group">
<label class="mc-margin-right">{{ 'MINIMUM_HEIGHT' | translate }}</label>
<input type="text" id="height-min" class="mc-margin-right" placeholder="{{'MINIMUM_HEIGHT' | translate}}" ng-model="config.minBtnHeight" pf-validation="mycCBtnsEdit.cs.isNumber(input)" required>
<span class="help-block">{{ 'VALIDATION_ERROR_NUMBER' | translate }}</span>
<label class="mc-margin-right">{{ 'MINIMUM_WIDTH' | translate }}</label>
<input type="text" id="width-min" placeholder="{{'MINIMUM_WIDTH' | translate}}" ng-model="config.minBtnWidth" pf-validation="mycCBtnsEdit.cs.isNumber(input)" required>
<span class="help-block">{{ 'VALIDATION_ERROR_NUMBER' | translate }}</span>
</div>
<div class="form-group">
<label>{{ 'JSON' | translate }}</label>
<textarea class="form-control" rows="12" style="resize:none" ng-model="config.buttonsJson" required ></textarea>
</div>
</form>

View File

@@ -0,0 +1,36 @@
<!--
Copyright (C) 2015-2016 Jeeva Kandasamy (jkandasa@gmail.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- Loading icon disaplay -->
<div ng-show="mycCBtns.showLoading">
<div ng-include src="'partials/common-html/loading-sm.html'"></div>
</div>
<div ng-hide="mycCBtns.showLoading">
<div ng-if="config.variableId" >
<span><span ng-bind-html="mycCBtns.variable.resourceName | mcResourceRepresentation"></span> <span class="badge">{{mycCBtns.variable.value}} {{mycCBtns.variable.unit}}</span></span>
<hr class="adf-myc-cb-margin">
<div id="custom-buttons-wrapper" class="row-fluid">
<button ng-repeat="button in mycCBtns.buttons track by $index" ng-click="updateSVariable(button)" class="btn"
ng-class="button.btnType ? 'btn-{{button.btnType}}' : 'btn-default'"
ng-style="{'min-width':'{{config.minBtnWidth}}px', 'min-height':'{{config.minBtnHeight}}px'}"
ng-bind-html="button.name"></button>
</div>
</div>
<!-- display no items configured -->
<div ng-if="!config.variableId" ng-include src="'partials/common-html/no-items-filter-sm.html'"></div>
</div>

View File

@@ -0,0 +1,102 @@
/*
* Copyright 2015-2018 Jeeva Kandasamy (jkandasa@gmail.com)
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
angular.module('adf.widget.myc-custom-widget', [])
.config(function(dashboardProvider){
dashboardProvider
.widget('mycCustomWidget', {
title: 'Custom widget',
description: 'Make your own widget with script and template',
templateUrl: 'controllers/adf-widgets/adf-myc-cw/view.html?mcv=29',
controller: 'mycCustomWidgetController',
controllerAs: 'mycCustomWidget',
config: {
script: null,
template: null,
refreshTime:-1,
bindings: '{}',
},
edit: {
templateUrl: 'controllers/adf-widgets/adf-myc-cw/edit.html?mcv=29',
controller: 'mycCustomWidgetEditController',
controllerAs: 'mycCustomWidgetEdit',
}
});
})
.controller('mycCustomWidgetController', function($scope, $interval, config, TemplatesFactory, $sce, mchelper, CommonServices){
var mycCustomWidget = this;
mycCustomWidget.showLoading = true;
mycCustomWidget.isSyncing = false;
mycCustomWidget.htmlData = null;
mycCustomWidget.trustedHtml = "";
$scope.mchelper = mchelper;
$scope.cs = CommonServices;
function updateState(){
mycCustomWidget.dataAvailable = true;
mycCustomWidget.isSyncing = false;
if(mycCustomWidget.showLoading){
mycCustomWidget.showLoading = false;
}
};
function loadData(){
mycCustomWidget.isSyncing = true;
TemplatesFactory.getHtml({'template':config.template, 'script':config.script, 'scriptBindings':JSON.stringify(eval('('+config.bindings+')'))}, function(response){
mycCustomWidget.htmlData = response.message;
mycCustomWidget.trustedHtml = $sce.trustAsHtml(response.message);
updateState();
},function(error){
mycCustomWidget.htmlData = '<pre>'+error.data.errorMessage+'</pre>';
updateState();
});
};
function updateData(){
if(mycCustomWidget.isSyncing){
return;
}else if(config.template !== null){
loadData();
}
}
//load variables initially
if(config.dataKey !== null){
updateData();
}else{
mycCustomWidget.showLoading = false;
}
// refresh every second, if config.refreshTime has positive value
if(config.refreshTime > 0){
var promise = $interval(updateData, config.refreshTime*1000);
// cancel interval on scope destroy
$scope.$on('$destroy', function(){
$interval.cancel(promise);
});
}
}).controller('mycCustomWidgetEditController', function($scope, $interval, config, TypesFactory, ScriptsFactory, TemplatesFactory, CommonServices){
var mycCustomWidgetEdit = this;
mycCustomWidgetEdit.cs = CommonServices;
// load variables at startup
mycCustomWidgetEdit.scripts = ScriptsFactory.getAllLessInfo({"type":"Operation"});
mycCustomWidgetEdit.templates = TemplatesFactory.getAllLessInfo();
});

View File

@@ -0,0 +1,46 @@
<!--
Copyright (C) 2015-2016 Jeeva Kandasamy (jkandasa@gmail.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<form role="form">
<div class="form-group">
<label>{{ 'REFRESH_TIME_SECONDS' | translate }}</label>
<input type="text" class="form-control" id="refreshTime" placeholder="{{'REFRESH_TIME_SECONDS' | translate}}" ng-model="config.refreshTime" pf-validation="mycCustomWidgetEdit.cs.isNumber(input)" required>
<span class="help-block">{{ 'VALIDATION_ERROR_NUMBER' | translate }}</span>
</div>
<div class="form-group">
<label>{{ 'TEMPLATE' | translate }}</label>
<select class="form-control" pf-select data-live-search="true" ng-options="template for template in mycCustomWidgetEdit.templates" ng-model="config.template" required>
<option value="" ng-hide="true"></option>
</select>
</div>
<div class="form-group">
<label>{{ 'SCRIPT' | translate }}</label>
<select class="form-control" pf-select data-live-search="true" ng-options="script for script in mycCustomWidgetEdit.scripts" ng-model="config.script" >
<option value="" ng-hide="false">{{ 'NOTHING_SELECTED' | translate }}</option>
</select>
</div>
<div class="form-group" ng-if="config.script">
<label>{{ 'SCRIPT_BINDINGS' | translate }}</label>
<input type="text" class="form-control" id="refreshTime" placeholder="{{'SCRIPT_BINDINGS' | translate}}" ng-model="config.bindings" pf-validation="mycCustomWidgetEdit.cs.isJsonString(input)" required>
<span class="help-block">{{ 'SYNTAX_ERROR' | translate }}</span>
</div>
</form>

View File

@@ -0,0 +1,30 @@
<!--
Copyright (C) 2015-2016 Jeeva Kandasamy (jkandasa@gmail.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- Loading icon disaplay -->
<div ng-show="config.template !== null">
<div ng-show="mycCustomWidget.showLoading">
<div ng-include src="'partials/common-html/loading-sm.html'"></div>
</div>
<div ng-if="!mycCustomWidget.showLoading">
<mc-dynamic ng-bind-html="mycCustomWidget.trustedHtml"></mc-dynamic>
<div ng-if="!mycCustomWidget.htmlData"><span>{{'NO_DATA_AVAILABLE' | translate}}</span></div>
</div>
</div>
<div ng-if="config.template === null" ng-include src="'partials/common-html/no-items-filter-sm.html'"></div>

View File

@@ -0,0 +1,132 @@
/*
* Copyright 2015-2018 Jeeva Kandasamy (jkandasa@gmail.com)
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// don't forget to declare this service module as a dependency in your main app constructor!
//http://js2.coffee/#coffee2js
//https://coderwall.com/p/r_bvhg/angular-ui-bootstrap-alert-service-for-angular-js
'use strict';
angular.module('adf.widget.myc-dsi', [])
.config(function(dashboardProvider){
dashboardProvider
.widget('mycDisplayStaticImage', {
title: 'Display image file',
description: 'Displays image file from local disk or url',
templateUrl: 'controllers/adf-widgets/adf-myc-dsi/view.html?mcv=29',
controller: 'mycDisplayStaticImageController',
controllerAs: 'mycDisplayStaticImage',
config: {
locationType:"disk",
imageNameUrl:"",
refreshTime:30,
},
edit: {
templateUrl: 'controllers/adf-widgets/adf-myc-dsi/edit.html?mcv=29',
controller: 'mycDisplayStaticImageEditController',
controllerAs: 'mycDisplayStaticImageEdit',
}
});
})
.controller('mycDisplayStaticImageController', function($scope, $interval, config, mchelper, $filter, StatusFactory, displayRestError, CommonServices){
var mycDisplayStaticImage = this;
mycDisplayStaticImage.showLoading = true;
mycDisplayStaticImage.isSyncing = true;
mycDisplayStaticImage.fileData = {};
mycDisplayStaticImage.error = false;
mycDisplayStaticImage.errorMsg;
mycDisplayStaticImage.imageNameUrl = config.imageNameUrl;
$scope.cs = CommonServices;
function loadImage(){
mycDisplayStaticImage.isSyncing = true;
if(config.locationType === "disk"){
StatusFactory.getStaticImageFile({'fileName':config.imageNameUrl}, function(response){
mycDisplayStaticImage.fileData = response;
mycDisplayStaticImage.isSyncing = false;
if(mycDisplayStaticImage.showLoading){
mycDisplayStaticImage.showLoading = false;
}
mycDisplayStaticImage.error = false;
},function(error){
mycDisplayStaticImage.showLoading = false;
mycDisplayStaticImage.isSyncing = false;
mycDisplayStaticImage.error = true;
if(error.data && error.data.errorMessage){
mycDisplayStaticImage.errorMsg = error.data.errorMessage;
}else{
mycDisplayStaticImage.errorMsg = error.statusText;
displayRestError.display(error);
}
});
}else{
mycDisplayStaticImage.imageNameUrl = config.imageNameUrl+'?t='+Date.now(); // Image should updated on every refresh
mycDisplayStaticImage.isSyncing = false;
if(mycDisplayStaticImage.showLoading){
mycDisplayStaticImage.showLoading = false;
}
}
};
function updateImage(){
if(mycDisplayStaticImage.isSyncing){
return;
}else if(config.imageNameUrl && config.imageNameUrl.length > 0){
loadImage();
}
}
//load image initially
if(config.imageNameUrl && config.imageNameUrl.length > 0){
loadImage();
}else{
mycDisplayStaticImage.showLoading = false;
}
// refresh every second
var promise = $interval(updateImage, config.refreshTime*1000);
// cancel interval on scope destroy
$scope.$on('$destroy', function(){
$interval.cancel(promise);
});
}).controller('mycDisplayStaticImageEditController', function($scope, config, StatusFactory, displayRestError, CommonServices){
var mycDisplayStaticImageEdit = this;
mycDisplayStaticImageEdit.cs = CommonServices;
mycDisplayStaticImageEdit.locationTypes = ["disk","url"];
mycDisplayStaticImageEdit.filesList = [];
mycDisplayStaticImageEdit.onLocationTypeChange = function(){
config.imageNameUrl = "";
if(config.locationType === "disk"){
StatusFactory.getStaticImageFilesList(function(response){
mycDisplayStaticImageEdit.filesList = response;
},function(error){
displayRestError.display(error);
});
}
};
if(config.locationType === "disk"){
var tmpImageUrl = config.imageNameUrl;
mycDisplayStaticImageEdit.onLocationTypeChange();
config.imageNameUrl = tmpImageUrl;
}
});

View File

@@ -0,0 +1,44 @@
<!--
Copyright (C) 2015-2016 Jeeva Kandasamy (jkandasa@gmail.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<form role="form">
<div class="form-group">
<label>{{ 'REFRESH_TIME_SECONDS' | translate }}</label>
<input type="text" class="form-control" id="refreshTime" placeholder="{{'REFRESH_TIME_SECONDS' | translate}}" ng-model="config.refreshTime" pf-validation="mycDisplayStaticImageEdit.cs.isNumber(input)" required>
<span class="help-block">{{ 'VALIDATION_ERROR_NUMBER' | translate }}</span>
</div>
<div class="form-group">
<label>{{ 'TYPE' | translate }}</label>
<select id="senVarsTypes" class="form-control" pf-select ng-model="config.locationType" ng-change="mycDisplayStaticImageEdit.onLocationTypeChange()" ng-options="type for type in mycDisplayStaticImageEdit.locationTypes">
<option value="" ng-hide="true"></option>
</select>
</div>
<div ng-if="config.locationType === 'disk'" class="form-group">
<label>{{ 'FILE' | translate }}</label>
<select id="senVars" class="form-control" pf-select data-live-search="true" ng-model="config.imageNameUrl" ng-options="fileName for fileName in mycDisplayStaticImageEdit.filesList" required>
<option value="" ng-hide="true"></option>
</select>
</div>
<div ng-if="config.locationType === 'url'" class="form-group">
<label>{{ 'URL' | translate }}</label>
<input type="text" class="form-control" id="fileUrl" placeholder="{{'URL' | translate}}" ng-model="config.imageNameUrl" required>
</div>
</form>

View File

@@ -0,0 +1,37 @@
<!--
Copyright (C) 2015-2016 Jeeva Kandasamy (jkandasa@gmail.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- Loading icon disaplay -->
<div ng-show="mycDisplayStaticImage.showLoading">
<div ng-include src="'partials/common-html/loading-sm.html'"></div>
</div>
<div ng-if="!mycDisplayStaticImage.showLoading">
<div ng-if="mycDisplayStaticImage.error" class="alert alert-danger">
<span class="pficon pficon-error-circle-o"></span>
<span>{{mycDisplayStaticImage.errorMsg}}</span>
</div>
<div ng-if="!mycDisplayStaticImage.error">
<img ng-if="config.locationType === 'disk'" ng-src="data:image/{{mycDisplayStaticImage.fileData.extension}};base64,{{mycDisplayStaticImage.fileData.data}}" alt="{{mycDisplayStaticImage.fileData.name}}" class="adf-myc-dsi-image"/>
<img ng-if="config.locationType === 'url'" ng-src="{{mycDisplayStaticImage.imageNameUrl}}" alt="{{mycDisplayStaticImage.imageNameUrl}}" class="adf-myc-dsi-image"/>
<div ng-if="!config.imageNameUrl" ng-include src="'partials/common-html/no-items-filter-sm.html'"></div>
</div>
</div>

View File

@@ -0,0 +1,103 @@
/*
* Copyright 2015-2018 Jeeva Kandasamy (jkandasa@gmail.com)
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// don't forget to declare this service module as a dependency in your main app constructor!
//http://js2.coffee/#coffee2js
//https://coderwall.com/p/r_bvhg/angular-ui-bootstrap-alert-service-for-angular-js
'use strict';
angular.module('adf.widget.myc-groups', [])
.config(function(dashboardProvider){
dashboardProvider
.widget('mycGroups', {
title: 'Groups',
description: 'Change state(ON/OFF) of resources group(Scene control)',
templateUrl: 'controllers/adf-widgets/adf-myc-groups/view.html?mcv=29',
controller: 'mycGroupsController',
controllerAs: 'mycGroups',
config: {
itemIds:[],
itemsPerRow:"1",
refreshTime:30,
},
edit: {
templateUrl: 'controllers/adf-widgets/adf-myc-groups/edit.html?mcv=29',
controller: 'mycGroupsEditController',
controllerAs: 'mycGroupsEdit',
}
});
})
.controller('mycGroupsController', function($scope, $interval, config, mchelper, $filter, ResourcesGroupFactory, TypesFactory, CommonServices){
var mycGroups = this;
mycGroups.showLoading = true;
mycGroups.isSyncing = false;
mycGroups.items = {};
$scope.cs = CommonServices;
function loadItems(){
mycGroups.isSyncing = true;
ResourcesGroupFactory.getAll({'id':config.itemIds, 'page':1, 'pageLimit':30}, function(response){
mycGroups.items = response.data;
mycGroups.isSyncing = false;
if(mycGroups.showLoading){
mycGroups.showLoading = false;
}
});
};
function updateItems(){
if(mycGroups.isSyncing){
return;
}else if(config.itemIds.length > 0){
loadItems();
}
}
//load items initially
updateItems();
//On,Off switch control
$scope.changeMystate = function(item, state){
var itemArray = [item.id];
if(state){
ResourcesGroupFactory.turnOnIds(itemArray, function(response) {
//alertService.success($filter('translate')('RESOURCE_GROUP_TURNED_ON'));
},function(error){
displayRestError.display(error);
});
}else{
ResourcesGroupFactory.turnOffIds(itemArray, function(response) {
//alertService.success($filter('translate')('RESOURCE_GROUP_TURNED_OFF'));
},function(error){
displayRestError.display(error);
});
}
}
// refresh every second
var promise = $interval(updateItems, config.refreshTime*1000);
// cancel interval on scope destroy
$scope.$on('$destroy', function(){
$interval.cancel(promise);
});
}).controller('mycGroupsEditController', function($scope, $interval, config, mchelper, $filter, TypesFactory, CommonServices){
var mycGroupsEdit = this;
mycGroupsEdit.cs = CommonServices;
mycGroupsEdit.items = TypesFactory.getResourcesGroups();
});

View File

@@ -0,0 +1,43 @@
<!--
Copyright (C) 2015-2016 Jeeva Kandasamy (jkandasa@gmail.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<form role="form">
<div class="form-group">
<label>{{ 'REFRESH_TIME_SECONDS' | translate }}</label>
<input type="text" class="form-control" id="refreshTime" placeholder="{{'REFRESH_TIME_SECONDS' | translate}}" ng-model="config.refreshTime" pf-validation="mycGroupsEdit.cs.isNumber(input)" required>
<span class="help-block">{{ 'VALIDATION_ERROR_NUMBER' | translate }}</span>
</div>
<div class="form-group">
<label>{{ 'ITEMS_PER_ROW' | translate }}</label>
<select id="panelSize" class="form-control" pf-select ng-model="config.itemsPerRow" required>
<option value="" ng-hide="true"></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="6">6</option>
<option value="12">12</option>
</select>
</div>
<div class="form-group">
<label>{{ 'GROUPS' | translate }}</label>
<select id="senVars" class="form-control" multiple pf-select data-live-search="true" ng-model="config.itemIds">
<option value="" ng-hide="true"></option>
<option ng-repeat="res in mycGroupsEdit.items" ng-bind-html="res.displayName | mcResourceRepresentation" value="{{res.id}}" ng-selected="config.itemIds.indexOf(res.id.toString()) != -1"></option>
</select>
</div>
</form>

View File

@@ -0,0 +1,51 @@
<!--
Copyright (C) 2015-2016 Jeeva Kandasamy (jkandasa@gmail.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<div ng-if="config.itemIds.length > 0">
<!-- Loading icon disaplay -->
<div ng-if="mycGroups.showLoading">
<div ng-include src="'partials/common-html/loading-sm.html'"></div>
</div>
<div ng-if="!mycGroups.showLoading">
<!-- items ng-repeat -->
<div ng-repeat="item in mycGroups.items">
<div class="col-md-{{12/config.itemsPerRow}}">
<div class="card-pf card-pf-aggregate-status card-pf-with-action card-pf-accented card-pf-aggregate-status-mini">
<h2 class="card-pf-title">
<span class="pficon pficon-replicator"></span>
<span class="card-pf-aggregate-status-count" tooltip-placement="top" uib-tooltip="{{item.name}}">{{item.name ? item.name : '-' | limitTo:18}}{{item.name.length > 18 ? '...' : ''}}</span>
<span tooltip-placement="top" uib-tooltip="{{item.description}}">{{item.description ? item.description : '-' | limitTo:36}}{{item.description.length > 36 ? '...' : ''}}</span>
</h2>
<div class="card-pf-body">
<p class="card-pf-aggregate-status-notifications">
<span class="card-pf-aggregate-status-notification">
<input bs-switch ng-change="changeMystate(item, state)" ng-init="state = item.state === 'On'? true:false" ng-model="state" type="checkbox"
switch-animate="true" switch-handle-width="35px" switch-label-width="7px"
switch-off-color="default" switch-on-color="primary" switch-size="small"
ng-true-value="true" ng-false-value="false" switch-on-text="{{ 'ON' | translate }}" switch-off-text="{{ 'OFF' | translate }}" >
</span>
</p>
</div>
</div>
</div>
</div>
</div>
</div>
<div ng-if="config.itemIds.length == 0" ng-include src="'partials/common-html/no-items-filter-sm.html'"></div>

View File

@@ -0,0 +1,189 @@
/*
* Copyright 2015-2018 Jeeva Kandasamy (jkandasa@gmail.com)
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
angular.module('adf.widget.myc-heat-map', [])
.config(function(dashboardProvider){
dashboardProvider
.widget('mycHeatMap', {
title: 'Heatmap chart',
description: 'Displays data as heatmap chart',
templateUrl: 'controllers/adf-widgets/adf-myc-hm/view.html?mcv=29',
controller: 'mycHeatMapController',
controllerAs: 'mycHeatMap',
config: {
dataType: null,
upperLimit: null,
thresholds: [],
colorPattern: [],
legendLabels: [],
dataKey:null,
refreshTime:30,
height:200,
maxBlockSize:50,
showLegends:true,
},
edit: {
templateUrl: 'controllers/adf-widgets/adf-myc-hm/edit.html?mcv=29',
controller: 'mycHeatMapEditController',
controllerAs: 'mycHeatMapEdit',
}
});
})
.controller('mycHeatMapController', function($scope, $interval, config, mchelper, $filter, MetricsFactory,$state){
var mycHeatMap = this;
mycHeatMap.showLoading = true;
mycHeatMap.isSyncing = false;
mycHeatMap.data = {};
mycHeatMap.dataAvailable = false;
function updateState(){
if(mycHeatMap.data.length === 0){
mycHeatMap.dataAvailable = false;
}else{
mycHeatMap.dataAvailable = true;
}
mycHeatMap.isSyncing = false;
if(mycHeatMap.showLoading){
mycHeatMap.showLoading = false;
}
};
function loadData(){
mycHeatMap.isSyncing = true;
if(config.dataType === 'NODE_STATUS'){
MetricsFactory.getHeatMapHeatMapNodeStatus({'nodeId':config.dataKey}, function(response){
mycHeatMap.data = response;
updateState();
});
}else if(config.dataType === 'BATTERY_LEVEL'){
MetricsFactory.getHeatMapBatteryLevel({'nodeId':config.dataKey}, function(response){
mycHeatMap.data = response;
updateState();
});
}else if(config.dataType === 'SENSOR_VARIABLES'){
MetricsFactory.getHeatMapHeatMapSensorVariable({'variableId':config.dataKey, 'upperLimit':config.upperLimit}, function(response){
mycHeatMap.data = response;
updateState();
});
}else if(config.dataType === 'SCRIPT'){
MetricsFactory.getHeatMapHeatMapScript({'scriptName':config.dataKey}, function(response){
mycHeatMap.data = response;
updateState();
});
}else{
mycHeatMap.isSyncing = false;
if(mycHeatMap.showLoading){
mycHeatMap.showLoading = false;
}
}
//remove this line
if(mycHeatMap.showLoading){
mycHeatMap.showLoading = false;
}
};
function updateData(){
if(mycHeatMap.isSyncing){
return;
}else if(config.dataKey !== null){
loadData();
}
}
//load variables initially
if(config.dataKey !== null){
updateData();
}else{
mycHeatMap.showLoading = false;
}
//Heat map click action
mycHeatMap.hmClickAction = function(block){
if(config.dataType === 'NODE_STATUS' || config.dataType === 'BATTERY_LEVEL'){
$state.go("nodesDetail", {'id':block.altId});
}else if(config.dataType === 'SENSOR_VARIABLES'){
$state.go("sensorsDetail", {'id':block.altId});
}else if(config.dataType === 'SCRIPT'){
//Not implemented yet
}
};
// refresh every second
var promise = $interval(updateData, config.refreshTime*1000);
// cancel interval on scope destroy
$scope.$on('$destroy', function(){
$interval.cancel(promise);
});
}).controller('mycHeatMapEditController', function($scope, $interval, config, mchelper, $filter, TypesFactory, ScriptsFactory, CommonServices){
var mycHeatMapEdit = this;
mycHeatMapEdit.cs = CommonServices;
var generalColorPattern = ['#21781F', '#3F9C35', '#57A8D4', '#F9D67A', '#EC7A08', '#CC0000', '#F00'];
var generalThresholds = [0.1, 0.3, 0.5, 0.7, 0.8, 0.9];
var generalLabels = ['< 10%', '10-30%', '30-50%', '50-70%', '70-80%', '80-90%', '> 90%'];
var statusColorPattern = ['#C00', '#808080', '#3F9C35'];
var statusThresholds = [0.4, 0.6];
var statusLabels = ['Down', 'Unavailable', 'Up'];
//Change data type
mycHeatMapEdit.changeDataType = function(){
//Update pattern, colors, labels
if(config.dataType === 'NODE_STATUS'){
config.thresholds = angular.copy(statusThresholds);
config.colorPattern = angular.copy(statusColorPattern);
config.legendLabels = angular.copy(statusLabels);
}else if(config.dataType){
config.thresholds = angular.copy(generalThresholds);
config.colorPattern = angular.copy(generalColorPattern);
config.legendLabels = angular.copy(generalLabels);
}
//Change color to reverse order if selected object is battery level
if(config.dataType === 'BATTERY_LEVEL'){
mycHeatMapEdit.swapColors();
}
//Change object type
if(config.dataType === 'SCRIPT'){
config.dataKey = {};
}else{
config.dataKey = [];
}
//load variables
loadVariables();
};
var loadVariables = function(){
if(config.dataType === 'NODE_STATUS' || config.dataType === 'BATTERY_LEVEL'){
mycHeatMapEdit.variables = TypesFactory.getNodes();
}else if(config.dataType === 'SENSOR_VARIABLES'){
//Get only DOUBLE type devices
mycHeatMapEdit.variables = TypesFactory.getSensorVariables({"metricType":"Double"});
}else if(config.dataType === 'SCRIPT'){
mycHeatMapEdit.variables = ScriptsFactory.getAllLessInfo({"type":"Operation"});
}
}
// load variables at startup
loadVariables();
//Swap up down color
mycHeatMapEdit.swapColors = function(){
config.colorPattern.reverse();
}
});

View File

@@ -0,0 +1,84 @@
<!--
Copyright (C) 2015-2016 Jeeva Kandasamy (jkandasa@gmail.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<form role="form">
<div class="form-group">
<label>{{ 'REFRESH_TIME_SECONDS' | translate }}</label>
<input type="text" class="form-control" id="refreshTime" placeholder="{{'REFRESH_TIME_SECONDS' | translate}}" ng-model="config.refreshTime" pf-validation="mycHeatMapEdit.cs.isNumber(input)" required>
<span class="help-block">{{ 'VALIDATION_ERROR_NUMBER' | translate }}</span>
</div>
<div class="form-group" ng-if="config.dataType">
<label class="mc-margin-right">{{ 'HEIGHT' | translate }}</label>
<input class="mc-margin-right" type="text" id="height" placeholder="{{'HEIGHT' | translate}}" ng-model="config.height" pf-validation="mycHeatMapEdit.cs.isNumber(input)" required>
<span class="help-block">{{ 'VALIDATION_ERROR_NUMBER' | translate }}</span>
<label class="mc-margin-right">{{ 'MAXIMUM_BLOCK_SIZE' | translate }}</label>
<input type="text" id="height" placeholder="{{'MAXIMUM_BLOCK_SIZE' | translate}}" ng-model="config.maxBlockSize" pf-validation="mycHeatMapEdit.cs.isNumber(input)" required>
<span class="help-block">{{ 'VALIDATION_ERROR_NUMBER' | translate }}</span>
</div>
<div class="form-group">
<input ng-model="config.showLegends" type="checkbox"/>
<label class="control-label">{{ 'SHOW_LEGENDS' | translate }}</label>
</div>
<div class="form-group">
<label>{{ 'DATA_TYPE' | translate }}</label>
<select id="panelSize" class="form-control" pf-select ng-change="mycHeatMapEdit.changeDataType()" ng-model="config.dataType">
<option value="" ng-hide="true"></option>
<option value="BATTERY_LEVEL">{{ 'BATTERY_LEVEL' | translate }}</option>
<option value="NODE_STATUS">{{ 'NODE_STATUS' | translate }}</option>
<option value="SENSOR_VARIABLES">{{ 'SENSOR_VARIABLES' | translate }}</option>
<option value="SCRIPT">{{ 'SCRIPT' | translate }}</option>
</select>
</div>
<div class="form-group" ng-if="config.dataType === 'SENSOR_VARIABLES'">
<label>{{ 'UPPER_LIMIT' | translate }}</label>
<input type="text" class="form-control" id="refreshTime" placeholder="{{'UPPER_LIMIT' | translate}}" ng-model="config.upperLimit" pf-validation="mycHeatMapEdit.cs.isNumber(input)" required>
<span class="help-block">{{ 'VALIDATION_ERROR_NUMBER' | translate }}</span>
</div>
<div class="form-group" ng-if="config.dataType">
<label class="mc-margin-right">{{ 'COLOR' | translate }}</label>
<i uib-tooltip="{{ 'SWAP' | translate }}" tooltip-placement="top" ng-click="mycHeatMapEdit.swapColors()" class="fa fa-exchange mc-icon-md-3 mc-pointer text-primary"></i>
</div>
<div class="form-group" ng-if="config.dataType">
<span ng-repeat="item in config.colorPattern track by $index">
<span style="background-color:{{config.colorPattern[$index]}};width:72px;color:white;" class="btn btn-sm mc-margin-right" colorpicker="hex" colorpicker-position="top"
ng-model="config.colorPattern[$index]">{{config.legendLabels[$index] || "-"}}</span>
</span>
</div>
<div class="form-group">
<label ng-if="config.dataType === 'SENSOR_VARIABLES'">{{ 'SENSOR_VARIABLES' | translate }}</label>
<label ng-if="config.dataType === 'BATTERY_LEVEL'">{{ 'NODES' | translate }}</label>
<label ng-if="config.dataType === 'NODE_STATUS'">{{ 'NODES' | translate }}</label>
<label ng-if="config.dataType === 'SCRIPT'">{{ 'SCRIPT' | translate }}</label>
<select ng-if="config.dataType === 'SENSOR_VARIABLES' || config.dataType === 'BATTERY_LEVEL' || config.dataType === 'NODE_STATUS'"
id="dataKey" class="form-control" multiple pf-select data-live-search="true" ng-model="config.dataKey">
<option value="" ng-hide="true"></option>
<option ng-repeat="res in mycHeatMapEdit.variables" ng-bind-html="res.displayName | mcResourceRepresentation" value="{{res.id}}" ng-selected="config.dataKey.indexOf(res.id.toString()) != -1"></option>
</select>
<select ng-if="config.dataType === 'SCRIPT'" id="dataKey" class="form-control" pf-select data-live-search="true" ng-options="resource for resource in mycHeatMapEdit.variables" ng-model="config.dataKey">
<option value="" ng-hide="true"></option>
</select>
</div>
</form>

View File

@@ -0,0 +1,36 @@
<!--
Copyright (C) 2015-2016 Jeeva Kandasamy (jkandasa@gmail.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- Loading icon disaplay -->
<div ng-show="mycHeatMap.showLoading">
<div ng-include src="'partials/common-html/loading-sm.html'"></div>
</div>
<div ng-if="!mycHeatMap.showLoading">
<div class="adf-myc-shm-margin" ng-if="mycHeatMap.data.length > 0" pf-heatmap
data="mycHeatMap.data" chart-data-available="mycHeatMap.dataAvailable"
show-legend="config.showLegends" legend-labels="config.legendLabels"
heatmap-color-pattern="config.colorPattern" thresholds="config.thresholds"
max-block-size="{{config.maxBlockSize}}" height="config.height"
click-action="mycHeatMap.hmClickAction">
</div>
<div ng-if="mycHeatMap.data.length == 0">
<span>{{'NO_DATA_AVAILABLE' | translate}}</span>
</div>
</div>
<div ng-if="config.dataKey === null" ng-include src="'partials/common-html/no-items-filter-sm.html'"></div>

View File

@@ -0,0 +1,104 @@
/*
* Copyright 2015-2019 Jeeva Kandasamy (jkandasa@gmail.com)
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// don't forget to declare this service module as a dependency in your main app constructor!
//http://js2.coffee/#coffee2js
//https://coderwall.com/p/r_bvhg/angular-ui-bootstrap-alert-service-for-angular-js
'use strict';
angular.module('adf.widget.myc-os-commands', [])
.config(function (dashboardProvider) {
dashboardProvider
.widget('mycOsCommands', {
title: 'OS Commands',
description: 'Create buttons to run Operating System Commands',
templateUrl: 'controllers/adf-widgets/adf-myc-os/view.html?mcv=${mc.gui.version}',
controller: 'mycOsCommandController',
controllerAs: 'mycOsBtns',
config: {
minBtnHeight: 30,
minBtnWidth: 90,
buttonsJson: "[\n]",
},
edit: {
templateUrl: 'controllers/adf-widgets/adf-myc-os/edit.html?mcv=${mc.gui.version}',
controller: 'mycOsCommandEditController',
controllerAs: 'mycOsBtnsEdit',
}
});
})
.controller('mycOsCommandController', function ($scope, $interval, config, mchelper, $uibModal, $filter, OSCommandFactory, CommonServices) {
var mycOsBtns = this;
mycOsBtns.showLoading = false;
$scope.tooltipEnabled = false;
$scope.cs = CommonServices;
mycOsBtns.buttons = angular.fromJson(config.buttonsJson);
// execute OS command directly
$scope.executeOsCommandDirect = function (button) {
var request = {};
request.os = button.os;
request.command = button.command;
OSCommandFactory.execute(request, function (response) {
if (response.error === undefined) {
alertService.success(response.result);
} else {
alertService.danger(angular.toJson(response));
}
}, function (error) {
displayRestError.display(error);
});
};
// execute OS command with confirmation check
$scope.executeOsCommand = function (button) {
if (button.confirmation === true) {
var addModalInstance = $uibModal.open({
templateUrl: 'controllers/adf-widgets/adf-myc-os/confirmation-modal.html?mcv=${mc.gui.version}',
controller: 'CommandConfirmationController',
resolve: {
button: button
}
});
addModalInstance.result.then(function () {
$scope.executeOsCommandDirect(button);
}),
function () {
//console.log('Modal dismissed at: ' + new Date());
}
} else {
$scope.executeOsCommandDirect(button);
}
};
}).controller('mycOsCommandEditController', function ($scope, $interval, config, mchelper, $filter, CommonServices) {
var mycOsBtnsEdit = this;
mycOsBtnsEdit.cs = CommonServices;
}).controller('CommandConfirmationController', function ($scope, $uibModalInstance, $filter, button) {
$scope.header = $filter('translate')('OS_COMMAND_EXECTION_CONFIRMATION_TITLE');
$scope.button = button;
$scope.reboot = function () {
$uibModalInstance.close();
};
$scope.cancel = function () {
$uibModalInstance.dismiss('cancel');
}
});

View File

@@ -0,0 +1,40 @@
<!--
Copyright (C) 2015-2016 Jeeva Kandasamy (jkandasa@gmail.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<div>
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true" ng-click="cancel()">
<span class="pficon pficon-close"></span>
</button>
<div class="modal-title"><b>{{header}}</b></div>
</div>
<div class="modal-body modal-body-text-only">
<div class="mc-model-text-margin">{{ 'OS_COMMAND_EXECTION_CONFIRMATION_MESSAGE' | translate }}
<div ng-if="button.os"> {{ 'OPERATING_SYSTEM' | translate }}: <b>{{button.os}}</b></div>
</div>
<div><pre> {{ 'COMMAND' | translate }}: <b>{{button.command}}</b></pre></div>
</div>
<div class="modal-footer">
<button class="btn btn-default" ng-click="cancel()"><i class="fa fa-close"></i> {{ 'CANCEL' | translate }}</button>
<button class="btn btn-primary" ng-click="reboot()"><i class="fa fa-check"></i> {{ 'CONTINUE' | translate }}</button>
</div>
</div>

View File

@@ -0,0 +1,35 @@
<!--
Copyright (C) 2015-2016 Jeeva Kandasamy (jkandasa@gmail.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<form role="form">
<legend><small>{{ 'BUTTON_SETTINGS' | translate }}</small></legend>
<div class="form-group">
<label class="mc-margin-right">{{ 'MINIMUM_HEIGHT' | translate }}</label>
<input type="text" id="height-min" class="mc-margin-right" placeholder="{{'MINIMUM_HEIGHT' | translate}}" ng-model="config.minBtnHeight" pf-validation="mycOsBtnsEdit.cs.isNumber(input)" required>
<span class="help-block">{{ 'VALIDATION_ERROR_NUMBER' | translate }}</span>
<label class="mc-margin-right">{{ 'MINIMUM_WIDTH' | translate }}</label>
<input type="text" id="width-min" placeholder="{{'MINIMUM_WIDTH' | translate}}" ng-model="config.minBtnWidth" pf-validation="mycOsBtnsEdit.cs.isNumber(input)" required>
<span class="help-block">{{ 'VALIDATION_ERROR_NUMBER' | translate }}</span>
</div>
<div class="form-group">
<label>{{ 'JSON' | translate }}</label>
<textarea class="form-control" rows="12" style="resize:none" ng-model="config.buttonsJson" required ></textarea>
</div>
</form>

View File

@@ -0,0 +1,34 @@
<!--
Copyright (C) 2015-2016 Jeeva Kandasamy (jkandasa@gmail.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- Loading icon disaplay -->
<div ng-show="mycOsBtns.showLoading">
<div ng-include src="'partials/common-html/loading-sm.html'"></div>
</div>
<div ng-hide="mycOsBtns.showLoading">
<div ng-if="config.buttonsJson" >
<div id="custom-buttons-wrapper" class="row-fluid">
<button ng-repeat="button in mycOsBtns.buttons track by $index" ng-click="executeOsCommand(button)" class="btn"
ng-class="button.btnType ? 'btn-{{button.btnType}}' : 'btn-default'"
ng-style="{'min-width':'{{config.minBtnWidth}}px', 'min-height':'{{config.minBtnHeight}}px'}"
ng-bind-html="button.name"></button>
</div>
</div>
<!-- display no items configured -->
<div ng-if="config.buttonsJson.length < 5" ng-include src="'partials/common-html/no-items-filter-sm.html'"></div>
</div>

View File

@@ -0,0 +1,140 @@
/*
* Copyright 2015-2018 Jeeva Kandasamy (jkandasa@gmail.com)
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// don't forget to declare this service module as a dependency in your main app constructor!
//http://js2.coffee/#coffee2js
//https://coderwall.com/p/r_bvhg/angular-ui-bootstrap-alert-service-for-angular-js
'use strict';
angular.module('adf.widget.myc-sensors-bullet-graph', [])
.config(function(dashboardProvider){
dashboardProvider
.widget('mycSensorsBulletGraph', {
title: 'Sensors bullet graph',
description: 'Monitor sensors value with bullet graph',
templateUrl: 'controllers/adf-widgets/adf-myc-sbg/view.html?mcv=29',
controller: 'mycSensorsBulletGraphController',
controllerAs: 'mycSensorsBulletGraph',
config: {
colorUp:"#3f9c35",
colorDown:"#c00000",
chartFromTimestamp:'3600000',
variableIds:[],
refreshTime:30,
},
edit: {
templateUrl: 'controllers/adf-widgets/adf-myc-sbg/edit.html?mcv=29',
controller: 'mycSensorsBulletGraphEditController',
controllerAs: 'mycSensorsBulletGraphEdit',
}
});
})
.controller('mycSensorsBulletGraphController', function($scope, $interval, config, mchelper, $filter, MetricsFactory){
var mycSensorsBulletGraph = this;
mycSensorsBulletGraph.showLoading = true;
mycSensorsBulletGraph.isSyncing = true;
mycSensorsBulletGraph.variables = {};
$scope.tooltipEnabled = false;
$scope.hideVariableName=true;
mycSensorsBulletGraph.variables = {};
mycSensorsBulletGraph.chartOptions = {
chart: {
type: 'bulletChart',
transitionDuration: 500,
//color: config.color, //rgb(31, 119, 180)
noData: $filter('translate')('NO_DATA_AVAILABLE'),
margin: {
top: 8,
right: 10,
bottom: 21,
left: 5,
},
}
};
mycSensorsBulletGraph.getChartOptions = function(){
return angular.copy(mycSensorsBulletGraph.chartOptions);
}
function loadVariables(){
mycSensorsBulletGraph.isSyncing = true;
MetricsFactory.getBulletChart({'variableId':config.variableIds, "start": new Date().getTime() - config.chartFromTimestamp}, function(response){
mycSensorsBulletGraph.sensorVariables = response;
angular.forEach(mycSensorsBulletGraph.sensorVariables, function(item){
if(item.markers && item.markers[0]){
if(parseFloat(item.markers[0]) <= parseFloat(item.measures[0])){
item.color = config.colorUp;
}else{
item.color = config.colorDown;
}
}else{
item.color = "#1f77b4";//default color
}
});
mycSensorsBulletGraph.isSyncing = false;
if(mycSensorsBulletGraph.showLoading){
mycSensorsBulletGraph.showLoading = false;
}
});
};
function updateVariables(){
if(mycSensorsBulletGraph.isSyncing){
return;
}else if(config.variableIds.length > 0){
loadVariables();
}
}
//load variables initially
if(config.variableIds.length > 0){
loadVariables();
}else{
mycSensorsBulletGraph.showLoading = false;
}
//updateVariables();
//Update Variable / Send Payload
$scope.updateVariable = function(variable){
SensorsFactory.updateVariable(variable, function(){
//update Success
},function(error){
displayRestError.display(error);
});
};
// refresh every second
var promise = $interval(updateVariables, config.refreshTime*1000);
// cancel interval on scope destroy
$scope.$on('$destroy', function(){
$interval.cancel(promise);
});
}).controller('mycSensorsBulletGraphEditController', function($scope, $interval, config, mchelper, $filter, TypesFactory, CommonServices){
var mycSensorsBulletGraphEdit = this;
mycSensorsBulletGraphEdit.cs = CommonServices;
//TODO: get only DOUBLE type devices
mycSensorsBulletGraphEdit.variables = TypesFactory.getSensorVariables({"metricType":"Double"});
//Swap up down color
mycSensorsBulletGraphEdit.swapColor = function(){
var colorUp = config.colorUp;
config.colorUp = config.colorDown;
config.colorDown = colorUp;
}
});

View File

@@ -0,0 +1,58 @@
<!--
Copyright (C) 2015-2016 Jeeva Kandasamy (jkandasa@gmail.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<form role="form">
<div class="form-group">
<label>{{ 'REFRESH_TIME_SECONDS' | translate }}</label>
<input type="text" class="form-control" id="refreshTime" placeholder="{{'REFRESH_TIME_SECONDS' | translate}}" ng-model="config.refreshTime" pf-validation="mycSensorsBulletGraphEdit.cs.isNumber(input)" required>
<span class="help-block">{{ 'VALIDATION_ERROR_NUMBER' | translate }}</span>
</div>
<div class="form-group">
<label class="mc-margin-right">{{ 'COLOR' | translate }}</label>
<i uib-tooltip="{{ 'UP' | translate }}" tooltip-placement="top" class="fa fa-arrow-up mc-icon-md-3"></i>
<span style="background-color:{{config.colorUp}};width:65px;color:white;" class="btn btn-sm mc-margin-right" colorpicker="hex" colorpicker-position="top" ng-model="config.colorUp">{{config.colorUp || "-"}}</span>
<i uib-tooltip="{{ 'DOWN' | translate }}" tooltip-placement="top" class="fa fa-arrow-down mc-icon-md-3"></i>
<span style="background-color:{{config.colorDown}};width:65px;color:white;" class="btn btn-sm mc-margin-right" colorpicker="hex" colorpicker-position="top" ng-model="config.colorDown">{{config.colorDown || "-"}}</span>
<i uib-tooltip="{{ 'SWAP' | translate }}" tooltip-placement="top" ng-click="mycSensorsBulletGraphEdit.swapColor()" class="fa fa-exchange mc-icon-md-3 mc-pointer text-primary"></i>
</div>
<div class="form-group">
<label>{{ 'TIME_RANGE' | translate }}</label>
<select id="panelSize" class="form-control" pf-select ng-model="config.chartFromTimestamp">
<option value="" ng-hide="true"></option>
<option value="300000">{{ 'LAST_5_MINUTES' | translate }}</option>
<option value="3600000">{{ 'LAST_HOUR' | translate }}</option>
<option value="21600000">{{ 'LAST_6_HOURS' | translate }}</option>
<option value="43200000">{{ 'LAST_12_HOURS' | translate }}</option>
<option value="86400000">{{ 'LAST_DAY' | translate }}</option>
<option value="604800000">{{ 'LAST_WEEK' | translate }}</option>
<option value="2419200000">{{ 'LAST_MONTH' | translate }}</option>
<option value="31536000000">{{ 'LAST_YEAR' | translate }}</option>
</select>
</div>
<div class="form-group">
<label>{{ 'SENSOR_VARIABLES' | translate }}</label>
<select id="senVars" class="form-control" multiple pf-select data-live-search="true" ng-model="config.variableIds">
<option value="" ng-hide="true"></option>
<option ng-repeat="res in mycSensorsBulletGraphEdit.variables" ng-bind-html="res.displayName | mcResourceRepresentation" value="{{res.id}}" ng-selected="config.variableIds.indexOf(res.id.toString()) != -1"></option>
</select>
</div>
</form>

View File

@@ -0,0 +1,35 @@
<!--
Copyright (C) 2015-2016 Jeeva Kandasamy (jkandasa@gmail.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- Loading icon disaplay -->
<div ng-show="mycSensorsBulletGraph.showLoading">
<div ng-include src="'partials/common-html/loading-sm.html'"></div>
</div>
<div ng-if="!mycSensorsBulletGraph.showLoading">
<!-- variables ng-repeat -->
<div ng-repeat="sensorVariable in mycSensorsBulletGraph.sensorVariables track by $index">
<hr ng-if="$index != 0" class="adf-myc-sbg-margin">
<div class="adf-myc-sbg">
<span class="mc-pointer" tooltip-placement="top" ui-sref="sensorsDetail({id:sensorVariable.internalId})"
uib-tooltip-html="sensorVariable.resourceName | mcResourceRepresentation" ng-bind-html="'[S]:'+sensorVariable.displayName | mcResourceRepresentation"></span>
<nvd3 id="sbg-{{config.variableIds.join('-')}}" ng-init="chartOptions=mycSensorsBulletGraph.getChartOptions()" options="chartOptions" data="sensorVariable"></nvd3>
</div>
</div>
</div>
<div ng-if="config.variableIds.length == 0" ng-include src="'partials/common-html/no-items-filter-sm.html'"></div>

View File

@@ -0,0 +1,147 @@
/*
* Copyright 2015-2019 Jeeva Kandasamy (jkandasa@gmail.com)
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// don't forget to declare this service module as a dependency in your main app constructor!
//http://js2.coffee/#coffee2js
//https://coderwall.com/p/r_bvhg/angular-ui-bootstrap-alert-service-for-angular-js
'use strict';
angular.module('adf.widget.myc-sen-vars', [])
.config(function (dashboardProvider) {
dashboardProvider
.widget('mycSenVars', {
title: 'Sensors',
description: 'Monitor and change sensors state',
templateUrl: 'controllers/adf-widgets/adf-myc-sen-vars/view.html?mcv=29',
controller: 'mycSenVarsController',
controllerAs: 'mycSenVars',
config: {
variableIds: [],
showIcon: true,
confirmationEnabled: false,
itemsPerRow: "2",
refreshTime: 30,
},
edit: {
templateUrl: 'controllers/adf-widgets/adf-myc-sen-vars/edit.html?mcv=29',
controller: 'mycSenVarsEditController',
controllerAs: 'mycSenVarsEdit',
}
});
})
.controller('mycSenVarsController', function ($scope, $interval, config, mchelper, $filter, SensorsFactory, TypesFactory, CommonServices, $uibModal) {
var mycSenVars = this;
mycSenVars.showLoading = true;
mycSenVars.isSyncing = true;
mycSenVars.variables = {};
$scope.tooltipEnabled = false;
$scope.hideVariableName = !config.showIcon;
$scope.cs = CommonServices;
//HVAC heater options - HVAC flow state
$scope.hvacOptionsFlowState = TypesFactory.getHvacOptionsFlowState();
//HVAC heater options - HVAC flow mode
$scope.hvacOptionsFlowMode = TypesFactory.getHvacOptionsFlowMode();
//HVAC heater options - HVAC fan speed
$scope.hvacOptionsFanSpeed = TypesFactory.getHvacOptionsFanSpeed();
//Defined variable types list
$scope.definedVariableTypes = CommonServices.getSensorVariablesKnownList();
//update rgba color
$scope.updateRgba = function (variable) {
variable.value = CommonServices.rgba2hex(variable.rgba);
$scope.updateVariable(variable);
};
function loadVariables() {
mycSenVars.isSyncing = true;
SensorsFactory.getVariables({
'ids': config.variableIds
}, function (response) {
mycSenVars.variables = response;
mycSenVars.isSyncing = false;
if (mycSenVars.showLoading) {
mycSenVars.showLoading = false;
}
});
};
function updateVariables() {
if (mycSenVars.isSyncing) {
return;
} else if (config.variableIds.length > 0) {
loadVariables();
}
}
// load variables initially
loadVariables();
//updateVariables();
// update Variable / Send Payload
$scope.updateVariableFinal = function (variable) {
SensorsFactory.updateVariable(variable, function () {
//update Success
}, function (error) {
displayRestError.display(error);
});
};
// update Variable confirmation test
$scope.updateVariable = function (variable) {
if (config.confirmationEnabled) {
var addModalInstance = $uibModal.open({
templateUrl: 'controllers/adf-widgets/adf-myc-sen-vars/confirmation-modal.html?mcv=29',
controller: 'SensorVarsConfirmationController',
resolve: {
variable: variable
}
});
addModalInstance.result.then(function () {
$scope.updateVariableFinal(variable);
}),
function () {
//console.log('Modal dismissed at: ' + new Date());
}
} else {
$scope.updateVariableFinal(variable);
}
};
// refresh every second
var promise = $interval(updateVariables, config.refreshTime * 1000);
// cancel interval on scope destroy
$scope.$on('$destroy', function () {
$interval.cancel(promise);
});
}).controller('mycSenVarsEditController', function ($scope, $interval, config, mchelper, $filter, TypesFactory, CommonServices) {
var mycSenVarsEdit = this;
mycSenVarsEdit.cs = CommonServices;
mycSenVarsEdit.variables = TypesFactory.getSensorVariables();
}).controller('SensorVarsConfirmationController', function ($scope, $uibModalInstance, $filter, variable) {
$scope.variable = variable;
$scope.accept = function () {
$uibModalInstance.close();
};
$scope.cancel = function () {
$uibModalInstance.dismiss('cancel');
}
});

View File

@@ -0,0 +1,37 @@
<!--
Copyright (C) 2015-2016 Jeeva Kandasamy (jkandasa@gmail.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<div>
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true" ng-click="cancel()">
<span class="pficon pficon-close"></span>
</button>
<div class="modal-title"><b>{{ 'SENSOR_VARIABLE_SUBMIT_CONFIRMATION_TITLE' | translate }}</b></div>
</div>
<div class="modal-body modal-body-text-only">
<div class="mc-model-text-margin">{{ 'SENSOR_VARIABLE_SUBMIT_CONFIRMATION_MESSAGE' | translate }}</div>
<pre><span ng-bind-html="variable.resourceName | mcResourceRepresentation"></span><span>, <b class="mc-color-steel-blue">{{ 'PAYLOAD' | translate }}: {{variable.value}}</span></b></pre>
</div>
<div class="modal-footer">
<button class="btn btn-default" ng-click="cancel()"><i class="fa fa-close"></i> {{ 'CANCEL' | translate }}</button>
<button class="btn btn-primary" ng-click="accept()"><i class="fa fa-check"></i> {{ 'CONTINUE' | translate }}</button>
</div>
</div>

View File

@@ -0,0 +1,54 @@
<!--
Copyright (C) 2015-2016 Jeeva Kandasamy (jkandasa@gmail.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<form role="form">
<div class="form-group">
<label>{{ 'REFRESH_TIME_SECONDS' | translate }}</label>
<input type="text" class="form-control" id="refreshTime" placeholder="{{'REFRESH_TIME_SECONDS' | translate}}" ng-model="config.refreshTime" pf-validation="mycSenVarsEdit.cs.isNumber(input)" required>
<span class="help-block">{{ 'VALIDATION_ERROR_NUMBER' | translate }}</span>
</div>
<div class="form-group">
<input ng-model="config.showIcon" type="checkbox"/>
<label class="control-label">{{ 'SHOW_ICON' | translate }}</label>
</div>
<div class="form-group">
<input ng-model="config.confirmationEnabled" type="checkbox"/>
<label class="control-label">{{ 'ENABLE_CONFIRMATION' | translate }}</label>
</div>
<div class="form-group">
<label>{{ 'ITEMS_PER_ROW' | translate }}</label>
<select id="panelSize" class="form-control" pf-select ng-model="config.itemsPerRow">
<option value="" ng-hide="true"></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="6">6</option>
<option value="12">12</option>
</select>
</div>
<div class="form-group">
<label>{{ 'SENSOR_VARIABLES' | translate }}</label>
<select id="senVars" class="form-control" multiple pf-select data-live-search="true" ng-model="config.variableIds">
<option value="" ng-hide="true"></option>
<option ng-repeat="res in mycSenVarsEdit.variables" ng-bind-html="res.displayName | mcResourceRepresentation" value="{{res.id}}" ng-selected="config.variableIds.indexOf(res.id.toString()) != -1"></option>
</select>
</div>
</form>

View File

@@ -0,0 +1,41 @@
<!--
Copyright (C) 2015-2016 Jeeva Kandasamy (jkandasa@gmail.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- Loading icon disaplay -->
<div ng-show="mycSenVars.showLoading">
<div ng-include src="'partials/common-html/loading-sm.html'"></div>
</div>
<div ng-hide="mycSenVars.showLoading">
<!-- variables ng-repeat -->
<div ng-repeat="variable in mycSenVars.variables">
<div class="col-md-{{12/config.itemsPerRow}}">
<div class="card-pf card-pf-aggregate-status card-pf-with-action card-pf-accented adf-myc-sen-var">
<h2 class="card-pf-title mc-pointer" tooltip-placement="top" uib-tooltip-html="variable.resourceName | mcResourceRepresentation" ui-sref="sensorsDetail({id:variable.sensorId})"><i class="fa fa-eye"></i>{{variable.sensorName}}</h2>
<div class="card-pf-body">
<!-- Sensor variables -->
<div ng-include src="'partials/common-html/sensor-actions-items.html'"></div>
</div>
</div>
</div>
</div>
<div ng-if="mycSenVars.variables.length == 0" ng-include src="'partials/common-html/no-items-filter-sm.html'"></div>
</div>
</div>

View File

@@ -0,0 +1,173 @@
/*
* Copyright 2015-2018 Jeeva Kandasamy (jkandasa@gmail.com)
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// don't forget to declare this service module as a dependency in your main app constructor!
//http://js2.coffee/#coffee2js
//https://coderwall.com/p/r_bvhg/angular-ui-bootstrap-alert-service-for-angular-js
'use strict';
angular.module('adf.widget.myc-sensors-grouped-graph', [])
.config(function(dashboardProvider){
dashboardProvider
.widget('mycSensorsGroupedGraph', {
title: 'Grouped sensors graph',
description: 'Similar type of sensors grouped graphical view',
templateUrl: 'controllers/adf-widgets/adf-myc-sgg/view.html?mcv=29',
controller: 'mycSensorsGroupedGraphController',
controllerAs: 'mycSensorsGroupedGraph',
config: {
useInteractiveGuideline:true,
enableUniqueName:false,
variableId:[],
variableType:null,
chartFromTimestamp:'3600000',
refreshTime:30,
marginTop:5,
marginRight:20,
marginBottom:60,
marginLeft:65,
},
edit: {
templateUrl: 'controllers/adf-widgets/adf-myc-sgg/edit.html?mcv=29',
controller: 'mycSensorsGroupedGraphEditController',
controllerAs: 'mycSensorsGroupedGraphEdit',
}
});
})
.controller('mycSensorsGroupedGraphController', function($scope, $interval, config, mchelper, $filter, MetricsFactory, CommonServices){
var mycSensorsGroupedGraph = this;
mycSensorsGroupedGraph.showLoading = true;
mycSensorsGroupedGraph.showError = false;
mycSensorsGroupedGraph.isSyncing = false;
mycSensorsGroupedGraph.cs = CommonServices;
CommonServices.updateGraphMarginDefault(config);
mycSensorsGroupedGraph.chartOptions = {
chart: {
type: 'lineChart',
noErrorCheck: true,
height: 225,
margin : {
top: config.marginTop,
right: config.marginRight,
bottom: config.marginBottom,
left: config.marginLeft,
},
color: d3.scale.category10().range(),
noData: $filter('translate')('NO_DATA_AVAILABLE'),
x: function(d){return d[0];},
y: function(d){return d[1];},
useVoronoi: !config.useInteractiveGuideline,
useInteractiveGuideline: config.useInteractiveGuideline,
clipEdge: false,
xAxis: {
showMaxMin: false,
tickFormat: function(d) {
return d3.time.format('hh:mm a')(new Date(d))
},
//axisLabel: 'Timestamp',
rotateLabels: -20
},
yAxis: {
tickFormat: function(d){
return d3.format(',.2f')(d);
},
axisLabelDistance: -10,
//axisLabel: ''
},
},
title: {
enable: false,
text: 'Title'
}
};
mycSensorsGroupedGraph.chartTimeFormat = mchelper.cfg.dateFormat;
function updateChart(){
mycSensorsGroupedGraph.isSyncing = true;
MetricsFactory.getMetricsData({"variableId":config.variableId, "chartType":"lineChart", "start": new Date().getTime() - config.chartFromTimestamp, "enableDetailedKey": config.enableUniqueName === undefined ? false : config.enableUniqueName}, function(resource){
if(resource.length > 0){
mycSensorsGroupedGraph.chartData = resource[0].chartData;
//Update display time format
mycSensorsGroupedGraph.chartTimeFormat = resource[0].timeFormat;
mycSensorsGroupedGraph.chartOptions.chart.xAxis.tickFormat = function(d) {return $filter('date')(d, mycSensorsGroupedGraph.chartTimeFormat, mchelper.cfg.timezone)};
mycSensorsGroupedGraph.chartOptions.chart.interpolate = resource[0].chartInterpolate;
if(resource[0].unit === ''){
mycSensorsGroupedGraph.chartOptions.chart.yAxis.tickFormat = function(d){return d3.format('.0f')(d);};
}else{
mycSensorsGroupedGraph.chartOptions.chart.yAxis.tickFormat = function(d){return d3.format('.02f')(d) + ' ' + resource[0].unit;};
}
}else{
if(config.variableId.length !== 0){
mycSensorsGroupedGraph.showError = true;
}
}
mycSensorsGroupedGraph.isSyncing = false;
if(mycSensorsGroupedGraph.showLoading){
mycSensorsGroupedGraph.showLoading = false;
}
});
}
function updateVariables(){
if(mycSensorsGroupedGraph.isSyncing){
return;
}else if(config.variableId.length !== 0){
updateChart();
}else{
mycSensorsGroupedGraph.showLoading = false;
}
}
//load graph initially
updateVariables();
// refresh every second
var promise = $interval(updateVariables, config.refreshTime*1000);
// cancel interval on scope destroy
$scope.$on('$destroy', function(){
$interval.cancel(promise);
});
}).controller('mycSensorsGroupedGraphEditController', function($scope, $interval, config, mchelper, $filter, TypesFactory, CommonServices){
var mycSensorsGroupedGraphEdit = this;
mycSensorsGroupedGraphEdit.cs = CommonServices;
mycSensorsGroupedGraphEdit.onVariableTypeChange = function(){
config.variableId = [];
if(config.variableType){
mycSensorsGroupedGraphEdit.variables = TypesFactory.getSensorVariables({"variableType":config.variableType});
}else{
mycSensorsGroupedGraphEdit.variables = {};
}
};
//Load variable types
mycSensorsGroupedGraphEdit.variableTypes = TypesFactory.getSensorVariableTypes({"metricType":["Double","Binary", "Counter"]});
if(config.variableType){
var variableIdRef = config.variableId;
mycSensorsGroupedGraphEdit.onVariableTypeChange();
config.variableId = variableIdRef;
}
});

View File

@@ -0,0 +1,101 @@
<!--
Copyright (C) 2015-2016 Jeeva Kandasamy (jkandasa@gmail.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<form role="form">
<div class="form-group">
<label>{{ 'REFRESH_TIME_SECONDS' | translate }}</label>
<input type="text" class="form-control" id="refreshTime" placeholder="{{'REFRESH_TIME_SECONDS' | translate}}" ng-model="config.refreshTime" pf-validation="mycSensorsGroupedGraphEdit.cs.isNumber(input)" required>
<span class="help-block">{{ 'VALIDATION_ERROR_NUMBER' | translate }}</span>
</div>
<div class="form-group">
<input ng-model="config.useInteractiveGuideline" type="checkbox"/>
<label class="control-label">{{ 'USE_INTERACTIVE_GUIDE_LINE' | translate }}</label>
</div>
<div class="form-group">
<input ng-model="config.enableUniqueName" type="checkbox"/>
<label class="control-label">{{ 'ENABLE_UNIQUE_NAME' | translate }}</label>
</div>
<div class="form-group">
<label>{{ 'MARGIN' | translate }}</label>
<table class="adf-table">
<tr>
<td>
<label>{{ 'LEFT' | translate }}</label>
</td>
<td>
<input class="form-control" type="number" id="left" placeholder="{{'LEFT' | translate}}" ng-model="config.marginLeft" pf-validation="mycSensorsGroupedGraphEdit.cs.isNumber(input)" required>
</td>
<td>
<label class="mc-margin-right">{{ 'RIGHT' | translate }}</label>
</td>
<td>
<input class="form-control" type="number" id="right" placeholder="{{'RIGHT' | translate}}" ng-model="config.marginRight" pf-validation="mycSensorsGroupedGraphEdit.cs.isNumber(input)" required>
</td>
</tr>
<tr>
<td>
<label>{{ 'TOP' | translate }}</label>
</td>
<td>
<input class="form-control" type="number" id="top" placeholder="{{'TOP' | translate}}" ng-model="config.marginTop" pf-validation="mycSensorsGroupedGraphEdit.cs.isNumber(input)" required>
</td>
<td>
<label>{{ 'BOTTOM' | translate }}</label>
</td>
<td>
<input class="form-control" type="number" id="bottom" placeholder="{{'BOTTOM' | translate}}" ng-model="config.marginBottom" pf-validation="mycSensorsGroupedGraphEdit.cs.isNumber(input)" required>
</td>
</tr>
</table>
</div>
<div class="form-group">
<label>{{ 'TIME_RANGE' | translate }}</label>
<select id="panelSize" class="form-control" pf-select ng-model="config.chartFromTimestamp">
<option value="" ng-hide="true"></option>
<option value="300000">{{ 'LAST_5_MINUTES' | translate }}</option>
<option value="3600000">{{ 'LAST_HOUR' | translate }}</option>
<option value="21600000">{{ 'LAST_6_HOURS' | translate }}</option>
<option value="43200000">{{ 'LAST_12_HOURS' | translate }}</option>
<option value="86400000">{{ 'LAST_DAY' | translate }}</option>
<option value="604800000">{{ 'LAST_WEEK' | translate }}</option>
<option value="2419200000">{{ 'LAST_MONTH' | translate }}</option>
<option value="31536000000">{{ 'LAST_YEAR' | translate }}</option>
</select>
</div>
<div class="form-group">
<label>{{ 'SENSOR_VARIABLE_TYPE' | translate }}</label>
<select id="senVarsTypes" class="form-control" pf-select data-live-search="true" ng-model="config.variableType" ng-change="mycSensorsGroupedGraphEdit.onVariableTypeChange()">
<option value="" ng-hide="true"></option>
<option ng-repeat="vType in mycSensorsGroupedGraphEdit.variableTypes | orderBy: 'displayName'" value="{{vType.id}}" ng-selected="config.variableType === vType.id">{{vType.displayName}}</option>
</select>
</div>
<div class="form-group">
<label>{{ 'SENSOR_VARIABLE' | translate }}</label>
<select id="senVars" class="form-control" multiple pf-select data-live-search="true" ng-model="config.variableId">
<option value="" ng-hide="true"></option>
<option ng-repeat="res in mycSensorsGroupedGraphEdit.variables" ng-bind-html="res.displayName | mcResourceRepresentation" value="{{res.id}}"
ng-selected="config.variableId.indexOf(res.id.toString()) !== -1 "></option>
</select>
</div>
</form>

View File

@@ -0,0 +1,32 @@
<!--
Copyright (C) 2015-2016 Jeeva Kandasamy (jkandasa@gmail.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- Loading icon disaplay -->
<div ng-if="mycSensorsGroupedGraph.showLoading">
<div ng-include src="'partials/common-html/loading-sm.html'"></div>
</div>
<div ng-if="mycSensorsGroupedGraph.showError">
<div ng-include src="'partials/common-html/error-sm.html'"></div>
</div>
<div ng-if="!(mycSensorsGroupedGraph.showLoading || mycSensorsGroupedGraph.showError)">
<!-- <label>{{ 'SENSOR_VARIABLE_TYPE' | translate }}: {{config.variableType}}</label> -->
<nvd3 id="sgg-{{config.variableId.join('-')}}" options='mycSensorsGroupedGraph.chartOptions' data="mycSensorsGroupedGraph.chartData"></nvd3>
<div ng-if="config.variableId.length === 0" ng-include src="'partials/common-html/no-items-filter-sm.html'"></div>
</div>

View File

@@ -0,0 +1,196 @@
/*
* Copyright 2015-2018 Jeeva Kandasamy (jkandasa@gmail.com)
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// don't forget to declare this service module as a dependency in your main app constructor!
//http://js2.coffee/#coffee2js
//https://coderwall.com/p/r_bvhg/angular-ui-bootstrap-alert-service-for-angular-js
'use strict';
angular.module('adf.widget.myc-sensors-mixed-graph', [])
.config(function(dashboardProvider){
dashboardProvider
.widget('mycSensorsMixedGraph', {
title: 'Mixed sensors graph',
description: 'Different type of sensors mixed graphical view [refer document]',
templateUrl: 'controllers/adf-widgets/adf-myc-smg/view.html?mcv=29',
controller: 'mycSensorsMixedGraphController',
controllerAs: 'mycSensorsMixedGraph',
config: {
useInteractiveGuideline:false,
enableUniqueName:false,
chartInterpolate:"linear",
variableId:[],
variableType:[],
chartFromTimestamp:'3600000',
refreshTime:30,
marginTop:5,
marginRight:20,
marginBottom:60,
marginLeft:65,
},
edit: {
templateUrl: 'controllers/adf-widgets/adf-myc-smg/edit.html?mcv=29',
controller: 'mycSensorsMixedGraphEditController',
controllerAs: 'mycSensorsMixedGraphEdit',
}
});
})
.controller('mycSensorsMixedGraphController', function($scope, $interval, config, mchelper, $filter, MetricsFactory, CommonServices){
var mycSensorsMixedGraph = this;
mycSensorsMixedGraph.showLoading = true;
mycSensorsMixedGraph.showError = false;
mycSensorsMixedGraph.isSyncing = false;
CommonServices.updateGraphMarginDefault(config);
mycSensorsMixedGraph.chartOptions = {
chart: {
type: 'multiChart',
noErrorCheck: true,
height: 225,
margin : {
top: config.marginTop,
right: config.marginRight,
bottom: config.marginBottom,
left: config.marginLeft,
},
color: d3.scale.category10().range(),
duration: 500,
noData: $filter('translate')('NO_DATA_AVAILABLE'),
//x: function(d,i){return d[0];},
//y: function(d,i){return d[1];},
clipEdge: false,
useVoronoi: !config.useInteractiveGuideline,
useInteractiveGuideline: config.useInteractiveGuideline,
xAxis: {
showMaxMin: false,
tickFormat: function(d) {
return d3.time.format('hh:mm a')(new Date(d))
},
//axisLabel: 'Timestamp',
rotateLabels: -20
},
yAxis1: {
axisLabelDistance: -10,
//axisLabel: ''
},
yAxis2: {
axisLabelDistance: -10,
//axisLabel: ''
},
},
title: {
enable: false,
text: 'Title'
}
};
mycSensorsMixedGraph.chartTimeFormat = mchelper.cfg.dateFormat;
function updateChart(){
mycSensorsMixedGraph.isSyncing = true;
MetricsFactory.getMetricsData({"variableId":config.variableId, "chartType":"multiChart", "start": new Date().getTime() - config.chartFromTimestamp, "enableDetailedKey": config.enableUniqueName === undefined ? false : config.enableUniqueName}, function(resource){
if(resource.length > 0){
mycSensorsMixedGraph.chartData = resource[0].chartData;
//Update display time format
mycSensorsMixedGraph.chartTimeFormat = resource[0].timeFormat;
mycSensorsMixedGraph.chartOptions.chart.xAxis.tickFormat = function(d) {return $filter('date')(d, mycSensorsMixedGraph.chartTimeFormat, mchelper.cfg.timezone)};
mycSensorsMixedGraph.chartOptions.chart.interpolate = config.chartInterpolate;
if(resource[0].unit === ''){
mycSensorsMixedGraph.chartOptions.chart.yAxis1.tickFormat = function(d){return d3.format('.0f')(d);};
}else{
//Not displaying properly axis unit, there is an issue
if(config.useInteractiveGuideline){
mycSensorsMixedGraph.chartOptions.chart.yAxis1.tickFormat = function(d){return d3.format('.02f')(d) + ' ' + resource[0].unit;};
}else{
mycSensorsMixedGraph.chartOptions.chart.yAxis1.tickFormat = function(d){return d3.format('.02f')(d)};
}
}
if(resource[0].unit2 === ''){
mycSensorsMixedGraph.chartOptions.chart.yAxis2.tickFormat = function(d){return d3.format('.0f')(d);};
}else{
mycSensorsMixedGraph.chartOptions.chart.yAxis2.tickFormat = function(d){return d3.format('.02f')(d) + ' ' + resource[0].unit2;};
}
}else{
if(config.variableId.length !== 0){
mycSensorsMixedGraph.showError = true;
}
}
mycSensorsMixedGraph.isSyncing = false;
if(mycSensorsMixedGraph.showLoading){
mycSensorsMixedGraph.showLoading = false;
}
});
}
function updateVariables(){
if(mycSensorsMixedGraph.isSyncing){
return;
}else if(config.variableId.length !== 0){
updateChart();
}
}
//load graph initially
updateVariables();
// refresh every second
var promise = $interval(updateChart, config.refreshTime*1000);
// cancel interval on scope destroy
$scope.$on('$destroy', function(){
$interval.cancel(promise);
});
}).controller('mycSensorsMixedGraphEditController', function($scope, $interval, config, mchelper, $filter, TypesFactory, CommonServices){
var mycSensorsMixedGraphEdit = this;
mycSensorsMixedGraphEdit.onVariableTypeChange = function(){
if(config.variableType.length > 0){
TypesFactory.getSensorVariables({"variableType":config.variableType}, function(response){
mycSensorsMixedGraphEdit.variables = response;
var newVariableId = [];
response.forEach(function(item) {
if(config.variableId.indexOf(item.id.toString()) !== -1){
newVariableId.push(item.id.toString());
}
});
config.variableId = newVariableId;
});
}else{
mycSensorsMixedGraphEdit.variables = {};
config.variableId = [];
}
};
//Pre load
mycSensorsMixedGraphEdit.cs = CommonServices;
//Load variable types
mycSensorsMixedGraphEdit.variableTypes = TypesFactory.getSensorVariableTypes({"metricType":["Double","Binary","Counter"]});
if(config.variableType.length > 0){
var variableIdRef = config.variableId;
mycSensorsMixedGraphEdit.onVariableTypeChange();
config.variableId = variableIdRef;
}
});

View File

@@ -0,0 +1,120 @@
<!--
Copyright (C) 2015-2016 Jeeva Kandasamy (jkandasa@gmail.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<form role="form">
<div class="form-group">
<label>{{ 'REFRESH_TIME_SECONDS' | translate }}</label>
<input type="text" class="form-control" id="refreshTime" placeholder="{{'REFRESH_TIME_SECONDS' | translate}}" ng-model="config.refreshTime" pf-validation="mycSensorsMixedGraphEdit.cs.isNumber(input)" required>
<span class="help-block">{{ 'VALIDATION_ERROR_NUMBER' | translate }}</span>
</div>
<div class="form-group">
<input ng-model="config.useInteractiveGuideline" type="checkbox"/>
<label class="control-label">{{ 'USE_INTERACTIVE_GUIDE_LINE' | translate }}</label>
</div>
<div class="form-group">
<input ng-model="config.enableUniqueName" type="checkbox"/>
<label class="control-label">{{ 'ENABLE_UNIQUE_NAME' | translate }}</label>
</div>
<div class="form-group">
<label>{{ 'MARGIN' | translate }}</label>
<table class="adf-table">
<tr>
<td>
<label>{{ 'LEFT' | translate }}</label>
</td>
<td>
<input class="form-control" type="number" id="left" placeholder="{{'LEFT' | translate}}" ng-model="config.marginLeft" pf-validation="mycSensorsMixedGraphEdit.cs.isNumber(input)" required>
</td>
<td>
<label class="mc-margin-right">{{ 'RIGHT' | translate }}</label>
</td>
<td>
<input class="form-control" type="number" id="right" placeholder="{{'RIGHT' | translate}}" ng-model="config.marginRight" pf-validation="mycSensorsMixedGraphEdit.cs.isNumber(input)" required>
</td>
</tr>
<tr>
<td>
<label>{{ 'TOP' | translate }}</label>
</td>
<td>
<input class="form-control" type="number" id="top" placeholder="{{'TOP' | translate}}" ng-model="config.marginTop" pf-validation="mycSensorsMixedGraphEdit.cs.isNumber(input)" required>
</td>
<td>
<label>{{ 'BOTTOM' | translate }}</label>
</td>
<td>
<input class="form-control" type="number" id="bottom" placeholder="{{'BOTTOM' | translate}}" ng-model="config.marginBottom" pf-validation="mycSensorsMixedGraphEdit.cs.isNumber(input)" required>
</td>
</tr>
</table>
</div>
<div class="form-group">
<label>{{ 'INTERPOLATE_TYPE' | translate }}</label>
<select class="form-control" pf-select ng-model="config.chartInterpolate" required>
<option value="" ng-hide="true"></option>
<option value="linear">{{ 'LINEAR' | translate }}</option>
<option value="basis">{{ 'BASIS' | translate }}</option>
<option value="cardinal">{{ 'CARDINAL' | translate }}</option>
<option value="monotone">{{ 'MONOTONE' | translate }}</option>
<option value="bundle">{{ 'BUNDLE' | translate }}</option>
<option value="step-before">{{ 'STEP_BEFORE' | translate }}</option>
<option value="step-after">{{ 'STEP_AFTER' | translate }}</option>
<option value="basis-open">{{ 'BASIS_OPEN' | translate }}</option>
<option value="basis-closed">{{ 'BASIS_CLOSED' | translate }}</option>
<option value="cardinal-open">{{ 'CARDINAL_OPEN' | translate }}</option>
<option value="cardinal-closed">{{ 'CARDINAL_CLOSED' | translate }}</option>
</select>
</div>
<div class="form-group">
<label>{{ 'TIME_RANGE' | translate }}</label>
<select id="panelSize" class="form-control" pf-select ng-model="config.chartFromTimestamp" required>
<option value="" ng-hide="true"></option>
<option value="300000">{{ 'LAST_5_MINUTES' | translate }}</option>
<option value="3600000">{{ 'LAST_HOUR' | translate }}</option>
<option value="21600000">{{ 'LAST_6_HOURS' | translate }}</option>
<option value="43200000">{{ 'LAST_12_HOURS' | translate }}</option>
<option value="86400000">{{ 'LAST_DAY' | translate }}</option>
<option value="604800000">{{ 'LAST_WEEK' | translate }}</option>
<option value="2419200000">{{ 'LAST_MONTH' | translate }}</option>
<option value="31536000000">{{ 'LAST_YEAR' | translate }}</option>
</select>
</div>
<div class="form-group">
<label>{{ 'SENSOR_VARIABLE_TYPE' | translate }}</label>
<select id="senVarsTypes" class="form-control" multiple pf-select data-live-search="true" ng-model="config.variableType" ng-change="mycSensorsMixedGraphEdit.onVariableTypeChange()" required>
<option value="" ng-hide="true"></option>
<option ng-repeat="vType in mycSensorsMixedGraphEdit.variableTypes" value="{{vType.id}}" ng-selected="config.variableType.indexOf(vType.id) !== -1 ">{{vType.displayName}}</option>
</select>
</div>
<div class="form-group">
<label>{{ 'SENSOR_VARIABLE' | translate }}</label>
<select id="senVars" class="form-control" multiple pf-select data-live-search="true" ng-model="config.variableId" required>
<option value="" ng-hide="true"></option>
<option ng-repeat="res in mycSensorsMixedGraphEdit.variables" ng-bind-html="res.displayName | mcResourceRepresentation" value="{{res.id}}"
ng-selected="config.variableId.indexOf(res.id.toString()) !== -1 "></option>
</select>
</div>
</form>

View File

@@ -0,0 +1,38 @@
<!--
Copyright (C) 2015-2016 Jeeva Kandasamy (jkandasa@gmail.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<div ng-if="config.variableId.length !== 0">
<!-- Loading icon disaplay -->
<div ng-if="mycSensorsMixedGraph.showLoading">
<div ng-include src="'partials/common-html/loading-sm.html'"></div>
</div>
<div ng-if="mycSensorsMixedGraph.showError">
<div ng-include src="'partials/common-html/error-sm.html'"></div>
</div>
<div ng-if="!(mycSensorsMixedGraph.showLoading || mycSensorsMixedGraph.showError)">
<!-- <span ng-bind-html="mycSensorsMixedGraph.resourceName | mcResourceRepresentation"></span> -->
<nvd3 id="msg-{{config.variableId.join('-')}}" options='mycSensorsMixedGraph.chartOptions' data="mycSensorsMixedGraph.chartData"></nvd3>
<div ng-if="config.variableId.length === 0" ng-include src="'partials/common-html/no-items-filter-sm.html'"></div>
</div>
</div>
<div ng-if="config.variableId.length == 0" ng-include src="'partials/common-html/no-items-filter-sm.html'"></div>

View File

@@ -0,0 +1,73 @@
/*
* Copyright 2015-2018 Jeeva Kandasamy (jkandasa@gmail.com)
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// don't forget to declare this service module as a dependency in your main app constructor!
//http://js2.coffee/#coffee2js
//https://coderwall.com/p/r_bvhg/angular-ui-bootstrap-alert-service-for-angular-js
'use strict';
angular.module('adf.widget.myc-sunrisetime', [])
.config(function(dashboardProvider){
dashboardProvider
.widget('mycSunriseTime', {
title: 'Sunrise and sunset time',
description: 'Displays sunrise and sunset time from MyController configuration',
templateUrl: 'controllers/adf-widgets/adf-myc-sunrisetime/view.html?mcv=29',
controller: 'mycSunriseController',
controllerAs: 'mycSunriseTime',
config: {
refreshTime:300,
},
edit: {
templateUrl: 'controllers/adf-widgets/adf-myc-sunrisetime/edit.html?mcv=29'
}
});
})
.controller('mycSunriseController', function($scope, $interval, config, mchelper, $filter, SettingsFactory){
var mycSunriseTime = this;
mycSunriseTime.isSyncing = false;
mycSunriseTime.showLoading = true;
function updateLocationSettings(){
if(mycSunriseTime.isSyncing){
return;
}
mycSunriseTime.isSyncing = true;
SettingsFactory.getLocation(function(response){
mycSunriseTime.sunriseTime = $filter('date')(response.sunriseTime, mchelper.cfg.timeFormatWithoutSeconds, mchelper.cfg.timezone);
mycSunriseTime.sunsetTime = $filter('date')(response.sunsetTime, mchelper.cfg.timeFormatWithoutSeconds, mchelper.cfg.timezone);
mycSunriseTime.latitude = response.latitude;
mycSunriseTime.longitude = response.longitude;
mycSunriseTime.name = response.name;
mycSunriseTime.isSyncing = false;
if(mycSunriseTime.showLoading){
mycSunriseTime.showLoading = false;
}
});
};
updateLocationSettings();
// refresh every five minutes
var promise = $interval(updateLocationSettings, config.refreshTime*1000);
// cancel interval on scope destroy
$scope.$on('$destroy', function(){
$interval.cancel(promise);
});
});

View File

@@ -0,0 +1,23 @@
<!--
Copyright (C) 2015-2016 Jeeva Kandasamy (jkandasa@gmail.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<form role="form">
<div class="form-group">
<label>{{ 'REFRESH_TIME_SECONDS' | translate }}</label>
<input type="text" class="form-control" id="refreshTime" ng-model="config.refreshTime">
</div>
</form>

View File

@@ -0,0 +1,28 @@
<!--
Copyright (C) 2015-2016 Jeeva Kandasamy (jkandasa@gmail.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- Loading icon disaplay -->
<div ng-show="mycSunriseTime.showLoading">
<div ng-include src="'partials/common-html/loading-sm.html'"></div>
</div>
<div ng-hide="mycSunriseTime.showLoading">
<div class="adf-mycsr">
<div class="adf-mycsr-time"><i class="wi wi-sunrise"></i>{{mycSunriseTime.sunriseTime}}<i class="wi wi-sunset"></i>{{mycSunriseTime.sunsetTime}}</div>
<div class="adf-mycsr-location"><i class="fa fa-map-marker"></i>{{mycSunriseTime.name}}</div>
</div>
</div>

View File

@@ -0,0 +1,92 @@
/*
* Copyright 2015-2018 Jeeva Kandasamy (jkandasa@gmail.com)
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// don't forget to declare this service module as a dependency in your main app constructor!
//http://js2.coffee/#coffee2js
//https://coderwall.com/p/r_bvhg/angular-ui-bootstrap-alert-service-for-angular-js
'use strict';
angular.module('adf.widget.myc-time', [])
.config(function(dashboardProvider){
dashboardProvider
.widget('mycTime', {
title: 'MyController time',
description: 'Displays date and time of MyController',
templateUrl: 'controllers/adf-widgets/adf-myc-time/view.html?mcv=29',
controller: 'mycTimeController',
controllerAs: 'mycTime',
config: {
datePattern: 'MMM dd, yyyy',
refreshTime:120,
},
edit: {
templateUrl: 'controllers/adf-widgets/adf-myc-time/edit.html?mcv=29'
}
});
})
.controller('mycTimeController', function($scope, $interval, config, mchelper, $filter, StatusFactory){
var mycTime = this;
mycTime.isSyncing = false;
mycTime.showLoading = true;
mycTime.mycTimestamp = {};
function updateDateTime(){
mycTime.time = $filter('date')(mycTime.mycTimestamp.timestamp, mchelper.cfg.timeFormat, mchelper.cfg.timezone);
mycTime.date = $filter('date')(mycTime.mycTimestamp.timestamp, config.datePattern, mchelper.cfg.timezone);
mycTime.timezone = mchelper.cfg.timezone;
mycTime.timezoneString = mchelper.cfg.timezoneString;
};
function getTimestampFromServer(){
mycTime.isSyncing = true;
StatusFactory.getTimestamp(function(response){
mycTime.mycTimestamp = response;
updateDateTime();
mycTime.isSyncing = false;
if(mycTime.showLoading){
mycTime.showLoading = false;
}
});
};
function setDateAndTime(){
if(mycTime.isSyncing){
return;
}
if((mycTime.mycTimestamp.timestamp/1000 | 0) % config.refreshTime == 0){
if(!mycTime.isSyncing){
getTimestampFromServer();
}
}else{
mycTime.mycTimestamp.timestamp += 1000;
updateDateTime();
}
}
getTimestampFromServer();
setDateAndTime();
// refresh every second
var promise = $interval(setDateAndTime, 1000);
// cancel interval on scope destroy
$scope.$on('$destroy', function(){
$interval.cancel(promise);
});
});

View File

@@ -0,0 +1,31 @@
<!--
Copyright (C) 2015-2016 Jeeva Kandasamy (jkandasa@gmail.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<form role="form">
<div class="form-group">
<label>{{ 'REFRESH_TIME_SECONDS' | translate }}</label>
<input type="text" class="form-control" id="refreshTime" ng-model="config.refreshTime">
</div>
<div class="form-group">
<label for="date">{{ 'DATE_PATTERN' | translate }}</label>
<input type="text" class="form-control" id="date" ng-model="config.datePattern">
</div>
<p class="text-info">
For the list of possible patterns, please have a look at
<a target="_blank" href="https://docs.angularjs.org/api/ng/filter/date">angular date documentation</a>
</p>
</form>

View File

@@ -0,0 +1,28 @@
<!--
Copyright (C) 2015-2016 Jeeva Kandasamy (jkandasa@gmail.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- Loading icon disaplay -->
<div ng-show="mycTime.showLoading">
<div ng-include src="'partials/common-html/loading-sm.html'"></div>
</div>
<div ng-hide="mycTime.showLoading">
<div class="adf-myct">
<div class="adf-myct-time">{{mycTime.time}}</div>
<div class="adf-myct-date">{{mycTime.date}},<span class="adf-myct-timezone"> {{mycTime.timezoneString}} ({{mycTime.timezone}})</span></div>
</div>
</div>

View File

@@ -0,0 +1,18 @@
<!--
Copyright (C) 2015-2016 Jeeva Kandasamy (jkandasa@gmail.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- to avoid 'apply' issue, while changing title of widgets -->

224
www/controllers/backup.js Normal file
View File

@@ -0,0 +1,224 @@
/*
* Copyright 2015-2018 Jeeva Kandasamy (jkandasa@gmail.com)
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
myControllerModule.controller('BackupControllerList', function(alertService, $scope, $filter, displayRestError, BackupRestoreFactory, $filter, mchelper, CommonServices, $uibModal) {
//GUI page settings
$scope.headerStringList = $filter('translate')('BACKUPS_DETAIL');
$scope.noItemsSystemMsg = $filter('translate')('NO_BACKUPS_SETUP');
$scope.noItemsSystemIcon = "fa fa-database";
//load empty, configuration, etc.,
$scope.mchelper = mchelper;
$scope.filteredList=[];
//data query details
$scope.currentPage = 1;
$scope.query = CommonServices.getQuery();
$scope.queryResponse = {};
//Get min number
$scope.getMin = function(item1, item2){
return CommonServices.getMin(item1, item2);
};
//get all items
$scope.getAllItems = function(){
BackupRestoreFactory.getAll($scope.query, function(response) {
$scope.queryResponse = response;
$scope.filteredList = $scope.queryResponse.data;
$scope.filterConfig.resultsCount = $scope.queryResponse.query.filteredCount;
},function(error){
$scope.queryResponse.$resolved = true;
displayRestError.display(error);
});
}
//Hold all the selected item ids
$scope.itemIds = [];
$scope.selectAllItems = function(){
CommonServices.selectAllItems($scope, 'name');
};
$scope.selectItem = function(item){
CommonServices.selectItem($scope, item, 'name');
};
//On page change
$scope.pageChanged = function(newPage){
CommonServices.updatePageChange($scope, newPage);
};
//Filter change method
var filterChange = function (filters) {
//Reset filter fields and update items
CommonServices.updateFiltersChange($scope, filters);
};
$scope.filterConfig = {
fields: [
{
id: 'name',
title: $filter('translate')('NAME'),
placeholder: $filter('translate')('FILTER_BY_NAME'),
filterType: 'text'
}
],
resultsCount: $scope.filteredList.length,
appliedFilters: [],
onFilterChange: filterChange
};
//Sort columns [*** NOT IN USE ***]
var sortChange = function (sortId, isAscending) {
//Reset sort type and update items
CommonServices.updateSortChange($scope, sortId, isAscending);
};
$scope.sortConfig = {
fields: [
{
id: 'name',
title: $filter('translate')('NAME'),
sortType: 'text'
}
],
onSortChange: sortChange
};
//Pre load
$scope.disableRunBackup = false;
//Delete item(s)
$scope.delete = function (size) {
var modalInstance = $uibModal.open({
templateUrl: 'partials/common-html/delete-modal.html',
controller: 'ControllerDeleteModal',
size: size,
resolve: {}
});
modalInstance.result.then(function () {
BackupRestoreFactory.deleteIds($scope.itemIds, function(response) {
alertService.success($filter('translate')('ITEMS_DELETED_SUCCESSFULLY'));
//Update display table
$scope.getAllItems();
$scope.itemIds = [];
},function(error){
displayRestError.display(error);
});
}),
function () {
//console.log('Modal dismissed at: ' + new Date());
}
};
//backup now
$scope.backupNow = function(){
$scope.disableRunBackup = true;
BackupRestoreFactory.backupNow(function(){
$scope.getAllItems();
alertService.success($filter('translate')('BACKUP_COMPLETED_SUCCESSFULLY'));
$scope.disableRunBackup = false;
},function(error){
displayRestError.display(error);
$scope.disableRunBackup = false;
});
};
//Restore
$scope.restoreItemFn = function (size) {
var addModalInstance = $uibModal.open({
templateUrl: 'partials/backup/restore-confirmation-modal.html',
controller: 'BackupControllerRestore',
size: size,
resolve: {backupFile: function () {return {'name': $scope.itemIds[0]}}}
});
addModalInstance.result.then(function () {
BackupRestoreFactory.restore($scope.itemIds[0], function(response) {
alertService.success($filter('translate')('RESTORE_INITIATED_SUCCESSFULLY')+' '+response.message);
},function(error){
displayRestError.display(error);
});
}),
function () {
//console.log('Modal dismissed at: ' + new Date());
}
};
});
//restore Modal
myControllerModule.controller('BackupControllerRestore', function ($scope, $uibModalInstance, $filter, backupFile) {
$scope.header = $filter('translate')('RESTORE_CONFIRMATION_TITLE', backupFile);
$scope.rebootMsg = $filter('translate')('RESTORE_CONFIRMATION_MESSAGE', backupFile);
$scope.restore = function() {$uibModalInstance.close(); };
$scope.cancel = function () { $uibModalInstance.dismiss('cancel'); }
});
//Automatice backup settings
myControllerModule.controller('BackupControllerAutoSettings', function ($scope, BackupRestoreFactory, mchelper, alertService, displayRestError, $filter, CommonServices) {
$scope.mchelper = mchelper;
$scope.item = {};
$scope.item.enabled = false;
$scope.cs = CommonServices;
$scope.resetSettings = function(){
BackupRestoreFactory.getBackupSettings(function(response) {
$scope.item = response;
//Update dropdown
if($scope.item.interval % 86400000 == 0){
$scope.intervalLocal = $scope.item.interval / 86400000;
$scope.intervalTimeConstant = "86400000";
$scope.intervalTimeConstantString = $filter('translate')('DAYS');
}else if($scope.item.interval % 3600000 == 0){
$scope.intervalLocal = $scope.item.interval / 3600000;
$scope.intervalTimeConstant = "3600000";
$scope.intervalTimeConstantString = $filter('translate')('Hours');
}else if($scope.item.interval % 60000 == 0){
$scope.intervalLocal = $scope.item.interval / 60000;
$scope.intervalTimeConstant = "60000";
$scope.intervalTimeConstantString = $filter('translate')('Minutes');
}
},function(error){
displayRestError.display(error);
});
}
//GUI page settings
$scope.saveProgress = false;
//Load details
$scope.resetSettings();
$scope.save = function(){
if($scope.item.enabled){
//Update time
$scope.item.interval = $scope.intervalLocal * $scope.intervalTimeConstant;
}
$scope.saveProgress = true;
BackupRestoreFactory.updateBackupSettings($scope.item,function(response) {
$scope.saveProgress = false;
$scope.editEnable.backupSettings = false;
$scope.resetSettings();
},function(error){
displayRestError.display(error);
$scope.saveProgress = false;
});
}
});

View File

@@ -0,0 +1,115 @@
/*
* Copyright 2015-2018 Jeeva Kandasamy (jkandasa@gmail.com)
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
myControllerModule.controller('DashboardListController', function(alertService,
$scope, $filter, $location, $uibModal, $stateParams, $state, displayRestError, DashboardFactory, mchelper, CommonServices) {
$scope.dId;
$scope.dashboards ={};
$scope.showLoading = false;
$scope.showLoadingMain = false;
$scope.mchelper = mchelper;
$scope.updateDashboard = function(){
DashboardFactory.getAll({'lessInfo':true}, function(responseDashboards){
$scope.dashboards = $filter('orderBy')(responseDashboards, 'id', false);
if(mchelper.user.selectedDashboard === undefined){
mchelper.user.selectedDashboard = $scope.dashboards[0].id;
//Update mchelper
CommonServices.saveMchelper(mchelper);
}
$scope.dId = mchelper.user.selectedDashboard;
$scope.showLoadingMain = false;
DashboardFactory.get({'dId':$scope.dId}, function(responseDashboard){
$scope.model = responseDashboard;
$scope.model.titleTemplateUrl = "partials/dashboard/dashboard-title.html";
$scope.selectedName = $scope.model.name;
});
});
};
//Initial load
$scope.updateDashboard();
$scope.changeDashboard = function (item){
$scope.showLoading = true;
$scope.dId = item.id;
mchelper.user.selectedDashboard = item.id;
//Update mchelper
CommonServices.saveMchelper(mchelper);
DashboardFactory.get({'dId':$scope.dId}, function(response){
$scope.model = response;
$scope.model.titleTemplateUrl = "partials/dashboard/dashboard-title.html";
$scope.selectedName = $scope.model.name;
//console.log(angular.toJson($scope.model));
$scope.showLoading = false;
});
};
$scope.createNewDashboad = function(){
if($scope.dashboards.length < mchelper.cfg.dashboardLimit){
DashboardFactory.get({'getNew':true,'title':$filter('translate')('NEW_DASHBOARD')},function(response){
//Update items
$scope.updateDashboard();
});
}
};
//Delete item(s)
$scope.deleteDashboad = function (size) {
if($scope.dashboards.length == 1){
return;
}
var modalInstance = $uibModal.open({
templateUrl: 'partials/common-html/delete-modal.html',
controller: 'ControllerDeleteModal',
size: size,
resolve: {}
});
modalInstance.result.then(function () {
DashboardFactory.delete({'dId':$scope.dId}, function(response) {
alertService.success('Deleted an item successfully!');
$scope.dId = undefined;
mchelper.selectedDashboard = undefined;
//Update items
$scope.updateDashboard();
},function(error){
displayRestError.display(error);
});
}),
function () {
}
};
var eventFired = function (event, name, model) {
//$scope.eventsFired.push(event);
//console.log(angular.toJson(model));
DashboardFactory.update(model);
$scope.dashboards.forEach
angular.forEach($scope.dashboards, function(dashboard) {
if(dashboard.id === model.id){
dashboard.title = model.title;
}
});
};
$scope.$on('adfDashboardChanged', eventFired);
//$scope.$on('adfWidgetAdded', eventFired);
//$scope.$on('adfWidgetMoved', eventFired);
//$scope.$on('adfWidgetAddedToColumn', eventFired);
//$scope.$on('adfWidgetRemovedFromColumn', eventFired);
//$scope.$on('adfWidgetMovedInColumn', eventFired);
});

View File

@@ -0,0 +1,267 @@
/*
* Copyright 2015-2018 Jeeva Kandasamy (jkandasa@gmail.com)
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
myControllerModule.controller('ExternalServerController', function(alertService,
$scope, ExternalServersFactory, $stateParams, $state, $uibModal, displayRestError, CommonServices, mchelper, $filter) {
//GUI page settings
$scope.headerStringList = $filter('translate')('EXTERNAL_SERVERS_DETAIL');
$scope.noItemsSystemMsg = $filter('translate')('NO_EXTERNAL_SERVERS_SETUP');
$scope.noItemsSystemIcon = "fa fa-server";
//load empty, configuration, etc.,
$scope.mchelper = mchelper;
$scope.filteredList=[];
//data query details
$scope.currentPage = 1;
$scope.query = CommonServices.getQuery();
$scope.queryResponse = {};
//Get min number
$scope.getMin = function(item1, item2){
return CommonServices.getMin(item1, item2);
};
if($stateParams.gatewayId){
$scope.query.gatewayId = $stateParams.gatewayId;
}
//get all ExternalServers
$scope.getAllItems = function(){
ExternalServersFactory.getAll($scope.query, function(response) {
$scope.queryResponse = response;
$scope.filteredList = $scope.queryResponse.data;
$scope.filterConfig.resultsCount = $scope.queryResponse.query.filteredCount;
},function(error){
displayRestError.display(error);
});
}
//Hold all the selected item ids
$scope.itemIds = [];
$scope.selectAllItems = function(){
CommonServices.selectAllItems($scope);
};
$scope.selectItem = function(item){
CommonServices.selectItem($scope, item);
};
//On page change
$scope.pageChanged = function(newPage){
CommonServices.updatePageChange($scope, newPage);
};
//Filter change method
var filterChange = function (filters) {
//Reset filter fields and update items
CommonServices.updateFiltersChange($scope, filters);
};
$scope.filterConfig = {
fields: [
{
id: 'name',
title: $filter('translate')('NAME'),
placeholder: $filter('translate')('FILTER_BY_NAME'),
filterType: 'text'
},
{
id: 'enabled',
title: $filter('translate')('ENABLED'),
placeholder: $filter('translate')('FILTER_BY_ENABLED'),
filterType: 'select',
filterValues: ['True','False'],
},
{
id: 'type',
title: 'Type',
placeholder: $filter('translate')('FILTER_BY_TYPE'),
filterType: 'select',
filterValues: ['Grafana.org','Emoncms.org'],
}
],
resultsCount: $scope.filteredList.length,
appliedFilters: [],
onFilterChange: filterChange
};
//Sort columns
var sortChange = function (sortId, isAscending) {
//Reset sort type and update items
CommonServices.updateSortChange($scope, sortId, isAscending);
};
$scope.sortConfig = {
fields: [
{
id: 'name',
title: $filter('translate')('NAME'),
sortType: 'text'
},
{
id: 'enabled',
title: $filter('translate')('ENABLED'),
sortType: 'text'
},
{
id: 'type',
title: $filter('translate')('TYPE'),
sortType: 'text'
}
],
onSortChange: sortChange
};
//Delete items(s)
$scope.delete = function (size) {
var modalInstance = $uibModal.open({
templateUrl: 'partials/common-html/delete-modal.html',
controller: 'ControllerDeleteModal',
size: size,
resolve: {}
});
modalInstance.result.then(function () {
ExternalServersFactory.deleteIds($scope.itemIds, function(response) {
alertService.success($filter('translate')('ITEMS_DELETED_SUCCESSFULLY'));
//Update display table
$scope.getAllItems();
$scope.itemIds = [];
},function(error){
displayRestError.display(error);
});
}),
function () {
//console.log('Modal dismissed at: ' + new Date());
}
};
//Edit item
$scope.edit = function () {
if($scope.itemIds.length == 1){
$state.go("externalServersAddEdit",{'id':$scope.itemIds[0]});
}
};
//Enable items
$scope.enable = function () {
if($scope.itemIds.length > 0){
ExternalServersFactory.enableIds($scope.itemIds, function(response) {
alertService.success($filter('translate')('ITEMS_ENABLED_SUCCESSFULLY'));
//Update display table
$scope.getAllItems();
$scope.itemIds = [];
},function(error){
displayRestError.display(error);
});
}
};
//Disable items
$scope.disable = function () {
if($scope.itemIds.length > 0){
ExternalServersFactory.disableIds($scope.itemIds, function(response) {
alertService.success($filter('translate')('ITEMS_DISABLED_SUCCESSFULLY'));
//Update display table
$scope.getAllItems();
$scope.itemIds = [];
},function(error){
displayRestError.display(error);
});
}
};
});
// ExternalServers other controllers
//Add/Edit Node
myControllerModule.controller('ExternalServersControllerAddEdit', function ($scope, $stateParams, CommonServices, ExternalServersFactory, TypesFactory, mchelper, alertService, displayRestError, $filter, $state) {
//Load mchelper variables to this scope
$scope.mchelper = mchelper;
$scope.cs = CommonServices;
$scope.item = {};
if($stateParams.id){
$scope.item = ExternalServersFactory.get({"id":$stateParams.id});
}else{
$scope.item.enabled = true;
$scope.item.keyCase='DEFAULT';
}
$scope.trustHostTypes = TypesFactory.getTrustHostTypes();
$scope.types = TypesFactory.getExternalServerTypes();
//Reset common things in all server types
$scope.item.keyFormat='$nodeEui_$sensorId_$variableType';
$scope.item.trustHostType='';
$scope.item.url='';
$scope.item.username='';
$scope.item.password='';
//Update type change
$scope.updateTypeChange = function (){
if($scope.item.type === 'Sparkfun [phant.io]'){
$scope.item.url='https://data.sparkfun.com';
$scope.item.publicKey='';
$scope.item.privateKey='';
}else if($scope.item.type === 'Emoncms.org'){
$scope.item.url='https://emoncms.org';
$scope.item.writeApiKey='';
}else if($scope.item.type === 'Influxdb'){
$scope.item.database='';
}else if($scope.item.type === 'MQTT'){
$scope.item.keyFormat='$nodeEui/$sensorId/$variableType';
}else if($scope.item.type === 'WUnderground'){
$scope.item.url='https://weatherstation.wunderground.com/weatherstation/updateweatherstation.php';
}
};
//GUI page settings
$scope.showHeaderUpdate = $stateParams.id;
$scope.headerStringAdd = $filter('translate')('ADD_EXTERNAL_SERVER');
$scope.headerStringUpdate = $filter('translate')('UPDATE_EXTERNAL_SERVER');
$scope.cancelButtonState = "externalServersList"; //Cancel button state
$scope.saveProgress = false;
//$scope.isSettingChange = false;
$scope.save = function(){
$scope.saveProgress = true;
if($stateParams.id){
ExternalServersFactory.update($scope.item,function(response) {
alertService.success($filter('translate')('ITEM_UPDATED_SUCCESSFULLY'));
$state.go("externalServersList");
},function(error){
displayRestError.display(error);
$scope.saveProgress = false;
});
}else{
ExternalServersFactory.create($scope.item,function(response) {
alertService.success($filter('translate')('ITEM_CREATED_SUCCESSFULLY'));
$state.go("externalServersList");
},function(error){
displayRestError.display(error);
$scope.saveProgress = false;
});
}
}
});

View File

@@ -0,0 +1,631 @@
/*
* Copyright 2015-2018 Jeeva Kandasamy (jkandasa@gmail.com)
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* Firmwares type */
myControllerModule.controller('FirmwaresTypeController', function(
alertService, $scope, $filter, FirmwaresFactory, $state, $uibModal, displayRestError, mchelper, CommonServices, $stateParams) {
//GUI page settings
$scope.headerStringList = $filter('translate')('FIRMWARE_TYPES_DETAIL');
$scope.noItemsSystemMsg = $filter('translate')('NO_FIRMWARE_TYPES_SETUP');
$scope.noItemsSystemIcon = "fa fa-file-code-o";
//load empty, configuration, etc.,
$scope.mchelper = mchelper;
$scope.filteredList=[];
//data query details
$scope.currentPage = 1;
$scope.query = CommonServices.getQuery();
$scope.queryResponse = {};
//Get min number
$scope.getMin = function(item1, item2){
return CommonServices.getMin(item1, item2);
};
//get all items
$scope.getAllItems = function(){
FirmwaresFactory.getAllFirmwareTypes($scope.query, function(response) {
$scope.queryResponse = response;
$scope.filteredList = $scope.queryResponse.data;
$scope.filterConfig.resultsCount = $scope.queryResponse.query.filteredCount;
},function(error){
displayRestError.display(error);
});
}
//Hold all the selected item ids
$scope.itemIds = [];
$scope.selectAllItems = function(){
CommonServices.selectAllItems($scope);
};
$scope.selectItem = function(item){
CommonServices.selectItem($scope, item);
};
//On page change
$scope.pageChanged = function(newPage){
CommonServices.updatePageChange($scope, newPage);
};
//Filter change method
var filterChange = function (filters) {
//Reset filter fields and update items
CommonServices.updateFiltersChange($scope, filters);
};
$scope.filterConfig = {
fields: [
{
id: 'name',
title: $filter('translate')('NAME'),
placeholder: $filter('translate')('FILTER_BY_NAME'),
filterType: 'text'
},{
id: 'id',
title: $filter('translate')('TYPE_ID'),
placeholder: $filter('translate')('FILTER_BY_TYPE_ID'),
filterType: 'text'
}
],
resultsCount: $scope.filteredList.length,
appliedFilters: [],
onFilterChange: filterChange
};
//Sort columns
var sortChange = function (sortId, isAscending) {
//Reset sort type and update items
CommonServices.updateSortChange($scope, sortId, isAscending);
};
$scope.sortConfig = {
fields: [
{
id: 'name',
title: $filter('translate')('NAME'),
sortType: 'text'
},{
id: 'id',
title: $filter('translate')('TYPE_ID'),
sortType: 'text'
}
],
onSortChange: sortChange
};
//Edit item
$scope.edit = function () {
if($scope.itemIds.length == 1){
$state.go("firmwaresTypeAddEdit", {'id': $scope.itemIds[0]});
}
};
//Delete item(s)
$scope.delete = function (size) {
var modalInstance = $uibModal.open({
templateUrl: 'partials/common-html/delete-modal.html',
controller: 'ControllerDeleteModal',
size: size,
resolve: {}
});
modalInstance.result.then(function () {
FirmwaresFactory.deleteFirmwareTypes($scope.itemIds, function(response) {
alertService.success($filter('translate')('ITEMS_DELETED_SUCCESSFULLY'));
//Update display table
$scope.getAllItems();
$scope.itemIds = [];
},function(error){
displayRestError.display(error);
});
}),
function () {
//console.log('Modal dismissed at: ' + new Date());
}
};
});
//add edit item
myControllerModule.controller('FirmwaresTypeControllerAddEdit', function ($scope, CommonServices, alertService, FirmwaresFactory, mchelper, $stateParams, $filter, $state) {
//GUI page settings
$scope.showHeaderUpdate = $stateParams.id;
$scope.headerStringAdd = $filter('translate')('ADD_FIRMWARE_TYPE');
$scope.headerStringUpdate = $filter('translate')('UPDATE_FIRMWARE_TYPE');
$scope.cancelButtonState = "firmwaresTypeList"; //Cancel button state
$scope.saveProgress = false;
//$scope.isSettingChange = false;
$scope.cs = CommonServices;
$scope.firmwareType = {};
$scope.ftypeId = $stateParams.id;
if($stateParams.id){
FirmwaresFactory.getFirmwareType({"refId":$stateParams.id},function(response) {
$scope.firmwareType = response;
$scope.firmwareType.newId = $scope.firmwareType.id;
},function(error){
displayRestError.display(error);
});
}
//Save data
$scope.save = function(){
$scope.saveProgress = true;
if($scope.firmwareType.id === undefined){
$scope.firmwareType.id = $scope.firmwareType.newId;
}
if($stateParams.id){
FirmwaresFactory.updateFirmwareType($scope.firmwareType,function(response) {
alertService.success($filter('translate')('ITEM_UPDATED_SUCCESSFULLY'));
$state.go("firmwaresTypeList");
},function(error){
displayRestError.display(error);
$scope.saveProgress = false;
});
}else{
FirmwaresFactory.createFirmwareType($scope.firmwareType,function(response) {
alertService.success($filter('translate')('ITEM_CREATED_SUCCESSFULLY'));
$state.go("firmwaresTypeList");
},function(error){
displayRestError.display(error);
$scope.saveProgress = false;
});
}
}
});
//type over
/* Firmwares version */
myControllerModule.controller('FirmwaresVersionController', function(
alertService, $scope, $filter, FirmwaresFactory, $state, $uibModal, displayRestError, mchelper, CommonServices, $stateParams) {
//GUI page settings
$scope.headerStringList = $filter('translate')('FIRMWARE_VERSIONS_DETAIL');
$scope.noItemsSystemMsg = $filter('translate')('NO_FIRMWARE_VERSIONS_SETUP');
$scope.noItemsSystemIcon = "fa fa-file-code-o";
//load empty, configuration, etc.,
$scope.mchelper = mchelper;
$scope.filteredList=[];
//data query details
$scope.currentPage = 1;
$scope.query = CommonServices.getQuery();
$scope.queryResponse = {};
//Get min number
$scope.getMin = function(item1, item2){
return CommonServices.getMin(item1, item2);
};
//get all items
$scope.getAllItems = function(){
FirmwaresFactory.getAllFirmwareVersions($scope.query, function(response) {
$scope.queryResponse = response;
$scope.filteredList = $scope.queryResponse.data;
$scope.filterConfig.resultsCount = $scope.queryResponse.query.filteredCount;
},function(error){
displayRestError.display(error);
});
}
//Hold all the selected item ids
$scope.itemIds = [];
$scope.selectAllItems = function(){
CommonServices.selectAllItems($scope);
};
$scope.selectItem = function(item){
CommonServices.selectItem($scope, item);
};
//On page change
$scope.pageChanged = function(newPage){
CommonServices.updatePageChange($scope, newPage);
};
//Filter change method
var filterChange = function (filters) {
//Reset filter fields and update items
CommonServices.updateFiltersChange($scope, filters);
};
$scope.filterConfig = {
fields: [
{
id: 'version',
title: $filter('translate')('VERSION'),
placeholder: $filter('translate')('FILTER_BY_VERSION'),
filterType: 'text'
},{
id: 'id',
title: $filter('translate')('VERSION_ID'),
placeholder: $filter('translate')('FILTER_BY_VERSION_ID'),
filterType: 'text'
}
],
resultsCount: $scope.filteredList.length,
appliedFilters: [],
onFilterChange: filterChange
};
//Sort columns
var sortChange = function (sortId, isAscending) {
//Reset sort type and update items
CommonServices.updateSortChange($scope, sortId, isAscending);
};
$scope.sortConfig = {
fields: [
{
id: 'version',
title: $filter('translate')('VERSION'),
sortType: 'text'
},{
id: 'id',
title: $filter('translate')('VERSION_ID'),
sortType: 'text'
}
],
onSortChange: sortChange
};
//Edit item
$scope.edit = function () {
if($scope.itemIds.length == 1){
$state.go("firmwaresVersionAddEdit", {'id':$scope.itemIds[0]});
}
};
//Delete item(s)
$scope.delete = function (size) {
var modalInstance = $uibModal.open({
templateUrl: 'partials/common-html/delete-modal.html',
controller: 'ControllerDeleteModal',
size: size,
resolve: {}
});
modalInstance.result.then(function () {
FirmwaresFactory.deleteFirmwareVersions($scope.itemIds, function(response) {
alertService.success($filter('translate')('ITEMS_DELETED_SUCCESSFULLY'));
//Update display table
$scope.getAllItems();
$scope.itemIds = [];
},function(error){
displayRestError.display(error);
});
}),
function () {
//console.log('Modal dismissed at: ' + new Date());
}
};
});
//add edit item
myControllerModule.controller('FirmwaresVersionControllerAddEdit', function ($scope, CommonServices, alertService, FirmwaresFactory, mchelper, $stateParams, $filter, $state, CommonServices) {
//GUI page settings
$scope.showHeaderUpdate = $stateParams.id;
$scope.headerStringAdd = $filter('translate')('ADD_FIRMWARE_VERSION');
$scope.headerStringUpdate = $filter('translate')('UPDATE_FIRMWARE_VERSION');
$scope.cancelButtonState = "firmwaresVersionList"; //Cancel button state
$scope.saveProgress = false;
//$scope.isSettingChange = false;
$scope.item = {};
$scope.itemId = $stateParams.id;
$scope.cs = CommonServices;
if($stateParams.id){
FirmwaresFactory.getFirmwareVersion({"refId":$stateParams.id},function(response) {
$scope.item = response;
$scope.item.newId = $scope.item.id;
},function(error){
displayRestError.display(error);
});
}
//Save data
$scope.save = function(){
$scope.saveProgress = true;
if($scope.item.id === undefined){
$scope.item.id = $scope.item.newId;
}
if($stateParams.id){
FirmwaresFactory.updateFirmwareVersion($scope.item,function(response) {
alertService.success($filter('translate')('ITEM_UPDATED_SUCCESSFULLY'));
$state.go("firmwaresVersionList");
},function(error){
displayRestError.display(error);
$scope.saveProgress = false;
});
}else{
FirmwaresFactory.createFirmwareVersion($scope.item,function(response) {
alertService.success($filter('translate')('ITEM_CREATED_SUCCESSFULLY'));
$state.go("firmwaresVersionList");
},function(error){
displayRestError.display(error);
$scope.saveProgress = false;
});
}
}
});
//Version over
/* Firmware controller */
myControllerModule.controller('FirmwaresController', function(
alertService, $scope, $filter, FirmwaresFactory, $state, $uibModal, displayRestError, mchelper, CommonServices, $stateParams) {
//GUI page settings
$scope.headerStringList = $filter('translate')('FIRMWARES_DETAIL');
$scope.noItemsSystemMsg = $filter('translate')('NO_FIRMWARES_SETUP');
$scope.noItemsSystemIcon = "fa fa-file-code-o";
//load empty, configuration, etc.,
$scope.mchelper = mchelper;
$scope.filteredList=[];
//data query details
$scope.currentPage = 1;
$scope.query = CommonServices.getQuery();
$scope.queryResponse = {};
//Get min number
$scope.getMin = function(item1, item2){
return CommonServices.getMin(item1, item2);
};
if($stateParams.sensorId){
$scope.sensorId = $stateParams.sensorId;
}
//get all items
$scope.getAllItems = function(){
FirmwaresFactory.getAllFirmwares($scope.query, function(response) {
$scope.queryResponse = response;
$scope.filteredList = $scope.queryResponse.data;
$scope.filterConfig.resultsCount = $scope.queryResponse.query.filteredCount;
},function(error){
displayRestError.display(error);
});
}
//Hold all the selected item ids
$scope.itemIds = [];
$scope.selectAllItems = function(){
CommonServices.selectAllItems($scope);
};
$scope.selectItem = function(item){
CommonServices.selectItem($scope, item);
};
//On page change
$scope.pageChanged = function(newPage){
CommonServices.updatePageChange($scope, newPage);
};
//Filter change method
var filterChange = function (filters) {
//Reset filter fields and update items
CommonServices.updateFiltersChange($scope, filters);
};
$scope.filterConfig = {
fields: [
{
id: 'typeId',
title: $filter('translate')('TYPE_ID'),
placeholder: $filter('translate')('FILTER_BY_TYPE_ID'),
filterType: 'text'
},{
id: 'versionId',
title: $filter('translate')('VERSION_ID'),
placeholder: $filter('translate')('FILTER_BY_VERSION_ID'),
filterType: 'text'
},{
id: 'blocks',
title: $filter('translate')('BLOCKS'),
placeholder: $filter('translate')('FILTER_BY_BLOCKS'),
filterType: 'text'
}
],
resultsCount: $scope.filteredList.length,
appliedFilters: [],
onFilterChange: filterChange
};
//Sort columns
var sortChange = function (sortId, isAscending) {
//Reset sort type and update items
CommonServices.updateSortChange($scope, sortId, isAscending);
};
$scope.sortConfig = {
fields: [
{
id: 'typeId',
title: $filter('translate')('TYPE_ID'),
sortType: 'text'
},{
id: 'versionId',
title: $filter('translate')('VERSION_ID'),
sortType: 'text'
},{
id: 'blocks',
title: $filter('translate')('BLOCKS'),
sortType: 'text'
},{
id: 'timestamp',
title: $filter('translate')('UPLOADED_ON'),
sortType: 'text'
},{
id: 'crc',
title: $filter('translate')('CRC'),
sortType: 'text'
},
],
onSortChange: sortChange
};
//Edit item
$scope.edit = function () {
if($scope.itemIds.length == 1){
$state.go("firmwaresAddEdit", {'id':$scope.itemIds[0]});
}
};
//Delete item(s)
$scope.delete = function (size) {
var modalInstance = $uibModal.open({
templateUrl: 'partials/common-html/delete-modal.html',
controller: 'ControllerDeleteModal',
size: size,
resolve: {}
});
modalInstance.result.then(function () {
FirmwaresFactory.deleteFirmwares($scope.itemIds, function(response) {
alertService.success($filter('translate')('ITEMS_DELETED_SUCCESSFULLY'));
//Update display table
$scope.getAllItems();
$scope.itemIds = [];
},function(error){
displayRestError.display(error);
});
}),
function () {
//console.log('Modal dismissed at: ' + new Date());
}
};
});
//add edit item
myControllerModule.controller('FirmwaresControllerAddEdit', function ($scope, CommonServices, displayRestError, alertService, FirmwaresFactory, mchelper, $stateParams, $state, $filter, TypesFactory) {
$scope.item = {};
//GUI page settings
$scope.showHeaderUpdate = $stateParams.id;
$scope.headerStringAdd = $filter('translate')('ADD_FIRMWARE');
$scope.headerStringUpdate = $filter('translate')('UPDATE_FIRMWARE');
$scope.cancelButtonState = "firmwaresList"; //Cancel button state
$scope.saveProgress = false;
//$scope.isSettingChange = false;
if($stateParams.id){
FirmwaresFactory.getFirmware({"refId":$stateParams.id},function(response) {
$scope.item = response;
},function(error){
displayRestError.display(error);
});
}
//Pre load
$scope.firmwareTypes = TypesFactory.getFirmwareTypes();
$scope.firmwareVersions = TypesFactory.getFirmwareVersions();
//Read File and put it in textarea
$scope.displayFileContents = function(contents, fileExtension) {
if(fileExtension === 'bin'){
$scope.item.fileBytes = Array.from(new Uint8Array(contents));
$scope.item.fileType = 'Bin';
}else if(fileExtension === 'hex'){
$scope.item.fileType = 'Hex';
$scope.item.fileString = contents;
}else{
$scope.item.fileType = 'Hex';
$scope.item.fileString = contents;
}
};
//Save data
$scope.save = function(){
$scope.saveProgress = true;
if($stateParams.id){
FirmwaresFactory.updateFirmware($scope.item,function(response) {
alertService.success($filter('translate')('ITEM_UPDATED_SUCCESSFULLY'));
$state.go("firmwaresList");
},function(error){
displayRestError.display(error);
$scope.saveProgress = false;
});
}else{
FirmwaresFactory.createFirmware($scope.item,function(response) {
alertService.success($filter('translate')('ITEM_CREATED_SUCCESSFULLY'));
$state.go("firmwaresList");
},function(error){
$scope.saveProgress = false;
displayRestError.display(error);
});
}
}
}).directive('onReadFile', function ($parse) {
return {
restrict: 'A',
scope: false,
link: function(scope, element, attrs) {
element.bind('change', function(e) {
var onFileReadFn = $parse(attrs.onReadFile);
var reader = new FileReader();
var fileExtension = element[0].files[0].name.split('.').pop().toLowerCase();
reader.onload = function() {
var fileContents = reader.result;
// invoke parsed function on scope
// special syntax for passing in data
// to named parameters
// in the parsed function
// we are providing a value for the property 'contents'
// in the scope we pass in to the function
scope.$apply(function() {
onFileReadFn(scope, {
'contents' : fileContents,
'fileExtension': fileExtension
});
});
};
if(fileExtension === 'bin'){
reader.readAsArrayBuffer(element[0].files[0]);
}else if(fileExtension === 'hex'){
reader.readAsText(element[0].files[0]);
}else{
reader.readAsText(element[0].files[0]);
}
});
}
};
});

View File

@@ -0,0 +1,240 @@
/*
* Copyright 2015-2018 Jeeva Kandasamy (jkandasa@gmail.com)
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
myControllerModule.controller('ForwardPayloadController', function(alertService,
$scope, $filter, ForwardPayloadFactory, $state, $uibModal, displayRestError, mchelper, CommonServices, $stateParams) {
//GUI page settings
$scope.headerStringList = $filter('translate')('FORWARD_PAYLOADS_DETAIL');
$scope.noItemsSystemMsg = $filter('translate')('NO_FORWARD_PAYLOADS_SETUP');
$scope.noItemsSystemIcon = "fa fa-forward";
//load empty, configuration, etc.,
$scope.mchelper = mchelper;
$scope.filteredList=[];
//data query details
$scope.currentPage = 1;
$scope.query = CommonServices.getQuery();
$scope.queryResponse = {};
//Get min number
$scope.getMin = function(item1, item2){
return CommonServices.getMin(item1, item2);
};
if($stateParams.sensorId){
$scope.query.sensorId = $stateParams.sensorId;
}
//get all items
$scope.getAllItems = function(){
ForwardPayloadFactory.getAll($scope.query, function(response) {
$scope.queryResponse = response;
$scope.filteredList = $scope.queryResponse.data;
$scope.filterConfig.resultsCount = $scope.queryResponse.query.filteredCount;
},function(error){
displayRestError.display(error);
});
}
//Hold all the selected item ids
$scope.itemIds = [];
$scope.selectAllItems = function(){
CommonServices.selectAllItems($scope);
};
$scope.selectItem = function(item){
CommonServices.selectItem($scope, item);
};
//On page change
$scope.pageChanged = function(newPage){
CommonServices.updatePageChange($scope, newPage);
};
//Filter change method
var filterChange = function (filters) {
//Reset filter fields and update items
CommonServices.updateFiltersChange($scope, filters);
};
$scope.filterConfig = {
fields: [
{
id: 'sourceId',
title: $filter('translate')('SOURCE_ID'),
placeholder: $filter('translate')('FILTER_BY_SOURCE_ID'),
filterType: 'text'
},
{
id: 'destinationId',
title: $filter('translate')('DESTINATION_ID'),
placeholder: $filter('translate')('FILTER_BY_DESTINATION_ID'),
filterType: 'text'
}
],
resultsCount: $scope.filteredList.length,
appliedFilters: [],
onFilterChange: filterChange
};
//Sort columns
var sortChange = function (sortId, isAscending) {
//Reset sort type and update items
CommonServices.updateSortChange($scope, sortId, isAscending);
};
$scope.sortConfig = {
fields: [
{
id: 'enabled',
title: $filter('translate')('ENABLED'),
sortType: 'text'
},{
id: 'sourceId',
title: $filter('translate')('SOURCE_ID'),
sortType: 'text'
},{
id: 'destinationId',
title: $filter('translate')('DESTINATION_ID'),
sortType: 'text'
}
],
onSortChange: sortChange,
isAscending: false,
};
//Edit item
$scope.edit = function () {
if($scope.itemIds.length == 1){
$state.go("forwardPayloadAddEdit", {'id':$scope.itemIds[0]});
}
};
//Delete item(s)
$scope.delete = function (size) {
var modalInstance = $uibModal.open({
templateUrl: 'partials/common-html/delete-modal.html',
controller: 'ControllerDeleteModal',
size: size,
resolve: {}
});
modalInstance.result.then(function () {
ForwardPayloadFactory.deleteIds($scope.itemIds, function(response) {
alertService.success('ITEMS_DELETED_SUCCESSFULLY');
//Update display table
$scope.getAllItems();
$scope.itemIds = [];
},function(error){
displayRestError.display(error);
});
}),
function () {
//console.log('Modal dismissed at: ' + new Date());
}
};
//Enable items
$scope.enable = function () {
if($scope.itemIds.length > 0){
ForwardPayloadFactory.enableIds($scope.itemIds, function(response) {
alertService.success('ITEMS_ENABLED_SUCCESSFULLY');
//Update display table
$scope.getAllItems();
$scope.itemIds = [];
},function(error){
displayRestError.display(error);
});
}
};
//Disable items
$scope.disable = function () {
if($scope.itemIds.length > 0){
ForwardPayloadFactory.disableIds($scope.itemIds, function(response) {
alertService.success('ITEMS_DISABLED_SUCCESSFULLY');
//Update display table
$scope.getAllItems();
$scope.itemIds = [];
},function(error){
displayRestError.display(error);
});
}
};
});
//add edit item
myControllerModule.controller('ForwardPayloadControllerAddEdit', function ($scope, CommonServices, alertService, ForwardPayloadFactory, mchelper, $stateParams, $state, $filter, displayRestError) {
$scope.fpayload = {};
$scope.fpayload.enabled=true;
$scope.fpayload.source={};
$scope.fpayload.destination={};
if($stateParams.id){
ForwardPayloadFactory.get({"id":$stateParams.id},function(response) {
$scope.fpayload = response;
},function(error){
displayRestError.display(error);
});
}
//Get resources
$scope.getResources = function(resourceType){
return CommonServices.getResources(resourceType);
}
//pre load
$scope.resources = $scope.getResources("Sensor variable");
//GUI page settings
$scope.showHeaderUpdate = $stateParams.id;
$scope.headerStringAdd = $filter('translate')('ADD_FORWARD_PAYLOAD_ENTRY');
$scope.headerStringUpdate = $filter('translate')('UPDATE_FORWARD_PAYLOAD_ENTRY');
$scope.cancelButtonState = "forwardPayloadList"; //Cancel button state
$scope.saveProgress = false;
//$scope.isSettingChange = false;
//Save data
$scope.save = function(){
$scope.saveProgress = true;
if($stateParams.id){
ForwardPayloadFactory.update($scope.fpayload,function(response) {
alertService.success($filter('translate')('ITEM_UPDATED_SUCCESSFULLY'));
$state.go("forwardPayloadList");
},function(error){
displayRestError.display(error);
$scope.saveProgress = false;
});
}else{
ForwardPayloadFactory.create($scope.fpayload,function(response) {
alertService.success($filter('translate')('ITEM_CREATED_SUCCESSFULLY'));
$state.go("forwardPayloadList");
},function(error){
displayRestError.display(error);
$scope.saveProgress = false;
});
}
}
});

353
www/controllers/gateways.js Normal file
View File

@@ -0,0 +1,353 @@
/*
* Copyright 2015-2018 Jeeva Kandasamy (jkandasa@gmail.com)
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
myControllerModule.controller('GatewaysController', function(alertService,
$scope, $filter, GatewaysFactory, $state, $uibModal, displayRestError, mchelper, CommonServices) {
//GUI page settings
$scope.headerStringList = $filter('translate')('GATEWAYS_DETAIL');
$scope.noItemsSystemMsg = $filter('translate')('NO_GATEWAYS_SETUP');
$scope.noItemsSystemIcon = "fa fa-plug";
//load empty, configuration, etc.,
$scope.mchelper = mchelper;
$scope.filteredList=[];
//data query details
$scope.currentPage = 1;
$scope.query = CommonServices.getQuery();
$scope.queryResponse = {};
//Get min number
$scope.getMin = function(item1, item2){
return CommonServices.getMin(item1, item2);
};
//get all Items
$scope.getAllItems = function(){
GatewaysFactory.getAll($scope.query, function(response) {
$scope.queryResponse = response;
$scope.filteredList = $scope.queryResponse.data;
$scope.filterConfig.resultsCount = $scope.queryResponse.query.filteredCount;
},function(error){
displayRestError.display(error);
});
}
//Hold all the selected item ids
$scope.itemIds = [];
$scope.selectAllItems = function(){
CommonServices.selectAllItems($scope);
};
$scope.selectItem = function(item){
CommonServices.selectItem($scope, item);
};
//On page change
$scope.pageChanged = function(newPage){
CommonServices.updatePageChange($scope, newPage);
};
//Filter change method
var filterChange = function (filters) {
//Reset filter fields and update items
CommonServices.updateFiltersChange($scope, filters);
};
$scope.filterConfig = {
fields: [
{
id: 'name',
title: $filter('translate')('NAME'),
placeholder: $filter('translate')('FILTER_BY_NAME'),
filterType: 'text',
},
{
id: 'type',
title: $filter('translate')('TYPE'),
placeholder: $filter('translate')('FILTER_BY_TYPE'),
filterType: 'select',
filterValues: ['Serial','Ethernet','MQTT'],
},
{
id: 'networkType',
title: $filter('translate')('NETWORK_TYPE'),
placeholder: $filter('translate')('FILTER_BY_NETWORK_TYPE'),
filterType: 'select',
filterValues: ['MySensors'],
},
{
id: 'statusMessage',
title: $filter('translate')('STATUS_MESSAGE'),
placeholder: $filter('translate')('FILTER_BY_STATUS_MESSAGE'),
filterType: 'text',
}
],
resultsCount: $scope.filteredList.length,
appliedFilters: [],
onFilterChange: filterChange
};
//Sort columns
var sortChange = function (sortId, isAscending) {
//Reset sort type and update items
CommonServices.updateSortChange($scope, sortId, isAscending);
};
$scope.sortConfig = {
fields: [
{
id: 'name',
title: $filter('translate')('NAME'),
sortType: 'text',
},
{
id: 'state',
title: $filter('translate')('STATUS'),
sortType: 'text',
},
{
id: 'type',
title: $filter('translate')('TYPE'),
sortType: 'text',
},
{
id: 'networkType',
title: $filter('translate')('NETWORK_TYPE'),
sortType: 'text',
},
{
id: 'statusMessage',
title: $filter('translate')('STATUS_MESSAGE'),
sortType: 'text',
},
{
id: 'statusSince',
title: $filter('translate')('STATUS_SINCE'),
sortType: 'text',
}
],
onSortChange: sortChange
};
//Edit item
$scope.edit = function () {
if($scope.itemIds.length == 1){
$state.go("gatewaysAddEdit", {'id':$scope.itemIds[0]});
}
};
//Enable items
$scope.enable = function () {
if($scope.itemIds.length > 0){
GatewaysFactory.enable($scope.itemIds, function(response) {
alertService.success($filter('translate')('ITEMS_ENABLED_SUCCESSFULLY'));
//Update display table
$scope.getAllItems();
$scope.itemIds = [];
},function(error){
displayRestError.display(error);
});
}
};
//Disable items
$scope.disable = function () {
if($scope.itemIds.length > 0){
GatewaysFactory.disable($scope.itemIds, function(response) {
alertService.success($filter('translate')('ITEMS_DISABLED_SUCCESSFULLY'));
//Update display table
$scope.getAllItems();
$scope.itemIds = [];
},function(error){
displayRestError.display(error);
});
}
};
//Discover items
$scope.discover = function () {
if($scope.itemIds.length > 0){
GatewaysFactory.discover($scope.itemIds, function(response) {
alertService.success($filter('translate')('DISCOVER_INITIATED_SUCCESSFULLY'));
$scope.itemIds = [];
},function(error){
displayRestError.display(error);
});
}
};
//Update noe informations
$scope.refreshNodesInfo = function () {
if($scope.itemIds.length > 0){
GatewaysFactory.executeNodeInfoUpdate($scope.itemIds, function(response) {
alertService.success($filter('translate')('REFRESH_NODES_INFO_INITIATED_SUCCESSFULLY'));
$scope.itemIds = [];
},function(error){
displayRestError.display(error);
});
}
};
//Reload items
$scope.reload = function () {
if($scope.itemIds.length > 0){
GatewaysFactory.reload($scope.itemIds, function(response) {
alertService.success($filter('translate')('RELOAD_INITIATED_SUCCESSFULLY'));
$scope.itemIds = [];
//Update display table
$scope.getAllItems();
},function(error){
displayRestError.display(error);
});
}
};
//Delete item(s)
$scope.delete = function (size) {
var modalInstance = $uibModal.open({
templateUrl: 'partials/common-html/delete-modal.html',
controller: 'ControllerDeleteModal',
size: size,
resolve: {}
});
modalInstance.result.then(function () {
GatewaysFactory.delete($scope.itemIds, function(response) {
alertService.success($filter('translate')('ITEMS_DELETED_SUCCESSFULLY'));
//Update display table
$scope.getAllItems();
$scope.itemIds = [];
},function(error){
displayRestError.display(error);
});
}),
function () {
//console.log('Modal dismissed at: ' + new Date());
}
};
});
myControllerModule.controller('GatewaysControllerAddEdit', function ($scope, TypesFactory, GatewaysFactory, $stateParams, mchelper, $state, alertService, $filter, CommonServices, displayRestError) {
$scope.gateway = {};
$scope.gateway.enabled = true;
$scope.gateway.txDelay = 0;
$scope.gateway.reconnectDelay = 120;
$scope.gatewayTypes = {};
$scope.trustHostTypes = TypesFactory.getTrustHostTypes();
$scope.gatewayNetworkTypes = TypesFactory.getGatewayNetworkTypes();
$scope.cs = CommonServices;
if($stateParams.id){
GatewaysFactory.get({"gatewayId":$stateParams.id}, function(response){
$scope.gateway = response;
$scope.updateGatewayTypes();
},function(error){
displayRestError.display(error);
});
}
$scope.gatewaySerialDrivers = TypesFactory.getGatewaySerialDrivers();
$scope.updateTypeChange = function (){
if($scope.gateway.type === 'Serial'){
$scope.gateway.driver='';
$scope.gateway.portName='';
$scope.gateway.baudRate='';
}else if($scope.gateway.type === 'Ethernet'){
$scope.gateway.host='';
$scope.gateway.port='';
$scope.gateway.aliveFrequency='';
}else if($scope.gateway.type === 'MQTT'){
$scope.gateway.brokerHost='';
$scope.gateway.clientId='';
$scope.gateway.topicsPublish='';
$scope.gateway.topicsSubscribe='';
$scope.gateway.username='';
$scope.gateway.password='';
}else if($scope.gateway.type === 'Sparkfun [phant.io]'){
$scope.gateway.url='https://data.sparkfun.com';
$scope.gateway.publicKey='';
$scope.gateway.privateKey='';
$scope.gateway.pollFrequency='1';
$scope.gateway.recordsLimit='10';
$scope.gateway.trustHostType='';
}else if($scope.gateway.type === 'Hue bridge'){
$scope.gateway.url='';
$scope.gateway.authorizedUser='';
$scope.gateway.pollFrequency='5';
}else if($scope.gateway.type === 'Weather Underground'){
$scope.gateway.apiKey='';
$scope.gateway.location='autoip';
$scope.gateway.pollFrequency='15';
}
};
//GUI page settings
$scope.showHeaderUpdate = $stateParams.id;
$scope.headerStringAdd = $filter('translate')('ADD_GATEWAY');
$scope.headerStringUpdate = $filter('translate')('UPDATE_GATEWAY');
$scope.cancelButtonState = "gatewaysList"; //Cancel button state
$scope.saveProgress = false;
//$scope.isSettingChange = false;
// Update gateway types
$scope.updateGatewayTypes = function(){
$scope.gatewayTypes = TypesFactory.getGatewayTypes({"networkType": $scope.gateway.networkType});
}
$scope.save = function(){
$scope.saveProgress = true;
if($stateParams.id){
GatewaysFactory.update($scope.gateway,function(response) {
alertService.success($filter('translate')('ITEM_UPDATED_SUCCESSFULLY'));
$state.go("gatewaysList");
},function(error){
displayRestError.display(error);
$scope.saveProgress = false;
});
}else{
GatewaysFactory.create($scope.gateway,function(response) {
alertService.success($filter('translate')('ITEM_CREATED_SUCCESSFULLY'));
$state.go("gatewaysList");
},function(error){
displayRestError.display(error);
$scope.saveProgress = false;
});
}
}
});
//item Detail
myControllerModule.controller('GatewaysControllerDetail', function ($scope, $stateParams, mchelper, GatewaysFactory, MetricsFactory, $filter) {
//Load mchelper variables to this scope
$scope.mchelper = mchelper;
$scope.node = {};
$scope.headerStringList = $filter('translate')('GATEWAY_DETAILS');
$scope.item = GatewaysFactory.get({"gatewayId":$stateParams.id});
$scope.statistics = GatewaysFactory.statistics({"gatewayId":$stateParams.id});
$scope.resourceCount = MetricsFactory.getResourceCount({"resourceType":"Gateway", "resourceId":$stateParams.id});
});

440
www/controllers/nodes.js Normal file
View File

@@ -0,0 +1,440 @@
/*
* Copyright 2015-2018 Jeeva Kandasamy (jkandasa@gmail.com)
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
myControllerModule.controller('NodesController', function(alertService,
$scope, NodesFactory, $stateParams, $state, $uibModal, displayRestError, CommonServices, mchelper, $filter, $interval) {
//GUI page settings
$scope.headerStringList = $filter('translate')('NODES_DETAIL');
$scope.noItemsSystemMsg = $filter('translate')('NO_NODES_SETUP');
$scope.noItemsSystemIcon = "fa fa-sitemap";
//load empty, configuration, etc.,
$scope.mchelper = mchelper;
$scope.filteredList=[];
//data query details
$scope.currentPage = 1;
$scope.query = CommonServices.getQuery();
$scope.queryResponse = {};
//Get min number
$scope.getMin = function(item1, item2){
return CommonServices.getMin(item1, item2);
};
if($stateParams.gatewayId){
$scope.query.gatewayId = $stateParams.gatewayId;
}
$scope.isRunning = false;
//get all Items
$scope.getAllItems = function(){
if($scope.isRunning){
return;
}
$scope.isRunning = true;
NodesFactory.getAll($scope.query, function(response) {
$scope.queryResponse = response;
$scope.filteredList = $scope.queryResponse.data;
$scope.filterConfig.resultsCount = $scope.queryResponse.query.filteredCount;
$scope.isRunning = false;
},function(error){
displayRestError.display(error);
$scope.isRunning = false;
});
}
//Hold all the selected item ids
$scope.itemIds = [];
$scope.selectAllItems = function(){
CommonServices.selectAllItems($scope);
};
$scope.selectItem = function(item){
CommonServices.selectItem($scope, item);
};
//On page change
$scope.pageChanged = function(newPage){
CommonServices.updatePageChange($scope, newPage);
};
//Filter change method
var filterChange = function (filters) {
//Reset filter fields and update items
CommonServices.updateFiltersChange($scope, filters);
};
$scope.filterConfig = {
fields: [
{
id: 'name',
title: $filter('translate')('NAME'),
placeholder: $filter('translate')('FILTER_BY_NAME'),
filterType: 'text'
},
{
id: 'state',
title: $filter('translate')('STATUS'),
placeholder: $filter('translate')('FILTER_BY_STATUS'),
filterType: 'select',
filterValues: ['Up','Down','Unavailable'],
},
{
id: 'type',
title: 'Type',
placeholder: $filter('translate')('FILTER_BY_TYPE'),
filterType: 'select',
filterValues: ['Node','Repeater node'],
},
{
id: 'eui',
title: 'EUI',
placeholder: $filter('translate')('FILTER_BY_EUI'),
filterType: 'text',
},
{
id: 'version',
title: 'Version',
placeholder: $filter('translate')('FILTER_BY_VERSION'),
filterType: 'text',
},
{
id: 'libVersion',
title: 'Library Version',
placeholder: $filter('translate')('FILTER_BY_LIBRARY_VERSION'),
filterType: 'text',
}
],
resultsCount: $scope.filteredList.length,
appliedFilters: [],
onFilterChange: filterChange
};
//Sort columns
var sortChange = function (sortId, isAscending) {
//Reset sort type and update items
CommonServices.updateSortChange($scope, sortId, isAscending);
};
$scope.sortConfig = {
fields: [
{
id: 'name',
title: $filter('translate')('NAME'),
sortType: 'text'
},
{
id: 'state',
title: $filter('translate')('STATUS'),
sortType: 'text'
},
{
id: 'eui',
title: $filter('translate')('EUI'),
sortType: 'text'
},
{
id: 'type',
title: $filter('translate')('TYPE'),
sortType: 'text'
},
{
id: 'version',
title: $filter('translate')('VERSION'),
sortType: 'text'
},
{
id: 'libVersion',
title: $filter('translate')('LIBRARY_VERSION'),
sortType: 'text'
}
],
onSortChange: sortChange
};
//Delete Node(s)
$scope.delete = function (size) {
var modalInstance = $uibModal.open({
templateUrl: 'partials/common-html/delete-modal.html',
controller: 'ControllerDeleteModal',
size: size,
resolve: {}
});
modalInstance.result.then(function () {
NodesFactory.deleteIds($scope.itemIds, function(response) {
alertService.success($filter('translate')('ITEMS_DELETED_SUCCESSFULLY'));
//Update display table
$scope.getAllItems();
$scope.itemIds = [];
},function(error){
displayRestError.display(error);
});
}),
function () {
//console.log('Modal dismissed at: ' + new Date());
}
};
//Edit item
$scope.edit = function () {
if($scope.itemIds.length == 1){
$state.go("nodesAddEdit",{'id':$scope.itemIds[0]});
}
};
//Upload Firmware
$scope.uploadFirmware = function (size) {
if($scope.itemIds.length > 0){
NodesFactory.uploadFirmware($scope.itemIds,function(response) {
alertService.success($filter('translate')('FIRMWARE_UPLOAD_INITIATED'));
},function(error){
displayRestError.display(error);
});
}
};
//Refresh nodes information
$scope.refreshNodesInfo = function (size) {
if($scope.itemIds.length > 0){
NodesFactory.executeNodeInfoUpdate($scope.itemIds,function(response) {
alertService.success($filter('translate')('REFRESH_NODES_INFO_INITIATED_SUCCESSFULLY'));
},function(error){
displayRestError.display(error);
});
}
};
//Reboot a Node
$scope.reboot = function (size) {
var addModalInstance = $uibModal.open({
templateUrl: 'partials/nodes/node-reboot-modal.html',
controller: 'NodesControllerReboot',
size: size,
resolve: {}
});
addModalInstance.result.then(function () {
NodesFactory.reboot($scope.itemIds, function(response) {
alertService.success($filter('translate')('REBOOT_INITIATED'));
},function(error){
displayRestError.display(error);
});
}),
function () {
//console.log('Modal dismissed at: ' + new Date());
}
};
//Erase Configuration of Nodes
$scope.eraseConfiguration = function (size) {
var addModalInstance = $uibModal.open({
templateUrl: 'partials/nodes/node-erase-configuration-modal.html',
controller: 'NodesControllerEraseConfiguration',
size: size,
resolve: {}
});
addModalInstance.result.then(function () {
NodesFactory.eraseConfiguration($scope.itemIds, function(response) {
alertService.success($filter('translate')('ERASE_CONFIGURATION_INITIATED'));
},function(error){
displayRestError.display(error);
});
}),
function () {
//console.log('Modal dismissed at: ' + new Date());
}
};
// global page refresh
var promise = $interval($scope.getAllItems, mchelper.cfg.globalPageRefreshTime);
// cancel interval on scope destroy
$scope.$on('$destroy', function(){
$interval.cancel(promise);
});
});
// Nodes other controllers
//Add/Edit Node
myControllerModule.controller('NodesControllerAddEdit', function ($scope, $stateParams, GatewaysFactory, NodesFactory, TypesFactory, mchelper, alertService, displayRestError, $filter, $state, CommonServices) {
//Load mchelper variables to this scope
$scope.mchelper = mchelper;
$scope.cs = CommonServices;
$scope.node = {};
$scope.node.altproperties='{}';
if($stateParams.id){
NodesFactory.get({"nodeId":$stateParams.id},function(response) {
$scope.node = response;
$scope.node.altproperties = angular.toJson(response.properties);
},function(error){
displayRestError.display(error);
});
}
$scope.node.gateway = {};
$scope.gateways = TypesFactory.getGateways();
$scope.nodeTypes = TypesFactory.getNodeTypes();
$scope.nodeRstatuses = TypesFactory.getNodeRegistrationStatuses();
$scope.firmwares = TypesFactory.getFirmwares();
//GUI page settings
$scope.showHeaderUpdate = $stateParams.id;
$scope.headerStringAdd = $filter('translate')('ADD_NODE');
$scope.headerStringUpdate = $filter('translate')('UPDATE_NODE');
$scope.cancelButtonState = "nodesList"; //Cancel button state
$scope.saveProgress = false;
//$scope.isSettingChange = false;
$scope.save = function(){
$scope.saveProgress = true;
$scope.node.properties = angular.fromJson(JSON.stringify(eval('('+$scope.node.altproperties+')')));
console.log(angular.toJson($scope.node.altproperties));
if($stateParams.id){
NodesFactory.update($scope.node,function(response) {
alertService.success($filter('translate')('ITEM_UPDATED_SUCCESSFULLY'));
$state.go("nodesList");
},function(error){
displayRestError.display(error);
$scope.saveProgress = false;
});
}else{
NodesFactory.create($scope.node,function(response) {
alertService.success($filter('translate')('ITEM_CREATED_SUCCESSFULLY'));
$state.go("nodesList");
},function(error){
displayRestError.display(error);
$scope.saveProgress = false;
});
}
}
});
//Node Detail
myControllerModule.controller('NodesControllerDetail', function ($scope, $stateParams, mchelper, NodesFactory, TypesFactory, MetricsFactory, $filter, $timeout, $window) {
//Load mchelper variables to this scope
$scope.mchelper = mchelper;
$scope.item = {};
$scope.headerStringList = $filter('translate')('NODE_DETAILS');
$scope.item = NodesFactory.get({"nodeId":$stateParams.id});
$scope.resourceCount = MetricsFactory.getResourceCount({"resourceType":"NODE", "resourceId":$stateParams.id});
$scope.chartOptions = {
chart: {
type: 'lineChart',
noErrorCheck: true,
height: 325,
width:null,
margin : {
top: 0,
right: 10,
bottom: 90,
left: 65
},
color: ["#2ca02c","#1f77b4", "#ff7f0e"],
x: function(d){return d[0];},
y: function(d){return d[1];},
useVoronoi: false,
clipEdge: false,
transitionDuration: 500,
useInteractiveGuideline: true,
xAxis: {
showMaxMin: false,
tickFormat: function(d) {
return d3.time.format('hh:mm:ss a')(new Date(d))
},
//axisLabel: 'Timestamp',
rotateLabels: -20
},
yAxis: {
tickFormat: function(d){
return d3.format(',.2f')(d) + ' %';
},
//axisLabel: ''
}
},
title: {
enable: false,
text: 'Title'
}
};
//pre select, should be updated from server
TypesFactory.getMetricsSettings(function(response){
$scope.metricsSettings = response;
$scope.chartEnableMinMax = $scope.metricsSettings.enabledMinMax;
$scope.chartFromTimestamp = $scope.metricsSettings.defaultTimeRange.toString();
MetricsFactory.getBatteryMetrics({"nodeId":$stateParams.id, "withMinMax":$scope.chartEnableMinMax, "start": new Date().getTime() - $scope.chartFromTimestamp},function(response){
$scope.batteryChartData = response;
//Update display time format
$scope.chartTimeFormat = response.timeFormat;
$scope.chartOptions.chart.type = response.chartType;
$scope.chartOptions.chart.interpolate = response.chartInterpolate;
$scope.fetching = false;
});
});
$scope.chartTimeFormat = mchelper.cfg.dateFormat;
$scope.chartOptions.chart.xAxis.tickFormat = function(d) {return $filter('date')(d, $scope.chartTimeFormat, mchelper.cfg.timezone)};
$scope.updateChart = function(){
MetricsFactory.getBatteryMetrics({"nodeId":$stateParams.id, "withMinMax":$scope.chartEnableMinMax, "start": new Date().getTime() - $scope.chartFromTimestamp}, function(resource){
$scope.batteryChartData.chartData = resource.chartData;
//Update display time format
$scope.chartTimeFormat = resource.timeFormat;
});
}
//Graph resize issue, see: https://github.com/krispo/angular-nvd3/issues/40
$scope.$watch('fetching', function() {
if(!$scope.fetching) {
$timeout(function() {
$window.dispatchEvent(new Event('resize'));
$scope.fetching = true;
}, 1000);
}
});
});
//Erase Configuration Modal
myControllerModule.controller('NodesControllerEraseConfiguration', function ($scope, $uibModalInstance, $filter) {
$scope.header = $filter('translate')('ERASE_CONFIGURATION_CONFIRMATION_TITLE');
$scope.eraseMsg = $filter('translate')('ERASE_CONFIGURATION_CONFIRMATION_MESSAGE');
$scope.eraseNodeConfiguration = function() {$uibModalInstance.close(); };
$scope.cancel = function () { $uibModalInstance.dismiss('cancel'); }
});
//reboot Modal
myControllerModule.controller('NodesControllerReboot', function ($scope, $uibModalInstance, $filter) {
$scope.header = $filter('translate')('REBOOT_CONFIRMATION_TITLE');
$scope.rebootMsg = $filter('translate')('REBOOT_CONFIRMATION_MESSAGE');
$scope.reboot = function() {$uibModalInstance.close(); };
$scope.cancel = function () { $uibModalInstance.dismiss('cancel'); }
});

View File

@@ -0,0 +1,346 @@
/*
* Copyright 2015-2018 Jeeva Kandasamy (jkandasa@gmail.com)
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
myControllerModule.controller('OperationsController', function(alertService,
$scope, OperationsFactory, $state, $uibModal, $stateParams, displayRestError, mchelper, CommonServices, $filter) {
//GUI page settings
$scope.headerStringList = $filter('translate')('OPERATIONS_DETAIL');
$scope.noItemsSystemMsg = $filter('translate')('NO_OPERATIONS_SETUP');
$scope.noItemsSystemIcon = "fa fa-tasks";
//load empty, configuration, etc.,
$scope.mchelper = mchelper;
$scope.filteredList=[];
//data query details
$scope.currentPage = 1;
$scope.query = CommonServices.getQuery();
$scope.queryResponse = {};
//Get min number
$scope.getMin = function(item1, item2){
return CommonServices.getMin(item1, item2);
};
if($stateParams.resourceType){
$scope.query.resourceType = $stateParams.resourceType;
$scope.query.resourceId = $stateParams.resourceId;
}
//get all Sensors
$scope.getAllItems = function(){
OperationsFactory.getAll($scope.query, function(response) {
$scope.queryResponse = response;
$scope.filteredList = $scope.queryResponse.data;
$scope.filterConfig.resultsCount = $scope.queryResponse.query.filteredCount;
},function(error){
displayRestError.display(error);
});
}
//Hold all the selected item ids
$scope.itemIds = [];
$scope.selectAllItems = function(){
CommonServices.selectAllItems($scope);
};
$scope.selectItem = function(item){
CommonServices.selectItem($scope, item);
};
//On page change
$scope.pageChanged = function(newPage){
CommonServices.updatePageChange($scope, newPage);
};
//Filter change method
var filterChange = function (filters) {
//Reset filter fields and update items
CommonServices.updateFiltersChange($scope, filters);
};
$scope.filterConfig = {
fields: [
{
id: 'name',
title: $filter('translate')('NAME'),
placeholder: $filter('translate')('FILTER_BY_NAME'),
filterType: 'text'
},
{
id: 'enabled',
title: $filter('translate')('ENABLED'),
placeholder: $filter('translate')('FILTER_BY_ENABLED'),
filterType: 'select',
filterValues: ['True','False'],
},
{
id: 'type',
title: $filter('translate')('OPERATION_TYPE'),
placeholder: $filter('translate')('FILTER_BY_OPERATION_TYPE'),
filterType: 'select',
filterValues: ['Send payload','Send SMS','Send email','Send pushbullet note','Execute script'],
},
{
id: 'publicAccess',
title: $filter('translate')('PUBLIC_ACCESS'),
placeholder: $filter('translate')('FILTER_BY_PUBLIC_ACCESS'),
filterType: 'select',
filterValues: ['True','False'],
}
],
resultsCount: $scope.filteredList.length,
appliedFilters: [],
onFilterChange: filterChange
};
//Sort columns
var sortChange = function (sortId, isAscending) {
//Reset sort type and update items
CommonServices.updateSortChange($scope, sortId, isAscending);
};
$scope.sortConfig = {
fields: [
{
id: 'name',
title: $filter('translate')('NAME'),
sortType: 'text'
},
{
id: 'enabled',
title: $filter('translate')('ENABLED'),
sortType: 'text'
},
{
id: 'type',
title: $filter('translate')('OPERATION_TYPE'),
sortType: 'text'
},
{
id: 'publicAccess',
title: $filter('translate')('PUBLIC_ACCESS'),
sortType: 'text'
},
{
id: 'lastExecution',
title: $filter('translate')('LAST_EXECUTION'),
sortType: 'text'
}
],
onSortChange: sortChange
};
//Delete item(s)
$scope.delete = function (size) {
var modalInstance = $uibModal.open({
templateUrl: 'partials/common-html/delete-modal.html',
controller: 'ControllerDeleteModal',
size: size,
resolve: {}
});
modalInstance.result.then(function () {
OperationsFactory.deleteIds($scope.itemIds, function(response) {
alertService.success($filter('translate')('ITEMS_DELETED_SUCCESSFULLY'));
//Update display table
$scope.getAllItems();
$scope.itemIds = [];
},function(error){
displayRestError.display(error);
});
}),
function () {
//console.log('Modal dismissed at: ' + new Date());
}
};
//Enable items
$scope.enable = function () {
if($scope.itemIds.length > 0){
OperationsFactory.enableIds($scope.itemIds, function(response) {
alertService.success($filter('translate')('ITEMS_ENABLED_SUCCESSFULLY'));
//Update display table
$scope.getAllItems();
$scope.itemIds = [];
},function(error){
displayRestError.display(error);
});
}
};
//Disable items
$scope.disable = function () {
if($scope.itemIds.length > 0){
OperationsFactory.disableIds($scope.itemIds, function(response) {
alertService.success($filter('translate')('ITEMS_DISABLED_SUCCESSFULLY'));
//Update display table
$scope.getAllItems();
$scope.itemIds = [];
},function(error){
displayRestError.display(error);
});
}
};
//Edit item
$scope.edit = function () {
if($scope.itemIds.length == 1){
$state.go("operationsAddEdit",{'id':$scope.itemIds[0]});
}
};
//Clone item
$scope.clone = function () {
if($scope.itemIds.length == 1){
$state.go("operationsAddEdit",{'id':$scope.itemIds[0], 'action': 'clone'});
}
};
});
//Add Edit notification controller
myControllerModule.controller('OperationsControllerAddEdit', function ($scope, $stateParams, $state, GatewaysFactory,
NodesFactory, SensorsFactory, TypesFactory, OperationsFactory, ScriptsFactory, TemplatesFactory, mchelper, alertService, displayRestError, $filter, CommonServices) {
$scope.mchelper = mchelper;
$scope.item = {};
$scope.item.enabled = true;
$scope.item.publicAccess = false;
$scope.cs = CommonServices;
// Update resources list
$scope.getResources= function(resourceType){
if(resourceType === 'Sensor variable'){
return TypesFactory.getSensorVariables();
}else if(resourceType === 'Gateway' || resourceType === 'Gateway state'){
return TypesFactory.getGateways();
}else if(resourceType === 'Node' || resourceType === 'Node state'){
return TypesFactory.getNodes();
}else if(resourceType === 'Resources group'){
return TypesFactory.getResourcesGroups();
}else if(resourceType === 'Rule definition'){
return TypesFactory.getRuleDefinitions();
}else if(resourceType === 'Timer'){
return TypesFactory.getTimers();
}else if(resourceType === 'Forward payload'){
return TypesFactory.getForwardPayloads();
}else if(resourceType === 'Value'){
$scope.updateThresholdValueTypes($scope.item.resourceType);
return null;
}else{
return null;
}
}
//Update Payload operations
$scope.updatePayloadOperations= function(resourceType){
$scope.payloadOperations = TypesFactory.getPayloadOperations({"resourceType":resourceType});
}
if($stateParams.id){
OperationsFactory.get({"id":$stateParams.id},function(response) {
$scope.item = response;
//Update Operation Type
if($scope.item.type === 'Send payload'){
$scope.plResourcesList = $scope.getResources($scope.item.resourceType);
$scope.plResourceId = parseInt($scope.item.resourceId);
//Update payload operations
if($scope.item.resourceType !== 'Sensor variable'){
$scope.updatePayloadOperations($scope.item.resourceType);
}
}else if($scope.item.type === 'Execute script'){
$scope.item.altScriptBindings = angular.toJson(response.scriptBindings);
}else if($scope.item.type === 'Send email'){
$scope.item.altTemplateBindings = angular.toJson(response.templateBindings);
}
//Update delay time
if($scope.item.delayTime){
$scope.item.dt = $scope.item.delayTime/1000;
}
if($stateParams.action === 'clone'){
$stateParams.id = undefined;
$scope.item.id = undefined;
$scope.item.name = $scope.item.name + '-' + $filter('translate')('CLONE');
}
},function(error){
displayRestError.display(error);
});
}else{
$scope.item.altScriptBindings='{}';
$scope.item.altTemplateBindings='{}';
$scope.item.parseText = "Text";
}
//--------------pre load -----------
$scope.resourceTypes = TypesFactory.getResourceTypes({"resourceType": "Rule definition"});
$scope.spResourceTypes = TypesFactory.getResourceTypes({"operationType": "Send payload"});
$scope.reqPlResourceTypes = TypesFactory.getResourceTypes({"operationType": "Request payload"});
$scope.operationTypes = TypesFactory.getOperationTypes();
$scope.templatesList = TemplatesFactory.getAllLessInfo();
$scope.scriptsList = ScriptsFactory.getAllLessInfo({"type":"Operation"});
//GUI page settings
if(!$stateParams.action || $stateParams.action !== 'clone'){
$scope.showHeaderUpdate = $stateParams.id;
}
$scope.headerStringAdd = $filter('translate')('ADD_OPERATION');
$scope.headerStringUpdate = $filter('translate')('UPDATE_OPERATION');
$scope.cancelButtonState = "operationsList"; //Cancel button url
$scope.saveProgress = false;
//$scope.isSettingChange = false;
$scope.save = function(){
//Update delay time
if($scope.item.dt){
$scope.item.delayTime = $scope.item.dt*1000;
}
//Change string to JSON string
if($scope.item.type === 'Execute script'){
$scope.item.scriptBindings = angular.fromJson(JSON.stringify(eval('('+$scope.item.altScriptBindings+')')));
}else if($scope.item.type === 'Send email'){
$scope.item.templateBindings = angular.fromJson(JSON.stringify(eval('('+$scope.item.altTemplateBindings+')')));
}
$scope.saveProgress = true;
if($stateParams.id){
OperationsFactory.update($scope.item, function(response) {
alertService.success($filter('translate')('ITEM_UPDATED_SUCCESSFULLY'));
$state.go("operationsList");
},function(error){
displayRestError.display(error);
$scope.saveProgress = false;
});
}else{
OperationsFactory.create($scope.item, function(response) {
alertService.success($filter('translate')('ITEM_CREATED_SUCCESSFULLY'));
$state.go("operationsList");
},function(error){
displayRestError.display(error);
$scope.saveProgress = false;
});
}
}
});

View File

@@ -0,0 +1,251 @@
/*
* Copyright 2015-2018 Jeeva Kandasamy (jkandasa@gmail.com)
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
myControllerModule.controller('ResourcesDataController', function(alertService,
$scope, ResourcesDataFactory, $stateParams, $state, $uibModal, displayRestError, CommonServices, mchelper, $filter) {
//GUI page settings
$scope.headerStringList = $filter('translate')('RESOURCES_DATA_DETAIL');
$scope.noItemsSystemMsg = $filter('translate')('NO_RESOURCES_DATA_SETUP');
$scope.noItemsSystemIcon = "fa fa-server";
//load empty, configuration, etc.,
$scope.mchelper = mchelper;
$scope.filteredList=[];
//data query details
$scope.currentPage = 1;
$scope.query = CommonServices.getQuery();
$scope.queryResponse = {};
//Get min number
$scope.getMin = function(item1, item2){
return CommonServices.getMin(item1, item2);
};
if($stateParams.gatewayId){
$scope.query.gatewayId = $stateParams.gatewayId;
}
//get all ResourcesDatas
$scope.getAllItems = function(){
ResourcesDataFactory.getAll($scope.query, function(response) {
$scope.queryResponse = response;
$scope.filteredList = $scope.queryResponse.data;
$scope.filterConfig.resultsCount = $scope.queryResponse.query.filteredCount;
},function(error){
displayRestError.display(error);
});
}
//Hold all the selected item ids
$scope.itemIds = [];
$scope.selectAllItems = function(){
CommonServices.selectAllItems($scope);
};
$scope.selectItem = function(item){
CommonServices.selectItem($scope, item);
};
//On page change
$scope.pageChanged = function(newPage){
CommonServices.updatePageChange($scope, newPage);
};
//Filter change method
var filterChange = function (filters) {
//Reset filter fields and update items
CommonServices.updateFiltersChange($scope, filters);
};
$scope.filterConfig = {
fields: [
{
id: 'resourceType',
title: $filter('translate')('RESOURCE_TYPE'),
placeholder: $filter('translate')('FILTER_BY_RESOURCE_TYPE'),
filterType: 'select',
filterValues: ['Gateway','Node','Sensor','Sensor variable'],
}, {
id: 'enabled',
title: $filter('translate')('ENABLED'),
placeholder: $filter('translate')('FILTER_BY_ENABLED'),
filterType: 'select',
filterValues: ['True','False'],
}
],
resultsCount: $scope.filteredList.length,
appliedFilters: [],
onFilterChange: filterChange
};
//Sort columns
var sortChange = function (sortId, isAscending) {
//Reset sort type and update items
CommonServices.updateSortChange($scope, sortId, isAscending);
};
$scope.sortConfig = {
fields: [
{
id: 'resourceType',
title: $filter('translate')('RESOURCE_TYPE'),
sortType: 'text'
},
{
id: 'enabled',
title: $filter('translate')('ENABLED'),
sortType: 'text'
}
],
onSortChange: sortChange
};
//Delete items(s)
$scope.delete = function (size) {
var modalInstance = $uibModal.open({
templateUrl: 'partials/common-html/delete-modal.html',
controller: 'ControllerDeleteModal',
size: size,
resolve: {}
});
modalInstance.result.then(function () {
ResourcesDataFactory.deleteIds($scope.itemIds, function(response) {
alertService.success($filter('translate')('ITEMS_DELETED_SUCCESSFULLY'));
//Update display table
$scope.getAllItems();
$scope.itemIds = [];
},function(error){
displayRestError.display(error);
});
}),
function () {
//console.log('Modal dismissed at: ' + new Date());
}
};
//Edit item
$scope.edit = function () {
if($scope.itemIds.length == 1){
$state.go("resourcesDataAddEdit",{'id':$scope.itemIds[0]});
}
};
//Enable items
$scope.enable = function () {
if($scope.itemIds.length > 0){
ResourcesDataFactory.enableIds($scope.itemIds, function(response) {
alertService.success($filter('translate')('ITEMS_ENABLED_SUCCESSFULLY'));
//Update display table
$scope.getAllItems();
$scope.itemIds = [];
},function(error){
displayRestError.display(error);
});
}
};
//Disable items
$scope.disable = function () {
if($scope.itemIds.length > 0){
ResourcesDataFactory.disableIds($scope.itemIds, function(response) {
alertService.success($filter('translate')('ITEMS_DISABLED_SUCCESSFULLY'));
//Update display table
$scope.getAllItems();
$scope.itemIds = [];
},function(error){
displayRestError.display(error);
});
}
};
});
// ResourcesDatas other controllers
// Add/Edit Node
myControllerModule.controller('ResourcesDataControllerAddEdit', function ($scope, $stateParams, CommonServices, ResourcesDataFactory, TypesFactory, mchelper, alertService, displayRestError, $filter, $state) {
//Load mchelper variables to this scope
$scope.mchelper = mchelper;
$scope.cs = CommonServices;
$scope.item = {};
if($stateParams.id){
ResourcesDataFactory.get({"id":$stateParams.id}, function(response){
$scope.item = response;
$scope.resourcesList = $scope.getResources($scope.item.resourceType);
},function(error){
});
}else{
$scope.item.enabled = true;
}
$scope.externalServers = TypesFactory.getExternalServers();
$scope.resourceTypes = TypesFactory.getResourceTypes({"resourceType": "Resource data"});
// Update resources list
$scope.getResources = function(resourceType){
if(resourceType === 'Sensor variable'){
return TypesFactory.getSensorVariables();
}else if(resourceType === 'Gateway'){
return TypesFactory.getGateways();
}else if(resourceType === 'Node'){
return TypesFactory.getNodes();
}else if(resourceType === 'Sensor'){
return TypesFactory.getSensors();
}else{
return null;
}
}
//GUI page settings
$scope.showHeaderUpdate = $stateParams.id;
$scope.headerStringAdd = $filter('translate')('ADD_RESOURCE');
$scope.headerStringUpdate = $filter('translate')('UPDATE_RESOURCE');
$scope.cancelButtonState = "resourcesDataList"; //Cancel button state
$scope.saveProgress = false;
//$scope.isSettingChange = false;
$scope.save = function(){
$scope.saveProgress = true;
if($stateParams.id){
ResourcesDataFactory.update($scope.item,function(response) {
alertService.success($filter('translate')('ITEM_UPDATED_SUCCESSFULLY'));
$state.go("resourcesDataList");
},function(error){
displayRestError.display(error);
$scope.saveProgress = false;
});
}else{
ResourcesDataFactory.create($scope.item,function(response) {
alertService.success($filter('translate')('ITEM_CREATED_SUCCESSFULLY'));
$state.go("resourcesDataList");
},function(error){
displayRestError.display(error);
$scope.saveProgress = false;
});
}
}
});

View File

@@ -0,0 +1,463 @@
/*
* Copyright 2015-2018 Jeeva Kandasamy (jkandasa@gmail.com)
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
myControllerModule.controller('ResourcesGroupController', function(alertService,
$scope, ResourcesGroupFactory, $state, $uibModal, displayRestError, mchelper, CommonServices, $filter) {
//GUI page settings
$scope.headerStringList = $filter('translate')('RESOURCE_GROUPS_DETAIL');
$scope.noItemsSystemMsg = $filter('translate')('NO_RESOURCE_GROUPS_SETUP');
$scope.noItemsSystemIcon = "pficon pficon-replicator";
//load empty, configuration, etc.,
$scope.mchelper = mchelper;
$scope.filteredList=[];
//data query details
$scope.currentPage = 1;
$scope.query = CommonServices.getQuery();
$scope.queryResponse = {};
//Get min number
$scope.getMin = function(item1, item2){
return CommonServices.getMin(item1, item2);
};
//get all Sensors
$scope.getAllItems = function(){
ResourcesGroupFactory.getAll($scope.query, function(response) {
$scope.queryResponse = response;
$scope.filteredList = $scope.queryResponse.data;
$scope.filterConfig.resultsCount = $scope.queryResponse.query.filteredCount;
},function(error){
displayRestError.display(error);
});
}
//Hold all the selected item ids
$scope.itemIds = [];
$scope.selectAllItems = function(){
CommonServices.selectAllItems($scope);
};
$scope.selectItem = function(item){
CommonServices.selectItem($scope, item);
};
//On page change
$scope.pageChanged = function(newPage){
CommonServices.updatePageChange($scope, newPage);
};
//Filter change method
var filterChange = function (filters) {
//Reset filter fields and update items
CommonServices.updateFiltersChange($scope, filters);
};
$scope.filterConfig = {
fields: [
{
id: 'name',
title: $filter('translate')('NAME'),
placeholder: $filter('translate')('FILTER_BY_NAME'),
filterType: 'text'
},
{
id: 'description',
title: $filter('translate')('DESCRIPTION'),
placeholder: $filter('translate')('FILTER_BY_DESCRIPTION'),
filterType: 'integer',
}
],
resultsCount: $scope.filteredList.length,
appliedFilters: [],
onFilterChange: filterChange
};
//Sort columns
var sortChange = function (sortId, isAscending) {
//Reset sort type and update items
CommonServices.updateSortChange($scope, sortId, isAscending);
};
$scope.sortConfig = {
fields: [
{
id: 'name',
title: $filter('translate')('NAME'),
sortType: 'text'
},{
id: 'description',
title: $filter('translate')('DESCRIPTION'),
sortType: 'text'
},{
id: 'state',
title: $filter('translate')('STATUS'),
sortType: 'text'
},{
id: 'stateSince',
title: $filter('translate')('STATUS_SINCE'),
sortType: 'text'
}
],
onSortChange: sortChange
};
//On,Off switch control
$scope.changeMystate = function(item, state){
var itemArray = [item.id];
if(state){
ResourcesGroupFactory.turnOnIds(itemArray, function(response) {
alertService.success($filter('translate')('RESOURCE_GROUP_TURNED_ON'));
//Update display table
//$scope.getAllItems();
},function(error){
displayRestError.display(error);
});
}else{
ResourcesGroupFactory.turnOffIds(itemArray, function(response) {
alertService.success($filter('translate')('RESOURCE_GROUP_TURNED_OFF'));
//Update display table
//$scope.getAllItems();
},function(error){
displayRestError.display(error);
});
}
}
//Edit item
$scope.edit = function () {
if($scope.itemIds.length == 1){
$state.go("resourcesGroupAddEdit", {'id':$scope.itemIds[0]});
}
};
//Turm ON items
$scope.turnOn = function () {
if($scope.itemIds.length > 0){
ResourcesGroupFactory.turnOnIds($scope.itemIds, function(response) {
alertService.success($filter('translate')('RESOURCE_GROUPS_TURNED_ON'));
//Update display table
$scope.getAllItems();
$scope.itemIds = [];
},function(error){
displayRestError.display(error);
});
}
};
//Turm OFF items
$scope.turnOff = function () {
if($scope.itemIds.length > 0){
ResourcesGroupFactory.turnOffIds($scope.itemIds, function(response) {
alertService.success($filter('translate')('RESOURCE_GROUPS_TURNED_OFF'));
//Update display table
$scope.getAllItems();
$scope.itemIds = [];
},function(error){
displayRestError.display(error);
});
}
};
//Delete item(s)
$scope.delete = function (size) {
var modalInstance = $uibModal.open({
templateUrl: 'partials/common-html/delete-modal.html',
controller: 'ControllerDeleteModal',
size: size,
resolve: {}
});
modalInstance.result.then(function () {
ResourcesGroupFactory.deleteIds($scope.itemIds, function(response) {
alertService.success($filter('translate')('ITEMS_DELETED_SUCCESSFULLY'));
//Update display table
$scope.getAllItems();
$scope.itemIds = [];
},function(error){
displayRestError.display(error);
});
}),
function () {
//console.log('Modal dismissed at: ' + new Date());
}
};
});
//Add Edit item controller
myControllerModule.controller('ResourcesGroupControllerAddEdit', function ($scope, $stateParams, $state, ResourcesGroupFactory, mchelper, alertService, displayRestError, $filter) {
//GUI page settings
$scope.showHeaderUpdate = $stateParams.id;
$scope.headerStringAdd = $filter('translate')('ADD_RESOURCES_GROUP');
$scope.headerStringUpdate = $filter('translate')('UPDATE_RESOURCES_GROUP');
$scope.cancelButtonState = "resourcesGroupList"; //Cancel button state
$scope.saveProgress = false;
//$scope.isSettingChange = false;
$scope.mchelper = mchelper;
$scope.group = {};
$scope.id = $stateParams.id;
if($stateParams.id){
ResourcesGroupFactory.get({'_id':$stateParams.id},function(response) {
$scope.group = response;
},function(error){
displayRestError.display(error);
});
}
$scope.save = function(){
$scope.saveProgress = true;
if($stateParams.id){
ResourcesGroupFactory.update($scope.group,function(response) {
alertService.success($filter('translate')('ITEM_UPDATED_SUCCESSFULLY'));
$state.go("resourcesGroupList");
},function(error){
displayRestError.display(error);
$scope.saveProgress = false;
});
}else{
ResourcesGroupFactory.create($scope.group,function(response) {
alertService.success($filter('translate')('ITEM_CREATED_SUCCESSFULLY'));
$state.go("resourcesGroupList");
},function(error){
displayRestError.display(error);
$scope.saveProgress = false;
});
}
}
});
//ResourcesGroup Map
//------------------------------------------------------------------------------
myControllerModule.controller('ResourcesGroupMapController', function(alertService,
$scope, ResourcesGroupFactory, ResourcesGroupMapFactory, $state, $uibModal, displayRestError, mchelper, CommonServices, $stateParams, $filter) {
//GUI page settings
$scope.headerStringList = $filter('translate')('RESOURCE_GROUPS_MAPS_DETAIL');
$scope.noItemsSystemMsg = $filter('translate')('NO_RESOURCE_GROUPS_MAP_SETUP');
$scope.noItemsSystemIcon = "pficon pficon-replicator";
//load empty, configuration, etc.,
$scope.mchelper = mchelper;
$scope.filteredList=[];
//data query details
$scope.currentPage = 1;
$scope.query = CommonServices.getQuery();
$scope.queryResponse = {};
//Get min number
$scope.getMin = function(item1, item2){
return CommonServices.getMin(item1, item2);
};
//redirect to groups list if id not found
if(!$stateParams){
$state.go("resourcesGroupList");
}
//always lock with group id
$scope.query.groupId = $stateParams.id;
$scope.resourcesGroup = ResourcesGroupFactory.get({"id":$stateParams.id});
//get all items
$scope.getAllItems = function(){
ResourcesGroupMapFactory.getAll($scope.query, function(response) {
$scope.queryResponse = response;
$scope.filteredList = $scope.queryResponse.data;
$scope.filterConfig.resultsCount = $scope.queryResponse.query.filteredCount;
},function(error){
displayRestError.display(error);
});
}
//Hold all the selected item ids
$scope.itemIds = [];
$scope.selectAllItems = function(){
CommonServices.selectAllItems($scope);
};
$scope.selectItem = function(item){
CommonServices.selectItem($scope, item);
};
//On page change
$scope.pageChanged = function(newPage){
CommonServices.updatePageChange($scope, newPage);
};
//Filter change method
var filterChange = function (filters) {
//Reset filter fields and update items
CommonServices.updateFiltersChange($scope, filters);
};
$scope.filterConfig = {
fields: [
{
id: 'resourceType',
title: $filter('translate')('RESOURCE_TYPE'),
placeholder: $filter('translate')('FILTER_BY_RESOURCE_TYPE'),
filterType: 'text'
},
{
id: 'payloadOn',
title: $filter('translate')('PAYLOAD_ON'),
placeholder: $filter('translate')('FILTER_BY_PAYLOAD_ON'),
filterType: 'integer',
},
{
id: 'payloadOff',
title: $filter('translate')('PAYLOAD_OFF'),
placeholder: $filter('translate')('FILTER_BY_PAYLOAD_OFF'),
filterType: 'text',
}
],
resultsCount: $scope.filteredList.length,
appliedFilters: [],
onFilterChange: filterChange
};
//Sort columns
var sortChange = function (sortId, isAscending) {
//Reset sort type and update items
CommonServices.updateSortChange($scope, sortId, isAscending);
};
$scope.sortConfig = {
fields: [
{
id: 'resourceType',
title: $filter('translate')('RESOURCE_TYPE'),
sortType: 'text'
},{
id: 'payloadOn',
title: $filter('translate')('PAYLOAD_ON'),
sortType: 'text'
},
{
id: 'payloadOff',
title: $filter('translate')('PAYLOAD_OFF'),
sortType: 'text'
}
],
onSortChange: sortChange
};
//Edit item
$scope.edit = function () {
if($scope.itemIds.length == 1){
$state.go("resourcesGroupMapAddEdit", {'groupId':$scope.query.groupId, 'id':$scope.itemIds[0]});
}
};
//Delete item(s)
$scope.delete = function (size) {
var modalInstance = $uibModal.open({
templateUrl: 'partials/common-html/delete-modal.html',
controller: 'ControllerDeleteModal',
size: size,
resolve: {}
});
modalInstance.result.then(function () {
ResourcesGroupMapFactory.deleteIds($scope.itemIds, function(response) {
alertService.success($filter('translate')('ITEMS_DELETED_SUCCESSFULLY'));
//Update display table
$scope.getAllItems();
$scope.itemIds = [];
},function(error){
displayRestError.display(error);
});
}),
function () {
//console.log('Modal dismissed at: ' + new Date());
}
};
});
//Add Edit item controller
myControllerModule.controller('ResourcesGroupMapControllerAddEdit', function ($scope, $stateParams, $state, TypesFactory, CommonServices, ResourcesGroupMapFactory, mchelper, alertService, displayRestError, $filter) {
$scope.mchelper = mchelper;
$scope.groupMap = {};
if($stateParams.id){
ResourcesGroupMapFactory.get({"id":$stateParams.id},function(response) {
$scope.groupMap = response;
//Update Resources
$scope.dspResources = $scope.getResources($scope.groupMap.resourceType);
},function(error){
displayRestError.display(error);
});
}else if($stateParams.groupId){
$scope.groupMap.resourcesGroup = {};
$scope.groupMap.resourcesGroup.id = $stateParams.groupId;
}else{
$state.go("resourcesGroupList");
}
//pre load
$scope.resourceTypes = TypesFactory.getResourceTypes({"resourceType": "resources group"});
//Get resources
$scope.getResources = function(resourceType){
return CommonServices.getResources(resourceType);
}
//GUI page settings
$scope.showHeaderUpdate = $stateParams.id;
$scope.headerStringAdd = $filter('translate')('ADD_AN_ENTRY');
$scope.headerStringUpdate = $filter('translate')('UPDATE_AN_ENTRY');
$scope.cancelButtonState = "resourcesGroupMapList({id:"+$stateParams.groupId+"})"; //Cancel button state
$scope.saveProgress = false;
//$scope.isSettingChange = false;
$scope.save = function(){
$scope.saveProgress = true;
if($stateParams.id){
ResourcesGroupMapFactory.update($scope.groupMap,function(response) {
alertService.success($filter('translate')('ITEM_UPDATED_SUCCESSFULLY'));
$state.go("resourcesGroupMapList",{id:$stateParams.groupId});
},function(error){
displayRestError.display(error);
$scope.saveProgress = false;
});
}else{
ResourcesGroupMapFactory.create($scope.groupMap,function(response) {
alertService.success($filter('translate')('ITEM_CREATED_SUCCESSFULLY'));
$state.go("resourcesGroupMapList",{id:$stateParams.groupId});
},function(error){
displayRestError.display(error);
$scope.saveProgress = false;
});
}
}
});

View File

@@ -0,0 +1,272 @@
/*
* Copyright 2015-2018 Jeeva Kandasamy (jkandasa@gmail.com)
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
myControllerModule.controller('ResourcesLogsController', function(alertService,
$scope, $filter, ResourcesLogsFactory, SettingsFactory, $uibModal, $stateParams, mchelper, CommonServices, $interval) {
//GUI page settings
$scope.headerStringList = $filter('translate')('RESOURCES_LOGS_DETAIL');
$scope.noItemsSystemMsg = $filter('translate')('NO_LOGS_AVAILABLE');
$scope.noItemsSystemIcon = "fa fa-list";
//load empty, configuration, etc.,
$scope.mchelper = mchelper;
$scope.filteredList=[];
//data query details
$scope.currentPage = 1;
$scope.query = CommonServices.getQuery();
$scope.queryResponse = {};
$scope.itemsPerPage = mchelper.userSettings.resourcesLogsItemsPerPage;
//Get min number
$scope.getMin = function(item1, item2){
return CommonServices.getMin(item1, item2);
};
if($stateParams.resourceType){
$scope.query.resourceType = $stateParams.resourceType;
if($stateParams.resourceId){
$scope.query.resourceId = $stateParams.resourceId;
}
}
//Stop if an request sent already
var updateInprogress = false;
//get all items
$scope.getAllItems = function(){
if(updateInprogress){
return;
}
updateInprogress = true;
$scope.query.pageLimit = parseInt($scope.itemsPerPage);
ResourcesLogsFactory.getAll($scope.query, function(response) {
$scope.queryResponse = response;
$scope.filteredList = $scope.queryResponse.data;
$scope.filterConfig.resultsCount = $scope.queryResponse.query.filteredCount;
updateInprogress = false;
},function(error){
updateInprogress = false;
displayRestError.display(error);
});
}
//Hold all the selected item ids
$scope.itemIds = [];
$scope.selectAllItems = function(){
CommonServices.selectAllItems($scope);
};
$scope.selectItem = function(item){
CommonServices.selectItem($scope, item);
};
//On page change
$scope.pageChanged = function(newPage){
CommonServices.updatePageChange($scope, newPage);
};
//Filter change method
var filterChange = function (filters) {
//Reset filter fields and update items
CommonServices.updateFiltersChange($scope, filters);
};
$scope.filterConfig = {
fields: [
{
id: 'message',
title: $filter('translate')('MESSAGE'),
placeholder: $filter('translate')('FILTER_BY_MESSAGE'),
filterType: 'text'
},
{
id: 'resourceType',
title: $filter('translate')('TYPE'),
placeholder: $filter('translate')('FILTER_BY_TYPE'),
filterType: 'select',
filterValues:['Gateway','Node','Sensor','Sensor variable','Resources group','Alarm definition','Timer'],
},
{
id: 'logLevel',
title: $filter('translate')('LEVEL'),
placeholder: $filter('translate')('FILTER_BY_LEVEL'),
filterType: 'select',
filterValues: ['Trace','Notice','Info','Warning','Error'],
},
{
id: 'messageType',
title: $filter('translate')('MESSAGE_TYPE'),
placeholder: $filter('translate')('FILTER_BY_MESSGAE_TYPE'),
filterType: 'select',
filterValues: ['Presentation','Set','Request','Internal','Stream'],
},
{
id: 'logDirection',
title: $filter('translate')('DIRECTION'),
placeholder: $filter('translate')('FILTER_BY_DIRECTION'),
filterType: 'select',
filterValues: ['Internal','Sent','Received'],
}
],
resultsCount: $scope.filteredList.length,
appliedFilters: [],
onFilterChange: filterChange
};
//Sort columns
var sortChange = function (sortId, isAscending) {
//Reset sort type and update items
CommonServices.updateSortChange($scope, sortId, isAscending);
};
$scope.sortConfig = {
fields: [
{
id: 'timestamp',
title: $filter('translate')('TIME'),
sortType: 'alpha'
},
{
id: 'logLevel',
title: $filter('translate')('LEVEL'),
sortType: 'alpha'
},
{
id: 'resourceType',
title: $filter('translate')('TYPE'),
sortType: 'alpha'
},
{
id: 'messageType',
title: $filter('translate')('MESSAGE_TYPE'),
sortType: 'alpha'
},
{
id: 'logDirection',
title: $filter('translate')('DIRECTION'),
sortType: 'alpha'
},
{
id: 'message',
title: $filter('translate')('MESSAGE'),
sortType: 'alpha'
}
],
onSortChange: sortChange,
isAscending: false,
};
//Update items per page
$scope.updateItemsPerPage = function(itemsPerPage){
mchelper.userSettings.resourcesLogsItemsPerPage = itemsPerPage;
SettingsFactory.saveUserSettings(mchelper.userSettings);
CommonServices.saveMchelper(mchelper);
$scope.getAllItems();
};
//Delete item(s)
$scope.delete = function (size) {
var modalInstance = $uibModal.open({
templateUrl: 'partials/common-html/delete-modal.html',
controller: 'ControllerDeleteModal',
size: size,
resolve: {}
});
modalInstance.result.then(function () {
ResourcesLogsFactory.delete($scope.itemIds, function(response) {
alertService.success($filter('translate')('ITEMS_DELETED_SUCCESSFULLY'));
//Update display table
$scope.getAllItems();
$scope.itemIds = [];
},function(error){
displayRestError.display(error);
});
}),
function () {
//console.log('Modal dismissed at: ' + new Date());
}
};
function updatePage(){
$scope.getAllItems(true);
};
// global page refresh
var promise = $interval(updatePage, mchelper.cfg.globalPageRefreshTime);
// cancel interval on scope destroy
$scope.$on('$destroy', function(){
$interval.cancel(promise);
});
});
//purge resources logs
myControllerModule.controller('ResourcesLogsPurgeController', function ($scope, CommonServices, alertService, ResourcesLogsFactory, mchelper, $filter, TypesFactory) {
$scope.item = {};
//GUI page settings
$scope.headerStringAdd = $filter('translate')('PURGE_RESOURCES_LOGS');
$scope.cancelButtonState = "resourcesLogsList"; //Cancel button state
$scope.saveProgress = false;
$scope.saveButtonName = $filter('translate')('PURGE');
$scope.savingButtonName = $filter('translate')('PURGING');
$scope.saveButtonTooltip = $filter('translate')('PURGE_WARNING');
//$scope.isSettingChange = false;
//Pre load
$scope.messageTypes = TypesFactory.getResourceLogsMessageTypes();
$scope.logDirections = TypesFactory.getResourceLogsLogDirections();
$scope.logLevels = TypesFactory.getResourceLogsLogLevels();
$scope.resourceTypes = TypesFactory.getResourceTypes();
$scope.resourcesLogs = {};
//Get resources
$scope.getResources = function(resourceType){
return CommonServices.getResources(resourceType);
}
//Convert as display string
$scope.getDateTimeDisplayFormat = function (newDate) {
return $filter('date')(newDate, mchelper.cfg.dateFormat, mchelper.cfg.timezone);
};
//Save data - here it's purge
$scope.save = function(){
//Update validity from/to
if($scope.purgeBefore){
$scope.resourcesLogs.timestamp = moment($scope.purgeBefore).format('YYYY-MM-DDTHH:mm:ss');
}
$scope.saveProgress = true;
ResourcesLogsFactory.purge($scope.resourcesLogs,function(response) {
alertService.success($filter('translate')('PURGE_DONE_SUCCESSFULLY'));
$scope.saveProgress = false;
},function(error){
displayRestError.display(error);
$scope.saveProgress = false;
});
}
});

209
www/controllers/roles.js Normal file
View File

@@ -0,0 +1,209 @@
/*
* Copyright 2015-2018 Jeeva Kandasamy (jkandasa@gmail.com)
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
myControllerModule.controller('RolesControllerList', function(alertService,
$scope, SecurityFactory, $state, $uibModal, displayRestError, mchelper, CommonServices, $filter) {
//GUI page settings
$scope.headerStringList = $filter('translate')('ROLES_DETAIL');
$scope.noItemsSystemMsg = $filter('translate')('NO_ROLES_SETUP');
$scope.noItemsSystemIcon = "pficon pficon-registry";
//load empty, configuration, etc.,
$scope.mchelper = mchelper;
$scope.filteredList=[];
//data query details
$scope.currentPage = 1;
$scope.query = CommonServices.getQuery();
$scope.queryResponse = {};
//Get min number
$scope.getMin = function(item1, item2){
return CommonServices.getMin(item1, item2);
};
//get all Sensors
$scope.getAllItems = function(){
SecurityFactory.getAllRoles($scope.query, function(response) {
$scope.queryResponse = response;
$scope.filteredList = $scope.queryResponse.data;
$scope.filterConfig.resultsCount = $scope.queryResponse.query.filteredCount;
},function(error){
displayRestError.display(error);
});
}
//Hold all the selected item ids
$scope.itemIds = [];
$scope.selectAllItems = function(){
CommonServices.selectAllItems($scope);
};
$scope.selectItem = function(item){
CommonServices.selectItem($scope, item);
};
//On page change
$scope.pageChanged = function(newPage){
CommonServices.updatePageChange($scope, newPage);
};
//Filter change method
var filterChange = function (filters) {
//Reset filter fields and update items
CommonServices.updateFiltersChange($scope, filters);
};
$scope.filterConfig = {
fields: [
{
id: 'name',
title: $filter('translate')('NAME'),
placeholder: $filter('translate')('FILTER_BY_NAME'),
filterType: 'text'
},
{
id: 'description',
title: $filter('translate')('DESCRIPTION'),
placeholder: $filter('translate')('FILTER_BY_DESCRIPTION'),
filterType: 'text',
},
{
id: 'permission',
title: $filter('translate')('PERMISSION'),
placeholder: $filter('translate')('FILTER_BY_PERMISSION'),
filterType: 'select',
filterValues: ['Super admin','User','MQTT user'],
}
],
resultsCount: $scope.filteredList.length,
appliedFilters: [],
onFilterChange: filterChange
};
//Sort columns
var sortChange = function (sortId, isAscending) {
//Reset sort type and update items
CommonServices.updateSortChange($scope, sortId, isAscending);
};
$scope.sortConfig = {
fields: [
{
id: 'name',
title: $filter('translate')('NAME'),
sortType: 'text'
},
{
id: 'description',
title: $filter('translate')('DESCRIPTION'),
sortType: 'text'
},
{
id: 'permission',
title: $filter('translate')('PERMISSION'),
sortType: 'text'
}
],
onSortChange: sortChange
};
//Edit item
$scope.edit = function () {
if($scope.itemIds.length == 1){
$state.go("settingsRolesAddEdit", {'id':$scope.itemIds[0]});
}
};
//Delete item(s)
$scope.delete = function (size) {
var modalInstance = $uibModal.open({
templateUrl: 'partials/common-html/delete-modal.html',
controller: 'ControllerDeleteModal',
size: size,
resolve: {}
});
modalInstance.result.then(function () {
SecurityFactory.deleteRoleIds($scope.itemIds, function(response) {
alertService.success($filter('translate')('ITEMS_DELETED_SUCCESSFULLY'));
//Update display table
$scope.getAllItems();
$scope.itemIds = [];
},function(error){
displayRestError.display(error);
});
}),
function () {
//console.log('Modal dismissed at: ' + new Date());
}
};
});
//Add Edit item
myControllerModule.controller('RolesControllerAddEdit', function ($scope, $stateParams, $state, SecurityFactory, TypesFactory, mchelper, alertService, displayRestError, $filter) {
$scope.mchelper = mchelper;
$scope.item = {};
if($stateParams.id){
SecurityFactory.getRole({"id":$stateParams.id},function(response) {
$scope.item = response;
},function(error){
displayRestError.display(error);
});
}
//GUI page settings
$scope.showHeaderUpdate = $stateParams.id;
$scope.headerStringAdd = $filter('translate')('ADD_ROLE');
$scope.headerStringUpdate = $filter('translate')('UPDATE_ROLE');
$scope.cancelButtonState = "settingsRolesList"; //Cancel button state
$scope.saveProgress = false;
//$scope.isSettingChange = false;
//Pre load
$scope.nodes = TypesFactory.getNodes();
$scope.sensors = TypesFactory.getSensors();
$scope.gateways = TypesFactory.getGateways();
$scope.users = SecurityFactory.getAllUsersSimple();
$scope.rolePermissions = TypesFactory.getRolePermissions();
$scope.save = function(){
$scope.saveProgress = true;
if($stateParams.id){
SecurityFactory.updateRole($scope.item,function(response) {
alertService.success($filter('translate')('ITEM_UPDATED_SUCCESSFULLY'));
$state.go("settingsRolesList");
},function(error){
displayRestError.display(error);
$scope.saveProgress = false;
});
}else{
SecurityFactory.createRole($scope.item,function(response) {
alertService.success($filter('translate')('ITEM_CREATED_SUCCESSFULLY'));
$state.go("settingsRolesList");
},function(error){
displayRestError.display(error);
$scope.saveProgress = false;
});
}
}
});

299
www/controllers/rooms.js Normal file
View File

@@ -0,0 +1,299 @@
/*
* Copyright 2015-2018 Jeeva Kandasamy (jkandasa@gmail.com)
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
myControllerModule.controller('RoomsControllerList', function(alertService,
$scope, RoomsFactory, $state, $uibModal, displayRestError, mchelper, CommonServices, $filter) {
//GUI page settings
$scope.headerStringList = $filter('translate')('ROOMS_DETAIL');
$scope.noItemsSystemMsg = $filter('translate')('NO_ROOMS_SETUP');
$scope.noItemsSystemIcon = "fa fa-object-group";
//load empty, configuration, etc.,
$scope.mchelper = mchelper;
$scope.filteredList=[];
//data query details
$scope.currentPage = 1;
$scope.query = CommonServices.getQuery();
$scope.queryResponse = {};
//Get min number
$scope.getMin = function(item1, item2){
return CommonServices.getMin(item1, item2);
};
//get all Sensors
$scope.getAllItems = function(){
RoomsFactory.getAll($scope.query, function(response) {
$scope.queryResponse = response;
$scope.filteredList = $scope.queryResponse.data;
$scope.filterConfig.resultsCount = $scope.queryResponse.query.filteredCount;
},function(error){
displayRestError.display(error);
});
}
//Hold all the selected item ids
$scope.itemIds = [];
$scope.selectAllItems = function(){
CommonServices.selectAllItems($scope);
};
$scope.selectItem = function(item){
CommonServices.selectItem($scope, item);
};
//On page change
$scope.pageChanged = function(newPage){
CommonServices.updatePageChange($scope, newPage);
};
//Filter change method
var filterChange = function (filters) {
//Reset filter fields and update items
CommonServices.updateFiltersChange($scope, filters);
};
$scope.filterConfig = {
fields: [
{
id: 'name',
title: $filter('translate')('NAME'),
placeholder: $filter('translate')('FILTER_BY_NAME'),
filterType: 'text'
},
{
id: 'description',
title: $filter('translate')('DESCRIPTION'),
placeholder: $filter('translate')('FILTER_BY_DESCRIPTION'),
filterType: 'text',
}
],
resultsCount: $scope.filteredList.length,
appliedFilters: [],
onFilterChange: filterChange
};
//Sort columns
var sortChange = function (sortId, isAscending) {
//Reset sort type and update items
CommonServices.updateSortChange($scope, sortId, isAscending);
};
$scope.sortConfig = {
fields: [
{
id: 'name',
title: $filter('translate')('NAME'),
sortType: 'text'
},{
id: 'description',
title: $filter('translate')('DESCRIPTION'),
sortType: 'text'
}
],
onSortChange: sortChange
};
//Edit item
$scope.edit = function () {
if($scope.itemIds.length == 1){
$state.go("roomsAddEdit", {'id':$scope.itemIds[0]});
}
};
//Delete item(s)
$scope.delete = function (size) {
var modalInstance = $uibModal.open({
templateUrl: 'partials/common-html/delete-modal.html',
controller: 'ControllerDeleteModal',
size: size,
resolve: {}
});
modalInstance.result.then(function () {
RoomsFactory.deleteIds($scope.itemIds, function(response) {
alertService.success($filter('translate')('ITEMS_DELETED_SUCCESSFULLY'));
//Update display table
$scope.getAllItems();
$scope.itemIds = [];
},function(error){
displayRestError.display(error);
});
}),
function () {
//console.log('Modal dismissed at: ' + new Date());
}
};
});
//Add Edit item controller
myControllerModule.controller('RoomsControllerAddEdit', function ($scope, $stateParams, $state, RoomsFactory, TypesFactory, mchelper, alertService, displayRestError, $filter) {
//GUI page settings
$scope.showHeaderUpdate = $stateParams.id;
$scope.headerStringAdd = $filter('translate')('ADD_ROOM');
$scope.headerStringUpdate = $filter('translate')('UPDATE_ROOM');
$scope.cancelButtonState = "roomsList"; //Cancel button state
$scope.saveProgress = false;
//$scope.isSettingChange = false;
$scope.mchelper = mchelper;
$scope.item = {};
$scope.sensorIds = [];
$scope.sensors = {};
$scope.id = $stateParams.id;
if($stateParams.id){
RoomsFactory.get({"id":$stateParams.id},function(response) {
$scope.item = response;
$scope.rooms = TypesFactory.getRooms({"selfId": response.id});
},function(error){
displayRestError.display(error);
});
$scope.sensors = TypesFactory.getSensors({"roomId":$stateParams.id, "enableNoRoomFilter":true});
}else{
$scope.sensors = TypesFactory.getSensors({"enableNoRoomFilter":true});
$scope.rooms = TypesFactory.getRooms();
}
$scope.save = function(){
$scope.saveProgress = true;
if($stateParams.id){
RoomsFactory.update($scope.item,function(response) {
alertService.success($filter('translate')('ITEM_UPDATED_SUCCESSFULLY'));
$state.go("roomsList");
},function(error){
displayRestError.display(error);
$scope.saveProgress = false;
});
}else{
RoomsFactory.create($scope.item,function(response) {
alertService.success($filter('translate')('ITEM_CREATED_SUCCESSFULLY'));
$state.go("roomsList");
},function(error){
displayRestError.display(error);
$scope.saveProgress = false;
});
}
}
});
//room list with sensors detail
myControllerModule.controller('RoomsSensorsControllerList', function(alertService, $stateParams,
$scope, RoomsFactory, SensorsFactory, TypesFactory, $state, $uibModal, displayRestError, mchelper, CommonServices, $filter) {
//GUI page settings
$scope.roomHeader = '/';
$scope.showLoading = true;
$scope.noItemsSystemMsg = $filter('translate')('NO_ROOMS_SETUP');
$scope.noItemsSystemIcon = "fa fa-object-group";
//load empty, configuration, etc.,
$scope.mchelper = mchelper;
$scope.cs = CommonServices;
$scope.tooltipPlacement = 'top';
$scope.tooltipEnabled=true;
$scope.showNoRoomsSetup=false;
$scope.queryResponse = {};
$scope.queryResponse.query = {};
$scope.query = {};
$scope.query.pageLimit = -1;
$scope.query.isSimpleQuery = true;
$scope.sensorsQueryResponse = {};
$scope.sensorsList = {};
//get all Sensors
$scope.getAllSensors = function(){
SensorsFactory.getAll($scope.query, function(response) {
$scope.sensorsQueryResponse = response;
$scope.sensorsList = $scope.sensorsQueryResponse.data;
$scope.showLoading = false;
},function(error){
displayRestError.display(error);
});
}
//get all items
$scope.getAllItems = function(){
RoomsFactory.getAll($scope.query, function(response) {
$scope.queryResponse = response;
$scope.queryResponse.query = {};
if(response.data.length == 0){
$scope.queryResponse.query.totalItems = 0;
}
},function(error){
displayRestError.display(error);
});
}
//pre-load
if($stateParams.id){
$scope.query.parentId = $stateParams.id;
$scope.query.roomId = $stateParams.id;
RoomsFactory.get({"id":$stateParams.id},function(response) {
$scope.parentRoom = response;
$scope.roomHeader = $scope.parentRoom.room.fullPath;
$scope.getAllSensors(); //Get sensors
},function(error){
displayRestError.display(error);
});
}else{
$scope.showNoRoomsSetup=true;
$scope.showLoading = false;
}
$scope.getAllItems();
//Load room
$scope.getRoom = function(item){
$state.go("dashboardRoomsSensorsList", {'id':item.id});
};
//Load room - root
$scope.getRoomRoot = function(){
//console.log("root room...");
$state.go('dashboardRoomsSensorsList', {'id':''}, { reload: true });
};
//Update Variable / Send Payload
$scope.updateVariable = function(variable){
SensorsFactory.updateVariable(variable, function(){
//update Success
},function(error){
displayRestError.display(error);
});
};
//HVAC heater options - HVAC flow state
$scope.hvacOptionsFlowState = TypesFactory.getHvacOptionsFlowState();
//HVAC heater options - HVAC flow mode
$scope.hvacOptionsFlowMode = TypesFactory.getHvacOptionsFlowMode();
//HVAC heater options - HVAC fan speed
$scope.hvacOptionsFanSpeed = TypesFactory.getHvacOptionsFanSpeed();
//Defined variable types list
$scope.definedVariableTypes = CommonServices.getSensorVariablesKnownList();
//Hide variable names
$scope.hideVariableName=false;
});

View File

@@ -0,0 +1,434 @@
/*
* Copyright 2015-2018 Jeeva Kandasamy (jkandasa@gmail.com)
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
myControllerModule.controller('RuleEngineController', function(alertService,
$scope, RulesFactory, $state, $uibModal, $stateParams, displayRestError, mchelper, CommonServices, $filter) {
//GUI page settings
$scope.headerStringList = $filter('translate')('RULES_DETAIL');
$scope.noItemsSystemMsg = $filter('translate')('NO_RULES_SETUP');
$scope.noItemsSystemIcon = "fa fa-cogs";
//load empty, configuration, etc.,
$scope.mchelper = mchelper;
$scope.filteredList=[];
//data query details
$scope.currentPage = 1;
$scope.query = CommonServices.getQuery();
$scope.queryResponse = {};
//Get min number
$scope.getMin = function(item1, item2){
return CommonServices.getMin(item1, item2);
};
if($stateParams.resourceType){
$scope.query.resourceType = $stateParams.resourceType;
$scope.query.resourceId = $stateParams.resourceId;
}
//get all Sensors
$scope.getAllItems = function(){
RulesFactory.getAll($scope.query, function(response) {
$scope.queryResponse = response;
$scope.filteredList = $scope.queryResponse.data;
$scope.filterConfig.resultsCount = $scope.queryResponse.query.filteredCount;
},function(error){
displayRestError.display(error);
});
}
//Hold all the selected item ids
$scope.itemIds = [];
$scope.selectAllItems = function(){
CommonServices.selectAllItems($scope);
};
$scope.selectItem = function(item){
CommonServices.selectItem($scope, item);
};
//On page change
$scope.pageChanged = function(newPage){
CommonServices.updatePageChange($scope, newPage);
};
//Filter change method
var filterChange = function (filters) {
//Reset filter fields and update items
CommonServices.updateFiltersChange($scope, filters);
};
$scope.filterConfig = {
fields: [
{
id: 'name',
title: $filter('translate')('NAME'),
placeholder: $filter('translate')('FILTER_BY_NAME'),
filterType: 'text'
},
{
id: 'resourceType',
title: $filter('translate')('RESOURCE_TYPE'),
placeholder: $filter('translate')('FILTER_BY_RESOURCE_TYPE'),
filterType: 'select',
filterValues: ['Gateway','Node','Sensor variable','Resources group','Script'],
},
{
id: 'enabled',
title: $filter('translate')('ENABLED'),
placeholder: $filter('translate')('FILTER_BY_ENABLED'),
filterType: 'select',
filterValues: ['True','False'],
},
{
id: 'conditionType',
title: $filter('translate')('CONDITION_TYPE'),
placeholder: $filter('translate')('FILTER_BY_CONDITION_TYPE'),
filterType: 'select',
filterValues: ['Threshold','Threshold range','Compare','State','String','Script'],
},
{
id: 'dampeningType',
title: $filter('translate')('DAMPENING_TYPE'),
placeholder: $filter('translate')('FILTER_BY_DAMPENING_TYPE'),
filterType: 'select',
filterValues: ['None','Consecutive','Last N evaluations','Active time'],
}
],
resultsCount: $scope.filteredList.length,
appliedFilters: [],
onFilterChange: filterChange
};
//Sort columns
var sortChange = function (sortId, isAscending) {
//Reset sort type and update items
CommonServices.updateSortChange($scope, sortId, isAscending);
};
$scope.sortConfig = {
fields: [
{
id: 'name',
title: $filter('translate')('NAME'),
sortType: 'text'
},
{
id: 'enabled',
title: $filter('translate')('ENABLED'),
sortType: 'text'
},
{
id: 'resourceType',
title: $filter('translate')('RESOURCE_TYPE'),
sortType: 'text'
},
{
id: 'conditionType',
title: $filter('translate')('CONDITION_TYPE'),
sortType: 'text'
},
{
id: 'dampeningType',
title: $filter('translate')('DAMPENING_TYPE'),
sortType: 'text'
},
{
id: 'lastTrigger',
title: $filter('translate')('LAST_TRIGGER'),
sortType: 'text'
}
],
onSortChange: sortChange
};
//Delete item(s)
$scope.delete = function (size) {
var modalInstance = $uibModal.open({
templateUrl: 'partials/common-html/delete-modal.html',
controller: 'ControllerDeleteModal',
size: size,
resolve: {}
});
modalInstance.result.then(function () {
RulesFactory.deleteIds($scope.itemIds, function(response) {
alertService.success($filter('translate')('ITEMS_DELETED_SUCCESSFULLY'));
//Update display table
$scope.getAllItems();
$scope.itemIds = [];
},function(error){
displayRestError.display(error);
});
}),
function () {
//console.log('Modal dismissed at: ' + new Date());
}
};
//Enable items
$scope.enable = function () {
if($scope.itemIds.length > 0){
RulesFactory.enableIds($scope.itemIds, function(response) {
alertService.success($filter('translate')('ITEMS_ENABLED_SUCCESSFULLY'));
//Update display table
$scope.getAllItems();
$scope.itemIds = [];
},function(error){
displayRestError.display(error);
});
}
};
//Disable items
$scope.disable = function () {
if($scope.itemIds.length > 0){
RulesFactory.disableIds($scope.itemIds, function(response) {
alertService.success($filter('translate')('ITEMS_DISABLED_SUCCESSFULLY'));
//Update display table
$scope.getAllItems();
$scope.itemIds = [];
},function(error){
displayRestError.display(error);
});
}
};
//Edit item
$scope.edit = function () {
if($scope.itemIds.length == 1){
$state.go("rulesAddEdit",{'id':$scope.itemIds[0]});
}
};
//Clone item
$scope.clone = function () {
if($scope.itemIds.length == 1){
$state.go("rulesAddEdit",{'id':$scope.itemIds[0], 'action': 'clone'});
}
};
});
//Add Edit alarm defination controller
myControllerModule.controller('RuleEngineControllerAddEdit', function ($scope, $stateParams, $state, GatewaysFactory, NodesFactory, SensorsFactory, TypesFactory, RulesFactory, ScriptsFactory,
mchelper, alertService, displayRestError, $filter, CommonServices) {
$scope.mchelper = mchelper;
$scope.item = {};
$scope.item.ignoreDuplicate = true;
$scope.item.enabled = true;
$scope.item.disableWhenTrigger = false;
$scope.cs = CommonServices;
// Update resources list
$scope.getResources= function(resourceType, filterValue){
if(resourceType === 'Sensor variable'){
return TypesFactory.getSensorVariables({'metricType':filterValue});
}else if(resourceType === 'Gateway' || resourceType === 'Gateway state'){
return TypesFactory.getGateways();
}else if(resourceType === 'Node' || resourceType === 'Node state'){
return TypesFactory.getNodes();
}else if(resourceType === 'Resources group'){
return TypesFactory.getResourcesGroups();
}else if(resourceType === 'Rule definition'){
return TypesFactory.getRuleDefinitions();
}else if(resourceType === 'Timer'){
return TypesFactory.getTimers();
}else if(resourceType === 'Value'){
$scope.updateThresholdValueTypes($scope.item.resourceType);
return null;
}else{
return null;
}
}
//Update operator types
$scope.getOperatorTypes = function(resourceType){
return TypesFactory.getRuleOperatorTypes({"resourceType":resourceType});
}
//Update State types
$scope.updateStateTypes= function(resourceType){
$scope.stateTypes = TypesFactory.getStateTypes({"resourceType":resourceType});
}
//Update Payload operations
$scope.updatePayloadOperations= function(resourceType){
$scope.payloadOperations = TypesFactory.getPayloadOperations({"resourceType":resourceType});
}
//Update on condition type change
$scope.updateOnConditionTypChange = function(){
$scope.item.resourceType = '';
$scope.item.resourceId = '';
if($scope.item.conditionType === 'Threshold'
|| $scope.item.conditionType === 'Threshold range'
|| $scope.item.conditionType === 'Compare'
|| $scope.item.conditionType === 'String'){
$scope.item.resourceType = 'Sensor variable';
}
if($scope.item.conditionType === 'Threshold'){
$scope.sensorVariablesList = TypesFactory.getSensorVariables({"metricType":"Double"});
$scope.ruleOperatorTypes = TypesFactory.getRuleOperatorTypes({"conditionType":$scope.item.conditionType});
$scope.ruleThresholdDataTypes = TypesFactory.getRuleThresholdDataTypes({"resourceType":$scope.item.resourceType});
$scope.item.operator = '';
$scope.item.dataType = '';
$scope.item.data = '';
}else if($scope.item.conditionType === 'Threshold range'){
$scope.sensorVariablesList = TypesFactory.getSensorVariables({"metricType":"Double"});
$scope.item.inRange = true;
$scope.item.includeOperatorLow = true;
$scope.item.includeOperatorHigh = true;
$scope.item.thresholdLow = '';
$scope.item.thresholdHigh = '';
}else if($scope.item.conditionType === 'Compare'){
$scope.sensorVariablesList = TypesFactory.getSensorVariables({"metricType":"Double"});
$scope.ruleOperatorTypes = TypesFactory.getRuleOperatorTypes({"conditionType":$scope.item.conditionType});
$scope.item.operator = '';
$scope.item.data2Multiplier = '';
$scope.item.data2ResourceId = '';
$scope.item.data2ResourceType = 'Sensor variable';
}else if($scope.item.conditionType === 'State'){
$scope.resourceTypes = TypesFactory.getResourceTypes({"conditionType":$scope.item.conditionType});
$scope.ruleOperatorTypes = TypesFactory.getRuleOperatorTypes({"conditionType":$scope.item.conditionType});
$scope.item.operator = '';
$scope.item.state = '';
}else if($scope.item.conditionType === 'String'){
$scope.sensorVariablesList = TypesFactory.getSensorVariables();
$scope.ruleOperatorTypes = TypesFactory.getRuleOperatorTypes({"conditionType":$scope.item.conditionType});
$scope.item.ignoreCase = true;
$scope.item.operator = '';
$scope.item.pattern = '';
}else if($scope.item.conditionType === 'Script'){
$scope.scriptsList = ScriptsFactory.getAllLessInfo({"type":"Condition"});
$scope.item.resourceId = -1;
$scope.item.resourceType = 'Script';
}
}
if($stateParams.id){
RulesFactory.get({"id":$stateParams.id},function(response) {
$scope.item = response;
if($scope.item.conditionType === 'Threshold'){
$scope.sensorVariablesList = TypesFactory.getSensorVariables({"metricType":"Double"});
$scope.ruleOperatorTypes = TypesFactory.getRuleOperatorTypes({"conditionType":$scope.item.conditionType});
$scope.ruleThresholdDataTypes = TypesFactory.getRuleThresholdDataTypes({"resourceType":$scope.item.resourceType});
}else if($scope.item.conditionType === 'Threshold range'){
$scope.sensorVariablesList = TypesFactory.getSensorVariables({"metricType":"Double"});
}else if($scope.item.conditionType === 'Compare'){
$scope.sensorVariablesList = TypesFactory.getSensorVariables({"metricType":"Double"});
$scope.ruleOperatorTypes = TypesFactory.getRuleOperatorTypes({"conditionType":$scope.item.conditionType});
$scope.item.targetResourceType = 'Sensor variable';
}else if($scope.item.conditionType === 'State'){
$scope.resourceTypes = TypesFactory.getResourceTypes({"conditionType":$scope.item.conditionType});
$scope.ruleOperatorTypes = TypesFactory.getRuleOperatorTypes({"conditionType":$scope.item.conditionType});
$scope.updateStateTypes($scope.item.resourceType);
$scope.stateResourcesList = $scope.getResources($scope.item.resourceType, 'Binary');
}else if($scope.item.conditionType === 'String'){
$scope.sensorVariablesList = TypesFactory.getSensorVariables();
$scope.ruleOperatorTypes = TypesFactory.getRuleOperatorTypes({"conditionType":$scope.item.conditionType});
}else if($scope.item.conditionType === 'Script'){
$scope.scriptsList = ScriptsFactory.getAllLessInfo({"type":"Condition"});
$scope.item.altScriptBindings = angular.toJson(response.scriptBindings);
}
//Update dampening value
if($scope.item.dampeningType === 'Active time'){
var item = {};
$scope.cs.updateReadable($scope.item.dampening.activeTime, item);
$scope.item.dampening.activeTimeReadable = item.readableValue;
$scope.item.dampening.activeTimeConstant = item.timeConstant;
}
//Update re enable delay
if($scope.item.reEnable){
var item = {};
$scope.cs.updateReadable($scope.item.reEnableDelay, item);
$scope.item.reEnableDelayReadable = item.readableValue;
$scope.item.reEnableDelayConstant = item.timeConstant;
}
if($stateParams.action === 'clone'){
$stateParams.id = undefined;
$scope.item.id = undefined;
$scope.item.name = $scope.item.name + '-' + $filter('translate')('CLONE');
}
},function(error){
displayRestError.display(error);
});
}else{
$scope.item.altScriptBindings='{}';
}
//--------------pre load -----------
$scope.dampeningTypes = TypesFactory.getRuleDampeningTypes();
$scope.operations = TypesFactory.getOperations();
$scope.ruleConditionTypes = TypesFactory.getRuleConditionTypes();
//GUI page settings
if(!$stateParams.action || $stateParams.action !== 'clone'){
$scope.showHeaderUpdate = $stateParams.id;
}
$scope.headerStringAdd = $filter('translate')('ADD_RULE');
$scope.headerStringUpdate = $filter('translate')('UPDATE_RULE');
$scope.cancelButtonState = "rulesList"; //Cancel button url
$scope.saveProgress = false;
//$scope.isSettingChange = false;
$scope.save = function(){
//Update dampening active time
if($scope.item.dampeningType === 'Active time'){
$scope.item.dampening.activeTime = $scope.cs.getMilliseconds($scope.item.dampening.activeTimeReadable, $scope.item.dampening.activeTimeConstant);
}
//Update re enable delay
if($scope.item.reEnable){
$scope.item.reEnableDelay = $scope.cs.getMilliseconds($scope.item.reEnableDelayReadable, $scope.item.reEnableDelayConstant);
}
//Change string to JSON string
if($scope.item.conditionType === 'Script'){
$scope.item.scriptBindings = angular.fromJson(JSON.stringify(eval('('+$scope.item.altScriptBindings+')')));
}
$scope.saveProgress = true;
if($stateParams.id){
RulesFactory.update($scope.item,function(response) {
alertService.success($filter('translate')('ITEM_UPDATED_SUCCESSFULLY'));
$state.go("rulesList");
},function(error){
displayRestError.display(error);
$scope.saveProgress = false;
});
}else{
RulesFactory.create($scope.item,function(response) {
alertService.success($filter('translate')('ITEM_CREATED_SUCCESSFULLY'));
$state.go("rulesList");
},function(error){
displayRestError.display(error);
$scope.saveProgress = false;
});
}
}
});

271
www/controllers/scripts.js Normal file
View File

@@ -0,0 +1,271 @@
/*
* Copyright 2015-2018 Jeeva Kandasamy (jkandasa@gmail.com)
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
myControllerModule.controller('ScriptsController', function(alertService,
$scope, ScriptsFactory, $state, $uibModal, $stateParams, displayRestError, mchelper, CommonServices, $filter, $base64) {
//GUI page settings
$scope.headerStringList = $filter('translate')('SCRIPTS_DETAIL');
$scope.noItemsSystemMsg = $filter('translate')('NO_SCRIPTS_SETUP');
$scope.noItemsSystemIcon = "fa fa-code";
//load empty, configuration, etc.,
$scope.mchelper = mchelper;
$scope.filteredList=[];
//data query details
$scope.currentPage = 1;
$scope.query = CommonServices.getQuery();
$scope.queryResponse = {};
//Get min number
$scope.getMin = function(item1, item2){
return CommonServices.getMin(item1, item2);
};
if($stateParams.resourceType){
$scope.query.resourceType = $stateParams.resourceType;
$scope.query.resourceId = $stateParams.resourceId;
}
//get all items
$scope.getAllItems = function(){
ScriptsFactory.getAll($scope.query, function(response) {
$scope.queryResponse = response;
$scope.filteredList = $scope.queryResponse.data;
$scope.filterConfig.resultsCount = $scope.queryResponse.query.filteredCount;
},function(error){
displayRestError.display(error);
});
}
//Hold all the selected item ids
$scope.itemIds = [];
$scope.selectAllItems = function(){
CommonServices.selectAllItems($scope, 'name');
};
$scope.selectItem = function(item){
CommonServices.selectItem($scope, item, 'name');
};
//On page change
$scope.pageChanged = function(newPage){
CommonServices.updatePageChange($scope, newPage);
};
//Filter change method
var filterChange = function (filters) {
//Reset filter fields and update items
CommonServices.updateFiltersChange($scope, filters);
};
$scope.filterConfig = {
fields: [
{
id: 'name',
title: $filter('translate')('NAME'),
placeholder: $filter('translate')('FILTER_BY_NAME'),
filterType: 'text'
},
{
id: 'type',
title: $filter('translate')('TYPE'),
placeholder: $filter('translate')('FILTER_BY_TYPE'),
filterType: 'select',
filterValues: ['Condition','Operation'],
},
{
id: 'extension',
title: $filter('translate')('EXTENSION'),
placeholder: $filter('translate')('FILTER_BY_EXTENSION'),
filterType: 'select',
filterValues: ['js','groovy','py','rb'],
}
],
resultsCount: $scope.filteredList.length,
appliedFilters: [],
onFilterChange: filterChange
};
//Sort columns
var sortChange = function (sortId, isAscending) {
//Reset sort type and update items
CommonServices.updateSortChange($scope, sortId, isAscending);
};
$scope.sortConfig = {
fields: [
{
id: 'name',
title: $filter('translate')('NAME'),
sortType: 'text'
}
],
onSortChange: sortChange
};
//Delete item(s)
$scope.delete = function (size) {
var modalInstance = $uibModal.open({
templateUrl: 'partials/common-html/delete-modal.html',
controller: 'ControllerDeleteModal',
size: size,
resolve: {}
});
modalInstance.result.then(function () {
ScriptsFactory.deleteIds($scope.itemIds, function(response) {
alertService.success($filter('translate')('ITEMS_DELETED_SUCCESSFULLY'));
//Update display table
$scope.getAllItems();
$scope.itemIds = [];
},function(error){
displayRestError.display(error);
});
}),
function () {
//console.log('Modal dismissed at: ' + new Date());
}
};
//Edit item
$scope.edit = function () {
if($scope.itemIds.length == 1){
$state.go("scriptsAddEdit",{'name':$base64.encode($scope.itemIds[0])});
}
};
/*
//execute item
$scope.runNow = function () {
if($scope.itemIds.length == 1){
ScriptsFactory.runNow({"script":$scope.itemIds[0]}, function(response) {
alertService.success('Result printed in console also.<br>'+angular.toJson(response));
console.log('Script['+$scope.itemIds[0]+'] result:\n'+angular.toJson(response));
$scope.itemIds = [];
},function(error){
displayRestError.display(error);
});
}
};
*/
//Execute item
$scope.runNow = function (size) {
if($scope.itemIds.length != 1){
return;
}
var modalInstance = $uibModal.open({
templateUrl: 'partials/scripts/run-now-modal.html',
controller: 'ControllerScriptRunNowModal',
size: size,
resolve: {itemId: function () {return $scope.itemIds[0]}}
});
modalInstance.result.then(function () {
//Nothing to do...
}),
function () {
//console.log('Modal dismissed at: ' + new Date());
}
};
});
//Script run now Modal
myControllerModule.controller('ControllerScriptRunNowModal', function ($scope, $uibModalInstance, $filter, CommonServices, ScriptsFactory, itemId) {
$scope.header = $filter('translate')('RUN_NOW');
$scope.cs = CommonServices;
$scope.request = {};
$scope.request.script = itemId;
$scope.request.bindings = '{ }';
//$uibModalInstance.close();
$scope.runNow = function() {
$scope.runningInProgress = true;
$scope.request.scriptBindings = angular.fromJson(JSON.stringify(eval('('+$scope.request.bindings+')')));
ScriptsFactory.runNow($scope.request, function(response) {
$scope.scriptResult = angular.toJson(response, true);
$scope.runningInProgress = false;
},function(error){
if(error.data.errorMessage){
$scope.scriptResult = error.data.errorMessage;
}else{
$scope.scriptResult = angular.toJson(error.data);
}
$scope.scriptResult = angular.toJson(error.data, true);
$scope.runningInProgress = false;
displayRestError.display(error);
});
};
$scope.cancel = function () { $uibModalInstance.dismiss('cancel'); }
});
//Add Edit script controller
myControllerModule.controller('ScriptsControllerAddEdit', function ($scope, $stateParams, $state,
ScriptsFactory, mchelper, alertService, displayRestError, $filter, CommonServices, $base64) {
$scope.mchelper = mchelper;
$scope.item = {};
$scope.cs = CommonServices;
$scope.showData = false;
$scope.editMode = false;
if($stateParams.name){
$scope.editMode = true;
ScriptsFactory.get({"name":$base64.decode($stateParams.name)},function(response) {
$scope.item = response;
$scope.showData = true;
},function(error){
displayRestError.display(error);
$scope.showData = true;
});
}else{
$scope.showData = true;
}
//Read File and put it in textarea
$scope.displayFileContents = function(contents) {
$scope.item.data = contents;
};
$scope.editorOptions = {
lineWrapping : true,
lineNumbers: true,
readOnly: 'nocursor',
mode: 'xml',
};
//GUI page settings
$scope.showHeaderUpdate = $stateParams.name;
$scope.headerStringAdd = $filter('translate')('ADD_SCRIPT');
$scope.headerStringUpdate = $filter('translate')('UPDATE_SCRIPT');
$scope.cancelButtonState = "scriptsList"; //Cancel button url
$scope.saveProgress = false;
$scope.save = function(){
$scope.saveProgress = true;
ScriptsFactory.upload($scope.item, function(response) {
alertService.success($filter('translate')('ITEM_UPDATED_SUCCESSFULLY'));
$state.go("scriptsList");
},function(error){
displayRestError.display(error);
$scope.saveProgress = false;
});
}
});

View File

@@ -0,0 +1,47 @@
/*
* Copyright 2015-2018 Jeeva Kandasamy (jkandasa@gmail.com)
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
myControllerModule.controller('SendRawMessageController', function(alertService, $scope, displayRestError, TypesFactory, SensorsFactory, $filter, CommonServices) {
//GUI page settings
$scope.headerStringAdd = $filter('translate')('SEND_RAW_MESSAGE');
$scope.cancelButtonState = "sendRawMessage"; //Cancel button state
$scope.sendProgress = false;
$scope.cs = CommonServices;
$scope.message = {};
//Get subtypes
$scope.updateSubTypes = function(type){
$scope.subTypes = TypesFactory.getMessageSubTypes({"messageType":type});
};
//Pre load
$scope.gateways = CommonServices.getResources("Gateway");
$scope.messageTypes = TypesFactory.getMessageTypes();
//Send raw message
$scope.send = function(){
$scope.saveProgress = true;
SensorsFactory.sendRawMessage($scope.message, function(response) {
alertService.success($filter('translate')('ITEM_UPDATED_SUCCESSFULLY'));
$scope.saveProgress = false;
},function(error){
displayRestError.display(error);
$scope.saveProgress = false;
});
};
});

View File

@@ -0,0 +1,251 @@
/*
* Copyright 2015-2018 Jeeva Kandasamy (jkandasa@gmail.com)
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
myControllerModule.controller('SensorsActionControllerList', function(
alertService, $scope, SensorsFactory, TypesFactory, NodesFactory, SettingsFactory, $uibModal, displayRestError, mchelper, CommonServices, pfViewUtils, $filter, $window, $interval) {
//GUI page settings
//$scope.headerStringList = "Sesnors detail";
$scope.noItemsSystemMsg = $filter('translate')('NO_SENSORS_SETUP');
$scope.noItemsSystemIcon = "fa fa-eye";
//load empty, configuration, etc.,
$scope.mchelper = mchelper;
$scope.filteredList=[];
$scope.cs = CommonServices;
//data query details
$scope.currentPage = 1;
$scope.query = CommonServices.getQuery();
$scope.queryResponse = {};
//Get min number
$scope.getMin = function(item1, item2){
return CommonServices.getMin(item1, item2);
};
//Stop if an request sent already
var updateInprogress = false;
//get all items
$scope.getAllItems = function(hideLoading){
if(updateInprogress){
return;
}
updateInprogress = true;
if(!hideLoading){
$scope.dataLoading = true;
}
SensorsFactory.getAll($scope.query, function(response) {
$scope.queryResponse = response;
$scope.filteredList = $scope.queryResponse.data;
$scope.filterConfig.resultsCount = $scope.queryResponse.query.filteredCount;
$scope.dataLoading = false;
updateInprogress = false;
},function(error){
displayRestError.display(error);
$scope.dataLoading = false;
updateInprogress = false;
});
}
//On page change
$scope.pageChanged = function(newPage){
CommonServices.updatePageChange($scope, newPage);
};
//Filter change method
var filterChange = function (filters) {
//Reset filter fields and update items
CommonServices.updateFiltersChange($scope, filters);
};
$scope.filterConfig = {
fields: [
{
id: 'name',
title: $filter('translate')('SENSOR_NAME'),
placeholder: $filter('translate')('FILTER_BY_SENSOR_NAME'),
filterType: 'text'
},
{
id: 'nodeId',
title: $filter('translate')('NODE_ID'),
placeholder: $filter('translate')('FILTER_BY_NODE_ID'),
filterType: 'text'
},
{
id: 'sensorId',
title: $filter('translate')('SENSOR_ID'),
placeholder: $filter('translate')('FILTER_BY_SENSOR_ID'),
filterType: 'text'
},
{
id: 'type',
title: $filter('translate')('TYPE'),
placeholder: $filter('translate')('FILTER_BY_TYPE'),
filterType: 'text',
}
],
resultsCount: $scope.filteredList.length,
appliedFilters: [],
onFilterChange: filterChange
};
//View selection
var viewSelected = function(viewId) {
mchelper.userSettings.actionBoardView = viewId;
SettingsFactory.saveUserSettings(mchelper.userSettings);
CommonServices.saveMchelper(mchelper);
if(viewId === 'cardView'){
$scope.query.pageLimit = 12;
$scope.tooltipPlacement = 'top';
}else if(viewId === 'listView'){
$scope.query.pageLimit = 10;
$scope.tooltipPlacement = 'left';
}
$scope.currentPage = 1;
$scope.query.page=1;
$scope.getAllItems();
$scope.viewType = viewId;
};
//View configuration
$scope.viewsConfig = {
views: [pfViewUtils.getListView(), pfViewUtils.getCardView()],
onViewSelect: viewSelected,
};
//Sort columns
var sortChange = function (sortId, isAscending) {
//Reset sort type and update items
CommonServices.updateSortChange($scope, sortId, isAscending);
};
$scope.sortConfig = {
fields: [
{
id: 'lastSeen',
title: $filter('translate')('LAST_SEEN'),
sortType: 'text'
},{
id: 'name',
title: $filter('translate')('SENSOR_NAME'),
sortType: 'text'
},
{
id: 'nodeId',
title: $filter('translate')('NODE_ID'),
sortType: 'text'
},
{
id: 'sensorId',
title: $filter('translate')('SENSOR_ID'),
sortType: 'number'
},
{
id: 'type',
title: $filter('translate')('TYPE'),
sortType: 'text'
}
],
onSortChange: sortChange,
isAscending: false,
};
// Item tool bar config
$scope.sensorsToolbarConfig = {
viewsConfig: $scope.viewsConfig,
filterConfig: $scope.filterConfig,
sortConfig: $scope.sortConfig,
};
//refresh sensor
$scope.refreshSensor = function(sensor){
SensorsFactory.get({"id":sensor.id}, function(response) {
var newSensor = response;
sensor.lastSeen = newSensor.lastSeen;
sensor.variables = newSensor.variables;
},function(error){
displayRestError.display(error);
});
};
//Update Variable / Send Payload
$scope.updateVariable = function(variable){
SensorsFactory.updateVariable(variable, function(){
//update Success
},function(error){
displayRestError.display(error);
});
};
//HVAC heater options - HVAC flow state
$scope.hvacOptionsFlowState = TypesFactory.getHvacOptionsFlowState();
//HVAC heater options - HVAC flow mode
$scope.hvacOptionsFlowMode = TypesFactory.getHvacOptionsFlowMode();
//HVAC heater options - HVAC fan speed
$scope.hvacOptionsFanSpeed = TypesFactory.getHvacOptionsFanSpeed();
//Defined variable types list
$scope.definedVariableTypes = CommonServices.getSensorVariablesKnownList();
//update rgba color
$scope.updateRgba = function(variable){
variable.value = CommonServices.rgba2hex(variable.rgba);
$scope.updateVariable(variable);
};
//Pre load
$scope.viewsConfig.currentView = mchelper.userSettings.actionBoardView;
$scope.tooltipPlacement = 'left';
$scope.tooltipEnabled = true;
$scope.viewType = $scope.viewsConfig.currentView;
//Update list table
//getAllItems();
//fix for layout tiles
var isInnterWidth = function(minWidth, maxWidth, value){
return (minWidth <= value) && (maxWidth >= value);
};
$scope.$watch(function(){
return $window.innerWidth;
}, function(value) {
$scope.colLg3 = isInnterWidth(1200,1600, value);
});
function updatePage(){
$scope.getAllItems(true);
};
// global page refresh
var promise = $interval(updatePage, mchelper.cfg.globalPageRefreshTime);
// cancel interval on scope destroy
$scope.$on('$destroy', function(){
$interval.cancel(promise);
});
});

595
www/controllers/sensors.js Normal file
View File

@@ -0,0 +1,595 @@
/*
* Copyright 2015-2018 Jeeva Kandasamy (jkandasa@gmail.com)
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
myControllerModule.controller('SensorsController', function(alertService,
$scope, SensorsFactory, TypesFactory, NodesFactory, $state, $uibModal, displayRestError, mchelper, CommonServices, $stateParams, $filter, $interval) {
//GUI page settings
$scope.headerStringList = $filter('translate')('SENSORS_DETAIL');
$scope.noItemsSystemMsg = $filter('translate')('NO_SENSORS_SETUP');
$scope.noItemsSystemIcon = "fa fa-eye";
//load empty, configuration, etc.,
$scope.mchelper = mchelper;
$scope.filteredList=[];
//data query details
$scope.currentPage = 1;
$scope.query = CommonServices.getQuery();
$scope.queryResponse = {};
//Get min number
$scope.getMin = function(item1, item2){
return CommonServices.getMin(item1, item2);
};
if($stateParams.nodeId){
//$scope.nodeId = $stateParams.nodeId;
$scope.query.nodeId = $stateParams.nodeId;
}
$scope.isRunning = false;
//get all Sensors
$scope.getAllItems = function(){
if($scope.isRunning){
return;
}
$scope.isRunning = true;
SensorsFactory.getAll($scope.query, function(response) {
$scope.queryResponse = response;
$scope.filteredList = $scope.queryResponse.data;
$scope.filterConfig.resultsCount = $scope.queryResponse.query.filteredCount;
$scope.isRunning = false;
},function(error){
displayRestError.display(error);
$scope.isRunning = false;
});
}
//Hold all the selected item ids
$scope.itemIds = [];
$scope.selectAllItems = function(){
CommonServices.selectAllItems($scope);
};
$scope.selectItem = function(item){
CommonServices.selectItem($scope, item);
};
//On page change
$scope.pageChanged = function(newPage){
CommonServices.updatePageChange($scope, newPage);
};
//Filter change method
var filterChange = function (filters) {
//Reset filter fields and update items
CommonServices.updateFiltersChange($scope, filters);
};
$scope.filterConfig = {
fields: [
{
id: 'name',
title: $filter('translate')('NAME'),
placeholder: $filter('translate')('FILTER_BY_NAME'),
filterType: 'text'
},
{
id: 'sensorId',
title: $filter('translate')('SENSOR_ID'),
placeholder: $filter('translate')('FILTER_BY_SENSOR_ID'),
filterType: 'integer',
},
{
id: 'nodeName',
title: $filter('translate')('NODE_NAME'),
placeholder: $filter('translate')('FILTER_BY_NAME'),
filterType: 'text',
},
{
id: 'nodeEui',
title: $filter('translate')('NODE_EUI'),
placeholder: $filter('translate')('FILTER_BY_EUI'),
filterType: 'text',
},
{
id: 'type',
title: $filter('translate')('TYPE'),
placeholder: $filter('translate')('FILTER_BY_TYPE'),
filterType: 'text',
},
{
id: 'variableTypes',
title: $filter('translate')('VARIABLE_TYPES'),
placeholder: $filter('translate')('FILTER_BY_VARIABLE_TYPES'),
filterType: 'text',
}
],
resultsCount: $scope.filteredList.length,
appliedFilters: [],
onFilterChange: filterChange
};
//Sort columns
var sortChange = function (sortId, isAscending) {
//Reset sort type and update items
CommonServices.updateSortChange($scope, sortId, isAscending);
};
$scope.sortConfig = {
fields: [
{
id: 'name',
title: $filter('translate')('NAME'),
sortType: 'text'
},
{
id: 'sensorId',
title: $filter('translate')('SENSOR_ID'),
sortType: 'number'
},
{
id: 'type',
title: $filter('translate')('TYPE'),
sortType: 'text'
},
{
id: 'nodeEui',
title: $filter('translate')('NODE_EUI'),
sortType: 'text'
},
{
id: 'nodeName',
title: $filter('translate')('NODE_NAME'),
sortType: 'text'
},
{
id: 'lastSeen',
title: $filter('translate')('LAST_SEEN'),
sortType: 'text'
}
],
onSortChange: sortChange
};
//Edit item
$scope.edit = function () {
if($scope.itemIds.length == 1){
$state.go("sensorsAddEdit", {'id':$scope.itemIds[0]});
}
};
//Delete item(s)
$scope.delete = function (size) {
var modalInstance = $uibModal.open({
templateUrl: 'partials/common-html/delete-modal.html',
controller: 'ControllerDeleteModal',
size: size,
resolve: {}
});
modalInstance.result.then(function () {
SensorsFactory.deleteIds($scope.itemIds, function(response) {
alertService.success($filter('translate')('ITEMS_DELETED_SUCCESSFULLY'));
//Update display table
$scope.getAllItems();
$scope.itemIds = [];
},function(error){
displayRestError.display(error);
});
}),
function () {
//console.log('Modal dismissed at: ' + new Date());
}
};
//Get sensor variable types
$scope.getSensorVariableTypes = function(variables){
var types = [];
angular.forEach(variables, function(variable){
types.push(variable.name ? variable.name : variable.type.locale);
});
return types.join(', ');
}
// global page refresh
var promise = $interval($scope.getAllItems, mchelper.cfg.globalPageRefreshTime);
// cancel interval on scope destroy
$scope.$on('$destroy', function(){
$interval.cancel(promise);
});
});
//Add Edit sensor controller
myControllerModule.controller('SensorsControllerAddEdit', function ($scope, $stateParams, $state, GatewaysFactory, NodesFactory, SensorsFactory, TypesFactory, mchelper, alertService, displayRestError, $filter) {
$scope.mchelper = mchelper;
$scope.sensor = {};
$scope.sensor.node = {};
$scope.sensor.node.gateway = {};
$scope.nodes = {};
$scope.sensorVariableTypes = {};
if($stateParams.id){
SensorsFactory.get({"sensorId":$stateParams.id},function(response) {
$scope.sensor = response;
$scope.sensorVariableTypes = TypesFactory.getSensorVariableTypes({'sensorType': $scope.sensor.type.en, 'sensorId': $scope.sensor.id});
},function(error){
displayRestError.display(error);
});
}
$scope.sensorTypes = TypesFactory.getSensorTypes();
$scope.nodes = TypesFactory.getNodes();
$scope.rooms = TypesFactory.getRooms();
/*
$scope.updateNodes= function(gatewayId){
$scope.nodes = TypesFactory.getNodes({"gatewayId":gatewayId});
}
*/
$scope.refreshVariableTypes = function(sensorType){
$scope.sensorVariableTypes = TypesFactory.getSensorVariableTypes({'sensorType': sensorType});
}
//GUI page settings
$scope.showHeaderUpdate = $stateParams.id;
$scope.headerStringAdd = $filter('translate')('ADD_SENSOR');
$scope.headerStringUpdate = $filter('translate')('UPDATE_SENSOR');
$scope.cancelButtonState = "sensorsList"; //Cancel button state
$scope.saveProgress = false;
//$scope.isSettingChange = false;
$scope.save = function(){
$scope.saveProgress = true;
//TODO: for now REST request fails if we send with 'lastSeen'. drop this here
$scope.sensor.lastSeen = null;
if($stateParams.id){
SensorsFactory.update($scope.sensor,function(response) {
alertService.success($filter('translate')('ITEM_UPDATED_SUCCESSFULLY'));
$state.go("sensorsList");
},function(error){
displayRestError.display(error);
$scope.saveProgress = false;
});
}else{
SensorsFactory.create($scope.sensor,function(response) {
alertService.success($filter('translate')('ITEM_CREATED_SUCCESSFULLY'));
$state.go("sensorsList");
},function(error){
displayRestError.display(error);
$scope.saveProgress = false;
});
}
}
});
//item Detail
myControllerModule.controller('SensorsControllerDetail', function ($scope, $stateParams, mchelper, SensorsFactory,
MetricsFactory, $filter, CommonServices, TypesFactory, $timeout, $window, displayRestError, $interval) {
//Load mchelper variables to this scope
$scope.mchelper = mchelper;
$scope.node = {};
$scope.headerStringList = $filter('translate')('SENSOR_DETAILS');
$scope.cs = CommonServices;
$scope.item = SensorsFactory.get({"id":$stateParams.id});
$scope.chartOptions = {
chart: {
type: 'lineChart',
noErrorCheck: true,
height: 270,
margin : {
top: 5,
right: 20,
bottom: 60,
left: 80
},
color: ["#2ca02c","#1f77b4", "#ff7f0e"],
noData: $filter('translate')('NO_DATA_AVAILABLE'),
x: function(d){return d[0];},
y: function(d){return d[1];},
useVoronoi: false,
clipEdge: false,
useInteractiveGuideline: true,
xAxis: {
showMaxMin: false,
tickFormat: function(d) {
return d3.time.format('hh:mm a')(new Date(d))
},
//axisLabel: 'Timestamp',
rotateLabels: -20
},
yAxis: {
tickFormat: function(d){
return d3.format(',.2f')(d);
},
axisLabelDistance: -10,
//axisLabel: ''
},
},
title: {
enable: false,
text: 'Title'
}
};
//pre select, should be updated from server
TypesFactory.getMetricsSettings(function(response){
$scope.metricsSettings = response;
$scope.chartEnableMinMax = $scope.metricsSettings.enabledMinMax;
$scope.chartFromTimestamp = $scope.metricsSettings.defaultTimeRange.toString();
MetricsFactory.getMetricsData({"sensorId":$stateParams.id, "withMinMax":$scope.chartEnableMinMax, "start": new Date().getTime() - $scope.chartFromTimestamp},function(response){
$scope.chartData = response;
$scope.fetching = false;
});
});
$scope.tooltipPlacement = 'top';
$scope.chartTimeFormat = mchelper.cfg.dateFormat;
$scope.chartOptions.chart.xAxis.tickFormat = function(d) {return $filter('date')(d, $scope.chartTimeFormat, mchelper.cfg.timezone)};
$scope.updateChart = function(){
MetricsFactory.getMetricsData({"sensorId":$stateParams.id, "withMinMax":$scope.chartEnableMinMax, "start": new Date().getTime() - $scope.chartFromTimestamp}, function(resource){
//$scope.chartData = resource;
resource.forEach(function(item) {
$scope.chartData.forEach(function(itemLocal) {
if(itemLocal.id === item.id){
itemLocal.chartData = item.chartData;
//Update display time format
$scope.chartTimeFormat = item.timeFormat;
}
});
});
});
}
$scope.resourceCount = MetricsFactory.getResourceCount({"resourceType":"Sensor", "resourceId":$stateParams.id});
$scope.updateChartOptions = function(chData){
var chOptions = angular.copy($scope.chartOptions);
chOptions.chart.type = chData.chartType;
chOptions.chart.interpolate = chData.chartInterpolate;
//Update margins
chOptions.chart.margin.left = chData.marginLeft;
chOptions.chart.margin.right = chData.marginRight;
chOptions.chart.margin.top = chData.marginTop;
chOptions.chart.margin.bottom = chData.marginBottom;
//Update display time format
$scope.chartTimeFormat = chData.timeFormat;
if(chData.dataType === 'Double'){
chOptions.chart.yAxis.tickFormat = function(d){return d3.format('.02f')(d) + ' ' + chData.unit};
}else if(chData.dataType === 'Binary' || chData.dataType === 'Counter'){
chOptions.chart.yAxis.tickFormat = function(d){return d3.format('.0f')(d)};
}
chOptions.title.text = chData.variableType;
return chOptions;
}
//Update Variable / Send Payload
$scope.updateVariable = function(variable){
SensorsFactory.updateVariable(variable, function(){
//update Success
},function(error){
displayRestError.display(error);
});
};
//update variable unit
$scope.updateVariableUnit = function(variable){
SensorsFactory.updateVariableUnit(variable, function(){
//update Success
},function(error){
displayRestError.display(error);
});
}
//HVAC heater options - HVAC flow state
$scope.hvacOptionsFlowState = TypesFactory.getHvacOptionsFlowState();
//HVAC heater options - HVAC flow mode
$scope.hvacOptionsFlowMode = TypesFactory.getHvacOptionsFlowMode();
//HVAC heater options - HVAC fan speed
$scope.hvacOptionsFanSpeed = TypesFactory.getHvacOptionsFanSpeed();
//Defined variable types list
$scope.definedVariableTypes = CommonServices.getSensorVariablesKnownList();
//Hide variable names
$scope.hideVariableName=true;
//update rgba color
$scope.updateRgba = function(variable){
variable.value = CommonServices.rgba2hex(variable.rgba);
$scope.updateVariable(variable);
};
//Graph resize issue, see: https://github.com/krispo/angular-nvd3/issues/40
$scope.$watch('fetching', function() {
if(!$scope.fetching) {
$timeout(function() {
$window.dispatchEvent(new Event('resize'));
$scope.fetching = true;
}, 1000);
}
});
//Get sensor variable types
$scope.getSensorVariableTypes = function(variables){
var types = [];
angular.forEach(variables, function(variable){
types.push(variable.type.locale);
});
return types.join(', ');
}
//Update data for N seconds once
var updatePageData = function(){
$scope.item = SensorsFactory.get({"id":$stateParams.id}); //This line introduces flickering on refresh
$scope.updateChart();
}
// global page refresh
var promise = $interval(updatePageData, mchelper.cfg.globalPageRefreshTime);
// cancel interval on scope destroy
$scope.$on('$destroy', function(){
$interval.cancel(promise);
});
});
//Purge sensor variable controller
myControllerModule.controller('SensorVariableControllerPurge', function ($scope, $stateParams, $state, SensorsFactory, TypesFactory,
mchelper, alertService, displayRestError, $filter, CommonServices, $uibModal) {
$scope.mchelper = mchelper;
$scope.cs = CommonServices;
$scope.sensorVariable = {};
$scope.item = {};
$scope.metricTypes = {};
$scope.unitTypes = {};
$scope.orgSvar = {};
if($stateParams.id){
SensorsFactory.getVariable({"id":$stateParams.id},function(response) {
$scope.sensorVariable = response;
$scope.orgSvar = angular.copy(response);
$scope.item.id = $scope.sensorVariable.id;
$scope.item.depthSearch = false;
},function(error){
displayRestError.display(error);
});
}
//GUI page settings
$scope.headerStringAdd = $filter('translate')('PURGE_SENSOR_VARIABLE');
$scope.cancelButtonState = "sensorsDetail({id: sensorVariable.sensorId})"; //Cancel button state
$scope.saveProgress = false;
$scope.saveButtonName = $filter('translate')('PURGE');
$scope.savingButtonName = $filter('translate')('PURGING');
$scope.saveButtonTooltip = $filter('translate')('PURGE_WARNING');
//Convert as display string
$scope.getDateTimeDisplayFormat = function (newDate) {
return $filter('date')(newDate, mchelper.cfg.dateFormat, mchelper.cfg.timezone);
};
//Save data - here it's purge
$scope.save = function(){
//Update time range from/to
if($scope.purgeFrom){
$scope.item.start = moment($scope.purgeFrom).format('YYYY-MM-DDTHH:mm:ss');
}
if($scope.purgeTo){
$scope.item.end = moment($scope.purgeTo).format('YYYY-MM-DDTHH:mm:ss');
}
$scope.saveProgress = true;
if($stateParams.id){
SensorsFactory.purgeVariable($scope.item,function(response) {
alertService.success($filter('translate')('PURGE_DONE_SUCCESSFULLY'));
$state.go("sensorsDetail", {"id": $scope.sensorVariable.sensorId});
},function(error){
displayRestError.display(error);
$scope.saveProgress = false;
});
}
}
});
//Edit sensor variable controller
myControllerModule.controller('SensorVariableControllerEdit', function ($scope, $stateParams, $state, SensorsFactory, TypesFactory,
mchelper, alertService, displayRestError, $filter, CommonServices, $uibModal) {
$scope.mchelper = mchelper;
$scope.cs = CommonServices;
$scope.sensorVariable = {};
$scope.metricTypes = {};
$scope.unitTypes = {};
$scope.orgSvar = {};
if($stateParams.id){
SensorsFactory.getVariable({"id":$stateParams.id},function(response) {
$scope.sensorVariable = response;
$scope.orgSvar = angular.copy(response);
},function(error){
displayRestError.display(error);
});
}
//GUI page settings
$scope.showHeaderUpdate = $stateParams.id;
$scope.headerStringAdd = $filter('translate')('ADD_SENSOR_VARIABLE');
$scope.headerStringUpdate = $filter('translate')('UPDATE_SENSOR_VARIABLE');
$scope.cancelButtonState = "sensorsDetail({id: sensorVariable.sensorId})"; //Cancel button state
$scope.saveProgress = false;
$scope.unitTypes = TypesFactory.getUnitTypes();
$scope.metricTypes = TypesFactory.getMetricTypes();
$scope.saveFinal = function(){
$scope.saveProgress = true;
if($stateParams.id){
SensorsFactory.updateVariableConfig($scope.sensorVariable,function(response) {
alertService.success($filter('translate')('ITEM_UPDATED_SUCCESSFULLY'));
$state.go("sensorsDetail", {"id": $scope.sensorVariable.sensorId});
},function(error){
displayRestError.display(error);
$scope.saveProgress = false;
});
}
}
//Show update warning
$scope.save = function (size) {
if($scope.orgSvar.metricType === $scope.sensorVariable.metricType){
$scope.saveFinal();
}else{
var modalInstance = $uibModal.open({
templateUrl: 'partials/common-html/edit-confirmation-modal.html',
controller: 'SensorVariableUpdateWarnController',
size: size,
resolve: {}
});
modalInstance.result.then(function () {
$scope.saveFinal();
}),
function () {
//console.log('Modal dismissed at: ' + new Date());
}
}
};
});
//sensor variable change Modal
myControllerModule.controller('SensorVariableUpdateWarnController', function ($scope, $uibModalInstance, $filter) {
$scope.header = $filter('translate')('S_VARIABLE_DIALOG_TITLE');
$scope.message = $filter('translate')('S_VARIABLE_DIALOG_CONFIRMATION_MSG');
$scope.continute = function() {$uibModalInstance.close(); };
$scope.cancel = function () { $uibModalInstance.dismiss('cancel'); }
});

532
www/controllers/settings.js Normal file
View File

@@ -0,0 +1,532 @@
/*
* Copyright 2015-2018 Jeeva Kandasamy (jkandasa@gmail.com)
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
myControllerModule.controller('SettingsSystemController', function(alertService, $scope, $filter, SettingsFactory,
StatusFactory, TypesFactory, displayRestError, mchelper, $translate, $cookieStore, CommonServices, NavigatorGeolocation, $uibModal) {
//config, language, user, etc.,
$scope.mchelper = mchelper;
$scope.cs = CommonServices;
//editable settings
$scope.editEnable = {};
$scope.saveProgress = {};
//settings location details, sunrise, sunset
$scope.updateSettingsLocation = function(){
$scope.locationSettings = SettingsFactory.getLocation();
};
//settings MyController
$scope.updateSettingsController = function(){
SettingsFactory.getController(function(resource){
$scope.controllerSettings = resource;
$scope.aliveCheckMinutes = $scope.controllerSettings.aliveCheckInterval / 60000;
$scope.globalPageRefreshTime = $scope.controllerSettings.globalPageRefreshTime / 1000;
$scope.executeDiscoverMinutes = $scope.controllerSettings.executeDiscoverInterval / 60000;
$scope.resourcesLogsRetentionDurationMinutes = $scope.controllerSettings.resourcesLogsRetentionDuration / 60000;
});
};
//Pre-load
$scope.locationSettings = {};
$scope.controllerSettings = {};
//get log levels
$scope.logLevels = TypesFactory.getResourceLogsLogLevels();
//get languages
$scope.languages = TypesFactory.getLanguages();
$scope.updateSettingsLocation();
$scope.updateSettingsController();
$scope.aliveCheckMinutes = null;
$scope.globalPageRefreshTime = null;
//Get current location
$scope.updateGeoLocation = function(){
NavigatorGeolocation.getCurrentPosition()
.then(function(position) {
$scope.locationSettings.latitude = $filter('number')(position.coords.latitude, 4);
$scope.locationSettings.longitude = $filter('number')(position.coords.longitude, 4);
});
};
//Save location
$scope.saveLocation = function(){
$scope.saveProgress.location = true;
SettingsFactory.saveLocation($scope.locationSettings,function(response) {
alertService.success($filter('translate')('UPDATED_SUCCESSFULLY'));
$scope.saveProgress.location = false;
$scope.updateSettingsLocation();
$scope.editEnable.location = false;
},function(error){
displayRestError.display(error);
$scope.saveProgress.location = false;
});
};
//Save controller
$scope.saveController = function(){
$scope.saveProgress.controller = true;
$scope.controllerSettings.aliveCheckInterval = $scope.aliveCheckMinutes * 60000;
$scope.controllerSettings.executeDiscoverInterval = $scope.executeDiscoverMinutes * 60000;
$scope.controllerSettings.resourcesLogsRetentionDuration = $scope.resourcesLogsRetentionDurationMinutes * 60000;
$scope.controllerSettings.globalPageRefreshTime = $scope.globalPageRefreshTime * 1000;
SettingsFactory.saveController($scope.controllerSettings,function(response) {
StatusFactory.getConfig(function(response) {
mchelper.cfg = response;//Update config
//Update language
$translate.use(mchelper.cfg.languageId);
//Store all the configurations locally
$cookieStore.put('mchelper', mchelper);
});
alertService.success($filter('translate')('UPDATED_SUCCESSFULLY'));
$scope.saveProgress.controller = false;
$scope.updateSettingsController();
$scope.editEnable.controller = false;
},function(error){
displayRestError.display(error);
$scope.saveProgress.controller = false;
});
};
//settings system jobs
$scope.updateSettingsSystemJobs = function(){
SettingsFactory.getSystemJobs(function(response) {
$scope.systemJobs = response;
});
};
//Pre-load
$scope.systemJobs = {};
$scope.updateSettingsSystemJobs();
//Save settings
$scope.saveSystemJobsLocal = function(){
$scope.saveProgress.systemJob = true;
SettingsFactory.saveSystemJobs($scope.systemJobs,function(response) {
alertService.success($filter('translate')('UPDATED_SUCCESSFULLY'));
$scope.saveProgress.systemJobs = false;
$scope.updateSettingsSystemJobs();
$scope.editEnable.systemJobs = false;
},function(error){
displayRestError.display(error);
$scope.saveProgress.systemJobs = false;
});
};
//edit confirmation
$scope.systemJobsWarning = function (size) {
var addModalInstance = $uibModal.open({
templateUrl: 'partials/common-html/edit-confirmation-modal.html',
controller: 'SystemJobsChangeController',
size: size,
resolve: {}
});
addModalInstance.result.then(function () {
$scope.editEnable.systemJobs = true;
}),
function () {
//console.log('Modal dismissed at: ' + new Date());
}
};
});
// System jobs change warning
myControllerModule.controller('SystemJobsChangeController', function ($scope, $uibModalInstance, $filter) {
$scope.header = $filter('translate')('SYSTEM_JOBS_EDIT_CONFIRMATION_TITLE');
$scope.message = $filter('translate')('SYSTEM_JOBS_EDIT_CONFIRMATION_MSG');
$scope.continute = function() {$uibModalInstance.close(); };
$scope.cancel = function () { $uibModalInstance.dismiss('cancel'); }
});
myControllerModule.controller('SettingsNotificationsController', function(alertService, $scope, $filter, SettingsFactory, displayRestError, mchelper, CommonServices) {
//config, language, user, etc.,
$scope.mchelper = mchelper;
$scope.cs = CommonServices;
//editable settings
$scope.editEnable = {};
$scope.saveProgress = {};
$scope.testing = {};
//settings Email
$scope.updateSettingsEmail = function(){
$scope.emailSettings = SettingsFactory.getEmail();
};
//settings SMS
$scope.updateSettingsSms = function(){
$scope.smsSettings = SettingsFactory.getSms();
};
//settings Pushbullet
$scope.updateSettingsPushbullet = function(){
$scope.pushbulletSettings = SettingsFactory.getPushbullet();
};
//settings TelegramBot
$scope.updateSettingsTelegramBot = function(){
$scope.telegramBotSettings = SettingsFactory.getTelegramBot();
};
//Pre-load
$scope.emailSettings = {};
$scope.smsSettings = {};
$scope.updateSettingsEmail();
$scope.updateSettingsSms();
$scope.updateSettingsPushbullet();
$scope.updateSettingsTelegramBot();
//Save email
$scope.saveEmail = function(){
$scope.saveProgress.email = true;
SettingsFactory.saveEmail($scope.emailSettings,function(response) {
alertService.success($filter('translate')('UPDATED_SUCCESSFULLY'));
$scope.saveProgress.email = false;
$scope.updateSettingsEmail();
$scope.editEnable.email = false;
},function(error){
displayRestError.display(error);
$scope.saveProgress.email = false;
});
};
//Send test email
$scope.sendTestEmail = function(){
$scope.testing.email = true;
SettingsFactory.saveEmail({'testOnly': true}, $scope.emailSettings, function(response) {
alertService.success(response.message);
$scope.testing.email = false;
},function(error){
displayRestError.display(error);
$scope.testing.email = false;
});
};
//Save sms
$scope.saveSms = function(){
$scope.saveProgress.sms = true;
SettingsFactory.saveSms($scope.smsSettings,function(response) {
alertService.success($filter('translate')('UPDATED_SUCCESSFULLY'));
$scope.saveProgress.sms = false;
$scope.updateSettingsSms();
$scope.editEnable.sms = false;
},function(error){
displayRestError.display(error);
$scope.saveProgress.sms = false;
});
};
//Save pushbullet
$scope.savePushbullet = function(){
$scope.saveProgress.pushbullet = true;
SettingsFactory.savePushbullet($scope.pushbulletSettings,function(response) {
alertService.success($filter('translate')('UPDATED_SUCCESSFULLY'));
$scope.saveProgress.pushbullet = false;
$scope.updateSettingsPushbullet();
$scope.editEnable.pushbullet = false;
},function(error){
displayRestError.display(error);
$scope.saveProgress.pushbullet = false;
});
};
//Save telegramBot
$scope.saveTelegramBot = function(){
$scope.saveProgress.telegramBot = true;
SettingsFactory.saveTelegramBot($scope.telegramBotSettings,function(response) {
alertService.success($filter('translate')('UPDATED_SUCCESSFULLY'));
$scope.saveProgress.telegramBot = false;
$scope.updateSettingsTelegramBot();
$scope.editEnable.telegramBot = false;
},function(error){
displayRestError.display(error);
$scope.saveProgress.telegramBot = false;
});
};
});
myControllerModule.controller('SettingsSystemMySensors', function(alertService, $scope, $filter, SettingsFactory, TypesFactory, FirmwaresFactory, displayRestError, mchelper) {
//config, language, user, etc.,
$scope.mchelper = mchelper;
//editable settings
$scope.editEnable = {};
$scope.saveProgress = {};
//settings MySensors
$scope.updateSettingsMySensors = function(){
SettingsFactory.getMySensors(function(response){
$scope.mySensorsSettings = response;
if(response.defaultFirmware){
FirmwaresFactory.getFirmware({"refId": response.defaultFirmware},function(response){
$scope.defaultFirmware = response.firmwareName;
});
}
});
};
//Pre-load
$scope.mySensorsSettings = {};
//Get firmwares list
$scope.firmwares = TypesFactory.getFirmwares();
$scope.updateSettingsMySensors();
$scope.defaultFirmware = null;
//Save mySensors
$scope.saveMySensors = function(){
$scope.saveProgress.mySensors = true;
SettingsFactory.saveMySensors($scope.mySensorsSettings,function(response) {
alertService.success($filter('translate')('UPDATED_SUCCESSFULLY'));
$scope.saveProgress.mySensors = false;
$scope.updateSettingsMySensors();
$scope.editEnable.mySensors = false;
},function(error){
displayRestError.display(error);
$scope.saveProgress.mySensors = false;
});
};
});
myControllerModule.controller('SettingsMetricsController', function(alertService, $scope, $filter, SettingsFactory, TypesFactory, displayRestError, mchelper, CommonServices, $uibModal) {
//config, language, user, etc.,
$scope.mchelper = mchelper;
$scope.cs = CommonServices;
//editable settings
$scope.editEnable = {};
$scope.saveProgress = {};
//settings Units
$scope.updateSettingsMetrics = function(){
SettingsFactory.getMetrics(function(response){
$scope.metricsSettings = response;
$scope.metricsSettings.defaultTimeRange = $scope.metricsSettings.defaultTimeRange.toString();
});
};
//Update Retention settings
$scope.updateSettingsMetricsRetention = function(){
SettingsFactory.getMetricsRetention(function(response) {
$scope.metricsRetention = response;
$scope.rRawData = CommonServices.getTimestampJson(response.retentionRawData);
$scope.rOneMinute = CommonServices.getTimestampJson(response.retentionOneMinute);
$scope.rFiveMinutes = CommonServices.getTimestampJson(response.retentionFiveMinutes);
$scope.rOneHour = CommonServices.getTimestampJson(response.retentionOneHour);
$scope.rSixHours = CommonServices.getTimestampJson(response.retentionSixHours);
$scope.rTwelveHours = CommonServices.getTimestampJson(response.retentionTwelveHours);
$scope.rOneDay = CommonServices.getTimestampJson(response.retentionOneDay);
$scope.rBinary = CommonServices.getTimestampJson(response.retentionBinary);
$scope.rGPS = CommonServices.getTimestampJson(response.retentionGPS);
},function(error){
displayRestError.display(error);
});
}
//Update engine settings
$scope.updateSettingsMetricsEngine = function(){
SettingsFactory.getMetricsEngine(function(response) {
$scope.metricsEngine = response;
$scope.metricsEngine.purgeEveryThing = false;
},function(error){
displayRestError.display(error);
});
}
//Pre-load
$scope.engineTypes = TypesFactory.getMetricEngineTypes();
$scope.trustHostTypes = TypesFactory.getTrustHostTypes();
$scope.metricsSettings = {};
$scope.updateSettingsMetricsEngine();
$scope.updateSettingsMetricsRetention();
$scope.updateSettingsMetrics();
//Save garphs settings
$scope.saveMetrics = function(){
$scope.saveProgress.metrics = true;
SettingsFactory.saveMetrics($scope.metricsSettings,function(response) {
alertService.success($filter('translate')('UPDATED_SUCCESSFULLY'));
$scope.saveProgress.metrics = false;
$scope.updateSettingsMetrics();
$scope.editEnable.metrics = false;
},function(error){
displayRestError.display(error);
$scope.saveProgress.metrics = false;
});
};
//Save engine settings
$scope.saveMetricsEngine = function(){
$scope.saveProgress.metricsEngine = true;
SettingsFactory.saveMetricsEngine($scope.metricsEngine,function(response) {
alertService.success($filter('translate')('UPDATED_SUCCESSFULLY'));
$scope.saveProgress.metricsEngine = false;
$scope.updateSettingsMetricsEngine();
$scope.editEnable.metricsEngine = false;
},function(error){
displayRestError.display(error);
$scope.saveProgress.metricsEngine = false;
});
};
//Save retention settings
$scope.saveMetricsRetention = function(){
$scope.saveProgress.metricsRetention = true;
//Update on timestamp format
$scope.metricsRetention.retentionRawData = CommonServices.getTimestamp($scope.rRawData);
$scope.metricsRetention.retentionOneMinute = CommonServices.getTimestamp($scope.rOneMinute);
$scope.metricsRetention.retentionFiveMinutes = CommonServices.getTimestamp($scope.rFiveMinutes);
$scope.metricsRetention.retentionOneHour = CommonServices.getTimestamp($scope.rOneHour);
$scope.metricsRetention.retentionSixHours = CommonServices.getTimestamp($scope.rSixHours);
$scope.metricsRetention.retentionTwelveHours = CommonServices.getTimestamp($scope.rTwelveHours);
$scope.metricsRetention.retentionOneDay = CommonServices.getTimestamp($scope.rOneDay);
$scope.metricsRetention.retentionBinary = CommonServices.getTimestamp($scope.rBinary);
$scope.metricsRetention.retentionGPS = CommonServices.getTimestamp($scope.rGPS);
SettingsFactory.saveMetricsRetention($scope.metricsRetention,function(response) {
alertService.success($filter('translate')('UPDATED_SUCCESSFULLY'));
$scope.saveProgress.metricsRetention = false;
$scope.updateSettingsMetricsRetention();
$scope.editEnable.metricsDataRetention = false;
},function(error){
displayRestError.display(error);
$scope.saveProgress.metricsRetention = false;
});
};
//edit retention confirmation
$scope.retentionWarning = function (size) {
var addModalInstance = $uibModal.open({
templateUrl: 'partials/common-html/edit-confirmation-modal.html',
controller: 'MetricsRetentionWarnController',
size: size,
resolve: {}
});
addModalInstance.result.then(function () {
$scope.editEnable.metricsDataRetention = true;
}),
function () {
//console.log('Modal dismissed at: ' + new Date());
}
};
//edit engine confirmation
$scope.engineChnageWarning = function (size) {
var addModalInstance = $uibModal.open({
templateUrl: 'partials/common-html/edit-confirmation-modal.html',
controller: 'MetricsEngineWarnController',
size: size,
resolve: {}
});
addModalInstance.result.then(function () {
$scope.editEnable.metricsEngine = true;
}),
function () {
//console.log('Modal dismissed at: ' + new Date());
}
};
});
//retention change Modal
myControllerModule.controller('MetricsRetentionWarnController', function ($scope, $uibModalInstance, $filter) {
$scope.header = $filter('translate')('RETENTION_DIALOG_TITLE');
$scope.message = $filter('translate')('RETENTION_DIALOG_CONFIRMATION_MSG');
$scope.continute = function() {$uibModalInstance.close(); };
$scope.cancel = function () { $uibModalInstance.dismiss('cancel'); }
});
//metric engine change Modal
myControllerModule.controller('MetricsEngineWarnController', function ($scope, $uibModalInstance, $filter) {
$scope.header = $filter('translate')('RETENTION_DIALOG_TITLE');
$scope.message = $filter('translate')('METRIC_ENGINE_DIALOG_CONFIRMATION_MSG');
$scope.continute = function() {$uibModalInstance.close(); };
$scope.cancel = function () { $uibModalInstance.dismiss('cancel'); }
});
myControllerModule.controller('SettingsMqttBrokerController', function(alertService, $scope, $filter, SettingsFactory, CommonServices, displayRestError, $uibModal) {
//config, language, user, etc.,
$scope.cs = CommonServices;
//editable settings
$scope.editEnable = {};
$scope.saveProgress = {};
//settings mqtt broker
$scope.updateSettingsMqttBroker = function(){
SettingsFactory.getMqttBroker(function(response){
$scope.mqttBrokerSettings = response;
});
};
//Pre-load
$scope.mqttBrokerSettings = {};
$scope.updateSettingsMqttBroker();
//Save settings
$scope.saveMqttBroker = function(){
$scope.saveProgress.mqttBroker = true;
SettingsFactory.saveMqttBroker($scope.mqttBrokerSettings,function(response) {
alertService.success($filter('translate')('UPDATED_SUCCESSFULLY'));
$scope.saveProgress.mqttBroker = false;
$scope.updateSettingsMqttBroker();
$scope.editEnable.mqttBroker = false;
},function(error){
displayRestError.display(error);
$scope.saveProgress.mqttBroker = false;
});
};
//edit confirmation
$scope.saveSettings = function (size) {
var addModalInstance = $uibModal.open({
templateUrl: 'partials/common-html/edit-confirmation-modal.html',
controller: 'MqttBrokerChangeController',
size: size,
resolve: {}
});
addModalInstance.result.then(function () {
$scope.saveMqttBroker();
}),
function () {
//console.log('Modal dismissed at: ' + new Date());
}
};
});
//Mqtt broker change warning
myControllerModule.controller('MqttBrokerChangeController', function ($scope, $uibModalInstance, $filter) {
$scope.header = $filter('translate')('MQTT_BROKER_EDIT_DIALOG');
$scope.message = $filter('translate')('MQTT_BROKER_EDIT_CONFIRMATION_MSG');
$scope.continute = function() {$uibModalInstance.close(); };
$scope.cancel = function () { $uibModalInstance.dismiss('cancel'); }
});

101
www/controllers/status.js Normal file
View File

@@ -0,0 +1,101 @@
/*
* Copyright 2015-2018 Jeeva Kandasamy (jkandasa@gmail.com)
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
myControllerModule.controller('StatusSystemController', function(alertService,
$scope, $filter, StatusFactory, $uibModal, $stateParams, displayRestError) {
//GUI page settings
$scope.headerStringList = "System status";
//OS Status
$scope.osStatus = StatusFactory.getOsStatus();
//JVM Status
$scope.jvmStatus = StatusFactory.getJvmStatus();
//Script engines
$scope.scriptEngines = StatusFactory.getScriptEngines();
//Run Garbage Collection
$scope.runGC = function(){
StatusFactory.runGarbageCollection(function(response) {
//Update display data
$scope.jvmStatus = response;
},function(error){
displayRestError.display(error);
});
}
});
myControllerModule.controller('McAboutController', function(alertService,
$scope, $filter, StatusFactory, $uibModal, $stateParams, displayRestError) {
//GUI page settings
$scope.headerStringList = "About";
//About MC
$scope.mcAbout = StatusFactory.getMcAbout();
});
myControllerModule.controller('StatusMcLogController', function(alertService,
$scope, $filter, StatusFactory, $uibModal, $stateParams, displayRestError) {
//GUI page settings
$scope.headerStringList = $filter('translate')('MYCONTROLLER_SERVER_LOG');
$scope.noItemsSystemMsg = $filter('translate')('NO_LOGS_AVAILABLE');
$scope.noItemsSystemIcon = "fa fa-list";
$scope.initialLog = {};
$scope.logData = [];
$scope.logLevel = null;
//Refresh
$scope.refreshLogs = function(){
$scope.initialLog = StatusFactory.getMcServerLog(function(response){
$scope.logData = response.data;
});
};
//Get log level string
/*
$scope.getLogLevel = function(log){
if(log.indexOf(' ERROR ') > -1 ){
$scope.logLevel = "danger";
}else if(log.indexOf(' INFO ') > -1 ){
$scope.logLevel = "info";
}else if(log.indexOf(' WARN ') > -1 ){
$scope.logLevel = "warning";
}else if(log.indexOf(' DEBUG ') > -1 ){
$scope.logLevel = "default";
}
if(!$scope.logLevel){
$scope.logLevel = "default";
}
return $scope.logLevel;
}
*/
//Pre load
$scope.initialLog = StatusFactory.getMcServerLog(function(response){
$scope.logData = response.data;
/*
if(response.data && response.data.length > 0){
$scope.logData = response.data.split('\n');
}
*/
});
});

View File

@@ -0,0 +1,254 @@
/*
* Copyright 2015-2018 Jeeva Kandasamy (jkandasa@gmail.com)
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
myControllerModule.controller('TemplatesController', function(alertService,
$scope, TemplatesFactory, $state, $uibModal, $stateParams, displayRestError, mchelper, CommonServices, $filter, $base64) {
//GUI page settings
$scope.headerStringList = $filter('translate')('TEMPLATES_DETAIL');
$scope.noItemsSystemMsg = $filter('translate')('NO_TEMPLATES_SETUP');
$scope.noItemsSystemIcon = "fa fa-file-text";
//load empty, configuration, etc.,
$scope.mchelper = mchelper;
$scope.filteredList=[];
//data query details
$scope.currentPage = 1;
$scope.query = CommonServices.getQuery();
$scope.queryResponse = {};
//Get min number
$scope.getMin = function(item1, item2){
return CommonServices.getMin(item1, item2);
};
if($stateParams.resourceType){
$scope.query.resourceType = $stateParams.resourceType;
$scope.query.resourceId = $stateParams.resourceId;
}
//get all items
$scope.getAllItems = function(){
TemplatesFactory.getAll($scope.query, function(response) {
$scope.queryResponse = response;
$scope.filteredList = $scope.queryResponse.data;
$scope.filterConfig.resultsCount = $scope.queryResponse.query.filteredCount;
},function(error){
displayRestError.display(error);
});
}
//Hold all the selected item ids
$scope.itemIds = [];
$scope.selectAllItems = function(){
CommonServices.selectAllItems($scope, 'name');
};
$scope.selectItem = function(item){
CommonServices.selectItem($scope, item, 'name');
};
//On page change
$scope.pageChanged = function(newPage){
CommonServices.updatePageChange($scope, newPage);
};
//Filter change method
var filterChange = function (filters) {
//Reset filter fields and update items
CommonServices.updateFiltersChange($scope, filters);
};
$scope.filterConfig = {
fields: [
{
id: 'name',
title: $filter('translate')('NAME'),
placeholder: $filter('translate')('FILTER_BY_NAME'),
filterType: 'text'
},
{
id: 'extension',
title: $filter('translate')('EXTENSION'),
placeholder: $filter('translate')('FILTER_BY_EXTENSION'),
filterType: 'select',
filterValues: ['html'],
}
],
resultsCount: $scope.filteredList.length,
appliedFilters: [],
onFilterChange: filterChange
};
//Sort columns
var sortChange = function (sortId, isAscending) {
//Reset sort type and update items
CommonServices.updateSortChange($scope, sortId, isAscending);
};
$scope.sortConfig = {
fields: [
{
id: 'name',
title: $filter('translate')('NAME'),
sortType: 'text'
}
],
onSortChange: sortChange
};
//Delete item(s)
$scope.delete = function (size) {
var modalInstance = $uibModal.open({
templateUrl: 'partials/common-html/delete-modal.html',
controller: 'ControllerDeleteModal',
size: size,
resolve: {}
});
modalInstance.result.then(function () {
TemplatesFactory.deleteIds($scope.itemIds, function(response) {
alertService.success($filter('translate')('ITEMS_DELETED_SUCCESSFULLY'));
//Update display table
$scope.getAllItems();
$scope.itemIds = [];
},function(error){
displayRestError.display(error);
});
}),
function () {
//console.log('Modal dismissed at: ' + new Date());
}
};
//Edit item
$scope.edit = function () {
if($scope.itemIds.length == 1){
$state.go("templatesAddEdit",{'name':$base64.encode($scope.itemIds[0])});
}
};
//Execute item
$scope.runNow = function (size) {
if($scope.itemIds.length != 1){
return;
}
var modalInstance = $uibModal.open({
templateUrl: 'partials/templates/run-now-modal.html',
controller: 'ControllerTemplateRunNowModal',
size: size,
resolve: {itemId: function () {return $scope.itemIds[0]}}
});
modalInstance.result.then(function () {
ScriptsFactory.deleteIds($scope.itemIds, function(response) {
//Nothing to do...
},function(error){
displayRestError.display(error);
});
}),
function () {
//console.log('Modal dismissed at: ' + new Date());
}
};
});
//Template run now Modal
myControllerModule.controller('ControllerTemplateRunNowModal', function ($scope, $uibModalInstance, $filter, CommonServices, ScriptsFactory, TemplatesFactory, $sce, itemId) {
$scope.header = $filter('translate')('RUN_NOW');
$scope.cs = CommonServices;
$scope.request = {};
$scope.request.template = itemId;
$scope.scripts = ScriptsFactory.getAllLessInfo({"type":"Operation"});
$scope.request.bindings = '{ }';
//$uibModalInstance.close();
$scope.runNow = function() {
$scope.runningInProgress = true;
$scope.request.scriptBindings = angular.fromJson(JSON.stringify(eval('('+$scope.request.bindings+')')));
TemplatesFactory.getHtml($scope.request, function(response) {
$scope.templateResult = $sce.trustAsHtml(response.message);
$scope.runningInProgress = false;
},function(error){
if(error.data.errorMessage){
$scope.templateResult = $sce.trustAsHtml('<pre class=\"pre-scrollable\">'+error.data.errorMessage+'</pre>');
}else{
$scope.templateResult = $sce.trustAsHtml('<pre class=\"pre-scrollable\">'+angular.toJson(error.data)+'</pre>');
}
$scope.runningInProgress = false;
displayRestError.display(error);
});
};
$scope.cancel = function () { $uibModalInstance.dismiss('cancel'); }
});
//Add Edit script controller
myControllerModule.controller('TemplatesControllerAddEdit', function ($scope, $stateParams, $state,
TemplatesFactory, mchelper, alertService, displayRestError, $filter, CommonServices, $base64) {
$scope.mchelper = mchelper;
$scope.item = {};
$scope.cs = CommonServices;
$scope.showData = false;
$scope.editMode = false;
if($stateParams.name){
$scope.editMode = true;
TemplatesFactory.get({"name":$base64.decode($stateParams.name)},function(response) {
$scope.item = response;
$scope.showData = true;
},function(error){
displayRestError.display(error);
$scope.showData = true;
});
}else{
$scope.showData = true;
}
//Read File and put it in textarea
$scope.displayFileContents = function(contents) {
$scope.item.data = contents;
};
$scope.editorOptions = {
lineWrapping : true,
lineNumbers: true,
readOnly: 'nocursor',
mode: 'xml',
};
//GUI page settings
$scope.showHeaderUpdate = $stateParams.name;
$scope.headerStringAdd = $filter('translate')('ADD_TEMPLATE');
$scope.headerStringUpdate = $filter('translate')('UPDATE_TEMPLATE');
$scope.cancelButtonState = "templatesList"; //Cancel button url
$scope.saveProgress = false;
$scope.save = function(){
$scope.saveProgress = true;
TemplatesFactory.upload($scope.item, function(response) {
alertService.success($filter('translate')('ITEM_UPDATED_SUCCESSFULLY'));
$state.go("templatesList");
},function(error){
displayRestError.display(error);
$scope.saveProgress = false;
});
}
});

420
www/controllers/timers.js Normal file
View File

@@ -0,0 +1,420 @@
/*
* Copyright 2015-2018 Jeeva Kandasamy (jkandasa@gmail.com)
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
myControllerModule.controller('TimersController', function(alertService,
$scope, TimersFactory, $state, $uibModal, $stateParams, displayRestError, mchelper, CommonServices, $filter) {
//GUI page settings
$scope.headerStringList = $filter('translate')('TIMERS_DETAIL');
$scope.noItemsSystemMsg = $filter('translate')('NO_TIMERS_SETUP');
$scope.noItemsSystemIcon = "fa fa-clock-o";
//load empty, configuration, etc.,
$scope.mchelper = mchelper;
$scope.filteredList=[];
//data query details
$scope.currentPage = 1;
$scope.query = CommonServices.getQuery();
$scope.queryResponse = {};
//Get min number
$scope.getMin = function(item1, item2){
return CommonServices.getMin(item1, item2);
};
if($stateParams.resourceType){
$scope.query.resourceType = $stateParams.resourceType;
$scope.query.resourceId = $stateParams.resourceId;
}
//get all Sensors
$scope.getAllItems = function(){
TimersFactory.getAll($scope.query, function(response) {
$scope.queryResponse = response;
$scope.filteredList = $scope.queryResponse.data;
$scope.filterConfig.resultsCount = $scope.queryResponse.query.filteredCount;
},function(error){
displayRestError.display(error);
});
}
//Hold all the selected item ids
$scope.itemIds = [];
$scope.selectAllItems = function(){
CommonServices.selectAllItems($scope);
};
$scope.selectItem = function(item){
CommonServices.selectItem($scope, item);
};
//On page change
$scope.pageChanged = function(newPage){
CommonServices.updatePageChange($scope, newPage);
};
//Filter change method
var filterChange = function (filters) {
//Reset filter fields and update items
CommonServices.updateFiltersChange($scope, filters);
};
$scope.filterConfig = {
fields: [
{
id: 'name',
title: $filter('translate')('NAME'),
placeholder: $filter('translate')('FILTER_BY_NAME'),
filterType: 'text'
},
{
id: 'timerType',
title: $filter('translate')('TIMER_TYPE'),
placeholder: $filter('translate')('FILTER_BY_RESOURCE_TYPE'),
filterType: 'select',
filterValues: ['Simple','Normal','Cron','Before sunrise','After sunrise','Before sunset','After sunset'],
},
{
id: 'frequency',
title: $filter('translate')('FREQUENCY'),
placeholder: $filter('translate')('FILTER_BY_FREQUENCY'),
filterType: 'select',
filterValues: ['Daily','Weekly','Monthly'],
},
{
id: 'enabled',
title: $filter('translate')('ENABLED'),
placeholder: $filter('translate')('FILTER_BY_ENABLED'),
filterType: 'select',
filterValues: ['True','False'],
}
],
resultsCount: $scope.filteredList.length,
appliedFilters: [],
onFilterChange: filterChange
};
//Sort columns
var sortChange = function (sortId, isAscending) {
//Reset sort type and update items
CommonServices.updateSortChange($scope, sortId, isAscending);
};
$scope.sortConfig = {
fields: [
{
id: 'name',
title: $filter('translate')('NAME'),
sortType: 'text'
},
{
id: 'enabled',
title: $filter('translate')('ENABLED'),
sortType: 'text'
},
{
id: 'timerType',
title: $filter('translate')('TIMER_TYPE'),
sortType: 'text'
},
{
id: 'frequency',
title: $filter('translate')('FREQUENCY'),
sortType: 'text'
},
{
id: 'lastFire',
title: $filter('translate')('LAST_FIRED'),
sortType: 'text'
}
],
onSortChange: sortChange
};
//Edit item
$scope.edit = function () {
if($scope.itemIds.length == 1){
$state.go("timersAddEdit",{'id':$scope.itemIds[0]});
}
};
//Clone item
$scope.clone = function () {
if($scope.itemIds.length == 1){
$state.go("timersAddEdit",{'id':$scope.itemIds[0], 'action': 'clone'});
}
};
//Delete item(s)
$scope.delete = function (size) {
var modalInstance = $uibModal.open({
templateUrl: 'partials/common-html/delete-modal.html',
controller: 'ControllerDeleteModal',
size: size,
resolve: {}
});
modalInstance.result.then(function () {
TimersFactory.deleteIds($scope.itemIds, function(response) {
alertService.success($filter('translate')('ITEMS_DELETED_SUCCESSFULLY'));
//Update display table
$scope.getAllItems();
$scope.itemIds = [];
},function(error){
displayRestError.display(error);
});
}),
function () {
//console.log('Modal dismissed at: ' + new Date());
}
};
//Enable items
$scope.enable = function () {
if($scope.itemIds.length > 0){
TimersFactory.enableIds($scope.itemIds, function(response) {
alertService.success($filter('translate')('ITEMS_ENABLED_SUCCESSFULLY'));
//Update display table
$scope.getAllItems();
$scope.itemIds = [];
},function(error){
displayRestError.display(error);
});
}
};
//Disable items
$scope.disable = function () {
if($scope.itemIds.length > 0){
TimersFactory.disableIds($scope.itemIds, function(response) {
alertService.success($filter('translate')('ITEMS_DISABLED_SUCCESSFULLY'));
//Update display table
$scope.getAllItems();
$scope.itemIds = [];
},function(error){
displayRestError.display(error);
});
}
};
});
myControllerModule.controller('TimersControllerAddEdit', function ($scope, TypesFactory, CommonServices, alertService, TimersFactory, mchelper, $stateParams, $state, $filter, displayRestError) {
$scope.timer = {};
$scope.timer.enabled=true;
$scope.showMeridian = angular.equals(mchelper.cfg.timeFormatSet, "12 hours");
$scope.cs = CommonServices;
if($stateParams.id){
TimersFactory.get({"id":$stateParams.id},function(response) {
$scope.timer = response;
//Update Resource Type
$scope.dspResources = $scope.getResources($scope.timer.resourceType);
//Update frequency data
if($scope.timer.timerType === 'Simple'){
var array = $scope.timer.frequencyData.split(',');
$scope.rpInterval = array[0]/1000;
$scope.rpCount = array[1];
}else if($scope.timer.timerType === 'Cron'){
$scope.cronFrequencyData = $scope.timer.frequencyData;
}else{
if($scope.timer.frequencyType === 'Daily'){
$scope.dailyFrequencyData = $scope.timer.frequencyData.split(',');
}else if($scope.timer.frequencyType === 'Weekly'){
$scope.weeklyFrequencyData = $scope.timer.frequencyData;
}else if($scope.timer.frequencyType === 'Monthly'){
$scope.monthlyFrequencyData = $scope.timer.frequencyData;
}
}
//Update payload operations
if($scope.timer.resourceType !== 'Sensor variable'){
$scope.updatePayloadOperations($scope.timer.resourceType);
}
//Update date
if($scope.timer.timerType !== 'Simple' || $scope.timer.timerType !== 'Cron'){
$scope.lTriggerTime = moment("1970-01-01T" + $scope.timer.triggerTime);
}
//Update validity from/to
if($scope.timer.validityFrom){
$scope.vFromDate = new Date(moment($scope.timer.validityFrom).utc());
$scope.vFromString = $filter('date')($scope.vFromDate.getTime(), mchelper.cfg.dateFormat);
}
if($scope.timer.validityTo){
$scope.vToDate = new Date(moment($scope.timer.validityTo).utc());
$scope.vToString = $filter('date')($scope.vToDate.getTime(), mchelper.cfg.dateFormat);
}
//Clone job
if($stateParams.action === 'clone'){
$stateParams.id = undefined;
$scope.timer.id = undefined;
$scope.timer.name = $scope.timer.name + '-' + $filter('translate')('CLONE');
}
},function(error){
displayRestError.display(error);
});
}
//pre load
$scope.dailyFrequencyData = [];
$scope.monthDays = ['00','01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31'];
$scope.hours = ['00','01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23'];
$scope.minutes = ['00','01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31',
'32','33','34','35','36','37','38','39','40','41','42','43','44','45','46','47','48','49','50','51','52','53','54','55','56','57','58','59'];
$scope.operations = TypesFactory.getOperations();
$scope.timerTypes = TypesFactory.getTimerTypes();
$scope.timerFrequencyTypes = TypesFactory.getTimerFrequencies();
$scope.timerWeekDays = TypesFactory.getTimerWeekDays();
$scope.resourceTypes = TypesFactory.getResourceTypes({"resourceType": "timer", "isSendPayload":true});
//Get resources
$scope.getResources = function(resourceType){
return CommonServices.getResources(resourceType);
}
//Update Payload operations
$scope.updatePayloadOperations= function(resourceType){
$scope.payloadOperations = TypesFactory.getPayloadOperations({"resourceType":resourceType});
}
//Get trigger time
$scope.setTriggerTime = function(isDefault){
if(!$scope.lTriggerTime){
$scope.lTriggerTime = moment();
if(isDefault){
$scope.lTriggerTime.hour(00);
$scope.lTriggerTime.minute(00);
$scope.lTriggerTime.second(00);
}
}
};
$scope.frequencyData;
//Update Frequency Data
$scope.updateFrequencyData = function(value1,value2){
if($scope.timer.timerType === 'Simple'){
}else if($scope.timer.timerType === 'Cron'){
$scope.frequencyData = value1;
}else{
if($scope.timer.frequencyType === 'Daily'){
$scope.frequencyData = value1.join();
}else if($scope.timer.frequencyType === 'Weekly'){
$scope.frequencyData = value1;
}else if($scope.timer.frequencyType === 'Monthly'){
$scope.frequencyData = value1;
}
}
console.log('FrequencyData:'+$scope.frequencyData);
};
//Update daily frequency
$scope.updateFrequency = function() {
if($scope.timer.frequencyType === 'Daily' && $scope.dailyFrequencyData.length == 0){
angular.forEach($scope.timerWeekDays, function(value, key){
$scope.dailyFrequencyData.push(value.displayName);
});
}
};
//Convert as display string
$scope.getDateTimeDisplayFormat = function (newDate) {
return $filter('date')(newDate.getTime(), mchelper.cfg.dateFormat);
};
//GUI page settings
if(!$stateParams.action || $stateParams.action !== 'clone'){
$scope.showHeaderUpdate = $stateParams.id;
}
$scope.headerStringAdd = $filter('translate')('ADD_TIMER');
$scope.headerStringUpdate = $filter('translate')('UPDATE_TIMER');
$scope.cancelButtonState = "timersList"; //Cancel button state
$scope.saveProgress = false;
//$scope.isSettingChange = false;
//Save data
$scope.save = function(){
//Clear update required values
$scope.timer.frequencyData = null;
//Update validity from/to
if($scope.vFromDate){
$scope.timer.validityFrom = moment($scope.vFromDate).format('YYYY-MM-DDTHH:mm:ss');
}
if($scope.vToDate){
$scope.timer.validityTo = moment($scope.vToDate).format('YYYY-MM-DDTHH:mm:ss');
}
//Update Frequency Data
if($scope.timer.timerType === 'Simple'){
$scope.timer.frequencyData = ($scope.rpInterval*1000)+','+$scope.rpCount;
}else if($scope.timer.timerType === 'Cron'){
$scope.timer.frequencyData = $scope.cronFrequencyData;
}else{
if($scope.timer.frequencyType === 'Daily'){
$scope.timer.frequencyData = $scope.dailyFrequencyData.join();
}else if($scope.timer.frequencyType === 'Weekly'){
$scope.timer.frequencyData = $scope.weeklyFrequencyData;
}else if($scope.timer.frequencyType === 'Monthly'){
$scope.timer.frequencyData = $scope.monthlyFrequencyData;
}
}
//Update Time
if($scope.timer.timerType === 'Simple' || $scope.timer.timerType === 'Cron'){
$scope.timer.triggerTime = null;
$scope.timer.frequency = null;
}else{
if(!$scope.lTriggerTime){
$scope.lTriggerTime = new Date();
}
//set seconds to zero until the issue resolved >> https://github.com/mycontroller-org/mycontroller/issues/214
$scope.timer.triggerTime = moment($scope.lTriggerTime).format('HH:mm:00');
}
$scope.saveProgress = true;
if($stateParams.id){
TimersFactory.update($scope.timer,function(response) {
alertService.success($filter('translate')('ITEM_UPDATED_SUCCESSFULLY'));
$state.go("timersList");
},function(error){
$scope.saveProgress = false;
displayRestError.display(error);
});
}else{
TimersFactory.create($scope.timer,function(response) {
alertService.success($filter('translate')('ITEM_CREATED_SUCCESSFULLY'));
$state.go("timersList");
},function(error){
$scope.saveProgress = false;
displayRestError.display(error);
});
}
}
});

212
www/controllers/topology.js Normal file
View File

@@ -0,0 +1,212 @@
/*
* Copyright 2015-2018 Jeeva Kandasamy (jkandasa@gmail.com)
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
myControllerModule.controller('TopologyController', function(alertService,
$scope, MetricsFactory, $stateParams, $state, displayRestError, mchelper, CommonServices, $filter, TopologyService, $interval, mchelper) {
//GUI page settings
$scope.headerStringList = $filter('translate')('TOPOLOGY');
$scope.noItemsSystemMsg = $filter('translate')('NO_DATA_AVAILABLE');
$scope.noItemsSystemIcon = "pficon pficon-topology";
$scope.mchelper = mchelper;
$scope.query = {};
//Update $stateParams
if($stateParams.resourceType && $stateParams.resourceId){
$scope.query = {'resourceType': $stateParams.resourceType, 'resourceId': $stateParams.resourceId};
}
$scope.query.realtime = true;
var self = this;
$scope.vs = null;
var d3 = window.d3;
$scope.data = {};
$scope.search = {};
$scope.topologyHeight;
$scope.displayKinds= {};
$scope.kinds = {
"Gateway": "#vertex-Gateway",
"Node": "#vertex-Node",
"Sensor": "#vertex-Sensor",
"SensorVariable": "#vertex-SensorVariable"
};
// Refresh topology
$scope.refresh = function() {
MetricsFactory.getTopologyData($scope.query, function(data){
$scope.data = data;
//$scope.relations = data.relations;
$scope.displayKinds = data.kinds;
},function(error){
displayRestError.display(error);
});
};
$scope.isEmpty = function(item){
return angular.equals({}, item);
}
$scope.checkboxModel = {
value : false
};
$scope.legendTooltip = "Click here to show/hide entities of this type";
$scope.show_hide_names = function() {
var vertices = $scope.vs;
if($scope.checkboxModel.value) {
vertices.selectAll("tspan")
.style("display", "block");
}
else {
vertices.selectAll("tspan")
.style("display", "none");
}
};
$scope.refresh();
var promise = $interval( $scope.refresh, mchelper.cfg.globalPageRefreshTime);
$scope.$on('$destroy', function() {
$interval.cancel(promise);
});
$scope.$on("render", function(ev, vertices, added) {
/*
* We are passed two selections of <g> elements:
* vertices: All the elements
* added: Just the ones that were added
*/
added.attr("class", function(d) { return self.getKindClass(d); });
added.append("circle")
.attr("r", function(d) { return self.getDimensions(d).r})
.attr('class' , function(d) {
return TopologyService.getItemStatusClass(d);
});
added.append("title");
added.on("dblclick", function(d) {
return self.dblclick(d);});
added.append("text")
.attr("x", function(d) { return self.getDimensions(d).x})
.attr("y", function(d) { return self.getDimensions(d).y})
.style("font-family", function(d) {return self.getIcon(d).fname;})
.style("fill", function(d) { return self.getDimensions(d).fc})
.attr('font-size', function(d) { return self.getDimensions(d).fs +'px'} )
.text(function(d) {return self.getIcon(d).ucode;})
.append("tspan")
.attr("x", 26)
.attr("y", 24)
.text(function(d) { return d.item.name })
.style("font-size", function(d) {return "12px"}).style("fill", function(d) {return "black"})
.style("font-family","FontAwesome")
.style("display", function(d) {if ($scope.checkboxModel.value) {return "block"} else {return "none"}});
added.selectAll("title").text(function(d) {
return TopologyService.tooltip(d).join("\n");
});
$scope.vs = vertices;
/* Don't do default rendering */
ev.preventDefault();
});
self.class_name = function class_name(d) {
var class_name = d.item.icon;
return class_name;
};
this.dblclick = function dblclick(d) {
//window.location.assign(TopologyService.geturl(d));
switch(d.item.kind) {
case "Gateway":
$state.go("gatewaysDetail", {'id': d.item.id});
break;
case "Node":
$state.go("nodesDetail", {'id': d.item.id});
break;
case "Sensor":
$state.go("sensorsDetail", {'id': d.item.id});
break;
case "SensorVariable":
$state.go("sensorVariableEdit", {'id': d.item.id});
break;
}
};
self.getDimensions = function getDimensions(d) {
switch (d.item.kind) {
case "Gateway":
return { x: 0, y: 11, r: 28, fs: 33, fc:'#663333'};
case "Node" :
return { x: 0, y: 9, r: 21, fs: 27, fc:'#1186C1'};
case "Sensor" :
return { x: 0.2, y: 8, r: 15, fs: 21, fc:'#9467bd'};
default :
return { x: 0, y: 6, r: 12, fs:16, fc:'#ff7f0e'};
}
};
self.getIcon = function(d) {
switch (d.item.kind) {
case "Gateway":
return {ucode:'\uf1e6', fname:'FontAwesome'};
case "Node" :
return {ucode:'\uf0e8', fname:'FontAwesome'};
case "Sensor" :
return CommonServices.getSensorIconData(d.item.subType.en);
default :
return {ucode:'\uf005', fname:'FontAwesome'};
}
};
self.getKindClass = function(d) {
switch (d.item.kind) {
case "Node":
return 'McNode';
default :
return d.item.kind;
}
};
$scope.searchNode = function() {
var svg = TopologyService.getSVG(d3);
var query = $scope.search.query;
TopologyService.searchNode(svg, query);
};
$scope.resetSearch = function() {
TopologyService.resetSearch(d3);
// Reset the search term in search input
$scope.search.query = "";
};
var resized = function(){
var height = window.innerHeight - 265;
if(height < 350){
$scope.topologyHeight = 350;
}else{
$scope.topologyHeight = height;
}
}
//set layout height
resized();
});

191
www/controllers/uid-tags.js Normal file
View File

@@ -0,0 +1,191 @@
/*
* Copyright 2015-2018 Jeeva Kandasamy (jkandasa@gmail.com)
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
myControllerModule.controller('UidTagsController', function(alertService,
$scope, $filter, UidTagsFactory, $state, $uibModal, displayRestError, mchelper, CommonServices, $stateParams) {
//GUI page settings
$scope.headerStringList = $filter('translate')('UID_TAGS_DETAIL');
$scope.noItemsSystemMsg = $filter('translate')('NO_UID_TAGS_SETUP');
$scope.noItemsSystemIcon = "fa fa-tags";
//load empty, configuration, etc.,
$scope.mchelper = mchelper;
$scope.filteredList=[];
//data query details
$scope.currentPage = 1;
$scope.query = CommonServices.getQuery();
$scope.queryResponse = {};
//Get min number
$scope.getMin = function(item1, item2){
return CommonServices.getMin(item1, item2);
};
if($stateParams.sensorId){
$scope.query.sensorId = $stateParams.sensorId;
}
//get all items
$scope.getAllItems = function(){
UidTagsFactory.getAll($scope.query, function(response) {
$scope.queryResponse = response;
$scope.filteredList = $scope.queryResponse.data;
$scope.filterConfig.resultsCount = $scope.queryResponse.query.filteredCount;
},function(error){
displayRestError.display(error);
});
}
//Hold all the selected item ids
$scope.itemIds = [];
$scope.selectAllItems = function(){
CommonServices.selectAllItems($scope);
};
$scope.selectItem = function(item){
CommonServices.selectItem($scope, item);
};
//On page change
$scope.pageChanged = function(newPage){
CommonServices.updatePageChange($scope, newPage);
};
//Filter change method
var filterChange = function (filters) {
//Reset filter fields and update items
CommonServices.updateFiltersChange($scope, filters);
};
$scope.filterConfig = {
fields: [
{
id: 'uid',
title: $filter('translate')('UID'),
placeholder: $filter('translate')('FILTER_BY_UID'),
filterType: 'text'
}
],
resultsCount: $scope.filteredList.length,
appliedFilters: [],
onFilterChange: filterChange
};
//Sort columns
var sortChange = function (sortId, isAscending) {
//Reset sort type and update items
CommonServices.updateSortChange($scope, sortId, isAscending);
};
$scope.sortConfig = {
fields: [
{
id: 'uid',
title: $filter('translate')('UID'),
sortType: 'numeric'
}
],
onSortChange: sortChange,
isAscending: true,
};
//Edit item
$scope.edit = function () {
if($scope.itemIds.length == 1){
$state.go("uidTagsAddEdit", {'id':$scope.itemIds[0]});
}
};
//Delete item(s)
$scope.delete = function (size) {
var modalInstance = $uibModal.open({
templateUrl: 'partials/common-html/delete-modal.html',
controller: 'ControllerDeleteModal',
size: size,
resolve: {}
});
modalInstance.result.then(function () {
UidTagsFactory.deleteIds($scope.itemIds, function(response) {
alertService.success('ITEM_DELETED_SUCCESSFULLY');
//Update display table
$scope.getAllItems();
$scope.itemIds = [];
},function(error){
displayRestError.display(error);
});
}),
function () {
//console.log('Modal dismissed at: ' + new Date());
}
};
});
//add edit item
myControllerModule.controller('UidTagsControllerAddEdit', function ($scope, CommonServices, alertService, UidTagsFactory, mchelper, $stateParams, $state, $filter, displayRestError, TypesFactory) {
$scope.item = {};
$scope.cs = CommonServices;
if($stateParams.id){
UidTagsFactory.get({"id":$stateParams.id},function(response) {
$scope.item = response;
$scope.resourcesList = $scope.cs.getResources($scope.item.resourceType);
},function(error){
displayRestError.display(error);
});
}
//pre load
$scope.resourceTypes = TypesFactory.getResourceTypes({"resourceType": "UID tag"});
//GUI page settings
$scope.showHeaderUpdate = $stateParams.id;
$scope.headerStringAdd = $filter('translate')('ADD_UID_TAG_ENTRY');
$scope.headerStringUpdate = $filter('translate')('UPDATE_UID_TAG_ENTRY');
$scope.cancelButtonState = "uidTagsList"; //Cancel button state
$scope.saveProgress = false;
//$scope.isSettingChange = false;
//Save data
$scope.save = function(){
$scope.saveProgress = true;
if($stateParams.id){
UidTagsFactory.update($scope.item,function(response) {
alertService.success($filter('translate')('ITEM_UPDATED_SUCCESSFULLY'));
$state.go("uidTagsList");
},function(error){
displayRestError.display(error);
$scope.saveProgress = false;
});
}else{
UidTagsFactory.create($scope.item,function(response) {
alertService.success($filter('translate')('ITEM_CREATED_SUCCESSFULLY'));
$state.go("uidTagsList");
},function(error){
displayRestError.display(error);
$scope.saveProgress = false;
});
}
}
});

257
www/controllers/users.js Normal file
View File

@@ -0,0 +1,257 @@
/*
* Copyright 2015-2018 Jeeva Kandasamy (jkandasa@gmail.com)
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
myControllerModule.controller('UsersControllerList', function(alertService,
$scope, SecurityFactory, $state, $uibModal, displayRestError, mchelper, CommonServices, $filter) {
//GUI page settings
$scope.headerStringList = $filter('translate')('USERS_DETAIL');
$scope.noItemsSystemMsg = $filter('translate')('NO_USERS_SETUP');
$scope.noItemsSystemIcon = "fa fa-users";
//load empty, configuration, etc.,
$scope.mchelper = mchelper;
$scope.filteredList=[];
//data query details
$scope.currentPage = 1;
$scope.query = CommonServices.getQuery();
$scope.queryResponse = {};
//Get min number
$scope.getMin = function(item1, item2){
return CommonServices.getMin(item1, item2);
};
//get all Sensors
$scope.getAllItems = function(){
SecurityFactory.getAllUsers($scope.query, function(response) {
$scope.queryResponse = response;
$scope.filteredList = $scope.queryResponse.data;
$scope.filterConfig.resultsCount = $scope.queryResponse.query.filteredCount;
},function(error){
displayRestError.display(error);
});
}
//Hold all the selected item ids
$scope.itemIds = [];
$scope.selectAllItems = function(){
CommonServices.selectAllItems($scope);
};
$scope.selectItem = function(item){
CommonServices.selectItem($scope, item);
};
//On page change
$scope.pageChanged = function(newPage){
CommonServices.updatePageChange($scope, newPage);
};
//Filter change method
var filterChange = function (filters) {
//Reset filter fields and update items
CommonServices.updateFiltersChange($scope, filters);
};
$scope.filterConfig = {
fields: [
{
id: 'username',
title: $filter('translate')('USERNAME'),
placeholder: $filter('translate')('FILTER_BY_USERNAME'),
filterType: 'text'
},
{
id: 'fullName',
title: $filter('translate')('FULL_NAME'),
placeholder: $filter('translate')('FILTER_BY_FULL_NAME'),
filterType: 'text',
},
{
id: 'email',
title: $filter('translate')('EMAIL'),
placeholder: $filter('translate')('FILTER_BY_EMAIL'),
filterType: 'text',
}
],
resultsCount: $scope.filteredList.length,
appliedFilters: [],
onFilterChange: filterChange
};
//Sort columns
var sortChange = function (sortId, isAscending) {
//Reset sort type and update items
CommonServices.updateSortChange($scope, sortId, isAscending);
};
$scope.sortConfig = {
fields: [
{
id: 'username',
title: $filter('translate')('USERNAME'),
sortType: 'text'
},
{
id: 'fullName',
title: $filter('translate')('FULL_NAME'),
sortType: 'text'
},
{
id: 'email',
title: $filter('translate')('EMAIL'),
sortType: 'text'
},
{
id: 'enabled',
title: $filter('translate')('ENABLED'),
sortType: 'text'
}
],
onSortChange: sortChange
};
//Edit item
$scope.edit = function () {
if($scope.itemIds.length == 1){
$state.go("settingsUsersAddEdit", {'id':$scope.itemIds[0]});
}
};
//Delete item(s)
$scope.delete = function (size) {
var modalInstance = $uibModal.open({
templateUrl: 'partials/common-html/delete-modal.html',
controller: 'ControllerDeleteModal',
size: size,
resolve: {}
});
modalInstance.result.then(function () {
SecurityFactory.deleteUserIds($scope.itemIds, function(response) {
alertService.success($filter('translate')('ITEMS_DELETED_SUCCESSFULLY'));
//Update display table
$scope.getAllItems();
$scope.itemIds = [];
},function(error){
displayRestError.display(error);
});
}),
function () {
//console.log('Modal dismissed at: ' + new Date());
}
};
});
//Add Edit item
myControllerModule.controller('UsersControllerAddEdit', function ($scope, $stateParams, $state, SecurityFactory, TypesFactory, mchelper, alertService, displayRestError, $filter) {
$scope.mchelper = mchelper;
$scope.item = {};
$scope.item.user = {};
$scope.item.user.enabled = true;
if($stateParams.id){
SecurityFactory.getUser({"id":$stateParams.id},function(response) {
$scope.item = response;
},function(error){
displayRestError.display(error);
});
}
//GUI page settings
$scope.showHeaderUpdate = $stateParams.id;
$scope.headerStringAdd = $filter('translate')('ADD_USER');
$scope.headerStringUpdate = $filter('translate')('UPDATE_USER');
$scope.cancelButtonState = "settingsUsersList"; //Cancel button state
$scope.saveProgress = false;
//$scope.isSettingChange = false;
//Pre load
$scope.roles = SecurityFactory.getAllRolesSimple();
$scope.save = function(){
$scope.saveProgress = true;
if($stateParams.id){
SecurityFactory.updateUser($scope.item,function(response) {
alertService.success($filter('translate')('ITEM_UPDATED_SUCCESSFULLY'));
$state.go("settingsUsersList");
},function(error){
displayRestError.display(error);
$scope.saveProgress = false;
});
}else{
SecurityFactory.createUser($scope.item,function(response) {
alertService.success($filter('translate')('ITEM_CREATED_SUCCESSFULLY'));
$state.go("settingsUsersList");
},function(error){
displayRestError.display(error);
$scope.saveProgress = false;
});
}
}
});
//Add Edit item
myControllerModule.controller('ProfileControllerUpdate', function ($scope, $stateParams, $state, SecurityFactory, TypesFactory, mchelper, alertService, displayRestError, $filter) {
$scope.mchelper = mchelper;
$scope.item = {};
$scope.item.user = {};
$scope.item.user.enabled = true;
$scope.resetProfile = function(){
SecurityFactory.getProfile(function(response) {
$scope.item = response;
mchelper.user = angular.copy(response.user);
},function(error){
if(error.statusText === 'Unauthorized'){
$state.go("login");
}else{
displayRestError.display(error);
}
});
}
//GUI page settings
$scope.showHeaderUpdate = $stateParams.id;
$scope.headerStringAdd = $filter('translate')('PROFILE');
$scope.headerStringUpdate = $filter('translate')('PROFILE');
$scope.cancelButtonState = "dashboard"; //Cancel button state
$scope.saveProgress = false;
//$scope.isSettingChange = false;
//Load self details
$scope.resetProfile();
$scope.save = function(){
$scope.saveProgress = true;
SecurityFactory.updateProfile($scope.item,function(response) {
alertService.success($filter('translate')('PROFILE_UPDATED_SUCCESSFULLY'));
$scope.saveProgress = false;
$scope.editEnable.profile = false;
$scope.resetProfile();
},function(error){
displayRestError.display(error);
$scope.saveProgress = false;
});
}
});

View File

@@ -0,0 +1,130 @@
/*
* Copyright 2015-2018 Jeeva Kandasamy (jkandasa@gmail.com)
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
myControllerModule.controller('VariablesMapperListController', function(alertService, $scope, $filter, displayRestError, TypesFactory, $filter, mchelper, CommonServices, $state) {
//GUI page settings
$scope.headerStringList = $filter('translate')('SENSORS_AND_VARIABLES_MAPPING');
//load empty, configuration, etc.,
$scope.mchelper = mchelper;
$scope.filteredList=[];
//data query details
$scope.currentPage = 1;
$scope.query = CommonServices.getQuery();
$scope.queryResponse = {};
//get all items
$scope.getAllItems = function(){
TypesFactory.getSensorVariableMapper(function(response) {
$scope.orgList = response;
$scope.filteredList = $scope.orgList;
$scope.filterConfig.resultsCount = $scope.filteredList.length;
},function(error){
displayRestError.display(error);
});
}
//Pre load
$scope.getAllItems();
$scope.itemName = null;
//Filter change method
var filterChange = function (filters) {
//Reset filter fields and update items
CommonServices.filterChangeLocal(filters, $scope);
$scope.itemName = null;
};
$scope.filterConfig = {
fields: [
{
id: 'displayName',
title: $filter('translate')('SENSOR_TYPE'),
placeholder: $filter('translate')('FILTER_BY_SENSOR_TYPE'),
filterType: 'text'
},{
id: 'value',
title: $filter('translate')('SENSOR_VARIABLES'),
placeholder: $filter('translate')('FILTER_BY_SENSOR_VARIABLES'),
filterType: 'array'
},
],
resultsCount: $scope.filteredList.length,
appliedFilters: [],
onFilterChange: filterChange
};
//Select item
$scope.selectItem = function (item) {
if($scope.itemName === item.displayName){
$scope.itemName = null;
}else{
$scope.itemName = item.displayName;
}
};
//Edit item
$scope.editItem = function () {
$state.go("settingsVariablesMapperEdit", {'sensorType':$scope.itemName});
};
});
//Edit mapping
myControllerModule.controller('VariablesMapperEditController', function ($scope, TypesFactory, $filter, $stateParams, mchelper, alertService) {
//GUI page settings
$scope.headerStringAdd = $filter('translate')('MODIFIY_SENSOR_VARIABLES_MAPPING');
$scope.cancelButtonState = "settingsVariablesMapperList"; //Cancel button state
$scope.saveProgress = false;
$scope.item = {};
$scope.sensorVariableTypes = {};
$scope.item.displayName = $stateParams.sensorType;
$scope.item.value = [];
$scope.getSensorVariables = function(){
TypesFactory.getSensorVariableMapperByType({"sensorType": $scope.item.displayName}, function(resource){
$scope.sensorVariableTypes = resource;
angular.forEach($scope.sensorVariableTypes, function(value, key) {
if(value.ticked){
$scope.item.value.push(value.displayName);
}
});
});
};
//pre load
$scope.getSensorVariables();
$scope.save = function(){
$scope.saveProgress = true;
TypesFactory.updateSensorVariableMapper($scope.item,function(response) {
$scope.saveProgress = false;
alertService.success($filter('translate')('ITEM_UPDATED_SUCCESSFULLY'));
},function(error){
$scope.saveProgress = false;
displayRestError.display(error);
});
}
});

View File

@@ -0,0 +1,221 @@
/*
* Copyright 2015-2018 Jeeva Kandasamy (jkandasa@gmail.com)
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
myControllerModule.controller('VariablesRepositoryController', function(alertService,
$scope, VariablesRepositoryFactory, $state, $uibModal, $stateParams, displayRestError, mchelper, CommonServices, $filter) {
//GUI page settings
$scope.headerStringList = $filter('translate')('VARIABLES_DETAIL');
$scope.noItemsSystemMsg = $filter('translate')('NO_VARIABLES_SETUP');
$scope.noItemsSystemIcon = "fa fa-list-alt";
//load empty, configuration, etc.,
$scope.mchelper = mchelper;
$scope.filteredList=[];
//data query details
$scope.currentPage = 1;
$scope.query = CommonServices.getQuery();
$scope.queryResponse = {};
//Get min number
$scope.getMin = function(item1, item2){
return CommonServices.getMin(item1, item2);
};
if($stateParams.resourceType){
$scope.query.resourceType = $stateParams.resourceType;
$scope.query.resourceId = $stateParams.resourceId;
}
//get all items
$scope.getAllItems = function(){
VariablesRepositoryFactory.getAll($scope.query, function(response) {
$scope.queryResponse = response;
$scope.filteredList = $scope.queryResponse.data;
$scope.filterConfig.resultsCount = $scope.queryResponse.query.filteredCount;
},function(error){
displayRestError.display(error);
});
}
//Hold all the selected item ids
$scope.itemIds = [];
$scope.selectAllItems = function(){
CommonServices.selectAllItems($scope);
};
$scope.selectItem = function(item){
CommonServices.selectItem($scope, item);
};
//On page change
$scope.pageChanged = function(newPage){
CommonServices.updatePageChange($scope, newPage);
};
//Filter change method
var filterChange = function (filters) {
//Reset filter fields and update items
CommonServices.updateFiltersChange($scope, filters);
};
$scope.filterConfig = {
fields: [
{
id: 'key',
title: $filter('translate')('KEY'),
placeholder: $filter('translate')('FILTER_BY_KEY'),
filterType: 'text'
},
{
id: 'value',
title: $filter('translate')('VALUE'),
placeholder: $filter('translate')('FILTER_BY_VALUE'),
filterType: 'text'
},
{
id: 'value2',
title: $filter('translate')('VALUE2'),
placeholder: $filter('translate')('FILTER_BY_VALUE2'),
filterType: 'text'
},
{
id: 'value3',
title: $filter('translate')('VALUE3'),
placeholder: $filter('translate')('FILTER_BY_VALUE3'),
filterType: 'text'
}
],
resultsCount: $scope.filteredList.length,
appliedFilters: [],
onFilterChange: filterChange
};
//Sort columns
var sortChange = function (sortId, isAscending) {
//Reset sort type and update items
CommonServices.updateSortChange($scope, sortId, isAscending);
};
$scope.sortConfig = {
fields: [
{
id: 'key',
title: $filter('translate')('KEY'),
sortType: 'text'
},
{
id: 'value',
title: $filter('translate')('VALUE'),
sortType: 'text'
},
{
id: 'value2',
title: $filter('translate')('VALUE2'),
sortType: 'text'
},
{
id: 'value3',
title: $filter('translate')('VALUE3'),
sortType: 'text'
}
],
onSortChange: sortChange
};
//Delete item(s)
$scope.delete = function (size) {
var modalInstance = $uibModal.open({
templateUrl: 'partials/common-html/delete-modal.html',
controller: 'ControllerDeleteModal',
size: size,
resolve: {}
});
modalInstance.result.then(function () {
VariablesRepositoryFactory.deleteIds($scope.itemIds, function(response) {
alertService.success($filter('translate')('ITEMS_DELETED_SUCCESSFULLY'));
//Update display table
$scope.getAllItems();
$scope.itemIds = [];
},function(error){
displayRestError.display(error);
});
}),
function () {
//console.log('Modal dismissed at: ' + new Date());
}
};
//Edit item
$scope.edit = function () {
if($scope.itemIds.length == 1){
$state.go("variablesRepositoryAddEdit",{'id':$scope.itemIds[0]});
}
};
});
//Add Edit script controller
myControllerModule.controller('VariablesRepositoryControllerAddEdit', function ($scope, $stateParams, $state,
VariablesRepositoryFactory, mchelper, alertService, displayRestError, $filter, CommonServices) {
$scope.mchelper = mchelper;
$scope.item = {};
$scope.cs = CommonServices;
$scope.showData = false;
if($stateParams.id){
VariablesRepositoryFactory.get({"id":$stateParams.id},function(response) {
$scope.item = response;
$scope.showData = true;
},function(error){
displayRestError.display(error);
$scope.showData = true;
});
}else{
$scope.showData = true;
}
$scope.editorOptions = {
lineWrapping : true,
lineNumbers: true,
readOnly: 'nocursor',
mode: 'xml',
};
//GUI page settings
$scope.showHeaderUpdate = $stateParams.id;
$scope.headerStringAdd = $filter('translate')('ADD_VARIABLE');
$scope.headerStringUpdate = $filter('translate')('UPDATE_VARIABLE');
$scope.cancelButtonState = "variablesRepositoryList"; //Cancel button url
$scope.saveProgress = false;
$scope.save = function(){
$scope.saveProgress = true;
VariablesRepositoryFactory.update($scope.item, function(response) {
alertService.success($filter('translate')('ITEM_UPDATED_SUCCESSFULLY'));
$state.go("variablesRepositoryList");
},function(error){
displayRestError.display(error);
$scope.saveProgress = false;
});
}
});

BIN
www/images/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

BIN
www/images/mc_logo.gif Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

BIN
www/images/mc_logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.0 KiB

Some files were not shown because too many files have changed in this diff Show More