// MQTT PUBLISH Implemtion for LOXONE // Version 0.1 ... kianusch@gmail.com #define CONNECT 0x10 #define DISCONNECT 0xE0 #define PUBLISH 0x30 // #define CLIENTID "iobroker" #define DEVICE "/dev/tcp/192.168.x.x/1883" #define USERNAME "mqttuser" #define PASSWORD "mqttpassword" char* topic[13]; topic[0]="esp01/gpio/12"; // AI1 topic[1]="esp02/gpio/12"; // AI2 topic[2]="esp03/relay/0/set"; // AI3 topic[3]="esp03/relay/0/set"; topic[4]="esp05/pwm/12"; topic[5]=""; topic[6]=""; topic[7]=""; topic[8]=""; topic[9]=""; topic[10]=""; topic[11]=""; topic[12]=""; char connectMsg[12] = {CONNECT, 10, 0, 4, 'M', 'Q', 'T', 'T', 4, 2, 0, 10}; char disconnectMsg[2] = {DISCONNECT, 0}; int nEvents; int input; char inputStr[8]; void tostring(char *str, int num) { int i, rem, len = 0, n; n = num; while (n != 0) { len++; n /= 10; } for (i = 0; i < len; i++) { rem = num % 10; num = num / 10; str[len - (i + 1)] = rem + '0'; } str[len] = '\0'; } int connect(STREAM* stream, char *username, char *password) { char response[2]; char payload[128]; char *ppayload; int len; int flag=0x02; ppayload=payload; // set Client Identifier to blank *(ppayload++)=0; *(ppayload++)=0; len=2; if (username != NULL) { *(ppayload++)=0; *(ppayload++)=strlen(username); strcpy(ppayload, username); ppayload+=strlen(username); len+=(strlen(username)+2); flag |= 0x80; } if (password != NULL) { *(ppayload++)=0; *(ppayload++)=strlen(password); strcpy(ppayload, password); ppayload+=strlen(password); len+=(strlen(password)+2); flag |= 0x40; } connectMsg[9]=flag; connectMsg[1]=10+len; stream_write(stream,connectMsg,12); stream_write(stream,payload,len); stream_flush(stream); len=stream_read(stream,response,2,1000); if (len==2 && response[0] == 0x20 && response[1] == 2) { stream_read(stream,response,2,1000); if (response[0] == 0 && response[1] == 0) { return 1; } else { printf("MQTT: ACK failed. [Session Present: %02x / Code: %02x]", response[0], response[1]); } } else { printf("MQTT: ACK failed. [len: %d / code: %02x]", len, response[0]); } return 0; } void publish(STREAM* stream, char* topic, char* publish) { char message[128]; char* msg; int len=2+strlen(topic)+strlen(publish); msg=message; *(msg++)=PUBLISH; *(msg++)=len; *(msg++)=0; *(msg++)=strlen(topic); strcpy(msg,topic); msg+=strlen(topic); strcpy(msg,publish); stream_write(stream,message,len+2); stream_flush(stream); } void disconnect(STREAM* stream) { stream_write(stream,disconnectMsg,2); stream_flush(stream); } // Main loop while(TRUE) { nEvents = getinputevent(); if (nEvents & 0xFFF8) { STREAM* stream = stream_create(DEVICE,0,0); if (stream != NULL && connect(stream, USERNAME, PASSWORD)) { for (input=0;input<13;input++) { if (nEvents & (0x8 << input)) { float inMsg = getinput(input); tostring(inputStr,(int)inMsg); publish(stream,topic[input],inputStr); } } disconnect(stream); } stream_close(stream); sleep(100); } else { sleep (500); } }