driver rename

This commit is contained in:
devfix 2019-05-16 09:36:20 +02:00
parent 7a1efabe49
commit 281a00ddc0
35 changed files with 0 additions and 0 deletions

59
control/src/Makefile Normal file
View file

@ -0,0 +1,59 @@
# Name: Makefile
# Project: B15F (board15 Famulus Edition)
# Author: Tristan Krause
# Creation Date: 2019-03-22
# Environment
COMPILER_PATH = g++
# Options
LIB_DRV = ../lib/libb15fdrv.so
LIB_PATH = /usr/lib/
INCLUDE_PATH = /usr/include/b15f/
BIN_PATH = /usr/bin/
OBJ_MAIN = main.o
OUT_CLI = ../bin/cli.elf
OBJ_CLI = cli.o
CFLAGS = -std=c++17 -O3 -Wall -Wextra -fPIC
LDFLAGS_DRV = -lcurses -lpthread
LDFLAGS = $(LDFLAGS_DRV) -lb15fdrv
OBJECTS_DRV = drv/usart.o drv/b15f.o drv/plottyfile.o drv/dot.o
OBJECTS_UI = ui/view.o ui/view_selection.o ui/view_promt.o ui/view_info.o ui/view_monitor.o ui/ui.o
COMPILE = $(COMPILER_PATH) $(CFLAGS)
all: drv cli
drv: $(OBJECTS_DRV) $(LIB_DRV)
cli: drv $(OBJECTS_UI) $(OBJ_CLI)
@echo "Linking cli..."
mkdir -p ../bin
$(COMPILE) $(OBJ_CLI) $(OBJECTS_UI) -L../lib -Wl,-rpath=../lib -o $(OUT_CLI) $(LDFLAGS)
install: drv
cp $(LIB_DRV) $(LIB_PATH)
mkdir -p $(INCLUDE_PATH)
cp drv/*.h $(INCLUDE_PATH)
cp plotty $(BIN_PATH)
help:
@echo "This Makefile compiles the b15f driver lib and command line interface (CLI):"
@echo "make ......... to compile all"
@echo "make drv ..... to compile the b15f driver lib"
@echo "make cli ..... to compile the cli"
@echo "make install . to install the lib and headers on this machine"
@echo "make clean ... to delete objects and executables"
clean:
@echo "Cleaning..."
rm -f $(OBJECTS_DRV) $(OBJECTS_UI) $(OBJ_CLI) $(OUT_CLI) $(OBJ_MAIN) $(LIB_DRV)
.cpp.o:
$(COMPILE) -c $< -o $@
$(LIB_DRV):
@echo "Linking driver library..."
mkdir -p ../lib
$(COMPILE) $(OBJECTS_DRV) -shared -o $(LIB_DRV) $(LDFLAGS_DRV)

114
control/src/cli.cpp Normal file
View file

@ -0,0 +1,114 @@
#define B15F_CLI_DEBUG
#include <stdio.h>
#include <ncurses.h> // sudo apt-get install libncurses5-dev
#include <vector>
#include <string>
#include <iostream>
#include <signal.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <signal.h>
#include <future>
#include <thread>
#include <chrono>
#include "drv/b15f.h"
#include "ui/ui.h"
#include "ui/view_selection.h"
#include "ui/view_info.h"
#include "ui/view_monitor.h"
#include "ui/view_promt.h"
volatile int win_changed_cooldown = 0;
volatile bool t_refresh_active = false;
void signal_handler(int signal)
{
if(signal == SIGWINCH)
{
win_changed_cooldown = 10; // 100ms
if (!t_refresh_active)
{
if(t_refresh.joinable())
t_refresh.join();
t_refresh_active = true;
t_refresh = std::thread([](){
while(win_changed_cooldown--)
std::this_thread::sleep_for(std::chrono::milliseconds(10));
t_refresh_active = false;
if(win_stack.size())
win_stack.back()->repaint();
});
}
}
else if(signal == SIGINT)
{
cleanup();
std::cout << "SIGINT - Abbruch." << std::endl;
exit(EXIT_FAILURE);
}
}
void abort_handler(std::exception& ex)
{
ViewInfo* view = new ViewInfo();
view->setTitle("Fehler");
std::string msg(ex.what());
msg += "\n\nBeende in 5 Sekunden.";
view->setText(msg.c_str());
view->setLabelClose("");
view->repaint();
std::this_thread::sleep_for(std::chrono::milliseconds(5000));
cleanup();
std::cerr << std::endl << "*** EXCEPTION ***" << std::endl << ex.what() << std::endl;
exit(EXIT_FAILURE);
}
void init()
{
// init b15 driver
B15F::getInstance();
#ifndef B15F_CLI_DEBUG
std::cout << std::endl << "Starte in 3s ..." << std::endl;
sleep(3);
#endif
B15F::setAbortHandler(&abort_handler);
// init all ncurses stuff
initscr();
start_color();
curs_set(0); // 0: invisible, 1: normal, 2: very visible
clear();
noecho();
cbreak(); // Line buffering disabled. pass on everything
mousemask(ALL_MOUSE_EVENTS, NULL);
// connect signals to handler
signal(SIGWINCH, signal_handler);
signal(SIGINT, signal_handler);
// set view context
View::setWinContext(newwin(25, 85, 0, 0));
}
int main()
{
init();
int exit_code = EXIT_SUCCESS;
show_main(0);
cleanup();
return exit_code;
}

322
control/src/drv/b15f.cpp Normal file
View file

@ -0,0 +1,322 @@
#include "b15f.h"
B15F* B15F::instance = nullptr;
errorhandler_t B15F::errorhandler = nullptr;
B15F::B15F()
{
init();
}
void B15F::init()
{
std::string device = exec("bash -c 'ls /dev/ttyUSB*'");
while(device.find(' ') != std::string::npos || device.find('\n') != std::string::npos || device.find('\t') != std::string::npos)
device.pop_back();
if(device.length() == 0)
abort("Adapter nicht gefunden");
std::cout << PRE << "Verwende Adapter: " << device << std::endl;
std::cout << PRE << "Stelle Verbindung mit Adapter her... " << std::flush;
usart.setBaudrate(BAUDRATE);
usart.openDevice(device);
std::cout << "OK" << std::endl;
std::cout << PRE << "Teste Verbindung... " << std::flush;
uint8_t tries = 3;
while(tries--)
{
// verwerfe Daten, die µC noch hat
//discard();
if(!testConnection())
continue;
if(!testIntConv())
continue;
break;
}
if(tries == 0)
abort("Verbindungstest fehlgeschlagen. Neueste Version im Einsatz?");
std::cout << "OK" << std::endl;
// Gib board info aus
std::vector<std::string> info = getBoardInfo();
std::cout << PRE << "AVR Firmware Version: " << info[0] << " um " << info[1] << " Uhr (" << info[2] << ")" << std::endl;
}
void B15F::reconnect()
{
uint8_t tries = RECONNECT_TRIES;
while(tries--)
{
delay_ms(RECONNECT_TIMEOUT);
discard();
if(testConnection())
return;
}
abort("Verbindung kann nicht repariert werden");
}
void B15F::discard(void)
{
try
{
usart.clearOutputBuffer();
for(uint8_t i = 0; i < 16; i++)
{
usart.writeByte(RQ_DISC); // sende discard Befehl (verwerfe input)
delay_ms(4);
}
usart.clearInputBuffer();
}
catch(std::exception& ex)
{
abort(ex);
}
}
bool B15F::testConnection()
{
// erzeuge zufälliges Byte
srand(time(NULL));
uint8_t dummy = rand() % 256;
usart.writeByte(RQ_TEST);
usart.writeByte(dummy);
uint8_t aw = usart.readByte();
uint8_t mirror = usart.readByte();
return aw == MSG_OK && mirror == dummy;
}
bool B15F::testIntConv()
{
srand(time(NULL));
uint16_t dummy = rand() % (0xFFFF / 3);
usart.writeByte(RQ_INT);
usart.writeInt(dummy);
uint16_t aw = usart.readInt();
return aw == dummy * 3;
}
std::vector<std::string> B15F::getBoardInfo(void)
{
std::vector<std::string> info;
usart.writeByte(RQ_INFO);
uint8_t n = usart.readByte();
while(n--)
{
uint8_t len = usart.readByte();
std::string str;
while(len--) {
str += static_cast<char>(usart.readByte());
}
info.push_back(str);
}
uint8_t aw = usart.readByte();
if(aw != MSG_OK)
abort("Board Info fehlerhalft: code " + std::to_string((int) aw));
return info;
}
bool B15F::activateSelfTestMode()
{
usart.writeByte(RQ_ST);
uint8_t aw = usart.readByte();
return aw == MSG_OK;
}
bool B15F::digitalWrite0(uint8_t port)
{
usart.writeByte(RQ_BA0);
usart.writeByte(port);
uint8_t aw = usart.readByte();
delay_us(10);
return aw == MSG_OK;
}
bool B15F::digitalWrite1(uint8_t port)
{
usart.writeByte(RQ_BA1);
usart.writeByte(port);
uint8_t aw = usart.readByte();
delay_us(10);
return aw == MSG_OK;
}
uint8_t B15F::digitalRead0()
{
usart.clearInputBuffer();
usart.writeByte(RQ_BE0);
uint8_t byte = usart.readByte();
delay_us(10);
return byte;
}
uint8_t B15F::digitalRead1()
{
usart.clearInputBuffer();
usart.writeByte(RQ_BE1);
uint8_t byte = usart.readByte();
delay_us(10);
return byte;
}
uint8_t B15F::readDipSwitch()
{
usart.clearInputBuffer();
usart.writeByte(RQ_DSW);
uint8_t byte = usart.readByte();
delay_us(10);
return byte;
}
bool B15F::analogWrite0(uint16_t value)
{
usart.writeByte(RQ_AA0);
usart.writeInt(value);
uint8_t aw = usart.readByte();
delay_us(10);
return aw == MSG_OK;
}
bool B15F::analogWrite1(uint16_t value)
{
usart.writeByte(RQ_AA1);
usart.writeInt(value);
uint8_t aw = usart.readByte();
delay_us(10);
return aw == MSG_OK;
}
uint16_t B15F::analogRead(uint8_t channel)
{
usart.clearInputBuffer();
if(channel > 7)
abort("Bad ADC channel: " + std::to_string(channel));
uint8_t rq[] = {
RQ_ADC,
channel
};
int n_sent = usart.write_timeout(&rq[0], 0, sizeof(rq), 1000);
if(n_sent != sizeof(rq))
abort("Sent failed");
uint16_t adc = usart.readInt();
if(adc > 1023)
abort("Bad ADC data detected (1)");
return adc;
}
void B15F::analogSequence(uint8_t channel_a, uint16_t* buffer_a, uint32_t offset_a, uint8_t channel_b, uint16_t* buffer_b, uint32_t offset_b, uint16_t start, int16_t delta, uint16_t count)
{
buffer_a += offset_a;
buffer_b += offset_b;
usart.clearInputBuffer();
usart.writeByte(RQ_ADC_DAC_STROKE);
usart.writeByte(channel_a);
usart.writeByte(channel_b);
usart.writeInt(start);
usart.writeInt(static_cast<uint16_t>(delta));
usart.writeInt(count);
for(uint16_t i = 0; i < count; i++)
{
buffer_a[i] = usart.readInt();
buffer_b[i] = usart.readInt();
if(buffer_a[i] > 1023 || buffer_b[i] > 1023)
abort("Bad ADC data detected (2)");
}
uint8_t aw = usart.readByte();
if(aw != MSG_OK)
abort("Sequenz unterbrochen");
delay_us(10);
}
void B15F::delay_ms(uint16_t ms)
{
std::this_thread::sleep_for(std::chrono::milliseconds(ms));
}
void B15F::delay_us(uint16_t us)
{
std::this_thread::sleep_for(std::chrono::microseconds(us));
}
B15F& B15F::getInstance(void)
{
if(!instance)
instance = new B15F();
return *instance;
}
// https://stackoverflow.com/a/478960
std::string B15F::exec(std::string cmd) {
std::array<char, 128> buffer;
std::string result;
std::unique_ptr<FILE, decltype(&pclose)> pipe(popen(cmd.c_str(), "r"), pclose);
if (!pipe) {
throw std::runtime_error("popen() failed!");
}
while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) {
result += buffer.data();
}
return result;
}
void B15F::abort(std::string msg)
{
DriverException ex(msg);
abort(ex);
}
void B15F::abort(std::exception& ex)
{
if(errorhandler)
errorhandler(ex);
else
{
std::cerr << "NOTICE: B15F::errorhandler not set" << std::endl;
std::cout << ex.what() << std::endl;
throw DriverException(ex.what());
}
}
void B15F::setAbortHandler(errorhandler_t func)
{
errorhandler = func;
}

237
control/src/drv/b15f.h Normal file
View file

@ -0,0 +1,237 @@
#ifndef B15F_H
#define B15F_H
#include <iostream>
#include <bits/stdc++.h>
#include <string>
#include <fstream>
#include <cstdlib>
#include <chrono>
#include <cstdint>
#include <vector>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <termios.h>
#include "usart.h"
#include "driverexception.h"
#include "timeoutexception.h"
typedef std::function<void(std::exception&)> errorhandler_t;
class B15F
{
private:
// privater Konstruktor
B15F(void);
public:
/*************************************
* Grundfunktionen des B15F Treibers *
*************************************/
/**
* Initialisiert und testet die Verbindung zum B15
* \throws DriverException
*/
void init(void);
/**
* Versucht die Verbindung zum B15 wiederherzustellen
* \throws DriverException
*/
void reconnect(void);
/**
* Verwirft Daten im USART Puffer auf dieser Maschine und B15
* \throws DriverException
*/
void discard(void);
/**
* Testet die USART Verbindung auf Funktion
* \throws DriverException
*/
bool testConnection(void);
/**
* Testet die Integer Konvertierung der USART Verbindung
* \throws DriverException
*/
bool testIntConv(void);
/**
* Liefert Informationen zur aktuellen Firmware des B15
* \throws DriverException
*/
std::vector<std::string> getBoardInfo(void);
/**
* Lässt den Treiber für eine angegebene Zeit pausieren
* \param ms Verzögerung in Millisekunden
*/
void delay_ms(uint16_t ms);
/**
* Lässt den Treiber für eine angegebene Zeit pausieren
* \param us Verzögerung in Microsekunden
*/
void delay_us(uint16_t us);
/**
* Liefert eine Referenz zur aktuellen Treiber-Instanz
* @throws DriverException
*/
static B15F& getInstance(void);
/**
* Führt ein Befehl auf dieser Maschine aus und liefert stdout zurück
* \param cmd Der Befehl
*/
static std::string exec(std::string cmd);
/**
* Multithread sicherer Abbruch des B15F-Treibers
* \param msg Beschreibung der Abbruchursache
*/
static void abort(std::string msg);
/**
* Multithread sicherer Abbruch des B15F-Treibers
* \param ex Exception als Abbruchursache
*/
static void abort(std::exception& ex);
/**
* Setzt eine Fehlerbehandlungsroutine für den Treiberabbruch (abort)
* \param func Funktion, die Exception als Parameter bekommt
*/
static void setAbortHandler(errorhandler_t func);
/*************************************/
/*************************
* Steuerbefehle für B15 *
*************************/
/**
* Versetzt das Board in den Selbsttest-Modus
* WICHTIG: Es darf dabei nichts an den Klemmen angeschlossen sein!
* \throws DriverException
*/
bool activateSelfTestMode(void);
/**
* Setzt den Wert des digitalen Ausgabeports 0
* \param port Wert für gesamten Port
* \throws DriverException
*/
bool digitalWrite0(uint8_t);
/**
* Setzt den Wert des digitalen Ausgabeports 1
* \param port Wert für gesamten Port
* \throws DriverException
*/
bool digitalWrite1(uint8_t);
/**
* Liest den Wert des digitalen Eingabeports 0
* \return Wert für gesamten Port
* \throws DriverException
*/
uint8_t digitalRead0(void);
/**
* Liest den Wert des digitalen Eingabeports 1
* \return Wert für gesamten Port
* \throws DriverException
*/
uint8_t digitalRead1(void);
/**
* Liest den Wert des digitalen Eingabeports, an dem der DIP-switch angeschlossen ist (S7)
* \return Wert für gesamten Port
* \throws DriverException
*/
uint8_t readDipSwitch(void);
/**
* Setzt den Wert des Digital-Analog-Converters (DAC / DAU) 0
* \param port 10-Bit Wert
* \throws DriverException
*/
bool analogWrite0(uint16_t);
/**
* Setzt den Wert des Digital-Analog-Converters (DAC / DAU) 1
* \param port 10-Bit Wert
* \throws DriverException
*/
bool analogWrite1(uint16_t);
/**
* Liest den Wert des Analog-Digital-Converters (ADC / ADU)
* \param channel Kanalwahl von 0 - 7
* \throws DriverException
*/
uint16_t analogRead(uint8_t channel);
/**
* \brief Komplexe Analoge Sequenz
* DAC 0 wird auf den Startwert gesetzt und dann schrittweise um Delta inkrementiert.
* Für jeden eingestelleten DAC-Wert werden zwei ADCs (channel_a und channel_b) angesprochen und die Werte übermittelt.
* Die Werte werden in buffer_a für Kanal a und buffer_b für Kanal b gespeichert.
* \param channel_a Auswahl des ADC a, von 0 - 7
* \param buffer_a Speichertort für Werte des Kanals a
* \param offset_a Anzahl an Werten des Kanals a, die im Speicher übersprungen werden sollen
* \param channel_b Auswahl des ADC b, von 0 - 7
* \param buffer_b Speichertort für Werte des Kanals b
* \param offset_b Anzahl an Werten des Kanals b, die im Speicher übersprungen werden
* \param start Startwert des DACs
* \param delta Schrittweite, mit welcher der DAC inkrementiert wird
* \param count Anzahl an Inkrementierungen
* \throws DriverException
*/
void analogSequence(uint8_t channel_a, uint16_t* buffer_a, uint32_t offset_a, uint8_t channel_b, uint16_t* buffer_b, uint32_t offset_b, uint16_t start, int16_t delta, uint16_t count);
/*************************/
// CONSTANTS
const std::string PRE = "[B15F] ";
constexpr static uint8_t MSG_OK = 0xFF;
constexpr static uint8_t MSG_FAIL = 0xFE;
constexpr static uint16_t RECONNECT_TIMEOUT = 64; // ms
constexpr static uint16_t WDT_TIMEOUT = 15; // ms
constexpr static uint8_t RECONNECT_TRIES = 3;
constexpr static uint32_t BAUDRATE = 57600;
private:
USART usart;
static B15F* instance;
static errorhandler_t errorhandler;
// REQUESTS
constexpr static uint8_t RQ_DISC = 0;
constexpr static uint8_t RQ_TEST = 1;
constexpr static uint8_t RQ_INFO = 2;
constexpr static uint8_t RQ_INT = 3;
constexpr static uint8_t RQ_ST = 4;
constexpr static uint8_t RQ_BA0 = 5;
constexpr static uint8_t RQ_BA1 = 6;
constexpr static uint8_t RQ_BE0 = 7;
constexpr static uint8_t RQ_BE1 = 8;
constexpr static uint8_t RQ_DSW = 9;
constexpr static uint8_t RQ_AA0 = 10;
constexpr static uint8_t RQ_AA1 = 11;
constexpr static uint8_t RQ_ADC = 12;
constexpr static uint8_t RQ_ADC_DAC_STROKE = 13;
};
#endif // B15F_H

