RTL8196 vs OpenWRT

Okay, I admit it. I screwed up. Bought some ‘edup’ shit to find out the chip was totally unsupported. Well, it caught my attension and I decided to make it supported. Not just because I can’t buy a supported one… It’s just the fun
Inside is… RTL8196C. Some time ago I already completed an awesome quest called “collect all the pacthes and get a somewhat working outdated toolchain” ( in russian, sorry I’m lazy to translate). A look at the BSP is quite enough for my ‘shit-o-meter’ to say “value out of range”.  This code causes depression, headache, stomachache and an unconventional desire to kill… make sure you have good nerves, before you open it.
Well, all the trash and fun I found in realtek’s BSP follows. THIS shit is running in production use!
Should anybody from realtek be reading this… Guys… Do a favor… Kill yourself, save the planet!

Okay, lets start with the fun stuff.

necromant@ilwyn:/media/NC-OS/pocket_router/linux-2.6.30-veteran/arch/mips/rtl8196b$ ls -la
итого 64
drwxr-xr-x 2 necromant necromant 4096 2010-12-17 11:48 .
drwxr-xr-x 19 necromant necromant 4096 2010-12-17 11:48 ..
-rw-r--r-- 1 necromant necromant 6268 2010-02-22 05:35 int.c
-rw-r--r-- 1 necromant necromant 236 2010-02-22 05:35 Makefile
-rw-r--r-- 1 necromant necromant 2615 2010-02-22 05:35 mem.c
lrwxrwxrwx 1 necromant necromant 84 2011-08-21 14:14 pci.c -> /home/bo_zhao/8196/linux-2.6.19/linux-2.6.x/arch/mips/realtek/rtl8196b/pci-rtl8196.c
-rw-r--r-- 1 necromant necromant 1996 2010-02-22 05:35 pci.h
-rw-r--r-- 1 necromant necromant 14802 2010-02-22 05:35 pci-rtl8196.c
-rw-r--r-- 1 necromant necromant 1111 2010-02-22 05:35 printf.c
-rw-r--r-- 1 necromant necromant 4383 2010-02-22 05:35 setup.c
-rw-r--r-- 1 necromant necromant 2240 2010-02-22 05:35 timer.c

pci.c symlinks to /home/%codemonkeyname%/…, and since %codemonkeyname% != necromant it wouldn’t get compiled. Luckily that was some old redundant stuff. Just a miracle it worked after all. There’s a plenty of this shit in kernel source.

From the kernel tree, lots of symlinks go outside. Without passing some vars to the hacked kernel Makefiles it wouldn’t compile at all. Only from BSP.

 

Board-specific init is not in mach-boardname.c, no way, a whole folder called bsp that is sylinked somewhere outside. And there’s little to no board-specific code in there.

MTD layout is hardwired in driver, not board specific and set via kconfig.

leds’n’buttons, just like the whole gpio subsystem is implemented as a char dev, incompatible with just about anything. Web apps are supposed to read and write to that char device. Forget those /sys/class/leds/, led triggers and such shit! Btw, board-specific led defines are in the led driver, not board-specific stuff.

For LexraCore (A veteran MIPS-like CPU, that got damaged by patent trolls and doesn’t have some instructions) there’s a new kernel arch called rlx, mostly copypaste from mips, with lottsa hacks.

Makefiles of the kernel are hacked to get compiled via an archeological gcc 3.4x.

Guys from realtek write in camelCase at kernel level.Crap!

Comments in dmesg are sucky like “IN WIFI INIT!111”. Why caps?

Kernel images are packed using rtkload, some hacked opensource project. It is put in kernel tree, and the Makefile calls ‘cvimg’ util by realtek, that gets compiled along in some ‘goahead’  (the webserver, yeah!?) Rootfs is attached to the image with ‘mgbin’ from the same ass.

Paths longer than about 20 chars cause mgbin & cvimg to crash. Who the heck is gonna do boundary checks, you ****?!?

Baudrate for earlyprintk is defined somewhere in a header totally unrelated to board init somewhere in в arch/rlx/include. It’s just not funny anymore!111

A COOL BONUS. 

Extract from their GPIO driver:

 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,27)
 kill_proc(1,SIGTERM,1);
 #else
...

This soon made it to the top of the russian site called govnokod.ru ( a collection of MOST shitty code from the known universe) =))

OpenWRT for unbranded-3gn(RT3050F) router (With USB!)

Okay. As promissed, usb support arrived. Thanks to Layne Edwards for his dwc_otg patches – everything now works.
Since I have this hardware and I use it, I will be updating a page with firmware builds.
So, meet the first version of it and grab on the ….

Release notes:

 

  • comgt for 3g modems is built-in
  • USB host and dwc_otg are compiled in kernel, therefore additional usb kmod packages have to be installed with –force-depends
  • Adjusted mtd partition sizes

 

Known issues: 

Since usb support is compiled-in additional usb kmod packages should be installed with –force-depends

 

 

This router support is now added to OpenWRT trunk under the name of wr512-3gn. Please use the OpenWRT snapshots or compile from source yourself. Beware, that I haven’t tested the if the update via web interface works or not. If it doesn’t, you have to solder in the UART.

A USB flash switcher for my RIGOL DSO

The good thing of my little Rigol DSO is the USB port, where I can pop the flash and dump data in CSV. However, when you have thrown in some bash/python script to analyze the data, or just want do download the pics, you have to remove the usb flash. In the first case, you get bored popping flash in and out pretty soon.
At least I am, sine I’m a still a lazy programmer.
So, what’s the deal?
I took a look at the junk around, and found a nice switch. The I etched a small PCB, and fixed the whole thing to the shelf. I will still have to cover the pcb with urethane, though. Pics follow:



Basically, it’s dumb. Really dumb. You connect the flash to the slot, you connect one cord to your rigol, the other one to some PC. It just switches the 2 data lines from one device to another. So, when I want to connect it to my tablet, instead of rigol… I just flip the switch. Later, after some testing I added 30k pulldown resistors on the data lines, to eliminate some false device detections, when the device is switched off, or not present. (Conductive flux?)
There’s also a known bug with some devices: since power doesn’t get switched, the usb device doen’t get a cold-reset. And they do not get resetted properly. In my case popping another card reader fixed the issue. Making the switch disable the power for a short time will also allow these broken devices to work.

Kicad project files are here. (Schematics are messy – I was in a hurry)
NB: remember to grab eagle converted libraries for kicad, since they have that nice miniusb jack module I used here.

Отправляем пинауты на планшет при помощи питона, гтк, и adb

Собственно, когда началась эта планшетная лихорадка, я себе раздобыл flytouch II из китая. Но кроме как посмотреть раз в месяц что-то мозгоразжижающее его не юзал. Разве что разок в виде навигатора.
Потом пришла в голову мысль, а ну как там удобно даташиты смотреть. Увы нет. Ищет в пдфах медленно, так как адобридер на андройде тормознутый. А читать… Читать все равно с мобильника в дороге удобнее.
В общем пришла мне в голову мысля. Хранить в нем распины микросхем, борд и прочего, что жутко надо когда паяешь. Иными словами те кусочки, которые искать не надо.
Начал с того, что при помощи подручных средств переоборудовал настольную лампу в держатель для планшета. прямо над местом, где паяю, чтобы он был перед глазами.
Дальше пошло веселье. Когда выделяешь в окуляре пинаут, да и вообще кусок документа – его можно скопировать как картинку. Но сохранить в файл автоматом – никак. У klipper’a есть действия с буфером обмена, но нужного мне не оказалось.
Ладно, призываем на помощь командную строку.
Сначала подумав немного, я соорудил на питоне и pygtk вот такой костыль:

#! /usr/bin/python
 
import pygtk
pygtk.require('2.0')
import gtk
import os
import sys
 
def save_image(f):
#    assert os.path.exists(f), "file does not exist"
    #image = gtk.gdk.pixbuf_new_from_file(f)
 
    clipboard = gtk.clipboard_get()
    pixbuf = clipboard.wait_for_image()
    pixbuf.save(f, "jpeg", {"quality":"100"})	
 
 
save_image(sys.argv[1]);

