w mx / warehouse_wmx

Dependencies:   mbed

Fork of SBY_sw4stm32_nucleo_f103rb by w mx

Files at this revision

API Documentation at this revision

Comitter:
xmwmx
Date:
Fri Jul 20 07:05:20 2018 +0000
Child:
1:4d8def597e29
Commit message:
1.0

Changed in this revision

SBY/.mbed Show annotated file Show diff for this revision Revisions of this file
SBY/GettingStarted.html Show annotated file Show diff for this revision Revisions of this file
SBY/esp8266.cpp Show annotated file Show diff for this revision Revisions of this file
SBY/esp8266.h Show annotated file Show diff for this revision Revisions of this file
SBY/language.settings.xml Show annotated file Show diff for this revision Revisions of this file
SBY/main.cpp Show annotated file Show diff for this revision Revisions of this file
SBY/makefile.targets Show annotated file Show diff for this revision Revisions of this file
SBY/mbed.bld Show annotated file Show diff for this revision Revisions of this file
SBY/mbed_config.h Show annotated file Show diff for this revision Revisions of this file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/SBY/.mbed	Fri Jul 20 07:05:20 2018 +0000
@@ -0,0 +1,1 @@
+ROOT=.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/SBY/GettingStarted.html	Fri Jul 20 07:05:20 2018 +0000
@@ -0,0 +1,16 @@
+<!DOCTYPE HTML>
+<html lang="en-US">
+    <head>
+        <meta charset="UTF-8">
+        <meta http-equiv="refresh"
+              content="1;url="https://os.mbed.com/docs/latest/tools/exporting.html>
+        <script type="text/javascript">
+            window.location.href = "https://os.mbed.com/docs/latest/tools/exporting.html"
+        </script>
+        <title>Page Redirection</title>
+    </head>
+    <body>
+        If you are not redirected automatically, please follow the
+        <a href='https://os.mbed.com/docs/v5.6/tools/exporting.html/'>link to the online exporter documentation</a>
+    </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/SBY/esp8266.cpp	Fri Jul 20 07:05:20 2018 +0000
@@ -0,0 +1,236 @@
+/***************************************************************
+功能 : ESP8266物联车接口函数
+作者 : 马晓健
+邮箱 : jeasinema[at]gmail[dot]com
+声明 : 
+本程序仅供学习与交流使用,如需他用,须联系作者
+本程序可以随意更改,但须保留本信息页
+All rights reserved
+2017.6.16
+***************************************************************/
+
+#include "esp8266.h"
+
+#include <cstdarg>
+#include <cstring>
+#include <stdint.h>
+#include "mbed.h"
+
+extern Serial ser2usb;
+
+static int ser_baud = 9600;
+
+//定义了一个调试的宏,C语言语法
+#define ESP_CMD(format, ...) do{\
+    char cmdbuf[128], *p;\
+    ser2esp8266.printf("\r"); \
+    sprintf(cmdbuf, format "\r", ##__VA_ARGS__);\
+    for(p=cmdbuf;*p;p++){\
+        ser2esp8266.putc(*p);\
+        wait(0.02);\
+    }\
+    wait(0.3);\
+}while(0)
+
+
+
+void Esp8266::gotResponse(char *token, char *param)
+{
+    if(*token<'a' || *token>'z') return;
+    ser2usb.printf("gotResponse %s %s\r\n", token, param);
+    if(strcmp(token, "connected") == 0)
+        mqtt_start = true;
+    else if(strcmp(token, "control") == 0){
+        if(!control_cmd){
+            strncpy(control_buf, param, sizeof(control_buf));
+            control_cmd = true;
+        }
+    }
+    else if(strcmp(token, "wifi") == 0){
+        if(*param == '5')
+            network_start = true;
+    }
+}
+
+bool Esp8266::get_control_cmd(char* actuator, char* value)
+{
+    if(!control_cmd)
+        return false;
+    
+    char* plus = strchr(control_buf, '+');
+    if(!plus){
+        control_cmd = false;
+        return false;
+    }
+    *plus = '\0';
+    strcpy(actuator, control_buf);
+    strcpy(value, plus+1);
+    control_cmd = false;
+    return true;
+}
+
+// 接收 esp8266 侧数据的回调函数, 每次仅接收一个8位字符
+// 数据格式约定: #token+data
+void Esp8266::esp8266_rxCallback() {
+    char in = ser2esp8266.getc();
+//    ser2usb.putc(in);
+    enum{STATE_WAIT, STATE_TOKEN, STATE_PARAM};
+    static uint8_t state = STATE_WAIT;
+    static int tokenLen, paramLen;
+    switch(state){
+    case STATE_WAIT:
+        if(in == '#'){
+            tokenLen = 0;
+            state = STATE_TOKEN;
+        }
+        break;
+    case STATE_TOKEN:
+        if(in == '+' || in == '\r' || in == '\n'){
+            esp_tokenBuf[tokenLen] = '\0';
+            if(in == '+'){
+                paramLen = 0;
+                state = STATE_PARAM;
+            }else{
+                gotResponse(esp_tokenBuf, NULL);
+                //memcpy(esp_token, esp_tokenBuf, tokenLen);
+                //esp_token[tokenLen] = '\0';
+                esp_buf_ready = true;
+                state = STATE_WAIT;
+            }
+        }else if(tokenLen+1 < sizeof(esp_tokenBuf)){
+            esp_tokenBuf[tokenLen++] = in;
+        }
+        break;
+    case STATE_PARAM:
+        if(in == '\r' || in == '\n'){
+            esp_paramBuf[paramLen] = '\0';
+            gotResponse(esp_tokenBuf, esp_paramBuf);
+            //memcpy(esp_token, esp_tokenBuf, tokenLen);
+            //memcpy(esp_param, esp_paramBuf, paramLen);
+            //esp_token[tokenLen] = '\0';
+            //esp_param[paramLen] = '\0';
+            //ser2usb.putc('?');
+            esp_buf_ready = true;
+            state = STATE_WAIT;
+        }else if(paramLen+1 < sizeof(esp_paramBuf)){
+            esp_paramBuf[paramLen++] = in;
+        }
+        break;
+    }
+}
+
+
+Esp8266::Esp8266(PinName TX, PinName RX, const char *wifi_ssid, const char *wifi_passwd)       //定义类的函数
+    : network_start(false), mqtt_start(false), control_cmd(false), esp_buf_ready(false), ser2esp8266(TX, RX)
+{
+    // serial to esp8266 init
+    ser2esp8266.baud(ser_baud);
+    ser2esp8266.attach(callback(this,&Esp8266::esp8266_rxCallback), Serial::RxIrq);    
+    //if (mode == 0) {                                                            // client mode 
+        this->reset();
+        this->connect_wifi(wifi_ssid, wifi_passwd);
+        while(!is_connected()){
+            wait(0.5);
+        }
+        this->weblogin();
+    //} else {
+    //    
+    //}
+}
+
+bool Esp8266::reset() {                                                         //定义类的函数
+    ESP_CMD("node.restart()");
+    wait(2);                                                                    // 延迟2s
+    return true;
+}   
+
+bool Esp8266::connect_wifi(const char *wifi_ssid, const char *wifi_passwd) {                                                  //定义类的函数
+    ESP_CMD("wifi.setmode(wifi.STATION)");
+    ESP_CMD("wifi.sta.config([[%s]],[[%s]])", wifi_ssid, wifi_passwd);
+    wait(2);
+    // set auto autoconnect
+    ESP_CMD("wifi.sta.autoconnect(1)");
+    return true;
+}
+
+bool Esp8266::is_connected()
+{
+    ESP_CMD("print('\\035wifi+'..wifi.sta.status())");
+    wait(0.4);
+    return network_start;
+}
+
+bool Esp8266::weblogin() {                                                      //定义类的函数
+    // not implemented yet
+    return true;
+}
+
+void Esp8266::buildCapability(char *out, const char* infoList[][2])
+{
+    out[0] = '\0';
+    for (int i = 0; infoList[i][0]; ++i)
+    {
+        strcat(out, infoList[i][0]);
+        strcat(out, ",");
+        strcat(out, infoList[i][1]);
+        strcat(out, "\\n");
+    }
+}
+
+bool Esp8266::connect_mqtt_broker(char *ip, const char *node_name, const char* sensors[][2], const char* actuator[][2]) {  //定义类的函数
+
+    ESP_CMD("node_name = '%s'", node_name);
+    ESP_CMD("m = mqtt.Client('i_' .. node.chipid(), 120)");
+    ESP_CMD("m:connect(\"%s\",1883,0,function(conn)print (\"\\035connected\"); end)", ip);
+
+    do{    
+        wait(0.5);
+    }while(!mqtt_start);
+
+    ESP_CMD("m:on(\"message\", function(conn, topic, data)");
+    ESP_CMD("if topic:find(\"^/control/\") then");
+    ESP_CMD("local tok = topic:match(\"^/control/.+/(.+)\")");
+    ESP_CMD("if tok then print(\"\\035control+\"..tok..\"+\"..data) end");
+    ESP_CMD("end");
+    ESP_CMD("end)");
+
+    ESP_CMD("m:publish('/events/'..node_name..'/online','',1,0)");
+    wait(0.1);
+
+    char * capabilities = new char[512];
+
+    if(sensors){
+        buildCapability(capabilities, sensors);
+        ESP_CMD("m:publish('/capability/'..node_name..'/values','%s',1,1)", capabilities);
+        wait(0.1);
+    }
+    if(actuator){
+        buildCapability(capabilities, actuator);
+        ESP_CMD("m:publish('/capability/'..node_name..'/control','%s',1,1)", capabilities);
+        wait(0.1);
+        for (int i = 0; actuator[i][0]; ++i)
+            subscribe_control(actuator[i][0]);
+    }
+
+    delete[ ] capabilities;
+
+    return true;
+}
+    
+bool Esp8266::publish_value(const char *topic, const char *data) {                      //定义类的函数
+    //if (mqtt_start) {
+        ESP_CMD("m:publish('/values/'..node_name..'/%s',\"%s\",0,1)", topic, data);
+        wait(0.1);
+    //}
+    return true;
+}
+
+bool Esp8266::subscribe_control(const char *topic, const char *data) {               //定义类的函数
+    //if (mqtt_start) {
+        ESP_CMD("m:subscribe('/control/'..node_name..'/%s', 0)", topic);
+        wait(0.1);
+    //}
+
+    // ESP_CMD("m:unsubscribe(\"%s\")", topic);
+    return true;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/SBY/esp8266.h	Fri Jul 20 07:05:20 2018 +0000
@@ -0,0 +1,36 @@
+#ifndef ESP8266_H
+#define ESP8266_H
+#include "mbed.h"
+
+class Esp8266 {                                                                 //声明一个类
+    volatile bool network_start;
+    volatile bool mqtt_start;
+    volatile bool control_cmd;
+    char esp_tokenBuf[32], esp_paramBuf[32];   // recv from esp8266
+    char control_buf[32];
+    bool esp_buf_ready;
+    Serial ser2esp8266;
+    
+protected:
+    void esp8266_rxCallback();
+    void gotResponse(char *token, char *param);
+    void buildCapability(char *out, const char* infoList[][2]);
+public:
+    Esp8266(PinName TX, PinName RX, const char *wifi_ssid, const char *wifi_passwd);
+    
+    // 通用
+    bool reset();
+    
+    // 连接模式
+    bool connect_wifi(const char *wifi_ssid, const char *wifi_passwd);
+    bool weblogin();
+    bool connect_mqtt_broker(char *ip, const char *node_name, const char* sensors[][2], const char* actuator[][2]);
+    bool is_connected();
+    
+    bool publish_value(const char *topic, const char *data);
+    bool subscribe_control(const char *topic, const char *data = NULL);
+    bool is_control_available(void) { return control_cmd; }
+    bool get_control_cmd(char* actuator, char* value);
+    // 热点模式
+};
+#endif
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/SBY/language.settings.xml	Fri Jul 20 07:05:20 2018 +0000
@@ -0,0 +1,32 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<project>
+	
+	
+	<configuration id="fr.ac6.managedbuild.config.gnu.cross.exe.debug.810899997" name="Debug">
+		<extension point="org.eclipse.cdt.core.LanguageSettingsProvider">
+			<provider copy-of="extension" id="org.eclipse.cdt.ui.UserLanguageSettingsProvider"/>
+			<provider-reference id="org.eclipse.cdt.core.ReferencedProjectsLanguageSettingsProvider" ref="shared-provider"/>
+			<provider-reference id="org.eclipse.cdt.managedbuilder.core.MBSLanguageSettingsProvider" ref="shared-provider"/>
+			<provider copy-of="extension" id="org.eclipse.cdt.managedbuilder.core.GCCBuildCommandParser"/>
+			<provider class="fr.ac6.mcu.ide.build.CrossBuiltinSpecsDetector" console="false" env-hash="-1025524915312781673" id="fr.ac6.mcu.ide.build.CrossBuiltinSpecsDetector" keep-relative-paths="false" name="Ac6 SW4 STM32 MCU Built-in Compiler Settings" parameter="${COMMAND} ${FLAGS} -E -P -v -dD &quot;${INPUTS}&quot;" prefer-non-shared="true">
+				<language-scope id="org.eclipse.cdt.core.gcc"/>
+				<language-scope id="org.eclipse.cdt.core.g++"/>
+			</provider>
+		</extension>
+	</configuration>
+	
+	
+	<configuration id="fr.ac6.managedbuild.config.gnu.cross.exe.release.984526824" name="Release">
+		<extension point="org.eclipse.cdt.core.LanguageSettingsProvider">
+			<provider copy-of="extension" id="org.eclipse.cdt.ui.UserLanguageSettingsProvider"/>
+			<provider-reference id="org.eclipse.cdt.core.ReferencedProjectsLanguageSettingsProvider" ref="shared-provider"/>
+			<provider-reference id="org.eclipse.cdt.managedbuilder.core.MBSLanguageSettingsProvider" ref="shared-provider"/>
+			<provider copy-of="extension" id="org.eclipse.cdt.managedbuilder.core.GCCBuildCommandParser"/>
+			<provider class="fr.ac6.mcu.ide.build.CrossBuiltinSpecsDetector" console="false" env-hash="-1025524915312781673" id="fr.ac6.mcu.ide.build.CrossBuiltinSpecsDetector" keep-relative-paths="false" name="Ac6 SW4 STM32 MCU Built-in Compiler Settings" parameter="${COMMAND} ${FLAGS} -E -P -v -dD &quot;${INPUTS}&quot;" prefer-non-shared="true">
+				<language-scope id="org.eclipse.cdt.core.gcc"/>
+				<language-scope id="org.eclipse.cdt.core.g++"/>
+			</provider>
+		</extension>
+	</configuration>
+	
+</project>
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/SBY/main.cpp	Fri Jul 20 07:05:20 2018 +0000
@@ -0,0 +1,117 @@
+#include <cstdarg>
+#include <cstring>
+#include "esp8266.h"
+#include "mbed.h"
+
+
+Serial ser2usb(PA_2, PA_3, 115200);
+int state = 0;
+void open(int row,int col);
+void SetUp();
+
+DigitalOut red[2]=
+{
+    PB_13,PB_12,
+};
+
+DigitalOut black[3]=
+{
+    PA_12,PA_11,PB_3,
+};
+
+
+int main() 
+{
+    SetUp();
+    wait(0.5);
+     
+
+
+//ser2usb.printf("starting\r\n");
+    
+    // 选定与 esp8266 相连接的串口,WiFi 名称和密码
+    Esp8266 client(PA_9, PA_10, "iot_b827eb8fb527", "7c02b50b");// 参数分别为 TX pin / RX pin / SSID / Password
+
+    //声明所有的传感器,每行一个,每个由名字、单位两部分组成,最后一行必须为空指针作为结尾
+    const char* sensors[][2] = {
+        "actionok", "",
+        NULL, NULL //最后一行以空指针作为结束标记
+    };
+
+    //声明所有的执行器,每行一个,每个由名字、参数类型两部分组成,最后一行必须为空指针作为结尾
+    const char* actuators[][2] = {
+        "openstore", "int",
+        NULL, NULL //最后一行以空指针作为结束标记
+    };
+    //ser2usb.printf("connecting...\r\n");
+
+    //连接到服务器
+    client.connect_mqtt_broker("192.168.12.1", "store", sensors, actuators);
+
+    ser2usb.printf("Initialization done.\r\n");
+    char actuator_name[32], control_value[32];
+    Timer t;// 定时器用于计量发送传感器数据的时间
+    t.start();
+        client.publish_value("openstore", "storeinit");
+    while(1) 
+    {
+        //检查有没有收到新的执行器控制指令
+        if(client.get_control_cmd(actuator_name, control_value))
+        {
+            ser2usb.printf("Received CMD %s %s\r\n", actuator_name, control_value);
+            //判断哪个执行器收到命令
+            state = atoi(control_value);
+            switch(state)
+            {
+                case 1:
+                    open(0,0);
+                    client.publish_value("openstore", "storefinish");
+                    break;
+                case 2:
+                    open(0,1);
+                    client.publish_value("openstore", "storefinish");
+                    break;
+                case 3:
+                    open(0,2);
+                    client.publish_value("openstore", "storefinish");
+                    break;
+                case 4:
+                    open(1,0);
+                    client.publish_value("openstore", "storefinish");
+                    break;
+                case 5:
+                    open(1,1);
+                    client.publish_value("openstore", "storefinish");
+                    break;
+                case 6:
+                    open(red[1],black[2]);
+                    client.publish_value("openstore", "storefinish");
+                    default:
+                    break;
+               }
+           } 
+        }        
+}
+
+void SetUp()
+{
+    for(int i=0; i<2; i++)
+    {
+        red[i].write(0);
+    }
+    
+    for(int i=0; i<3; i++)
+    {
+        black[i].write(0);
+    }
+    
+
+}
+void open(int row,int col)
+{
+        red[row].write(1);
+        black[col].write(1);
+        wait(0.2);
+        SetUp();  
+}
+          
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/SBY/makefile.targets	Fri Jul 20 07:05:20 2018 +0000
@@ -0,0 +1,18 @@
+# DO NOT REMOVE! Generated by the SW4STM32 exporter from the mbed project.
+
+PREPROC_CMD ?= arm-none-eabi-cpp -E -P
+
+ldclean:
+	$(RM) linker-script-debug.ld
+	$(RM) linker-script-release.ld
+
+linker-script-debug.ld: ../mbed/TARGET_NUCLEO_F103RB/TOOLCHAIN_GCC_ARM/STM32F103XB.ld
+	$(PREPROC_CMD) -DMBED_DEBUG -DMBED_TRAP_ERRORS_ENABLED=1 -Wl,-n -Wl,--start-group -lstdc++ -lsupc++ -lm -lc -lgcc -lnosys -Wl,--end-group $< -o $@
+
+SBY-debug.elf: linker-script-debug.ld
+
+linker-script-release.ld: ../mbed/TARGET_NUCLEO_F103RB/TOOLCHAIN_GCC_ARM/STM32F103XB.ld
+	$(PREPROC_CMD) -DNDEBUG -Wl,-n -Wl,--start-group -lstdc++ -lsupc++ -lm -lc -lgcc -lnosys -Wl,--end-group $< -o $@
+
+SBY-release.elf: linker-script-release.ld
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/SBY/mbed.bld	Fri Jul 20 07:05:20 2018 +0000
@@ -0,0 +1,1 @@
+http://mbed.org/users/mbed_official/code/mbed/builds/5aab5a7997ee
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/SBY/mbed_config.h	Fri Jul 20 07:05:20 2018 +0000
@@ -0,0 +1,36 @@
+/*
+ * mbed SDK
+ * Copyright (c) 2017 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// Automatically generated configuration file.
+// DO NOT EDIT, content will be overwritten.
+
+#ifndef __MBED_CONFIG_DATA__
+#define __MBED_CONFIG_DATA__
+
+// Configuration parameters
+#define MBED_CONF_PLATFORM_FORCE_NON_COPYABLE_ERROR   0                            // set by library:platform
+#define MBED_CONF_PLATFORM_STDIO_CONVERT_TTY_NEWLINES 0                            // set by library:platform
+#define MBED_CONF_PLATFORM_DEFAULT_SERIAL_BAUD_RATE   9600                         // set by library:platform
+#define MBED_CONF_PLATFORM_STDIO_CONVERT_NEWLINES     0                            // set by library:platform
+#define MBED_CONF_TARGET_LSE_AVAILABLE                1                            // set by target:FAMILY_STM32
+#define MBED_CONF_PLATFORM_STDIO_BAUD_RATE            9600                         // set by library:platform
+#define CLOCK_SOURCE                                  USE_PLL_HSE_EXTC|USE_PLL_HSI // set by target:NUCLEO_F103RB
+#define MBED_CONF_PLATFORM_STDIO_BUFFERED_SERIAL      0                            // set by library:platform
+#define CLOCK_SOURCE_USB                              0                            // set by target:NUCLEO_F103RB
+#define MBED_CONF_PLATFORM_STDIO_FLUSH_AT_EXIT        1                            // set by library:platform
+
+#endif