Thanks you @J-M-L and @dougp this was helpful, in particular for starting new projects. I will use this.
In the case I want to try some code I find (e.g. on github or here in the forum), I need something to insert the required OTA code at the right place.
I typed some python code which of course I need to execute on the .ino I want to upload first but it seems to work. I'm sure there are more elegant ways to solve this but in case anybody is interesed, here is my python code. The name of the .ino file which gets modified need to be specified as a cmd line parameter. Lets say you want to add OTA to blink.ino you would write:
python addcode.py blink.ino
as a command line.
Here is my python code for addcode.py:
import fileinput
import sys
filename = sys.argv[1]
OTA = False
WiFi = False
for line in fileinput.input(filename, inplace=1):
print(line, end='') # line in the file already have a \n so need to say ''
if line.startswith('#include <ArduinoOTA.h>'):
OTA = True
if line.startswith('#include <WiFi.h>'):
WiFi = True
if not OTA:
for line in fileinput.input(filename, inplace=1):
if fileinput.isfirstline():
print("#include <ArduinoOTA.h>", end='\n') # replave the first line with this string
print(line, end='') # but then reprint the original line into the next line
else:
print(line, end='') # if not first line just reprint the lines
for line in fileinput.input(filename, inplace=1):
if line.startswith('void setup()'):
print(line, end='')
print(" WiFi.begin(ssid, password);", end='\n') # as there is no \n, it needs to be added
print(' if (WiFi.waitForConnectResult() != WL_CONNECTED) {', end='\n')
print(' Serial.println("WiFi Failed");', end='\n')
print(' while(1) {', end='\n')
print(' delay(1000);', end='\n')
print(' }', end='\n')
print(' }', end='\n')
print(' ArduinoOTA.setHostname("tmpOTAname");', end='\n') # here you can set the Hostname as it will be dislayed by OTA in the network
print(' ArduinoOTA.setPassword("1234");', end='\n')
print(' ArduinoOTA.begin();', end='\n')
else:
print(line, end='')
for line in fileinput.input(filename, inplace=1):
if line.startswith('void loop()'):
print(line, end='')
print(' ArduinoOTA.handle();', end='\n')
else:
print(line, end='')
if not WiFi:
for line in fileinput.input(filename, inplace=1):
if fileinput.isfirstline():
print("#include <WiFi.h>")
print('//=================================== WLAN credentials =============================================//')
print('// Enter WLAN credentials here. //')
print('//==================================================================================================//')
print('const char * ssid = "****";') # include your WiFi ssid here
print('const char * password = "****";') # include your WiFi password here
print(line, end='')
else:
print(line, end= '')