22
control/src/drv/dot.cpp Normal file
View file

@ -0,0 +1,22 @@
#include "dot.h"
Dot::Dot(uint16_t x, uint16_t y, uint8_t curve) : x(x), y(y), curve(curve)
{
if(curve >= 64)
throw std::range_error("Kurvenindex muss im Bereich [0, 63] liegen");
}
uint16_t Dot::getX() const
{
return x;
}
uint16_t Dot::getY() const
{
return y;
}
uint8_t Dot::getCurve(void) const
{
return curve;
}

21
control/src/drv/dot.h Normal file
View file

@ -0,0 +1,21 @@
#ifndef DOT_H
#define DOT_H
#include <cstdint>
#include <stdexcept>
class Dot
{
public:
Dot(uint16_t x, uint16_t y, uint8_t curve);
uint16_t getX(void) const;
uint16_t getY(void) const;
uint8_t getCurve(void) const;
private:
uint16_t x, y;
uint8_t curve;
};
#endif // DOT_H

View file

@ -0,0 +1,33 @@
#ifndef DRIVEREXCEPTION_H
#define DRIVEREXCEPTION_H
#include <exception>
// SOURCE: https://stackoverflow.com/a/8152888
class DriverException: public std::exception
{
public:
explicit DriverException(const char* message) : msg_(message)
{
}
explicit DriverException(const std::string& message) : msg_(message)
{
}
virtual ~DriverException() throw ()
{
}
virtual const char* what() const throw ()
{
return msg_.c_str();
}
protected:
std::string msg_;
};
#endif // DRIVEREXCEPTION_H

