Typecasting struct to char* in C++ without a lot of fluff

Want to cast from a struct to a character string? Seen all those posts out there suggesting that reinterpret_cast will work, but is unsafe? Yeah, I tried it. Yeah, it's unsafe.

What about the ones saying you could just malloc()? Well, my own personal mantra says that direct memory manipulation is also rather unsafe if you don't count right or are not careful with stack memory and such. I have avoided malloc() like I have learned to avoid reinterpret_cast.

But just today I discovered a most elegant solution:

struct newStruct { //33 total bytes long
    int dw0;
    uint_16 s0, s1, s2, s3;
    float f0, f1, f2, f3;
    char b0;
    int i0;
};

void byteOperation(char *p) {
    // Treat input parameter "p" like a big character array and do things one byte at a time!!
}

newStruct v;
newStruct w[1];

byteOperation((char*)v); // Compiler error: Cannot cast from 'newStruct' to 'char *'
byteOperation((char*)w); // Will just work.




Embarcadero TThread Just Works

I've been annoyed for a large amount of time (years in fact) over some of our software we use and sell. In essence, what we have is a TCP GUI that communicates on a 250ms timer with a microcontroller that's serving up a two-way communications protocol over ModBus FC23 - we send commands either to write data to or read data from the unit.

The developer we had make the initial software for us decided to use Embarcadero's system timer object to control the 250ms polling. Not only that, but I had to put in an 8-second delay during socket initialization (via a TPing object) in the event that the unit was rebooted (we want to wait until the unit can finish booting before we say that it can't be found on the network). And I learned ALL of my Borland/Embarcadero, and even the majority of my C++ knowledge from this program and others I've patterned after it.

But both the timer and the timeout exist in the main method. So every time the TPing object waits for the unit's response, or every time the 250ms timer hung, the entire program would freeze. It's been very annoying to say the least.

The microcontroller library I use (Netburner uCOS) has a fairly straightforward way to set up "tasks," and particularly the MOD5282 has something called a periodic interrupt (PITR) which will run a very fast clock at some hardware-programmable rate that will set an IRQ interrupt flag (and hardware pin) every time it fires. These two things are really cool because not only do I have a very fast and very calibrated clock that I can run certain tasks on at a rapid rate, but I can do so within separate tasks which keep the entire program from freezing if set up correctly.

But it required a slight change in thinking. I cannot run intensive processing within the PITR (printf(), etc). I cannot use OSTimeDly(n) (essentially the Sleep() function of uCOS, which is also limited to 20ms minimum) within the PITR. And I cannot utilize critical sections or OSLock() for any more than a few essential operations at a time. Otherwise the watchdog timer of the microcontroller could hang and force it to reboot.

I also have to explicitly declare a task's stack memory on the Netburner and have to give each some priority to make sure that more important tasks continue to run properly.

Thing is, Netburner's documentation on Tasks is quite good once you know where to look.

Embarcadero's documentation is a bit more confusing.

Borland/Embarcadero uses something called the TThread class. I figured multithreading a GUI application would be simple - simply declare a "task," set it up to run by itself using numerous different parameters with timers and what-not. Not according to documentation.

According to documentation you have to set up an entirely separate TThread class and you have to Synchronize objects from the main form in order to change their values. And none of the example programs look very straightforward.

Of course, the only example program I have is some triple-sorting GUI with three threads other than the main one, each sorting a set of data with a different algorithm. Out of the box, it's really cool. You hit the button and watch the three bar graphs simultaneously sort themselves from high values to low values, some taking longer than others. A great example program.

But I don't do any sorting in my programs. All I WANT is to push a button in my GUI and have it attempt to connect to a remote unit for eight seconds without hanging. Meaning, if I know it's not there, I can simply push the disconnect button and cancel it. Or close the GUI completely because I realize I made some mistake in programming.

In short, MY need for multithreading exists on a much simpler level. I want to be able to interrupt something that would otherwise force me to wait, since it emulates the Sleep() function.

Then I figured it out. Threading is still my solution. Only getting it set up in the Embarcadero IDE is much much simpler than the scant documentation and example programs would lead you to believe.

Here's my example program:
1. Create a simple VCL form with a TLabel (or any other object that takes a String input and displays it).

2. Drop a TSpeedButton object, setting its GroupIndex to a positive integer (like 1) and setting its AllowAllUp property to true. Now we have a toggle switch.

