forked from Krautspace/doorstatus
clientprogramme in eigenes verzeichnis verschoben
This commit is contained in:
parent
f5f2efccae
commit
af78204005
8 changed files with 0 additions and 0 deletions
36
source/client/nodemcu/statusclient/certs.template
Normal file
36
source/client/nodemcu/statusclient/certs.template
Normal file
|
@ -0,0 +1,36 @@
|
|||
/*
|
||||
* file: certs.template
|
||||
* desc: This file is part of the Krautspace Doorstatus project. It contains
|
||||
* certificates for the statusclient.ino programm, that runs on a NodeMCU
|
||||
* with a ESP8266 chip.
|
||||
*
|
||||
* Replace the comments in certificate sections with our own certificates.
|
||||
*/
|
||||
|
||||
|
||||
const char SERVER_CERT[] PROGMEM = R"EOF(
|
||||
-----BEGIN CERTIFICATE-----
|
||||
/*
|
||||
* lace for the public server certificate to authenticate the doorstatus
|
||||
* server.
|
||||
*/
|
||||
-----END CERTIFICATE-----
|
||||
)EOF";
|
||||
|
||||
const char CLIENT_CERT[] PROGMEM = R"EOF(
|
||||
-----BEGIN CERTIFICATE-----
|
||||
/*
|
||||
* Place for the clients (this program) public certificate to authenticate
|
||||
* client against the server.
|
||||
*/
|
||||
-----END CERTIFICATE-----
|
||||
)EOF";
|
||||
|
||||
const char CLIENT_KEY[] PROGMEM = R"EOF(
|
||||
-----BEGIN CERTIFICATE-----
|
||||
/*
|
||||
* Place for the clients private key file.
|
||||
*/
|
||||
-----END CERTIFICATE-----
|
||||
)EOF";
|
||||
|
18
source/client/nodemcu/statusclient/config.h
Normal file
18
source/client/nodemcu/statusclient/config.h
Normal file
|
@ -0,0 +1,18 @@
|
|||
/*
|
||||
* file: config.h
|
||||
*/
|
||||
|
||||
/* endpoint */
|
||||
#define SERVER_URL "status.kraut.space"
|
||||
#define SERVER_PORT 10001
|
||||
|
||||
/* serial interface settings */
|
||||
#define BAUD_RATE 115200
|
||||
#define DEBUG true
|
||||
|
||||
/* frequence to read the pin */
|
||||
#define FREQUENCY 5000
|
||||
|
||||
/* time server settings */
|
||||
#define NTP_URL "pool.ntp.org"
|
||||
#define TZ_STRING "CET-1CDT,M3.5.0,M10.5.0/3"
|
17
source/client/nodemcu/statusclient/credentials.template
Normal file
17
source/client/nodemcu/statusclient/credentials.template
Normal file
|
@ -0,0 +1,17 @@
|
|||
/*
|
||||
* file: credentials.template
|
||||
* desc: This file is part of the Krautspace Doorstatus project. It contains
|
||||
* wifi ssid and passwords for the statusclient.ino programm, that runs on a
|
||||
* NodeMCU with a ESP8266 chip.
|
||||
*
|
||||
* Rename this file into 'credentials.h' and adapt the values to your
|
||||
* wifi conditions.
|
||||
*/
|
||||
|
||||
/* wifi credentials */
|
||||
#define SSID_1 "your_first__wlan_ssid"
|
||||
#define PSK_1 "your_first_wlan_passwort"
|
||||
#define SSID_2 "your_second_wlan_ssid"
|
||||
#define PSK_2 "your_seconde_wlan_password"
|
||||
#define SSID_3 "your_third_wlan_ssid"
|
||||
#define PSK_3 "your_third_wlan_password"
|
198
source/client/nodemcu/statusclient/statusclient.ino
Normal file
198
source/client/nodemcu/statusclient/statusclient.ino
Normal file
|
@ -0,0 +1,198 @@
|
|||
/*
|
||||
* file: statusclient.ino
|
||||
* desc: This file is part of the Krautspace Doorstatus project. It's the
|
||||
* main file for a client, who deals with the input from a reed sensor and
|
||||
* push these values to a server. The code is make to run on a NodeMCU with
|
||||
* ESP8266 chip.
|
||||
*/
|
||||
|
||||
#include <ESP8266WiFiMulti.h>
|
||||
#include <WiFiClientSecure.h>
|
||||
#include <time.h>
|
||||
|
||||
#include "config.h"
|
||||
#include "certs.h"
|
||||
#include "credentials.h"
|
||||
|
||||
const int LED_PIN = 16; // D0
|
||||
const int REED_PIN = 5; // D1
|
||||
|
||||
typedef enum {
|
||||
DOOR_CLOSED = 0,
|
||||
DOOR_OPEN = 1
|
||||
} door_state;
|
||||
door_state current_door_state = DOOR_CLOSED;
|
||||
|
||||
BearSSL::WiFiClientSecure client;
|
||||
|
||||
void blink_led(int blink_count, int delay_time) {
|
||||
/*
|
||||
* zur ausgabe von meldungen blinkt die interne led.
|
||||
* erfolgreichesmeldungen werden durch kurze blinkzeichen angezeigt,
|
||||
* fehlermeldungen sind durch eine lange sequenz gekennzeichnet.
|
||||
* Signale:
|
||||
* status der tür hat sich geändert: 2x kurz
|
||||
* änderung erfolgreich gesendet: 5x kurz
|
||||
* es konnte keine wifi aufgebaut werden: 3x lang
|
||||
* senden des status fehlgeschlagen: 5x lang
|
||||
*
|
||||
* param 1: integer
|
||||
* param 2: integer
|
||||
*/
|
||||
for(int i=0; i!= blink_count; ++i) {
|
||||
digitalWrite(LED_PIN, LOW);
|
||||
delay(delay_time);
|
||||
digitalWrite(LED_PIN, HIGH);
|
||||
delay(delay_time);
|
||||
}
|
||||
}
|
||||
|
||||
void init_serial() {
|
||||
/*
|
||||
* set baudrate and debug modus
|
||||
*/
|
||||
Serial.begin(BAUD_RATE);
|
||||
Serial.setDebugOutput(DEBUG);
|
||||
Serial.println();
|
||||
Serial.println("[Srl] Serial interface initialized");
|
||||
}
|
||||
|
||||
void init_pins() {
|
||||
/*
|
||||
* set gpio for reed sensor and led
|
||||
*/
|
||||
pinMode(REED_PIN, INPUT_PULLUP);
|
||||
pinMode(LED_PIN, OUTPUT);
|
||||
digitalWrite(LED_PIN, HIGH);
|
||||
Serial.println("[Pin] LED and REED initialized");
|
||||
}
|
||||
|
||||
void init_wifi() {
|
||||
/*
|
||||
* Creates the ssl context. Turns wifi off and than into
|
||||
* access point mode.
|
||||
* TODO: is 'turn of' needed!
|
||||
*/
|
||||
ESP8266WiFiMulti wifi;
|
||||
WiFi.mode(WIFI_OFF);
|
||||
WiFi.mode(WIFI_STA);
|
||||
wifi.addAP(SSID_1, PSK_1);
|
||||
wifi.addAP(SSID_2, NULL);
|
||||
Serial.println("[Wifi] Wifi initialized");
|
||||
wifi.run();
|
||||
if (WiFi.status() == WL_CONNECTED) {
|
||||
Serial.print("[Wif] Connected to ");
|
||||
Serial.println(WiFi.SSID());
|
||||
Serial.print("[Wifi] IP: ");
|
||||
Serial.println(WiFi.localIP());
|
||||
set_clock();
|
||||
} else {
|
||||
Serial.println("[Wifi] Error: Failed to connect");
|
||||
blink_led(3, 500);
|
||||
}
|
||||
}
|
||||
|
||||
door_state read_door_state() {
|
||||
/*
|
||||
* die initialisierung des reed-pin mit pullup bewirkt, daß am pin
|
||||
* 3,3 volt anliegen. die verbindung des pins mit GND sorgt dafür,
|
||||
* daß die spannung "abfließen" kann. dadurch hat der pin dann den
|
||||
* status 'low'.
|
||||
* geschlossene tür -> reed geschlossen -> low
|
||||
* geöffnete tür -> reed offen -> high
|
||||
*/
|
||||
if (digitalRead(REED_PIN) == HIGH) {
|
||||
return DOOR_OPEN;
|
||||
}
|
||||
return DOOR_CLOSED;
|
||||
}
|
||||
|
||||
void set_clock() {
|
||||
/*
|
||||
* We need time for certificate authorization
|
||||
*/
|
||||
configTime(TZ_STRING, NTP_URL);
|
||||
|
||||
Serial.print("[Clock] Waiting for NTP time sync");
|
||||
time_t now = time(nullptr);
|
||||
while (now < 8 * 3600 * 2) {
|
||||
delay(500);
|
||||
Serial.print(".");
|
||||
now = time(nullptr);
|
||||
}
|
||||
Serial.println("");
|
||||
struct tm timeinfo;
|
||||
gmtime_r(&now, &timeinfo);
|
||||
Serial.print("[Clock] Current time: ");
|
||||
Serial.println(asctime(&timeinfo));
|
||||
}
|
||||
|
||||
int send_status(door_state state) {
|
||||
|
||||
/*
|
||||
* Inits wifi (if needed) and send the status
|
||||
*/
|
||||
char status[2] = "";
|
||||
|
||||
if (state == DOOR_CLOSED) {
|
||||
strncpy(status, "0", 1);
|
||||
} else if (state == DOOR_OPEN) {
|
||||
strncpy(status, "1", 1);
|
||||
} else {
|
||||
return 1;
|
||||
}
|
||||
|
||||
BearSSL::X509List server_cert(SERVER_CERT);
|
||||
BearSSL::X509List client_cert(CLIENT_CERT);
|
||||
BearSSL::PrivateKey client_key(CLIENT_KEY);
|
||||
client.setTrustAnchors(&server_cert);
|
||||
client.setClientRSACert(&client_cert, &client_key);
|
||||
Serial.println("[Ctx] SSL Context initialized");
|
||||
Serial.printf("[Send] Connect to %s:%i\n", SERVER_URL, SERVER_PORT);
|
||||
client.connect(SERVER_URL, SERVER_PORT);
|
||||
if (!client.connected()) {
|
||||
Serial.println("[Send] Can't connect to server");
|
||||
Serial.print("[Send] SSL Error: ");
|
||||
Serial.println(client.getLastSSLError());
|
||||
client.stop();
|
||||
return 1;
|
||||
} else {
|
||||
ESP.resetFreeContStack();
|
||||
uint32_t freeStackStart = ESP.getFreeContStack();
|
||||
Serial.println("[Send] Connection successful established");
|
||||
Serial.printf("[Send] Send status: %s\n", status);
|
||||
client.write(status);
|
||||
client.stop();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
void setup() {
|
||||
|
||||
/*
|
||||
* things to do once at boot time
|
||||
*/
|
||||
init_serial();
|
||||
init_pins();
|
||||
init_wifi();
|
||||
}
|
||||
|
||||
void loop() {
|
||||
|
||||
/*
|
||||
* things are running in a endless loop
|
||||
*/
|
||||
door_state new_door_state = read_door_state();
|
||||
if (new_door_state != current_door_state) {
|
||||
Serial.printf("[Loop] Status has changed to %i\n", new_door_state);
|
||||
blink_led(2, 100);
|
||||
if (send_status(new_door_state) == 0) {
|
||||
current_door_state = new_door_state;
|
||||
blink_led(5, 100);
|
||||
} else {
|
||||
blink_led(5, 500);
|
||||
}
|
||||
}
|
||||
delay(FREQUENCY);
|
||||
}
|
20
source/client/python/setstatus.conf
Normal file
20
source/client/python/setstatus.conf
Normal file
|
@ -0,0 +1,20 @@
|
|||
# file: setstatus.conf
|
||||
|
||||
# Setstatus.conf is part of doorstatus - a programm to change the krautspaces
|
||||
# doorstatus. This is the configuration file for the client who triggers the
|
||||
# change.
|
||||
|
||||
[general]
|
||||
timeout = 3.0
|
||||
loglevel = debug
|
||||
|
||||
[server]
|
||||
host = status.kraut.space
|
||||
port = 10001
|
||||
cert = ./certs/statusd-pub.pem
|
||||
fqdn = status.kraut.space
|
||||
|
||||
[client]
|
||||
cert = ./certs/statusclient-pub.pem
|
||||
key = ./certs/statusclient-key.pem
|
||||
|
251
source/client/python/setstatus.py
Executable file
251
source/client/python/setstatus.py
Executable file
|
@ -0,0 +1,251 @@
|
|||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# file: setstatus.py
|
||||
# date: 26.07.2019
|
||||
# email: berhsi@web.de
|
||||
|
||||
# Setstatus.py is part of doorstatus - a programm to deal with the
|
||||
# krautspaces doorstatus.
|
||||
|
||||
# client, who connects to the statusserver at port 10001 to update the
|
||||
# krautspace door status.
|
||||
|
||||
import os
|
||||
import ssl
|
||||
import socket
|
||||
import logging
|
||||
import configparser
|
||||
from time import sleep
|
||||
from sys import exit, argv
|
||||
|
||||
|
||||
# basic configuration
|
||||
loglevel = logging.WARNING
|
||||
formatstring = '%(asctime)s: %(levelname)s: %(message)s'
|
||||
logging.basicConfig(format=formatstring, level=loglevel)
|
||||
|
||||
|
||||
class SetStatus:
|
||||
|
||||
def __init__(self):
|
||||
"""
|
||||
"""
|
||||
self.status = None
|
||||
self.config = None
|
||||
self.log = None
|
||||
self.context = None
|
||||
self.connection = None
|
||||
self.configfile = './setstatus.conf'
|
||||
self.config = configparser.ConfigParser()
|
||||
self.default_config = {
|
||||
'general': {
|
||||
'timeout': 5.0,
|
||||
'loglevel': 'warning'
|
||||
},
|
||||
'server': {
|
||||
'host': 'localhost',
|
||||
'port': 10001,
|
||||
'cert': './certs/server-pub.pem',
|
||||
'fqdn': 'kraut.space'
|
||||
},
|
||||
'client': {
|
||||
'cert': './certs/client-pub.pem',
|
||||
'key': './certs/client-key.pem'
|
||||
}
|
||||
}
|
||||
|
||||
def check_status(self):
|
||||
"""
|
||||
checkes, if the self.status variable is a valid value
|
||||
return: boolean
|
||||
"""
|
||||
if self.status in ('0', '1'):
|
||||
self.log.debug('Set status to {}'.format(self.status))
|
||||
return True
|
||||
self.log.debug('{} is not a valid status'.format(self.status))
|
||||
return False
|
||||
|
||||
def set_config(self):
|
||||
"""
|
||||
Tries to read and use the values from the configuration file. If
|
||||
this failes, we still use the default values.
|
||||
"""
|
||||
self.log = logging.getLogger()
|
||||
# read config file
|
||||
self.config.read_dict(self.default_config)
|
||||
if not self.config.read(self.configfile):
|
||||
self.log.warning('Configuration file {} not found or not '
|
||||
' readable.'.format(self.configfile))
|
||||
self.log.warning('Using default values.')
|
||||
# set loglevel
|
||||
config_loglevel = self.config['general']['loglevel']
|
||||
default_loglevel = self.default_config['general']['loglevel']
|
||||
if not config_loglevel.lower() in ('critical', 'error','warning',
|
||||
'info', 'debug'):
|
||||
self.log.warning('Invalid loglevel {} given. Using default '
|
||||
'level {}.'.format(config_loglevel,
|
||||
default_loglevel))
|
||||
self.config.set('general', 'loglevel', default_loglevel)
|
||||
self.log.setLevel(config_loglevel.upper())
|
||||
|
||||
def check_certs(self, certs):
|
||||
"""
|
||||
Check if certs are readable.
|
||||
return: boolean
|
||||
"""
|
||||
self.log.debug('Check certificates')
|
||||
for certfile in certs:
|
||||
if os.access(certfile, os.R_OK) is False:
|
||||
self.log.error('Failed to read certificate: {}'.format( \
|
||||
certfile))
|
||||
return False
|
||||
return True
|
||||
|
||||
def log_config(self):
|
||||
"""
|
||||
Logs the config if loglevel is debug.
|
||||
"""
|
||||
logging.debug('Using config:')
|
||||
for section in self.config.sections():
|
||||
logging.debug('Section {}'.format(section))
|
||||
for i in self.config[section]:
|
||||
logging.debug(' {}: {}'.format(i, self.config[section][i]))
|
||||
|
||||
def create_ssl_context(self):
|
||||
"""
|
||||
Creates SSL context
|
||||
return: context object or false
|
||||
"""
|
||||
try:
|
||||
context = ssl.create_default_context(purpose=ssl.Purpose.SERVER_AUTH)
|
||||
except Exception as e:
|
||||
self.log.error('Failed to create SSL Context')
|
||||
return False
|
||||
context.load_verify_locations(cafile=self.config['server']['cert'])
|
||||
context.load_cert_chain(certfile=self.config['client']['cert'],
|
||||
keyfile=self.config['client']['key'])
|
||||
context.set_ciphers('EECDH+AESGCM') # only ciphers for tls 1.2 and 1.3
|
||||
context.options |= getattr(ssl._ssl, 'OP_NO_COMPRESSION', 0)
|
||||
self.log.debug('SSL context created')
|
||||
return context
|
||||
|
||||
def create_ssl_socket(self, config, context):
|
||||
"""
|
||||
Opens a socket and wrapes the socket into the given ssl context.
|
||||
param1: dictionary
|
||||
param2: ssl context
|
||||
return: ssl-socket or false
|
||||
"""
|
||||
bare_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
|
||||
if not bare_socket:
|
||||
logging.error('Socket creation failed')
|
||||
return False
|
||||
logging.debug('Socket created')
|
||||
try:
|
||||
secure_socket = context.wrap_socket(bare_socket, server_side=False,
|
||||
server_hostname=config['server']['fqdn'])
|
||||
logging.debug('Socket wrapped with SSL')
|
||||
except Exception as e:
|
||||
logging.error('Context wrapper failed: {}'.format(e))
|
||||
return False
|
||||
try:
|
||||
secure_socket.settimeout(float(config['general']['timeout']))
|
||||
except Exception as e:
|
||||
logging.debug('Failed to set timeout: {}'.format(e))
|
||||
return secure_socket
|
||||
|
||||
def create_ssl_connection(self):
|
||||
"""
|
||||
"""
|
||||
counter = 0
|
||||
conn = False
|
||||
|
||||
while conn is False and counter < 5:
|
||||
ssl_socket = self.create_ssl_socket(self.config, self.context)
|
||||
if ssl_socket is False:
|
||||
exit(4)
|
||||
try:
|
||||
self.log.debug('Connect {}: {}'.format(self.config['server']['host'],
|
||||
int(self.config['server']['port'])))
|
||||
conn = ssl_socket.connect((self.config['server']['host'],
|
||||
int(self.config['server']['port'])))
|
||||
except socket.timeout:
|
||||
self.log.error('Connection timeout')
|
||||
ssl_socket.close()
|
||||
sleep(5)
|
||||
counter += 1
|
||||
except Exception as e:
|
||||
self.log.error('Connection failed: {}'.format(e))
|
||||
exit(5)
|
||||
self.log.debug('Conection established')
|
||||
self.log.debug('Peer certificate commonName: {}'.format(
|
||||
ssl_socket.getpeercert()['subject'][5][0][1]))
|
||||
self.log.debug('Peer certificate serialNumber: {}'.format(
|
||||
ssl_socket.getpeercert()['serialNumber']))
|
||||
return ssl_socket
|
||||
|
||||
|
||||
def run(self, status):
|
||||
"""
|
||||
starts the engine.
|
||||
param 1: integer
|
||||
"""
|
||||
self.status = status
|
||||
|
||||
# read config
|
||||
self.set_config()
|
||||
|
||||
# check given status
|
||||
if self.check_status() is False:
|
||||
exit(1)
|
||||
|
||||
# log config if level is debug
|
||||
if self.config['general']['loglevel'].lower() == 'debug':
|
||||
self.log_config()
|
||||
|
||||
# check certificates are readable
|
||||
certs = (self.config['server']['cert'],
|
||||
self.config['client']['cert'],
|
||||
self.config['client']['key'])
|
||||
if self.check_certs(certs) is False:
|
||||
exit(2)
|
||||
|
||||
# create ssl context
|
||||
self.context = self.create_ssl_context()
|
||||
if self.context is False:
|
||||
exit(3)
|
||||
|
||||
# get a ssl encrypted connection
|
||||
self.connection = self.create_ssl_connection()
|
||||
|
||||
# send status
|
||||
try:
|
||||
self.log.debug('Send new status: {}'.format(self.status))
|
||||
self.connection.send(self.status.encode(encoding='utf-8',
|
||||
errors='strict'))
|
||||
except Exception as e:
|
||||
self.log.error('Error: {}'.format(e))
|
||||
exit(6)
|
||||
try:
|
||||
response = self.connection.recv(1).decode(encoding='utf-8',
|
||||
errors='strict')
|
||||
self.log.debug('Server returns: {}'.format(response))
|
||||
if response == self.status:
|
||||
self.log.info('Status sucessfull updated')
|
||||
else:
|
||||
self.log.error('Failed to update status')
|
||||
self.log.debug('Disconnect from server')
|
||||
except Exception as e:
|
||||
self.log.error('Error: {}'.format(e))
|
||||
exit(7)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
s = SetStatus()
|
||||
if len(argv) < 2:
|
||||
log.error('Usage: setstatus.py <0|1>')
|
||||
exit(255)
|
||||
else:
|
||||
s.run(argv[1])
|
||||
|
54
source/client/python/watchdoor.py
Executable file
54
source/client/python/watchdoor.py
Executable file
|
@ -0,0 +1,54 @@
|
|||
#!/usr/bin/env python
|
||||
#coding: utf8
|
||||
|
||||
# file: watchdoor.py
|
||||
# date: 06.09.2020
|
||||
# mail: berhsi@web.de
|
||||
# desc: deamon who deals with edge detection at pin 18
|
||||
|
||||
import logging
|
||||
loglevel = logging.INFO
|
||||
formatstring = '%(asctime)s: %(levelname)s: %(message)s'
|
||||
logging.basicConfig(format=formatstring, level=loglevel)
|
||||
import time
|
||||
import RPi.GPIO as GPIO
|
||||
try:
|
||||
from setstatus import SetStatus
|
||||
except Exception as e:
|
||||
logging.error('Cant import module setstatus')
|
||||
logging.error('Error: {}'.format(e))
|
||||
|
||||
|
||||
GPIO.setmode(GPIO.BOARD) # kind of enumeration
|
||||
GPIO.setup(18, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) # pin 18 (GPIO 24)
|
||||
channel = 18
|
||||
|
||||
def voltage_changed(channel):
|
||||
'''
|
||||
callback-function
|
||||
'''
|
||||
if GPIO.input(channel) == GPIO.HIGH:
|
||||
# door closed -> pin hight
|
||||
logging.info('Pin high triggered - Space closed')
|
||||
s = SetStatus()
|
||||
s.run(0)
|
||||
else:
|
||||
# door open -> pin low
|
||||
logging.info('Pin low triggered - Space is open')
|
||||
s = SetStatus()
|
||||
s.run(1)
|
||||
|
||||
def main():
|
||||
'''
|
||||
'''
|
||||
logging.info('watchdoor.py started')
|
||||
GPIO.add_event_detect(channel,
|
||||
GPIO.BOTH,
|
||||
callback = voltage_changed,
|
||||
bouncetime = 200)
|
||||
while 1:
|
||||
time.sleep(0.1)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
14
source/client/python/watchdoor.service
Normal file
14
source/client/python/watchdoor.service
Normal file
|
@ -0,0 +1,14 @@
|
|||
[Unit]
|
||||
Description=Deamon for setting status API
|
||||
After=systemd-network.service network.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
WorkingDirectory=/opt/watchdoor/
|
||||
ExecStart=/opt/watchdoor/watchdoor.py
|
||||
SyslogIdentifier=watchdoor
|
||||
User=statusd
|
||||
Group=statusd
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
Loading…
Add table
Add a link
Reference in a new issue