Step 4: Adding More Bells and Whistles
|Top Previous Next|
This and other projects in the Code Examples section are published on our website under the name "test_dhcp_lib".
OK, DHCP now works but your device is probably getting a new IP each time it boots. This is because the device does not "suggest" an IP address when calling dhcp_start(). It is a good practice to do so — memorize the previously obtained IP, then request the same from the DHCP server during the next boot.
Since the IP address must be preserved between boots, your device needs to store it in the EEPROM. Use the STG (settings) library for the purpose (this is, by the way, a shining example of STG's immense usefulness). In the code below, two settings — "IPN" and "IPW" — remember the IP addresses for the Ethernet and Wi-Fi interfaces. Note that the STG library is integrated here in a rather sloppy way. Everything will work but don't take this as a golden standard for STG library use.
Suggested IP address is provided in the on_sys_init() handler, when executing dhcp_start(), first for Ethernet, and then for Wi-Fi. When you run the code for the first time, settings won't have valid values, so stg_get() will return default values of the settings, which are "0.0.0.0" (see settings.txt descriptor file). This means that no specific IP is being requested.
Notice also how device names ("tibbo_net" and "tibbo_wln") are supplied with dhcp_start().
When DHCP configuration completes successfully, callback_dhcp_ok() is called and the obtained IP is saved into the corresponding setting using stg_set(). This also "repairs" the setting if its previous data was invalid. This way, when the device boots next time, stg_get() will return the actual saved data.