Tag Archive interface

Korad KA3005P Serial Programming

korad-ka3005pThis is a cheap lab bench power supply that given its flaws is a surprisingly solid piece of equipment. I wouldn’t call this a precision power supply, but its tolerances and ripple are acceptable for ordinary bench work. (And really, if you’re doing precision work, you’ll invest in a precision supply anyhow.)

There are two methods for communicating with the unit: a serial interface and a proprietary binary USB interface. One may use either the DB-9 connector or USB to access the serial interface.

I wrote a Python wrapper for the serial protocol to encapsulate the various tidbits  of information I’ve encountered on the  Internet. The firmware is buggy and there are various gotchas. Hopefully the Python wrapper will address the worst of the problems one might encounter.

Tags, , , ,

How to Access a Local Node Server Using Websockets


The AngularJS web application that I’m working on runs on a remote server, but needs to access laboratory instruments connected to the local computer that is running the web browser. JavaScript running in the web browser runs in a sandbox and is prohibited from accessing local hardware.

We explored several possibilities of how to work around this and found a fairly simple solution. The local computer runs a small Node.js program to act as glue between the instrument and the local web browser. Node.js communicates with the instrument’s USB serial port using the Node serialport plugin.

Node also runs express to serve up a simple AngularJS web application for diagnostics. We also connect socket.io to the express instance to provide an interactive communication pipeline between the Node.js program and the main web application.

The Problem Space

One of the traditional iron clad security paradigms of web programming is that JavaScript served up from a server cannot access another server. This works for nearly all web sites, but there are instances where being able to share resources across servers is desirable. For example, if our web app can communicate with local laboratory instruments it’s a big win for my client.

The Approach

The W3C has published Cross-Origin Resource Sharing specifications which provide a standardized method for doing this. To implement this, the non-origin server (in our case, the Node.js server) has to provide HTTP headers to the web browser indicating that it will accept the cross-origin request.

If these headers are missing, the web browser will not complete the HTTP request. For example, Firefox 29 — in its debug console — will report

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8888/socket.io/1/?t=1402443850582. This can be fixed by moving the resource to the same domain or enabling CORS.

This means that the web browser is denying access to Node.js running on localhost because (a) it is a different destination than the original server (the origin) and (b) the Node.js server is not granting permission for the cross-origin request.

Thus the problem boils down to coaxing socket.io to provide those headers when the web browser connects.

The Snag

I have not been able to get this to work on socket.io version 1.0 and higher. To avoid wasting time I reverted to pre-1.0 thus:

npm install --save socket.io@"<1.0"

In the Node.js program’s main app.js, I added one line to allow connections from any cross-origin server (see line 2 below). Note that this is development code running on an isolated network inaccessible from the Internet. One should think hard before leaving this open to all comers.

var io = require('socket.io').listen(server);
io.set('origins', '*:*');

If you look in the socket.io source file ./lib/manager.js you’ll see the lines:

  if (origin) {
    // https://developer.mozilla.org/En/HTTP_Access_Control
    headers['Access-Control-Allow-Origin'] = origin;
    headers['Access-Control-Allow-Credentials'] = 'true';

This may prove useful during debugging if adding the set('origins' ... call doesn’t work as expected.

Unanswered Questions

This solution doesn’t appear to work for serialport.io version 1.0 and higher.


Cross-Origin Resource Sharing official W3C documentation.

Using CORS introduction to CORS.

Enable Cross-Origin Resource Sharing sample code.

Socket.io doesn’t set CORS header(s) on Stackoverflow





Tags, , , , ,

Focus On Functionality with Objective C

Polymorphism has saved my buns quite a few times on various projects. When using languages that support interfaces, like Java or Delphi, I tend to design around them. This allows me to focus on functionality rather than classes.

In other words, when interfaces are passed around and used, rather than classes, I ultimately don’t care what the class is “hiding behind” the interface. The only question is whether that class provides the functionality the interface “contract” specifies. New functionality can be obtained seamlessly by hiding a new class behind the required interface. Similar comments can be made about the strong information hiding aspect of interfaces.

Objective C protocols are similar in many respects to interfaces. The one big syntactic difference that bit me was that you can’t declare a variable’s type to be a protocol. In the following example, I can’t declare myLocalVariable to be any kind of protocol (something I would do in other languages).

@protocol SomeProtocol
- (void) foo;
  SomeProtocol  myLocalVariable;
//SomeProtocol *myLocalVariable; <-- this is also wrong
[myLocalVariable foo];

Having found interfaces a key language feature when designing, this caused some heartburn at first. Objective C, however, allows one to include a protocol in type declarations. Thus, the code becomes:

id  myLocalVariable;
[myLocalVariable foo];

With this syntax, I can continue to focus on designing around functionality rather than classes.

But Wait! There's More!

If id <SomeProtocol> has your gears turning, you can apply the syntax one step further. This may only be useful in specific situations, but here it is for the record.

You need not stop at the generic id, and may use any class. For example, given a parent class ParentClass, you could ensure that a variable accepts any descendant of ParentClass that also supports the SomeProtocol protocol thus:

ParentClass  *myLocalVariable;
[myLocalVariable foo];

Note that you must still pay attention to the usual caveat that id is an implied pointer declaration, and must not include the star (*) after it like all other classes do. id is still the equivalent of (void *).

Tags, , , ,

Leaking Interfaced Objects in Delphi

I’ve been tracking down some memory leaks in a program written in the Delphi language (formerly known as Borland’s Object Pascal). I’ve run across this a few times over the years.

Interfaced objects in Delphi have the wonderful benefit of automatic lifetime management due to automatic reference counting. It’s almost as convenient as the automatic object disposal Java, C#, and Objective C (on Mac OS X Leopard).

There’s a potential memory leak, however if you descend from TInterfacedObject and override the AfterConstruction method. You must call inherited else the object will never be released!

How This Happens

Note that the constructor increments the reference count otherwise it will go to zero during construction under certain circumstances. That, of course, would cause the object to free itself immediately… and you the programmer would go an a man hunt to avenge the accelerated hair loss.

Because the constructor increases the reference count to prevent premature destruction, the reference count must also be decreased to its correct value after the constructor has finished executing. This happens in the AfterConstruction method. Look at the implementation in System.pas:

procedure TInterfacedObject.AfterConstruction;
  // Release the constructor's implicit refcount


Say you descend from TInterfacedObject, and do something in AfterConstruction. The following example is simplistic, but makes the case:

  IFoo = interface

  TFoo = class(TInterfacedObject, IFoo)
    Bar :Integer;
    procedure AfterConstruction; override;
  Bar := 1;

Note that TFoo.AfterConstruction does not call inherited. Because inherited is not called, TInterfacedObject.AfterConstruction is not called, and the implicit reference count done in the constructor will never be undone.

Thus, the following code will never release the instance of TFoo:

  lFoo :IFoo;
  lFoo := TFoo.Create;

To fix this memory leak, call inherited in the descendant’s AfterConstruction definition, thus:

  inherited; // <---- CALL inherited HERE!
  Bar := 1;

Tags, , , , , ,

%d bloggers like this: