]> rtime.felk.cvut.cz Git - lincan.git/blob - embedded/app/usbcan/main.c
Merge branch 'master' into can-usb1
[lincan.git] / embedded / app / usbcan / main.c
1 /**************************************************************************/
2 /* File: main.c - setup and main loop of USB<->CAN converter              */
3 /*                                                                        */
4 /* LinCAN - (Not only) Linux CAN bus driver                               */
5 /* Copyright (C) 2002-2011 DCE FEE CTU Prague <http://dce.felk.cvut.cz>   */
6 /* Copyright (C) 2008 Jan Kriz email:johen@post.cz                        */
7 /*                                                                        */
8 /* LinCAN is free software; you can redistribute it and/or modify it      */
9 /* under terms of the GNU General Public License as published by the      */
10 /* Free Software Foundation; either version 2, or (at your option) any    */
11 /* later version.  LinCAN is distributed in the hope that it will be      */
12 /* useful, but WITHOUT ANY WARRANTY; without even the implied warranty    */
13 /* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU    */
14 /* General Public License for more details. You should have received a    */
15 /* copy of the GNU General Public License along with LinCAN; see file     */
16 /* COPYING. If not, write to the Free Software Foundation, 675 Mass Ave,  */
17 /* Cambridge, MA 02139, USA.                                              */
18 /*                                                                        */
19 /* To allow use of LinCAN in the compact embedded systems firmware        */
20 /* and RT-executives (RTEMS for example), main authors agree with next    */
21 /* special exception:                                                     */
22 /*                                                                        */
23 /* Including LinCAN header files in a file, instantiating LinCAN generics */
24 /* or templates, or linking other files with LinCAN objects to produce    */
25 /* an application image/executable, does not by itself cause the          */
26 /* resulting application image/executable to be covered by                */
27 /* the GNU General Public License.                                        */
28 /* This exception does not however invalidate any other reasons           */
29 /* why the executable file might be covered by the GNU Public License.    */
30 /* Publication of enhanced or derived LinCAN files is required although.  */
31 /**************************************************************************/
32
33 #include <stdio.h>
34 #include <string.h>
35 #include <cpu_def.h>
36 #include <system_def.h>
37 #include <lt_timer.h>
38 #include <local_config.h>
39 #include <usb/usbdebug.h>
40 #include <usb/usb.h>
41 #include <usb/lpc.h>
42 #include <usb/usb_srq.h>
43 #include <mem_loc.h>
44 #include <keyval_id.h>
45 #include <hal_machperiph.h>
46 #include <keyval_loc.h>
47 #include <lpciap.h>
48 #include <lpciap_kvpb.h>
49
50 #include <endian.h>
51 #if __BYTE_ORDER == __BIG_ENDIAN
52   #include <byteswap.h>
53 #endif
54
55 #include "./can/can.h"
56 #include "./can/sja1000p.h"
57 #include "./can/main.h"
58
59 // #include "./can/can_sysdep.h"
60 #include "./can/modparms.h"
61 #include "./can/devcommon.h"
62
63 #include "./can/ul_usb1.h"
64 //#include "./can/setup.h"
65
66 #include "./usb/usb_defs.h"
67 #include "./usb/usb_vend.h"
68
69 #define MASK_EP1RX  0x01
70 #define MASK_EP1TX  0x02
71
72 #define CAN_OP_MASK 0x80
73 #define CAN_OP_READ 0x80
74 #define CAN_OP_WRITE 0x00
75
76 #ifdef USB_MAX_PACKET
77         #undef USB_MAX_PACKET
78         #define USB_MAX_PACKET 16
79 #endif
80 /***********************************************************************
81  * Note:
82  * Comparing to LinCAN, there is no need to sleep for processes
83  * because the degree of filling of fifo from the client side
84  * is solved in main cycle (no new messages are accepted when full)
85  * and on the server side by speed of USB interface. FIFO in edge
86  * from SJA chip to USB interface should never be filled.
87  ***********************************************************************/
88
89 /***********************************************************************
90  * Note:
91  * Code is wittingly complex in order to ease future changes in hardware
92  * configuration and to make it as much similar as the code of LinCAN
93  ***********************************************************************/
94
95 LT_TIMER_DEC(lt_10msec)
96 LT_TIMER_IMP(lt_10msec)
97 LT_TIMER_DEC(lt_100msec)
98 LT_TIMER_IMP(lt_100msec)
99 LT_TIMER_DEC(lt_2sec)
100 LT_TIMER_IMP(lt_2sec)
101
102 typedef void (*FNC)(); //function ptr
103
104 /***********************************************************************
105  * global variables
106  ***********************************************************************/
107
108
109 usb_device_t usb_device;
110
111 usb_ep_t eps[NUM_ENDPOINTS];
112 unsigned char ep1_rx_buff[USB_MAX_PACKET];
113 unsigned char ep1_tx_buff[USB_MAX_PACKET];
114 uint8_t timer_str,timer_rx_off,timer_tx_off,timer_configured;
115 volatile uint8_t bootloader_run;
116
117 uint8_t vendor_ret;
118
119 int processlocal;
120
121 int baudrate[MAX_TOT_CHIPS];
122 struct canhardware_t canhardware;
123 struct canhardware_t *hardware_p=&canhardware;
124 struct canchip_t *chips_p[MAX_TOT_CHIPS];
125 struct msgobj_t *objects_p[MAX_TOT_MSGOBJS];
126
127 struct canuser_t *canuser;
128
129 extern int init_chip_struct(struct candevice_t *candev, int chipnr, int irq, long baudrate);
130 extern int register_chip_struct(struct canchip_t *chip, int minorbase);
131 extern int register_obj_struct(struct msgobj_t *obj, int minorbase);
132
133 /***********************************************************************
134  * IF SOMETHING BAD HAPPENED
135  ***********************************************************************/
136
137 int sys_err(){
138   unsigned char i=0;
139
140   while(1) {
141     if (lt_100msec_expired(100)) {
142       i++;
143       if (i&1) {
144         SET_OUT_PIN(LED_PORT,LED_ERR);
145       } else {
146         CLR_OUT_PIN(LED_PORT,LED_ERR);
147       }
148      #ifdef WATCHDOG_ENABLED
149       watchdog_feed();
150      #endif /* WATCHDOG_ENABLED */
151     }
152   }
153 }
154
155 /***********************************************************************
156  * Microsecond delay routine
157  ***********************************************************************/
158
159 void udelay(long time)
160 {
161   volatile long ticks=(time * CCLK) / 2000000;
162   do{
163     ticks--;
164   } while(ticks>0);
165 }
166
167
168 /***********************************************************************
169  * Routine for visible LED blinking (on USB transmission)
170  ***********************************************************************/
171
172 void timer_10ms(void)
173 {
174   if (timer_tx_off!=0) timer_tx_off--;
175   else SET_OUT_PIN(LED_PORT,LED1_BIT);
176   if (timer_rx_off!=0) timer_rx_off--;
177   else SET_OUT_PIN(LED_PORT,LED2_BIT);
178 /*  if (timer_configured!=0) timer_configured--;
179   else {
180     timer_configured=20;
181                 CLR_OUT_PIN(LED_PORT,LED1_BIT);
182                 CLR_OUT_PIN(LED_PORT,LED2_BIT);
183                 timer_rx_off=timer_tx_off=5;
184   }*/
185 }
186
187 /***********************************************************************
188  * Main routine
189  ***********************************************************************/
190
191 int main(void)
192 {
193         struct candevice_t *candev;
194         struct canchip_t *chip=NULL;
195         struct msgobj_t *obj;
196         struct canque_ends_t *qends;
197         struct canque_edge_t *edge,*qedge;
198         struct canque_slot_t *slot;
199         struct canmsg_t canmsg;
200         can_spin_irqflags_t iflags;
201
202         int chipnr,bd;
203         int i,size,m=0;
204
205         CANMSG("Starting USBCAN module firmware...\n");
206
207 //      volatile int i=0;
208         bootloader_run=0;
209         /***********************************/
210         lt_10msec_init();
211         lt_100msec_init();
212         lt_2sec_init();
213
214         SET_OUT_PIN(LED_PORT,LED_ERR);
215         CLR_OUT_PIN(LED_PORT,LED_GP);
216
217         if (USB_MAX_PACKET<16){
218                 CANMSG("Maximum packet size less than 16B (is %dB)\n",USB_MAX_PACKET);
219                 sys_err();
220         }
221
222         /***********************************************************************
223          * CAN device initialization - device side (adapted from LinCAN setup.c)
224          ***********************************************************************/
225
226         can_init();
227
228         DEBUGMSG("Initiating CAN device initialization\n");
229         baudrate[0]=1000;
230
231         canqueue_kern_initialize();
232
233         hardware_p->nr_boards=1;
234
235         candev=(struct candevice_t *)malloc(sizeof(struct candevice_t));
236         if (!candev){
237                 CANMSG("No space left in memory\n");
238                 sys_err();
239         }
240         memset(candev, 0, sizeof(struct candevice_t));
241
242         hardware_p->candevice[0]=candev;
243         candev->candev_idx=0;
244         candev->io_addr=0;
245         candev->dev_base_addr=0;
246
247         candev->hwspecops=(struct hwspecops_t *)malloc(sizeof(struct hwspecops_t));
248         if (!candev->hwspecops){
249                 CANMSG("No space left in memory\n");
250                 sys_err();
251         }
252         memset(candev->hwspecops, 0, sizeof(struct hwspecops_t));
253
254         ul_usb1_register(candev->hwspecops);
255
256         bd=baudrate[0];
257         if (candev->hwspecops->init_hw_data(candev)){
258                 CANMSG("HW data could not be initialized\n");
259                 sys_err();
260         }
261         /* Alocate and initialize the chip structures */
262         for (chipnr=0; chipnr < candev->nr_all_chips; chipnr++) {
263 /*              if(chipnr<irqnum)
264                         irqsig=irq[*irq_param_idx_p+chipnr];*/
265                 if (init_chip_struct(candev, chipnr, 0, bd*1000)){
266                         CANMSG("Chip structure could not be initialized\n");
267                         sys_err();
268                 }
269         }
270         for (chipnr=0; chipnr < candev->nr_all_chips; chipnr++) {
271                 struct canchip_t *chip=candev->chip[chipnr];
272                 int objnr;
273
274                 register_chip_struct(chip, m);
275
276                 for (objnr=0; objnr<chip->max_objects; objnr++) {
277                         register_obj_struct(chip->msgobj[objnr], m);
278                         if(m>=0) m++;
279                 }
280         }
281         if (candev->hwspecops->request_io(candev))
282                 sys_err();
283         candev->flags|=CANDEV_IO_RESERVED;
284         if (candev->hwspecops->reset(candev))
285                 sys_err();
286         for(chipnr=0; chipnr<candev->nr_all_chips; chipnr++) {
287                 if((chip=candev->chip[chipnr])==NULL)
288                         continue;
289
290                 if(chip->chipspecops->attach_to_chip(chip)<0) {
291 //                      CANMSG("Initial attach to the chip HW failed\n");
292                         sys_err();
293                 }
294
295                 chip->flags |= CHIP_ATTACHED;
296
297 // Interrupts from chip are served in main cycle
298 /*              if(can_chip_setup_irq(chip)<0) {
299 //                      CANMSG("Error to setup chip IRQ\n");
300                         sys_err();
301                 }*/
302         }
303
304         if (candev->flags & CANDEV_PROGRAMMABLE_IRQ)
305                 if (candev->hwspecops->program_irq(candev)){
306 //                      CANMSG("Error to program board interrupt\n");
307                         sys_err();
308                 }
309
310         /***********************************************************************
311          * CAN device initialization - client side (adapted from LinCAN open.c)
312          ***********************************************************************/
313
314         chip=candev->chip[0];
315         obj=chip->msgobj[0];
316         atomic_inc(&obj->obj_used);
317         can_msgobj_set_fl(obj,OPENED);
318
319         if (chip->flags & CHIP_CONFIGURED)
320                 DEBUGMSG("Device is already configured.\n");
321         else {
322                 if (chip->chipspecops->chip_config(chip))
323                         CANMSG("Error configuring chip.\n");
324                 else
325                         chip->flags |= CHIP_CONFIGURED;
326
327                 if (chip->chipspecops->pre_read_config(chip,obj)<0)
328                         CANMSG("Error initializing chip for receiving\n");
329
330         } /* End of chip configuration */
331
332         canuser = (struct canuser_t *)malloc(sizeof(struct canuser_t));
333         if(canuser == NULL) sys_err();
334         canuser->flags=0;
335 //      canuser->userinfo.fileinfo.file = file;
336         canuser->msgobj = obj;
337 //      canuser->magic = CAN_USER_MAGIC;
338 //      file->private_data = canuser;
339
340         qends = (struct canque_ends_t *)malloc(sizeof(struct canque_ends_t));
341         if(qends == NULL) sys_err();
342         canqueue_ends_init_kern(qends);
343         canuser->qends = qends;
344
345         /*required to synchronize with RT-Linux context*/
346         can_spin_lock_irqsave(&canuser_manipulation_lock, iflags);
347         list_add(&canuser->peers, &obj->obj_users);
348         can_spin_unlock_irqrestore(&canuser_manipulation_lock, iflags);
349
350         if(canqueue_connect_edge(edge=canque_new_edge_kern(MAX_BUF_LENGTH),
351                 canuser->qends, obj->qends)<0) sys_err();
352
353         if(canqueue_connect_edge(canuser->rx_edge0=canque_new_edge_kern(MAX_BUF_LENGTH),
354                 obj->qends, canuser->qends)<0) sys_err();
355         /*FIXME: more generic model should be used there*/
356         canque_edge_decref(canuser->rx_edge0);
357         canque_edge_decref(edge);
358
359
360         /***********************************************************************
361          * USB Init
362          ***********************************************************************/
363
364         memset( &usb_device, 0, sizeof( usb_device));
365         usb_device.id = 1;
366         usb_device.devdes_table = &usb_devdes_table;
367         usb_device.init = usb_lpc_init;
368         usb_debug_set_level(DEBUG_LEVEL_NONE);
369         usb_device.cntep = NUM_ENDPOINTS;
370         usb_device.ep = eps;
371
372         eps[0].max_packet_size = USB_MAX_PACKET;
373         eps[1].max_packet_size = USB_MAX_PACKET;
374         eps[0].epnum = 0x01;
375         eps[1].epnum = 0x81;
376         eps[0].event_mask = 0x04;
377         eps[1].event_mask = 0x08;
378         eps[0].udev = &usb_device;
379         eps[1].udev = &usb_device;
380
381         usb_device.vendor_fnc=usbcan_vendor;
382
383         usb_init(&usb_device);
384         usb_connect(&usb_device);
385         usb_device.ep_events |= MASK_EP1TX;
386
387         /***********************************************************************
388          * Start
389          ***********************************************************************/
390
391         timer_rx_off=timer_tx_off=timer_str=timer_configured=0;
392         while (1) {
393
394                 usb_check_events(&usb_device);
395                 usb_control_response(&usb_device);
396
397                 if (!(IO0PIN&P0_SJA1000_INT_PIN)) //INT PIN is inverted
398                         chip->chipspecops->irq_handler(0,chip);
399
400                 if (usb_device.ep_events & MASK_EP1RX) {  //EP1RX - data waiting to receive
401                         if (canque_get_inslot(qends, &qedge, &slot, 0)>=0){ //Free slot obtained
402                                 size=usb_udev_read_endpoint(&eps[0],ep1_rx_buff,16);
403                                 if (size==16){
404                                         uint16_t msgflags;
405                                         uint32_t msgid;
406                                         canmsg.cob=0;
407                                         canmsg.length=*(uint8_t *)(ep1_rx_buff+1);
408                                         if (canmsg.length > CAN_MSG_LENGTH)
409                                                 canmsg.length=CAN_MSG_LENGTH;
410                                         msgflags=*(uint16_t *)(ep1_rx_buff+2);
411                                         msgid=*(uint32_t *)(ep1_rx_buff+4);
412                                         #if __BYTE_ORDER == __BIG_ENDIAN
413                                                 msgflags  = bswap_16( msgflags);
414                                                 msgid  = bswap_32( msgid);
415                                         #endif
416                                         canmsg.flags=msgflags;
417                                         canmsg.id=msgid;
418
419                                         for (i=0;i<canmsg.length;i++){
420                                                 canmsg.data[i]=*(unsigned char*)(ep1_rx_buff+8+i);
421                                         }
422                                         for (;i<CAN_MSG_LENGTH;i++){
423                                                 canmsg.data[i]=0;
424                                         }
425                                         /* Automatic selection of extended format if ID>2047 */
426                                         if (canmsg.id & ~0x7ffl & MSG_ID_MASK ) canmsg.flags |= MSG_EXT;
427                                         /* has been dependent on "extended" option */
428                                         slot->msg=canmsg;
429                                         canque_put_inslot(qends, qedge, slot);
430                                 }
431                                 else
432                                         canque_abort_inslot(qends,qedge,slot);
433                                 timer_rx_off=50;        //rosviceni diody pri prijmu
434                                 CLR_OUT_PIN(LED_PORT,LED2_BIT);
435                                 usb_device.ep_events &= ~MASK_EP1RX;
436                         }
437
438
439 /*                      if (size==2){
440                                 uint8_t val;
441                                 if ((data[0]&CAN_OP_MASK)==CAN_OP_READ){ // Get data from CAN device and return to caller
442                                         val = can_read(data[0] & ~CAN_OP_MASK);
443                                         *(data+1)=val;
444                                         usb_udev_write_endpoint(&eps[1],(unsigned char *)data,size);
445                                         timer_rx_off=50;        //rosviceni diody pri prijmu
446                                         CLR_OUT_PIN(LED_PORT,LED2_BIT);
447                                         usb_can_send=0;
448                                 }
449                                 if ((data[0]&CAN_OP_MASK)==CAN_OP_WRITE){ // Save data to CAN device
450                                         can_write(data[1], data[0] & ~CAN_OP_MASK);
451                                         timer_tx_off=50;                //rozsviceni diod pri vysilani
452                                         CLR_OUT_PIN(LED_PORT,LED1_BIT);
453                                 }
454                         }*/
455                 }
456
457                 if(usb_device.ep_events & MASK_EP1TX){ //EP1TX - data transmitted
458                         if(canque_test_outslot(qends, &qedge, &slot)>=0){
459                                 DEBUGMSG("CAN message ready to send over usb\n");
460                                 uint16_t msgflags;
461                                 uint32_t msgid;
462
463                                 *(uint8_t *)(ep1_tx_buff)=0;
464                                 *(uint8_t *)(ep1_tx_buff+1)=slot->msg.length;
465
466                                 msgflags=slot->msg.flags;
467                                 msgid=slot->msg.id;
468                                 #if __BYTE_ORDER == __BIG_ENDIAN
469                                         msgflags  = bswap_16( msgflags);
470                                         msgid  = bswap_32( msgid);
471                                 #endif
472
473                                 *(uint16_t *)(ep1_tx_buff+2)=msgflags;
474                                 *(uint32_t *)(ep1_tx_buff+4)=msgid;
475                                 for (i=0;i<slot->msg.length;i++){
476                                         *(uint8_t *)(ep1_tx_buff+8+i)=slot->msg.data[i];
477                                 }
478                                 for (;i<CAN_MSG_LENGTH;i++){
479                                         *(uint8_t *)(ep1_tx_buff+8+i)=0;
480                                 }
481                                 usb_udev_write_endpoint(&eps[1],ep1_tx_buff,16);
482
483                                 canque_free_outslot(qends, qedge, slot);
484                                 timer_tx_off=50;                //rozsviceni diod pri vysilani
485                                 CLR_OUT_PIN(LED_PORT,LED1_BIT);
486                                 usb_device.ep_events &= ~MASK_EP1TX;
487                         }
488                 }
489
490                 //if (usb_can_send && )
491
492 #ifdef WATCHDOG_ENABLED
493                 watchdog_feed();
494 #endif /* WATCHDOG_ENABLED */
495
496                 /* 10ms timer */
497                 if (lt_10msec_expired(10))
498                         timer_10ms();
499         }
500
501         SET_OUT_PIN(LED_PORT,LED_GP);
502         SET_OUT_PIN(LED_PORT,LED_ERR);
503
504         /* unreachable code */
505 #ifdef SDCC
506         vec_jmp(0x0);  /* need to call a function from misc to correct linking */
507 #endif
508         return 0;
509 }