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