Is there easy way to do macro to string map? - sockets

For example,in Windows,if I want to make the error message of gethostbyname meaningful,I would need to manually map the error code to message, as follows,
#include <stdio.h>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
int
main(void)
{
struct hostent *host;
WSAData wsaData;
int errcode;
if (WSAStartup(MAKEWORD(2, 2), &wsaData)) {
perror("WSAStartup failed");
exit(-1);
}
host = gethostbyname("www.google.com");
if (host != NULL) {
printf("the offical name of the host is: %s\n", host->h_name);
} else {
errcode = WSAGetLastError();
printf("the error code is %d\n", errcode);
if (errcode == WSAENETDOWN)
perror("network down");
else if (errcode == WSANOTINITIALISED)
perror("call WSAStartup before");
else if ...
perror("gethostbyname failed");
return -1;
}
return 0;
}
Is there easy way to do this?
thanks.

I think you codes is in the easy way already, check the error code and return the error message. If you just want to make your codes more elegant, you could use an array of custom struct like below.
struct ErrorInfo
{
int Code;
const char* Message;
};
ErrorInfo* errorMap =
{
{ WSAENETDOWN, "network down" },
{ WSANOTINITIALISED, "call WSAStartup before" },
};
const char* GetErrorMessage(int errorCode)
{
for(int i=0; i<sizeof(errorMap)/sizeof(ErrorInfo)); i++)
{
if(errorMap[i].Code == errorCode)
return errorMap[i].Message;
}
return "";
}

Related

ESP8266 is reset while overwriting the existing database

If the test program is started by deleting (resetting) the database file each time it is run, the procedures are working.
/*
This creates two empty databases, populates values, and retrieves them back
from the SPIFFS file system.
*/
#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h>
#include <vfs.h>
#include <SPI.h>
#include <FS.h>
extern "C" {
#include "user_interface.h"
}
#include <ESP8266WiFi.h>
sqlite3* db1;
void WiFiOff() {
wifi_station_disconnect();
wifi_set_opmode(NULL_MODE);
wifi_set_sleep_type(MODEM_SLEEP_T);
wifi_fpm_open();
wifi_fpm_do_sleep(0xFFFFFFF);
}
const char* data = "Callback function called";
static int callback(void* data, int argc, char** argv, char** azColName) {
int i;
Serial.printf("%s: ", (const char*)data);
for (i = 0; i < argc; i++) {
Serial.printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
}
Serial.printf("\n");
return 0;
}
int db_open(const char* filename, sqlite3** db) {
int rc = sqlite3_open(filename, db);
if (rc) {
Serial.printf("Can't open database: %s\n", sqlite3_errmsg(*db));
return rc;
}
else {
Serial.printf("Opened database successfully\n");
}
return rc;
}
char* zErrMsg = 0;
int db_exec(sqlite3* db, const char* sql) {
Serial.println(sql);
long start = micros();
int rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg);
if (rc != SQLITE_OK) {
Serial.printf("SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
}
else {
Serial.printf("Operation done successfully\n");
}
Serial.print(F("Time taken:"));
Serial.println(micros() - start);
return rc;
}
void OpenDatabase();
void CreateTable();
void InsertValues();
void SelectValues();
void setup() {
Serial.begin(74880);
system_update_cpu_freq(SYS_CPU_160MHZ);
WiFiOff();
if (!SPIFFS.begin()) {
Serial.println("Failed to mount file system");
return;
}
// list SPIFFS contents
Dir dir = SPIFFS.openDir("/");
while (dir.next()) {
String fileName = dir.fileName();
size_t fileSize = dir.fileSize();
Serial.printf("FS File: %s, size: %ld\n", fileName.c_str(), (long)fileSize);
}
Serial.printf("\n");
// remove existing file
SPIFFS.remove("/test1.db");
sqlite3_initialize();
OpenDatabase();
CreateTable();
InsertValues();
SelectValues(); */
// list SPIFFS contents
dir = SPIFFS.openDir("/");
while (dir.next()) {
String fileName = dir.fileName();
size_t fileSize = dir.fileSize();
Serial.printf("FS File: %s, size: %ld\n", fileName.c_str(), (long)fileSize);
}
Serial.printf("\n");
}
void loop() {
}
void OpenDatabase() {
int rc;
// Open databases
File db_file_obj_1;
vfs_set_spiffs_file_obj(&db_file_obj_1);
if (db_open("/test1.db", &db1)) return;
}
void CreateTable() {
int rc;
// Create Table
rc = db_exec(db1, "CREATE TABLE IF NOT EXISTS test1 (id INTEGER, content);");
if (rc != SQLITE_OK) {
sqlite3_close(db1);
return;
}
}
void InsertValues() {
int rc;
// Insert Values
rc = db_exec(db1, "INSERT INTO test1 VALUES (1, 'Hello, Hurol from test1');");
if (rc != SQLITE_OK) {
sqlite3_close(db1);
return;
}
}
void SelectValues() {
int rc;
// Select Values
rc = db_exec(db1, "SELECT * FROM test1");
if (rc != SQLITE_OK) {
sqlite3_close(db1);
return;
}
}
}
deleting the existing database file ...
// remove existing file
SPIFFS.remove("/test1.db");
But when the INSERT or SELECT procedure is executed on the table created without deleting the existing database, ESP8266 is reset.
// remove existing file
// SPIFFS.remove("/test1.db");
(If deletion of the existing database file is canceled)
How can I get the best document about the reset problem when using ESP8266 and SQLite?
Can you please help in this matter? Thank you from now.
It looks like it has improved. Thank you very much.
hw_wdt_disable();
void hw_wdt_disable() {
((volatile uint32_t)0x60000900) &= ~(1); // Hardware WDT OFF
}

