]> rtime.felk.cvut.cz Git - lincan.git/blob - embedded/app/usbcan/main.c
6053645608fc458720b3441d0ae185eb88134e61
[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
65 //#include "./can/setup.h"
66
67 #include "./usb/usb_defs.h"
68 #include "./usb/usb_vend.h"
69
70 // DEBUG CAN
71 #include "can/lpc17xx_can.h"
72 // DEBUG CAN - end
73
74 #define MASK_EP1RX  0x01
75 #define MASK_EP1TX  0x02
76
77 #define CAN_OP_MASK 0x80
78 #define CAN_OP_READ 0x80
79 #define CAN_OP_WRITE 0x00
80
81 #ifdef USB_MAX_PACKET
82         #undef USB_MAX_PACKET
83         #define USB_MAX_PACKET 16
84 #endif
85 /***********************************************************************
86  * Note:
87  * Comparing to LinCAN, there is no need to sleep for processes
88  * because the degree of filling of fifo from the client side
89  * is solved in main cycle (no new messages are accepted when full)
90  * and on the server side by speed of USB interface. FIFO in edge
91  * from SJA chip to USB interface should never be filled.
92  ***********************************************************************/
93
94 /***********************************************************************
95  * Note:
96  * Code is wittingly complex in order to ease future changes in hardware
97  * configuration and to make it as much similar as the code of LinCAN
98  ***********************************************************************/
99
100 LT_TIMER_DEC(lt_10msec)
101 LT_TIMER_IMP(lt_10msec)
102 LT_TIMER_DEC(lt_100msec)
103 LT_TIMER_IMP(lt_100msec)
104 LT_TIMER_DEC(lt_2sec)
105 LT_TIMER_IMP(lt_2sec)
106
107 typedef void (*FNC)(); //function ptr
108
109 /***********************************************************************
110  * global variables
111  ***********************************************************************/
112
113
114 usb_device_t usb_device;
115
116 usb_ep_t eps[NUM_ENDPOINTS];
117 unsigned char ep1_rx_buff[USB_MAX_PACKET];
118 unsigned char ep1_tx_buff[USB_MAX_PACKET];
119 uint8_t timer_str,timer_rx_off,timer_tx_off,timer_configured;
120 volatile uint8_t bootloader_run;
121
122 uint8_t vendor_ret;
123
124 int processlocal;
125
126 int baudrate[MAX_TOT_CHIPS];
127 struct canhardware_t canhardware;
128 struct canhardware_t *hardware_p=&canhardware;
129 struct canchip_t *chips_p[MAX_TOT_CHIPS];
130 struct msgobj_t *objects_p[MAX_TOT_MSGOBJS];
131
132 struct canuser_t *canuser;
133
134 extern int init_chip_struct(struct candevice_t *candev, int chipnr, int irq, long baudrate);
135 extern int register_chip_struct(struct canchip_t *chip, int minorbase);
136 extern int register_obj_struct(struct msgobj_t *obj, int minorbase);
137
138 /***********************************************************************
139  * IF SOMETHING BAD HAPPENED
140  ***********************************************************************/
141
142 int sys_err(){
143   
144   unsigned char i=0;
145
146   while(1) {
147     if (lt_100msec_expired(100)) {
148       i++;
149       if (i&1) {
150         SET_OUT_PIN(LED_PORT,LED_ERR);
151       } else {
152         CLR_OUT_PIN(LED_PORT,LED_ERR);
153       }
154      #ifdef WATCHDOG_ENABLED
155       watchdog_feed();
156      #endif /* WATCHDOG_ENABLED */
157     }
158   }
159 }
160
161 /***********************************************************************
162  * Microsecond delay routine
163  ***********************************************************************/
164 /*
165 void udelay(long time)
166 {
167   volatile long ticks=(time * CCLK) / 2000000;
168   do{
169     ticks--;
170   } while(ticks>0);
171 }
172 */
173
174 /***********************************************************************
175  * Routine for visible LED blinking (on USB transmission)
176  ***********************************************************************/
177
178 void timer_10ms(void)
179 {
180   if (timer_tx_off!=0) timer_tx_off--;
181   else SET_OUT_PIN(LED_PORT,LED1_BIT);
182   if (timer_rx_off!=0) timer_rx_off--;
183   else SET_OUT_PIN(LED_PORT,LED2_BIT);
184
185 /*  if (timer_configured!=0) timer_configured--;
186   else {
187     timer_configured=20;
188                 CLR_OUT_PIN(LED_PORT,LED1_BIT);
189                 CLR_OUT_PIN(LED_PORT,LED2_BIT);
190                 timer_rx_off=timer_tx_off=5;
191   }*/
192 }
193
194 /***********************************************************************
195  * Main routine
196  ***********************************************************************/
197
198 int main(void)
199 {
200         struct candevice_t *candev;
201         struct canchip_t *chip=NULL;
202         struct msgobj_t *obj;
203         struct canque_ends_t *qends;
204         struct canque_edge_t *edge,*qedge;
205         struct canque_slot_t *slot;
206         struct canmsg_t canmsg;
207         can_spin_irqflags_t iflags;
208
209         int chipnr,bd;
210         int i,size,m=0;
211
212         CANMSG("Starting USBCAN module firmware...\n");
213         
214
215 //      volatile int i=0;
216         bootloader_run=0;
217         /***********************************/
218
219         lt_10msec_init();
220         lt_100msec_init();
221         lt_2sec_init();
222
223         // DEBUG
224         //SET_OUT_PIN(LED_PORT,LED_ERR);
225         //CLR_OUT_PIN(LED_PORT,LED_GP);
226
227         if (USB_MAX_PACKET<16){
228                 CANMSG("Maximum packet size less than 16B (is %dB)\n",USB_MAX_PACKET);
229                 sys_err();
230         }
231
232 // !!! DEBUG - first version, only transmitting CAN messages with usage of queue system from LinCAN
233
234
235         //***********************************************************************
236         // * CAN device initialization - device side (adapted from LinCAN setup.c)
237         // ***********************************************************************
238
239         // DEBUG
240         //can_init(); // only for successful compiling (defined in can_lpcbusemu.c)
241
242
243         DEBUGMSG("Initiating CAN device initialization\n");
244         baudrate[0]=1000;
245
246         canqueue_kern_initialize();
247
248         hardware_p->nr_boards=1;
249
250         candev=(struct candevice_t *)malloc(sizeof(struct candevice_t));
251         if (!candev){
252                 CANMSG("No space left in memory\n");
253                 sys_err();
254         }
255         memset(candev, 0, sizeof(struct candevice_t));
256
257         hardware_p->candevice[0]=candev;
258         candev->candev_idx=0;
259         candev->io_addr=0;
260         candev->dev_base_addr=0;
261
262         candev->hwspecops=(struct hwspecops_t *)malloc(sizeof(struct hwspecops_t));
263         if (!candev->hwspecops){
264                 CANMSG("No space left in memory\n");
265                 sys_err();
266         }
267         memset(candev->hwspecops, 0, sizeof(struct hwspecops_t));
268
269         
270
271         // DEBUG
272         //ul_usb1_register(candev->hwspecops);  // only for successful compiling (defined in ul_usb1.c)
273         // register for another board
274         can_lmc1_register(candev->hwspecops);
275
276         
277
278         bd=baudrate[0];
279         if (candev->hwspecops->init_hw_data(candev)){
280                 CANMSG("HW data could not be initialized\n");
281                 sys_err();
282         }
283
284         // Alocate and initialize the chip structures
285         for (chipnr=0; chipnr < candev->nr_all_chips; chipnr++) {
286 //              if(chipnr<irqnum)
287 //                      irqsig=irq[*irq_param_idx_p+chipnr];
288                 if (init_chip_struct(candev, chipnr, 0, bd*1000)){
289                         CANMSG("Chip structure could not be initialized\n");
290                         sys_err();
291                 }
292         }
293
294
295
296         for (chipnr=0; chipnr < candev->nr_all_chips; chipnr++) {
297                 struct canchip_t *chip=candev->chip[chipnr];
298                 int objnr;
299
300                 register_chip_struct(chip, m);
301
302                 for (objnr=0; objnr<chip->max_objects; objnr++) {
303                         register_obj_struct(chip->msgobj[objnr], m);
304                         if(m>=0) m++;
305                 }
306         }
307
308
309         if (candev->hwspecops->request_io(candev))
310                 sys_err();
311         candev->flags|=CANDEV_IO_RESERVED;
312
313
314         if (candev->hwspecops->reset(candev))
315                 sys_err();
316
317
318         for(chipnr=0; chipnr<candev->nr_all_chips; chipnr++) {
319                 if((chip=candev->chip[chipnr])==NULL)
320                         continue;
321
322                 if(chip->chipspecops->attach_to_chip(chip)<0) {
323 //                      CANMSG("Initial attach to the chip HW failed\n");
324                         sys_err();
325                 }
326
327                 chip->flags |= CHIP_ATTACHED;
328
329 // Interrupts from chip are served in main cycle
330 //              if(can_chip_setup_irq(chip)<0) {
331 //                      CANMSG("Error to setup chip IRQ\n");
332 //                      sys_err();
333 //              }
334         }
335
336         if (candev->flags & CANDEV_PROGRAMMABLE_IRQ)
337                 if (candev->hwspecops->program_irq(candev)){
338 //                      CANMSG("Error to program board interrupt\n");
339                         sys_err();
340                 }
341
342         //***********************************************************************
343         // * CAN device initialization - client side (adapted from LinCAN open.c)
344         // ***********************************************************************
345
346
347         chip=candev->chip[0];
348         obj=chip->msgobj[0];
349         atomic_inc(&obj->obj_used);
350         can_msgobj_set_fl(obj,OPENED);
351
352         if (chip->flags & CHIP_CONFIGURED)
353                 DEBUGMSG("Device is already configured.\n");
354         else {
355                 if (chip->chipspecops->chip_config(chip))
356                         CANMSG("Error configuring chip.\n");
357                 else
358                         chip->flags |= CHIP_CONFIGURED;
359
360                 if (chip->chipspecops->pre_read_config(chip,obj)<0)
361                         CANMSG("Error initializing chip for receiving\n");
362
363         } // End of chip configuration
364
365
366         canuser = (struct canuser_t *)malloc(sizeof(struct canuser_t));
367         if(canuser == NULL) sys_err();
368         canuser->flags=0;
369 //      canuser->userinfo.fileinfo.file = file;
370         canuser->msgobj = obj;
371 //      canuser->magic = CAN_USER_MAGIC;
372 //      file->private_data = canuser;
373
374         qends = (struct canque_ends_t *)malloc(sizeof(struct canque_ends_t));
375         if(qends == NULL) sys_err();
376         canqueue_ends_init_kern(qends);
377         canuser->qends = qends;
378
379         //required to synchronize with RT-Linux context
380         can_spin_lock_irqsave(&canuser_manipulation_lock, iflags);
381         list_add(&canuser->peers, &obj->obj_users);
382         can_spin_unlock_irqrestore(&canuser_manipulation_lock, iflags);
383
384         if(canqueue_connect_edge(edge=canque_new_edge_kern(MAX_BUF_LENGTH),
385                 canuser->qends, obj->qends)<0) sys_err();
386
387         if(canqueue_connect_edge(canuser->rx_edge0=canque_new_edge_kern(MAX_BUF_LENGTH),
388                 obj->qends, canuser->qends)<0) sys_err();
389         //FIXME: more generic model should be used there
390         canque_edge_decref(canuser->rx_edge0);
391         canque_edge_decref(edge);
392
393
394
395         /***********************************************************************
396          * USB Init
397          ***********************************************************************/
398
399         memset( &usb_device, 0, sizeof( usb_device));
400         usb_device.id = 1;
401         usb_device.devdes_table = &usb_devdes_table;
402         usb_device.init = usb_lpc_init;
403         usb_debug_set_level(DEBUG_LEVEL_NONE);
404         usb_device.cntep = NUM_ENDPOINTS;
405         usb_device.ep = eps;
406
407         eps[0].max_packet_size = USB_MAX_PACKET;
408         eps[1].max_packet_size = USB_MAX_PACKET;
409         eps[0].epnum = 0x01;
410         eps[1].epnum = 0x81;
411         eps[0].event_mask = 0x04;
412         eps[1].event_mask = 0x08;
413         eps[0].udev = &usb_device;
414         eps[1].udev = &usb_device;
415
416         usb_device.vendor_fnc=usbcan_vendor;
417
418         usb_init(&usb_device);
419         usb_connect(&usb_device);
420         usb_device.ep_events |= MASK_EP1TX;
421
422         /***********************************************************************
423          * Start
424          ***********************************************************************/
425
426         timer_rx_off=timer_tx_off=timer_str=timer_configured=0;
427
428
429         printf("Main loop\n");
430
431         while (1) {
432
433                 usb_check_events(&usb_device);
434                 usb_control_response(&usb_device);
435
436 // DEBUG
437 //              if (!(IO0PIN&P0_SJA1000_INT_PIN)) //INT PIN is inverted
438 //                      chip->chipspecops->irq_handler(0,chip);
439
440                 if (usb_device.ep_events & MASK_EP1RX) {  //EP1RX - data waiting to receive
441                         
442                         if (canque_get_inslot(qends, &qedge, &slot, 0)>=0){ //Free slot obtained
443
444                                 size=usb_udev_read_endpoint(&eps[0],ep1_rx_buff,16);
445                                 if (size==16){
446                                         uint16_t msgflags;
447                                         uint32_t msgid;
448                                         canmsg.cob=0;
449                                         canmsg.length=*(uint8_t *)(ep1_rx_buff+1);
450                                         if (canmsg.length > CAN_MSG_LENGTH)
451                                                 canmsg.length=CAN_MSG_LENGTH;
452                                         msgflags=*(uint16_t *)(ep1_rx_buff+2);
453                                         msgid=*(uint32_t *)(ep1_rx_buff+4);
454                                         #if __BYTE_ORDER == __BIG_ENDIAN
455                                                 msgflags  = bswap_16( msgflags);
456                                                 msgid  = bswap_32( msgid);
457                                         #endif
458                                         canmsg.flags=msgflags;
459                                         canmsg.id=msgid;
460
461                                         for (i=0;i<canmsg.length;i++){
462                                                 canmsg.data[i]=*(unsigned char*)(ep1_rx_buff+8+i);
463                                         }
464                                         for (;i<CAN_MSG_LENGTH;i++){
465                                                 canmsg.data[i]=0;
466                                         }
467                                         /* Automatic selection of extended format if ID>2047 */
468                                         if (canmsg.id & ~0x7ffl & MSG_ID_MASK ) canmsg.flags |= MSG_EXT;
469                                         /* has been dependent on "extended" option */
470                         
471                                         slot->msg=canmsg;
472                                         canque_put_inslot(qends, qedge, slot);
473                                         //CAN_send(&canmsg);
474                                 }
475                                 else
476                                         canque_abort_inslot(qends,qedge,slot);
477                                         
478
479                                 timer_rx_off=50;        //rosviceni diody pri prijmu
480                                 CLR_OUT_PIN(LED_PORT,LED2_BIT);
481                                 usb_device.ep_events &= ~MASK_EP1RX;
482                         
483                                         
484                         }
485                         
486
487 /*                      if (size==2){
488                                 uint8_t val;
489                                 if ((data[0]&CAN_OP_MASK)==CAN_OP_READ){ // Get data from CAN device and return to caller
490                                         val = can_read(data[0] & ~CAN_OP_MASK);
491                                         *(data+1)=val;
492                                         usb_udev_write_endpoint(&eps[1],(unsigned char *)data,size);
493                                         timer_rx_off=50;        //rosviceni diody pri prijmu
494                                         CLR_OUT_PIN(LED_PORT,LED2_BIT);
495                                         usb_can_send=0;
496                                 }
497                                 if ((data[0]&CAN_OP_MASK)==CAN_OP_WRITE){ // Save data to CAN device
498                                         can_write(data[1], data[0] & ~CAN_OP_MASK);
499                                         timer_tx_off=50;                //rozsviceni diod pri vysilani
500                                         CLR_OUT_PIN(LED_PORT,LED1_BIT);
501                                 }
502                         }*/
503                 }
504
505                 // DEBUG - only transmitting CAN messages, no reading (yet)
506                 /*
507                 if(usb_device.ep_events & MASK_EP1TX){ //EP1TX - data transmitted
508                         if(canque_test_outslot(qends, &qedge, &slot)>=0){
509                                 DEBUGMSG("CAN message ready to send over usb\n");
510                                 uint16_t msgflags;
511                                 uint32_t msgid;
512
513                                 *(uint8_t *)(ep1_tx_buff)=0;
514                                 *(uint8_t *)(ep1_tx_buff+1)=slot->msg.length;
515
516                                 msgflags=slot->msg.flags;
517                                 msgid=slot->msg.id;
518                                 #if __BYTE_ORDER == __BIG_ENDIAN
519                                         msgflags  = bswap_16( msgflags);
520                                         msgid  = bswap_32( msgid);
521                                 #endif
522
523                                 *(uint16_t *)(ep1_tx_buff+2)=msgflags;
524                                 *(uint32_t *)(ep1_tx_buff+4)=msgid;
525                                 for (i=0;i<slot->msg.length;i++){
526                                         *(uint8_t *)(ep1_tx_buff+8+i)=slot->msg.data[i];
527                                 }
528                                 for (;i<CAN_MSG_LENGTH;i++){
529                                         *(uint8_t *)(ep1_tx_buff+8+i)=0;
530                                 }
531                                 usb_udev_write_endpoint(&eps[1],ep1_tx_buff,16);
532
533                                 canque_free_outslot(qends, qedge, slot);
534                                 timer_tx_off=50;                //rozsviceni diod pri vysilani
535                                 CLR_OUT_PIN(LED_PORT,LED1_BIT);
536                                 usb_device.ep_events &= ~MASK_EP1TX;
537                         }
538                 }
539                 */
540
541                 //if (usb_can_send && )
542
543 #ifdef WATCHDOG_ENABLED
544                 watchdog_feed();
545 #endif /* WATCHDOG_ENABLED */
546
547                 /* 10ms timer */
548                 if (lt_10msec_expired(10))
549                         timer_10ms();
550         }
551
552         SET_OUT_PIN(LED_PORT,LED_GP);
553         SET_OUT_PIN(LED_PORT,LED_ERR);
554
555         /* unreachable code */
556 #ifdef SDCC
557         vec_jmp(0x0);  /* need to call a function from misc to correct linking */
558 #endif
559         return 0;
560 }