3. Create a global bool variable and give it some name like "ThreadExecute."

4. Bind the OnClick event of the TSpeedButton to some function, namely its default "SpeedButton1Click(TObject *Sender)" and tell it to toggle the global boolean set in step 3 based on its Down boolean property:
void __fastcall TForm1::SpeedButton1Click(TObject *Sender) {
  // This ensures that the SpeedButton1->Down status is available globally for other things, such as the other thread.
  ThreadExecute = SpeedButton1->Down;
}

5. Now for the super simple part - File > New > Other > C++ Builder Files > Thread Object. This will create a new unit, a cpp and h file set with the same name that act like a single "unit" (hence the name) within the IDE. The class it automatically creates will be assigned to the TThread class type, just like the main form is assigned to the TForm class type. It will also create two default functions - a constructor for initializing internal variables or what-not when a TThread object of this class is created, and an Execute() function for when the thread is "started."

6. In the TThread::Execute() function, create some iterative process, like adding 1 to a number within an endless while loop:
int n = 0;

void __fastcall ThLooper::Execute() {
  // Note - A while(1) loop, particularly with a Sleep() delay at the end would most certainly freeze the main loop and make it unresponsive to any further user interaction.
  while (1) {
    // Only execute if Toggle button in the Main form is Down.
    if (ThreadExecute) {
      n++;
    }
    Sleep(250);  } // end while
}

7. In the main form, set up the TForm's constructor to initialize the Thread in its own object:
ThLooper *Thread1;
__fastcall TForm1::TForm1(TComponent *Owner) : TForm(Owner) {
  Thread1 = new ThLooper(true); // Note - the CreateSuspended parameter creates the Thread object without starting it automatically.
  Thread1->Start(); // Can also use Resume(). This is needed if the Thread was created with CreateSuspended == true.
}
8. We now will probably need to display the value of n in the main form. However note the comment in the Thread class file - "Methods and properties of objects in VCL can only be used in a method called using Synchronize." This means you must use the Synchronize() function in order to access Form1 objects like the Label we want to update the caption of:
int n = 0;
// Should declare this first. Can be done in the thread header file.
void __fastcall ThLooper::UpdateLabel(void);


void __fastcall ThLooper::Execute() {
  while (1) {
    if (ThreadExecute) {
      n++; // Note - we made this global to access it from a synchronize method call.
      Synchronize(&UpdateLabel);
    }
    Sleep(250);
  } // end while
}

void __fastcall ThLooper::UpdateLabel() {
  Form1->Label1->Caption = (String)"N=" + n;

}

And that's it! That's all I needed to do to set up a thread that runs a constant process that would normally freeze the program outright. I can start the timer, or stop it using the toggle button, but the endless while loop will not freeze any portion of the main thread.

Looking at the documentation, there are also properties for setting a thread's priority to low or high, set it to destroy itself on an exception, and numerous other things.

And my knowledge of Netburner tasks simply verifies what I already know when Embarcadero highlights the following things to be aware of:
1. Too many threads consumes CPU time - limit yourself to 16 threads per CPU processor.
2. If multiple threads access the same resources, they must be synchronized to avoid conflict.
3. Updates to the form must be limited to the main thread. Updating a form element from within a thread should be done via thread synchronization such as TMultiReadExclusiveWriteSynchronizer.

This subject is not as complex as I had first believed!

Official Documentation:

Example.h:

#ifndef ExampleH
#define ExampleH

#include
#include
#include
#include
#include

class TForm1 : public TForm {
__published:    // IDE-managed Components
    TLabel *Label1;
    TSpeedButton *SpeedButton1;
    void __fastcall SpeedButton1Click(TObject *Sender);
    void __fastcall FormShow(TObject *Sender);
private:    // User declarations
public:        // User declarations
    __fastcall TForm1(TComponent* Owner);
};

extern PACKAGE TForm1 *Form1;

#endif


Example.cpp:

#include
#pragma hdrstop

#include "Example.h"
#include "ThLooper.h"

#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
ThLooper *Looper;

__fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner) {
    Looper = new ThLooper(true); // Initially suspended. We don't want to risk updating VCL components before they are completely created.
}

void __fastcall TForm1::FormShow(TObject *Sender) {
    Looper->Start(); // VCL Form has been fully created. Can now start Looper thread.
}

