ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

智能开关1.0

2020-07-25 13:33:56  阅读:37  来源: 互联网

标签:1.0 智能 void private 开关 client msg import Serial


arduino代码:

#include <ESP8266WiFi.h>
#include <PubSubClient.h>
WiFiClient espClient;
PubSubClient client(espClient);
const char* wifissid = "HO"; //改成自己家wifi
const char* password = "zlf7783616"; //改成自己家wifi
const char* mqtt_server = "106.13.150.28";
const char* mqtt_id = "1151226060_ESP";   //改成自己的QQ号+_ESP
const char* Mqtt_sub_topic = "1151226060_ESP";   //改成自己的QQ号+_ESP
const char* Mqtt_pub_topic = "1151226060";  //  上报消息给  手机APP的TOPIC  //改成自己的QQ号
void setup() {
  pinMode(2, OUTPUT); //如果该引脚通过pinMode()设置为输出模式(OUTPUT),您可以通过digitalWrite()语句将该引脚设置为HIGH(5伏特)或LOW(0伏特/GND)。    
  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
}
void setup_wifi() {
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(wifissid);
  WiFi.begin(wifissid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}
void callback(char* topic, byte* payload, unsigned int length) {
  String msg="";
  String LED_set = "";
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    msg+= (char)payload[i];
  }
  Serial.println(msg);
  if(msg.indexOf("led"))  //判断是否是要设置LED灯
  {
    //取出LED_set数据 并执行
    LED_set = msg.substring(msg.indexOf("led\":")+5,msg.indexOf("}")); 
    digitalWrite(2,!LED_set.toInt()); 
  }
}
void reconnect() {
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    if (client.connect(mqtt_id)) {
      Serial.println("connected");
      //连接成功以后就开始订阅
      client.subscribe(Mqtt_sub_topic,1);
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);
    }
  }
}
void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
  
}

IDEA Android stydio代码:

package com.example.intelligent_switch;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class MainActivity extends AppCompatActivity {
    private String host = "tcp://106.13.150.28:1883";
    private String userName = "android";
    private String passWord = "android";
    private String mqtt_id = "1151226060"; //定义成自己的QQ号  切记!不然会掉线!!!
    private String mqtt_sub_topic = "1151226060"; //为了保证你不受到别人的消息  哈哈
    private String mqtt_pub_topic = "1151226060_ESP"; //为了保证你不受到别人的消息  哈哈  自己QQ好后面加 _ESP
    private int led_flag =1;
    private ScheduledExecutorService scheduler;
    private Button btn_1;  //类似于单片机开发里面的   参数初始化
    private Button image_1;
    private MqttClient client;
    private MqttConnectOptions options;
    private Handler handler;

    @SuppressLint("HandlerLeak")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //这里是界面打开后 最先运行的地方
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main); // 对应界面UI
        //一般先用来进行界面初始化 控件初始化  初始化一些参数和变量。。。。。
        //不恰当比方    类似于 单片机的   main函数
        btn_1 = findViewById(R.id.btn_1); // 寻找xml里面真正的id  与自己定义的id绑定
        btn_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 这里就是单机之后执行的地方
                // 玩单片机  最常用的就是调试  printf(“hello”)
                System.out.println("hello");
                //更直观的方法   用弹窗:toast
                //在当前activity 显示内容为“hello”的短时间弹窗
                Toast.makeText(MainActivity.this,"hello" ,Toast.LENGTH_SHORT).show();
            }
        });
        //到这里  你已经学会了基本的安卓开发
        // 按钮单机事件你会了   图片单机呢???
        image_1 =findViewById(R.id.image_1);
        image_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(led_flag == 0)
                {
                    publishmessageplus(mqtt_pub_topic,"{\"set_led\":1}");
                    led_flag =1;
                }else{
                    publishmessageplus(mqtt_pub_topic,"{\"set_led\":0}");
                    led_flag =0;
                }
            }
        });
        //  两个控件联动    按钮单机 更改 textview 的内容

