• Nenhum resultado encontrado

PowerGame - Uma aplicação de suporte aos jogos sérios usando medições energéticas reais

N/A
N/A
Protected

Academic year: 2021

Share "PowerGame - Uma aplicação de suporte aos jogos sérios usando medições energéticas reais"

Copied!
78
0
0

Texto

(1)

F

ACULDADE DE

E

NGENHARIA DA

U

NIVERSIDADE DO

P

ORTO

PowerGame: A support application for

serious games using real life energy

measurements

José Carlos Cadilha Coelho

D

ISSERTATION

Mestrado Integrado de Engenharia Informática e de Computação Supervisor: Rui Rodrigues

(2)

c

(3)

PowerGame: A support application for serious games

using real life energy measurements

José Carlos Cadilha Coelho

Mestrado Integrado de Engenharia Informática e de Computação

Approved in oral examination by the committee:

Chair: Doctor António Augusto de Sousa

External Examiner: Doctor Maximino Esteves Correia Bessa Supervisor: Doctor Rui Pedro Amaral Rodrigues

(4)
(5)

Resumo

Nesta tese vamos descrever os problemas encontrados pela SmartWatt, uma empresa de consul-tadoria no domínio de consumo e gestão energética, no que toca a transferência de conhecimento com os seus clientes e colaboradores em boas praticas de gestão de energia, e o cumprimento de ditas práticas no dia a dia. Para o fazer, vamos estudar a influência e eficácia dos jogos sérios na aprendizagem, e como os mecanismos de recompensa nos jogos de video conseguem aumentar a vontade do jogador absorver conhecimento novo. Adicionalmente, vamos pesquisar sobre como a opinião subconsciente dos utilizadores pode ser influenciada usando técnicas persuasivas e como ao incluir essas técnicas num jogo sério se pode traduzir no regular e consistente uso de boas práticas de gestão energética.

Iremos falar sobre os desafios de modificar a lógica interna da aplicação responsável por mon-itorizar remotamente sobre TCP/IP a unidade de medição, convertendo-a numa aplicação que tira vantagem de uma ligação série local e corre num sistema Linux ao invés de Windows.

De modo a criar um protótipo eficaz, foi feita pesquisa sobre vários jogos sérios cujo objectivo principal era convencer e aliciar os utilizadores a utilizar uma série de boas práticas ao longo do tempo, tais como aquelas exigidas para uma boa gestão energética e uma alimentação saudável. Ao estudar as mecânicas de jogo e mecanismos de recompensa utilizados em cada jogo, vamos ser capazes de definir um conjunto de funcionalidades cativantes que estão provadas funcionar na aprendizagem a longo prazo.

Para nos ajudar a alcançar os efeitos a longo termo de boas práticas de gestão energéticas, foi criada uma aplicação que usa medições de energia reais para servir como suporte a jogos sérios. Usando um conjunto de mecanismos de aprendizagem previamente provados úteis, em conjunto com o uso de tecnologia persuasiva para diminuir a intrusividade da mensagem a ser assimilada, esta aplicação actuará como um sistema visual de feedback no que toca ao desempenho de gestão energética, enquanto serve simultaneamente como back-end para jogos sérios.

Um conjunto de linhas de guia para futuros testes foi criado de modo a ajudar a determinar a utilidade do protótipo, e a guiar na descoberta de quais funcionalidades de jogo são mais efi-cientes em mudar o comportamento dos utilizadores. Adicionalmente propomos uma sequência de trabalho futuro a ser concretizado de modo a continuar a melhoria do sistema Power Game.

(6)
(7)

Abstract

In this thesis we will describe the problems faced by SmartWatt, a consulting company in the do-main of energy consumption and management, when it comes to knowledge transfer to its clients and associates of the best practices in energy management, and the enforcement of said practices on a daily basis. To do so, we will take a look over the influence and effectiveness of serious games in learning, and how the reward mechanisms in video games can increase the willingness of the player to absorb new knowledge. In addition, we will glance over how the users subconscious opinion can be influenced using persuasive techniques and how by including those in a serious game it can translate into a consistent and customary use of best practices.

In order to create an effective prototype, research was made on several serious games whose main objective was to convince and entice users to apply a series of good practices over time, like those required for good energy management or healthy eating. By studying the game mechanics and reward mechanisms employed in each game, we will be able to define a set of interesting and engaging features that are proven to work on long term learning.

We talk about the challenges of modifying the inner logic of the application responsible for remotely monitoring the measuring terminal unit over TCP/IP, turning it into an application which takes advantage of a local serial connection and runs on a Linux system instead of Windows.

To help achieve the long term effects of good energy management, an application that uses real life measurements was created to act as support to serious games. Using a set of learning mechanisms previously proven useful, in conjunction with the use of persuasive technology to di-minish the intrusiveness of the message to be assimilated, this application acts as a visual feedback system regarding energy management performance, while simultaneously serving as a back-end for serious games.

The created Test Scenario Guidelines will help overseers assess the usefulness of the proto-type on their particular environment, and will guide them in discovering what game features are most effective in changing user behaviour. We further propose a sequence of future work to be accomplished in order to further improve the Power Game system.

(8)
(9)

Acknowledgements

To my teachers, from the first to the last To my family, for always being there To my friends, for all the fun times To my girlfriend, for all the support To my colleagues, for all the help given

To Ruben Costa, Tiago Santos, the folk at SmartWatt and Professor Rui Rodrigues for all the availability and feedback provided

To all the great people before and after My deepest thanks

(10)
(11)

“Don’t compare yourself with anyone in this world... if you do so, you are insulting yourself.”

(12)
(13)

Contents

1 Introduction 1

1.1 Objectives . . . 2

1.2 Dissertation Structure . . . 2

2 State of the Art Review 3 2.1 Persuasive Technology . . . 3

2.2 Serious Games and Application Examples . . . 4

2.2.1 Power Agent . . . 5

2.2.2 Power House . . . 6

2.2.3 Persuasive Fish Tank . . . 7

2.3 Technology Overview . . . 9 2.3.1 libGDX . . . 9 2.3.2 Turbulenz . . . 10 2.3.3 Playcraft . . . 10 2.3.4 NodeJS . . . 10 3 PowerGame System 13 3.1 Goals . . . 13 3.2 PowerGame Application . . . 13

3.2.1 Requirements and User Stories . . . 14

3.2.2 Concept . . . 16

3.2.3 PowerGame Work Flow . . . 17

3.3 Global System Architecture . . . 18

3.4 Architecture Implementation . . . 18 4 Measurements 21 4.1 Data Logging . . . 21 4.1.1 Circutor Device . . . 21 4.1.2 Data . . . 22 4.1.3 MyGenBox . . . 25 5 Web App 31 5.1 PowerGame Application . . . 31 5.1.1 WebApp Architecture . . . 31 5.1.2 Organizational Hierarchy . . . 33 5.1.3 Database Architecture . . . 34 5.1.4 WorkFlow . . . 35

(14)

CONTENTS

5.1.6 Implemented Features . . . 38

6 Tests and Results 41 6.1 Data Testing . . . 41

6.2 Test Scenarios . . . 43