C++ class member variable resetting to 0

I'm trying to increment and decrement the index of a list of readings, however, everytime I run update(), m_notifIndex gets set back to zero. I'm sorry if this type of question has been asked before, but after looking for the answer for an hour, I gave up and went on to ask my first question here. Sorry for the bad formatting too, again, this is my first time posting.
Display.cpp
#include "display.h"
#include <time.h>
#include <unistd.h>
#include <iostream>
Display::Display(unsigned int width, unsigned int height, unsigned int num_sensors, std::string* sensors, const std::string& dir, Message* messages) {
m_notifIndex = 0;
}
void Display::update() {
if (m_showNotif) {
//when there are no more messages, show the notifications
while (!m_notifications->isEmpty()) {
//first draw the notification if there is a warning in the current index
if (m_notifications->sensors[m_notifIndex] != NULL) {
m_oled->clear(PAGE);
drawSensor();
m_oled->display();
sleep(1);
//keep updating the message and notif stack when there are no inputs
while (m_a->pinRead() == HIGH && m_right->pinRead() == HIGH && m_left->pinRead() == HIGH && m_b->pinRead() == HIGH) {
m_messages->updateMsgStack();
updateNotif();
if (!m_messages->isEmpty() || m_notifications->warnings[m_notifIndex])
return; //break away from the loop if a new message comes in
}
//listen in for inputs
if (m_right->pinRead() == LOW) {
//wait until the button is released
while (m_right->pinRead() == LOW) {}
if (m_notifIndex == m_num_sensors-1)
m_notifIndex = 0; //wrap around when at the end
else m_notifIndex++;
}
else if (m_left->pinRead() == LOW) {
while (m_left->pinRead() == LOW) {}
if (m_notifIndex == 0)
m_notifIndex = m_num_sensors-1; //wrap around when at the beginning
else m_notifIndex--;
}
else if (m_a->pinRead() == LOW) {
while (m_a->pinRead() == LOW) {}
m_showNotif = false;
return;
}
checkForPanic();
}
else { //when the current index has no warning
if (m_notifIndex == m_num_sensors-1)
m_notifIndex = 0; //wrap around when at the end
else m_notifIndex++;
}
}
}
}
void Display::updateNotif() {
std::string line;
for (unsigned int i = 0; i < sizeof(m_sensors)/sizeof(m_sensors[0]); i++) {
const char* filePath = (m_notifDir + m_sensors[i] + ".txt").c_str();
if (m_messages->exists(filePath)) {
usleep(10000);
try {
m_messages->m_incMsg.open(filePath);
while(std::getline(m_messages->m_incMsg, line)) {
m_notifications->addWarning (line, i);
}
m_messages->m_incMsg.close();
}
catch (std::ios_base::failure& e) {
std::cerr << e.what() << '\n' << std::endl;
}
}
else m_notifications->removeWarning (i); //delete the warning when the file doesnt exist
}
}
void Display::checkForPanic() {
if (m_b->pinRead() == LOW) {
time_t hold;
time(&hold);
while (m_b->pinRead() == LOW) {
if (time(NULL) > hold + 3) { //if the timer reaches 3 seconds
//m_messages->sendReply("Miner_Emergency");
return;
}
}
}
}
Display.h
#ifndef OLED_DISPLAY_H_
#define OLED_DISPLAY_H_
#include <sstream>
#include <string>
#include "image/image.h"
#include "oled/Edison_OLED.h"
#include "message.h"
#include "DataStructs/Notif.h"
#include "gpio/gpio.h"
#define SLEEPTIMEOUT 20
class Display {
public:
Display(unsigned int width, unsigned int height, unsigned int num_sensors, std::string* sensors, const std::string& dir, Message* messages);
void run();
~Display();
private:
edOLED* m_oled;
const unsigned int m_height, m_width;
Image* m_miner;
Image* m_checkin;
Image* m_reminder;
Image* m_blast;
Image* m_go_to;
Image* m_goto_zone;
bool m_isSleeping, m_showNotif;
time_t m_timer;
Message* m_messages;
std::string* m_sensors;
std::string m_notifDir;
NotifHandler* m_notifications;
unsigned int m_notifIndex;
const unsigned int m_num_sensors;
gpio* m_up;
gpio* m_down;
gpio* m_left;
gpio* m_right;
gpio* m_a;
gpio* m_b;
void drawImage(Image* image);
void update();
void drawMessage(MsgNode* message);
void drawTime();
void drawSensor();
void updateNotif();
void checkForPanic();
};
#endif //OLED_DISPLAY_H_

