Device command handling and messaging integration · Learning
English translation
Execution conditions
The basic activity uses Python only. Choose a real messenger or MQTT connection only after verifying the handling rules.
Topics covered
Separate input, state, and response so that the same command handling rules can be reused across messengers, the web, and device buses.
Overall workflow
External message → common command → validation and deduplication → state and response
Separate messages from device actions
The same on command can arrive through the web, a messenger, or a device bus. Convert the transport format into a common request {request_id,device,command}, then pass it to one handler function.
Duplicate and invalid commands
Retransmission affects commands that specify a target state, such as on, differently from commands that change the current state, such as toggle. Validate the request ID, device, and command before handling duplicates, and record both the response and actual state.
Worked example
The inputs are /start, /led on, /led off, /led invalid, and /unknown. The initial LED state is off.
def handle(text,state):
if text=='/start':return state,'Commands: /led on, /led off'
if text=='/led on':return True,'LED on'
if text=='/led off':return False,'LED off'
return state,'Usage: /led on | /led off'
state=False
for text in ['/start','/led on','/led off','/led invalid','/unknown']:
next_state,reply=handle(text,state);print(text,state,next_state,reply);state=next_state
/start False False Commands: /led on, /led off /led on False True LED on /led off True False LED off /led invalid False False Usage: /led on | /led off /unknown False False Usage: /led on | /led off
Reference example
View more examples