View file

@ -0,0 +1,198 @@
#include "plottyfile.h"
void PlottyFile::addDot(Dot& dot)
{
dots.push_back(dot);
}
void PlottyFile::addDot(Dot dot)
{
dots.push_back(dot);
}
void PlottyFile::setFunctionType(FunctionType function_type)
{
this->function_type = function_type;
}
void PlottyFile::setQuadrant(uint8_t quadrant)
{
if(quadrant < 1 || quadrant > 4)
throw std::range_error("Ungueltiger Quadrant");
this->quadrant = quadrant;
}
void PlottyFile::setRefX(uint16_t ref_x)
{
this->ref_x = ref_x;
}
void PlottyFile::setRefY(uint16_t ref_y)
{
this->ref_y = ref_y;
}
void PlottyFile::setParaFirstCurve(uint16_t para_first)
{
this->para_first = para_first;
}
void PlottyFile::setParaStepWidth(uint16_t para_stepwidth)
{
this->para_stepwidth = para_stepwidth;
}
void PlottyFile::setUnitX(std::string unit_x)
{
this->unit_x = unit_x;
}
void PlottyFile::setDescX(std::string desc_x)
{
this->desc_x = desc_x;
}
void PlottyFile::setUnitY(std::string unit_y)
{
this->unit_y = unit_y;
}
void PlottyFile::setDescY(std::string desc_y)
{
this->desc_y = desc_y;
}
void PlottyFile::setUnitPara(std::string unit_para)
{
this->unit_para = unit_para;
}
void PlottyFile::setDescPara(std::string desc_para)
{
this->desc_para = desc_para;
}
FunctionType PlottyFile::getFunctionType() const
{
return function_type;
}
uint8_t PlottyFile::getQuadrant() const
{
return quadrant;
}
uint16_t PlottyFile::getRefX() const
{
return ref_x;
}
uint16_t PlottyFile::getRefY() const
{
return ref_y;
}
uint16_t PlottyFile::getParaFirstCurve() const
{
return para_first;
}
uint16_t PlottyFile::getParaStepWidth() const
{
return para_stepwidth;
}
std::string PlottyFile::getUnitX() const
{
return unit_x;
}
std::string PlottyFile::getDescX() const
{
return desc_x;
}
std::string PlottyFile::getUnitY() const
{
return unit_y;
}
std::string PlottyFile::getDescY() const
{
return desc_y;
}
std::string PlottyFile::getUnitPara() const
{
return unit_para;
}
std::string PlottyFile::getDescPara() const
{
return desc_para;
}
void PlottyFile::prepStr(std::string& str, uint8_t len)
{
if(str.length() > len)
throw std::runtime_error("Zu grosser String.");
if(str.length() != len)
str += '\n';
while(str.length() < len)
str += '\0';
}
void PlottyFile::writeToFile(std::string filename)
{
prepStr(unit_x, STR_LEN_SHORT);
prepStr(desc_x, STR_LEN_LARGE);
prepStr(unit_y, STR_LEN_SHORT);
prepStr(desc_y, STR_LEN_LARGE);
prepStr(unit_para, STR_LEN_SHORT);
prepStr(desc_para, STR_LEN_LARGE);
std::ofstream file(filename);
// write file header
file.write(reinterpret_cast<char*>(&command), 1);
file.write(head.c_str(), head.length());
file.write(filetype.c_str(), filetype.length());
file.write(reinterpret_cast<char*>(&version), 2);
file.write(reinterpret_cast<char*>(&subversion), 2);
file.put(static_cast<uint8_t>(function_type));
file.write(reinterpret_cast<char*>(&quadrant), 1);
file.write(reinterpret_cast<char*>(&ref_x), 2);
file.write(reinterpret_cast<char*>(&ref_y), 2);
file.write(reinterpret_cast<char*>(&para_first), 2);
file.write(reinterpret_cast<char*>(&para_stepwidth), 2);
file.write(unit_x.c_str(), unit_x.length());
file.write(desc_x.c_str(), desc_x.length());
file.write(unit_y.c_str(), unit_y.length());
file.write(desc_y.c_str(), desc_y.length());
file.write(unit_para.c_str(), unit_para.length());
file.write(desc_para.c_str(), desc_para.length());
file.write(reinterpret_cast<const char*>(&eof), 1);
// make sure header size is 256 Byte
while(file.tellp() < 256)
file.put(0);
for(Dot& dot : dots)
{
file.put((dot.getX() >> 8) | (static_cast<uint8_t>(dot.getCurve()) << 2));
file.put(dot.getX() & 0xFF);
file.put(dot.getY() >> 8);
file.put(dot.getY() & 0xFF);
}
file.close();
}
void PlottyFile::startPlotty(std::string filename)
{
int code = system(("plotty --in " + filename).c_str());
if(code)
throw std::runtime_error("Fehler beim Aufruf von plotty");
}

