Prev: Making it a Function
Combining SMS and User Interface
Now that we have our user interface, we would like to allow the user to edit the database while the SMS code presented in section
* () is running.
Doing so is relatively straightforward by adding a menu with two options: the Edit option should run the editor (our function edit()), and Stop should stop the script. With function ui.menu(), it is trivial to install a menu:
ui.menu("Service",["Edit","Stop"])
|
adds a menu with title Service and the two options:
 | |  |
| Series 60 sample screen | | UIQ sample screen |
If the user picks an option, ui.cmd() will return it:
But now we have a problem: if the user hasn't picked an option before, ui.cmd() will wait. Likewise, sms.receive() will wait until an SMS arrives. So we have two events to wait for, but we can only wait for one at a given point in our code.
There is a simple solution to this: both sms.receive() and ui.cmd() take a timeout: they do not necessarily wait forever, but optionally only for a certain period. Almost all functions in m which wait for a certain event have such timeouts. The timeout period is always indicated in milliseconds (ms, 1/1000 of a second). If the timeout expires, the functions typically return null.
For instance,
waits one second for a new message, then simply returns null if no message arrives within this period[2].
With this simple method, we can combine the user interface and the SMS monitoring[3]:
ui.menu("Service",["Edit","Stop"]);
do
id=sms.receive(1000);
if id#null then // there is a new message
msg=sms.get(id);
t=lower(trim(msg["text"]));
if db[t]#null then
print "Got",t,"from",msg["sender"];
sms.send(msg["sender"], db[t]);
sms.delete(id)
end
end;
cmd=ui.cmd(5000);
if cmd="Edit" then
edit(db)
end
until cmd="Stop"
|
Remarks:
- The do-until loop executes code until a condition becomes true: in this case, until the user picks Stop from the menu. It is similar to the while-do-end loop, but the condition is tested at the end of the loop.
- If sms.receive() times out, it returns null: no message can be checked in this case.
- The script does not respond to a pick from the menu while sms.receive() is executing. To minimize the time this happens, the timeout for the sms.receive() is only one second, whereas the timeout for ui.cmd() is five seconds.
- If ui.cmd() times out, the variable cmd becomes null, which is different from both "Edit" and "Stop". There is no need to check this case explicitly.
Next: Reading and Writing Files© 2004-2011 airbit AG, CH-8008 Zürich
Document AB-M-TUT-887