Share Internet connection on Arduino

Discussion in 'Linux Ubuntu' started by brrmatteo, Feb 19, 2014.

  1. brrmatteo

    brrmatteo New Member

    Joined:
    Dec 11, 2013
    Messages:
    3
    Likes Received:
    0
    Can I share the Udoo's internet connection to SAM3x Arduino due processor? Or I must use a ethernet shield?
     
  2. delba

    delba Administrator Staff Member

    Joined:
    May 8, 2013
    Messages:
    1,064
    Likes Received:
    9
    No, unfortunately you can't. You must use an ethernet shield.
     
  3. hillcz

    hillcz Member

    Joined:
    Oct 3, 2013
    Messages:
    72
    Likes Received:
    1
    Hi directly no.
    But I use the script in python. Deamon is listening on any port and transfer command to the COM port shared with SAM x.
     
  4. brrmatteo

    brrmatteo New Member

    Joined:
    Dec 11, 2013
    Messages:
    3
    Likes Received:
    0
    Can you post the code please?
     
  5. hillcz

    hillcz Member

    Joined:
    Oct 3, 2013
    Messages:
    72
    Likes Received:
    1
    Code:
    #!/usr/bin/env python3
    # script by Patrik Hora
    
    #IMPORT LIB
    import sys
    import multiprocessing
    from time import *
    import serial
    import configparser
    import os
    import json
    import socket, ssl
    
    
    #READ CONFIG FILE
    
    config = configparser.ConfigParser()
    config.read('/etc/hato/config.ini')
    
    #VAR
    
    Ardu_ID=config['Arduino']['ID']
    line = ""
    jobs = []
    arduino_blocked = multiprocessing.Value('b', 0)
    arduino_cmd_list =('Ident','Report','Set:')
    linux_cmd_list = ('Cron','ShutDown', 'Restart')
    
    try:
        
        f = open("/run/hatodaemon.pid", "w")
        try:
            f.write(str(os.getpid())) # PID
        finally:
            f.close()
    except IOError:
        pass
    
    
    #LINUX CMD
    
    def linux_cmd(cmd):
        if cmd.startswith(linux_cmd_list):
            if cmd.startswith('ShutDown'):
                os.system("shutdown -h now")
            if cmd.startswith('Restart'):
                os.system("reboot")
            if cmd.startswith('Cron'):
                os.system('crontab -l | grep -v "WASH" | { cat; echo "15 0 * * * /etc/hato/socket_client.py  \"Set:TS03:1200;\" #WASH"; } | crontab')
            
        
    
    
    #COMM WITH ARDUINO
    
    def arduino(cmd):
        timeout = time() + 5
        while arduino_blocked.value==1 and timeout > time():
            pass
        arduino_blocked.value = 1
    
        try:
            serial_port = serial.Serial('/dev/ttymxc3', baudrate=115200, timeout=3)
        except serial.SerialException as e:
            print("could not open serial port '{}': {}".format(com_port, e))
    
        serial_port.write(cmd.encode('utf-8'))
    
        lines = []
        while True:
            try:
               line = serial_port.readline()
            except:
                tb = sys.exc_info()
                print(tb)
                
            timeout = time() + 0.1
            while not serial_port.inWaiting() and timeout > time():
                pass
            if not serial_port.inWaiting():
                break 
    
        serial_port.close()
        arduino_blocked.value = 0
        return str(line.decode('ascii').rstrip())
    
    ## SOCKET ON PORT 15000
    
    bindsocket = socket.socket()
    bindsocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    bindsocket.bind(('', 15000))
    bindsocket.listen(5)
    
    def do_something(connstream, data):
        try:
    
            f = open("/etc/hato/log/hatodaemon.log", "a")
            try:
                f.write(str(time())) # PID
                f.write(str(data)) # PID
                f.write("\n") # PID
            finally:
                f.close()
        except IOError:
            pass
        tmp=(data).decode('utf-8')
        if tmp.startswith(arduino_cmd_list):
            txt=arduino(tmp)
            
        if tmp.startswith(linux_cmd_list):
            txt=linux_cmd(tmp)
            
    
        connstream.sendall(txt.encode('utf-8'))
    
    def socket_instance():
        try:
            timeout = time() + 2
            connstream = ssl.wrap_socket(newsocket,server_side=True,certfile="/etc/hato/cert.pem",ca_certs="/etc/hato/cert.pem",ssl_version=ssl.PROTOCOL_TLSv1,cert_reqs=ssl.CERT_REQUIRED)
                
        except:
            tb = sys.exc_info()
            print(tb)
        else:
            deal_with_client(connstream)
        finally:
            connstream.shutdown(socket.SHUT_RDWR)
            connstream.close()      
    
    
    
    
    
    def deal_with_client(connstream):
        data = connstream.recv(1024)
        while data:
            if not do_something(connstream, data):
                break
            data = connstream.recv(1024)
            print(data)
    
    
    
    
    while True:
            try:        
               newsocket, fromaddr = bindsocket.accept()
            except:
               tb = sys.exc_info()
               print(tb)
            else:      
                p = multiprocessing.Process(target=socket_instance)
                jobs.append(p)
                p.start()
    
    Code:
    function Connect_to_unit ($UID,$CMD,$IP) {
    
                $sslPem = "/cert/$UID.pem";
    
                $streamContext = stream_context_create();
    
                stream_context_set_option($streamContext, 'ssl', 'local_cert', dirname(__FILE__) . '/' . $sslPem);
    
                $server = stream_socket_client("ssl://$IP:15000", $error, $errorString, 5, STREAM_CLIENT_CONNECT, $streamContext);
    
                stream_set_timeout($server, 10);
    
                if (!$server) {
    
                    echo "$errorString ($error, )<br />\n";
    
                    return ("ERR");
    
                } else {
    
    
                    fwrite($server, $CMD);
    
                    $buffer = fgets($server, 1024);
                    $JsonData=json_decode($buffer);
                    if ($buffer === null && json_last_error() !== JSON_ERROR_NONE) {    
                        fwrite($server, 'ERR');
                        fclose ($server);
                        die('ERR');
                        }
                    fwrite($server, 'OK');
                        fclose ($server);                
                    
                    return($JsonData);
                }
            }
    
     

Share This Page