Appropriate Class structure representing a hardware device - c++

I'm trying to code up an interface to a basic ECG device. I need the form to setup the device, send the 'record' message and save the ECG data that comes back into a file (as well as report a bit on the screen). The hardware device gets sent commands, and returns data via a serial interface.
My question is about the most appropriate class structures to set up.
Option 1:
MainWindow instantiates a
Hardware Device Object that reads the ECG info realtime, creates an 'ECG File class object' and handles it all internally to the Device object.
When recording is finished, MainWindow deletes the Device object and we're done.
Option 2:
MainWindow instantiates the
Hardware Device Object that receives a whole lot of data, maintains that data as a publically accessible data structure (member) then
MainWindow would then refer to that Device Object data structure, instantiate the ECG File class object itself and write it out to a file.
Ideally I'd like to write the data out in different formats (eg. classes that specify the format?)
Sorry if the question's not that clear, I guess I'm asking whether it's appropriate for a hardware device object to also manage all its own data, or pass it back for the main window to then process itself.
I've had a go at option 1, but it's getting ugly and I'm not sure whether I've mis-designed the thing from the start.
Any/all views appreciated!
Pete

Not knowing too much about the Domain, I have designed several systems that uses devices. I have also seem some design for devices. There are many ways to design this kind of stuff, but i like to write wrappers for all devices and use an open, close, read, and write interface.
So essentially, an abstract class is created called Device. Specific devices can be designed to extend this base class. Then a builder class is created to create and initialize the specific class. From this basic class a system can be built to handle it's out input and output. I tend to design to interfaces and keep classes as simple as possible.

Related

Trouble understanding OpenVR driver API

