Netduino home hardware projects downloads community

Jump to content


The Netduino forums have been replaced by new forums at community.wildernesslabs.co. This site has been preserved for archival purposes only and the ability to make new accounts or posts has been turned off.

Serkan Polat's Content

There have been 17 items by Serkan Polat (Search limited from 19-April 23)


By content type

See this member's

Sort by                Order  

#25663 I2C configuration help needed! :)

Posted by Serkan Polat on 18 March 2012 - 01:02 AM in Visual Studio

today i am gonna try it.. we had some problems with the i2c and rtc.. there is a problem with smd rtc mcu.. :)) after solving it.. i will try it.. thank you for the code sharing :))) i will tell you the results when i finish them..



#25520 I2C configuration help needed! :)

Posted by Serkan Polat on 14 March 2012 - 09:07 PM in Visual Studio

Yes exactly, but our system also support shoutcast, mp3 streaming and playing downloaded files. Currently we have 1.500 customers :) Our managment system prepares filelist and sends it over webservices, the n+ device stores this data on sqlite, checks date and time and download files., then loops the files.. So far, we tried many systems, embedded linux distros, damn small linux, wince, embedded win7 etc.. İ rewrite system more then 20 times for better performance and memory usage.. At last i wrote compressor and limiter to stabilize the volume level.. Now i want to do it with vs1053b, i will get the vumeter valus and realtime increase or decrease volume.. Do you kniw how to get vumeter values? Ps: i got you prv message..



#25504 I2C configuration help needed! :)

Posted by Serkan Polat on 14 March 2012 - 03:16 PM in Visual Studio

No :) we will give free to our customers when they get our service for 1 year :)) Normally the most problem part is the hardware cost in our business, we use atom based ultra thin pc and windows.. İt cost alot.. Our customers dont want to make that investment.. Thats why we are teing to make our own hardware



#25498 I2C configuration help needed! :)

Posted by Serkan Polat on 14 March 2012 - 12:50 PM in Visual Studio

yes thats the one i bought 200 piece.. 1.500 pieces are on the way.. yeah there are hundreds of them.. all have skype and live chat.. so you can ask whatever you want.. they reply immediately.. but when you want some feature they all say "yes yes we can do it" but not :))) , some of them made me crazy.. :) thank you very much.. i am not the hardware guru.. my friend "sevan" is the pcb designer.. i am just the guy that say "use vs1053b, atmel cpu , these features etc.." he made it all.. i coded the software.. soldering of the final pcb is handmade :) he was like an artist.. :)) if you can send the patch code and if you know how to implement a vumeter, that would be cool.. i am very tired of reading mcu documentations.. :)) my expertise is on gesture, pattern, object recognition and multimedia development on pc.. not micro controller developer :))



#25495 I2C configuration help needed! :)

Posted by Serkan Polat on 14 March 2012 - 11:56 AM in Visual Studio

by the way, i have 4-5 different android devices purchased before.. i opened all of them :)) what i see is, there is one android device board on the top and all manufacturers/assemblers made their expansion units (hdmi out, usb, vga, sdcard slot, wireless etc.. ) so the outer plastic box differs from one to another.. but all uses same kind of main android boards.. cortext, Amlogic8726 etc cpus.. actual mainboard supports 4 usb + 1 host usb but some manufacturers removes some usb ports, vga out , even rtc battery to reduce price of the device :)) also the wireless module is 7-8 usd and that is optional when buying.. they solder it inside the device.. all those devices can use usb mouse and keyboard.. the first 2 device i ordered did not have rtc battery.. the third one has it but the user interface was not good and it heats much.. the fourth one was perfect (the picture i send).. the user interface etc works incredible fast.. also the remote controller is more complex then the others.. all others have credit card size remote controlers and does not work properly.. anyway this device is amazing.. forexample i put a iso and img dvd file, just clicked it and it mounted image file automatically and started to play.. i tried h264 1080p dts videos.. normally my lg and samsung and also WDTV device can not play dts sounds.. but this device played it perfectly on analog output..



#25494 I2C configuration help needed! :)

Posted by Serkan Polat on 14 March 2012 - 11:42 AM in Visual Studio

there are hundreds of different android tvbox devices on alibaba.. also you can directly purchase from aliexpress.com

we made it from scratch , we read the atmel and netduino plus documentations and schematics..
also as you see, we replaced some components from original design....

yes the crstal and battery is for rtc.. as you know N+ does not have rtc backup battery..
our system uses scheduled playlists , so without internet we have to know what the time is..
thats why we used battery..

here are the photos of our development phase device while coding:
Posted Image
Posted Image

and this is the final device's schematic:
Posted Image



#25492 I2C configuration help needed! :)

Posted by Serkan Polat on 14 March 2012 - 10:52 AM in Visual Studio

check these links:
http://www.alibaba.c...Android_TV.html
http://www.alibaba.c...ndroid.html?s=p

also i can directly send you the features... i already bought 200 piece.. :))
they made custom housing, custom logo , custom boot logo , custom boot animations, menu items etc..
even the cartoon box is already customized..

here is the picture of it:
Posted Image



also here is our custom N+ device :
Posted Image
Posted Image
Posted Image



#25483 I2C configuration help needed! :)