Его назначение сохранить картинку из буфера обмена в жопег. Имя файла дается в виде первого и единственного аргумента.
Остальное было делом техники:
При помощи kdialog запрашиваем имя файла, категорию в которую будем сохранять (подпапки на устройстве), после чего сохраняем картинку и отправляем на планшет, откуда ее всегда легко открыть.

Выходит примерно такой скрипт в первом приближении

#!/bin/bash
N=`kdialog --inputbox "Name, please"`
C=`kdialog --inputbox "Category, please"`
getimg /tmp/pin.jpg
adb shell mkdir /sdcard/sdcard2/pinouts/$C
adb push /tmp/pin.jpg /sdcard/sdcard2/pinouts/$C/$N.jpg

Porting OpenWRT to an unbranded 3GN router

Ok, not porting, but more like adding support for the board, ’cause the chip is already quite known.
I got this thing from my favourite place to waste money – DX. It has RTL3050F inside, 32MB RAM, 4MB FLASH, and runs at 320Mhz. A good bonus is a usb host and a usual uart, well hidden in a small case.
Obligatory photo follows:

Ok, so what next? As usual, the first thing I do, once I get a router… Turn on the soldering iron, take it apart and solder the 2,54 header to connect to the uart. Hehe.
UART is here, the usual 4 pins. GND, RX, TX and Vcc. Logic levels are 3,3 volts (As if I expected anything else), so I just soldered the pins and hooked the bus pirate.


The board is shipped with u-boot, has no jtag whatsoever (careful not to brick – or else you’ll have some bad time desoldering the flash chip, programming it and soldering back!).
Next I got the latest OpenWRT trunk… To just find that this thing doesn’t boot with any of the images generated.
the MOFI3500-3GN image kind of worked, but complained about incorrect mtd patitioning schema.
Time to get some coffee and start hacking OpenWRT to get things right.

As the result, I:

  • Created a new mach-type called ‘mach-unbranded-3gn’
  • Altered the scripts to correctly pack the firmware for this new supported router.
  • Figured out the correct GPIOS for LEDs, so that all 5+1 leds that can be controlled are avaliable from /sys/class/leds
  • Figured out the GPIOS for both buttons at the back to work
  • Altered some scripts to correctly extract firmware for wireless chip
  • Sent the patches to openwrt-devel.
USB didn’t work, so I grabbed some GPL code from asus router based on the same chip and gave it a look. USB host is called here dwc_otg. According to the headers ralink just grabbed the IP core of that from synopsys. Actually, it can act both as a device and as a host. But you cannot switch that in the runtime, since the modes of operation are hardcoded there.
Synopsys didn’t use ohci/ehci, but just invented their own shit(tm) whith blackjack and hoo… err… hmmm… other stuff. As the result the code resides in drivers/usb/dwc_otg and looks quite alien.
Layne Edwards from OpenWRT-devel has already provided some patches, but:
  • I haven’t yet tried them yet
  • They aren’t yet in the OpenWRT trunk
So no usb support this time. Check back in a week or so.
To flash, you have to solder the uart and hook a terminal at 57600 baud 8n1 (for dummies: speed 57600, 8 data bits, no parity, 1 stop bits, no software or hardware flow control).
Once it boots and you see the 5 sec countdown – press a key, and select “2”.
You need a tftpd server running – the firmware is transferred via ethernet using tftp.
If you do everything correctly – you’ll see something like that in your terminal:

U-Boot 1.1.3 (Apr 7 2010 - 09:43:57)

Board: Ralink APSoC DRAM: 32 MB
relocate_code Pointer at: 81fac000
======= config usb otg =====
flash_protect ON: from 0xBF000000 to 0xBF0205C3
protect on 0
protect on 1
protect on 2
protect on 3
protect on 4
protect on 5
protect on 6
protect on 7
protect on 8
protect on 9
flash_protect ON: from 0xBF030000 to 0xBF03FFFF
protect on 10
============================================
Ralink UBoot Version: 3.2
--------------------------------------------
ASIC 3052_MP2 (Port5<->None)
DRAM COMPONENT: 256Mbits
DRAM BUS: 16BIT
Total memory: 32 MBytes
Date:Apr 7 2010 Time:09:43:57
============================================
icache: sets:128, ways:4, linesz:32 ,total:16384
dcache: sets:128, ways:4, linesz:32 ,total:16384

##### The CPU freq = 320 MHZ ####

SDRAM bus set to 16 bit
SDRAM size =32 Mbytes

Please choose the operation:
1: Load system code to SDRAM via TFTP.
2: Load system code then write to Flash via TFTP.
3: Boot system code via Flash (default).
4: Entr boot command line interface.
9: Load Boot Loader code then write to Flash via TFTP.
0

3: System Boot system code via Flash.
## Booting image at bf050000 ...
Image Name: MIPS OpenWrt Linux-2.6.39.2
Created: 2011-08-04 17:34:58 UTC

System Control Status = 0x00400000
Image Type: MIPS Linux Kernel Image (lzma compressed)
Data Size: 804635 Bytes = 785.8 kB
Load Address: 80000000
Entry Point: 80000000
Verifying Checksum ... OK
Uncompressing Kernel Image ... OK
No initrd
## Transferring control to Linux (at address 80000000) ...
## Giving linux memsize in MB, 32

Starting kernel ...

Linux version 2.6.39.2 (necromant@ilwyn) (gcc version 4.5.4 20110526 (prerelease) (Linaro GCC 4.5-2011.06-0) ) #18 Thu Aug 4 21:34:21 MSD 2011
bootconsole [early0] enabled
CPU revision is: 0001964c (MIPS 24Kc)
Ralink RT3350 id:1 rev:2 running at 320.00 MHz
Determined physical RAM map:
memory: 02000000 @ 00000000 (usable)
Initrd not found or empty - disabling initrd
Zone PFN ranges:
Normal 0x00000000 -> 0x00002000
Movable zone start PFN for each node
early_node_map[1] active PFN ranges
0: 0x00000000 -> 0x00002000
Built 1 zonelists in Zone order, mobility grouping on. Total pages: 8128
Kernel command line: board=NONAME-3GN mtdparts=physmap-flash.0:192k(u-boot)ro,64k(devdata)ro,64k(devconf)ro,832k(kernel),2944k(rootfs),3776k@0x50000(firmware) console=ttyS1,57600 rootfstype=squashfs,jffs2
PID hash table entries: 128 (order: -3, 512 bytes)
Dentry cache hash table entries: 4096 (order: 2, 16384 bytes)
Inode-cache hash table entries: 2048 (order: 1, 8192 bytes)
Primary instruction cache 16kB, VIPT, 4-way, linesize 32 bytes.
Primary data cache 16kB, 4-way, VIPT, no aliases, linesize 32 bytes
Writing ErrCtl register=0007a000
Readback ErrCtl register=0007a000
Memory: 30032k/32768k available (1849k kernel code, 2736k reserved, 312k data, 148k init, 0k highmem)
SLUB: Genslabs=9, HWalign=32, Order=0-3, MinObjects=0, CPUs=1, Nodes=1
NR_IRQS:48
console [ttyS1] enabled, bootconsole disabled
console [ttyS1] enabled, bootconsole disabled
Calibrating delay loop... 212.58 BogoMIPS (lpj=1062912)
pid_max: default: 32768 minimum: 301
Mount-cache hash table entries: 512
NET: Registered protocol family 16
MIPS: machine is Unbranded 3G router from DX
bio: create slab at 0
Switching to clocksource MIPS
NET: Registered protocol family 2
IP route cache hash table entries: 1024 (order: 0, 4096 bytes)
TCP established hash table entries: 1024 (order: 1, 8192 bytes)
TCP bind hash table entries: 1024 (order: 0, 4096 bytes)
TCP: Hash tables configured (established 1024 bind 1024)
TCP reno registered
UDP hash table entries: 256 (order: 0, 4096 bytes)
UDP-Lite hash table entries: 256 (order: 0, 4096 bytes)
NET: Registered protocol family 1
squashfs: version 4.0 (2009/01/31) Phillip Lougher
JFFS2 version 2.2 (NAND) (SUMMARY) (LZMA) (RTIME) (CMODE_PRIORITY) (c) 2001-2006 Red Hat, Inc.
msgmni has been set to 58
io scheduler noop registered
io scheduler deadline registered (default)
Serial: 8250/16550 driver, 2 ports, IRQ sharing disabled
serial8250: ttyS0 at MMIO 0x10000500 (irq = 13) is a 16550A
serial8250: ttyS1 at MMIO 0x10000c00 (irq = 20) is a 16550A
physmap platform flash device: 00800000 at bf000000
physmap-flash.0: Found 1 x16 devices at 0x0 in 16-bit bank. Manufacturer ID 0x0000c2 Chip ID 0x0022a8
Amd/Fujitsu Extended Query Table at 0x0040
Amd/Fujitsu Extended Query version 1.1.
Silicon revision: 0
Address sensitive unlock: Required
Erase Suspend: Read/write
Block protection: 4 sectors per group
Temporary block unprotect: Supported
Block protect/unprotect scheme: 4
Number of simultaneous operations: 0
Burst mode: Not supported
Page mode: Not supported
Vpp Supply Minimum Program/Erase Voltage: 9.5 V
Vpp Supply Maximum Program/Erase Voltage: 10.5 V
Top/Bottom Boot Block: Bottom boot
number of CFI chips: 1
cmdlinepart partition parsing not available
RedBoot partition parsing not available
Using physmap partition information
Creating 6 MTD partitions on "physmap-flash.0":
0x000000000000-0x000000030000 : "u-boot"
0x000000030000-0x000000040000 : "config"
0x000000040000-0x000000050000 : "factory"
0x000000050000-0x000000120000 : "kernel"
0x000000120000-0x000000800000 : "rootfs"
mtd: partition "rootfs" extends beyond the end of device "physmap-flash.0" -- size truncated to 0x2e0000
mtd: partition "rootfs" set to be root filesystem
mtd: partition "rootfs_data" created automatically, ofs=260000, len=1A0000
0x000000260000-0x000000400000 : "rootfs_data"
0x000000050000-0x000000800000 : "firmware"
mtd: partition "firmware" extends beyond the end of device "physmap-flash.0" -- size truncated to 0x3b0000
TCP westwood registered
NET: Registered protocol family 17
802.1Q VLAN Support v1.8 Ben Greear
All bugs added by David S. Miller
lib80211: common routines for IEEE802.11 drivers
VFS: Mounted root (squashfs filesystem) readonly on device 31:4.
Freeing unused kernel memory: 148k freed
- preinit -
Press the [f] key and hit [enter] to enter failsafe mode
- regular preinit -
JFFS2 notice: (290) jffs2_build_xattr_subsystem: complete building xattr subsystem, 1 of xdatum (1 unchecked, 0 orphan) and 4 of xref (0 dead, 2 orphan) found.
switching to jffs2
- init -