void __fastcall TForm1::SpeedButton1Click(TObject *Sender) {
    Label1->Caption = (SpeedButton1->Down)?"Running":"Halted";
    Looper->Go = SpeedButton1->Down;
}



ThLooper.h:

#ifndef ThLooperH
#define ThLooperH
#include

class ThLooper : public TThread {
private:
  void __fastcall UpdateLabel(void);
  void __fastcall AnimateStatus(void);
protected:
  void __fastcall Execute();
public:
  __fastcall ThLooper(bool CreateSuspended);
  bool Go;
};

#endif


ThLooper.cpp:

#include
#pragma hdrstop

#include "Example.h" // To update VCL form elements.
#include "ThLooper.h"
#pragma package(smart_init)

// AnimateStatus is a quick little text-based progress bar I made.
char ConnAniCtr = 0;
char ConnAniMax = 4;
char ConnAniDelay = 2;
char ConnAniDelayCtr = 0;
String ConnAni = "";
short N = 0;
void __fastcall ThLooper::AnimateStatus() {
  if (ConnAniDelayCtr < ConnAniDelay)
    ConnAniDelayCtr++;
  else {
    ConnAniDelayCtr = 0;
    if (ConnAniCtr >= ConnAniMax)
      ConnAniCtr = 0;
    else
      ConnAniCtr++;
  } // if

  ConnAni = StringOfChar('.',ConnAniCtr);
  Synchronize(&UpdateLabel); // Synchronously update VCL Form Label.
}

__fastcall ThLooper::ThLooper(bool CreateSuspended) : TThread(CreateSuspended) {
    Go = false; // Do not run initially.
}

void __fastcall ThLooper::Execute() {
  while (1) {
    if (Go) {
        AnimateStatus();
        N++;
    }
    Sleep(250); // Can comment this to see max speed of thread. Synchronize does not significantly pause thread execution.
  }
}

void __fastcall ThLooper::UpdateLabel() {
  Form1->Label1->Caption = (String)"Running" + N + ConnAni;
}

PHP Access Control List

A quick little Access Control List (ACL) snippet I made for PHP/HTML. Enjoy!
<?php

$acl = array(
// Populate with IP/Subnet Mask pairs.
// Any zero bit in the subnet mask acts as a wildcard in the IP address check.
array("192.168.10.24","255.255.255.255"),
);

$acl_allow = false;
for ($i = 0; $i < count($acl); $i++) {
$ip2chk = (ip2long($acl[$i][0]) & ip2long($acl[$i][1]));

if ((ip2long($_SERVER['REMOTE_ADDR']) & $ip2chk) == $ip2chk) {
$acl_allow=true;
}
}

if ($acl_allow) {
// Put all test stuff here!! Only visible to ACL.
phpInfo();
} else {
echo "<a href='http://this-page-intentionally-left-blank.org/whythat.html' target='_blank'>This page intentionally left blank.</a>";
}

?>

Linux - find what is preventing you from unmounting a drive

Disclaimer: I've had this problem for probably four months, ever since I started running Plex Media Server on my headless linux machine at home, whilst storing all my actual media on a nice external portable drive. Usually I just yank it, but then I watch the drive letters run themselves up obscenely high before I need to reboot.
So you've gone through the process of mounting your drive in Linux:
> sudo fdisk -l
Device Boot = /dev/sdb1 (and a bunch of other technical information regarding drive size, id, and such)
>

> sudo mount -t ntfs-3g /dev/sdb1 /media/TOSHIBA
>

You run a bunch of stuff, get it all working, then find you need to take the drive to work the next day, so you try to unmount it.

 > sudo umount /media/TOSHIBA
umount: /media/TOSHIBA: device is busy.
(In some cases useful info about processes that use the device is found by lsof(8) or fuser(1))
>

Well, being a Windows guy at heart, and not really understanding why everything here needs to be so technical, this message never told me ANYTHING. I would try typing just plain "lsof" or "lsof(8)" or "fuser(1)" with no useful results.

Then I asked a friend.

"lsof | grep <stuff>," he said.

"Like, <stuff> would be the /dev/sdb1?"

"Yeah."

So I tried it:
> sudo lsof | grep /dev/sdb1
mount.ntf     2096      root     3u     BLK    8,33 0x1d1ba997e00       2897182   /dev/sdb1