6.2.1 T1 - Login Regularity . . . 43

6.2.2 T2 - Mission Influence . . . 44

6.2.3 T3 - Mission After burn . . . 44

6.2.4 T4 - Reward Influence . . . 45

7 Conclusions and Future Work 47 7.1 Future Work . . . 48

A Apendix I 49

References 57

(15)

List of Figures

2.1 Screenshots of the Power Agent Game . . . 5

2.2 Screenshots of the Power House Game . . . 7

2.3 Different feedback stages of persuasive fish tank . . . 8

3.1 Pre Development Concept . . . 16

3.2 Planning for Website Workflow . . . 17

3.3 High Level View of the System Architecture . . . 18

3.4 Architecture of the System . . . 19

4.1 System Setup . . . 22

4.2 Jamod Sequence . . . 24

4.3 Data Array Structure . . . 27

4.4 Jamod Modification . . . 29

5.1 Folder Structure for the NodeJS App . . . 32

5.2 Group Structure . . . 34

5.3 Database Schema for PowerGame . . . 34

5.4 Login Screen . . . 35

5.5 Admin Signup . . . 36

5.6 Game Screen . . . 37

5.7 The Active Missions . . . 38

6.1 Data Graph of the Instant Consumption Variable . . . 42

6.2 Data Graph of the Accumulated Consumption Variable . . . 43

A.1 User Being Promoted to Admin . . . 49

A.2 Group Criation . . . 51

A.3 Admin Creating Mission . . . 52

A.4 Mission Activation . . . 53

A.5 End Mission . . . 54

A.6 Acknowledge Log . . . 55

A.7 Daily Bonus . . . 56

(16)

LIST OF FIGURES

(17)

List of Tables

2.1 Feature comparison of apps reviewed . . . 5

4.1 Single, Two and Triple phase variables . . . 23

4.2 Modbus RTU Frame Format . . . 23

4.3 Modbus Serial Connection Parameters . . . 25

4.4 Device Parameters . . . 26

(18)

LIST OF TABLES

(19)

Abbreviations and Symbols

AP Administration Panel

API Application Programming Interface CPU Central Processing Unit

CRUD Create, Read, Update and Delete ePoints Energy Points

HUD Head Up Display

IDE Integrated Development Environment I/O Input/Output

JDK Java Development Kit MGB MyGenBox

MHz Mega Hertz mongoDB Mongo Database ms Milliseconds

NPM Node Package Modules OS Operating System PC Personal Computer

R&D Research and Development

SCADA Supervisory Control And Data Acquisition SDK Software Development Kit

SSH Secure Shell

TCP/IP Internet Protocol Suite or TCP over IP USB Universal Serial Bus

(20)
(21)

Chapter 1

Introduction

With the increasing scarceness of fossil fuels, one of the most used products in energy generation, energy costs are expected to continue to rise in the near future. It is then of no surprise that energy expenditures is starting to become one of companies biggest concern. According to a recent study by Delloite [Del12], "90% of the companies have set goals regarding electricity and energy management practices". Although many claim such practices have as a goal reducing costs, these are not always obvious or easy to implement. For such cases, 3rd party consulting companies specialized in the energy domain are required to conduct a study.

SmartWatt(SW) is a Portuguese consulting company that studies the energy efficiency of cor-porations, schools and other associations. By recurring to a set of measurement devices that mon-itor energy use, SW is able to keep an accurate history of energy use across a long span of time, creating a baseline of the client company energy waste. This baseline, in conjunction with the tariff being used by said company to pay his electrical bills, allows them to detect the critical time intervals where inefficiency is at his highest. After the study is done, the client company receives an action plan that if followed, should make it possible to lower expenditures and lead to higher profitability.

The value of such action plan is not always apparent and its effectiveness is always dependent on the willingness of the participants to follow the guidelines created. Even if the plan is followed to perfection by all company collaborators, the feedback obtained which most of the times is limited to a financial result, is not always instant. Depending on the time frame where the biggest inefficiency lies, positive reinforcement can take months to appear, assuming that the company can persevere with high efficiency by following a plan without any feedback system during that span of time.

As stated, one of the few items that can be useful as a feedback system for this case is the amount of financial resources allocated for energy use. The problem herein is that no one besides the executive board or financial department has access, or is influenced by, the savings achieved. An employee working at a desk answering customers calls will have no incentive to turn off the lights or shut down the computer when he goes to lunch, which is a hindrance when trying to implement the plan created by the consulting company.

(22)

Introduction

The problems found when implementing energy saving policies can be put into three different categories: ignorance, forgetfulness, and sloth. Ignorance is solved with an action plan delineated by a specialized consulting company like SW, forgetfulness and sloth will need a solution that keeps the good practices fresh in the users memory, while enticing them to have a proactive stance on energy saving without a decay in efficiency of said stance over time.

1.1

Objectives

The objective of this master thesis is to design a support application for serious games that can influence effectively through the use of persuasive technology the players to act regularly on a set of good energy saving practices.

1.2

Dissertation Structure

In Chapter 1 we give a brief introduction to this dissertation, by describing the problem and giving a possible solution, the objectives we expect to achieve and the expected results.

In Chapter 2 we do the bibliographic revision, where we study the topics of serious games, persuasive technologies and give examples of serious games and applications that already to some extend persuade people to apply best practices of energy management, discussing what they do right and what they do wrong. We also give a brief overview about possible technologies to be used with the prototype.

In Chapter 3 we talk about the general architecture of the prototype, including a brief introduc-tion of the necessary systems and ways for user interacintroduc-tion. We’ll also brush over what we intend to achieve with the implemented prototype, including possible game concepts, how the framework will work and we will go over the typical use flow for a regular player and an administrator.

In Chapter 5 we describe in detail the work done while implementing the prototype, which includes two big sections: data logging and the web framework. On data logging we’ll glance over the devices and hardware, as well as the industry standard protocols used, and further details on implementation and the problems faced on that task. On the web framework we’ll justify the technologies chosen for implementation, explain the architecture of both framework and database systems used.

In Chapter 6 we explain the test carried out in order to better understand the viability of the data used, and delineate several test case scenarios that can be used in the future to measure the effectiveness of the use of the app in each instance.

In Chapter 7 we close this dissertation with the conclusions we arrived at and give some point-ers on future work.

(23)

Chapter 2

State of the Art Review

In order to ensure the best results with our proposed solution we first need to take a look at what has already been made in the area, allowing us to take note of the flaws encountered and improve upon the features and solutions that are proven to work. In this chapter we will present an overview of the literary review made, which included subjects on the topic of ’Learning Methodologies’, ’Persuasive Technologies’ and ’Serious Games’.

2.1

Persuasive Technology

According to Fogg [Fog02] persuasive technology can be considered any technology that was made to mould the attitudes and behaviours of users through persuasion and social influence, but not through coercion. According to the same author, persuasion can be categorized into five different categories: physical, psychological, language, social dynamics and social roles. Several experiments were conducted to prove the influence of these five types of persuasion in influencing the perception one has about someone or something, thus influencing decision making.