Please press Enter to activate this console. Compat-wireless backport release: compat-wireless-2011-06-23
Backport based on wireless-testing.git master-2011-06-22
cfg80211: Calling CRDA to update world regulatory domain
device eth0.1 entered promiscuous mode
device eth0 entered promiscuous mode
br-lan: port 1(eth0.1) entering forwarding state
br-lan: port 1(eth0.1) entering forwarding state
PPP generic driver version 2.4.2
ip_tables: (C) 2000-2006 Netfilter Core Team
NET: Registered protocol family 24
nf_conntrack version 0.5.0 (471 buckets, 1884 max)
cfg80211: World regulatory domain updated:
cfg80211: (start_freq - end_freq @ bandwidth), (max_antenna_gain, max_eirp)
cfg80211: (2402000 KHz - 2472000 KHz @ 40000 KHz), (300 mBi, 2000 mBm)
cfg80211: (2457000 KHz - 2482000 KHz @ 20000 KHz), (300 mBi, 2000 mBm)
cfg80211: (2474000 KHz - 2494000 KHz @ 20000 KHz), (300 mBi, 2000 mBm)
cfg80211: (5170000 KHz - 5250000 KHz @ 40000 KHz), (300 mBi, 2000 mBm)
cfg80211: (5735000 KHz - 5835000 KHz @ 40000 KHz), (300 mBi, 2000 mBm)

BusyBox v1.18.5 (2011-08-02 21:37:04 MSD) built-in shell (ash)
Enter 'help' for a list of built-in commands.