View file

@ -0,0 +1,79 @@
#ifndef PLOTTYFILE_H
#define PLOTTYFILE_H
#include <iostream>
#include <fstream>
#include <exception>
#include <vector>
#include "dot.h"
enum FunctionType
{
CurveFamily = 'S',
Curve = 'C',
Level = 'P'
};
class PlottyFile
{
public:
void addDot(Dot& dot);
void addDot(Dot dot);
void setFunctionType(FunctionType);
void setQuadrant(uint8_t);
void setRefX(uint16_t);
void setRefY(uint16_t);
void setParaFirstCurve(uint16_t);
void setParaStepWidth(uint16_t);
void setUnitX(std::string);
void setDescX(std::string);
void setUnitY(std::string);
void setDescY(std::string);
void setUnitPara(std::string);
void setDescPara(std::string);
FunctionType getFunctionType(void) const;
uint8_t getQuadrant(void) const;
uint16_t getRefX(void) const;
uint16_t getRefY(void) const;
uint16_t getParaFirstCurve(void) const;
uint16_t getParaStepWidth(void) const;
std::string getUnitX(void) const;
std::string getDescX(void) const;
std::string getUnitY(void) const;
std::string getDescY(void) const;
std::string getUnitPara(void) const;
std::string getDescPara(void) const;
void writeToFile(std::string filename);
void startPlotty(std::string filename);
private:
void prepStr(std::string& str, uint8_t len);
std::vector<Dot> dots;
int8_t command = 0x1D;
const std::string head = "HTWK-HWLab";
const std::string filetype = "MD";
int16_t version = 1;
int16_t subversion = 0;
FunctionType function_type = FunctionType::Curve;
uint8_t quadrant = 1;
uint16_t ref_x = 1023;
uint16_t ref_y = 1023;
uint16_t para_first = 1;
uint16_t para_stepwidth = 1;
std::string unit_x;
std::string desc_x;
std::string unit_y;
std::string desc_y;
std::string unit_para;
std::string desc_para;
const uint8_t eof = 0xD;
constexpr static uint8_t STR_LEN_SHORT = 10;
constexpr static uint8_t STR_LEN_LARGE = 20;
};
#endif // PLOTTYFILE_H

View file

@ -0,0 +1,35 @@
#ifndef TIMEOUTEXCEPTION_H
#define TIMEOUTEXCEPTION_H
#include <exception>
// SOURCE: https://stackoverflow.com/a/8152888
class TimeoutException: public std::exception
{
public:
explicit TimeoutException(const char* message, int timeout) : TimeoutException(std::string(message), timeout)
{
}
explicit TimeoutException(const std::string& message, int timeout) : msg(message), m_timeout(timeout)
{
if(!msg.length())
msg = "Timeout reached (" + std::to_string(m_timeout) + ")";
}
virtual ~TimeoutException() throw ()
{
}
virtual const char* what() const throw ()
{
return msg.c_str();
}
protected:
std::string msg;
int m_timeout;
};
#endif // TIMEOUTEXCEPTION_H

324
control/src/drv/usart.cpp Normal file
View file

@ -0,0 +1,324 @@
#include "usart.h"
void USART::openDevice(std::string device)
{
file_desc = open(device.c_str(), O_RDWR | O_NOCTTY | O_NDELAY /* | O_NONBLOCK*/);
if(file_desc <= 0)
throw USARTException("Fehler beim Öffnen des Gerätes");
struct termios options;
int code = tcgetattr(file_desc, &options);
if(code)
throw USARTException("Fehler beim Lesen der Geräteparameter");
options.c_cflag = CS8 | CLOCAL | CREAD;
options.c_iflag = IGNPAR;
options.c_oflag = 0;
options.c_lflag = 0;
options.c_cc[VMIN] = 0; // #bytes read returns at least
options.c_cc[VTIME] = timeout;
code = cfsetspeed(&options, baudrate);
if(code)
throw USARTException("Fehler beim Setzen der Baudrate");
code = tcsetattr(file_desc, TCSANOW, &options);
if(code)
throw USARTException("Fehler beim Setzen der Geräteparameter");
clearOutputBuffer();
clearInputBuffer();
}
void USART::closeDevice()
{
int code = close(file_desc);
if(code)
throw USARTException("Fehler beim Schließen des Gerätes");
}
void USART::clearInputBuffer()
{
int code = tcflush(file_desc, TCIFLUSH);
if(code)
throw USARTException("Fehler beim Leeren des Eingangspuffers");
}
void USART::clearOutputBuffer()
{
int code = tcflush(file_desc, TCOFLUSH);
if(code)
throw USARTException("Fehler beim Leeren des Ausgangspuffers");
}
void USART::flushOutputBuffer()
{
int code = tcdrain(file_desc);
if(code)
throw USARTException("Fehler beim Versenden des Ausgangspuffers");
}
void USART::printStatistics()
{
double pz = 1e2 * n_blocks_failed / n_blocks_total;
pz = std::round(pz * 1e2) / 1e2;
std::cout << "blocks total: " << n_blocks_total << " ok: " << (n_blocks_total - n_blocks_failed) << " failed: " << n_blocks_failed << " (" << pz << "%)" << std::endl;
}
void USART::writeByte(uint8_t b)
{
int sent = write(file_desc, &b, 1);
if(sent != 1)
{
std::cout << "WARNUNG: Fehler beim Senden (" << sent << "): writeByte(), wiederhole..." << std::endl;
usleep(100000);
sent = write(file_desc, &b, 1);
if(sent != 1)
throw USARTException("Fehler beim Senden: writeByte()");
}
}
void USART::writeInt(uint16_t d)
{
int sent = write(file_desc, reinterpret_cast<char*>(&d), 2);
if(sent != 2)
throw USARTException("Fehler beim Senden: writeInt()");
}
int USART::read_timeout(uint8_t* buffer, uint16_t offset, uint8_t len, uint32_t timeout)
{
uint32_t elapsed = 0;
int n_read = -1;
auto start = std::chrono::steady_clock::now();
auto end = start;
while(elapsed < timeout)
{
n_read = read(file_desc, buffer + offset, len);
if (n_read == len)
return n_read;
end = std::chrono::steady_clock::now();
elapsed = std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
}
return 0;
}
int USART::write_timeout(uint8_t* buffer, uint16_t offset, uint8_t len, uint32_t timeout)
{
uint32_t elapsed = 0;
int n_sent = -1;
auto start = std::chrono::steady_clock::now();
auto end = start;
while(elapsed < timeout)
{
n_sent = write(file_desc, buffer + offset, len);
flushOutputBuffer();
if (n_sent == len)
return n_sent;
end = std::chrono::steady_clock::now();
elapsed = std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
}
return n_sent;
}
void USART::writeBlock(uint8_t* buffer, uint16_t offset, uint8_t len)
{
uint8_t crc;
uint8_t aw;
const uint16_t us_per_bit = (1000000 / baudrate) * 16;
const uint16_t n_total = len + 3;
n_blocks_total++;
bool failed = false;
do
{
// calc crc
crc = 0;
for(uint8_t i = 0; i < len; i++)
{
crc ^= buffer[i];
for (uint8_t k = 0; k < 8; k++)
{
if (crc & 1)
crc ^= CRC7_POLY;
crc >>= 1;
}
}
// construct block
block_buffer[0] = len;
std::memcpy(&block_buffer[1], buffer + offset, len);
block_buffer[len + 1] = crc;
block_buffer[len + 2] = BLOCK_END;
// send block
clearOutputBuffer();
clearInputBuffer();
int n_sent = write_timeout(&block_buffer[0], 0, len + 3, us_per_bit * n_total);
if(n_sent != n_total)
throw std::runtime_error("fatal (send): " + std::to_string(n_sent));
/*for(uint8_t i = 0; i < len + 3; i++)
{
write_timeout(&block_buffer[i], 0, 1, us_per_bit * n_total);
//tcdrain(file_desc);
//usleep(1000);
}*/
// flush output data
tcdrain(file_desc);
//usleep(us_per_bit * n_total * 10);
// check response
int n_read = read_timeout(&aw, 0, 1, us_per_bit * n_blocks_total * 10);
for(uint16_t i = 0; i < 255 && n_read != 1; i++)
{
writeByte(0x80); // Stoppzeichen für Block
if(tcdrain(file_desc))
{
std::cout << "drain failed" << std::endl;
}
std::cout << "WARNING: read error (" << n_read << "), retry #" << (int) i << std::endl;
usleep(us_per_bit*100);
n_read = read_timeout(&aw, 0, 1, us_per_bit);
}
if(n_read != 1)
throw std::runtime_error("fatal: " + std::to_string(n_read));
//clearInputBuffer();
if(aw != 0xFF) {
if(!failed)
n_blocks_failed++;
failed = true;
std::cout << "block failed, retry" << std::endl;
}
}
while(aw != 0xFF);
//std::cout << "OK" << std::endl;
}
uint8_t USART::readByte(void)
{
char b;
auto start = std::chrono::steady_clock::now();
auto end = start;
uint16_t elapsed = 0;
while(elapsed < timeout * 100)
{
int code = read(file_desc, &b, 1);
if (code > 0)
return static_cast<uint8_t>(b);
end = std::chrono::steady_clock::now();
elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
}
throw TimeoutException("Verbindung unterbrochen.", timeout);
}
uint16_t USART::readInt(void)
{
return readByte() | readByte() << 8;
}
bool USART::readBlock(uint8_t* buffer, uint16_t offset)
{
uint8_t len = readByte();
uint8_t crc = 0;
buffer += offset;
uint32_t block_timeout = timeout / 10;
// wait for block
int n_ready;
uint16_t elapsed = 0;
auto start = std::chrono::steady_clock::now();
auto end = start;
while(elapsed < block_timeout)
{
int code = ioctl(file_desc, FIONREAD, &n_ready);
if(code != 0)
{
std::cout << "n_ready code: " << code << std::endl;
return false;
}
if(n_ready >= len + 1)
break;
end = std::chrono::steady_clock::now();
elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
}
if(elapsed >= timeout)
{
std::cout << "block timeout: " << std::endl;
return false;
}
while(len--)
{
*buffer = readByte();
crc ^= *buffer++;
for (uint8_t i = 0; i < 8; i++)
{
if (crc & 1)
crc ^= CRC7_POLY;
crc >>= 1;
}
}
crc ^= readByte();
for (uint8_t i = 0; i < 8; i++)
{
if (crc & 1)
crc ^= CRC7_POLY;
crc >>= 1;
}
if(TEST == 1)
crc = 1;
if(TEST > 100)
TEST = 0;
if (crc == 0)
{
writeByte(0xFF);
return true;
}
else
{
writeByte(0xFE);
return false;
}
}
uint32_t USART::getBaudrate()
{
return baudrate;
}
uint8_t USART::getTimeout()
{
return timeout;
}
void USART::setBaudrate(uint32_t baudrate)
{
this->baudrate = baudrate;
}
void USART::setTimeout(uint8_t timeout)
{
this->timeout = timeout;
}