"Oh," he said. "Try the mount path. /dev/sdb1 is the device which is mounted somewhere else."

> sudo lsof | grep /media/TOSHIBA
>

"Nothing," I said. "Just a blank line."

"Looks like no program has any file open on it?"

"Let me try again."

bash     2068     daniel    cwd    DIR    8,33     8192    17459  /media/TOSHIBA
grep     2254     root       cwd    DIR    8,33     8192     17459  /media/TOSHIBA
lsof     2255     root       cwd    DIR    8,33     8192     17459  /media/TOSHIBA

"Ahh...It may have been because I was still cd'd into it."

"Yes!"


So lessons learned:
  • grep, no matter how weird and complicated it looks with all those pipes and stuff, is still VERY useful. 
  • lsof is the command of choice for figuring this out. 
  • Use the mount point rather than the drive itself when searcing the lsof output text. 
  • Even just navigating into a drive will lock it from being unmounted - it's not like in Windows where if you "Safely Remove Hardware" or yank the USB cable, the computer conveniently closes the explorer window for you.

Pentax Camera Accessories - The Expensive Joy of Brand Loyalty


Last April, after months of researching and stressing over whether or not I should (or could), I finally bit the bullet and spent $1300 on a nice 24Mpx Pentax K-3 DSLR. This is a super camera that I really have been enjoying and getting some high quality photos with. Most of all I like the standard ability you get with any DSLR of a fully manual photograph, something you just don't get with a snapshot like my old Fujifilm A820. Sure the good snapshot cameras come with that little pseudo-manual exposure mode where you set one or two preferred manual settings and the rest remain automatic, but a nice DSLR will give you the ability to adjust everything about both exposure AND focus.

The one biggest drawback I've discovered with expensive DSLR cameras are the equally-as-expensive accessories. Sure, I can justify paying $400+ for a nicer lens, because I understand the need for accurately-ground and polished glass, spherical aberration, and the like to produce a decent to high-quality photo.

However, the minor accessories themselves are atrociously overpriced, especially for the Pentax brand.

To date, 8 months later, in addition to the two Wasabi-brand batteries+charger I felt were a good idea to have ($25), I am now a semi-proud owner of a second brand-name focusing screen ($45) (I didn't realize the camera already came with the exact one I ordered separately), a brand-name battery-grip ($125), a brand-name electronic cable release ($40), a brand-name flash-mountable GPS unit ($200), a brand-name K-mount to 42mm threaded adapter ($50), a 62mm Hoya circular polarizer ($70), a 62mm Hoya skylight filter ($35), and a 62mm Tiffen 0.3 neutral density filter ($26). Doing some quick calculator math because I'm too lazy to spend two minutes doing it in my head this brings my total cost for accessories that I've purchased in the last eight months to $616, which is an additional 60% of the cost of the camera itself (which came with a stock lens)!

Now the one thing that I don't have for this thing, which I probably ought to have if I want to do any of the long-term stuff I've already pushed my batteries to the limit with is the AC adapter. Except for one thing. The OEM AC adapter for the K-3 camera is a mindblowing $100.

Not only does the AC adapter use a somewhat-obscure Japanese connector - a Hirose H10485, but the voltage requirements (8.3V) for this camera are EXACTLY the same as that for the Pentax K10D for which a DIYer created a decent tutorial for a number of years ago, as well that of the K-5 which an eBay seller offered power supplies for a mere $16.

I've examined the K-3's AC connector and it looks exactly the same as previous models. Why then, for this model, did Pentax decide to create a completely new part number for yet another 'official' AC adapter and charge $100 for it when I can get what LOOKS like an equivalent for $16? Actually the only two questions regarding this that I have are:
  • Are the pinouts the same as on previous models (+8.3V on the connector's keyed pin, ground on the opposite end and unconnected in the middle)?
  • Is the current rating for the K-3's adapter for some reason higher than the 1.5A spec'd for the K10D? Why can't we just beef up this power supply to handle 2A? Or 2.5A?
The only reason I could see to paying the full $100 for a simple 8.3V DC power supply is that people don't want to risk plugging something whose material cost is less than $16 sold by a third party into their $1000+ camera when the $100 OEM version is guaranteed to work. Oh, and it keeps any warranty valid.

By the way, the cable release, which connects to the camera via a simple 2.5mm stereo headphone jack is the one of the simplest of DPST circuits: