Page 1 of 1

FT232 Driver [GSoC Task]

Posted: Thu May 29, 2014 9:36 am
by gtament
My proposal
Spoiler:Implementation details:

I'm going to write a driver for common USB <-> RS232 converter. This will allow KolibriOS to communicate with many devices. Also this chip can act as the programming device for most of MCUs. So implementation of this driver will enable users to write and flash firmwares directly in KolibriOS environment, without necessity of switching between operating systems.


To do:

Stable FT232 VCP Driver
KolibriOS will have support for Virtual COM port
Stable FT232 D2XX Driver
KolibriOS users will be able to directly control FT232 chip IO buses and write some embedded systems.
Arduino sketches flash utility
Plugin or standalone software to write and flash firmware
Special-design circuit board
Demonstration board designed specifically for KolibriOS users. I want to design my own FT232 circuit board as part of GSoC because there is no ready-made board like this one available with the following functionalities:

Direct control basic parts, e.g. relays, LEDs
Interface for device with low-level protocol, e.g. RS-232, I2C, One-wire, any custom protocol
Replacement of some of chip programming devices

Timeline:

Code: Select all

 From        To          Task
April 21   May 19       Study KolibriOS driver model
May 19     June 8       Study FT232 datasheet
June 9     June 22      Trace and solder the circuit board with a FT232 chip
June 23    June 29      Develop and test VCP driver
June 30    July 20      Develop and test D2XX driver
July 21    August 3     Develop UI utilities to work with a FT232 chip
August 4   August 18    Refactor
Other time commitments: Exams June 14 - June 28
About me:

My name is Yurii Shevtsov. I am 18 years old. I have never participated in any open-source organizations, but I participated in several programming contests, while I was in high school.
Skills:

Education:

I am a 2nd year student of Odessa Polytechnic University, Ukraine.

The major in Computer Science and System Software design

GMT+2
Timeline я писал тогда, когда еще точно не знал, с чем мне придется столкнуться. Сейчас очевидно, что месяц на изучение документации слишком много. Так что за драйвер я сел уже. Также стоить отметить, что FTDI (фирма-производитель этой микросхемы) выдает части протокола только под NDA, но к счастью есть умельцы, которые написали свободный драйвер для Linux, из которого и можно вытащить нужные константы. Вместо двух драйверов будет один, объединяющий VCP и D2XX. Также hidnplayr предположил, что скорее всего стоит в будущем дописать функции ядра, для поддержки VCP. Я лично вижу необходимость в изменении процедуры определения устройства и вызова его драйвера (в данный момент драйвер вызывается для целого класса). Впрочем, пока драйвера нет, эти потенциальные значения обсуждать не имеет смысла)

When I was writing Timeline, I didn't know, how exactly it would be. It's clear now that one month is too much for manual studying. So, I already started working on the driver. Also I want to notice, that FTDI (chip manufacturer) sends protocol description only under NDA, but fortunately there is free Linux driver, where I found all needed constants. Instead of two drivers I will write one, combining VCP and D2XX. Also hidnplayr suggested, that maybe it's worth to add kernel functions for VCP support. Personally I think, that usb device identification and driver call should be modified (now driver is called for device class). However, while there is no driver, no need to talk about changes in kernel)

Re: FT232 Driver [GSoC Task]

Posted: Thu May 29, 2014 9:52 am
by gtament
Пока что я пишу реализацию односвязного списка.
Now I'm working on single linked list.

Этот участок кода добавляет экземпляр структуры в список, простой подменой адреса в head.
This code adds struct in list, by simple address change in head

Code: Select all

        movi    eax, sizeof.ftdi_context
        call    Kmalloc
        test    eax, eax
        jnz     @f
        mov     esi, nomemory_msg
        call    SysMsgBoardStr
        jmp     .return0
@@:
        mov     ebx, [head]                             ;Сохраняем указатель на начало списка в ебх
        mov     [head], eax                             ;Делаем новую структура головой списка
        mov     [eax + ftdi_context.next_context], ebx  ;Помещаем в голову указатель на следующую структура
Этот участок кода удаляет нужный экземпляр стуктуры из списка
This code deletes given struct from list

Code: Select all

        mov edi, ftdi_context
        cmp edi, [head]
        jz .unlink_head
        mov eax, [head]
  
  .getnext:  
        mov ebx, eax
        mov eax, [eax+ftdi_context.next_context]        
        cmp eax, [edi]
        jz  .unlink
        jmp .getnext
        
  .unlink:
        mov  ebx+ftdi_context.next_context, [ftdi_context.next_context] ;!!!Возможно проблемы с []        
        jmp  @f
        
  .unlink_head:
        mov head, [ftdi_context.next_context]
  @@:   
        movi eax, ftdi_context
        call Kfree 
Пока что, ничего из этого не тестировалось, так что, если на лицо явные опечатки или ошибки, не подсказывайте)
Также у меня уже есть вопрос, как мне правильно пользоваться callback'ами в вызовах USB*TransferAsync? Дело в том, что я не могу понять зачем мне асинхронность, я был бы очень рад если бы функции были блокирующими. Ведь допустим прикладная программа запрашивает данные с устройства, получаются, что они нужны уже и сейчас. Как решается такая проблема? Мне пришло в голову только после вызова USB*TransferAsync впадать в цикл с выходом по флагу, который выставляется в callback'е.

Nothing of that tested so far, so if you find typos or mistakes, please don't suggest while) Also I have a question about how to use callback in USB*TransferAsync? The point is, I don't understand why I need async, I would be really happy if those functions are blocking. For example, application asks driver to obtain data from device, it turns out that data is needed right now. How to solve this problem? The only way I see now is to put a loop after each USB*TransferAsync, and wait for callback function to raise some flag.