150
control/src/drv/usart.h Normal file
View file

@ -0,0 +1,150 @@
#ifndef USART_H
#define USART_H
#include <iostream>
#include <cstdint>
#include <chrono>
#include <unistd.h>
#include <cstring>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <termios.h>
#include <cmath>
#include "usartexception.h"
#include "timeoutexception.h"
class USART
{
public:
/*************************************************
* Methoden für die Verwaltung der Schnittstelle *
*************************************************/
/**
* Öffnet die USART Schnittstelle
* \param device Linux-Gerätepfad
* \throws USARTException
*/
void openDevice(std::string device);
/**
* Schließt die USART Schnittstelle
* \throws USARTException
*/
void closeDevice(void);
/**
* Verwirft Daten, die bereits im Puffer liegen, aber noch nicht gelesen wurden
* \throws USARTException
*/
void clearInputBuffer(void);
/**
* Verwirft Daten, die bereits im Puffer liegen, aber noch nicht gesendet wurden
* \throws USARTException
*/
void clearOutputBuffer(void);
/**
* Schreibt Daten, die bereits im Puffer liegen, aber noch nicht gesendet wurden
* \throws USARTException
*/
void flushOutputBuffer(void);
/**
* Gibt Anzahl an erfolgreichen und fehlgeschlagenen Block-Übertragungen an
*/
void printStatistics(void);
/*************************************************/
/*************************************
* Methoden für die Datenübertragung *
*************************************/
/**
* Sendet ein Byte über die USART Schnittstelle
* \param b das zu sendende Byte
* \throws USARTException
*/
void writeByte(uint8_t b);
/**
* Sendet ein Integer über die USART Schnittstelle
* \param b das zu sendende Byte
* \throws USARTException
*/
void writeInt(uint16_t d);
/**
* Empfängt ein Byte über die USART Schnittstelle
* \throws USARTException
*/
uint8_t readByte(void);
/**
* Empfängt ein Integer über die USART Schnittstelle
* \throws USARTException
*/
uint16_t readInt(void);
int read_timeout(uint8_t* buffer, uint16_t offset, uint8_t len, uint32_t timeout);
int write_timeout(uint8_t* buffer, uint16_t offset, uint8_t len, uint32_t timeout);
void writeBlock(uint8_t* buffer, uint16_t offset, uint8_t len);
bool readBlock(uint8_t* buffer, uint16_t offset);
/*************************************/
/***************************************
* Methoden für einstellbare Parameter *
***************************************/
/**
* Liefert die eingestellte Baudrate
* <b>Änderungen werden erst nach einem open() wirksam</b>
*/
uint32_t getBaudrate(void);
/**
* Liefert den eingestellten Timeout (in Dezisekunden)
* <b>Änderungen werden erst nach einem open() wirksam</b>
*/
uint8_t getTimeout(void);
/**
* Setzt die Baudrate
* <b>Änderungen werden erst nach einem open() wirksam</b>
*/
void setBaudrate(uint32_t baudrate);
/**
* Setzt den Timeout (in Dezisekunden)
* <b>Änderungen werden erst nach einem open() wirksam</b>
*/
void setTimeout(uint8_t timeout);
/***************************************/
constexpr static uint8_t CRC7_POLY = 0x91;
constexpr static uint8_t MAX_BLOCK_SIZE = 64;
constexpr static uint8_t BLOCK_END = 0x80;
private:
int file_desc = -1; // Linux Dateideskriptor
uint32_t baudrate = 9600; // Standard-Baudrate, sollte mit setBaudrate() überschrieben werden!
int TEST = 0;
uint8_t timeout = 10; // in Dezisekunden
uint8_t block_buffer[MAX_BLOCK_SIZE + 3];
// debug statistics
uint32_t n_blocks_total = 0;
uint32_t n_blocks_failed = 0;
};
#endif // USART_H

View file

@ -0,0 +1,33 @@
#ifndef USARTEXCEPTION_H
#define USARTEXCEPTION_H
#include <exception>
#include <string>
// SOURCE: https://stackoverflow.com/a/8152888
class USARTException: public std::exception
{
public:
explicit USARTException(const char* message) : msg(message)
{
}
explicit USARTException(const std::string& message) : msg(message)
{
}
virtual ~USARTException() throw ()
{
}
virtual const char* what() const throw ()
{
return msg.c_str();
}
protected:
std::string msg;
};
#endif // USARTEXCEPTION_H

View file

@ -0,0 +1,21 @@
set margin 10,10
unset key
set grid
set title ''
set xlabel 'U_{DS} [V]'
set ylabel 'I_D [mA]'
set xrange [0:5]
set yrange [0:50]
set label at 4,2 'U_{GS} [V] = 440' left
set label at 4,4 'U_{GS} [V] = 460' left
set label at 4,7 'U_{GS} [V] = 480' left
set label at 3,14 'U_{GS} [V] = 500' left
set label at 2,22 'U_{GS} [V] = 520' left
set label at 1,33 'U_{GS} [V] = 540' left
set label at 0,38 'U_{GS} [V] = 560' left
set label at 0,38 'U_{GS} [V] = 580' left
set label at 0,38 'U_{GS} [V] = 600' left
unset output
set terminal qt
unset output
plot "/tmp/tempfile0" using ($1*0.004888):($2*0.048876) binary format="%int16%int16" endian=big title 'U_{GS} [V] = 440' w l,"/tmp/tempfile1" using ($1*0.004888):($2*0.048876) binary format="%int16%int16" endian=big title 'U_{GS} [V] = 460' w l,"/tmp/tempfile2" using ($1*0.004888):($2*0.048876) binary format="%int16%int16" endian=big title 'U_{GS} [V] = 480' w l,"/tmp/tempfile3" using ($1*0.004888):($2*0.048876) binary format="%int16%int16" endian=big title 'U_{GS} [V] = 500' w l,"/tmp/tempfile4" using ($1*0.004888):($2*0.048876) binary format="%int16%int16" endian=big title 'U_{GS} [V] = 520' w l,"/tmp/tempfile5" using ($1*0.004888):($2*0.048876) binary format="%int16%int16" endian=big title 'U_{GS} [V] = 540' w l,"/tmp/tempfile6" using ($1*0.004888):($2*0.048876) binary format="%int16%int16" endian=big title 'U_{GS} [V] = 560' w l,"/tmp/tempfile7" using ($1*0.004888):($2*0.048876) binary format="%int16%int16" endian=big title 'U_{GS} [V] = 580' w l,"/tmp/tempfile8" using ($1*0.004888):($2*0.048876) binary format="%int16%int16" endian=big title 'U_{GS} [V] = 600' w l