Error in use of the pcap_findalldevs_ex Function in c++

Below this program to retrieve the list of adapters and print it on the screen :
#include <stdio.h>
#include <pcap.h>
int main()
{
pcap_if_t *alldevs;
pcap_if_t *d;
int i=0;
char errbuf[PCAP_ERRBUF_SIZE];
if (pcap_findalldevs_ex(PCAP_SRC_IF_STRING, NULL, &alldevs, errbuf) == -1)
{
fprintf(stderr,"Error in pcap_findalldevs_ex: %s/n", errbuf);
exit(1);
}
for(d= alldevs; d != NULL; d= d->next)
{
printf("%d. %s", ++i, d->name);
if (d->description)
printf(" (%s)/n", d->description);
else
printf(" (No description available)/n");
}
if (i == 0)
{
printf("/nNo interfaces found! Make sure WinPcap is installed./n");
return 0;
}
pcap_freealldevs(alldevs);
}
It is compile But Give an Error :
Every body have These Errors, while using pcap.h, go to bellow link and download pcap, after it Install it :
http://www.winpcap.org/install/default.htm

How can I compile HAL examples on Neatbeans?

I am trying to compile a HAL API example on Netbeans. Netbeans shows warning and error about some header files. But I am able to compile my sample codes using following command line:
gcc `pkg-config --libs --cflags dbus-1 hal hal-storage dbus-glib-1 glib-2.0` main.c HalDemos.c HalDemos.h -o HalDemos -lpthread
How can apply this command to my Netbeans project?
Here the codes which I am trying to compile:
/*
* File: HallDemos.h
* Author: olcay
*
* Created on December 25, 2011, 5:05 AM
*/
#ifndef HALLDEMOS_H
#define HALLDEMOS_H
#ifdef __cplusplus
extern "C" {
#endif
#include <hal/libhal.h>
#include <hal/libhal-storage.h>
#include <dbus/dbus.h>
#include <glib-1.2/glib.h>
//#include <dbus/dbus-glib-lowlevel.h>
#define HAL_DBUS_SERVICE "org.freedesktop.Hal"
#define HAL_ROOT_COMPUTER "/org/freedesktop/Hal/devices/computer"
#define HAL_DBUS_INTERFACE_POWER "org.freedesktop.Hal.Device.SystemPowerManagement"
static void handle_device_removed(LibHalContext *ctx, const char *udi);
static void handle_device_added(LibHalContext *ctx, const char *udi);
DBusConnection *connection;
DBusError error;
DBusMessage *mess;
DBusMessage *reply;
LibHalContext *ctx;
LibHalDrive *drive;
LibHalVolume *volume;
const char *udi;
int exit_code;
int initHal();
int getSystemInfo();
int getDeviceWithCapability(const char *capability);
void callbackLoop();
void listDeviceContent();
#ifdef __cplusplus
}
#endif
#endif /* HALLDEMOS_H */
#include "HalDemos.h"
#include <stdio.h>
static void handle_device_removed(LibHalContext *ctx, const char *udi) {
printf("Device with udi=%s is removed\n", udi);
}
static void handle_device_added(LibHalContext *ctx, const char *udi) {
dbus_bool_t is_storage;
is_storage = libhal_device_query_capability(ctx, udi, "storage", NULL);
if (is_storage) {
drive = libhal_drive_from_udi(ctx, udi);
volume = libhal_volume_from_udi(ctx, udi);
if (libhal_drive_is_hotpluggable(drive) || libhal_drive_uses_removable_media(drive)) {
printf("Storage device added %s model %s\n",
libhal_drive_get_device_file(drive),
libhal_drive_get_model(drive));
//printf("Mount point = %s\n", libhal_volume_get_mount_point(volume));
}
libhal_drive_free(drive);
}
//printf("Device with udi=%s is added\n", udi);
}
int initHal() {
udi = "/org/freedesktop/Hal/devices/computer";
dbus_error_init(&error);
connection = dbus_bus_get(DBUS_BUS_SYSTEM, &error);
if (dbus_error_is_set(&error)) {
printf("Unable to connect to Dbus: %s\n", error.message);
dbus_error_free(&error);
return 1;
}
ctx = libhal_ctx_new();
if (!libhal_ctx_set_dbus_connection(ctx, connection)) {
printf("Error: %s\n", error.message);
dbus_error_free(&error);
return 1;
}
if (!libhal_ctx_init(ctx, &error)) {
printf("Hal context initializing failure %s\n", error.message);
return 1;
}
}
int getSystemInfo() {
char *kernel_version = libhal_device_get_property_string(ctx, udi, "system.kernel.version", &error);
if (dbus_error_is_set(&error)) {
printf("Error getting string property %s\n", error.message);
dbus_error_free(&error);
return 1;
}
char *power_management_type = libhal_device_get_property_string(ctx, udi, "power_management.type", &error);
if (dbus_error_is_set(&error)) {
printf("Error getting string property %s\n", error.message);
dbus_error_free(&error);
return 1;
}
dbus_bool_t can_hibernate = libhal_device_get_property_bool(ctx, udi, "power_management.can_hibernate", &error);
if (dbus_error_is_set(&error)) {
printf("Error getting bool property %s\n", error.message);
dbus_error_free(&error);
return 1;
}
printf("System information:\n");
printf("Kernel = %s\n", kernel_version);
printf("Power management type = %s\n", power_management_type);
printf("Hibernate = %s\n", can_hibernate ? "Supported" : "Not supported");
libhal_free_string(kernel_version);
libhal_free_string(power_management_type);
return 0;
}
int getDeviceWithCapability(const char* capability) {
int num_devices = 0;
char **udis = libhal_find_device_by_capability(ctx, capability, &num_devices, &error);
if (dbus_error_is_set(&error)) {
printf("Error getting bool property %s\n", error.message);
dbus_error_free(&error);
return 1;
}
if (num_devices == 0) {
printf("No device found with input capability!");
return 0;
}
int i;
printf("Devices with input capability:\n");
for (i = 0; udis[i]; i++) {
printf("%2d - udi = %s\n", i + 1, udis[i]);
/* Do something with it */
}
/* Free the string array */
libhal_free_string_array(udis);
}
void callbackLoop() {
GMainLoop *loop;
loop = (GMainLoop*) g_main_loop_new(NULL, FALSE);
dbus_connection_setup_with_g_main(connection, NULL);
libhal_ctx_set_device_added(ctx, handle_device_added);
libhal_ctx_set_device_removed(ctx, handle_device_removed);
g_main_loop_run(loop);
}
void listDeviceContent(){
}
UPDATE:
Writing the command I used with $$() and adding it to additional compiler settings solved my problem.
Go to your project properties -> Build -> C Compiler -> Additional Options
Put your compiler flags here between $$() like:
$$(pkg-config --libs --cflags dbus-1 hal hal-storage dbus-glib-1 glib-2.0)