My end goal is to make a VRidge lightweight clone to understand the OpenVR API, but I'm struggling to understand how to get my code to display something. As a starting point, instead of my phone, I want to create a window as the HMD (SFML, SDL, you name it...) and having SteamVR rendering the VR view in it.
I understand that an object implementing IServerTrackedDeviceProvider is the handler of my driver's devices, ITrackedDeviceServerDriver is the interface of the device itself, and I suspect that my "HMD" device will have to implement IVRDisplayComponent.
Aside from setting some properties and having callbacks to activate and deactivate my device, I have no clue where to get an actual frame to display on the screen. What am I missing ?
You are almost right.
A class inheriting vr::IServerTrackedDeviceProvider(I'll call it the device parent later on) is responsible for registering and maintaining the lifetime of your devices(creating them, registering them, etc.)
Classes inheriting vr::ITrackedDeviceServerDriver after they have been registered by a device parent are considered a tracked device, device type is set by the device parent on register, also in case of the HMD device GetComponent() method needs to return display components if requested, for other devices it can just return NULL
GetComponent() receives a c string with a component name and version, for example "IVRDisplayComponent_002" stored in vr::IVRDisplayComponent_Version, and if the device has a component with a matching name version pair you need to return a pointer to it, if no match is found return NULL
Also about components, in the driver example that Valve provides its done in a very lazy and bad way, DO NOT INHERIT COMPONENTS TO YOUR DEVICE CLASSES
Segment your components into separate objects that you initialize in your device and return them in GetComponent() accordingly
Now, the only thing left for your devices to be properly identified and used by SteamVR is registering them, but there is a catch, you need to specify the device type when you register it by passing one of the values from vr::ETrackedDeviceClass enum(these should be pretty self explanatory when you look at the enum)
This is not all there is to openvr driver of course, for it all to work and for SteamVR to even acknowledge your driver's existence you need to implement an HmdDriverFactory() function, its similarly to GetComponent() except you compare the input c string to a provider name version pair and in case of a device parent its vr::IServerTrackedDeviceProvider_Version, if you get a match return a pointer to the instance of your device parent or any other provider you implemented
A few notes:
HMD needs at least one display component
HMD device is very sensitive to how you submit poses to it(dont ask why, it just is)
Be prepared for the lack of documentation, the best docs that you're gonna get are code comments in openvr_driver.h, ValveSoftware/openvr issue tracker and other people working with openvr drivers (even though there are only few...)
This is not the best explanation of how openvr drivers work, so you're always welcomed to ask for more details in the comments

Changing audio stream from physical input

I wondering about method to change voice from microphone on Windows on as low level as possible. So other applications will take changed voice on their inputs.
Some programs takes original stream, pipes it on virtual microphone, change here, and then forwards to an application.
I am looking for a method to affect on original audio stream. Looks like it is requires writing custom C++ audio driver for specific microphone. Is there any guideline for this? Maybe i can modify default driver for my purposes? Or maybe there is an easier method?
This sort of change is considered "Digital Signal Processing" or DSP, and in the Windows architecture that's the job of Audio Processing Objects or APO's.
Microsoft indeed provides a base class, CBaseAudioProcessingObject. And there's even a "swap" sample which swaps the right and left channels.

Protecting QML source code from plagiarism

The goal is to come up with a way to protect your QML code from plagiarism. It is a problem, since the way QML was designed and implemented seems to be inexplicably unprotected in this regard. The only QML types which are somewhat protected are those implemented entirely in C++.
Qt resource files don't support any degree of protection
even if you compress the resource file, extracting data from it is still fairly trivial to anyone with moderate experience
QML files stored on the file system are practically there for the taking
the same applies to any remote QML files, aside from adding dependency on internet connection, it is easy to sniff on the network access and get the QML files through their urls
QML doesn't provide seem to provide any public API to allow users enough control over QML type resolution to protect their code
All in all, it almost looks like Qt deliberately skimps on QML code protection, one obvious candidate reason would be to force people into buying the insanely expressive commercial license, which features the QML compiler.
So absent any stock method of protecting QML sources, the only solution that currently comes to my mind is control over how QML types are resolved. There are several ways of registering types to QML:
register in the application executable
register in a plugin
register via a QML module
However, what I need is to manually resolve QML types, much like you can create a custom QQuickImageProvider which inputs a URL string and outputs an image, I need the QML engine to request a string with the type to my custom component provider which outputs a ready for object instantiation component.
This would be easy if any custom instantiation mechanism is used, but I need those types to be usable in regular QML sources. Ideally this should be the first mechanism used to resolve the type, before looking in the available import paths or even internally registered types.
Alternatively, it would be just as useful if there is a way to define a QML module entirely in C++, without any external QML files, without a qmldir file and so on.
As a last resort, and falling short from ideally, I would also settle for registering QML (not C++) types to the runtime, this could also be useful, but I'd prefer to have full control over the resolving process.
A QML plugin does not do the trick, as it registers C++ types, and I want to register QML types, that is, QQmlComponents created from string sources and referencing each other.
The (ideal) Solution: Precompile it
The Qt Quick Compiler is a development add-on for Qt Quick applications which allows you to compile QML source code into the final binary. As it's description says, it will help on preventing plagiarism and it will also enhance your application launch times and provide other benefits.
This is as close as you can get to protecting your QML source code, even when it's not yet fully optimized
Update
As of Qt 5.11 the solution is in place and getting better fast.
Update (2)
Seems the QML compiler is already opensource from 5.11 I can't tell about tooling but Lars Knoll explains it on the blog post.
Option A) use qtquick compiler
Option B) use encrypted resources:
compile resources into separated file:
rcc -binary your_resource.qrc -o extresources.rcc
encrypt extresources.rcc to extresources.rcc.cr (for example with gnupg)
create a new resource file APP.rcc, only with extresources.rcc.cr file
on startup, load ":/extresources.rcc.cr" and decrypt them into buffer (you need a cryptographic library like Libgcrypt ...hide private key for decompilers and debuggers etc)
Q_CLEANUP_RESOURCE(APP); (optional, clear APP.rcc for saving memory)
Resource::registerResource((unsigned char *) myBuffer.constData()))
//now, you have available decrypted resources...for example
engine.load(QUrl("qrc:/main.qml"))
Real implementation is not trivial, but works very good...
Actually, you can register QML types in C++. The function qmlRegisterType has an overlapped form which accepts a QUrl denoting to a qml file in qrc:
qmlRegisterType(QUrl("qrc:/YourQMLModule.qml"), "YourModule", 1, 0, "YourQMLModule");
It just looks like you register a normal C++ class. It is commonly used in Qt's official sources, though be missing on the documentation.
After some digging around I found two directions that might be worth pursuing:
using a custom QQmlAbstractUrlInterceptor for the QML engine, that resolves QML types and returs a QUrl, in the case of "protected" types, the interceptor can prepend a custom scheme. The using a custom QNetworkAccessManager to intercept that url, calls the default implementation for unprotected types and for protected types decrypts the data and returns it in a QNetworkReply.
another, simpler but less flexible solution involves only the second part of the previous solution, and the qmlRegisterType(const QUrl &url, ...) function to expose as QML types, avoiding the usage of the interceptor.
I will post updates as I investigate those two. Note that this is not 100% secure either, as the network reply with the decrypted code itself will at least temporarily stay in RAM, so given enough competence it would still be possible to get to the code, however it is not as trivial as taking it directly from the application binary. A possible direction to go even further would be to resort to a custom QNetworkReply which doesn't contain the decrypted data, but overloads the QIODevice part to act as an accessor to the encrypted data that decrypts it along the way while reading it.