The physical type considers physical characteristics and attractiveness, taking advantage of the increased trust the human mind places into someone we consider attractive. An example of this would be the use of pleasantly looking characters, famous people and attractive interfaces. Besides the experiment made by Fogg on this subject, an extensive study on the marketing of children food [BHKH11] shows that the use of promotional characters or celebrity endorsers, as well as logos and slogans deeply sways the decision making of children, while simultaneously increasing the thrust given by parents to the product or brand.

The psychological type considers hints that portray the existence of emotion or personality in the technological system, leading the user to behave as if he was interacting with a real human. We can then design the system in order to take advantage of the human tendency to listen more attentively to similar people or people affiliated to a common group. On a different article by Russo [RC10] about the influence of persuasion in decision making, an experiment is done to see how this tendency can lead someone to choose one of two equal products presented in two

(24)

State of the Art Review

different ways, according to the way they identify themselves and the similarity they find between them and the way the product is presented.

The language type considers the different types of language that can be used to better suit the user, and the different messages text can transmit depending on how it is presented. For example, an application that constantly addresses its user by name will transmit a more familiar feeling to the experience. Depending on how it is written, text can seem friendly, inquisitive, affirmative, demanding, and others. By combining this fact with previous explained types of persuasion, we can create an application that seems insecure and introverted to better influence insecure and introvert users. That same way, if the application targets for example, rap singers, the colloquialisms used by those users should be taken into account when designing the application.

The social dynamics type considers the cultural norms and rules the user is accustomed to. The most common example of this is the greeting of someone that just arrived or logged in, which is universal throughout almost every culture. This type of persuasion needs to be implemented very carefully, because what some cultures might consider the norm, others might consider offensive.

The social roles type considers the perception of importance of each role in society, and the ability of that role to perform a given task. For example, a piece of software that performs a diagnostic of sorts will persuade more users to buy it if it possesses ’Dr’ on its name, a profession that is given great respect by society and is associated with performing diagnostics and ’fixing’ the ill. Likewise, a learning application will influence the user more if it includes ’Teacher’ in the title.

The language and social dynamics need to be carefully incorporated, since tipping the scale too much in one way will alienate the user base on the opposite end, creating an unintended undesired effect on the application.

In sum, persuasive technology tries to emulate favourable traces of human personality in order to achieve a higher degree of thrust and commitment from the user.

2.2

Serious Games and Application Examples

When reviewing all the different applications related to energy saving and learning a set of com-mon features were found that we were interested in having in PowerGame. These features can be found and be missing interchangeably in several applications. A description of all the important features can be found bellow.

Measurements: These applications use real life measurements as input for their game and as feedback, either internally on the app or externally to the users, for the players actions. Multi Platform: These applications run on multiple devices or operating systems. If no details

are provided otherwise, we assume the application failed to comply with this requirement. Learning Mechanisms: These applications use some form of feedback or learning mechanism

to let the user know the consequences of their actions. 4

(25)

State of the Art Review

Feature Measurements Multi Platform Learning Rewards Power House X X V V Power Agent V X X X Persuasive Fish Tank V X V X

Table 2.1: Feature comparison of apps reviewed

Reward Mechanisms: These applications use some form of reward to reinforce positive be-haviours. Be it points, virtual items, benefits or even levelling up counts as a reward. A summarized feature comparison for the following applications can be found on Table 2.1

2.2.1 Power Agent

Power Agent [BGK07] is a mobile video-game prototype conceptualized and developed by a re-search group for the Sweden Energy Agency. The paper describing the process and reason behind the design of this game states that there is no such thing as knowledge transfer, but that learners actively construct knowledge built on previous experience of real world tasks. By blurring the line between what is simulated and what is real, researchers hope to increase success of situated learning, achieving behavioural changes by contextualizing familiar activities in the social context the user lives in.

Figure 2.1: Screenshots of the Power Agent Game

Researchers proposed therefore the creation of a pervasive game, a game that somehow ex-pands the virtual gaming experience to the physical world. Examples of this are location based games like geo-caching, where the progress of the player and the hints for the locations to visit are virtually stored, while the actions of the player itself are conducted in the real life world.

(26)

State of the Art Review

According to the document revision made, in pervasive gaming rules inside the game tend to alter the notions of rules outside the game, more so if said rules are in some way socially contextualized. This leads to activities in game that require adaptability from the player to help him recognize the problems and transfer such skills to outside the game.

To implement this, they suggest following the four tenets of pervasive learning games by Thomas [Tho06] , where players are directly responsible and in control for their own learning process (autonomy), connected to places and other players (community), learn in a location and time relevant for the subject they’re expanding their knowledge into (location) and where they construct relevant scenarios to which they can relate, easing the learning process (relation).

Social learning theories explains "human behaviour as an interaction process between cogni-tive, behavioural and social components". By rewarding and punishing certain actions, the game is showing the outcome of certain choices, which will be reinforced by their peers by course of regular conversation, or to a greater degree if such rewards or consequences affect the social group as a whole.

In the Power Agent game, as can be seen in figure 2.1, the user role plays a secret agent that receives missions through its mobile phone. This can be categorized in training missions (where the player runs through a classic platform level, grabbing tips and hints about saving energy and influencing family and friends) or real life tasks missions that range from the obvious and direct (turn off all stand by appliances) to those who require more thought from the player (minimize household consumption for a day). Each player household has a series of measurements (electri-cal consumption, water heating) that are used to measure the performance during the real world missions. These performances are clustered into groups of players and shown to every group in order to entice competitiveness and increase awareness.

This two stage play mode is based on Bandura [BM77], who suggests a two stage model for learning, where first a behaviour can be symbolically rehearsed and later enacted.

2.2.2 Power House

This video game [BTK06] proposes to teach young people how to save energy on every day tasks performed at home, using for this effect persuasive techniques as delineated by Fogg. By taking advantage of the use of a simulated environment that is relatable to the task at hand, it allows the users to experiment with trial and error, get accustomed to the environment and the influence their actions have over it, foundation of simulation games used for learning purposes like those used in the air force. Another commonly used technique is called Operant Conditioning, which has as a goal to manipulate future behaviour by giving positive or negative reinforcement.

As explained earlier, the use of easily identifiable characters or persons can influence the thrust level felt by the user when completing a task or making a decision. This technique is put to good effect on the game, that provides a set of avatars within the age range of the users without any negative features in its complexion, with an emphasis on attractive physical features.

As can be seen in figure 2.2, in this game the player controls the house inhabitants to perform a series of tasks that provide happiness but consume energy, resulting in extra income as virtual

(27)

State of the Art Review

Figure 2.2: Screenshots of the Power House Game

money when tasks are successful, income that the player can use to improve efficiency of several parts of the house, or not. An example given is that of taking a shower, the longer the shower takes, the more currency is depleted in the form of energy, but the more happiness is generated by the user taking it. As the main goal of the game is to keep all the characters inside the house as long as possible, a balancing act needs to be made. The immediate feedback of the draining currency helps the user realize how taxing each task is, and the influence of the upgrade of different devices such as a massage shower, or an efficiency A washing machine.

The actions of the players are many times influenced, praised or criticized by the "show host", as a way to reinforce the conditioning loop.