BIN
control/src/graph Executable file

Binary file not shown.

BIN
control/src/plotty Executable file

Binary file not shown.

BIN
control/src/test_plot Normal file

Binary file not shown.

282
control/src/ui/ui.cpp Normal file
View file

@ -0,0 +1,282 @@
#include "ui.h"
#include "../drv/b15f.h"
std::vector<View*> win_stack;
std::thread t_refresh;
void show_main(int)
{
ViewSelection* view = new ViewSelection();
view->setTitle("B15F - Command Line Interface");
view->addChoice("[ Monitor - Eingaben beobachten ]", &show_monitor);
view->addChoice("[ Digitale Ausgabe BE0 ]", &show_digital_output0);
view->addChoice("[ Digitale Ausgabe BE1 ]", &show_digital_output1);
view->addChoice("[ Analoge Ausgabe AA0 ]", &show_analog_output0);
view->addChoice("[ Analoge Ausgabe AA1 ]", &show_analog_output1);
view->addChoice("[ Selbsttest des B15 ]", &show_selftest_info);
view->addChoice("[ Informationen ]", &show_info);
view->addChoice("", nullptr);
view->addChoice("[ Beenden ]", &finish);
view->repaint();
win_stack.push_back(view);
input(0);
}
void input(int)
{
call_t nextCall;
int key;
do
{
key = wgetch(View::getWinContext());
win_stack.back()->repaint();
nextCall = win_stack.back()->keypress(key);
if(key == -1)
view_back(key);
if(nextCall)
nextCall(key);
}
while(win_stack.size());
}
void view_back(int)
{
if(win_stack.size())
{
delete win_stack.back();
win_stack.pop_back();
}
if(win_stack.size())
win_stack.back()->repaint();
}
void finish(int)
{
cleanup();
exit(EXIT_SUCCESS);
}
void cleanup()
{
if(t_refresh.joinable())
t_refresh.join();
clrtoeol();
refresh();
endwin();
}
void show_info(int)
{
ViewInfo* view = new ViewInfo();
view->setTitle("Info");
view->setText("Informationen zu Board 15 Famulus Edition\nEs war einmal...");
view->setLabelClose("[ Zurueck ]");
view->repaint();
win_stack.push_back(view);
input(0);
}
void show_monitor(int)
{
ViewMonitor* view = new ViewMonitor();
view->setTitle("Monitor");
view->setText("\nErfasse Messwerte...");
view->setLabelClose("[ Zurueck ]");
view->repaint();
win_stack.push_back(view);
input(0);
}
void show_invalid_port_input(int)
{
ViewInfo* view = new ViewInfo();
view->setTitle("Falsche Eingabe");
view->setText("Bitte geben Sie einen Wert aus dem Intervall [0, FF] an.");
view->setLabelClose("[ Schliessen ]");
view->repaint();
win_stack.push_back(view);
input(0);
}
void show_invalid_dac_input(int)
{
ViewInfo* view = new ViewInfo();
view->setTitle("Falsche Eingabe");
view->setText("Bitte geben Sie einen Wert aus dem Intervall [0, 1023] an.");
view->setLabelClose("[ Schliessen ]");
view->repaint();
win_stack.push_back(view);
input(0);
}
void write_digital_output0(int)
{
try
{
int d = std::stoi(static_cast<ViewPromt*>(win_stack.back())->getInput(), 0, 16);
if(d > 255 || 0 > d)
throw std::invalid_argument("bad value");
uint8_t port = static_cast<uint8_t>(d);
B15F& drv = B15F::getInstance();
drv.digitalWrite0(port);
view_back(0);
}
catch(std::invalid_argument& ex)
{
show_invalid_port_input(0);
}
}
void write_digital_output1(int)
{
try
{
int d = std::stoi(static_cast<ViewPromt*>(win_stack.back())->getInput(), 0, 16);
if(d > 255 || 0 > d)
throw std::invalid_argument("bad value");
uint8_t port = static_cast<uint8_t>(d);
B15F& drv = B15F::getInstance();
drv.digitalWrite1(port);
view_back(0);
}
catch(std::invalid_argument& ex)
{
show_invalid_port_input(0);
}
}
void write_analog_output0(int)
{
try
{
uint16_t port = std::stoi(static_cast<ViewPromt*>(win_stack.back())->getInput());
if(port > 1023)
throw std::invalid_argument("bad value");
B15F& drv = B15F::getInstance();
drv.analogWrite0(port);
view_back(0);
}
catch(std::invalid_argument& ex)
{
show_invalid_dac_input(0);
}
}
void write_analog_output1(int)
{
try
{
uint16_t port = std::stoi(static_cast<ViewPromt*>(win_stack.back())->getInput());
if(port > 1023)
throw std::invalid_argument("bad value");
B15F& drv = B15F::getInstance();
drv.analogWrite1(port);
view_back(0);
}
catch(std::invalid_argument& ex)
{
show_invalid_dac_input(0);
}
}
void show_digital_output0(int)
{
ViewPromt* view = new ViewPromt();
view->setTitle("Digitale Ausgabe BE0");
view->setMessage("\nAusgabe Port-Wert (hex): 0x");
view->setCancel("[ Zurueck ]", true);
view->setConfirm("[ OK ]", &write_digital_output0);
view->repaint();
win_stack.push_back(view);
input(0);
}
void show_digital_output1(int)
{
ViewPromt* view = new ViewPromt();
view->setTitle("Digitale Ausgabe BE1");
view->setMessage("\nAusgabe Port-Wert (hex): 0x");
view->setCancel("[ Zurueck ]", true);
view->setConfirm("[ OK ]", &write_digital_output1);
view->repaint();
win_stack.push_back(view);
input(0);
}
void show_analog_output0(int)
{
ViewPromt* view = new ViewPromt();
view->setTitle("Analoge Ausgabe AA0");
view->setMessage("\nAusgabe 10-Bit-Wert (0...1023): ");
view->setCancel("[ Zurueck ]", true);
view->setConfirm("[ OK ]", &write_analog_output0);
view->repaint();
win_stack.push_back(view);
input(0);
}
void show_analog_output1(int)
{
ViewPromt* view = new ViewPromt();
view->setTitle("Analoge Ausgabe AA1");
view->setMessage("\nAusgabe 10-Bit-Wert (0...1023): ");
view->setCancel("[ Zurueck ]", true);
view->setConfirm("[ OK ]", &write_analog_output1);
view->repaint();
win_stack.push_back(view);
input(0);
}
void start_selftest(int)
{
B15F& drv = B15F::getInstance();
drv.activateSelfTestMode();
ViewInfo* view = new ViewInfo();
view->setTitle("Selbsttest aktiv");
view->setText("Das B15 befindet sich jetzt im Selbsttestmodus.\n \nSelbsttest:\nZu Beginn geht der Reihe nach jede LED von BA0 bis BA1 an.\nDanach leuchten die LEDs an AA0 und AA1 kurz auf.\nZum Schluss spiegelt in einer Endlosschleife:\n* BA0 Port BE0\n* BA1 die DIP-Schalter S7\n* AA0 ADC0\n* AA1 ADC1");
view->setLabelClose("[ Selbsttest Beenden ]");
view->setCall(&stop_selftest);
view->repaint();
win_stack.push_back(view);
input(0);
}
void stop_selftest(int)
{
B15F& drv = B15F::getInstance();
drv.discard();
drv.delay_ms(B15F::WDT_TIMEOUT);
drv.reconnect();
drv.digitalWrite0(0);
drv.digitalWrite1(0);
}
void show_selftest_info(int)
{
ViewInfo* view = new ViewInfo();
view->setTitle("Selbsttest");
view->setText("Bitte entfernen Sie jetzt alle Draehte von den Anschlussklemmen und bestaetigen\nmit Enter.");
view->setLabelClose("[ Weiter ]");
view->setCall(&start_selftest);
view->repaint();
win_stack.push_back(view);
input(0);
}

