Visit The New, Modern Unix Linux Community


Arduino Project: iPhone to HM-10 BLE to NB-IoT Shield to NB-IoT Network to Internet to Linux Server


 
Thread Tools Search this Thread
Top Forums Programming Arduino Project: iPhone to HM-10 BLE to NB-IoT Shield to NB-IoT Network to Internet to Linux Server
# 8  
It's quite amazing what we can do with a few pieces of Arduino electronics when we put our minds to it. New products can be created.

I always appreciate people who create "new knowledge" and that's what you're doing. Just proofing that it can be done so inexpensively is great.
This User Gave Thanks to hicksd8 For This Post:
# 9  
Yeah, I think it is really nice we can build a custom iPhone app which does not use WIFI or a direct network connection to the Internet to get server / network management data on the other side of the world.

Of course, the sky is the limit, and some people might like home or factory automation and other person might want to control a server, like force a reboot (of course the app would need some built in access controls), etc.

Here in Thailand, we can drive around in the country side in our car, without direct Internet access, and can push a button on our iPhone to get remote server stats via BLE.

.... and I built the prototype in a very short period of time.

I'm not trying to advocate BLE or NB-IoT (or even the Arduino, per se; instead this test just demonstrates one possibility of nearly infinite possibilities for creative makers.

For this app, I think I'll create a few more "mini-apps" via the push button command console (and then post the sketch) and move on to testing another Arduino / shield module.

Arduino Project:  iPhone to HM-10 BLE to NB-IoT Shield to NB-IoT Network to Internet to Linux Server-img_9093jpg
# 10  
Added "Get Disk Space" button for the main boot disk, in this Linux Ubuntu case, MD2:

Arduino Project:  iPhone to HM-10 BLE to NB-IoT Shield to NB-IoT Network to Internet to Linux Server-img_9095jpg


Arduino Project:  iPhone to HM-10 BLE to NB-IoT Shield to NB-IoT Network to Internet to Linux Server-img_9094jpg
# 11  
I'm "done for now" adding "mini-apps" to this demo app, with five little "mini-stats":

Of course, since the NB-IoT network is all UDP based, it would take considerable more coding to insure this kind of app is "truly reliable".

Arduino Project:  iPhone to HM-10 BLE to NB-IoT Shield to NB-IoT Network to Internet to Linux Server-img_9096jpg


Arduino Project:  iPhone to HM-10 BLE to NB-IoT Shield to NB-IoT Network to Internet to Linux Server-img_9097jpg
# 12  
Here is the current "work in progress" rough draft of the Arduino UNO sketch for this demo / test.

Please free free to improve to code and repost your improvements back and use as you wish, free as a bird.

Code:
/*
  Arduino Project: iPhone to HM-10 BLE to NB-IoT Shield to NB-IoT Network to Internet to Linux Server
  Work in Progress by Neo version 0.01 Jan 2020
  Currently does not receive data from UDP server when doBLE() is active
  Comments welcome.
*/

#include <SoftwareSerial.h>
#include <ArduinoBlue.h>
#include "AIS_NB_BC95.h"
#define NBIOT true
#define BLE true
#define DEBUG2 true
#define ENABLE_BLE_IN_LOOP true
#define ENABLE_NBIOT_PING false

String apnName = "ble.nms";
String serverIP = "YOUR.IP.ADDR.HERE"; // Your Server IP
String serverPort = "YOUR_PORT";       // Your Server Port

String udpData = apnName;

AIS_NB_BC95 AISnb;

const long interval = 20000; //millisecond
unsigned long previousMillis = 0;

long cnt = 0;

const unsigned long BAUD_RATE = 9600;

// The bluetooth tx and rx pins must be supported by software serial.
// Visit https://www.arduino.cc/en/Reference/SoftwareSerial for unsupported pins.
// Bluetooth TX -> Arduino UNO D3 was D8
const int BLUETOOTH_TX = 3;
// Bluetooth RX -> Arduino UNO D4 was D7
const int BLUETOOTH_RX = 2;
int prevThrottle = 49;
int prevSteering = 49;
int throttle, steering, sliderVal, button, sliderId;

SoftwareSerial bluetooth(BLUETOOTH_TX, BLUETOOTH_RX);
ArduinoBlue phone(bluetooth); // pass reference of bluetooth object to ArduinoBlue constructor