_______ ________ __
| |.-----.-----.-----.| | | |.----.| |_
| - || _ | -__| || | | || _|| _|
|_______|| __|_____|__|__||________||__| |____|
|__| W I R E L E S S F R E E D O M
ATTITUDE ADJUSTMENT (bleeding edge, r27878) ----------
* 1/4 oz Vodka Pour all ingredients into mixing
* 1/4 oz Gin tin with ice, strain into glass.
* 1/4 oz Amaretto
* 1/4 oz Triple sec
* 1/4 oz Peach schnapps
* 1/4 oz Sour mix
* 1 splash Cranberry juice
-----------------------------------------------------
root@OpenWrt:/#

ee-locket

Well, I really wanted to make my own version of a locket with leds, as seen on HaD some time ago. So I ordered some lockets as soon as I could.
However, the seller did include a smaller locket as a gift…. And I couldn’t think of a use to it… Well, until I gave it a thought.
Meet the ee-locket! A locket with 64k of eeprom embedded in it on a tiny PCB.

P.S. Still needs some ultrasonic washing…

Necromant’s MultiDrop UART: The software.

Well, there were quite a few bugs in the device and it looks like the baseboard is going to redesigned, although it will still be compatible with all the extension ‘shields’.
It looked like the transistors gave a .2 volts voltage drop, and the diodes dropped 0.1 more, turning regulated 3.3 into 3.0 volts, so sot-23 mosfets are already on the way.
Meanwhile, I started to write some software. This resulted into a dumb commandline utility called muart-ctl.
And… A KDE4 Plasmoid, that acts as a frontend.

Here goes the obligatory screenshot:
And the full shot of the desktop:

Profile management is not yet ready, and there are still some issues in the electronics, that need further addressing (And a new PCB!), but nevertheless it works.
The plasmoid is written in javascript, which was kind of pain. The bindings are not well documented, so I had to do quite a lot of guessing. Nevertheless, as for my first javascript project it all went fine. Lots of thanks to Nikita Melnichenko, for the plasmoid ‘makeprogress’. I tore that one apart and used as a reference.

Necromant’s MultiDrop UART: The Baseboard

I work with a lot of different embedded boards. Most of them have linux istalled. And what do these have in common? Yep. UART. The thing you use to debug them, send uboot parameters and etc. When there are a plenty of boards around, you tend to have a pile of usb<-->uart chips around, your /dev/ becomes a mess (Is that ttyUSB0 or ttyUSB1?) that even udev cannot sort out (Damn, I’ve swapped that out, so it’s not /dev/armboard1)…
And the worst is the difference in logic levels. I have a couple of exotic boards that require 2.5 volts. Something few uart bridges can handle out of the box.
So I had a quick look at what I had around. Since I mostly work with one board at a time…
1. I grabbed an ft232rl
2. Some buffers and shift registers
3. Some POTs and ams1117 voltage regulators
4. Lottsa coffee

The idea was simple as hell. MUX the UART and select the channel you want to work with a small command line utility. FT232RL has the CBUS pins that can be used in bitbang mode. e.g. You can use them as GPIO. 4 GPIO are quite enough for 2 shift registers.
Each shift register has clk and data pins, which you can use to serially input the data, and 8 pins of parallel output, which are used to actually cotrol hardware.
So, my FT232RL got 2 shift registers.
One selects the power channel, the other selects the adress of the UART outlet to use.
Forthe power circuit, I had no mosfets around (huge 10 Amps thingies do not count), so I made use of some PNP transistors in digital switch mode. After the switch there goes a linear stabilizer – AMS1117, adjustable version, which is adjusted by a POT. And after that through a Schottky diode (Is it really required?) it goes to VCCIO power net.
So we have 7 power channels. 3.3, 5 volts and 5 adjustable channels. The voltage can be anything fro 2 to 5 volts so that gives us some freedom of choice
The baseboard has 2 pin arrays that will be used to connect arduino-like shields with buffers and outputs. One has the address selection shift register outputs, that will be connected to ‘/inhibit’ pins of the buffers on the shields, one has the actual outputs of FT232RL serial port.
So I set off to work and after one wasted day of my life I got a baseboard ready. There it is, my little thingie:

.
There were a few bugs though. I had a wrong kicad footprint that resulted in the need of turning all the sot-23 transistors over. And the Schottkey diodes were a bit smaller, so I had to bend the contacts a bit. I also made a small mistake: Since the shift registers are powered via the VCCIO voltage, disabling all power to this net results in inability to supply any voltage again unless you short VCCIO to some voltage and then turn on the correct transistor. So I sacrificed one adjustable channel and made it always output 2 volts of ‘standby’ to the VCCIO net.
Next weekend I’m gonna make some shields and finally publish all the fixed circuits and layouts.
Btw, that’s plain press’n’peel method I used to make the board.

Creating .libs for kicad/eeschema semiautomatically

Well, everyone has to eventually make one. Since we have a cool online utility from C. Rohrbacher http://kicad.rohrbacher.net/quicklib.php This is quite simple. Just fill in all the pins, orient them and you are ready to go…
But if there are over 200 pins,this is getting tiresome. When I was making a lib for at91rm9200 I got tired at 30th pin. And there are 208 of them and it’s quite easy to screw up… So I got a nice idea. Unfortunately, I didn’t find C. Rohrbacher’s email on his site, as well as I saw no sources of the utility. So, it was time for a hackish solution.

We’ll need:

bash (Oh, yeah!)
xdotool
okular (Any other PDF viewr thatcan select text will do)

Step one.
Open the datasheet, find the pin list, select the pins:

Step two.
Copypaste them into a blank file. They should be strictly ordered

Step three
Now a little black magic. Save the following bash script somewhere:

#!/bin/bash
write_pin()
{
xdotool type "$1"
xdotool key Tab Tab Tab Tab Tab Tab
}
 
