Skip to content

Commit

Permalink
Merge pull request #1 from Ehsan2754/dev/ble
Browse files Browse the repository at this point in the history
Dev/ble Merge
  • Loading branch information
Ehsan2754 authored Jul 20, 2022
2 parents 271911c + dfc1bc5 commit 94d9bf8
Show file tree
Hide file tree
Showing 7 changed files with 349 additions and 221 deletions.
13 changes: 3 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,9 @@
## Прошивка

Инструменты -> Платы:.. -> ESP32 Arduino -> ESP32 Dev Module
![](img/data_upload.png)

![](img/board_choose.jpg)

<!-- ![](img/board_choose.jpg) -->
нажать галку, если все собралось, то ок.

![](img/check.png)
Expand Down Expand Up @@ -66,14 +66,7 @@
# ESP32server
Labroatory WebServer based on ESP32 serving BLE and Web over network for ZARNITZA company
# Compile options
1. ESP32 dev module
2. Upload speed 921600
3. Flash configurations:
* Cpu speed 240 mhz
* Flash speed 80 mhz
* Flash mode qio
* Flash size 4mb
* Partition scheme default
![](docs\compileparameters.png)
# Device Modes
## SERVER
http://62.113.104.145/?sn=<SERIALNUMBER>
Expand Down
137 changes: 137 additions & 0 deletions bt.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLEUtils.h>
#include <BLE2902.h>
#include <Wire.h>
#include "config.hpp"
#include "bt.hpp"

bool deviceConnected = false;
bool requestFlag = false;

uint8_t CUD_value[17] = "Characteristic 6";

static uint8_t bt_req[BUFFER_SIZE];
static uint8_t bt_res[BUFFER_SIZE];

// Characteristic and Descriptor
// BLEServer *bleServer = NULL;
// BLEService *bleService = NULL;
// BLECharacteristic *bleCharacteristics = NULL;
// BLEAdvertising *bleAdvertising = NULL;

BLEDescriptor cudDescriptor(BLEUUID((uint16_t)0x2901));

// Setup callbacks onWrite
class MyCharacteristicCallbacks : public BLECharacteristicCallbacks
{
void onWrite(BLECharacteristic *pCharacteristic)
{
if (!requestFlag)
{
requestFlag = true;
std::string value = pCharacteristic->getValue();
if (value.length() > 0)
{
for (int i = 0; i < value.length(); i++)
{
bt_req[i] = value[i];
}

if (deviceConnected)
{
auto len = transmitCommand(bt_req, value.length(), bt_res, BUFFER_SIZE);
for (int i = 0; i < (len / 20) + 1; i++)
{
auto startPtr = 20 * i;
auto pktLen = (len < (20 * (i + 1))) ? len % 20 : 20;
DEBUG_PRINTF(DEBUG_APP"\t>>Packet sent from byte %d to %d\n", startPtr, startPtr + pktLen);
DEBUG_PRINTF("\t\t PTR=[MEM@%d,MEM@%d]\n", bt_res + startPtr, bt_res + startPtr + pktLen);
pCharacteristic->setValue(bt_res + startPtr, pktLen);
pCharacteristic->notify();
}
}
}
requestFlag = false;
}
}
};

// Setup callbacks onConnect and onDisconnect
class MyServerCallbacks : public BLEServerCallbacks
{
void onConnect(BLEServer *pServer, esp_ble_gatts_cb_param_t *param)
{
deviceConnected = true;
pServer->updateConnParams(param->connect.remote_bda, 0x06, 0x12, 0, 100);
DEBUG_PRINTLN(DEBUG_APP"DEVICE CONNECTED!");
DEBUG_PRINTF("\tNUMBER OF CONNECTED DEVICES = %d\n", pServer->getConnectedCount() + 1);
}
void onDisconnect(BLEServer *pServer)
{
deviceConnected = false;
DEBUG_PRINTLN(DEBUG_APP"DEVICE DISCONNECTED!");
DEBUG_PRINTF("\tNUMBER OF CONNECTED DEVICES = %d\n", pServer->getConnectedCount() - 1);
pServer->getAdvertising()->start();
}
};
void deinitBT()
{
BLEDevice::deinit(true);
}
void initBT()
{
char devname[10];
sprintf(devname,"%s%s",obtainLabtype(),SN);
DEBUG_PRINTF(DEBUG_INFO"BT-Beacon->%s\n",devname);
// Create the BLE Device
BLEDevice::init(devname);

// Create the BLE Server
BLEServer *bleServer = BLEDevice::createServer();
bleServer->setCallbacks(new MyServerCallbacks());

// Create the BLE Service
BLEService *bleService = bleServer->createService(SERVICE_UUID);

// Create BLE Characteristics and Create BLE Descriptors
BLECharacteristic *bleCharacteristics = bleService->createCharacteristic(CHARACTERISTIC_UUID, BLECharacteristic::PROPERTY_READ |
BLECharacteristic::PROPERTY_WRITE |
BLECharacteristic::PROPERTY_WRITE_NR |
BLECharacteristic::PROPERTY_NOTIFY);

bleCharacteristics->setCallbacks(new MyCharacteristicCallbacks());
cudDescriptor.setValue(CUD_value, 16);
bleCharacteristics->addDescriptor(&cudDescriptor);
bleCharacteristics->addDescriptor(new BLE2902());

bleService->addCharacteristic(bleCharacteristics);

// Start the service
bleService->start();

// Start advertising
BLEAdvertising *bleAdvertising = bleServer->getAdvertising();
bleAdvertising->addServiceUUID(SERVICE_UUID);
bleAdvertising->setScanResponse(true);
bleAdvertising->setMinPreferred(0x06); // functions that help with iPhone connections issue
bleAdvertising->setMinPreferred(0x12);
bleAdvertising->start();
BLEDevice::startAdvertising();
DEBUG_PRINTLN(DEBUG_INFO"Waiting a client connection to notify...");
}