One of the main flaws of this game is the purely virtual approach to learning. As the game takes no use of real life measurements, the game relies on the willpower of the player to practice what he learns in game outside of it.

2.2.3 Persuasive Fish Tank

This research [CLH+11] was conducted due to concerns about global warming. According to several studies reviewed by this group, a big percentage of energy consumption nationwide can be attributed to homes and corporations (inside buildings). Since alternative energy generation methods are very expensive, a good way to save energy is to teach people how to effectively save energy both at home and on the job.

(28)

State of the Art Review

Figure 2.3: Different feedback stages of persuasive fish tank

This paper summarizes several other studies that employed feedback systems as an energy saving teaching technique, most of which use additional incentives "such as reduction in electricity expenses, competition and peer education". All of these studies use simple text or graphs as feedback data, while the researchers of this paper will use a more augmented visual system to do it, as can be seen in figure 2.3.

The first problem with a feedback system is how the users personality relates to the feedback it receives. According to the studies at hand, biospheric and altruistic people tend to be more easily persuaded to practice beneficial behaviour when the feedback received is put on a positive light, while egotistical personalities tend to only cooperate when the consequences of its actions directly

(29)

State of the Art Review affect the individual or their loved ones.

To solve the problem this paper proposes the use of Computers as Persuasive Technology. The system takes the data collected from the energy consumption monitoring devices and transforms the virtual environment according to what considers good or bad, leading the user to a change in behaviour, which will in turn change the virtual environment.

To measure the effectiveness of this system a prototype was deployed on two offices with twenty PhD or master students each. Measurements were taken before and after the model intro-duction. Additional user perceptions and advice were recorded using questionnaires.

People were more active when directly responsible for paying the bills, and the negative feed-back proved to be more impactful in animals than on humans. Peer pressure was an important factor in the use of good practices.

The biggest problem left unanswered was how to prevent user fatigue from reducing the long term influence of the system on energy saving behaviour.

2.3

Technology Overview

For the proposed solution we chose to use a set of technologies that allowed us to deliver our prototype in the most amount of different devices possible. These technologies had to allow us to render some kind of graphical output to the user, and communicate between clients. To achieve this, we decided to use the latest iteration of the HTML standard, HTML5, which includes the Canvas specification for immediate mode 2D drawing. This will allow the user to run the pro-posed solution on any device able to run a browser that supports HTML5. To perform real time communication between clients we decided to use Node.js, a software system for the creation of scalable web applications capable of non-blocking event driven I/O.

In order to accelerate the development of the prototype additional research about game engines was done, a detailed list of JavaScript based engines and features can be found in [Htm]. We prioritized free engines with sprite management classes and networking support, while open source was a big plus when making the final verdict.

Conforming to these features we ended up with three different engines in the search phase: libGDX, Turbulenz and Playcraft. These engines were later scraped in favour of a more bare bones HTML5 framework, since the requirements for the web app were simplified in terms of graphical and interaction requirements although more complex in regards to data storage and 3rd party interaction. To deal with this we required a new scalable database system that could efficiently handle and process a large data set and a node module that would allows us to quickly develop a web API. Regardless of the actual use of the game engines in our app, we consider it relevant to present here the information regarding their features.

2.3.1 libGDX

LibGDX is an open source cross platform framework that abstracts several components of game development allowing the developer to write the code once and compile to Windows, Linux, Mac,

(30)

State of the Art Review

HMTL5, Android and iOS. The biggest advantage is the possibility of extending the features of the framework due to its open source nature. The biggest disadvantage is the bare bone nature of the framework, requiring the developer to create his own game engine before doing any prototype work.

2.3.2 Turbulenz

Turbulenz is a free HTML5 javascript game engine that supports shaders, particle systems, in-cludes a physics package and supports 3D sound sources. This engine also inin-cludes networking capabilities and built-in integration with social networks. This engine provides its own SDK.

2.3.3 Playcraft

Playcraft is an HTML5 game engine currently in beta state. It provides an object oriented devel-opment environment, includes a mobile framework to run the applications on Android and iOS, a physics package and multiplayer capabilities with the integration of Node.js. It uses spatial in-dexing to decrease rendering times and developers have access to a web based world editor that allows the inspection of object state, game performance and live testing of the game.

2.3.4 NodeJS

NodeJS is an open source platform built on Google’s V8 javascript engine and designed to build low-latency scalable network applications using an event-driven non blocking I/O model. In node all I/O operations are asynchronous, and all of them are invoked through a lower-level C++ layer [Nodb]. NodeJS works by running a single-threaded event loop that reads the event queue sequen-tially. While these I/O operations are being processed node can handle other events, and once an operation is concluded a callback is returned and sent to the queue. Due to a strong and growing community around this project a series of high performance drivers for middleware and other li-braries is available and easily integrated into NodeJS, the most notable of which were used being MongoDB, Jade and Express.

2.3.4.1 MongoDB

MongoDB is an open source document oriented NoSQL database system. Each JSON-style doc-ument is stored into a collection, and several collections can be stored in a single database. This db system supports indexing of any attribute in the document, provides auto-sharding, map/reduce and rich queries. MongoDB can have several documents in the same collection with a different schema between themselves, or missing attributes.

2.3.4.2 JADE

Jade is a nodeJS templating engine built on javascript and influenced by Haml. This library is available through the NPM and the purpose of the engine is to allow the web designer to write

(31)

State of the Art Review

jade code which doesn’t suffer from the verbosity required by the html standard, as this code is later compiled to html on the back end.

One of the main features used besides the beautification of code is the inheritance system that allows us to extend layout files with each other. In our case we created a template called ’lay-out.jade’ that served as a base to each page and included scripts, dependencies and dom elements common to every page. By including the line ’extends layout’ each jade file extended the base one. In addition, the existence of blocks allowed us to avoid the repetition of code with the inclusion of code sections into named blocks, that were later included in the needed section of a new page.

Although this engine is designed to take advantage of a different syntax, it also supports pure HTML mixed in with Jade. The use of JavaScript mixed in is also available, with loops and conditionals like ’if’ and ’unless’ supported directly as part of the Jade language.

2.3.4.3 Express

Express is a web application framework available for NodeJS through NPM. Express allows us to run a lightweight dedicated http server, and it simplifies the creation of a web API by taking advantage of its robust routing system. Express also supports caching of web-pages, simple access to URL variables and sending http responses.

In conclusion, we decided to choose a set of open source software in order to accelerate devel-opment and take advantage of the strong open source community and rising popularity of NodeJS, to facilitate and simplify further needs in regards to modules and extra tools required to be built to accommodate possible new features.

(32)

State of the Art Review

(33)

Chapter 3

PowerGame System

In the following chapter we will talk about what goals we intend to achieve with the PowerGame system and how we’ve designed and envisioned its functioning.

We will talk about the proposed solution, a visual feedback system and support application that uses real time measurements to provide the players with information about the outcome of their real life actions in a virtual world, and how we plan for it to be used after finished.

We finish this chapter with a section where we fit PowerGame into a broader context and talk about its dependencies in the whole system.