Posted by Serkan Polat on 14 March 2012 - 12:49 AM in Visual Studio

On android i used monodroid , this is c# for android Also i used basic4android and it is really fast.. i also used java, but for rapid development i suggest basic4android.. İt has visual basic syntax... And has almost everything.. Sorry for text mistakes, i am writing these with iphone keyboard :))



#25482 I2C configuration help needed! :)

Posted by Serkan Polat on 14 March 2012 - 12:46 AM in Visual Studio

For the vs1053b, the patch is about to patch chip for vumeter and some other fearures İn vs1053d it is already patched.. But i coludnt patch the vs1053b, if you know how to do it , please teach me :) For the network: İ also have ghi panda and domino devices and ethernet shield, it is slower than n+ but n+ eats many memory area for tcpip stack İ wrote http and ftp classes from stratch and still the speed is too bad for downloading mp3 or such things. İt says it is 10/100 but it is not :) Also i have android based arm9 and some other mcus And i have android tv box devices.. The interesting part is : The n+ has 55mhz, 30-40 km ram , 40-80kb/s download speed, no usb etc, with vs1053 my device will cost near 50 usd The android tvbox has: 1 ghz cpu, 512 mb ram, 4gb nand storage, ethernet, wireless, 4 usb, sdcard, hdmi output, analog and digital audio, composite video output Remote controller, full operating system, mali 400 gpu , mkv and h264 native decoding, full enclosure Guess what? Finished device is 50 usd... Unfortunately i found them 2 weeks ago, but i was working on my own n+ more then 2 months.... i want to make this device work, then i will return to android device....



#25481 I2C configuration help needed! :)

Posted by Serkan Polat on 14 March 2012 - 12:31 AM in Visual Studio

SDA -> PA14 //analog pin 4 SCL -> PA15 //analog pin 5 These are the default pins of n+ pa14 is the pin in mcu's schematics But i want to use SCL->PA11 SDA->PA10 For I2C AT91SAM7x512 document and schematics says that i can use it The n+ sdk maps pa14 to pin4 and pa15 to pin5 Those pin4 and pin5 are enums and private I2CDevice clock = new I2CDevice(new I2CDevice.Configuration(I2CAddress, I2CClockRateKhz)); I2CDevice object default maps to them, what i want to kniw, is it possible to map them to my pin configuration



#25462 I2C configuration help needed! :)

Posted by Serkan Polat on 13 March 2012 - 06:03 PM in Visual Studio

Hmm so how can we set our pin configuration according to our settings? For the vs1053b, it works very well but i have some notes about it.. İf you play wma after mp3 , you will get silence.. Also if you play mp3 after wma you will also get silence.. But you can play mp3 files after and after.. Also still i cant get audio level (for vumeter purposes) .. But the vs1053b documentation taljs about a patch.. Still i am not able to do it.. :)) i also have many experiences about it.. Also n+ network speed is too slow.. Max dl rate is 40kb/s



#25452 I2C configuration help needed! :)

Posted by Serkan Polat on 13 March 2012 - 12:35 PM in Visual Studio

actually :) yes and no, we use N+ architecture but not itself.. we redesigned our pcb for our needs and we used N+ architecture.. we added vs1053b, RTC, 2 lines lcd, 2 extra buttons and some couple things.. (my company distributes legal music to chain stores, shopping malls etc..) while we were checking the documentation, we saw that FSA2257Mux is hard to find in our country market.. we dont need any muxer for muxing between analog and digital. so we removed it and directly connected to PA11 and PA10 but we couldnt find I2CAddress adress related to it.. thats why i am asking :))



#25421 I2C configuration help needed! :)

Posted by Serkan Polat on 12 March 2012 - 08:35 PM in Visual Studio

hi all,
i am using net fw 4.2.0.0
using ds1307 for RTC,
based on AT91SAM7x512 mcu datasheet i used my wire configuration as:
SCL->PA11
SDA->PA10

what will be I2CAddress ?
currently i am using 0x68 for it (not working), here is my code sample:
private const int I2CAddress = 0x68;
        private const int I2CTimeout = 1000;
        private const int I2CClockRateKhz = 100;
private I2CDevice clock = new I2CDevice(new I2CDevice.Configuration(I2CAddress, I2CClockRateKhz));




is it a must for i2c
SDA -> PA14 //analog pin 4
SCL -> PA15 //analog pin 5

?



#21901 So how does the SD card stuff work anyway?

Posted by Serkan Polat on 20 December 2011 - 09:47 AM in Netduino 2 (and Netduino 1)

Hi, I am having the same issues. I was curious if you had managed to make yours work.



if you still looking for an answer, here is the code i used:


vs1053 class (sparkfun's)
using System;
using System.IO;
using Microsoft.SPOT.Hardware;
using System.Threading;
using SecretLabs.NETMF.Hardware.NetduinoPlus;
using System.Runtime.CompilerServices;

namespace smg.Drivers.Music
{
    public static class Vs1053
    {
        // GPIO ports:
        static private OutputPort _reset;
        static private InterruptPort _dreq;

        const Cpu.Pin PinBsync = Pins.GPIO_PIN_D2;
        const Cpu.Pin PinDreq = Pins.GPIO_PIN_D3;
        const Cpu.Pin PinReset = Pins.GPIO_PIN_D6;  // NOTE: This doesn't map to an actual pin
        const Cpu.Pin PinCs = Pins.GPIO_PIN_D9;

        // Define SPI Configuration for VS1053 MP3 decoder:
        static private readonly SPI.Configuration DataConfig = new SPI.Configuration(PinBsync, false, 0, 0, false, true, 3000, SPI.SPI_module.SPI1);
        static private readonly SPI.Configuration CmdConfig = new SPI.Configuration(PinCs, false, 0, 0, false, true, 3000, SPI.SPI_module.SPI1);
        static private SPI _spi;

        // Registers:
        const int RegisterSciMode = 0x00;
        const int RegisterSciVol = 0xFF;
        const int RegisterSciClockf = 0x03;

        public static readonly int BufferSize = 256;
        private const ushort SciMode = 0x880;  // SM_SDINEW (default) + SM_EARSPEAKER_HI

        static private bool _isInitialized;
        static private readonly byte[] ReadBuffer = new byte[BufferSize];
        static private readonly byte[] CmdBuffer = new byte[4];

        static private readonly AutoResetEvent AutoResetEvent = new AutoResetEvent(false);


        private static bool _initialized;       // Pins created succesfully when true
        private static int _duration = -1;      // Duration of file playing (in seconds)
        private static int _position = -1;      // Current Play Position (in seconds)
        private static object _source;        // Filename or Resource Reference
        private static bool _busy = false;      // Playing a file when true
        private static bool _pause = false;     // Paused when true
        private static long _rawSize = -1;
        private static long _readSoFar = -1;
        private static int _bitrate = 0;
        private static int _mpegLayer = 0;
        private static bool _stop = false;
        private static int _lastPos = -1;
        static private byte[] block = new byte[32];
        static private byte[] cmdBuffer = new byte[4];
        private static bool _cancelMusic = false;

        public static event musicFinished onMusicFinished;
        public delegate void musicFinished();


        public static bool CancelMusic { set { _cancelMusic = value; } get { return _cancelMusic; } }

        public static void Initialize()
        {
            if (_isInitialized)
                Shutdown();

            _spi = new SPI(CmdConfig);
            _reset = new OutputPort(PinReset, true);
            _dreq = new InterruptPort(PinDreq, false, Port.ResistorMode.PullUp, Port.InterruptMode.InterruptEdgeBoth);
            _dreq.OnInterrupt += _dreq_OnInterrupt;

            _isInitialized = true;

            Reset();

            CommandWrite(RegisterSciMode, SciMode | (1 << 2));
            CommandWrite(RegisterSciClockf, 7 << 13);
            CommandWrite(RegisterSciVol, 0xFEFE);

            _spi.Config = DataConfig;
        }

        private static void _dreq_OnInterrupt(uint port, uint state, DateTime time)
        {
            if (state == 0)
            {
                AutoResetEvent.Set();
            }
            else
            {
                AutoResetEvent.WaitOne();
            }
            _dreq.ClearInterrupt();
        }

        private static void Reset()
        {
            _reset.Write(false);
            Thread.Sleep(1);
            _reset.Write(true);
            Thread.Sleep(1);
        }

        static private void CommandWrite(byte address, ushort data)
        {
            CmdBuffer[0] = 0x02;
            CmdBuffer[1] = address;
            CmdBuffer[2] = (byte)(data >> 8);
            CmdBuffer[3] = (byte)data;

            _spi.Write(CmdBuffer);
        }

        static private ushort CommandRead(byte address)
        {
            CmdBuffer[0] = 0x03;
            CmdBuffer[1] = address;
            CmdBuffer[2] = 0;
            CmdBuffer[3] = 0;

            _spi.WriteRead(CmdBuffer, CmdBuffer, 2);

            ushort command = CmdBuffer[0];
            if (command < 100)
            {
                throw new ArgumentOutOfRangeException("volume");
            }
            //SetVolumePercent(volume, volume);
            return command;
        }

        public static void SetVolumePercent(int leftChannel, int rightChannel)
        {
            if (leftChannel < 0 || leftChannel > 100)
                throw new ArgumentOutOfRangeException("leftChannel");
            if (rightChannel < 0 || rightChannel > 100)
                throw new ArgumentOutOfRangeException("rightChannel");

            // TODO: Invert decibel value, divide by percent, call SetVolume(ushort leftChannel, ushort rightChannel)
        }

        public static void SetVolume(ushort bothChannels)
        {
            CommandWrite(RegisterSciVol, bothChannels);  // TODO: This doesn't work outside the Initialize() method
        }

        public static void SetVolume(ushort leftChannel, ushort rightChannel)
        {
            SetVolume((ushort)(leftChannel * 256 + rightChannel)); // TODO: Verify no loss of fidelity
        }

        public static void SendData(FileStream fileStream)
        {
            var size = fileStream.Length - fileStream.Length % BufferSize;
            for (var i = 0; i < size; i += BufferSize)
            {
                fileStream.Read(ReadBuffer, 0, BufferSize);

                _spi.Write(ReadBuffer);
                while (_dreq.Read() == false) { Thread.Sleep(1); }

                if (_cancelMusic) { break; }
            }
        }

        public static void Shutdown()
        {
            if (!_isInitialized) return;

            Reset();

            _spi.Dispose();
            _reset.Dispose();
            _dreq.Dispose();

            _isInitialized = false;
        }

        [MethodImpl(MethodImplOptions.Synchronized)]
        public static void PlayLoop()
        {
            byte[] b;

            _cancelMusic = false;
            _busy = true;
            _stop = false;
            _readSoFar = 0;
            _lastPos = -1;

            if (_source is string)
            {
                FileStream iFile = new FileStream((string)_source, FileMode.Open, FileAccess.Read);
                _rawSize = iFile.Length;
                b = new byte[2 * 1024];
                int count = iFile.Read(b, 0, b.Length);
                while (count > 0)
                {
                    SendData(B);
                    count = iFile.Read(b, 0, b.Length);
                    if (_cancelMusic) { break; }
                }
                iFile.Close();
            }
            else if (_source is byte[])
            {
                b = (byte[])_source;
                _rawSize = b.Length;
                SendData(B);
            }

            _busy = false;
            _readSoFar = -1;
            _position = _duration;
            _bitrate = 0;
            _mpegLayer = 0;
            if (onMusicFinished!=null)
            {
                onMusicFinished();
            }

        }
        [MethodImpl(MethodImplOptions.Synchronized)]
        public static void SendData(byte[] data)
        {
            int size = data.Length - data.Length % 32;

            //_spi.Config = dataConfig;
            for (int i = 0; i < size; i += 32)
            {

                while (_dreq.Read() == false)
                    Thread.Sleep(1);    // wait till done


                Array.Copy(data, i, block, 0, 32);

                _spi.Write(block);
                _readSoFar += 32;       // We need to know how many bytes we've read to calculate header size to get duration

                while (_pause)
                    Thread.Sleep(1);    // Wait while paused
            }
        }

        public static string Filename
        {
            get
            {
                if (_source is string)
                    return (string)_source;
                else
                    return "Embedded Resource";
            }
            set { _source = value; }
        }

        [MethodImpl(MethodImplOptions.Synchronized)]
        public static void Play()
        {
            new Thread(PlayLoop).Start();
        }
    }
}


and here how i use it

Vs1053.Initialize();
            Vs1053.SetVolume(0xFEFE);

Vs1053.Filename = "\\SD\test.mp3";
                  
                    Vs1053.PlayLoop();


also i implemented two new thing
1-
Vs1053.onMusicFinished += new Vs1053.musicFinished(Vs1053_onMusicFinished);
fires event when music finishes..(useful when threading music playback.. normally it is not async)

2-
Vs1053.CancelMusic = true;

this cancels music immediately , useful when you want to cancel and play next file..



#21869 network download speed is too slow

Posted by Serkan Polat on 19 December 2011 - 03:31 PM in Netduino Plus 2 (and Netduino Plus 1)

still no answer from anyone.. what is the download speed limit of lwip and parallel bus? i need help about speed improvement with netduino plus devices.. chris helppppp! :)