38
control/src/ui/ui.h Normal file
View file

@ -0,0 +1,38 @@
#ifndef UI_H
#define UI_H
#include <vector>
#include "view_selection.h"
#include "view_info.h"
#include "view_monitor.h"
#include "view_promt.h"
void show_main(int);
void input(int);
void view_back(int);
void finish(int);
void cleanup();
void show_info(int);
void show_monitor(int);
void show_invalid_port_input(int);
void show_invalid_dac_input(int);
void write_digital_output0(int);
void write_digital_output1(int);
void write_analog_output0(int);
void write_analog_output1(int);
void show_digital_output0(int);
void show_digital_output1(int);
void show_analog_output0(int);
void show_analog_output1(int);
// selftest group
void show_selftest_info(int);
void start_selftest(int);
void stop_selftest(int);
extern std::vector<View*> win_stack;
extern std::thread t_refresh;
#endif // UI_H

78
control/src/ui/view.cpp Normal file
View file

@ -0,0 +1,78 @@
#include "view.h"
WINDOW* View::win = nullptr;
View::View()
{
if(!win)
{
B15F::abort("View::win not initialized, missing context");
}
getmaxyx(win, height, width); // init width and height
keypad(win, TRUE);
}
View::~View()
{
}
void View::setWinContext(WINDOW* win)
{
View::win = win;
}
WINDOW* View::getWinContext()
{
return win;
}
// from: https://stackoverflow.com/a/37454181
std::vector<std::string> View::str_split(const std::string& str, const std::string delim)
{
std::vector<std::string> tokens;
size_t prev = 0, pos = 0;
do
{
pos = str.find(delim, prev);
if (pos == std::string::npos) pos = str.length();
std::string token = str.substr(prev, pos-prev);
if (!token.empty()) tokens.push_back(token);
prev = pos + delim.length();
}
while (pos < str.length() && prev < str.length());
return tokens;
}
void View::setTitle(std::string title)
{
this->title = title;
}
void View::repaint()
{
// get screen size
struct winsize size;
if (ioctl(0, TIOCGWINSZ, (char *) &size) < 0)
throw std::runtime_error("TIOCGWINSZ error");
start_x = floor((size.ws_col - width) / 2.);
start_y = floor((size.ws_row - height) / 2.);
curs_set(0); // hide cursor
mvwin(win, start_y, start_x);
clear();
wclear(win);
// generic draw
box(win, 0, 0);
int offset_x = (width - title.length()) / 2;
mvwprintw(win, 1, offset_x, "%s", title.c_str());
// specific draw
draw();
refresh();
wrefresh(win);
}

45
control/src/ui/view.h Normal file
View file

@ -0,0 +1,45 @@
#ifndef VIEW_H
#define VIEW_H
#include <iostream>
#include <cmath>
#include <vector>
#include <functional>
#include <ncurses.h> // sudo apt-get install libncurses5-dev
#include <sys/ioctl.h>
#include <unistd.h>
#include <signal.h>
#include "../drv/b15f.h"
extern std::string ERR_MSG;
typedef std::function<void(int)> call_t;
class View
{
public:
View(void);
virtual ~View(void);
static void setWinContext(WINDOW* win);
static WINDOW* getWinContext(void);
static std::vector<std::string> str_split(const std::string& str, const std::string delim);
virtual void setTitle(std::string title);
virtual void repaint(void);
virtual void draw(void) = 0;
virtual call_t keypress(int& key) = 0;
protected:
int width, height;
int start_x = 0, start_y = 0;
std::string title;
std::vector<call_t> calls;
static WINDOW* win;
constexpr static int KEY_ENT = 10;
};
#endif // VIEW_H

View file

@ -0,0 +1,63 @@
#include "view_info.h"
ViewInfo::ViewInfo()
{
calls.push_back(nullptr);
}
void ViewInfo::setText(std::string text)
{
this->text = text;
}
void ViewInfo::setLabelClose(std::string label)
{
this->label_close = label;
}
void ViewInfo::setCall(call_t call)
{
calls[0] = call;
}
void ViewInfo::draw()
{
int li = 0;
for(std::string line : str_split(text, "\n"))
mvwprintw(win, text_offset_y + li++, text_offset_x, "%s", line.c_str());
close_offset_x = (width - label_close.length()) / 2;
close_offset_y = height - 2;
wattron(win, A_REVERSE);
mvwprintw(win, close_offset_y, close_offset_x, "%s", label_close.c_str());
wattroff(win, A_REVERSE);
}
call_t ViewInfo::keypress(int& key)
{
switch(key)
{
case KEY_MOUSE:
{
// http://pronix.linuxdelta.de/C/Linuxprogrammierung/Linuxsystemprogrammieren_C_Kurs_Kapitel10b.shtml
MEVENT event;
if(getmouse(&event) == OK && event.bstate & (BUTTON1_CLICKED | BUTTON1_DOUBLE_CLICKED))
{
size_t column = start_x + close_offset_x;
size_t row = start_y + close_offset_y;
size_t mouse_x = event.x, mouse_y = event.y;
if(mouse_y == row && mouse_x >= column && mouse_x < column + label_close.length())
key = -1; // do return from view
}
break;
}
case KEY_ENT:
key = -1; // do return from view
break;
default:
break;
}
return calls[0];
}

View file

@ -0,0 +1,25 @@
#ifndef VIEW_INFO
#define VIEW_INFO
#include "view.h"
class ViewInfo : public View
{
public:
ViewInfo(void);
virtual void setText(std::string text);
virtual void setLabelClose(std::string label);;
virtual void setCall(call_t call);
virtual void draw(void) override;
virtual call_t keypress(int& key) override;
protected:
std::string text;
std::string label_close;
int close_offset_x = 0;
int close_offset_y = 0;
constexpr static int text_offset_x = 2;
constexpr static int text_offset_y = 3;
};
#endif // VIEW_INFO

View file

@ -0,0 +1,139 @@
#include "view_monitor.h"
ViewMonitor::ViewMonitor() : t_worker(&ViewMonitor::worker, this)
{
}
call_t ViewMonitor::keypress(int& key)
{
switch(key)
{
case KEY_MOUSE:
{
// http://pronix.linuxdelta.de/C/Linuxprogrammierung/Linuxsystemprogrammieren_C_Kurs_Kapitel10b.shtml
MEVENT event;
bool hit = false;
if(getmouse(&event) == OK && event.bstate & (BUTTON1_CLICKED | BUTTON1_DOUBLE_CLICKED))
{
size_t column = start_x + close_offset_x;
size_t row = start_y + close_offset_y;
size_t mouse_x = event.x, mouse_y = event.y;
if(mouse_y == row && mouse_x >= column && mouse_x < column + label_close.length())
hit = true;
}
if(!hit)
break;
// fall through to next case
[[fallthrough]];
}
case KEY_ENT:
run_worker = false;
key = -1; // do return from view
wclear(win);
wrefresh(win);
t_worker.join();
break;
default:
break;
}
return calls[0];
}
std::string ViewMonitor::fancyDigitalString(uint8_t& b)
{
std::stringstream str;
str << std::bitset<8>(b).to_string();
str << " ";
str << "0x" << std::setfill ('0') << std::setw(2) << std::hex << (int) b << std::dec;
return str.str();
}
std::string ViewMonitor::fancyAnalogString(uint16_t& v)
{
std::stringstream str;
double volt = round(v * 100.0 * 5.0 / 1023.0) / 100.0;
str << std::setfill ('0') << std::setw(4) << (int) v << " " << std::fixed << std::setprecision(2) << volt << " V ";
str << "[";
uint8_t p = round(v * 40.0 / 1023.0);
for(uint8_t i = 0; i < p; i++)
str << "X";
for(uint8_t i = 0; i < 40 - p; i++)
str << " ";
str << "]" << std::endl;
return str.str();
}
void ViewMonitor::worker()
{
B15F& drv = B15F::getInstance();
while(run_worker)
{
try
{
std::this_thread::sleep_for(std::chrono::milliseconds(100));
uint8_t be0 = drv.digitalRead0();
uint8_t be1 = drv.digitalRead1();
uint8_t dsw = drv.readDipSwitch();
uint16_t adc[8];
for(uint8_t i = 0; i < sizeof(adc) / sizeof(adc[0]); i++)
adc[i] = drv.analogRead(i);
std::stringstream str;
// hline
for(uint8_t i = 0; i < width - 2 * text_offset_x; i++)
if(i % 2 == 0)
str << "-";
else
str << " ";
str << std::endl;
str << "Digitale Enigaenge:" << std::endl;
str << "Binaere Eingabe 0: " << fancyDigitalString(be0) << std::endl;
str << "Binaere Eingabe 1: " << fancyDigitalString(be1) << std::endl;
str << "Dip Schalter (S7): " << fancyDigitalString(dsw) << std::endl;
// hline
for(uint8_t i = 0; i < width - 2 * text_offset_x; i++)
if(i % 2 == 0)
str << "-";
else
str << " ";
str << std::endl;
str << "Analoge Eingaenge:" << std::endl;
for(uint8_t i = 0; i < sizeof(adc) / sizeof(adc[0]); i++)
{
str << "Kanal " << std::to_string((int) i) << ": ";
str << fancyAnalogString(adc[i]) << std::endl;
}
text = str.str();
repaint();
}
catch(DriverException& ex)
{
std::cout << "DriverException: " << ex.what() << std::endl;
drv.delay_ms(1000);
}
catch(...)
{
try
{
drv.reconnect();
}
catch(...)
{
B15F::abort("yoho meine dudes");
return;
}
}
}
}