3.1

Goals

When designing the PowerGame our goal was to create an application that granted users the ability to understand the outcome of their actions in real life in regards to energy consumption habits, and help them better themselves on that subject through the use of something they enjoyed interacting with.

To support this we needed to use a system that allowed the PowerGame to accurately monitor the energetic behaviours of users.

3.2

PowerGame Application

The purpose of PowerGame, the nodeJS web app of the PowerGame system, is to act as a cen-tral hub between the measurements and 3rd party games, a hub where players can check their progress and the progress of others, and visually see their main inefficiencies and flaws in energy management.

It is expected in the future for the PowerGame back-end to provide an API that allows 3rd party games to access the information of the players registered in the PowerGame. Information such as the energy points obtained through saving energy or the stars from completing missions might be used as currency in those games to unlock cosmetic items or features.

(34)

PowerGame System

The PowerGame web app is split into two modules: the first, that every player has access to, is the User Panel, where the players have access to the information directly related to them and the group they belong to. The second, that only the administrators of each group and of SmartWatt have access to, is the Admin Panel, where the administrators have access to the controls that allows them to control and manage the group they belong to, and the direct child groups attached to it. On top of this the influence of a counsellor or teacher outside the game is expected to guide the players using learning techniques and to mould them into knowledgeable best practice followers.

3.2.1 Requirements and User Stories

After the initial design was outlined, the requirements that would describe it in detail were defined through a set of user stories that were then split into three modules: server, admin panel and user interface.

Some specific terms are used throughout these user stories which are not immediately under-standable, and can be described as follows:

Group In-game team corresponding to an institution/corporation/entity the user is part of. Mission One or more tasks in a predetermined sequence.

Tier of Competition Hierarchical level containing all children groups of a common super group. 3.2.1.1 Server

The server must be able to store:

- the name, password, email, ePoints, stars and time of last login of each user; - the relationship between users and groups;

- the name of each group;

- the relationship between groups;

- a flag to distinguish normal users from admins;

- data information about each group consumption levels; - information about each groups progress on missions; - information about missions created for each group; - the name, description, difficulty of each mission; - a flag to distinguish an active from an inactive mission; - the relationship between missions and groups;

- the content and date of each log;

- the relationship between a log and corresponding mission and user;

- a flag to distinguish between an acknowledged and unacknowledged mission; 14

(35)

PowerGame System 3.2.1.2 Admin Panel

The Admin must be able to:

- alternate between the Admin panel and the User Interface Module; - create a new group under the one he administrates;

- promote a regular user of a child group to an administrator; - create a mission;

- define a title and description for each mission;

- define the an associated value of difficulty between 1 and 3 points for each mission; - activate an inactive mission;

- send notifications warning the user of an active mission; - select the active missions to be accomplished by the group.

- acknowledge a mission as successful, granting the user with some reward points equivalent to the difficulty of said mission;

- see the logs sent by users regarding each mission; - see which user sent which log on which date and time; 3.2.1.3 User Interface

- upon arrival to the page, the user is faced with a login screen; - the user must be able to register;

- the user must be able to reset his password;

- the reset password must be sent to the stored email account; - the user must be rewarded for a daily login;

- the app must be able to automatically authenticate the user if he allowed cookies; - the user must be able to log out off his account;

- the app must warn the user on logout;

- the app must be able to show the real energy consumption line to the corresponding group. - the app must update the stars of the user every time a mission is completed successfully; - the app must update the ePoints of the user based on the savings calculated;

- the app must associate a performance value to each group using the variance between the real energy consumption and the baseline values;

- the app should display in a grid like interface the several peer groups and respective perfor-mance levels;

- the app must allow the user to see which active missions are available; - the app must allow the user to see information about each mission; - the app must allow the user to send a log to the administrator; - the app must confirm if the log sending was successful or not;

(36)

PowerGame System

3.2.2 Concept

In figure 3.1 we can see the concept created before the start of the development phase. In this concept the screen is split into three sections: the visual feedback system takes most of the space on the top left corner, the data graph is situated on the bottom left corner and the function section is located on the right.

Figure 3.1: Pre Development Concept

In the data graph section we can see the information received by the devices plotted in conjunc-tion with the baseline values belonging to the group the logged in user is part of. These baseline values are the energy consumption values that the users of this particular group are expected to consume on a minimum, meaning any value above this one will be considered unneeded waste. These baseline values are dependent on the study of the installations and business process and the use of calculations over the historic of consumption of all users over a predefined stretch of time. The background of the graph itself changes color depending on the positive of negative difference between the expected baseline values and the real consumption measurements.

In the visual feedback section, we can see three rows of tiles representing each a different child group from the same parent group. In order to be able to compare values between themselves, these child groups need to have each a different measurement or group of measurement devices. Each tile represents a set span of time, and its appearance changes depending on the performance achieved by the group during that time. In the beginning of each row an identifier for each group is found, and an avatar of the user is placed on the tile corresponding to the current time frame.

On the right side we have the function bar were the user can interact with the system. On the top area additional info is shown about each tile, such as the consumption and the specific time where it occurred. Bellow a set of color coded buttons is placed each corresponding to a different action. It was later decided to let the players compare their overall efficiency levels with others

(37)

PowerGame System

on the same level, to check active missions and to send a log telling the coordinator how the user contributed to the completion of the mission.

3.2.3 PowerGame Work Flow

Several kinds of different users will have access to the PowerGame website, and the way they interact with each other will differ depending on the roles they take. On the top of the permission chain we have the SmartWatt super administrator, which is the person responsible for coordination with a joining organisation that by enacting the initial creation of a group, giving admin access to the coordinator of that organization and helping him understand the workflow of the application enables this coordinator to become an independent admin capable of managing the PowerGame on his own accord. The following administrators all follow a top down hierarchy depending on who promoted who, and they are all responsible for guiding the players that belong to their group through the use of a set of tools that are restricted to regular users. The regular users are the players who have access to the game as described in the Concept section above.

Figure 3.2: Planning for Website Workflow

As can be seen in figure 3.2 the first step when an organization joins the PowerGame is done by a Super Admin that creates the main group with an appropriate name. The coordinator on the new organization joins this group and is promoted to administrator. From here on out he has total independence to create new groups, so he creates two different groups called X1 and X2. After a new user joins X2, Admin A creates mission M1 and makes it available on group X2. From the user B side he reads the mission goals and tips, carries out its activities in real life and periodically returns to the website to send text logs with a description of its activities. Admin A can then read

(38)

PowerGame System

the logs from the user, and seeing a consumption graph decide if the mission was successful or not. Depending on what Admin A decides, the user gets a reward.

An example of a similar interaction using the finished prototype can be seen in section 5.1.4.

3.3

Global System Architecture

Our PowerGame website will be part of a bigger system comprised of several different compo-nents. The first one which is located on the client organization site is a physical measuring system composed by several energy measurement devices. These devices measure the consumption and energetic performance of the grid on that location, and send the data to the SmartWatt servers. These servers are also responsible for hosting the PowerGame website and it is by accessing it that users anywhere and using any type of OS can join and participate in the PowerGame.

