Script Programming Model Tips

Select the programming model

You might be very familiar with procedural programming on microcontrollers where you do the tasks sequentially or use a while(1) main loop to poll the status of the system. In a lot of cases, this approach is simple and do the work. However, in this meter, there’re a lot of time-consuming processes (e.g. To get the charger into QC2.0 mode needs approx. 2 seconds. To wait for the user to press a button.), if your application can stuck here and wait, it’s no problem. However, if you are also doing some UI stuff on the screen (e.g. Display meter readings), when you call a time-consuming API, your screen will be frozen, which is undesired on most of the cases. Here, time-consuming API functions usually comes with a optional parameter, which could be used to specify a callback when it completes, some events can also be setup with a callback(e.g. When a Source_Capability message is received). These enable you to use event-driven approach when implementing your application.

If your application don’t call time-consuming APIs, or your application is comfortable with some frozen conditions, you might prefer a straight-forward procedural approach.

If your application is unhappy with such frozen conditions, you might need to choose event-driven approach.

Tips for procedural programming

  1. If you chose procedural programming, don’t try to setup event handlers, as they will never be called. Events can only be fired when your script exited, and the executor enteres event-loop. Before that, the execution is fully in your hand, there is no chance for the event-loop to run.

  2. You don’t need event-loop, so when you want to exit, you should call os.exit(), don’t make the script exits natually, as doing so, your script in some way is still alive, it needs an external kill signal (e.g. Exit on meter UI, exit with PC software) to end completely.

Tips for event-driven programming

  1. You should setup resources you needed, setup events (e.g. A timer for screen refreshing) and just let the script exits. Then the executor enters event-loop, the behaviour of your code fully depends on the events you’ve just setup.

  2. When you call a time-consuming API, make sure you have setup a callback for it to call when the operation completes, don’t spend too much time on the callbacks, there is no chance for other events to fire when you are executing the current callback.

  3. Don’t use delay.ms() in your callbacks, it blocks the executor and other callbacks won’t fire. If you want to do something some time later, use tmr instead.

  4. You can exit the event-loop totally end your application by os.exit()