Я пытаюсь отправить / получить сообщения MQTT в формате JSON.
Это мой код:
public class MainActivity extends AppCompatActivity {
Gson gson = new Gson();
public static final String BROKER_URL = "tcp://iot.eclipse.org:1883";
String userid = "12345"; //
//We have to generate a unique Client id.
String clientId = userid + "-sub";
// Default sensor to listen for -
// Change to another if you are broadcasting a different sensor name
String sensorname = "brightness";
String sensorTemp = "temperature";
String topicname = userid + "/" + sensorname;
String topicname2 = userid + "/" + sensorTemp;
public final String TOPIC_BRIGHTNESS = userid + "/brightness";
public final String TOPIC_TEMPERATURE = userid + "/temperature";
public final String TOPIC_DOORLOCK = userid + "/doorlock";
private MqttClient mqttClient;
Button publishTemperatureBtn;
Switch publishDoorState;
SeekBar tempSeekBar;
TextView tempLabel;
SensorData oneSensor = new SensorData("unknown", "unknown");
String oneSensorJson = new String();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
publishTemperatureBtn = (Button) findViewById(R.id.publishTemperatureBtnID);
tempSeekBar = (SeekBar) findViewById(R.id.temperatureSeekBar);
publishDoorState = (Switch) findViewById(R.id.doorSwitch);
tempLabel = (TextView) findViewById(R.id.temperatureLabel);
publishTemperatureBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Code here executes on main thread after user presses button
System.out.println("PUBLISHING");
runOnUiThread(new Runnable() {
public void run() {
publishTemperature();
}
});
}
});
publishDoorState.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if (isChecked == true) {
runOnUiThread(new Runnable() {
@Override
public void run() {
publishDoorStateMethod_ON();
}
});
} else if (isChecked == false) {
runOnUiThread(new Runnable() {
@Override
public void run() {
publishDoorStateMethod_OFF();
}
});
}
}
});
tempSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
tempLabel.setText(i + "°C");
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
runOnUiThread(new Runnable() {
@Override
public void run() {
publishTemperature();
}
});
}
});
// start new
// Create MQTT client and start subscribing to message queue
try {
// change from original. Messages in "null" are not stored
mqttClient = new MqttClient(BROKER_URL, clientId, null);
mqttClient.setCallback(new MqttCallbackExtended() {
@Override
public void connectionLost(Throwable cause) {
//This is called when the connection is lost. We could reconnect here.
}
@Override
public void messageArrived(final String topic, final MqttMessage message) throws Exception {
System.out.println("DEBUG: Message arrived. Topic: " + topic + " Message: " + message.toString());
// get message data
final String messageStr = message.toString();
runOnUiThread(new Runnable() {
public void run() {
System.out.println("Updating UI");
// Update UI elements
if ((topic).equals(topicname)) {
System.err.println("Sensor gone!");
TextView sensorValueTV = (TextView) findViewById(R.id.sensorValueTV);
sensorValueTV.setText(messageStr);
} else if ((topic).equals(topicname2)) {
System.err.println("Sensor gone!");
TextView sensorTempValue = (TextView) findViewById(R.id.sensorTempValue);
sensorTempValue.setText(messageStr);
}
}
});
}
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
//no-op
}
@Override
public void connectComplete(boolean b, String s) {
//no-op
}
});
} catch (MqttException e) {
e.printStackTrace();
System.exit(1);
}
// temp use of ThreadPolicy until use AsyncTask
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
startSubscribing();
}
public void startSubscribing() {
try {
mqttClient.connect();
//Subscribe to all subtopics of home
final String topic = topicname;
mqttClient.subscribe(topic);
final String topic2 = topicname2;
mqttClient.subscribe(topic2);
System.out.println("Subscriber is now listening to " + topic);
} catch (MqttException e) {
e.printStackTrace();
System.exit(1);
}
}
public void publishTemperature() {
try {
final MqttTopic temperatureTopic = mqttClient.getTopic(TOPIC_TEMPERATURE);
final int temperatureNumber = 30;
EditText temperatureETValue = (EditText) findViewById(R.id.temperatureETValue);
final String temperature = tempLabel.getText().toString();
temperatureTopic.publish(new MqttMessage(temperature.getBytes()));
System.out.println("Now publishing " + temperatureTopic);
} catch (MqttException e) {
e.printStackTrace();
System.exit(1);
}
}
public void publishDoorStateMethod_ON() {
try {
final MqttTopic doorButtonTopic = mqttClient.getTopic(TOPIC_DOORLOCK);
String doorState;
Button doorStateButton = (Button) findViewById(R.id.doorSwitch);
doorState = "ON";
doorButtonTopic.publish(new MqttMessage(doorState.getBytes()));
System.out.println("Now publishing " + doorButtonTopic);
} catch (MqttException e) {
e.printStackTrace();
System.exit(1);
}
}
public void publishDoorStateMethod_OFF() {
try {
final MqttTopic doorButtonTopic = mqttClient.getTopic(TOPIC_DOORLOCK);
String doorState;
Button doorStateButton = (Button) findViewById(R.id.doorSwitch);
doorState = "OFF";
doorButtonTopic.publish(new MqttMessage(doorState.getBytes()));
System.out.println("Now publishing " + doorButtonTopic);
} catch (MqttException e) {
e.printStackTrace();
System.exit(1);
}
}
}
Это то, что мне было поручено:
- Изменить код Android, чтобы отправлять / получать сообщения MQTT в виде строк json, представляющих объекты датчика.Вам нужно будет включить тот же объект SensorData, который вы использовали в лабораториях Eclipse, и включить класс Gson в свой проект Android.Используйте пример кода из клиент-серверной лаборатории Eclipse, чтобы напомнить, как создавать объекты json из объекта SensorData и как извлекать данные объекта при поступлении объекта json.
У меня уже есть SensorDataобъект.Примеры в Elicpse, которые у меня есть, не помогают.Может ли кто-нибудь, пожалуйста, указать мне в правильном направлении.