Figure 3.3: High Level View of the System Architecture

While a simplified schematic of this can be contemplated in figure 3.3, further details on technologies and implementation can be found on section 3.4

3.4

Architecture Implementation

In this section we will explain into greater detail the technical side of the Global Architecture mentioned before, which includes a list of all technologies used, both in client sites as well as in the SmartWatt servers, and how they interact with each other to provide us with a solution.

(39)

PowerGame System

As seen in Figure 3.4, each client site will have one or more measurement systems capable of sending information about the energy consumption and other variables at regular intervals to the SmartWatt servers.

Figure 3.4: Architecture of the System

In the case of the currently used legacy system, a set of Circutor measurement devices con-nects using TCP/IP to a single Windows Server. These servers contain a Java app that polls the measurement devices in sequence in an infinite loop, and sends the values obtained at the end of each loop to a SCADA system. These values, if valid, override the ones stored in a buffer in the server, and every 15 minutes the contents of the buffer are stored into a MySQL database.

In the case of the developed system described in the Data Logging section 4.1 that will be used in the future, one or more Circutor devices are associated to a mini PC running Debian called MyGenBox (MGB) to which it connects using a Serial-To-USB adapter. These MGBs contain a Java app that constantly polls the device and stores the valid values in an array in memory. A task is executed every 15 minutes to write the contents of the array directly into a MongoDB document on the instance running in the SmartWatt server. Each device has its own collection of documents, and each building its own database instance.

The SmartWatt Server runs Linux Ubuntu and has a single NodeJS instance running a web server with an HTML5 interface called PowerGame, a web app that uses the values stored in the MongoDB database as energy measurements, and uses MySQL to store and read all the info related to users, groups and other data required for the functioning of its web interface. This web app is accessible to users in any operating system through a browser compatible with HTML5.

(40)

PowerGame System

(41)

Chapter 4

Measurements

In the following chapter we describe in detail the experience obtained and the decision making behind the implementation of the planned and thought of framework prototype.

In this section, Data Logging, we will talk about the requirements stipulated for data inputs needed for the correct functioning of our framework, the solutions proposed and the reasoning behind it, the protocols used to transfer information and the hardware assembled to gather it. We’ll round up this subsection with the main problems faced and drawbacks while implementing, and the solutions at which we arrived to solve them.

4.1

Data Logging

Data Logging is an essential task that needs to be performed for the correct and scientific as-sessment of the influence of a behaviour altering framework that uses real life measurements as input.

4.1.1 Circutor Device

For the data collection SmartWatt uses two different kinds of Circutor devices.

The first one, used by the legacy system, has an Ethernet port through which a remote server polls using a Modbus TCP protocol. Depending on the distance between the remote server and the Circutor device, and depending on conditions such as humidity and heat of the site in which the Circutor device is stored, the rate at which the CRC check of the response fails increases. Other failures occur when the polling of the same machine and variable is done at the same time by two concurrent processes. To solve this problem a timeout is issued, and the poll is repeated.

The second one, which will be the focus of this section, is a Circutor Mini [cir] and takes advantage of a Serial to USB adapter to connect itself to a mini computer running Debian Linux.

The setup as seen in Figure 4.1 is accomplished by connecting terminals 14 and 15 of the Circutor device, which correspond to Power supply voltage input, to the power supply circuit we are interested in monitoring. Terminals 3 and 4 are then connected to Pins RxD and TxD of the pl2303x [pl2] serial to USB adapter. These pins correspond to the Serial Port Transmitted Data

(42)

Measurements

Figure 4.1: System Setup

and Received Data respectively. The USB side of the adapter is then connected to a USB 2.0 port on the Debian machine, with the Ethernet port being used to connect said machine to the web, in order to send the polled values to a MongoDB databased located in a remote server. Due to the short distance between the Circutor device and the machine polling for data, the failures in data reading are minimized.

4.1.2 Data

The Circutor device is capable of reading several variables, that are dependant on the electric setup available. On table 4.1 we can see the variables available in Single, Two and Triple phase setups, which can be identified by the 1,2 or 3 post-fix on the symbol column while the temperature parameter is available on all 3 setups. Variables incompatible with the current setup will return the value of 0 (zero) upon polling, which is the case on the test case we have available, which uses a Single-Phase measurement. In the Parameter column we have the variable name, while on the Code column we have the hexadecimal number corresponding to the MODBUS register of the instant value stored in the memory of the device. Each variable occupies a single register of space. For the input of the PowerGame framework we will use only the Active Energy variable, which holds the value of the accumulated consumption of energy since the start of the setup. In addition to the mentioned variable, additional variables being polled by the future system can be consulted on table A.1.

(43)

Measurements Paremeter Symbol Code Units Phase-neutral voltage V 1 00 V x10 Current A 1 02 mA Active power kW 1 04 w Reactive power L/C KvarL/C 1 06 w Apparent power kV·A 4A

Power factor PF 1 08 x 100 Phase-neutral voltage V 2 0A V x10 Current A 2 0C mA Active power kW 2 0E w Reactive power L/C KvarL/C 2 10 w Apparent power kV·A 4C w Power factor PF 2 12 x100 Phase-neutral voltage V 3 14 V x10 Current A 3 16 mA Active power kW 3 18 W Reactive power L/C KvarL/C 3 1A W Apparent power kV·A 4E w Power factor PF 3 1C x 100 Temperature -oC 50 oC x 10

Table 4.1: Single, Two and Triple phase variables

4.1.2.1 Modbus Protocol

Modbus is an open and royalty free communications protocol originally designed to be used with programmable logic controllers. Due to its dominance in the industrial market it has become a standard, protocol which is to this day still updated by an official organization.

Modbus supports the polling of up to 240 devices in the same network, and each device must be assigned a unique address, which will be used in the request frame. In such networks the machine doing the polling must be setup as the master in order for the request to be accepted.

We can find the format of the request frame in table 4.2. In order to receive a valid response the device being polled must have the equivalent to at least 7 character times worth or silence between each request. The first byte contains the address of the device being polled, the second byte the code of the function to be performed, and the following bytes contain data pertaining to

Field Length Description

Start 3.5c idle 3.5 character times of silence Address 8 bits Device address

Function 8 bits Function code

Data n * 8 bits Data size dependant on the message type CRC 16 bits Frame integrity check

End 3.5c idle 3.5 character times of silence

(44)

Measurements the function at hand.

In order to communicate with the Circutor device over serial, we decided to keep up with the choice of SmartWatt, that was using the Jamod library TCP component on the legacy system, and use the Serial component of Jamod to interact with the device.

Figure 4.2: Jamod Sequence

As can be seen in figure 4.2 the Jamod Serial package contains several elements which are required for the execution of a simple request. ModbusSerialConnection is responsible for the setup, opening and maintenance of the connection with the serial port, ModbusSerialTransport is responsible for the transfer of data in the connected layer, while ModbusSerialTransaction is responsible for the execution and reception of queries and respective responses.