void setup()
{
    // Start serial communications.
    // The baud rate must be the same for both the serial and the bluetooth.
    Serial.begin(BAUD_RATE);

    if (BLE)
    {
        if (NBIOT)
        {
            delay(10000);
        }
        bluetooth.begin(BAUD_RATE);
        delay(100);

        Serial.println("arduino ble setup complete\n");
        phone.sendMessage("Arduino setup complete");
    }

    if (NBIOT)
    {
        AISnb.debug = true;
        if (DEBUG2)
            Serial.println("NBIOT SETUP START\n");
        AISnb.setupDevice(serverPort);
        if (DEBUG2)
            Serial.println("NBIOT SETUP GET DEVICE IP\n");
        String ip1 = AISnb.getDeviceIP();
        delay(1000);
        if (DEBUG2)
            Serial.println("NBIOT SETUP GET DEVICE IP\n");
        pingRESP pingR = AISnb.pingIP(serverIP);
        previousMillis = millis();
        if (DEBUG2)
            Serial.println("NBIOT SETUP COMPLETE\n");
        if (BLE)
        {
            phone.sendMessage("NBIOT Setup Complete");
        }
    }
}

// Put your main code here, to run repeatedly:
void loop()
{
    if (BLE and ENABLE_BLE_IN_LOOP)
    {
        doBLE();
    }

    if (NBIOT)
    {

        doNBIOT();
    }
}

void doBLE()
{
    // ID of the button pressed pressed.
    button = phone.getButton();
    String msg = "";
    // Returns the text data sent from the phone.
    // After it returns the latest data, empty string "" is sent in subsequent.
    // calls until text data is sent again.
    String str = phone.getText();

    // Throttle and steering values go from 0 to 99.
    // When throttle and steering values are at 99/2 = 49, the joystick is at center.
    throttle = phone.getThrottle();
    steering = phone.getSteering();

    // ID of the slider moved.
    sliderId = phone.getSliderId();

    // Slider value goes from 0 to 200.
    sliderVal = phone.getSliderVal();

    // Display button data whenever its pressed.
    if (button != -1)
    {
        Serial.print("Button: ");
        Serial.println(button);
        if (button == 5)
        {
            msg = "GetLoadAvgs";
        }
        else if (button == 6)
        {
            msg = "GetDiskSpace";
        }
        else if (button == 7)
        {
            msg = "GetApache2Procs";
        }
        else if (button == 8)
        {
            msg = "GetLastBackup";
        }
        else if (button == 9)
        {
            msg = "GetSSHDStatus";
        }
        else
        {
            //phone.sendMessage("Button: " + String(button));
            msg = "Button: " + String(button);
        }
        UDPSend udp2 = AISnb.sendUDPmsgStr(serverIP, serverPort, msg);
        Serial.println("You sent to NB-IOT: " + msg);
    }

    // Display slider data when slider moves
    if (sliderId != -1)
    {
        Serial.print("Slider ID: ");
        Serial.print(sliderId);
        Serial.print("\tValue: ");
        Serial.println(sliderVal);
    }

    // Display throttle and steering data if steering or throttle value is changed
    if (prevThrottle != throttle || prevSteering != steering)
    {
        Serial.print("Throttle: ");
        Serial.print(throttle);
        Serial.print("\tSteering: ");
        Serial.println(steering);
        prevThrottle = throttle;
        prevSteering = steering;
    }

    // If a text from the phone was sent print it to the serial monitor
    if (str != "")
    {
        Serial.println(str);
    }

    // Send string from serial command line to the phone. This will alert the user.
    if (Serial.available())
    {
        Serial.write("send: ");
        String str = Serial.readString();
        phone.sendMessage(str); // phone.sendMessage(str) sends the text to the phone.
        Serial.print(str);
        Serial.write('\n');
    }
}

void doNBIOT()
{
    unsigned long currentMillis = millis();
    if (currentMillis - previousMillis >= interval and ENABLE_NBIOT_PING)
    {
        cnt++;
        Serial.println("Ping Count: " + String(cnt) + "\n");
        // Send data in String
        UDPSend udp0 = AISnb.sendUDPmsgStr(serverIP, serverPort, "Ping Count: " + String(cnt));
        UDPSend udp = AISnb.sendUDPmsgStr(serverIP, serverPort, udpData + " " + String(cnt));

        previousMillis = currentMillis;
    }
    UDPReceive resp = AISnb.waitResponse();
    if (resp.data.length() > 0)
    {
        String reply = AISnb.toString(resp.data);
        reply.replace(":", "\n");
        phone.sendMessage(reply);
        Serial.println("Received by NB-IOT sketch: " + resp.data);
        Serial.println('\n');
    }
}

# 13  
Here is some very preliminary Python UDP server code this test / demo application.

Please feel free to clean it up and repost. Use it anyway you wish.

I know the Python code a mess, so please clean it up and post your "cleaner, nicer, prettier" code back in this thread if the spirit moves you to do so.

This is mainly a "debugging and testing script" and it NOT intended for production use at all.

FOR DEMO AND TESTING PURPOSES ONLY

Code:
#!/usr/bin/python3
"""
NB-IoT Test Code with ArduinoBlue
Listens on a port for UDP, simple authentication, echo back with unix time
Version 0.15 29 January 2020
Neo wwww.unix.com
Use as you wish.   If you improve it, please post back.
"""
import socket
import sys
import time
import subprocess

# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# sock.setblocking(False)
port = 1234  # your port number here
append = str(time.time())
file = "/root/debug/arduino/nbiot"+append+".log"
f = open(file, "w")
# Bind the socket to the port
server_address = ('your.server.com', port)
print >>sys.stderr, 'starting up on %s port %s' % server_address
f.write('starting up on %s port %s' % server_address)
sock.bind(server_address)
password = "my_simple_password\n"
authenticated = True
receivepw = True
lastsent = 0

while True:
    print >>sys.stderr, '\nwaiting to receive message'
    f.write('\nwaiting to receive message')
   now = time.time()

    data, address = sock.recvfrom(4096)
    print >>sys.stderr, str(time.time())+': received %s bytes from %s' % (len(data), address)
    f.write(str(time.time())+': received %s bytes from %s' % (len(data), address))
    stuff = str(time.time())+ ": "+ data
    print >>sys.stderr, stuff
    f.write(stuff)

    # override simple authentication  for now
    if data:
        lastsent = time.time()
        if authenticated == False and receivepw == False:
            sent = sock.sendto("Password: ", address)
            receivepw = True
        elif receivepw == True and authenticated == False:
            if data == password:
                sent = sock.sendto("Authenticated\n", address)
                authenticated = True
            else:
                sent = sock.sendto("Password:\n", address)
            print >>sys.stderr, 'a: sent %s bytes back to %s' % (sent, address)
            f.write('a: sent %s bytes back to %s' % (sent, address))
        elif authenticated == True:   #set to True all the time passing the auth code
            if '86940503122XXXXXXX' not in data:
                print >>sys.stderr, str(time.time())+': received %s' % (data)
                f.write(str(time.time())+':received %s' % (data))
                message = data
                # received = "You sent: " + data
                # sent = sock.sendto(received, address)
                # data = time.time()
               
                # data = "Unix Time: " + str(data)+"\n"
                # sent = sock.sendto(data, address)
                # sensor = sock.sendto("Sensor Data", address)
                # print >>sys.stderr, str(time.time())+': sent %s bytes back to %s' % (sent, address)
                # f.write(str(time.time())+': sent %s bytes back to %s' % (sent, address))
                doit = False
                if 'GetLoadAvgs' in message:
                    replydata = "Server Load Averages:"+subprocess.check_output(['cat', '/proc/loadavg'])
                    doit = True
                elif 'GetDiskSpace' in message:
                    tmp = subprocess.check_output("df | grep md2", shell=True)
                    tmp = tmp.split()
                    replydata ="MD2 Disk Space:"+tmp[4]
                    doit = True
                elif 'GetApache2Procs' in message:
                    tmp = subprocess.check_output("ps aux | grep apache2 | grep -v grep| wc -l", shell=True)
                    replydata ="Apache2 Processes:"+tmp
                    doit = True
                elif 'GetLastBackup' in message:
                    tmp = subprocess.check_output("ls -l /data/dumps | grep main | tail -1", shell=True)
                    tmp = tmp.split(".")
                    tmp = tmp[0].split("_")
                    replydata ="Last Backup:"+tmp[2]
                    doit = True
                elif 'GetSSHDStatus' in message:
                    tmp = subprocess.check_output("ps aux | grep sshd | grep sbin", shell=True)
                    if tmp > 0:
                        sshd = "UP"
                    else:
                        sshd = "DOWN"
                    replydata ="SSHD Status:"+sshd
                    doit = True
                if doit == True:
                    load = sock.sendto(replydata, address)
                    print >>sys.stderr, str(time.time())+': sent %s bytes back to %s message %s' % (load,address, replydata)
                    f.write(str(time.time())+': sent %s bytes back to %s message %s' % (load, address,replydata))
            else:
                received = "Rejected: Unauthorized EMEI"
                sent = sock.sendto(received, address)
        else:
            sent = sock.sendto("Error\n", address)
            print >>sys.stderr, str(time.time())+' : sent %s bytes back to %s' % (sent, address)
            f.write(str(time.time())+' : sent %s bytes back to %s' % (sent, address))

This User Gave Thanks to Neo For This Post:
# 14  
Update:

I've posted the high level overview, the schematic, links, a lot of pictures, screenshots, discussion, and all my testing /working code (for testing purposes only).

So, for now I'm going to call this Arduino UNO project / proof-of-concept "good enough" and move on to testing a different Ardunio module or shield.

If you like this demo or find anything useful, I'm happy to hear about it. Please consider this demo "like an online notebook" of my testing and my results. Raw, unpolished, the "real deal", and no artificial sweeteners added Smilie I tend to have a low attention span, so when I get a proof-of-concept like this up and running (and prove it works), even if the final results are not "polished", I then want to "call it good enough" and quickly move on to the next project.