#21734 network download speed is too slow

Posted by Serkan Polat on 15 December 2011 - 07:19 PM in Netduino Plus 2 (and Netduino Plus 1)

hi everyone,
i wrote my custom ftp client class and try to download a file from my ftp server.
also i tried httpwebrequest and download a file from http server..
but the speed is about 16kbit per second, is this the speed limit? or am i making mistake?
here is my ftp class

using System;
using System.IO;
using Microsoft.SPOT;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using System.Net;



namespace smg.ftp
{

    public class FtpClient
    {

        public class FtpException : Exception
        {
            public FtpException(string message) : base(message) { }
            public FtpException(string message, Exception innerException) : base(message, innerException) { }
        }

        private static int BUFFER_SIZE = 2048;
        private static Encoding ASCII = Encoding.UTF8;

        private bool verboseDebugging = false;

        // defaults
        private string server = "localhost";
        private string remotePath = ".";
        private string username = "anonymous";
        private string password = "anonymous@anonymous.net";
        private string message = null;
        private string result = null;

        private int port = 21;
        private int bytes = 0;
        private int resultCode = 0;

        private bool loggedin = false;
        private bool binMode = false;

        private Byte[] buffer = new Byte[BUFFER_SIZE];
        private Socket clientSocket = null;

        private int timeoutSeconds = 300;