The application needs to first setup the parameters of the serial connection to be established. These parameters must be in accord to the parameters of the serial port available through the operating system being used, or the connection will fail to be opened. If the parameters are not supported by the kernel, such parameters will be ignored when opening the connection. The parameters used in this case can be seen in table 4.3. As the port name may vary on different machines depending on the port and type of port used, it is wise to check on the amount of devices connected to each block of ports available. In our case, if the device was connected directly to the serial port, as opposed to using a serial to USB adapter, the port name would be ’/dev/ttyS0’.

After setting up the parameters, the connection can be opened. After the connection is estab-lished, we need to setup the request paramters, which includes the device address, the register to start reading from and the amount of subsequent registers to read. Since we were using the same

(45)

Measurements Field Value

Port name /dev/ttyUSB0 Baudrate 19200 Databits 8 bits Parity none Stopbits 1 bit

Encoding Modbus.SERIAL_ENCODING_RTU

Table 4.3: Modbus Serial Connection Parameters

library as the legacy code, we will use the same frame as used by the TCP request. The request frame is then written on the connected port, and a response is obtained. After checking the in-tegrity of the response the connection is finally closed. To ensure a fail safe operation and extend the existing legacy code, we opted to send a different request for each variable and machine.

4.1.3 MyGenBox

The MyGenBox is a mini computer that was chosen by SmartWatt to serve as a master node in the Circutor network to poll the devices, process the responses and periodically send the data over the web to a mongo database on their servers.

4.1.3.1 Hardware & Software

The MyGenBox uses an alix2d2 [myg] system to act as a master on the network. Hardware side and of relevance to this project the board boasts a 500MHz AMD Geode LX800 CPU and 256MB of DDR DRAM. For ports we have access to two USB ports, two ethernet ports and a single serial port. In addition to this, a 4GB flash card was added for semi-permanent storage, in this case holding the operating system, data logging application and supporting libraries. For the operating system a slim version of Debian 6.0.6 is being used, with the kernel version at 2.6.32.

During the implementation phase, the usual setup had the development computer connect-ing through SSH to MyGenBox usconnect-ing putty and a local area connection between machines. The Circutor device would be interchangeably connected either on the USB or Serial port of the My-GenBox, that would be connected with its second ethernet port to the internet in order to more easily download and install the software packages required for development and debugging. 4.1.3.2 TCP-IP to Serial Adaptation

In order to take advantage of a cheaper and more fail safe system a port of the legacy system was requested. Besides porting the code from the Windows platform to the Linux environment, it was also requested an adaptation of the code from using an internet connection to transfer data through TCP/IP to using a serial connection to do so.

Due to differences in how the general architecture of both legacy and new systems were de-signed, and the necessity of keeping the legacy code for eventual scenarios, the legacy code was

(46)

Measurements Field Description

id The decimal value corresponding to the hexadecimal value representing the register where the variable is stored. If reading all variables it changes by 2 starting at 0

nBytes Number of bytes needed by the request frame on the data block

Modbus Mode Modbus function code. For reading variables the code is al-ways equal to 3, which represents the ’Read Holding Reg-isters’ in the modbus protocol

Multiplier Value to multiply the received variable with. If we receive W and we want to receive KW, we need to set the multiplier at 0.001

Min Minimum value the variable must have. If bellow this value, this reading instance of this variable is ignored Max Minimum value the variable must have. If above this value,

this reading instance of this variable is ignored Name Name of the variable on the new Mongo database PSS Variable Name of the variable on the legacy SCADA system

Table 4.4: Device Parameters

expanded upon with a control flag restricting access to the portions of the codebase exclusive to the serial component, and a portion of the program flow was altered.

The application starts by opening a configuration file containing several parameters needed for the connection to the SCADA system. It then proceeds to count the files inside a folder called ’equipamentos’, that contains the variables to read from each device. The filename for each device is according to the format ’deviceId’ + ’.conf’ for file termination. On the device configuration file, each line represents a different variable to read, and each line contains a set of parameters that can be consulted on table 4.4. If the line starts by ’#’ that variable will not be polled.

Inside the loop for each device the variables are sequentially polled using the modbus request frame, that is compatible with both systems. The response obtained is then passed to a decoding function that reads the response frame and returns a readable value. The legacy system would pair these values with the variable names, and instantly send them to the SCADA system. In the new system a data structure that can be seen in image 4.3 is created upon counting the configuration files. The application creates a single array of arrays that contains a pair of ’variable name’-’value’ arrays for each Circutor device available. Upon decoding a value, if such value is within the configuration parameters, the corresponding variable in the array is updated, if not, the old one is kept. A task is set at the beginning of the application to write the whole array into the mongo database every 15 minutes, starting after the initial 15 minutes of the application running.

4.1.3.3 Linux Problems and Challenges

While porting the code from Windows to Linux several problems arose, not only due to specific features of the operating system by itself, but also due to changes in the hardware and software

(47)

Measurements

Figure 4.3: Data Array Structure

components of the data transportation.

Due to the fact that MyGenBox didn’t have a visual environment on which we could run an IDE, all the coding was remotely written using Notepad++. The JDK had to be manually installed, and the compilation was done with the Java compiler through putty. The first obstacle occurred with a missing dependency on compilation, which was later found out was the discontinued Java-comm package which the serial component of the Jamod library used, but the TCP/IP component didn’t. Due to Oracle no longer supporting this library, its download and manual installation proved lengthy and troublesome.

The following problems are, in a way or another, all related to the configuration of the se-rial port and the use of the Sese-rial-to-USB adapter model PL-2303X, which on the adapter itself was labeled as PL-2303. Every time a writing attempt of the request frame was presented, the application would throw an exception regarding the I/O operation.

Using the command ’dmesg’

It was possible to identify that the OS recognized something connected to the USB port seeing in the response

’usb 2-2: New USB device found, idVendor=067b, idProduct=2303’ Using the command:

’lsusb’

the OS would return

(48)

Measurements

which informed us that the OS had the drivers and correctly recognized the adapter connected to the USB port as a Serial Adapter PL2303, as is labeled on the hardware itself. Upon further investigation it was discovered that this model had two different versions, PL2303 and PL2303X, both of which used the same driver. To identify which was which, it was possible to query the system for a verbose description of the adapter using lsusb along with the adapter id, such as ’lsusb -v -d 067b:2303’

which would return dozens of lines of info regarding the adapter. If the param ’bMaxPacketSize0’ was equal to 64 this meant that the connected device was a PL2303X, as it happened in our case. Due to a bug in the drivers included, every version of the Linux kernel pre dating version 2.6.8 would recognize PL2303X as being PL2303, and fail to correctly communicate. An update to kernel solved this issue.

As referred previously, the application sets up the serial port parameters as in table 4.3, which must be the same as working parameters of the port in the operating system. To do this we used a simple application for serial port setup and initialization called ’minicom’, which allowed us to define a default profile for the serial ports to be used and started with the system boot. For testing purposes we built our own request frame instead of relying on the TCP request. As a "failed to write" error persisted, we turned off hardware flow control using minicom, which was known for preventing correct communication with Jamod. Upon the change, some request frames are successfully sent, while others fail with the error "failed to read", with no repeating pattern that would allows us to identify the cause.