void btHandleRoutine(void *pvParameters)
{
for (;;)
{
// if(SerialBT.available()){
// DEBUG_PRINTLN(DEBUG_INFO "Request from BT");
// uint16_t req_len = SerialBT.readBytes(bt_req,BUFFER_SIZE);
// uint16_t res_len = transmitCommand(bt_req,req_len,bt_res,BUFFER_SIZE);
// for(uint16_t i=0;i<res_len;i++){
// SerialBT.write(bt_res[i]);
// }
// }
}
}
10 changes: 10 additions & 0 deletions bt.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
#ifndef __BT_HPP__
#define __BT_HPP__
#define BT_TIMEOUT 100

extern bool deviceConnected;
void initBT();
void deinitBT();
void btHandleRoutine(void *pvParameters);

#endif//__BT_HPP__
73 changes: 47 additions & 26 deletions config.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
#include <WiFi.h>
#include <WiFiUdp.h>
#include <HardwareSerial.h>
#include "config.hpp"
#include <freertos/semphr.h>
#include "config.hpp"
SemaphoreHandle_t mutex;
bool labLock = false;
const TickType_t xServerDelay = UDP_SERVER_AWAIT / portTICK_PERIOD_MS;
Expand Down Expand Up @@ -56,7 +56,7 @@ unsigned int transmitCommand(unsigned char *Tx, unsigned int lenTx, unsigned cha
}
while (labLock)
{
// DEBUG_PRINT(".");
DEBUG_PRINT(".");
}
DEBUG_PRINTLN();
labLock = true;
Expand Down Expand Up @@ -100,7 +100,6 @@ unsigned int transmitCommand(unsigned char *Tx, unsigned int lenTx, unsigned cha
}
return response_len;
}

uint16_t MODBUS_CRC16(unsigned char *buf, unsigned int len)
{

Expand All @@ -116,6 +115,51 @@ uint16_t MODBUS_CRC16(unsigned char *buf, unsigned int len)
DEBUG_PRINTF(DEBUG_LAB "CRC-16/MODBUS = 0x%X\n", (uint16_t)(crc << 8 | crc >> 8));
return crc << 8 | crc >> 8;
}

char labtypes[5][5] = {
"ZLAB",
"PHYS",
"CHEM",
"ECO",
"BIO"};

char* obtainLabtype()
{

char *result_labtype = NULL;
DEBUG_PRINTLN(DEBUG_LAB "Obtaining Lab type.");
unsigned char GET_INFO[] = {0xAA, 0x06, 0x00, 0x00, 0xc1, 0xfd};
unsigned char RESP_BUFFER[128];
auto LenResp = transmitCommand(GET_INFO, 6, RESP_BUFFER, 128);
auto expectedLen = 38;
if (!LenResp)
{
DEBUG_PRINTF(DEBUG_LAB "Device is off.\n", LenResp, expectedLen);
return 0;
}

if (LenResp != expectedLen)
{
DEBUG_PRINTF(DEBUG_LAB "ERROR->Invalid Package Length! GOT:%d : EXPECTED %d\n", LenResp, expectedLen);
}
switch (RESP_BUFFER[10])
{
default:
case 0:
result_labtype = labtypes[0];
DEBUG_PRINTF(DEBUG_INFO "LAB-TYPE=%s\n", result_labtype);
break;
case 1:
case 2:
case 3:
case 4:
result_labtype = labtypes[RESP_BUFFER[10]];
DEBUG_PRINTF(DEBUG_INFO "LAB-TYPE=%s\n", result_labtype);
break;
}
return result_labtype;
}