View file

@ -0,0 +1,29 @@
#ifndef VIEW_MONITOR_H
#define VIEW_MONITOR_H
#include <thread>
#include <chrono>
#include <sstream>
#include <bitset>
#include "view_info.h"
#include "../drv/b15f.h"
class ViewMonitor : public ViewInfo
{
public:
ViewMonitor(void);
virtual call_t keypress(int& key) override;
private:
std::string fancyDigitalString(uint8_t& b);
std::string fancyAnalogString(uint16_t& v);
protected:
virtual void worker(void);
volatile bool run_worker = true;
std::thread t_worker;
};
#endif // VIEW_MONITOR_H

View file

@ -0,0 +1,121 @@
#include "view_promt.h"
void ViewPromt::draw()
{
curs_set(1); // show cursor
int li = text_offset_y;
int ci = 0;
for(std::string line : str_split(message + input, "\n"))
{
mvwprintw(win, ++li, text_offset_x, "%s", line.c_str());
ci = line.length() + text_offset_x;
}
button_offset_x = (width - label_cancel.length() - sep.length() - label_confirm.length()) / 2;
button_offset_y = height - text_offset_y;
if(selection == 0)
{
wattron(win, A_REVERSE);
mvwprintw(win, button_offset_y, button_offset_x, "%s", label_cancel.c_str());
wattroff(win, A_REVERSE);
mvwprintw(win, button_offset_y, button_offset_x + label_cancel.length(), "%s", sep.c_str());
mvwprintw(win, button_offset_y, button_offset_x + label_cancel.length() + sep.length(), "%s", label_confirm.c_str());
}
else
{
mvwprintw(win, button_offset_y, button_offset_x, "%s", label_cancel.c_str());
mvwprintw(win, button_offset_y, button_offset_x + label_cancel.length(), "%s", sep.c_str());
wattron(win, A_REVERSE);
mvwprintw(win, button_offset_y, button_offset_x + label_cancel.length() + sep.length(), "%s", label_confirm.c_str());
wattroff(win, A_REVERSE);
}
wmove(win, li, ci);
}
void ViewPromt::setMessage(std::string message)
{
this->message = message;
}
void ViewPromt::setConfirm(std::string name, std::function<void(int)> call)
{
label_confirm = name;
call_confirm = call;
}
void ViewPromt::setCancel(std::string name, bool cancelable)
{
label_cancel = name;
this->cancelable = cancelable;
}
std::string ViewPromt::getInput()
{
return input;
}
std::function<void(int)> ViewPromt::keypress(int& key)
{
std::function<void(int)> ret = nullptr;
switch(key)
{
case KEY_BACKSPACE:
if(input.length())
input.pop_back();
break;
case '\t':
case KEY_LEFT:
case KEY_RIGHT:
selection = (selection + 1 ) % 2;
break;
case KEY_MOUSE:
{
// http://pronix.linuxdelta.de/C/Linuxprogrammierung/Linuxsystemprogrammieren_C_Kurs_Kapitel10b.shtml
MEVENT event;
bool hit = false;
if(getmouse(&event) == OK && event.bstate & (BUTTON1_CLICKED | BUTTON1_DOUBLE_CLICKED))
{
size_t column_start = start_x + button_offset_x;
size_t row_start = start_y + button_offset_y;
size_t mouse_x = event.x, mouse_y = event.y;
if(mouse_y == row_start)
{
if(cancelable && mouse_x >= column_start && mouse_x < column_start + label_cancel.length())
{
if(selection == 0 || event.bstate & BUTTON1_DOUBLE_CLICKED)
hit = true;
selection = 0;
}
if(mouse_x >= column_start + label_cancel.length() + sep.length() && mouse_x < column_start + label_cancel.length() + sep.length() + label_confirm.length())
{
if(selection == 1 || event.bstate & BUTTON1_DOUBLE_CLICKED)
hit = true;
selection = 1;
}
}
}
if(!hit)
break;
// fall through to next case
[[fallthrough]];
}
case KEY_ENT:
if(selection == 0) // exit
key = -1; // do return from view
else
ret = call_confirm;
break;
default:
break;
}
if(key >= ' ' && key <= '~')
input += (char) key;
if(key != KEY_ENT)
repaint();
return ret;
}

View file

@ -0,0 +1,32 @@
#ifndef VIEW_PROMT_H
#define VIEW_PROMT_H
#include <vector>
#include <string>
#include "view.h"
class ViewPromt : public View
{
public:
virtual void draw(void) override;
virtual void setMessage(std::string message);
virtual void setConfirm(std::string name, call_t call);
virtual void setCancel(std::string name, bool cancelable);
virtual std::string getInput(void);
virtual call_t keypress(int& key) override;
protected:
size_t selection = 1;
std::string input;
std::string message = "Input";
std::string label_confirm = "[ OK ]";
std::string sep = " ";
std::string label_cancel = "[ Cancel ]";
call_t call_confirm = nullptr;
bool cancelable = true;
int button_offset_x = 0, button_offset_y = 0;
constexpr static int text_offset_x = 2;
constexpr static int text_offset_y = 2;
};
#endif // VIEW_PROMT_H

View file

@ -0,0 +1,76 @@
#include "view_selection.h"
void ViewSelection::draw()
{
//curs_set(0); // hide cursor
for(size_t i = 0; i < choices.size(); i++)
{
if(selection == i)
wattron(win, A_REVERSE);
mvwprintw(win, i + choice_offset_y, choice_offset_x, "%s", choices[i].c_str());
if(selection == i)
wattroff(win, A_REVERSE);
}
}
void ViewSelection::addChoice(std::string name, call_t call)
{
choices.push_back(name);
calls.push_back(call);
}
call_t ViewSelection::keypress(int& key)
{
call_t ret = nullptr;
switch(key)
{
case KEY_UP:
do
selection = (selection - 1 + choices.size()) % choices.size();
while(!choices[selection].length() && choices.size());
break;
case '\t':
case KEY_DOWN:
do
selection = (selection + 1) % choices.size();
while(!choices[selection].length() && choices.size());
break;
case KEY_MOUSE:
{
// http://pronix.linuxdelta.de/C/Linuxprogrammierung/Linuxsystemprogrammieren_C_Kurs_Kapitel10b.shtml
MEVENT event;
bool hit = false;
if(getmouse(&event) == OK && event.bstate & (BUTTON1_CLICKED | BUTTON1_DOUBLE_CLICKED))
{
size_t column_start = start_x + choice_offset_x;
size_t row_start = start_y + choice_offset_y;
size_t mouse_x = event.x, mouse_y = event.y;
for(size_t i = 0; i < choices.size(); i++)
if(choices[i].length() && mouse_y == row_start + i && mouse_x >= column_start && mouse_x < column_start + choices[i].length())
{
if(selection == i || event.bstate & BUTTON1_DOUBLE_CLICKED)
hit = true;
selection = i;
}
}
if(!hit)
break;
// fall through to next case
[[fallthrough]];
}
case KEY_ENT:
if(selection == choices.size() - 1) // exit
key = -1; // do return from view
else
ret = calls[selection];
break;
default:
break;
}
repaint();
return ret;
}

View file

@ -0,0 +1,24 @@
#ifndef VIEW_SELECTION_H
#define VIEW_SELECTION_H
#include <vector>
#include <string>
#include "view.h"
class ViewSelection : public View
{
public:
virtual void draw(void) override;
virtual void addChoice(std::string name, call_t call);
virtual call_t keypress(int& key) override;
protected:
size_t selection = 0;
std::vector<std::string> choices;
constexpr static int choice_offset_x = 2;
constexpr static int choice_offset_y = 3;
};
#endif // VIEW_SELECTION_H