With the hardware flow control turned off, the continual transmission of data caused problems in the buffer. Additionally, the request frame must respect 3.5 characters of silence at the start and end of each request. Considering the parameters we were using, we can calculate such interval by using the following formula:

SilenceInterval: 8(bits) ∗ 3.5(ct)

19200(bps) = 1.45ms (4.1) As calculated, it’s safe to assume we need at least 3 ms of inactivity between requests to respect the modbus protocol, and some additional time to take into account the lack of acknowledgement protocol implemented on the master machine. To do this we modified the SerialTransaction class of the IO package of the Jamod library, by forcing a sleep period of the main thread between the writing of the request and the reception of its response, as can be seen in image 4.4. For the purpose of this scenario we defined the variable m_Delay at 50 ms.

The final obstacle we faced when trying to write the data to the MongoDB on one of the SmartWatt servers. The application would fail to connect to the server, as if the instance of said database was not running or the server was inaccessible. We started by pinging a website like google.com to assure connectivity to the internet, which proved successful. A ping to the server adress, however, was not. To debug this, we installed the arp-scan program, which upon calling the command

(49)

Measurements

Figure 4.4: Jamod Modification

’sudo arp-scan –interface=eth0 –localnet’

would return a list of all the computers connected in the internal SmartWatt network, including the server to which the ping would fail. Several hypothesis were tested client side, but it was later solved server side as the server was not accepting connections of machines with dynamic addresses, only static ones.

(50)

Measurements

(51)

Chapter 5

Web App

In the following chapter we describe in detail the experience obtained and the decision making behind the implementation of the planned and thought of framework prototype.

In this section, we will talk about the features of the web app and the reasoning behind their implementation. We will show a step by step demonstration of the work flow behind the web app, both from the point of view of a group administrator and overseer as well as from the point of view of an user. We will round up this subsection with the listing of the state of the art technologies used, which includes not only programming languages and standards, but also some open source frameworks and libraries.

5.1

PowerGame Application

The PowerGame website is built entirely on NodeJS and supporting libraries following the typical file structure and workflow of this platform. The client side of the app works as any other website that takes advantage of HTML5, javascript, jquery and CSS.

5.1.1 WebApp Architecture

The PowerGame webapp follows the typical architecture of a NodeJS app, with the folder structure that can be seen in figure 5.1 following the one used on the Node-Login example project by Stephen Braitsch [Noda], which we used as a base to build our app upon.

A typical NodeJS app contains an ’app.js’ file containing settings such as the required libraries to run the app, port name, rendering engine and other middleware, favicon graphics to be used and others. In addition to the settings it includes the necessary initialization code to start the server. This is done by calling ’node app’ from the command line on the root folder. The root folder also includes an ’app’ folder where most of the app files like html css and js are stored, and in this folder the file structure has some more liberty as long as the paths are correctly defined in the config files. In the root there’s still the ’node_modules’ folder where the source code of the required libraries is stored, and the file ’package.json’ where the developer can define the version of the libraries he

(52)

Web App

Figure 5.1: Folder Structure for the NodeJS App

(53)

Web App

wants to see used. To install or update the libraries defined in this file the command ’npm install’ in the root folder will download or update the code into the ’node_modules’ folder.

Inside the app folder we have the code split between the ’public’ and the ’server’ folder, de-pending of the level of privacy required for the source files. In the ’server’ folder we will find another core file of nodeJS called ’router.js’, which is responsible for loading and executing server side code, and routing the user by handling CRUD requests. The private server sided code is stored in the folder ’modules’ where we have modules such as the account manager, the email dispatcher, the energy reader and the mission manager. Alongside this folder we have the ’views’ where all the jade code, that is later compiled to html is stored. This ’views’ folder includes a ’modal’ folder containing the jade code for the warning pop up windows that show up to confirm the success or failure of user actions.

Inside the public folder we have the ’css’, ’img’, and ’js’ folders containing the stylesheets, the graphic resources and the javascript files respectively. Inside the javascript folder we have a ’controllers’ folder with the jquery code to manage the functionality of some pages, while the ’form-validators’ folder includes the jquery code to assess the correct submission of forms, such as the restriction of no empty fields or the limit in password length. The folder ’views’ contains the jquery code responsible for calling the modal pop-up windows and other smaller functions relating to interfacing with the user.

5.1.2 Organizational Hierarchy

The users of this website will be joining a group upon registration, group that they must belong to in real life. Internally all the groups follow a hierarchical tree structure that accurately represents the hierarchy of said groups outside the virtual world in order to facilitate the assignment of tasks and selection of counsellors. This structure has as a goal to promote social competitiveness and peer pressure between groups and users within each group.

Using as an example the structure in Figure 5.2, SmartWatt can define at any time (using the in-game Administration Panel) the master groups, placing them as child groups of Group ZERO. The administrators assigned for group A and B must be users belonging to these groups, and should be the people responsible for the interaction with SmartWatt, or be someone totally aware of the energy saving plan. Each group can create other sub groups directly below them, like subgroup A1, A2 for A, B1 and B2 for B, B11 for B1, and assign administrators to these subgroups on their own from its user base. These user aggregations can represent different types of groups, from manufacturing companies, to schools, to cities or countries or even individual households.

Each group will have a measuring device associated with it, and the performance values to be calculated will consider an aggregate of all values in the direct child nodes, allowing for multiple levels of competition and management to occur at the same time.

This abstracted way of representing and organizing users amongst groups in a hierarchical way allows the web app to be used in a multitude of different contexts that require a top-down distribution of tasks and sharing of knowledge, acting as middle ware to support serious games for energy management.

(54)

Web App

Figure 5.2: Group Structure

5.1.3 Database Architecture

As can be seen in fig 5.3 the MySQL database schema used for the backend of the PowerGame webapp is comprised of only five tables.

Figure 5.3: Database Schema for PowerGame

The ’user’ table is the central point of data and data in the system. It includes a flag called ’idAdminOf’ that is null for a regular user and has the id of the group he administers otherwise.

Referências

Documentos relacionados

Partindo do princípio que não apenas os cientistas podem falar sobre ciência – assim como não são apenas os economistas que falam sobre economia, nem somente os políticos que

Assim, as hipóteses “[...] cumprem sua finalidade no processo de investigação científica, tornando-se capazes, mediante o adequado teste, de proporcionar respostas aos

Ousasse apontar algumas hipóteses para a solução desse problema público a partir do exposto dos autores usados como base para fundamentação teórica, da análise dos dados

Resumo Este relatório tem como objetivo apresentar o percurso académico e profissional da candidata, iniciado em 1980 com o ingresso na Universidade de Aveiro,

It turns out, however, that there are no zero modes of the instability that are also bound states.5 This was shown by Hod in the case of a test, massive, charged scalar field on the

Neste exemplo, “parcela”, o sentido que é primeiro associado a parte, não é central para a compreensão da sentença, pois é no adjetivo que se amparam as deduções

 Managers involved residents in the process of creating the new image of the city of Porto: It is clear that the participation of a resident designer in Porto gave a

The stresses in the specimen half thickness grow when the crack length grows in the free surfaces and seems to be ruptured when the stresses get too big in the