if [ $# -lt 1 ]; then
  echo "Usage: fill-pins filename"
  exit
fi
 
echo "Starting in 5 seconds..."
sleep 5
 
cat $1|while read line; do
  write_pin "$line"
done

chmod+x, And give it the file with pins you’ve madeearlier. You have 5 seconds to open the browser on page withpins and select PIN1.
The script will do everything by itself. Just relax – it looks pretty funny

And by the way, kill all instances of skype, icq, kopete, irc – these things tend to steal focus from the browser and screw thing up.

Готовим фотошаблоны печаток из kicad’a при помощи latex

Если вы начинали со Sprint Layout, то наверное помните диалог печати, который позволяет совместить на листе сколько-то копий одной и той же платы. К сожалению, одной единственной, или одного и того же слоя.
В kicad’е нет и этого. Если плата здоровая, а изготавливать с первого раза уже получается почти всегда, то это нормально. Но если вдруг надо изготовить сразу пачку мелких плат, или отпечатать сразу два слоя рядом… В общем, облом.
Посему, начал я думать над каким-нибудь костылем. kicad отлично выводит как в gerber (для производства) так и в postscript (для кустарного производства). Последнее-то мне и приглянулось.
Рамку смело выкидываем в реактор, она нам не понадобится.
После выведения в postscript мы имеем несколько .ps файликов, с каждым слоем. Каждый занимает A4 страницу.
Первым делом надо их перегнать во что-то удобоваримое. Сначала я перегнал их в png imagemagic’ом и увидел здоровенный холст на страницу размером. Не вариант, ибо bounding box оно не считает, и картинка выйдет во весь лист. На помощь пришла маленькая утилитка ps2eps. Она создает векторное eps изображение из постсрипта и обсчитывает тот самый bounding box. Иными словами, в LaTeX документ можно будет эту картинку воткнуть тупо при помощи заклинания

\includegraphics[scale=1]{jtagice-1.eps}

И это будет гарантировать масштаб 1:1, то есть если это статья для журнала, то читатели вашей научной статьи смогут ксерануть страничку на глянец и сразу сделать плату для своего домашнего реактора.

Теперь, остается только автоматизировать процесс.
Немного покумекав, я соорудил вот такой костыль.
В виде аргументов скармливаем:
1. Как обозвать проект в первой и единственной строчки текста.
2. Сколько раз изпользовать каждый из файлов
3. Сами файлики. Много их…

Скрипт требует наличие LaTeX’a, а в конце запускает окуляр. Последние строчки скрипта можно подкрутить по вкусу, но смысл изменится врядли. В идеале, конечно, можно было подкрутить оформление. Была мысля соорудить рамку по ЕСКД ради прикола, но она много места на листе занимает, так что отправилась она прямиком в реактор.

#!/bin/bash
# This program is free software. It comes without any warranty, to
# the extent permitted by applicable law. You can redistribute it
# and/or modify it under the terms of the Do What The Fuck You Want
# To Public License, Version 2, as published by Sam Hocevar. See
# http://sam.zoy.org/wtfpl/COPYING for more detail
 
usage()
{
echo "mkpcb.  (c) 2011, Necromant"
echo "Generate a printable document out of several postscript images. "
echo "usage: mkpcb project_name n file1.ps file2.ps ..."
echo "where n is the number of times to use each file"
echo "Great for exporting PCBs from kicad for batch printout"
}
 
if [ "$#" -lt "3" ]; then
echo "Need moar args"
usage
exit 1
fi
 
if [ "$1" == "--help" ]; then
usage
exit 1
fi
 
gen_latex()
{
cat << EOF
\documentclass[a4paper,14pt]{report} %размер бумаги устанавливаем А4, шрифт 12пунктов
\usepackage[T2A]{fontenc}
\usepackage{extsizes}
\usepackage{listings}
\usepackage{longtable}
\usepackage{courier}
\usepackage{tabularx}
\usepackage{framed}
\usepackage[utf8]{inputenc}%включаем свою кодировку: koi8-r или utf8 в UNIX, cp1251 в Windows
\usepackage[english,russian]{babel}%используем русский и английский языки с переносами
\usepackage{amssymb,amsfonts,amsmath,mathtext,cite,enumerate,float} %подключаем нужные пакеты расширений
\usepackage[dvips]{graphicx} %хотим вставлять в диплом рисунки?
\graphicspath{{data/images}}%путь к рисункам
 
 
\makeatletter
\renewcommand{\@biblabel}[1]{#1.} % Заменяем библиографию с квадратных скобок на точку:
\makeatother
 
%\usepackage{geometry} % Меняем поля страницы
%\geometry{left=2cm}% левое поле
%\geometry{right=1.5cm}% правое поле
%\geometry{top=1cm}% верхнее поле
%\geometry{bottom=2cm}% нижнее поле
\usepackage[a4paper,left=30mm,right=15mm,top=25mm,bottom=25mm]{geometry}
 
\renewcommand{\theenumi}{\arabic{enumi}}% Меняем везде перечисления на цифра.цифра
\renewcommand{\labelenumi}{\arabic{enumi}}% Меняем везде перечисления на цифра.цифра
\renewcommand{\theenumii}{.\arabic{enumii}}% Меняем везде перечисления на цифра.цифра
\renewcommand{\labelenumii}{\arabic{enumi}.\arabic{enumii}.}% Меняем везде перечисления на цифра.цифра
\renewcommand{\theenumiii}{.\arabic{enumiii}}% Меняем везде перечисления на цифра.цифра
\renewcommand{\labelenumiii}{\arabic{enumi}.\arabic{enumii}.\arabic{enumiii}.}% Меняем везде перечисления на цифра.цифра
\renewcommand{\lstlistingname}{Листинг \No}
\renewcommand{\baselinestretch}{1.25}
 
%\addtocounter{chapter}{0} % не хочу нумеровать главы
%\setcounter{secnumdepth}{-1} % глубина оглавления
 
 
 
 
 
 
\begin{document}
EOF
echo "Plots for Project $1 ($2 pieces each)\\"
echo ""
echo ""
COUNT=$2
shift
shift
 
ps2eps $*
 
while [ "$COUNT" -gt "0" ]; do
for plot in $*; do
echo "\includegraphics[scale=1]{`basename $plot .ps`.eps}"
let COUNT-=1
#\includegraphics[scale=1]{2.eps}  
 
#%\includegraphics[scale=1]{jtagice-1.eps}  
#%\includegraphics[scale=1]{jtagice-1.eps}  
done 
done
 
echo "\end{document}"
}
 
 
gen_latex $* > output.tex
latex output.tex
okular output.dvi