Re: FT232 Driver [GSoC Task]

Posted: Fri May 30, 2014 12:31 am
by hidnplayr
It would be appreciated if you write the comments in source code in english :)

Re: FT232 Driver [GSoC Task]

Posted: Fri May 30, 2014 11:04 am
by gtament
No problem) I will, those were the last one in russian)

Re: FT232 Driver [GSoC Task]

Posted: Mon Jun 02, 2014 3:58 pm
by gtament
Кстати, что будет, если вторая программа обратиться к драйверу, пока драйвер обрабатывает вызов первой? Выполнение второй программы блокируется в этом месте?

BTW, what if second program calls driver, while driver is working on first program's call? Will the execution of second program block?

Re: FT232 Driver [GSoC Task]

Posted: Wed Jul 30, 2014 10:55 pm
by gtament
Не подумайте, я все также усердно работаю над драйвером) И я никуда непропадал, почти каждый день я онлайн. Несмотря на некоторые несоответсвия с внутренним графиком, я обещаю полный результат в срок: драйвер, прикладные программки, плата. На данный момент драйвер готов на 90%, осталось дописать части кода, отвечающие за: чтение данных с буфера микросхемы, геттеры и сеттеры кол-ва байт, считываемых за один раз (их надобность все еще остается под сомнением). Ну и тестируется уже написанное. Очень надеюсь, что 31 июля представлю полностью укомплектованную версию драйвера.

Don't worry, I'm still diligently working on driver. And I wasn't missing, I'm online almost every day) Despite of discrepancy with my timeline, I promise complete result: driver, utilities, circuit board. Right now driver is ready for 90%, parts of code left are: reading data from device's buffer, getters and setters for quantity of bytes to process at once. And, of course, I'm testing that I've already done. I hope, I will present fully equipped version of the driver on July, 31.

Re: FT232 Driver [GSoC Task]

Posted: Mon Aug 18, 2014 8:48 pm
by gtament
Вот рисунок платы. На ней разведены места под 7 светодиодов и реле, все это может присоединено к пинам FT232 с помощью джамперов. Я предусмотрел место для MAX3232, так что пользователь сможет подключить платы к компьютеру с родным COM-
портом. Микросхема также подключается к пинам Tx и Rx с помощью джамперов. Лого пока еще не выбрал. Теперь о приятном!) В ближайшем будущем я соберу три таких платы и подарю любому, кто попросит.

Here is layout of circuit board. It contains 7 LEDs and relay, all of them can be connected to FT232's pins via jumpers. I placed MAX3232 on the board, so user can connect board to PC with standard COM-port. It also can be connected to FT232's Rx and Tx pins via jumpers. Still thinking what Kolibri logo to choose. Now the best part. I'm going to do three circuit boards in the nearest future and present each to somebody)

Re: FT232 Driver [GSoC Task]

Posted: Mon Aug 18, 2014 9:02 pm
by gtament
FT232 Control Center - программа, которая работает с микросхемой FT232, а именно позволяет управлять ее пинами в режиме BitBang (D2XX составляющая драйвера). К сожалению, либо в драйвере, либо в программе есть ошибка, которую на момент этого поста я все еще не исправил. Проблема в том, что микросхема под управлением этой программы не ведет себя, как ожидается.

FT232 Control Center - application, which works with FT232, allows controlling its pins in BitBang mode (D2XX driver's part). Unfortunately, there is a bug in a driver or in an application, which I haven't corrected at the time of this post. The problem is IC, controlled by this app, doesn't behave as expected.

Исходник\Source

Re: FT232 Driver [GSoC Task]

Posted: Mon Aug 18, 2014 9:17 pm
by gtament
По поводу VCP, у меня не было возможности полноценно протестировать эту часть. Впрочем, это необязательно, т.к. и D2XX и VCP используют буквально одни и те же процедуры драйвера. А значит, если работает одно, то работает и другое. Хотя программа выше работает не так, как надо. Однако hidnplayr проверил отправку сообщения по протоколу RS-232 и написал мне, что смог прочесть отправленное на другой машине, если я его правильно понял.
Тем не менее, драйвер готов (если так можно сказать) и никаких изменений в архитектуре не предвидется (все фичи уже на месте), разве что придется править оставшиеся баги и дописать к некоторым процедурам проверку ошибок.

About VCP, I wasn't able to test this part properly. But it is not that neccessary, because D2XX and VCP use the same driver's procs. So if first works, the second works also. Although application above doesn't work, as it has to. However hidnplayr tested message sending via RS-232 and wrote to me, that he could read sent message on other PC, if I understood him correctly.
Anyway driver is ready (if I can say so) and no architectural changes needed (all features are already implemented), the only left is to fix last bugs and add error checks to some procs.

Re: FT232 Driver [GSoC Task]

Posted: Fri Apr 27, 2018 10:45 am
by tsdima
В связи с вопросом Kopa у меня тоже возник вопрос. В исходниках gtament драйвер называется usbother, ядро тоже грузит автоматически такой драйвер, а в репозитории он вроде называется usbftdi. Где правда?

Re: FT232 Driver [GSoC Task]

Posted: Fri Apr 27, 2018 11:25 am
by G@К
Всем Hi
Правда в том, что usbother -это общее название всех юсб-драйверов не входящее в состав usb-hid,usb-накопителей и по моему еще usb-принтеров. То есть ели написать драйвер для usb-сетевой карты или usb-модема то в систему его надо прописать с именем usbother. А в репозитории usbftdi-это название проекта.