        /// <summary>
        /// Default contructor
        /// </summary>
        public FtpClient()
        {
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="server"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        public FtpClient(string server, string username, string password)
        {
            this.server = server;
            this.username = username;
            this.password = password;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="server"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="timeoutSeconds"></param>
        /// <param name="port"></param>
        public FtpClient(string server, string username, string password, int timeoutSeconds, int port)
        {
            this.server = server;
            this.username = username;
            this.password = password;
            this.timeoutSeconds = timeoutSeconds;
            this.port = port;
        }

        /// <summary>
        /// Display all communications to the debug log
        /// </summary>
        public bool VerboseDebugging
        {
            get
            {
                return this.verboseDebugging;
            }
            set
            {
                this.verboseDebugging = value;
            }
        }
        /// <summary>
        /// Remote server port. Typically TCP 21
        /// </summary>
        public int Port
        {
            get
            {
                return this.port;
            }
            set
            {
                this.port = value;
            }
        }
        /// <summary>
        /// Timeout waiting for a response from server, in seconds.
        /// </summary>
        public int Timeout
        {
            get
            {
                return this.timeoutSeconds;
            }
            set
            {
                this.timeoutSeconds = value;
            }
        }
        /// <summary>
        /// Gets and Sets the name of the FTP server.
        /// </summary>
        /// <returns></returns>
        public string Server
        {
            get
            {
                return this.server;
            }
            set
            {
                this.server = value;
            }
        }
        /// <summary>
        /// Gets and Sets the port number.
        /// </summary>
        /// <returns></returns>
        public int RemotePort
        {
            get
            {
                return this.port;
            }
            set
            {
                this.port = value;
            }
        }
        /// <summary>
        /// GetS and Sets the remote directory.
        /// </summary>
        public string RemotePath
        {
            get
            {
                return this.remotePath;
            }
            set
            {
                this.remotePath = value;
            }

        }
        /// <summary>
        /// Gets and Sets the username.
        /// </summary>
        public string Username
        {
            get
            {
                return this.username;
            }
            set
            {
                this.username = value;
            }
        }
        /// <summary>
        /// Gets and Set the password.
        /// </summary>
        public string Password
        {
            get
            {
                return this.password;
            }
            set
            {
                this.password = value;
            }
        }

        /// <summary>
        /// If the value of mode is true, set binary mode for downloads, else, Ascii mode.
        /// </summary>
        public bool BinaryMode
        {
            get
            {
                return this.binMode;
            }
            set
            {
                if (this.binMode == value) return;

                if (value)
                    sendCommand("TYPE I");

                else
                    sendCommand("TYPE A");

                if (this.resultCode != 200) throw new FtpException(result.Substring(4));
            }
        }
        /// <summary>
        /// Login to the remote server.
        /// </summary>
        public void Login()
        {
            if (this.loggedin) this.Close();

            Debug.Print("Opening connection to " + this.server + "FtpClient");


            IPEndPoint ep = null;

            try
            {
                this.clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                ep = new IPEndPoint(IPAddress.Parse(this.server), this.port);
                this.clientSocket.Connect(ep);
            }
            catch (Exception ex)
            {
                // doubtfull

                if (this.clientSocket != null) this.clientSocket.Close();

                throw new FtpException("Couldn't connect to remote server", ex);
            }

            this.readResponse();

            if (this.resultCode != 220)
            {
                this.Close();
                throw new FtpException(this.result.Substring(4));
            }

            this.sendCommand("USER " + username);

            if (!(this.resultCode == 331 || this.resultCode == 230))
            {
                this.cleanup();
                throw new FtpException(this.result.Substring(4));
            }

            if (this.resultCode != 230)
            {
                this.sendCommand("PASS " + password);

                if (!(this.resultCode == 230 || this.resultCode == 202))
                {
                    this.cleanup();
                    throw new FtpException(this.result.Substring(4));
                }
            }

            this.loggedin = true;

            Debug.Print("Connected to " + this.server + "FtpClient");


        }

        /// <summary>
        /// Close the FTP connection.
        /// </summary>
        public void Close()
        {
            Debug.Print("Closing connection to " + this.server + "FtpClient");

            if (this.clientSocket != null)
            {
                this.sendCommand("QUIT");
            }

            this.cleanup();
        }



        /// <summary>
        /// Return the size of a file.
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public long GetFileSize(string fileName)
        {
            if (!this.loggedin) this.Login();

            this.sendCommand("SIZE " + fileName);
            long size = 0;

            if (this.resultCode == 213)
                size = long.Parse(this.result.Substring(4));

            else
                throw new FtpException(this.result.Substring(4));

            return size;
        }


        /// <summary>
        /// Download a file to the Assembly's local directory,
        /// keeping the same file name.
        /// </summary>
        /// <param name="remFileName"></param>
        public void Download(string remFileName)
        {
            this.Download(remFileName, "", false);
        }

        /// <summary>
        /// Download a remote file to the Assembly's local directory,
        /// keeping the same file name, and set the resume flag.
        /// </summary>
        /// <param name="remFileName"></param>
        /// <param name="resume"></param>
        public void Download(string remFileName, Boolean resume)
        {
            this.Download(remFileName, "", resume);
        }

        /// <summary>
        /// Download a remote file to a local file name which can include
        /// a path. The local file name will be created or overwritten,
        /// but the path must exist.
        /// </summary>
        /// <param name="remFileName"></param>
        /// <param name="locFileName"></param>
        public void Download(string remFileName, string locFileName)
        {
            this.Download(remFileName, locFileName, false);
        }

        /// <summary>
        /// Download a remote file to a local file name which can include
        /// a path, and set the resume flag. The local file name will be
        /// created or overwritten, but the path must exist.
        /// </summary>
        /// <param name="remFileName"></param>
        /// <param name="locFileName"></param>
        /// <param name="resume"></param>
        public void Download(string remFileName, string locFileName, Boolean resume)
        {
            if (!this.loggedin) this.Login();

           // this.BinaryMode = true;

            Debug.Print("Downloading file " + remFileName + " from " + server + "/" + remotePath + "FtpClient");

            if (locFileName.Equals(""))
            {
                locFileName = remFileName;
            }

            FileStream output = null;

            if (!File.Exists(locFileName))
                output = File.Create(locFileName);

            else
                output = new FileStream(locFileName, FileMode.Open);

            Socket cSocket = createDataSocket();

            long offset = 0;

            if (resume)
            {
                offset = output.Length;

                if (offset > 0)
                {
                    this.sendCommand("REST " + offset);
                    if (this.resultCode != 350)
                    {
                        //Server dosnt support resuming
                        offset = 0;
                        Debug.Print("Resuming not supported:" + result.Substring(4) + "FtpClient");
                    }
                    else
                    {
                        Debug.Print("Resuming at offset " + offset + "FtpClient");
                        output.Seek(offset, SeekOrigin.Begin);
                    }
                }
            }

            this.sendCommand("RETR " + remFileName);

            if (this.resultCode != 150 && this.resultCode != 125)
            {
                throw new FtpException(this.result.Substring(4));
            }

            DateTime timeout = DateTime.Now.AddSeconds(this.timeoutSeconds);

            while (timeout > DateTime.Now)
            {
                this.bytes = cSocket.Receive(buffer, buffer.Length, 0);
                //output.Write(this.buffer, 0, this.bytes);
                //Thread.Sleep(1);
                if (this.bytes <= 0)
                {
                    break;
                }
            }

            output.Close();

            try { cSocket.Close(); }
            catch (Exception) { }

            this.readResponse();

            if (this.resultCode != 226 && this.resultCode != 250)
                throw new FtpException(this.result.Substring(4));
        }







        /// <summary>
        /// 
        /// </summary>
        private void readResponse()
        {
            this.message = "";
            this.result = this.readLine();

            if (this.result.Length > 3)
                this.resultCode = int.Parse(this.result.Substring(0, 3));
            else
                this.result = null;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private string readLine()
        {
            while (true)
            {
                this.bytes = clientSocket.Receive(this.buffer, this.buffer.Length, 0);
                char[] cc = ASCII.GetChars(this.buffer);
                this.message += new string(cc).Substring(0, this.bytes);
                //this.message += ASCII.GetString(this.buffer, 0, this.bytes);
                Thread.Sleep(10);
                if (this.bytes < this.buffer.Length)
                {
                    break;
                }
            }
            Thread.Sleep(100);
            string[] msg = this.message.Split('\n');

            if (this.message.Length > 2)
            {
                if (msg.Length>=2)
                {
                    this.message = msg[msg.Length - 2];
                }
                else
                {
                    this.message = msg[0];
                }
            }
            else
            {
                this.message = msg[0];
            }

            if (this.message.Length > 4 && !this.message.Substring(3, 1).Equals(" ")) return this.readLine();

            if (this.verboseDebugging)
            {
                for (int i = 0; i < msg.Length - 1; i++)
                {
                    Debug.Print(msg[i] + "FtpClient");
                }
            }

            return message;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="command"></param>
        private void sendCommand(String command)
        {
            if (this.verboseDebugging) Debug.Print(command + "FtpClient");

            //Byte[] cmdBytes = Encoding.UTF8.GetBytes(command + "\r\n");

            Byte[] cmdBytes = ASCII.GetBytes(command + "\r\n");
            clientSocket.Send(cmdBytes, cmdBytes.Length, 0);
            this.readResponse();
        }


        /// <summary>
        /// when doing data transfers, we need to open another socket for it.
        /// </summary>
        /// <returns>Connected socket</returns>
        private Socket createDataSocket()
        {
            this.sendCommand("PASV");

            if (this.resultCode != 227) throw new FtpException(this.result.Substring(4));

            int index1 = this.result.IndexOf('(');
            int index2 = this.result.IndexOf(')');

            string ipData = this.result.Substring(index1 + 1, index2 - index1 - 1);

            int[] parts = new int[6];
            string[] sparts = ipData.Split(',');
            for (int i = 0; i < parts.Length; i++)
            {
                parts[i] = int.Parse(sparts[i]);
            }

            int len = ipData.Length;
            int partCount = 0;
            string buf = "";

            //for (int i = 0; i < len && partCount <= 6; i++)
            //{
            //    char[] charr = ipData.Substring(i, 1).ToCharArray();
            //    char ch = charr[0];

            //    if (int.Parse(ch.ToString()) >= 0)
            //        buf += ch;

            //    else if (ch != ',')
            //        throw new FtpException("Malformed PASV result: " + result);

            //    if (ch == ',' || i + 1 == len)
            //    {
            //        try
            //        {
            //            parts[partCount++] = int.Parse(buf);
            //            buf = "";
            //        }
            //        catch (Exception ex)
            //        {
            //            throw new FtpException("Malformed PASV result (not supported?): " + this.result, ex);
            //        }
            //    }
            //}

            string ipAddress = parts[0] + "." + parts[1] + "." + parts[2] + "." + parts[3];

            int port = (parts[4] << 8) + parts[5];

            Socket socket = null;
            IPEndPoint ep = null;

            try
            {
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                ep = new IPEndPoint(IPAddress.Parse(ipAddress), port);
                socket.Connect(ep);
            }
            catch (Exception ex)
            {
                // doubtfull....
                if (socket != null) socket.Close();

                throw new FtpException("Can't connect to remote server", ex);
            }

            return socket;
        }

        /// <summary>
        /// Always release those sockets.
        /// </summary>
        private void cleanup()
        {
            if (this.clientSocket != null)
            {
                this.clientSocket.Close();
                this.clientSocket = null;
            }
            this.loggedin = false;
        }

        /// <summary>
        /// Destuctor
        /// </summary>
        ~FtpClient()
        {
            this.cleanup();
        }


        /**************************************************************************************************************/
        #region Async methods (auto generated)

        /*
				WinInetApi.FtpClient ftp = new WinInetApi.FtpClient();

				MethodInfo[] methods = ftp.GetType().GetMethods(BindingFlags.DeclaredOnly|BindingFlags.Instance|BindingFlags.Public);

				foreach ( MethodInfo method in methods )
				{
					string param = "";
					string values = "";
					foreach ( ParameterInfo i in  method.GetParameters() )
					{
						param += i.ParameterType.Name + " " + i.Name + ",";
						values += i.Name + ",";
					}
					

					Debug.Print("private delegate " + method.ReturnType.Name + " " + method.Name + "Callback(" + param.TrimEnd(',') + ");");

					Debug.Print("public System.IAsyncResult Begin" + method.Name + "( " + param + " System.AsyncCallback callback )");
					Debug.Print("{");
					Debug.Print("" + method.Name + "Callback ftpCallback = new " + method.Name + "Callback(" + values + " this." + method.Name + ");");
					Debug.Print("return ftpCallback.BeginInvoke(callback, null);");
					Debug.Print("}");
					Debug.Print("public void End" + method.Name + "(System.IAsyncResult asyncResult)");
					Debug.Print("{");
					Debug.Print(method.Name + "Callback fc = (" + method.Name + "Callback) ((AsyncResult)asyncResult).AsyncDelegate;");
					Debug.Print("fc.EndInvoke(asyncResult);");
					Debug.Print("}");
					//Debug.Print(method);
				}
*/


        private delegate void LoginCallback();
        public System.IAsyncResult BeginLogin(System.AsyncCallback callback)
        {
            LoginCallback ftpCallback = new LoginCallback(this.Login);
            return ftpCallback.BeginInvoke(callback, null);
        }
        private delegate void CloseCallback();
        public System.IAsyncResult BeginClose(System.AsyncCallback callback)
        {
            CloseCallback ftpCallback = new CloseCallback(this.Close);
            return ftpCallback.BeginInvoke(callback, null);
        }

        private delegate Int64 GetFileSizeCallback(String fileName);
        public System.IAsyncResult BeginGetFileSize(String fileName, System.AsyncCallback callback)
        {
            GetFileSizeCallback ftpCallback = new GetFileSizeCallback(this.GetFileSize);
            return ftpCallback.BeginInvoke(fileName, callback, null);
        }
        private delegate void DownloadCallback(String remFileName);
        public System.IAsyncResult BeginDownload(String remFileName, System.AsyncCallback callback)
        {
            DownloadCallback ftpCallback = new DownloadCallback(this.Download);
            return ftpCallback.BeginInvoke(remFileName, callback, null);
        }
        private delegate void DownloadFileNameResumeCallback(String remFileName, Boolean resume);
        public System.IAsyncResult BeginDownload(String remFileName, Boolean resume, System.AsyncCallback callback)
        {
            DownloadFileNameResumeCallback ftpCallback = new DownloadFileNameResumeCallback(this.Download);
            return ftpCallback.BeginInvoke(remFileName, resume, callback, null);
        }
        private delegate void DownloadFileNameFileNameCallback(String remFileName, String locFileName);
        public System.IAsyncResult BeginDownload(String remFileName, String locFileName, System.AsyncCallback callback)
        {
            DownloadFileNameFileNameCallback ftpCallback = new DownloadFileNameFileNameCallback(this.Download);
            return ftpCallback.BeginInvoke(remFileName, locFileName, callback, null);
        }
        private delegate void DownloadFileNameFileNameResumeCallback(String remFileName, String locFileName, Boolean resume);
        public System.IAsyncResult BeginDownload(String remFileName, String locFileName, Boolean resume, System.AsyncCallback callback)
        {
            DownloadFileNameFileNameResumeCallback ftpCallback = new DownloadFileNameFileNameResumeCallback(this.Download);
            return ftpCallback.BeginInvoke(remFileName, locFileName, resume, callback, null);
        }





        #endregion
    }
}


here how i use it
FtpClient ftp = new FtpClient("192.168.1.21", "mtest", "mtest", 1000, 21);


            ftp.Download("test.MP3", "\\SD\\bb.mp3", true);


before i start ftp download
here is my dhcp configuration
static private void InitNetwork()
        {
            // write your code here
            NetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();

            foreach (NetworkInterface networkInterface in networkInterfaces)
            {
                if (networkInterface.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
                {
                    if (!networkInterface.IsDhcpEnabled)
                    {
                        // Switch to DHCP ...
                        networkInterface.EnableDhcp();
                        networkInterface.RenewDhcpLease();
                        Thread.Sleep(10000);
                    }

                    Debug.Print("IP Address: " + networkInterface.IPAddress);
                    Debug.Print("Subnet mask " + networkInterface.SubnetMask);
                    Debug.Print("Gateway " + networkInterface.GatewayAddress);
                    Debug.Print("DNS " + networkInterface.DnsAddresses[0]);
                }
            }
        }



also as i told, i write an http downloader, speed is the same with it..

here is the http downloader
using System;
using Microsoft.SPOT;
using System.IO;
using System.Net;
using System.Net.Sockets;


namespace smg.utulity.downloader
{
    class downloader
    {

        public static event Progress onProgress;
        public delegate void Progress(long currentSize, long TotalSize, string Filename);

        public static event DownloadFinished onDownloadFinished;
        public delegate void DownloadFinished(string errMsg);

        public static int DownloadFile(String remoteFilename,
                               String localFilename)
        {

            string fname = localFilename.Split('\\')[localFilename.Split('\\').Length - 1];
            // Function will return the number of bytes processed
            // to the caller. Initialize to 0 here.
            int bytesProcessed = 0;

            // Assign values to these objects here so that they can
            // be referenced in the finally block
            Stream remoteStream = null;
            Stream localStream = null;
            WebResponse response = null;

            // Use a try/catch/finally block as both the WebRequest and Stream
            // classes throw exceptions upon error
            try
            {
                // Create a request for the specified remote file name
                WebRequest request = WebRequest.Create(remoteFilename);
                if (request != null)
                {
                    // Send the request to the server and retrieve the
                    // WebResponse object 
                    // request.ContentLength
                    response = request.GetResponse();
                    if (response != null)
                    {
                        // Once the WebResponse object has been retrieved,
                        // get the stream object associated with the response's data
                        remoteStream = response.GetResponseStream();
                        long total = response.ContentLength;

                        // Create the local file
                        localStream = File.Create(localFilename);

                        // Allocate a 1k buffer

                        byte[] buffer = new byte[1024];
                        int bytesRead;

                        // Simple do/while loop to read from stream until
                        // no bytes are returned
                        do
                        {
                            // Read data (up to 1k) from the stream
                            bytesRead = remoteStream.Read(buffer, 0, buffer.Length);

                            // Write the data to the local file
                            localStream.Write(buffer, 0, bytesRead);

                            // Increment total bytes processed
                            bytesProcessed += bytesRead;

                            if (onProgress != null) { onProgress(bytesProcessed, total, fname); }
                        } while (bytesRead > 0);
                    }
                }
                if (onDownloadFinished != null) { onDownloadFinished("finished"); }
            }
            catch (WebException webEx)
            {
                Debug.Print("Web Exception Occured");
                if (webEx.InnerException is SocketException)
                {
                    SocketException sock = webEx.InnerException as SocketException;
                    Debug.Print("Socket error code: " + sock.ErrorCode.ToString());
                }
            }
            catch (Exception ex)
            {
                Debug.Print("Exception of type: " + ex.GetType().FullName);
                Debug.Print(ex.Message);
                if (onDownloadFinished != null) { onDownloadFinished(ex.Message); }
            }
            finally
            {
                // Close the response and streams objects here 
                // to make sure they're closed even if an exception
                // is thrown at some point
                if (response != null) response.Close();
                if (remoteStream != null) remoteStream.Close();
                if (localStream != null) localStream.Close();
            }

            // Return total bytes processed to caller.
            return bytesProcessed;
        }
    }
}



here is how i used it
public static void Main()
        {
downloader.onProgress += new downloader.Progress(downloader_onProgress);
            downloader.onDownloadFinished += new downloader.DownloadFinished(downloader_onDownloadFinished);
            int filesize = downloader.DownloadFile("http://192.168.1.21/test.MP3", "\\SD\\deneme1.mp3");
}
static void downloader_onDownloadFinished(string errMsg)
        {
            Debug.Print("download finished" + errMsg);
        }

        static void downloader_onProgress(long currentSize, long TotalSize, string Filename)
        {
            Debug.Print("c:" + currentSize + "-t:" + TotalSize + "-f:" + Filename);
        }


my network connection is 100mbit..
my internet speed is 10 mbit.. my pc downloads the same file with 800-900kbit/s
but netduino plus downloads at 16-20kbit/s

how can i improve speed?

note: i am using MF 4.2 and when using system.ftp (also adding system.http) , i cant deploy the application..
can anyone show me a better way?



#21656 HD SD card and 4.2 RC3

Posted by Serkan Polat on 13 December 2011 - 12:38 PM in Netduino Plus 2 (and Netduino Plus 1)

Just to help out I gave it a run since i'm on 4.2. No issues here using a 2gb or 8gb card. No 4gb card to try with.



so is there any limitation on 4.2?
i mean i want to use 8 or 16gb for playling mp3..




home    hardware    projects    downloads    community    where to buy    contact Copyright © 2016 Wilderness Labs Inc.  |  Legal   |   CC BY-SA
This webpage is licensed under a Creative Commons Attribution-ShareAlike License.