Sending ATD command to a Fastrack Supreme via RS232 in LabWindows/CVI

I work on project based on a FASTRACK SUPREME which has to receive commands via a serial RS232. The
problem is:
When I use HyperTerm the command ATDxxxxxxxxx; works fine.
When I use the CVI RS232 library nothing happens. Is it possible that my command remains blocked in
the serial buffer?
Here is my code:
#include <ansi_c.h>
#include <cvirte.h>
#include <userint.h>
#include <rs232.h>
#include <utility.h>
#include <formatio.h>
#include <string.h>
int configurePort(void);
int sendCommand(void);
int port_open;
int error;
int main()
{
configurePort();
sendCommand ();
return 0;
}
int configurePort()
{
port_open = 0;
error = OpenComConfig (4, "COM4",115200 ,0,8,1,0, -1);
if (error)
{
printf("Error!\n");
}
if (error == 0)
{
port_open = 1;
SetXMode (4, 0);
SetCTSMode (4, 0);
SetComTime (4, 0);
}
return 0;
}
int sendCommand ()
{
char bufferWrite[100] ;
Fmt(bufferWrite,"%s","ATD0040761768027;");
ComWrt(4, bufferWrite, 18);
return 0;
}
Where is the problem? Please help!
Thanks.
I tried your code as it was. I am not sure what you mean by "nothing happens" When I used the code as it is (except I had to use port 2) everything worked well. the character count was 18 out of the ComWrt function.
Make sure the com port you are trying to use is available.
with the exception of your #includes, here is your code with minor mods that I ran on my PC, WinXP running CVI 2010:
#define PORT 2
#define PORTNAME "COM2"
int configurePort(void);
int sendCommand(void);
int port_open;
int error;
int main()
{
configurePort();
sendCommand ();
return 0;
}
int configurePort()
{
port_open = 0;
error = OpenComConfig (PORT, PORTNAME,115200 ,0,8,1,0, -1);
if (error)
{
printf("Error!\n");
}
if (error == 0)
{
port_open = 1;
SetXMode (PORT, 0);
SetCTSMode (PORT, 0);
SetComTime (PORT, 0);
}
return 0;
}
int sendCommand ()
{
char bufferWrite[100] ;
Fmt(bufferWrite,"%s","ATD0040761768027;");
error = ComWrt(PORT, bufferWrite, sizeof("ATD0040761768027;"));
return 0;
}