uint16_t obtainSerialNumber()
{
DEBUG_PRINTLN(DEBUG_LAB "Obtaining Serial Number.");
Expand Down Expand Up @@ -180,33 +224,11 @@ static unsigned char serverResponse[BUFFER_SIZE];

void serverConnectionHandleRoutine(void *pvParameters)
{
// pinging
// DEBUG_PRINTLN(DEBUG_SERVER "Checking if Server is available.");
// if (!Ping.ping(ServerIP))
// {
// DEBUG_PRINT(DEBUG_SERVER "Server ");
// DEBUG_PRINT(ServerIP);
// DEBUG_PRINTLN(" not available. OFFLINE");
// DEBUG_PRINTLN(DEBUG_SERVER " Waiting for connection ...");
// }
// while (!Ping.ping(ServerIP))
// {
// }
// DEBUG_PRINT(DEBUG_SERVER "Server ");
// DEBUG_PRINT(ServerIP);
// DEBUG_PRINTLN(" Online");
// end of pinging

DEBUG_PRINT(DEBUG_SERVER "Connecting Server TCP SOCKET : ");
DEBUG_PRINT(SERVER_ADDR);
DEBUG_PRINTLN(SERVER_PORT);

bool established = false;

// while (!udp.connect(SERVER_ADDR, SERVER_PORT))
// ;
// DEBUG_PRINT(DEBUG_SERVER "Connected to server. ");
// DEBUG_PRINTF("IP="SERVER_ADDR" PORT=%d\n",SERVER_PORT)
for (;;)
{
packetSize = 0;
Expand All @@ -233,7 +255,6 @@ void serverConnectionHandleRoutine(void *pvParameters)
}
vTaskDelay(xServerDelay);
packetSize = udp.parsePacket();
// packetSize = udp.available();
if (packetSize)
{
uint16_t serverReqLen = udp.read(serverPacket, BUFFER_SIZE);
Expand Down
20 changes: 15 additions & 5 deletions config.hpp
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
#ifndef __CONFIG_HPP__
#define __CONFIG_HPP__



#include <HardwareSerial.h>
// Serial Port For the Lab
#define LAB_SERIAL Serial2
#define LAB_BAUDRATE 115200
Expand All @@ -13,6 +12,13 @@
#define PASSWORD_AP "1234567890"
#define PASSWORD_AP_LEN 10

//Bluetooth configuration
#define BT_NAME "zlab"
#define BT_NAME_LEN 4
#define bleServerName "CHEM10817"
#define SERVICE_UUID "0000ffe0-0000-1000-8000-00805f9b34fb"
#define CHARACTERISTIC_UUID "0000ffe1-0000-1000-8000-00805f9b34fb"

// DNS RESOLVE DOMAIN e.g http://DOMAIN.local
#define DOMAIN "zlab"
#define DOMAIN_LEN 4
Expand All @@ -30,7 +36,7 @@
#define PATH_CONFIG_LEN 7

// WEBSOCKET CYCLE
#define CYCLE_INTERVAL 10
#define CYCLE_INTERVAL 200
// Laboratory [STM] Heartbeat cycle
#define HEARBEAT_INTERVAL 2500

Expand All @@ -43,12 +49,12 @@
// TIMEOUT FOR LAB [STM] response
#define TIMEOUT 100
// Buffer size for binary requests [e.g send-command, socket packets, laboratory responses]
#define BUFFER_SIZE 4096
#define BUFFER_SIZE 2048

// RESERVED
extern SemaphoreHandle_t mutex;
// DEBUG TOOLS
//#define DEBUG
#define DEBUG
#ifdef DEBUG
#define DEBUG_PRINT(...) Serial.print(__VA_ARGS__)
#define DEBUG_PRINTLN(...) Serial.println(__VA_ARGS__)
Expand All @@ -70,6 +76,9 @@ extern SemaphoreHandle_t mutex;
// Laboratory Lock [STM Serial Lock]
extern bool labLock;



// CORE ENUMERATION
#define ESP32_CORE_0 0
#define ESP32_CORE_1 1

Expand All @@ -86,6 +95,7 @@ extern char SN[SERIAL_NO_LEN];
// PT
unsigned int transmitCommand(unsigned char *Tx, unsigned int lenTx, unsigned char *Rx, unsigned int lenRx);
uint16_t MODBUS_CRC16(const unsigned char *buf, unsigned int len);
char* obtainLabtype();
void getSerialNumber();
void printWifiStatus();
void serverConnectionHandleRoutine(void *pvParameters);
Expand Down
Loading

0 comments on commit 94d9bf8

Please sign in to comment.