How could components communicate effectively with each other?

I'm designing a component-based system and everything works well, but a critical feature is missing and that is to be able to obtain a type of component from within a class of type Object, whereof this class can be added/removed components. In the Object class there exists a vector of components thus:
vector<Component*> pComponents;
And in the Component class, a Component has to have a name. So, a component such as Drawable would be called like so:
pPlayer->addComponent(new Drawable("Drawable"));
And that's all that's required for the player to be drawable. Now this is the problem: when it comes to adding loads of components that rely on other components, is there a settlement in how components communicate with one another?
Currently, in my Game class (which is not of type Object, although I might have it derive from Object albeit not sure if that's a good design decision) I have this code in the update function:
void Game::update()
{
pPlayer->update(0);
pSpriteLoader->getSprite()->move(pPlayer->getVelocity());
}
I'm using SFML2 solely because it's easy to use for the 2D graphics. The player update function calls the components' respective update functions. And the sprite loader is also a component and it is in charge of handling the loading of sprites through textures/images that can be read from file or memory. If I were to omit this line of code then the sprite would not be able to appear moving on the screen. As you can see, it's odd that pPlayer has a getVelocity() function and it's because I haven't moved all the physics stuff into its own component. What is dreading is that once I have moved the physics stuff out of the Player class into a Physical component class, how can I get these components to communicate with each other without having to resort to the lines of code ascribed above?
My solution is to create a component manager which registers each component and any component that requires another component will have to consult with this component manager without having to do so directly. Would this be a viable solution, and how can I proceed with the logic of such a component manager then?
Well, I suppose you would start by designing a messaging system.
It appears that you want to heavily decouple code and create components as much as possible. This is fine, I suppose, but the answer to having dependencies without coupling is probably something among the lines of message passing.
Say you need an Achievement system. This is a perfect example of a system that needs to stick its hand into as many nooks and crannies as possible in order to allow for the greatest flexibility in designing achievements. But how would you be able to stick your hand into, say, the Physics, AI, and Input system all at the same time and not write spaghetti code? The answer would be to put listeners on event queues and then run them by certain criteria based on the contents of the messages.
So for each component, you might want to inherit a common message sending/receiving component, possibly with generics, in order to send data messages. For example, say you shoot a laser in a FPS game. The laser will most likely make a sound, and the laser will most likely need an animation. You will probably want to send a message to the sound system to play a certain sound, and then send a message to the physics system or such to simulate the effects of the laser.
If you're interested, I have a really, really crude library for modeling a event system based on queues, listeners, and generic messages here: https://github.com/VermillionAzure/Flexiglass You might get some insight from fellow newbie code.
I really suggest taking a look at Boost.Signals2 or Boost.Asio as well. Knowledge of signals/networking can often help when designing communication systems, even if the system is just between game components.
I've recently been working on an entity-component system in SFML and came across the same problem.
Instead of creating some sort of messaging system that allows components to communicate with each other I ended up adding 'System' objects to the mix instead. This is another popular method that is often used when implementing component systems and it's the most flexible one that I've used so far.
Entities are nothing more than collections of components
Components are POD structs and have no methods (e.g. a PositionComponent would have nothing more than X and Y values)
Systems update any entities that have the required components
For example, my 'MovementSystem' iterates through each of my entities and checks if they have a VelocityComponent and an InputComponent. If it does, it changes the velocity of the current entity according to the current key being pressed.
This removes the issue with components communicating with each other because now all you need to do is access/modify the data stored in the current entity's components.
There are a few different ways that you can work out whether or not the current entity has the required components - I'm using bitmasks. If you decide to do the same, I highly suggest you take a look at this post for a more thorough explanation of the method: https://gamedev.stackexchange.com/questions/31473/role-of-systems-in-entity-systems-architecture

How to synchronize the same object on client and server side in client-server application? Is small messages framework good for this job?

I'm making a game engine in c++ and python. I'm using OGRE for 3D rendering, OpenAL for sound, ODE for physics, OIS for input, HawkNL for networking and boost.python for embedded python interpreter. Every subsystem (library) is wrapped by a class - manager and every manager is singleton. Now, I have a class - Object - this could be every visible object in game world. This is some kind of mix, object has graphics representation (entity) and representation in physics simulator (solid). These two are most important here. Class Object is just pure abstract base class - interface. I've decided to implement Object on client side as ObjectClientSide - this implementation has the entity, and on server side as ObjectServerSide - this implementation has the solid. Physics simulator runs only on server, and rendering is done only on client of course. The object can exist only when both implementations are working together. Every object has unique id and both instances of the same object on client and server side have the same id.
So, after this short background, my first question is: is this design good? How can I make it better? And the main question: how should I synchronize these objects?
Next, both implementations have the same interface, but part of it is implemented on server side and part on client side. So, for example, if player wants to move forward his character he should send a request to object on server. The server then makes changes to simulation and sends updated position to client. For that reason, I've created small messages framework. There is a Message class, Router, Rule and rules inherited from Rule. When message arrives, Router checks it against the rules and sends it to destination. So, when I call myObjectInstanceOnClientSide->setPosition(x,y,z) this object creates Message, its content is function and parameters and destination is object with the same id on server. When object with the same id on server side gets this message it calls this function with given arguments. So, when a function can't be implemented on one side it creates a message and sends it to object on the other side. I think this can be very useful in scripts. Scripts can be very clean, if script needs for example turn on animation on clients, I only need to call this function on server's local object - the rest is in background.
So, is this ok? Am I wrong about this? It this common solution?
It sounds like you would be sending a lot of tiny messages. The UDP and IP headers will add 28 bytes of overhead (20 bytes for the IPv4 header or 40 for IPv6 plus 8 bytes for the UDP header). So, I would suggest combining multiple messages to be dispatched together at a perioidic rate.
You may also want to read these other questions and answers:
Dealing with Latency in Networked Games
Real-time multiplayer game (concept question)
I added a bunch of useful links to the DevMaster.net Wiki years ago that are still relavent:
Networking for Games 101 FAQ
Multiplayer and Network Programming
Introduction to Multiplayer Game
Programming The Quake3 Networking Model
Unreal Networking Architecture
Networked Physics
Beej's Network Guide
I'd suggest starting to read Glenn Fiedler's blog. He's done some incredibly work with networked physics including the recent Mercenaries 2 release. He started a series of articles called Networking for Game Programmers.