If you want to improve the code and post your code back here, or elsewhere, that is even better. Share and share alike.

Either way, you are free to share and use any or all the the content in this test / demo (not designed nor created for production code); and so for now, this concludes:

Arduino Project: iPhone to HM-10 BLE to NB-IoT Shield to NB-IoT Network to Internet to Linux Server

Thanks!
These 2 Users Gave Thanks to Neo For This Post:

Previous Thread | Next Thread
Thread Tools Search this Thread
Search this Thread:
Advanced Search

Test Your Knowledge in Computers #617
Difficulty: Medium
If you place two string literals side by side, they are automatically concatenated by Python.
True or False?

10 More Discussions You Might Find Interesting

1. Hardware

Arduino Robot Tank Project

Normally I'm not into kits, but I thought my wife would enjoy this one since she is a big fan of robots and droids on StarWars! We are done with the basic mechanical assembly and starting on the electronics assembly today. The robot's "brain" consists of three levels. The Arduino board, on... (5 Replies)
Discussion started by: Neo
5 Replies

2. Programming

Wuhan Coronavirus Status App for China - Rapid Prototype using MQTT and the IoT OnOff IOS App

With a little bit of work, was able to build a nice "Wuhan Coronavirus Status" app using MQTT and the IoT-OnOff app. More on this technique here: ESP32 (ESP-WROOM-32) as an MQTT Client Subscribed to Linux Server Load Average Messages The result turned out nice, I think. I like the look and... (10 Replies)
Discussion started by: Neo
10 Replies

3. Programming

Basic Arduino UNO Bluetooth Testing with the BLE 4.0 (CC2541, MLT-BT04 IC)

Here is a sketch to do basic testing for the Arduino UNO and the MLT-BT04. This BLE module works with IOS (iPhone) and I'll add some details on my IOS testing with an iPhone in a follow-up post. For now, here is the basic BLE (HM-10) sketch for the Arduino UNO: /* Arduino test-code... (7 Replies)
Discussion started by: Neo
7 Replies

4. Programming

Elecrow GSM/GPRS/EDGE SIM5360E 3G Shield for Arduino

Normally I have very good experiences buying from AliExpress, but in this case with Elecrow, I'm disappointed. After confirming with Elecrow on AliExpress that their Elecrow GSM/GPRS/EDGE SIM5360E 3G Shield for Arduino would work with 3G SIM cards in Thailand, I purchased one. My plan was to... (1 Reply)
Discussion started by: Neo
1 Replies

5. Programming

NB-IoT Arduino Shield from AIS (Thailand) First Impressions

Today I received my NB-IoT Arduino Shield for AIS (Thailand). Here is a "pinout" photo of the shield. My shield looks just like the one above, for the most part. I'll post another photo of the actual device later. When I received the shield in the mail, I went immediately to a local... (8 Replies)
Discussion started by: Neo
8 Replies

6. Programming

Arduino Project with NB-IoT (3GPP) and LoRa / LoRaWAN

My favorite projects are always related to the "latest" tech in command and control, networking and network communications. This Elecrow GSM/GPRS/EDGE SIM5360E 3G Shield seems to be the "latest and the greatest" as far as 3G and GPS, as far as I can see so far, but I has it drawbacks for sure.... (6 Replies)
Discussion started by: Neo
6 Replies

7. Programming

Arduino-cli - Uploading to Unknown Chinese Arduino Boards using the Arduino Command Line Interface

In my further exploration of Arduino, today I decided to install the arduino-cli on my mac today. https://github.com/arduino/arduino-cli I followed the instructions for macOS but when I got to this part: arduino-cli board list I got the dreaded "Unknown" Fully Qualified Board Name... (1 Reply)
Discussion started by: Neo
1 Replies

8. IP Networking

Can not access Linux server over the Internet

hi i have linux server connected to internet through a switch/router. i have opened a port on the router and i am able to connect to the server if iptables is off. but when it is on i cant. i want to create a rule in iptables so that it accepts packets coming from a particular datacard. it... (7 Replies)
Discussion started by: u.n.i.x
7 Replies

9. IP Networking

can i force connecting to local web server via internet network ?

Hello all this is general question , if i have web server installed in my local pc and i have client that connecting to that web server can i force it always to go via the internet network ? the reason im asking is .. that im noticed when i close my internet connection i still can connect to my... (2 Replies)
Discussion started by: umen
2 Replies

10. UNIX for Dummies Questions & Answers

Linux for an internet server to an ISP

I just moved away from a T3 line back to a dial up I just wanted to know would a P200 with 64meg and a 4 gig hard drive be ok for a linux server for an additional 3 pcs all running win98. I will be dialing into an isp using a 56k v90 modem. Any support or help will be great. (3 Replies)
Discussion started by: izrailov
3 Replies

Featured Tech Videos