Sockets y Procesos de Aplicación - NicolasCacer/Proyecto_Final_RCD GitHub Wiki
La solución de software orientada al seguimiento remoto de un paciente ubicado en la red SOHO, utilizará una aplicación en el smarthphone llamada Tracker App
para monitorizar su temperatura. Las mediciones de temperatura son generadas aleatoriamente dentro de un rango de 30°C y 45°C. Las mediciones capturadas por la Tracker App son enviadas al servidor Tracker Server, ubicado en la LAN de servidores, cada segundo. El servidor Tracker Server cuenta con una aplicación Tracker Replay
que recibe las mediciones enviadas por la Tracker App y las reenvía a la aplicación Tracker Dashboard
. Esta última se ejecuta en un computador portátil inalámbrico (denominado “Wireless Host_Doctor”) ubicado en la Intranet HOSPITAL. La aplicación “Tracker Dashboard” permite a la Doctora visualizar las mediciones capturadas por el dispositivo inteligente instalado en el paciente y las alertas generadas al superar los 40°C. Las aplicaciones intercambian mensajes a través de sockets.
from tcp import *
from time import *
import random
serverIP = "209.174.54.4"
serverPort = 1234
client = TCPClient()
def onTCPConnectionChange(type):
print("connection to " + client.remoteIP() + " was " + str('established')if type == 0 else str('Connection closed by '+client.remoteIP()+'. Please run again the program') if type == 3 else None)
def onTCPReceive(data):
print("received from " + client.remoteIP() + " with data: " + str(data))
def main():
client.onConnectionChange(onTCPConnectionChange)
client.onReceive(onTCPReceive)
print(client.connect(serverIP, serverPort))
count = 0
while True:
count += 1
data = round(15*random.random()+30,1)
client.send('App '+str(data))
sleep(1)
if __name__ == "__main__":
main()
from tcp import *
from time import *
port = 1234
server = TCPServer()
saves = []
def onTCPNewClient(client):
def onTCPConnectionChange(type):
print("Connection to " + client.remoteIP() + " was " + str('interrupted by client') if type == 3 else None )
def onTCPReceive(data):
print("received from " + client.remoteIP() + " with data: " + data)
dat = data.split(' ')
if dat[0] == 'dash':
clientDash = TCPClient()
clientDash.connect(client.remoteIP(), 4321)
client.send(saves)
elif dat[0] == 'App':
saves.append(float(dat[1]))
client.send('OK. Recieved ' + dat[1])
clientDashboard = TCPClient()
if len(saves) == 20:
saves.pop(0)
client.onConnectionChange(onTCPConnectionChange)
client.onReceive(onTCPReceive)
def main():
server.onNewClient(onTCPNewClient)
print(server.listen(port))
# don't let it finish
while True:
sleep(3600)
if __name__ == "__main__":
main()
Para poder utilizar la aplicación Trcaker Dashboard en necesario crear una plantilla para una App de Desktop en python desde la función de programming en el W_Doctor. Se generarán archivos por default, en donde se puede copiar y pegar cada uno de los códigos presentados para reemplazar estos archivos de default.
from gui import *
from cli import *
from json import *
from time import *
count = 0
def guiEvent(type, args):
print('guiEvent: ' + type + ',' + dumps(args))
def cliEvent(type, args):
print('cliEvent: ' + type + ',' + dumps(args))
CLI.exit()
from tcp import *
from time import *
serverIP = "209.174.54.4"
serverPort = 1234
client = TCPClient()
def onTCPConnectionChange(type):
print("\nconnection to " + client.remoteIP() + " was " + str('established')if type == 0 else str('Connection closed by '+client.remoteIP()+'. Please run again the program') if type == 3 else None)
def onTCPReceive(data):
temp = []
for i in data.split(','):
temp.append(float(i))
print(("received data: " + str(temp[-1])) if len(temp)>1 else str('Waiting for Data'))
if temp[-1] >= 40:
print('\n################################################')
print(' ALERTA DE ALTA TEMPERATURA: '+ str(temp[-1]))
print('################################################\n')
GUI.update('Current Temperature: ', temp)
def main():
GUI.setup()
CLI.setup
client.onConnectionChange(onTCPConnectionChange)
client.onReceive(onTCPReceive)
client.connect(serverIP, serverPort)
while True:
data = "fetch"
client.send(data)
sleep(1)
if __name__ == "__main__":
main()
<application>
<!-- Unique ID to identify this project,
recommend using reverse domain name notation -->
<id>net.netacad.cisco.example_desktop</id>
<version>1.0</version>
<name>Desktop Example</name>
<!-- Optional tags -->
<description>Desktop example with desktop GUI app and CLI commands</description>
<author>Packet Tracer Team</author>
<contact/>
<!-- If this app is to be installed on the Desktop,
provide this tag and its children. -->
<gui>
<name>Tracker Dashboard</name>
<html>main.html</html>
<icon>icon.png</icon>
<background>true</background>
</gui>
<!-- If this app is to provide commands in the Command Prompt,
provide this tag and a command tag for each command. -->
<cli>
<command>
<name>example_cmd</name>
<description>Example Command</description>
</command>
<command>
<name>example_cmd2</name>
<description>Example Command 2</description>
</command>
</cli>
<!-- If this app is to be exported, you can specify the devices
that this app will automatically installed on.
Either the gui or cli tag is required.
Possible values are PC, Laptop, Server, Tablet, Smartphone, SBC, Thing. -->
<auto-install>
<device>PC</device>
<device>Laptop</device>
<device>Server</device>
<device>Tablet</device>
<device>Smartphone</device>
<device>SBC</device>
<device>Thing</device>
</auto-install>
</application>
.main-container {
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
width: 100%;
height: 100vh;
font-family: sans-serif;
}
h1 {
margin: 18px 0px;
font-size: 48px;
font-weight: 800;
}
h2 {
margin: 2px 0px;
font-size: 18px;
font-weight: 300;
}
.info {
display: flex;
text-align: left;
color: black;
flex-direction: column;
width: 60%;
}
.tracker {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
margin: 16px 0px;
}
#label {
margin-left: 4px;
}
img {
position: absolute;
top: 5px;
right: 5px;
width: 64px;
height: auto;
}
span{
margin: 2px 0px;
font-size: 12px;
}
#temperatureTable {
border-collapse: collapse;
width: 300px; /* Reduced width */
max-height: 200px; /* Reduced height */
overflow-y: auto; /* Enable vertical scroll */
margin: 8px 0px;
}
#temperatureTable th,
#temperatureTable td {
text-align: center;
color: black;
padding: 8px;
}
#temperatureTable tbody tr:nth-child(odd) {
background-color: lightblue;
}
#temperatureTable tbody tr:nth-child(even) {
background-color: white;
}
function update(type, args) {
var label = document.getElementById('label');
var alertSpan = document.getElementById('alert');
label.innerText = type + ' ' + args[args.length - 1]; // Update label with the most recent temperature reading
// Update table with last 20 temperature values
var table = document.getElementById('temperatureTable');
var tbody = table.getElementsByTagName('tbody')[0];
tbody.innerHTML = ''; // Clear existing table body content
// Insert new rows in reverse order
for (var i = Math.max(0, args.length - 1); i >= Math.max(0, args.length - 20); i--) {
var row = tbody.insertRow();
var cellIndex = row.insertCell(0); // Add new cell for index column
var cellValue = row.insertCell(1); // Add new cell for value column
// Populate index and value cells
cellIndex.innerText = args.length - i; // Reverse index from 20 to 1
cellValue.innerText = args[i];
}
// Check if the value is over 39.9
if (parseFloat(args[args.length - 1]) > 39.9) {
label.style.color = 'red';
alertSpan.style.color = 'red';
alertSpan.innerText = 'Alert: Temperature is way too high! Contact immediately';
}
// Check if the value is under 35
else if (parseFloat(args[args.length - 1]) < 35) {
label.style.color = 'darkblue';
alertSpan.style.color = 'darkblue';
alertSpan.innerText = 'Alert: Temperature is very low! Contact immediately';
}
else {
label.style.color = 'black';
alertSpan.innerText = '';
}
}
<html>
<head>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body onload='onLoad()'>
<div class="main-container">
<h1>Patient Tracker</h1>
<div class="info">
<h2>Patient ID: 1021836251</h2>
<h2>Name: John Doe</h2>
<h2>Age: 76</h2>
</div>
<div class="tracker">
<span id='label'></span>
<span id='alert'></span>
<table id="temperatureTable" border="1">
<thead>
<tr>
<th>Number Register</th>
<th>Temperature in °C</th>
</tr>
</thead>
<tbody>
<!-- Table rows will be dynamically populated by JavaScript -->
</tbody>
</table>
</div>
<img src='icon.png' class='right-align' alt="IMG">
</div>
</body>
</html>
Para finalizar con las instalación de este programa se da click en el boton de install to Desktop para que aparezca la aplicación en el Desktop.
Desde el desktop del Laptop del doctor se busca la aplicación que se acabo de crear y se ingresa al seleccionar el icono de la aplicación
Una vez que se ingresa a la aplicación se muestra la siguiente información, en donde se podrán ver los últimos 20 registros y se dará una alerta si la temperatura está muy baja o muy alta.