//**********************************************************//
        Mqtt_init();
        startReconnect();
        handler = new Handler() {
            @SuppressLint("SetTextI18n")
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what){
                    case 1: //开机校验更新回传
                        break;
                    case 2:  // 反馈回传

                        break;
                    case 3:  //MQTT 收到消息回传   UTF8Buffer msg=new UTF8Buffer(object.toString());


                        //Toast.makeText(MainActivity.this,T_val ,Toast.LENGTH_SHORT).show();

                        break;
                    case 30:  //连接失败
                        Toast.makeText(MainActivity.this,"连接失败" ,Toast.LENGTH_SHORT).show();
                        break;
                    case 31:   //连接成功
                        Toast.makeText(MainActivity.this,"连接成功" ,Toast.LENGTH_SHORT).show();
                        try {
                            client.subscribe(mqtt_sub_topic,1);
                        } catch (MqttException e) {
                            e.printStackTrace();
                        }
                        break;
                    default:
                        break;
                }
            }
        };
    }

    private void Mqtt_init()
    {
        try {
            //host为主机名,test为clientid即连接MQTT的客户端ID,一般以客户端唯一标识符表示,MemoryPersistence设置clientid的保存形式,默认为以内存保存
            client = new MqttClient(host, mqtt_id,
                    new MemoryPersistence());
            //MQTT的连接设置
            options = new MqttConnectOptions();
            //设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录,这里设置为true表示每次连接到服务器都以新的身份连接
            options.setCleanSession(false);
            //设置连接的用户名
            options.setUserName(userName);
            //设置连接的密码
            options.setPassword(passWord.toCharArray());
            // 设置超时时间 单位为秒
            options.setConnectionTimeout(10);
            // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线,但这个方法并没有重连的机制
            options.setKeepAliveInterval(20);
            //设置回调
            client.setCallback(new MqttCallback() {
                @Override
                public void connectionLost(Throwable cause) {
                    //连接丢失后,一般在这里面进行重连
                    System.out.println("connectionLost----------");
                    //startReconnect();
                }
                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {
                    //publish后会执行到这里
                    System.out.println("deliveryComplete---------"
                            + token.isComplete());
                }
                @Override
                public void messageArrived(String topicName, MqttMessage message)
                        throws Exception {
                    //subscribe后得到的消息会执行到这里面
                    System.out.println("messageArrived----------");
                    Message msg = new Message();
                    msg.what = 3;   //收到消息标志位
                    msg.obj = topicName + "---" + message.toString();
                    handler.sendMessage(msg);    // hander 回传
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private void Mqtt_connect() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    if(!(client.isConnected()) )  //如果还未连接
                    {
                        client.connect(options);
                        Message msg = new Message();
                        msg.what = 31;
                        handler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Message msg = new Message();
                    msg.what = 30;
                    handler.sendMessage(msg);
                }
            }
        }).start();
    }
    private void startReconnect() {
        scheduler = Executors.newSingleThreadScheduledExecutor();
        scheduler.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                if (!client.isConnected()) {
                    Mqtt_connect();
                }
            }
        }, 0 * 1000, 10 * 1000, TimeUnit.MILLISECONDS);
    }
    private void publishmessageplus(String topic,String message2)
    {
        if (client == null || !client.isConnected()) {
            return;
        }
        MqttMessage message = new MqttMessage();
        message.setPayload(message2.getBytes());
        try {
            client.publish(topic,message);
        } catch (MqttException e) {

            e.printStackTrace();
        }
    }





}
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
    <LinearLayout
            android:layout_width="match_parent"
            android:orientation="vertical"
            android:layout_height="match_parent">
        <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="160dp">
            <TextView
                    android:layout_width="wrap_content"
                    android:text="基于物联网的智能开关"
                    android:textSize="35dp"
                    android:textColor="#CCFFFF"
                    android:background="@drawable/background_lvshe"


                    android:layout_height="wrap_content">

            </TextView>

        </LinearLayout>
        <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="160dp">


        </LinearLayout>
        <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
            <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_weight="1"
                    android:orientation="vertical"
                    android:layout_height="wrap_content">
                <Button
                        android:layout_width="wrap_content"
                        android:text="电源开关"
                        android:textSize="50dp"
                        android:background="@drawable/drawable"
                        android:layout_gravity="center_horizontal"
                        android:id="@+id/image_1"
                        android:layout_height="wrap_content">
                </Button>
            </LinearLayout>


        </LinearLayout>
        <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="230dp">


        </LinearLayout>
        <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">
            <Button
                    android:layout_width="wrap_content"
                    android:text="按下有惊喜"
                    android:id="@+id/btn_1"
                    android:layout_height="wrap_content">
            </Button>
        </LinearLayout>

    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.example.intelligent_switch">
            <!--允许程序打开网络套接字-->
            <uses-permission android:name="android.permission.INTERNET" />
            <!--允许程序获取网络状态-->
            <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="智能开关"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>

</manifest>

 

标签:1.0,智能,void,private,开关,client,msg,import,Serial
来源: https://www.cnblogs.com/Llingfeng/p/13376424.html

专注分享技术,共同学习,共同进步。侵权联系[admin#icode9.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有