bluerhinos / phpMQTT

a simple php class to connect/publish/subscribe to a MQTT broker
Other
770 stars 461 forks source link

How to publish a topic with multiple params #63

Closed amun1303 closed 4 years ago

amun1303 commented 6 years ago

Hello @bluerhinos My code is working by turn the light on/off URLAPI calling: http://domainname.com/api/turnTheLight/5/1 routes: /api/{pin}/{action}

public function turnTheLight( Request $request ) {
        $action    = $request->route( 'action' );
        $device    = Device::find( $request->route( 'id' ) );
        $client_id = $device->device_id; 
        $mqtt      = new phpMQTT( $this->server, $this->port, $client_id );
        if ( $mqtt->connect( true, null, $this->username, $this->password ) ) {
            $mqtt->publish( '/turn/light', $action, 0 );
            $mqtt->close();
            $device->status = $action;
            $device->save();

            return response()->json( [
                'statusCode' => 1,
                'message'    => 'Success',
            ] );
        } else {
            return response()->json( [ 'message' => 'Error!!' ], 204 );
        }
    }

But now I want to publish the topic include the deviceID and the pin of light /turn/light/{deviceID}/{pin}/{action} Example: /turn/light/esp123456/5/1 That only effect with the deviceID: esp123456 and the light connected on pin 5th is ON

Below is Arduino code

void callback(char* topic, byte* payload, unsigned int length) {
  String topicStr = topic;
  //turn the light on if the payload is '1' and publish to the MQTT server a confirmation message
  if (payload[0] == '1') {
    digitalWrite(5, HIGH);
    client.publish("/state/light", "Light On");
  }
  //turn the light off if the payload is '0' and publish to the MQTT server a confirmation message
  else if (payload[0] == '0') {
    digitalWrite(5, LOW);
    client.publish("/state/light", "Light Off");
  }
}

Please help me.

lxlin315 commented 6 years ago

请问你的问题解决了吗?我现在也在用MQTT做灯控系统,也遇到问题了,想请教一下,谢谢!

bluerhinos commented 4 years ago

I am restarting this project so having a clear out of old issues (If you believe this is still valid please reopen)